Skip to content

Commit 017e585

Browse files
joslattamirdresher
andauthored
fix(cli): scope squad cost to the shell's Squad session (#2348)
Plain `squad cost` read usage from the ledger, which only the interactive shell writes, but took the session start from the newest Scribe session log in .squad/log/, which the shell never writes. With no log it reported every session; a log written by another host during a shell run hid that run's earlier turns. - the ledger records get an optional squadSessionId; the shell stamps turn starts and usage with its persisted session id (the one /resume restores); - squad cost scopes to the Squad session of the newest ledger row, and falls back to the session-log cutoff when that row has no id; - the summary counts Squad sessions instead of SDK sessions; - cost-tracking.md describes the ledger and shows the real output. USAGE_LEDGER_VERSION stays 1; older readers ignore the new field. Closes #2347 Co-authored-by: Tamir Dresher <tamir.dresher@gmail.com>
1 parent 6df734d commit 017e585

7 files changed

Lines changed: 240 additions & 38 deletions

File tree

‎.changeset/cost-squad-session.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
---
2+
"@bradygaster/squad-cli": patch
3+
"@bradygaster/squad-sdk": patch
4+
---
5+
6+
`squad cost` now finds the current session from the usage ledger instead of Scribe's session logs. The interactive shell stamps every usage record with its session id (the one `/resume` restores), as a new optional `squadSessionId` field, and plain `squad cost` reports the records that share the newest one. Before, the boundary was the newest `.squad/log/*.md` file, which the shell never writes: with no session log, plain `squad cost` reported every session, and a log written by another host during a shell run hid that run's earlier turns. The summary also counts Squad sessions instead of SDK sessions, so one shell run with three agents no longer shows as four sessions. Ledgers written before this change fall back to the old cutoff, and older CLIs still read the new records.

‎docs/src/content/docs/features/cost-tracking.md‎

Lines changed: 27 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,52 +1,57 @@
11
# Token Usage & Cost Tracking
22

3-
Squad can track token usage and estimated cost for each agent spawn, roll that data up by session, and expose it through orchestration logs, terminal summaries, and telemetry backends.
3+
Squad records token usage and estimated cost for each turn in the interactive shell, summarizes it by session with `squad cost`, and can export token metrics to telemetry backends.
44

55
---
66

77
## Overview
88

9-
- Squad tracks token usage (input/output tokens) and estimated cost per agent spawn
10-
- Usage data is recorded in orchestration logs and available via `squad cost` CLI
9+
- The interactive shell (`squad` with no arguments) records input tokens, output tokens and estimated cost for every coordinator and agent turn
10+
- `squad cost` reports that usage for the current session, for every session, or for one agent
1111
- Optional budget limits can be configured per agent or per session
1212

1313
---
1414

1515
## How It Works
1616

17-
- The `CostTracker` class (`packages/squad-sdk/src/runtime/cost-tracker.ts`) accumulates token data
18-
- Each orchestration log entry includes a **Token usage** row
17+
- Each shell turn appends JSON Lines records to `.squad/log/usage.jsonl`: one when the turn starts and one with its usage when it completes
18+
- Each record names the SDK session that ran the turn and the Squad session it belongs to. The Squad session is the shell session, the one `/resume` restores, so it covers the coordinator and every agent the shell talks to
19+
- Hosts that run the coordinator themselves, such as Copilot CLI and VS Code, don't write this ledger
20+
- The `CostTracker` class (`packages/squad-sdk/src/runtime/cost-tracker.ts`) accumulates token data for telemetry
1921
- OTel metrics (`squad.tokens.input`, `squad.tokens.output`, `squad.tokens.cost`) are emitted when telemetry is enabled
2022

21-
The orchestration log template stores usage in a markdown table row like this:
22-
23-
```md
24-
| **Token usage** | 12,450 in / 3,200 out — $0.0234 |
25-
```
23+
When the ledger has no data, `squad cost` falls back to older orchestration log entries that contain a **Token usage** row and labels the totals as estimates.
2624

2725
---
2826

2927
## Viewing Costs
3028

3129
```bash
3230
squad cost # current session costs
33-
squad cost --all # all historical costs
34-
squad cost --agent fenster # costs for specific agent
31+
squad cost --all # all recorded costs
32+
squad cost --agent fenster # one agent's costs in the current session
3533
```
3634

35+
The current session is the Squad session of the newest record in the ledger. If that record has no Squad session because an older Squad wrote it, `squad cost` counts the records after the newest timestamped session log in `.squad/log/` instead, or all records when there is none.
36+
3737
**Example output:**
3838

3939
```text
40-
=== Squad Cost Summary ===
41-
Total input tokens: 12,450
42-
Total output tokens: 3,200
43-
Estimated cost: $0.0234
44-
45-
--- By Agent ---
46-
fenster: 12,450in / 3,200out ($0.0234) [1 turns, model: claude-sonnet-4.5]
47-
48-
--- By Session ---
49-
session-abc123: 12,450in / 3,200out ($0.0234) [1 turns]
40+
💰 Squad Cost Summary
41+
━━━━━━━━━━━━━━━━━━━━
42+
43+
Agent Input Tokens Output Tokens Est. Cost
44+
───────────── ────────────── ─────────────── ───────────
45+
EECOM 7,000 100 $0.0700
46+
Control 5,000 100 $0.0500
47+
coordinator 1,000 100 $0.0100
48+
───────────── ────────────── ─────────────── ───────────
49+
Total 13,000 300 $0.1300
50+
51+
📊 3 agents across 3 turns in 1 session
52+
Models: claude-sonnet-5 (3 turns, $0.1300)
53+
Source: structured runtime usage ledger
54+
Coverage: 3 of 3 turn attempts with recorded usage (100.0%)
5055
```
5156

5257
---

‎packages/squad-cli/src/cli/commands/cost.ts‎

Lines changed: 42 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import {
22
resolveSquadState,
33
UsageLedger,
44
type StateBackend,
5+
type UsageLedgerReadResult,
56
type UsageLedgerRecord,
67
type UsageLedgerTurnStart,
78
} from '@bradygaster/squad-sdk';
@@ -15,6 +16,7 @@ interface CostArgs {
1516
interface CostEntry {
1617
agent: string;
1718
sessionId: string;
19+
squadSessionId?: string;
1820
turnId?: string;
1921
model: string;
2022
inputTokens: number;
@@ -97,6 +99,7 @@ function fromLedgerRecord(record: UsageLedgerRecord): CostEntry {
9799
return {
98100
agent: record.agentName ?? 'unknown',
99101
sessionId: record.sessionId,
102+
...(record.squadSessionId ? { squadSessionId: record.squadSessionId } : {}),
100103
...(record.turnId ? { turnId: record.turnId } : {}),
101104
model: record.model,
102105
inputTokens: record.inputTokens,
@@ -213,7 +216,7 @@ function printSummary(
213216
console.log(formatRow('Total', total.inputTokens, total.outputTokens, total.estimatedCost));
214217
console.log();
215218

216-
const sessionCount = new Set(entries.map(entry => entry.sessionId)).size;
219+
const sessionCount = new Set(entries.map(entry => entry.squadSessionId ?? entry.sessionId)).size;
217220
const modelTotals = new Map<string, { turns: number; estimatedCost: number }>();
218221
for (const entry of entries) {
219222
const model = modelTotals.get(entry.model) ?? { turns: 0, estimatedCost: 0 };
@@ -261,14 +264,36 @@ function getCurrentSessionCutoff(backend: StateBackend): number | null {
261264
}
262265
}
263266

267+
/**
268+
* The current session is the Squad session of the newest ledger row. When that
269+
* row has no Squad session id (written by an older Squad), callers fall back to
270+
* the newest session log in `log/`.
271+
*/
272+
function getCurrentSquadSessionId(ledger: UsageLedgerReadResult): string | undefined {
273+
let newest: { timestamp: number; squadSessionId?: string } | undefined;
274+
for (const row of [...ledger.records, ...ledger.turnStarts]) {
275+
const timestamp = parseTimestamp(row.timestamp);
276+
if (timestamp !== null && (!newest || timestamp >= newest.timestamp)) {
277+
newest = { timestamp, squadSessionId: row.squadSessionId };
278+
}
279+
}
280+
return newest?.squadSessionId;
281+
}
282+
283+
interface StructuredScope {
284+
cutoffTimestamp: number | null;
285+
squadSessionId?: string;
286+
}
287+
264288
function matchesScope(
265-
record: Pick<UsageLedgerRecord | UsageLedgerTurnStart, 'agentName' | 'timestamp'>,
266-
cutoffTimestamp: number | null,
289+
record: Pick<UsageLedgerRecord | UsageLedgerTurnStart, 'agentName' | 'squadSessionId' | 'timestamp'>,
290+
scope: StructuredScope,
267291
agentFilter?: string,
268292
): boolean {
269293
const timestamp = parseTimestamp(record.timestamp);
270294
return timestamp !== null
271-
&& (cutoffTimestamp === null || timestamp > cutoffTimestamp)
295+
&& (scope.squadSessionId === undefined || record.squadSessionId === scope.squadSessionId)
296+
&& (scope.cutoffTimestamp === null || timestamp > scope.cutoffTimestamp)
272297
&& (!agentFilter || (record.agentName ?? 'unknown').toLowerCase() === agentFilter.toLowerCase());
273298
}
274299

@@ -286,16 +311,15 @@ function calculateCoverage(entries: CostEntry[], turnStarts: UsageLedgerTurnStar
286311
};
287312
}
288313

289-
async function readStructuredEntries(
290-
backend: StateBackend,
291-
cutoffTimestamp: number | null,
314+
function readStructuredEntries(
315+
result: UsageLedgerReadResult,
316+
scope: StructuredScope,
292317
agentFilter?: string,
293-
): Promise<{ entries: CostEntry[]; coverage: UsageCoverage; invalidRecordCount: number }> {
294-
const result = await new UsageLedger(backend).read();
318+
): { entries: CostEntry[]; coverage: UsageCoverage; invalidRecordCount: number } {
295319
const entries = result.records
296-
.filter(record => matchesScope(record, cutoffTimestamp, agentFilter))
320+
.filter(record => matchesScope(record, scope, agentFilter))
297321
.map(fromLedgerRecord);
298-
const turnStarts = result.turnStarts.filter(record => matchesScope(record, cutoffTimestamp, agentFilter));
322+
const turnStarts = result.turnStarts.filter(record => matchesScope(record, scope, agentFilter));
299323

300324
return {
301325
entries,
@@ -344,8 +368,14 @@ export async function runCost(args: string[], teamRoot: string): Promise<void> {
344368
return;
345369
}
346370

371+
const ledger = await new UsageLedger(stateContext.backend).read();
347372
const cutoffTimestamp = showAll ? null : getCurrentSessionCutoff(stateContext.backend);
348-
const structured = await readStructuredEntries(stateContext.backend, cutoffTimestamp, agentFilter);
373+
const squadSessionId = showAll ? undefined : getCurrentSquadSessionId(ledger);
374+
const structured = readStructuredEntries(
375+
ledger,
376+
squadSessionId ? { cutoffTimestamp: null, squadSessionId } : { cutoffTimestamp },
377+
agentFilter,
378+
);
349379
if (structured.entries.length > 0) {
350380
printSummary(
351381
structured.entries,

‎packages/squad-cli/src/cli/shell/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -276,7 +276,7 @@ export async function runShell(): Promise<void> {
276276
const nextUsageTurnId = (sessionId: string): string =>
277277
`${sessionId}:${Date.now()}:${++usageTurnSequence}`;
278278
streamingPipeline.onUsage(async (event) => {
279-
await persistUsage(ledger => ledger.append(event));
279+
await persistUsage(ledger => ledger.append(event, { squadSessionId: persistedSession.id }));
280280
});
281281
if (
282282
rawContextWarningThreshold
@@ -522,6 +522,7 @@ export async function runShell(): Promise<void> {
522522
await persistUsage(ledger => ledger.recordTurnStart({
523523
turnId,
524524
sessionId: sid,
525+
squadSessionId: persistedSession.id,
525526
agentName,
526527
timestamp: new Date(),
527528
}));
@@ -719,6 +720,7 @@ export async function runShell(): Promise<void> {
719720
await persistUsage(ledger => ledger.recordTurnStart({
720721
turnId,
721722
sessionId: coordSid,
723+
squadSessionId: persistedSession.id,
722724
agentName: 'coordinator',
723725
timestamp: new Date(),
724726
}));

‎packages/squad-sdk/src/runtime/usage-ledger.ts‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export interface UsageLedgerRecord {
1616
version: typeof USAGE_LEDGER_VERSION;
1717
kind: 'usage';
1818
sessionId: string;
19+
squadSessionId?: string;
1920
turnId?: string;
2021
agentName?: string;
2122
model: string;
@@ -30,17 +31,29 @@ export interface UsageLedgerTurnStart {
3031
kind: 'turn-start';
3132
turnId: string;
3233
sessionId: string;
34+
squadSessionId?: string;
3335
agentName?: string;
3436
timestamp: string;
3537
}
3638

3739
export interface UsageTurnStart {
3840
turnId: string;
3941
sessionId: string;
42+
squadSessionId?: string;
4043
agentName?: string;
4144
timestamp: Date;
4245
}
4346

47+
/** Context stamped on a usage record that the runtime event does not carry. */
48+
export interface UsageRecordContext {
49+
/**
50+
* The Squad session the record belongs to. One Squad session spans several SDK
51+
* sessions (the coordinator's and one per agent), so `sessionId` cannot mark it.
52+
* The interactive shell passes its persisted session id, the one `/resume` restores.
53+
*/
54+
squadSessionId?: string;
55+
}
56+
4457
export interface UsageLedgerReadResult {
4558
records: UsageLedgerRecord[];
4659
turnStarts: UsageLedgerTurnStart[];
@@ -56,6 +69,10 @@ function isNonNegativeFiniteNumber(value: unknown): value is number {
5669
return typeof value === 'number' && Number.isFinite(value) && value >= 0;
5770
}
5871

72+
function isOptionalNonEmptyString(value: unknown): boolean {
73+
return value === undefined || (typeof value === 'string' && value.length > 0);
74+
}
75+
5976
function isUsageLedgerRecord(value: unknown): value is UsageLedgerRecord {
6077
if (!value || typeof value !== 'object') return false;
6178

@@ -64,6 +81,7 @@ function isUsageLedgerRecord(value: unknown): value is UsageLedgerRecord {
6481
&& record.kind === 'usage'
6582
&& typeof record.sessionId === 'string'
6683
&& record.sessionId.length > 0
84+
&& isOptionalNonEmptyString(record.squadSessionId)
6785
&& (record.turnId === undefined || (typeof record.turnId === 'string' && record.turnId.length > 0))
6886
&& (record.agentName === undefined || typeof record.agentName === 'string')
6987
&& typeof record.model === 'string'
@@ -87,12 +105,13 @@ function isUsageLedgerTurnStart(value: unknown): value is UsageLedgerTurnStart {
87105
&& record.turnId.length > 0
88106
&& typeof record.sessionId === 'string'
89107
&& record.sessionId.length > 0
108+
&& isOptionalNonEmptyString(record.squadSessionId)
90109
&& (record.agentName === undefined || typeof record.agentName === 'string')
91110
&& typeof record.timestamp === 'string'
92111
&& Number.isFinite(Date.parse(record.timestamp));
93112
}
94113

95-
function toRecord(event: UsageEvent): UsageLedgerRecord {
114+
function toRecord(event: UsageEvent, context: UsageRecordContext = {}): UsageLedgerRecord {
96115
const record: UsageLedgerRecord = {
97116
version: USAGE_LEDGER_VERSION,
98117
kind: 'usage',
@@ -102,6 +121,7 @@ function toRecord(event: UsageEvent): UsageLedgerRecord {
102121
outputTokens: event.outputTokens,
103122
estimatedCost: event.estimatedCost,
104123
timestamp: event.timestamp.toISOString(),
124+
...(context.squadSessionId !== undefined ? { squadSessionId: context.squadSessionId } : {}),
105125
...(event.turnId ? { turnId: event.turnId } : {}),
106126
...(event.agentName ? { agentName: event.agentName } : {}),
107127
};
@@ -120,6 +140,7 @@ function toTurnStart(turn: UsageTurnStart): UsageLedgerTurnStart {
120140
turnId: turn.turnId,
121141
sessionId: turn.sessionId,
122142
timestamp: turn.timestamp.toISOString(),
143+
...(turn.squadSessionId !== undefined ? { squadSessionId: turn.squadSessionId } : {}),
123144
...(turn.agentName ? { agentName: turn.agentName } : {}),
124145
};
125146

@@ -136,8 +157,8 @@ export class UsageLedger {
136157
private readonly ledgerPath: string = USAGE_LEDGER_PATH,
137158
) {}
138159

139-
async append(event: UsageEvent): Promise<void> {
140-
await Promise.resolve(this.storage.append(this.ledgerPath, `${JSON.stringify(toRecord(event))}\n`));
160+
async append(event: UsageEvent, context?: UsageRecordContext): Promise<void> {
161+
await Promise.resolve(this.storage.append(this.ledgerPath, `${JSON.stringify(toRecord(event, context))}\n`));
141162
}
142163

143164
async recordTurnStart(turn: UsageTurnStart): Promise<void> {

0 commit comments

Comments
 (0)