Compare commits

...
Author SHA1 Message Date
Theo BrowneandClaude Fable 5 ee46b611d2 feat(usage): local usage analytics — durable ledger, usage.getSummary RPC, settings page
Records token/cost usage facts from live provider events into a replayable
projection, exposes a dashboard-shaped RPC, and adds Settings > Usage.

Server:
- New thread.usage-recorded orchestration event (internal thread.usage.record
  command) carrying immutable per-model interval facts with provider-native
  session identity; emitted from runtime ingestion for Codex cumulative
  token-usage updates and Claude turn.completed modelUsage settlements
  (exact cost in integer micro-USD; stale completions recorded, flagged).
- Registered projection.usage projector -> projection_usage_facts (fact_id
  upsert, migration 033). Deliberately does NOT prune on thread.reverted
  (billing history is immutable); thread deletion redacts linkage.
- Cumulative->delta baselines keyed by native session + model, reseeded from
  fact sums after restart to prevent double counting.
- ClaudeAdapter: providerRefs now carry the SDK session id. CodexAdapter:
  snapshots now include cumulative total* fields; native thread id attached
  to usage events (separates concurrent subagent sessions on one thread).
- usage.getSummary RPC (orchestration:read scope): totals, by-model, daily,
  hour-of-week, by-project buckets grouped in the caller's IANA timezone.
- Pricing: versioned effective-dated list-price catalog in shared runtime
  code; estimates computed at query time only, never stored, always flagged.
  Unpriced models surface as token-only, never $0.

Web:
- Settings > Usage per the approved mock: harness-level twin donuts
  (tokens + cost, model shades within family, striped estimate slices),
  KPI tiles, tokens-per-day stacks, hour x weekday heatmap, models table,
  project bars.

Tests: pure accounting (delta/reset/normalization), projector (idempotent
replay, revert retention, deletion redaction, session-model sums), adapter
fixtures updated for the new snapshot fields.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-24 04:49:36 -07:00
31 changed files with 5658 additions and 39 deletions

No files matched your search

@@ -18,6 +18,7 @@ import { OrchestrationEventStore } from "../../persistence/Services/Orchestratio
import { ProjectionPendingApprovalRepository } from "../../persistence/Services/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepository } from "../../persistence/Services/ProjectionProjects.ts";
import { ProjectionStateRepository } from "../../persistence/Services/ProjectionState.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ProjectionThreadActivityRepository } from "../../persistence/Services/ProjectionThreadActivities.ts";
import { type ProjectionThreadActivity } from "../../persistence/Services/ProjectionThreadActivities.ts";
import {
@@ -37,6 +38,7 @@ import { ProjectionThreadRepository } from "../../persistence/Services/Projectio
import { ProjectionPendingApprovalRepositoryLive } from "../../persistence/Layers/ProjectionPendingApprovals.ts";
import { ProjectionProjectRepositoryLive } from "../../persistence/Layers/ProjectionProjects.ts";
import { ProjectionStateRepositoryLive } from "../../persistence/Layers/ProjectionState.ts";
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
import { ProjectionThreadActivityRepositoryLive } from "../../persistence/Layers/ProjectionThreadActivities.ts";
import { ProjectionThreadMessageRepositoryLive } from "../../persistence/Layers/ProjectionThreadMessages.ts";
import { ProjectionThreadProposedPlanRepositoryLive } from "../../persistence/Layers/ProjectionThreadProposedPlans.ts";
@@ -65,6 +67,7 @@ export const ORCHESTRATION_PROJECTOR_NAMES = {
threadTurns: "projection.thread-turns",
checkpoints: "projection.checkpoints",
pendingApprovals: "projection.pending-approvals",
usage: "projection.usage",
} as const;
type ProjectorName =
@@ -480,6 +483,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
const projectionThreadSessionRepository = yield* ProjectionThreadSessionRepository;
const projectionTurnRepository = yield* ProjectionTurnRepository;
const projectionPendingApprovalRepository = yield* ProjectionPendingApprovalRepository;
const projectionUsageRepository = yield* ProjectionUsageRepository;
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
@@ -1007,6 +1011,51 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
});
});
const applyUsageProjection: ProjectorDefinition["apply"] = Effect.fn("applyUsageProjection")(
function* (event, _attachmentSideEffects) {
switch (event.type) {
case "thread.usage-recorded":
yield* Effect.forEach(
event.payload.facts,
(fact) =>
projectionUsageRepository.upsertFact({
factId: fact.factId,
threadId: event.payload.threadId,
turnId: event.payload.turnId,
projectId: event.payload.projectId,
provider: fact.provider,
providerInstanceId: fact.providerInstanceId ?? null,
providerSessionId: fact.providerSessionId,
model: fact.model,
modelRaw: fact.modelRaw,
reasoningEffort: fact.reasoningEffort ?? null,
kind: fact.kind,
inputTokens: fact.tokens.inputTokens,
cachedInputTokens: fact.tokens.cachedInputTokens,
cacheCreationTokens: fact.tokens.cacheCreationTokens,
outputTokens: fact.tokens.outputTokens,
reasoningOutputTokens: fact.tokens.reasoningOutputTokens,
costMicroUsd: fact.costMicroUsd ?? null,
stale: fact.stale ?? false,
observedAt: fact.observedAt,
}),
{ concurrency: 1 },
).pipe(Effect.asVoid);
return;
case "thread.deleted":
yield* projectionUsageRepository.redactThread({
threadId: event.payload.threadId,
});
return;
// No thread.reverted case: usage facts are immutable billing history and survive reverts.
default:
return;
}
},
);
const applyThreadTurnsProjection: ProjectorDefinition["apply"] = Effect.fn(
"applyThreadTurnsProjection",
)(function* (event, _attachmentSideEffects) {
@@ -1480,6 +1529,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
name: ORCHESTRATION_PROJECTOR_NAMES.threadSessions,
apply: applyThreadSessionsProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.usage,
apply: applyUsageProjection,
},
{
name: ORCHESTRATION_PROJECTOR_NAMES.threadTurns,
apply: applyThreadTurnsProjection,
@@ -1596,6 +1649,7 @@ export const OrchestrationProjectionPipelineLive = Layer.effect(
Layer.provideMerge(ProjectionThreadProposedPlanRepositoryLive),
Layer.provideMerge(ProjectionThreadActivityRepositoryLive),
Layer.provideMerge(ProjectionThreadSessionRepositoryLive),
Layer.provideMerge(ProjectionUsageRepositoryLive),
Layer.provideMerge(ProjectionTurnRepositoryLive),
Layer.provideMerge(ProjectionPendingApprovalRepositoryLive),
Layer.provideMerge(ProjectionStateRepositoryLive),
@@ -0,0 +1,557 @@
import {
CommandId,
EventId,
IsoDateTime,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TurnId,
type UsageFact,
UsageFactId,
} from "@t3tools/contracts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import { assert, it } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as SqlClient from "effect/unstable/sql/SqlClient";
import { OrchestrationEventStoreLive } from "../../persistence/Layers/OrchestrationEventStore.ts";
import { SqlitePersistenceMemory } from "../../persistence/Layers/Sqlite.ts";
import { OrchestrationEventStore } from "../../persistence/Services/OrchestrationEventStore.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ServerConfig } from "../../config.ts";
import { OrchestrationProjectionPipeline } from "../Services/ProjectionPipeline.ts";
import { OrchestrationProjectionPipelineLive } from "./ProjectionPipeline.ts";
const BaseTestLayer = OrchestrationProjectionPipelineLive.pipe(
Layer.provideMerge(OrchestrationEventStoreLive),
Layer.provideMerge(
ServerConfig.layerTest(process.cwd(), { prefix: "t3-projection-pipeline-usage-test-" }),
),
Layer.provideMerge(SqlitePersistenceMemory),
Layer.provideMerge(NodeServices.layer),
);
const threadId = ThreadId.make("thread-usage");
const turnId = TurnId.make("turn-usage");
const projectId = ProjectId.make("project-usage");
const observedAt = IsoDateTime.make("2026-04-01T12:00:00.000Z");
function makeFact(factId: string, overrides: Partial<UsageFact> = {}): UsageFact {
return {
factId: UsageFactId.make(factId),
kind: "final",
provider: ProviderDriverKind.make("claudeAgent"),
providerInstanceId: ProviderInstanceId.make("claude-primary"),
providerSessionId: "session-claude-1",
model: "claude-fable-5",
modelRaw: "claude-fable-5[1m]",
reasoningEffort: "high",
tokens: {
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
},
costMicroUsd: 1_250_000,
observedAt,
...overrides,
};
}
it.layer(BaseTestLayer)("usage projection", (it) => {
it.effect("projects every usage fact with exact persisted values", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-single"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-single"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-single"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [
makeFact("fact-final"),
makeFact("fact-interval", {
kind: "interval",
provider: ProviderDriverKind.make("codex"),
providerInstanceId: undefined,
providerSessionId: "session-codex-1",
model: "gpt-5.6",
modelRaw: "gpt-5.6",
reasoningEffort: undefined,
tokens: {
inputTokens: 300,
cachedInputTokens: 75,
cacheCreationTokens: 0,
outputTokens: 125,
reasoningOutputTokens: 40,
},
costMicroUsd: undefined,
observedAt: IsoDateTime.make("2026-04-01T12:00:01.000Z"),
}),
],
recordedAt: IsoDateTime.make("2026-04-01T12:00:02.000Z"),
},
});
const rows = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly turnId: string | null;
readonly projectId: string | null;
readonly provider: string;
readonly providerInstanceId: string | null;
readonly providerSessionId: string;
readonly model: string;
readonly modelRaw: string;
readonly reasoningEffort: string | null;
readonly kind: string;
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly cacheCreationTokens: number;
readonly outputTokens: number;
readonly reasoningOutputTokens: number;
readonly costMicroUsd: number | null;
readonly stale: number;
readonly observedAt: string;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
turn_id AS "turnId",
project_id AS "projectId",
provider,
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
model,
model_raw AS "modelRaw",
reasoning_effort AS "reasoningEffort",
kind,
input_tokens AS "inputTokens",
cached_input_tokens AS "cachedInputTokens",
cache_creation_tokens AS "cacheCreationTokens",
output_tokens AS "outputTokens",
reasoning_output_tokens AS "reasoningOutputTokens",
cost_micro_usd AS "costMicroUsd",
stale,
observed_at AS "observedAt"
FROM projection_usage_facts
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [
{
factId: "fact-final",
threadId: "thread-usage",
turnId: "turn-usage",
projectId: "project-usage",
provider: "claudeAgent",
providerInstanceId: "claude-primary",
providerSessionId: "session-claude-1",
model: "claude-fable-5",
modelRaw: "claude-fable-5[1m]",
reasoningEffort: "high",
kind: "final",
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
costMicroUsd: 1_250_000,
stale: 0,
observedAt: "2026-04-01T12:00:00.000Z",
},
{
factId: "fact-interval",
threadId: "thread-usage",
turnId: "turn-usage",
projectId: "project-usage",
provider: "codex",
providerInstanceId: null,
providerSessionId: "session-codex-1",
model: "gpt-5.6",
modelRaw: "gpt-5.6",
reasoningEffort: null,
kind: "interval",
inputTokens: 300,
cachedInputTokens: 75,
cacheCreationTokens: 0,
outputTokens: 125,
reasoningOutputTokens: 40,
costMicroUsd: null,
stale: 0,
observedAt: "2026-04-01T12:00:01.000Z",
},
]);
}),
);
it.effect("upserts repeated facts by fact id", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
const facts = [makeFact("fact-replay-1"), makeFact("fact-replay-2", { kind: "interval" })];
for (const suffix of ["one", "two"] as const) {
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make(`evt-usage-replay-${suffix}`),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make(`cmd-usage-replay-${suffix}`),
causationEventId: null,
correlationId: CommandId.make(`cmd-usage-replay-${suffix}`),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts,
recordedAt: observedAt,
},
});
}
const rows = yield* sql<{ readonly factId: string }>`
SELECT fact_id AS "factId"
FROM projection_usage_facts
WHERE fact_id IN ('fact-replay-1', 'fact-replay-2')
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [{ factId: "fact-replay-1" }, { factId: "fact-replay-2" }]);
}),
);
it.effect("retains usage facts after a thread revert", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-before-revert"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-before-revert"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-before-revert"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [makeFact("fact-retained")],
recordedAt: observedAt,
},
});
const before = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
readonly outputTokens: number;
readonly costMicroUsd: number | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId",
output_tokens AS "outputTokens",
cost_micro_usd AS "costMicroUsd"
FROM projection_usage_facts
WHERE fact_id = 'fact-retained'
`;
yield* appendAndProject({
type: "thread.reverted",
eventId: EventId.make("evt-usage-reverted"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
commandId: CommandId.make("cmd-usage-reverted"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-reverted"),
metadata: {},
payload: { threadId, turnCount: 0 },
});
const after = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
readonly outputTokens: number;
readonly costMicroUsd: number | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId",
output_tokens AS "outputTokens",
cost_micro_usd AS "costMicroUsd"
FROM projection_usage_facts
WHERE fact_id = 'fact-retained'
`;
assert.deepEqual(after, before);
assert.deepEqual(after, [
{
factId: "fact-retained",
threadId: "thread-usage",
projectId: "project-usage",
outputTokens: 50,
costMicroUsd: 1_250_000,
},
]);
}),
);
it.effect("redacts thread and project attribution after thread deletion", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-before-delete"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-before-delete"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-before-delete"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [makeFact("fact-redacted-1"), makeFact("fact-redacted-2")],
recordedAt: observedAt,
},
});
yield* appendAndProject({
type: "thread.deleted",
eventId: EventId.make("evt-usage-deleted"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
commandId: CommandId.make("cmd-usage-deleted"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-deleted"),
metadata: {},
payload: {
threadId,
deletedAt: IsoDateTime.make("2026-04-01T12:01:00.000Z"),
},
});
const rows = yield* sql<{
readonly factId: string;
readonly threadId: string;
readonly projectId: string | null;
}>`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
project_id AS "projectId"
FROM projection_usage_facts
WHERE fact_id IN ('fact-redacted-1', 'fact-redacted-2')
ORDER BY fact_id ASC
`;
assert.deepEqual(rows, [
{ factId: "fact-redacted-1", threadId: "deleted", projectId: null },
{ factId: "fact-redacted-2", threadId: "deleted", projectId: null },
]);
}),
);
it.effect("persists the stale flag", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const sql = yield* SqlClient.SqlClient;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-stale"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-stale"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-stale"),
metadata: {},
payload: {
threadId,
turnId,
projectId: null,
facts: [makeFact("fact-stale", { stale: true })],
recordedAt: observedAt,
},
});
const rows = yield* sql<{ readonly factId: string; readonly stale: number }>`
SELECT fact_id AS "factId", stale
FROM projection_usage_facts
WHERE fact_id = 'fact-stale'
`;
assert.deepEqual(rows, [{ factId: "fact-stale", stale: 1 }]);
}),
);
it.effect("sums final and interval facts by session and model", () =>
Effect.gen(function* () {
const projectionPipeline = yield* OrchestrationProjectionPipeline;
const eventStore = yield* OrchestrationEventStore;
const usageRepository = yield* ProjectionUsageRepository;
const appendAndProject = (event: Parameters<typeof eventStore.append>[0]) =>
eventStore
.append(event)
.pipe(Effect.flatMap((savedEvent) => projectionPipeline.projectEvent(savedEvent)));
yield* appendAndProject({
type: "thread.usage-recorded",
eventId: EventId.make("evt-usage-sums"),
aggregateKind: "thread",
aggregateId: threadId,
occurredAt: observedAt,
commandId: CommandId.make("cmd-usage-sums"),
causationEventId: null,
correlationId: CommandId.make("cmd-usage-sums"),
metadata: {},
payload: {
threadId,
turnId,
projectId,
facts: [
makeFact("fact-sum-fable-final", {
providerSessionId: "session-target",
tokens: {
inputTokens: 100,
cachedInputTokens: 10,
cacheCreationTokens: 5,
outputTokens: 20,
reasoningOutputTokens: 2,
},
costMicroUsd: 1_000,
}),
makeFact("fact-sum-fable-interval", {
kind: "interval",
providerSessionId: "session-target",
tokens: {
inputTokens: 50,
cachedInputTokens: 5,
cacheCreationTokens: 3,
outputTokens: 10,
reasoningOutputTokens: 1,
},
costMicroUsd: 500,
}),
makeFact("fact-sum-opus", {
providerSessionId: "session-target",
model: "claude-opus-4-8",
modelRaw: "claude-opus-4-8",
tokens: {
inputTokens: 200,
cachedInputTokens: 20,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 4,
},
costMicroUsd: 2_000,
}),
makeFact("fact-sum-turn-total", {
kind: "turn-total",
providerSessionId: "session-target",
tokens: {
inputTokens: 9_999,
cachedInputTokens: 9_999,
cacheCreationTokens: 9_999,
outputTokens: 9_999,
reasoningOutputTokens: 9_999,
},
costMicroUsd: 9_999,
}),
makeFact("fact-sum-other-session", {
providerSessionId: "session-other",
tokens: {
inputTokens: 8_888,
cachedInputTokens: 8_888,
cacheCreationTokens: 8_888,
outputTokens: 8_888,
reasoningOutputTokens: 8_888,
},
costMicroUsd: 8_888,
}),
],
recordedAt: observedAt,
},
});
const sums = yield* usageRepository.sumBySessionModel({
providerSessionId: "session-target",
});
assert.deepEqual(
[...sums].toSorted((left, right) => left.model.localeCompare(right.model)),
[
{
model: "claude-fable-5",
inputTokens: 150,
cachedInputTokens: 15,
cacheCreationTokens: 8,
outputTokens: 30,
reasoningOutputTokens: 3,
costMicroUsd: 1_500,
},
{
model: "claude-opus-4-8",
inputTokens: 200,
cachedInputTokens: 20,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 4,
costMicroUsd: 2_000,
},
],
);
}),
);
});
@@ -3,6 +3,9 @@ import {
type AssistantDeliveryMode,
CommandId,
MessageId,
type OrchestrationThreadShell,
type UsageFact,
UsageFactId,
type OrchestrationEvent,
type OrchestrationMessage,
type OrchestrationProposedPlanId,
@@ -30,6 +33,17 @@ import { makeDrainableWorker } from "@t3tools/shared/DrainableWorker";
import { ProviderService } from "../../provider/Services/ProviderService.ts";
import { ProjectionTurnRepository } from "../../persistence/Services/ProjectionTurns.ts";
import { ProjectionTurnRepositoryLive } from "../../persistence/Layers/ProjectionTurns.ts";
import { ProjectionUsageRepository } from "../../persistence/Services/ProjectionUsage.ts";
import { ProjectionUsageRepositoryLive } from "../../persistence/Layers/ProjectionUsage.ts";
import {
ZERO_USAGE_COUNTERS,
type UsageCumulativeCounters,
canonicalModelId,
claudeCumulativeByModel,
codexCumulativeFromSnapshot,
isZeroUsage,
usageDelta,
} from "../usageAccounting.ts";
import { isGitRepository } from "../../git/Utils.ts";
import { OrchestrationEngineService } from "../Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../Services/ProjectionSnapshotQuery.ts";
@@ -697,6 +711,7 @@ const make = Effect.gen(function* () {
crypto.randomUUIDv4.pipe(
Effect.map((uuid) => CommandId.make(`provider:${event.eventId}:${tag}:${uuid}`)),
);
const projectionUsageRepository = yield* ProjectionUsageRepository;
const turnMessageIdsByTurnKey = yield* Cache.make<string, Set<MessageId>>({
capacity: TURN_MESSAGE_IDS_BY_TURN_CACHE_CAPACITY,
@@ -1290,6 +1305,194 @@ const make = Effect.gen(function* () {
},
);
// ---------------------------------------------------------------------
// Usage accounting: converts provider-cumulative counters into interval
// usage facts dispatched as thread.usage.record commands. Baselines are
// keyed by provider-native session id + model; on first sight of a session
// they are reseeded from projection_usage_facts sums so a server restart
// between samples never double counts.
// ---------------------------------------------------------------------
const usageBaselines = new Map<string, UsageCumulativeCounters>();
const seededUsageSessions = new Set<string>();
const usageBaselineKey = (providerSessionId: string, model: string) =>
`${providerSessionId}|${model}`;
const seedUsageBaselines = Effect.fn("seedUsageBaselines")(function* (providerSessionId: string) {
if (seededUsageSessions.has(providerSessionId)) {
return;
}
seededUsageSessions.add(providerSessionId);
const sums = yield* projectionUsageRepository.sumBySessionModel({ providerSessionId });
for (const sum of sums) {
const key = usageBaselineKey(providerSessionId, sum.model);
if (!usageBaselines.has(key)) {
usageBaselines.set(key, {
inputTokens: sum.inputTokens,
cachedInputTokens: sum.cachedInputTokens,
cacheCreationTokens: sum.cacheCreationTokens,
outputTokens: sum.outputTokens,
reasoningOutputTokens: sum.reasoningOutputTokens,
costMicroUsd: sum.costMicroUsd,
});
}
}
});
const reasoningEffortFromThread = (thread: OrchestrationThreadShell): string | undefined => {
const options = thread.modelSelection.options;
if (!options) return undefined;
for (const option of options) {
if (option.id === "reasoningEffort" && typeof option.value === "string") {
return option.value;
}
}
return undefined;
};
const dispatchUsageFacts = (input: {
readonly event: ProviderRuntimeEvent;
readonly threadId: ThreadId;
readonly projectId: OrchestrationThreadShell["projectId"] | null;
readonly turnId: TurnId | null;
readonly facts: ReadonlyArray<UsageFact>;
}) =>
providerCommandId(input.event, "usage-record").pipe(
Effect.flatMap((commandId) =>
orchestrationEngine.dispatch({
type: "thread.usage.record",
commandId,
threadId: input.threadId,
turnId: input.turnId,
projectId: input.projectId,
facts: input.facts,
createdAt: input.event.createdAt,
}),
),
Effect.asVoid,
);
const recordUsageForRuntimeEvent = (
event: ProviderRuntimeEvent,
thread: OrchestrationThreadShell,
options: { readonly staleCompletion: boolean },
) =>
Effect.gen(function* () {
// Codex path: cumulative totals ride every token-usage notification and
// are attributed by the provider-native thread id. Snapshots without
// native identity or cumulative fields are context-window telemetry
// only and carry no accounting weight.
if (event.type === "thread.token-usage.updated") {
const cumulative = codexCumulativeFromSnapshot(event.payload.usage);
const providerSessionId = event.providerRefs?.providerSessionId;
if (!cumulative || !providerSessionId || isZeroUsage(cumulative)) {
return;
}
const model = canonicalModelId(thread.modelSelection.model);
yield* seedUsageBaselines(providerSessionId);
const key = usageBaselineKey(providerSessionId, model);
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
usageBaselines.set(key, nextBaseline);
if (isZeroUsage(delta)) {
return;
}
const effort = reasoningEffortFromThread(thread);
const fact: UsageFact = {
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
kind: "interval",
provider: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
providerSessionId,
model,
modelRaw: thread.modelSelection.model,
...(effort !== undefined ? { reasoningEffort: effort } : {}),
tokens: {
inputTokens: delta.inputTokens,
cachedInputTokens: delta.cachedInputTokens,
cacheCreationTokens: delta.cacheCreationTokens,
outputTokens: delta.outputTokens,
reasoningOutputTokens: delta.reasoningOutputTokens,
},
observedAt: event.createdAt,
};
yield* dispatchUsageFacts({
event,
threadId: thread.id,
projectId: thread.projectId,
turnId: toTurnId(event.turnId) ?? null,
facts: [fact],
});
return;
}
// Claude path: turn.completed carries the SDK's session-cumulative
// per-model usage map (exact cost included). Settle each model's delta
// as a final fact; stale completions are recorded but flagged.
if (event.type === "turn.completed") {
const byModel = claudeCumulativeByModel(event.payload.modelUsage);
if (!byModel || byModel.size === 0) {
return;
}
const providerSessionId = event.providerRefs?.providerSessionId ?? thread.id;
yield* seedUsageBaselines(providerSessionId);
const facts: Array<UsageFact> = [];
for (const [rawModel, cumulative] of byModel) {
const model = canonicalModelId(rawModel);
const key = usageBaselineKey(providerSessionId, model);
const baseline = usageBaselines.get(key) ?? ZERO_USAGE_COUNTERS;
const { delta, nextBaseline } = usageDelta(baseline, cumulative);
usageBaselines.set(key, nextBaseline);
if (isZeroUsage(delta)) {
continue;
}
facts.push({
factId: UsageFactId.make(`usage:${event.eventId}:${model}`),
kind: "final",
provider: event.provider,
...(event.providerInstanceId !== undefined
? { providerInstanceId: event.providerInstanceId }
: {}),
providerSessionId,
model,
modelRaw: rawModel,
tokens: {
inputTokens: delta.inputTokens,
cachedInputTokens: delta.cachedInputTokens,
cacheCreationTokens: delta.cacheCreationTokens,
outputTokens: delta.outputTokens,
reasoningOutputTokens: delta.reasoningOutputTokens,
},
...(delta.costMicroUsd > 0 ? { costMicroUsd: delta.costMicroUsd } : {}),
...(options.staleCompletion ? { stale: true } : {}),
observedAt: event.createdAt,
});
}
if (facts.length === 0) {
return;
}
yield* dispatchUsageFacts({
event,
threadId: thread.id,
projectId: thread.projectId,
turnId: toTurnId(event.turnId) ?? null,
facts,
});
}
}).pipe(
Effect.catchCause((cause) => {
if (Cause.hasInterruptsOnly(cause)) {
return Effect.failCause(cause);
}
return Effect.logWarning("usage accounting failed for runtime event", {
eventId: event.eventId,
eventType: event.type,
cause: Cause.pretty(cause),
});
}),
);
const processRuntimeEvent = (event: ProviderRuntimeEvent) =>
Effect.gen(function* () {
const thread = yield* resolveThreadShell(event.threadId);
@@ -1360,6 +1563,13 @@ const make = Effect.gen(function* () {
? yield* getSourceProposedPlanReferenceForAcceptedTurnStart(thread.id, eventTurnId)
: null;
// Usage accounting runs for every usage-bearing event, including
// lifecycle-rejected completions (recorded with stale: true) — tokens
// were consumed regardless of what the turn state machine thinks.
yield* recordUsageForRuntimeEvent(event, thread, {
staleCompletion: event.type === "turn.completed" && !shouldApplyThreadLifecycle,
});
if (
event.type === "session.started" ||
event.type === "session.state.changed" ||
@@ -1822,4 +2032,4 @@ const make = Effect.gen(function* () {
export const ProviderRuntimeIngestionLive = Layer.effect(
ProviderRuntimeIngestionService,
make,
).pipe(Layer.provide(ProjectionTurnRepositoryLive));
).pipe(Layer.provide(ProjectionTurnRepositoryLive), Layer.provide(ProjectionUsageRepositoryLive));
+24
View File
@@ -774,6 +774,30 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
};
}
case "thread.usage.record": {
yield* requireThread({
readModel,
command,
threadId: command.threadId,
});
return {
...(yield* withEventBase({
aggregateKind: "thread",
aggregateId: command.threadId,
occurredAt: command.createdAt,
commandId: command.commandId,
})),
type: "thread.usage-recorded",
payload: {
threadId: command.threadId,
turnId: command.turnId,
projectId: command.projectId,
facts: command.facts,
recordedAt: command.createdAt,
},
};
}
default: {
command satisfies never;
const fallback = command as never as { type: string };
@@ -2,6 +2,7 @@ import * as Layer from "effect/Layer";
import { OrchestrationCommandReceiptRepositoryLive } from "../persistence/Layers/OrchestrationCommandReceipts.ts";
import { OrchestrationEventStoreLive } from "../persistence/Layers/OrchestrationEventStore.ts";
import { ProjectionUsageRepositoryLive } from "../persistence/Layers/ProjectionUsage.ts";
import { OrchestrationEngineLive } from "./Layers/OrchestrationEngine.ts";
import { OrchestrationProjectionPipelineLive } from "./Layers/ProjectionPipeline.ts";
import { OrchestrationProjectionSnapshotQueryLive } from "./Layers/ProjectionSnapshotQuery.ts";
@@ -19,6 +20,8 @@ export const OrchestrationInfrastructureLayerLive = Layer.mergeAll(
OrchestrationProjectionSnapshotQueryLive,
OrchestrationEventInfrastructureLayerLive,
OrchestrationProjectionPipelineLayerLive,
// Exposed for the usage.getSummary RPC handler in ws.ts.
ProjectionUsageRepositoryLive,
);
export const OrchestrationLayerLive = Layer.mergeAll(
@@ -0,0 +1,194 @@
import { describe, expect, it } from "@effect/vitest";
import {
canonicalModelId,
claudeCumulativeByModel,
codexCumulativeFromSnapshot,
isZeroUsage,
usageDelta,
ZERO_USAGE_COUNTERS,
} from "./usageAccounting.ts";
describe("usageAccounting", () => {
describe("usageDelta", () => {
it("computes interval counters from cumulative counters", () => {
const result = usageDelta(
{
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
},
{
inputTokens: 175,
cachedInputTokens: 35,
cacheCreationTokens: 18,
outputTokens: 90,
reasoningOutputTokens: 12,
costMicroUsd: 1_750_000,
},
);
expect(result).toEqual({
delta: {
inputTokens: 75,
cachedInputTokens: 15,
cacheCreationTokens: 8,
outputTokens: 40,
reasoningOutputTokens: 7,
costMicroUsd: 750_000,
},
nextBaseline: {
inputTokens: 175,
cachedInputTokens: 35,
cacheCreationTokens: 18,
outputTokens: 90,
reasoningOutputTokens: 12,
costMicroUsd: 1_750_000,
},
reset: false,
});
});
it("returns a zero delta when baseline equals cumulative", () => {
const cumulative = {
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
};
expect(usageDelta(cumulative, cumulative)).toEqual({
delta: ZERO_USAGE_COUNTERS,
nextBaseline: cumulative,
reset: false,
});
});
it("treats a counter regression as a provider session reset", () => {
const cumulative = {
inputTokens: 125,
cachedInputTokens: 25,
cacheCreationTokens: 12,
outputTokens: 10,
reasoningOutputTokens: 6,
costMicroUsd: 1_250_000,
};
expect(
usageDelta(
{
inputTokens: 100,
cachedInputTokens: 20,
cacheCreationTokens: 10,
outputTokens: 50,
reasoningOutputTokens: 5,
costMicroUsd: 1_000_000,
},
cumulative,
),
).toEqual({
delta: cumulative,
nextBaseline: cumulative,
reset: true,
});
});
});
describe("claudeCumulativeByModel", () => {
it("decodes per-model cumulative usage and converts USD to micro-USD", () => {
const result = claudeCumulativeByModel({
"claude-fable-5[1m]": {
inputTokens: 100,
outputTokens: 50,
cacheReadInputTokens: 1_000,
cacheCreationInputTokens: 200,
costUSD: 1.25,
},
"claude-opus-4-8": {
inputTokens: 80,
outputTokens: 30,
cacheReadInputTokens: 400,
cacheCreationInputTokens: 25,
},
});
expect(result).toEqual(
new Map([
[
"claude-fable-5[1m]",
{
inputTokens: 100,
cachedInputTokens: 1_000,
cacheCreationTokens: 200,
outputTokens: 50,
reasoningOutputTokens: 0,
costMicroUsd: 1_250_000,
},
],
[
"claude-opus-4-8",
{
inputTokens: 80,
cachedInputTokens: 400,
cacheCreationTokens: 25,
outputTokens: 30,
reasoningOutputTokens: 0,
costMicroUsd: 0,
},
],
]),
);
});
it("returns undefined for malformed input", () => {
expect(claudeCumulativeByModel({ model: "not usage" })).toBeUndefined();
expect(claudeCumulativeByModel(null)).toBeUndefined();
});
});
describe("codexCumulativeFromSnapshot", () => {
it("stores only the uncached share in inputTokens", () => {
expect(
codexCumulativeFromSnapshot({
totalInputTokens: 1_000,
totalCachedInputTokens: 250,
totalOutputTokens: 400,
totalReasoningOutputTokens: 125,
}),
).toEqual({
inputTokens: 750,
cachedInputTokens: 250,
cacheCreationTokens: 0,
outputTokens: 400,
reasoningOutputTokens: 125,
costMicroUsd: 0,
});
});
it("returns undefined when no cumulative total fields are present", () => {
expect(codexCumulativeFromSnapshot({})).toBeUndefined();
expect(
codexCumulativeFromSnapshot({
totalCachedInputTokens: 100,
totalReasoningOutputTokens: 20,
}),
).toBeUndefined();
});
});
it("canonicalizes provider capacity suffixes", () => {
expect(canonicalModelId("claude-fable-5[1m]")).toBe("claude-fable-5");
expect(canonicalModelId("claude-opus-4-8")).toBe("claude-opus-4-8");
});
it("detects zero usage", () => {
expect(isZeroUsage(ZERO_USAGE_COUNTERS)).toBe(true);
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, outputTokens: 1 })).toBe(false);
expect(isZeroUsage({ ...ZERO_USAGE_COUNTERS, costMicroUsd: 1 })).toBe(false);
});
});
@@ -0,0 +1,136 @@
import * as Schema from "effect/Schema";
import { ClaudeModelUsageMap, type UsageTokenCounters } from "@t3tools/contracts";
/**
* Pure delta accounting for usage facts.
*
* Providers report session-cumulative counters (Codex `tokenUsage.total`,
* Claude `modelUsage`). A usage fact must carry interval counters, so every
* emission subtracts a baseline: the sum of everything already recorded for
* that provider-native session and model. Baselines survive restarts by
* reseeding from `projection_usage_facts` sums.
*/
export interface UsageCumulativeCounters extends UsageTokenCounters {
readonly costMicroUsd: number;
}
export const ZERO_USAGE_COUNTERS: UsageCumulativeCounters = {
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
costMicroUsd: 0,
};
export interface UsageDeltaResult {
readonly delta: UsageCumulativeCounters;
/** The cumulative counters that become the next baseline. */
readonly nextBaseline: UsageCumulativeCounters;
/** True when any counter went backwards (provider session reset); the
* absolute cumulative value is used as the delta in that case. */
readonly reset: boolean;
}
function nonNegative(value: number): number {
return value > 0 ? Math.round(value) : 0;
}
export function usageDelta(
baseline: UsageCumulativeCounters,
cumulative: UsageCumulativeCounters,
): UsageDeltaResult {
const reset =
cumulative.inputTokens < baseline.inputTokens ||
cumulative.cachedInputTokens < baseline.cachedInputTokens ||
cumulative.outputTokens < baseline.outputTokens;
if (reset) {
return { delta: cumulative, nextBaseline: cumulative, reset: true };
}
return {
delta: {
inputTokens: nonNegative(cumulative.inputTokens - baseline.inputTokens),
cachedInputTokens: nonNegative(cumulative.cachedInputTokens - baseline.cachedInputTokens),
cacheCreationTokens: nonNegative(
cumulative.cacheCreationTokens - baseline.cacheCreationTokens,
),
outputTokens: nonNegative(cumulative.outputTokens - baseline.outputTokens),
reasoningOutputTokens: nonNegative(
cumulative.reasoningOutputTokens - baseline.reasoningOutputTokens,
),
costMicroUsd: nonNegative(cumulative.costMicroUsd - baseline.costMicroUsd),
},
nextBaseline: cumulative,
reset: false,
};
}
export function isZeroUsage(counters: UsageCumulativeCounters): boolean {
return (
counters.inputTokens === 0 &&
counters.cachedInputTokens === 0 &&
counters.cacheCreationTokens === 0 &&
counters.outputTokens === 0 &&
counters.reasoningOutputTokens === 0 &&
counters.costMicroUsd === 0
);
}
/** Strip provider capacity suffixes (`claude-fable-5[1m]` → `claude-fable-5`)
* while keeping the raw id available for display and pricing overrides. */
export function canonicalModelId(rawModel: string): string {
return rawModel.replace(/\[[^\]]+\]$/, "");
}
const decodeClaudeModelUsage = Schema.decodeUnknownOption(ClaudeModelUsageMap);
/** Claude's `modelUsage` map is cumulative per SDK session. Returns cumulative
* counters per raw model id, or undefined when the payload doesn't parse. */
export function claudeCumulativeByModel(
modelUsage: unknown,
): ReadonlyMap<string, UsageCumulativeCounters> | undefined {
const decoded = decodeClaudeModelUsage(modelUsage);
if (decoded._tag === "None") {
return undefined;
}
const result = new Map<string, UsageCumulativeCounters>();
for (const [rawModel, entry] of Object.entries(decoded.value)) {
result.set(rawModel, {
inputTokens: nonNegative(entry.inputTokens),
cachedInputTokens: nonNegative(entry.cacheReadInputTokens),
cacheCreationTokens: nonNegative(entry.cacheCreationInputTokens),
outputTokens: nonNegative(entry.outputTokens),
reasoningOutputTokens: 0,
costMicroUsd: entry.costUSD !== undefined ? nonNegative(entry.costUSD * 1_000_000) : 0,
});
}
return result;
}
/** Codex cumulative totals from a ThreadTokenUsageSnapshot's `total*` fields.
* Codex reports input inclusive of cached reads; the uncached share is the
* difference. Returns undefined when the snapshot has no cumulative fields
* (Claude context-window snapshots land here and are settled at turn end). */
export function codexCumulativeFromSnapshot(usage: {
readonly totalInputTokens?: number | undefined;
readonly totalCachedInputTokens?: number | undefined;
readonly totalOutputTokens?: number | undefined;
readonly totalReasoningOutputTokens?: number | undefined;
}): UsageCumulativeCounters | undefined {
if (usage.totalInputTokens === undefined && usage.totalOutputTokens === undefined) {
return undefined;
}
const totalInput = usage.totalInputTokens ?? 0;
const cached = usage.totalCachedInputTokens ?? 0;
return {
inputTokens: nonNegative(totalInput - cached),
cachedInputTokens: nonNegative(cached),
cacheCreationTokens: 0,
outputTokens: nonNegative(usage.totalOutputTokens ?? 0),
reasoningOutputTokens: nonNegative(usage.totalReasoningOutputTokens ?? 0),
costMicroUsd: 0,
};
}
@@ -0,0 +1,276 @@
import type { UsageAggregate, UsageSummaryResponse } from "@t3tools/contracts";
import { USAGE_PRICING_VERSION, estimateCostMicroUsd } from "@t3tools/shared/usagePricing";
import type { ProjectionUsageFact } from "../persistence/Services/ProjectionUsage.ts";
/**
* Pure aggregation of usage facts into the dashboard-shaped summary. Calendar
* bucketing happens in the requested IANA timezone via Intl (DST folds into
* the local calendar naturally). `turn-total` facts are reconciliation-only
* and excluded from all sums; stale facts count (tokens were consumed).
*/
interface MutableAggregate {
inputTokens: number;
cachedInputTokens: number;
cacheCreationTokens: number;
outputTokens: number;
reasoningOutputTokens: number;
totalTokens: number;
turns: number;
exactCostMicroUsd: number;
estimatedCostMicroUsd: number;
}
function newAggregate(): MutableAggregate {
return {
inputTokens: 0,
cachedInputTokens: 0,
cacheCreationTokens: 0,
outputTokens: 0,
reasoningOutputTokens: 0,
totalTokens: 0,
turns: 0,
exactCostMicroUsd: 0,
estimatedCostMicroUsd: 0,
};
}
function addFact(
aggregate: MutableAggregate,
fact: ProjectionUsageFact,
estimatedMicroUsd: number | undefined,
): void {
aggregate.inputTokens += fact.inputTokens;
aggregate.cachedInputTokens += fact.cachedInputTokens;
aggregate.cacheCreationTokens += fact.cacheCreationTokens;
aggregate.outputTokens += fact.outputTokens;
aggregate.reasoningOutputTokens += fact.reasoningOutputTokens;
aggregate.totalTokens +=
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
if (fact.costMicroUsd !== null) {
aggregate.exactCostMicroUsd += fact.costMicroUsd;
} else if (estimatedMicroUsd !== undefined) {
aggregate.estimatedCostMicroUsd += estimatedMicroUsd;
}
}
function toAggregate(mutable: MutableAggregate): UsageAggregate {
return { ...mutable };
}
function makeCalendarFormatter(timeZone: string): Intl.DateTimeFormat {
return new Intl.DateTimeFormat("en-CA", {
timeZone,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hour12: false,
weekday: "short",
});
}
const WEEKDAY_INDEX: Record<string, number> = {
Sun: 0,
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
};
interface CalendarParts {
readonly day: string;
readonly hour: number;
readonly dayOfWeek: number;
}
function calendarParts(formatter: Intl.DateTimeFormat, iso: string): CalendarParts {
const parts = formatter.formatToParts(Date.parse(iso));
let year = "",
month = "",
day = "",
hour = 0,
dayOfWeek = 0;
for (const part of parts) {
switch (part.type) {
case "year":
year = part.value;
break;
case "month":
month = part.value;
break;
case "day":
day = part.value;
break;
case "hour":
hour = Number(part.value) % 24;
break;
case "weekday":
dayOfWeek = WEEKDAY_INDEX[part.value] ?? 0;
break;
}
}
return { day: `${year}-${month}-${day}`, hour, dayOfWeek };
}
export type UsageProjectTitleLookup = (projectId: string) => string | null;
export function summarizeUsageFacts(input: {
readonly facts: ReadonlyArray<ProjectionUsageFact>;
readonly timeZone: string;
readonly earliestFactAt: string | null;
readonly projectTitle: UsageProjectTitleLookup;
}): UsageSummaryResponse {
const formatter = makeCalendarFormatter(input.timeZone);
const totals = newAggregate();
const byModel = new Map<
string,
MutableAggregate & { provider: ProjectionUsageFact["provider"]; hasEstimate: boolean }
>();
const daily = new Map<
string,
MutableAggregate & {
day: string;
provider: ProjectionUsageFact["provider"];
model: string;
}
>();
const hourOfWeek = new Map<
string,
{ dayOfWeek: number; hour: number; turns: number; totalTokens: number }
>();
const byProject = new Map<
string,
MutableAggregate & { projectId: ProjectionUsageFact["projectId"] }
>();
const unpricedModels = new Set<string>();
const turnKeys = new Set<string>();
const turnKeysByScope = new Map<string, Set<string>>();
const scopedTurnCount = (scope: string, turnKey: string): number => {
let keys = turnKeysByScope.get(scope);
if (!keys) {
keys = new Set();
turnKeysByScope.set(scope, keys);
}
const before = keys.size;
keys.add(turnKey);
return keys.size - before;
};
for (const fact of input.facts) {
if (fact.kind === "turn-total") {
continue;
}
const estimated =
fact.costMicroUsd === null
? estimateCostMicroUsd(fact.model, fact.observedAt, {
inputTokens: fact.inputTokens,
cachedInputTokens: fact.cachedInputTokens,
cacheCreationTokens: fact.cacheCreationTokens,
outputTokens: fact.outputTokens,
})
: undefined;
if (fact.costMicroUsd === null && estimated === undefined) {
unpricedModels.add(fact.model);
}
const cal = calendarParts(formatter, fact.observedAt);
const turnKey = `${fact.threadId}|${fact.turnId ?? fact.factId}`;
const factTokens =
fact.inputTokens + fact.cachedInputTokens + fact.cacheCreationTokens + fact.outputTokens;
addFact(totals, fact, estimated);
if (!turnKeys.has(turnKey)) {
turnKeys.add(turnKey);
totals.turns += 1;
}
const modelKey = `${fact.provider}|${fact.model}`;
let model = byModel.get(modelKey);
if (!model) {
model = { ...newAggregate(), provider: fact.provider, hasEstimate: false };
byModel.set(modelKey, model);
}
addFact(model, fact, estimated);
if (estimated !== undefined) model.hasEstimate = true;
model.turns += scopedTurnCount(`model:${modelKey}`, turnKey);
const dayKey = `${cal.day}|${fact.provider}|${fact.model}`;
let dayBucket = daily.get(dayKey);
if (!dayBucket) {
dayBucket = { ...newAggregate(), day: cal.day, provider: fact.provider, model: fact.model };
daily.set(dayKey, dayBucket);
}
addFact(dayBucket, fact, estimated);
dayBucket.turns += scopedTurnCount(`day:${dayKey}`, turnKey);
const howKey = `${cal.dayOfWeek}|${cal.hour}`;
let how = hourOfWeek.get(howKey);
if (!how) {
how = { dayOfWeek: cal.dayOfWeek, hour: cal.hour, turns: 0, totalTokens: 0 };
hourOfWeek.set(howKey, how);
}
how.totalTokens += factTokens;
how.turns += scopedTurnCount(`how:${howKey}`, turnKey);
const projectKey = fact.projectId ?? "__none__";
let project = byProject.get(projectKey);
if (!project) {
project = { ...newAggregate(), projectId: fact.projectId };
byProject.set(projectKey, project);
}
addFact(project, fact, estimated);
project.turns += scopedTurnCount(`project:${projectKey}`, turnKey);
}
const modelBuckets = [...byModel.entries()]
.map(([key, aggregate]) => ({
...toAggregate(aggregate),
provider: aggregate.provider,
model: key.slice(key.indexOf("|") + 1),
costSource:
aggregate.exactCostMicroUsd > 0
? ("exact" as const)
: aggregate.hasEstimate
? ("estimated" as const)
: ("none" as const),
}))
.sort((a, b) => b.totalTokens - a.totalTokens);
const dailyBuckets = [...daily.values()]
.map((bucket) => ({
...toAggregate(bucket),
day: bucket.day,
provider: bucket.provider,
model: bucket.model,
}))
.sort((a, b) => (a.day === b.day ? b.totalTokens - a.totalTokens : a.day.localeCompare(b.day)));
const hourBuckets = [...hourOfWeek.values()].sort(
(a, b) => a.dayOfWeek - b.dayOfWeek || a.hour - b.hour,
);
const projectBuckets = [...byProject.values()]
.map((bucket) => ({
...toAggregate(bucket),
projectId: bucket.projectId,
projectTitle: bucket.projectId ? input.projectTitle(bucket.projectId) : null,
}))
.sort((a, b) => b.totalTokens - a.totalTokens);
return {
totals: toAggregate(totals),
byModel: modelBuckets,
daily: dailyBuckets,
hourOfWeek: hourBuckets,
byProject: projectBuckets,
unpricedModels: [...unpricedModels].sort(),
pricingVersion: USAGE_PRICING_VERSION,
earliestFactAt: input.earliestFactAt,
} as UsageSummaryResponse;
}
@@ -0,0 +1,221 @@
import * as SqlClient from "effect/unstable/sql/SqlClient";
import * as SqlSchema from "effect/unstable/sql/SqlSchema";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
import * as Schema from "effect/Schema";
import * as Struct from "effect/Struct";
import { IsoDateTime } from "@t3tools/contracts";
import { toPersistenceSqlError } from "../Errors.ts";
import {
ListProjectionUsageFactsInput,
ProjectionUsageFact,
ProjectionUsageRepository,
type ProjectionUsageRepositoryShape,
ProjectionUsageSessionModelSum,
RedactProjectionUsageThreadInput,
} from "../Services/ProjectionUsage.ts";
const ProjectionUsageFactDbRowSchema = ProjectionUsageFact.mapFields(
Struct.assign({
stale: Schema.Number,
}),
);
const EarliestObservedAtRowSchema = Schema.Struct({
earliestObservedAt: Schema.NullOr(IsoDateTime),
});
function toProjectionUsageFact(
row: Schema.Schema.Type<typeof ProjectionUsageFactDbRowSchema>,
): ProjectionUsageFact {
return {
...row,
stale: row.stale === 1,
};
}
const makeProjectionUsageRepository = Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
const upsertProjectionUsageFactRow = SqlSchema.void({
Request: ProjectionUsageFact,
execute: (row) =>
sql`
INSERT INTO projection_usage_facts (
fact_id,
thread_id,
turn_id,
project_id,
provider,
provider_instance_id,
provider_session_id,
model,
model_raw,
reasoning_effort,
kind,
input_tokens,
cached_input_tokens,
cache_creation_tokens,
output_tokens,
reasoning_output_tokens,
cost_micro_usd,
stale,
observed_at
)
VALUES (
${row.factId},
${row.threadId},
${row.turnId},
${row.projectId},
${row.provider},
${row.providerInstanceId},
${row.providerSessionId},
${row.model},
${row.modelRaw},
${row.reasoningEffort},
${row.kind},
${row.inputTokens},
${row.cachedInputTokens},
${row.cacheCreationTokens},
${row.outputTokens},
${row.reasoningOutputTokens},
${row.costMicroUsd},
${row.stale ? 1 : 0},
${row.observedAt}
)
ON CONFLICT (fact_id)
DO UPDATE SET
thread_id = excluded.thread_id,
turn_id = excluded.turn_id,
project_id = excluded.project_id,
provider = excluded.provider,
provider_instance_id = excluded.provider_instance_id,
provider_session_id = excluded.provider_session_id,
model = excluded.model,
model_raw = excluded.model_raw,
reasoning_effort = excluded.reasoning_effort,
kind = excluded.kind,
input_tokens = excluded.input_tokens,
cached_input_tokens = excluded.cached_input_tokens,
cache_creation_tokens = excluded.cache_creation_tokens,
output_tokens = excluded.output_tokens,
reasoning_output_tokens = excluded.reasoning_output_tokens,
cost_micro_usd = excluded.cost_micro_usd,
stale = excluded.stale,
observed_at = excluded.observed_at
`,
});
const redactProjectionUsageThreadRows = SqlSchema.void({
Request: RedactProjectionUsageThreadInput,
execute: ({ threadId }) =>
sql`
UPDATE projection_usage_facts
SET thread_id = 'deleted', project_id = NULL
WHERE thread_id = ${threadId}
`,
});
const listProjectionUsageFactRows = SqlSchema.findAll({
Request: ListProjectionUsageFactsInput,
Result: ProjectionUsageFactDbRowSchema,
execute: ({ sinceIso, untilIso }) =>
sql`
SELECT
fact_id AS "factId",
thread_id AS "threadId",
turn_id AS "turnId",
project_id AS "projectId",
provider,
provider_instance_id AS "providerInstanceId",
provider_session_id AS "providerSessionId",
model,
model_raw AS "modelRaw",
reasoning_effort AS "reasoningEffort",
kind,
input_tokens AS "inputTokens",
cached_input_tokens AS "cachedInputTokens",
cache_creation_tokens AS "cacheCreationTokens",
output_tokens AS "outputTokens",
reasoning_output_tokens AS "reasoningOutputTokens",
cost_micro_usd AS "costMicroUsd",
stale,
observed_at AS "observedAt"
FROM projection_usage_facts
WHERE (${sinceIso ?? null} IS NULL OR observed_at >= ${sinceIso ?? null})
AND (${untilIso ?? null} IS NULL OR observed_at < ${untilIso ?? null})
ORDER BY observed_at ASC
`,
});
const readSessionModelSums = SqlSchema.findAll({
Request: Schema.Struct({ providerSessionId: Schema.String }),
Result: ProjectionUsageSessionModelSum,
execute: ({ providerSessionId }) =>
sql`
SELECT
model,
COALESCE(SUM(input_tokens), 0) AS "inputTokens",
COALESCE(SUM(cached_input_tokens), 0) AS "cachedInputTokens",
COALESCE(SUM(cache_creation_tokens), 0) AS "cacheCreationTokens",
COALESCE(SUM(output_tokens), 0) AS "outputTokens",
COALESCE(SUM(reasoning_output_tokens), 0) AS "reasoningOutputTokens",
COALESCE(SUM(COALESCE(cost_micro_usd, 0)), 0) AS "costMicroUsd"
FROM projection_usage_facts
WHERE provider_session_id = ${providerSessionId}
AND kind IN ('final', 'interval')
GROUP BY model
`,
});
const readEarliestObservedAt = SqlSchema.findOne({
Request: Schema.Void,
Result: EarliestObservedAtRowSchema,
execute: () =>
sql`
SELECT MIN(observed_at) AS "earliestObservedAt"
FROM projection_usage_facts
`,
});
const upsertFact: ProjectionUsageRepositoryShape["upsertFact"] = (row) =>
upsertProjectionUsageFactRow(row).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.upsertFact:query")),
);
const redactThread: ProjectionUsageRepositoryShape["redactThread"] = (input) =>
redactProjectionUsageThreadRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.redactThread:query")),
);
const listFacts: ProjectionUsageRepositoryShape["listFacts"] = (input) =>
listProjectionUsageFactRows(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.listFacts:query")),
Effect.map((rows) => rows.map(toProjectionUsageFact)),
);
const earliestObservedAt: ProjectionUsageRepositoryShape["earliestObservedAt"] = () =>
readEarliestObservedAt(undefined).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.earliestObservedAt:query")),
Effect.map((row) => row.earliestObservedAt),
);
const sumBySessionModel: ProjectionUsageRepositoryShape["sumBySessionModel"] = (input) =>
readSessionModelSums(input).pipe(
Effect.mapError(toPersistenceSqlError("ProjectionUsageRepository.sumBySessionModel:query")),
);
return {
upsertFact,
redactThread,
listFacts,
earliestObservedAt,
sumBySessionModel,
} satisfies ProjectionUsageRepositoryShape;
});
export const ProjectionUsageRepositoryLive = Layer.effect(
ProjectionUsageRepository,
makeProjectionUsageRepository,
);
@@ -45,6 +45,7 @@ import Migration0029 from "./Migrations/029_ProjectionThreadDetailOrderingIndexe
import Migration0030 from "./Migrations/030_ProjectionThreadShellArchiveIndexes.ts";
import Migration0031 from "./Migrations/031_AuthAuthorizationScopes.ts";
import Migration0032 from "./Migrations/032_AuthPairingProofKeyThumbprint.ts";
import Migration0033 from "./Migrations/033_ProjectionUsage.ts";
/**
* Migration loader with all migrations defined inline.
@@ -89,6 +90,7 @@ export const migrationEntries = [
[30, "ProjectionThreadShellArchiveIndexes", Migration0030],
[31, "AuthAuthorizationScopes", Migration0031],
[32, "AuthPairingProofKeyThumbprint", Migration0032],
[33, "ProjectionUsage", Migration0033],
] as const;
export const makeMigrationLoader = (throughId?: number) =>
@@ -0,0 +1,45 @@
import * as Effect from "effect/Effect";
import * as SqlClient from "effect/unstable/sql/SqlClient";
export default Effect.gen(function* () {
const sql = yield* SqlClient.SqlClient;
yield* sql`
CREATE TABLE IF NOT EXISTS projection_usage_facts (
fact_id TEXT PRIMARY KEY,
thread_id TEXT NOT NULL,
turn_id TEXT,
project_id TEXT,
provider TEXT NOT NULL,
provider_instance_id TEXT,
provider_session_id TEXT NOT NULL,
model TEXT NOT NULL,
model_raw TEXT NOT NULL,
reasoning_effort TEXT,
kind TEXT NOT NULL,
input_tokens INTEGER NOT NULL DEFAULT 0,
cached_input_tokens INTEGER NOT NULL DEFAULT 0,
cache_creation_tokens INTEGER NOT NULL DEFAULT 0,
output_tokens INTEGER NOT NULL DEFAULT 0,
reasoning_output_tokens INTEGER NOT NULL DEFAULT 0,
cost_micro_usd INTEGER,
stale INTEGER NOT NULL DEFAULT 0,
observed_at TEXT NOT NULL
)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_observed_at
ON projection_usage_facts(observed_at)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_provider_model
ON projection_usage_facts(provider, model)
`;
yield* sql`
CREATE INDEX IF NOT EXISTS idx_projection_usage_facts_thread_id
ON projection_usage_facts(thread_id)
`;
});
@@ -0,0 +1,89 @@
import {
IsoDateTime,
NonNegativeInt,
ProjectId,
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
TrimmedNonEmptyString,
TurnId,
UsageFactId,
UsageFactKind,
} from "@t3tools/contracts";
import * as Context from "effect/Context";
import type * as Effect from "effect/Effect";
import * as Schema from "effect/Schema";
import type { ProjectionRepositoryError } from "../Errors.ts";
export const ProjectionUsageFact = Schema.Struct({
factId: UsageFactId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
projectId: Schema.NullOr(ProjectId),
provider: ProviderDriverKind,
providerInstanceId: Schema.NullOr(ProviderInstanceId),
providerSessionId: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
modelRaw: TrimmedNonEmptyString,
reasoningEffort: Schema.NullOr(TrimmedNonEmptyString),
kind: UsageFactKind,
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
costMicroUsd: Schema.NullOr(NonNegativeInt),
stale: Schema.Boolean,
observedAt: IsoDateTime,
});
export type ProjectionUsageFact = typeof ProjectionUsageFact.Type;
export const RedactProjectionUsageThreadInput = Schema.Struct({
threadId: ThreadId,
});
export type RedactProjectionUsageThreadInput = typeof RedactProjectionUsageThreadInput.Type;
export const ListProjectionUsageFactsInput = Schema.Struct({
sinceIso: Schema.optional(IsoDateTime),
untilIso: Schema.optional(IsoDateTime),
});
export type ListProjectionUsageFactsInput = typeof ListProjectionUsageFactsInput.Type;
/** Per-model sums of everything already recorded for one provider-native
* session. Used as the durable baseline when converting a provider's
* cumulative counters into interval facts — after a restart the in-memory
* baseline is gone, and resuming from recorded sums prevents double counting. */
export const ProjectionUsageSessionModelSum = Schema.Struct({
model: TrimmedNonEmptyString,
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
costMicroUsd: NonNegativeInt,
});
export type ProjectionUsageSessionModelSum = typeof ProjectionUsageSessionModelSum.Type;
export interface ProjectionUsageRepositoryShape {
readonly upsertFact: (row: ProjectionUsageFact) => Effect.Effect<void, ProjectionRepositoryError>;
readonly redactThread: (
input: RedactProjectionUsageThreadInput,
) => Effect.Effect<void, ProjectionRepositoryError>;
readonly listFacts: (
input: ListProjectionUsageFactsInput,
) => Effect.Effect<ReadonlyArray<ProjectionUsageFact>, ProjectionRepositoryError>;
readonly earliestObservedAt: () => Effect.Effect<string | null, ProjectionRepositoryError>;
readonly sumBySessionModel: (input: {
readonly providerSessionId: string;
}) => Effect.Effect<ReadonlyArray<ProjectionUsageSessionModelSum>, ProjectionRepositoryError>;
}
export class ProjectionUsageRepository extends Context.Service<
ProjectionUsageRepository,
ProjectionUsageRepositoryShape
>()("t3/persistence/Services/ProjectionUsage/ProjectionUsageRepository") {}
@@ -2802,9 +2802,7 @@ describe("ClaudeAdapterLive", () => {
if (requested.value.type !== "request.opened") {
return;
}
assert.deepEqual(requested.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
});
assert.equal(requested.value.providerRefs?.providerItemId, ProviderItemId.make("tool-use-1"));
const runtimeRequestId = requested.value.requestId;
assert.equal(typeof runtimeRequestId, "string");
if (runtimeRequestId === undefined) {
@@ -2828,9 +2826,7 @@ describe("ClaudeAdapterLive", () => {
}
assert.equal(resolved.value.requestId, requested.value.requestId);
assert.equal(resolved.value.payload.decision, "accept");
assert.deepEqual(resolved.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-use-1"),
});
assert.equal(resolved.value.providerRefs?.providerItemId, ProviderItemId.make("tool-use-1"));
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "allow");
@@ -3440,9 +3436,10 @@ describe("ClaudeAdapterLive", () => {
return;
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Ship it\n\n- one\n- two");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-1"),
});
assert.equal(
proposedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-exit-1"),
);
const permissionResult = yield* Effect.promise(() => permissionPromise);
assert.equal((permissionResult as PermissionResult).behavior, "deny");
@@ -3518,9 +3515,10 @@ describe("ClaudeAdapterLive", () => {
return;
}
assert.equal(proposedEvent.value.payload.planMarkdown, "# Final plan\n\n- capture it");
assert.deepEqual(proposedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-exit-2"),
});
assert.equal(
proposedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-exit-2"),
);
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
@@ -3612,9 +3610,10 @@ describe("ClaudeAdapterLive", () => {
// Regression for #2388: `id` must equal the full question text so the
// UI's draft-answer key matches what the SDK looks up downstream.
assert.equal(requestedEvent.value.payload.questions[0]?.id, "Which framework?");
assert.deepEqual(requestedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
});
assert.equal(
requestedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-ask-1"),
);
// Respond with the user's answers.
yield* adapter.respondToUserInput(session.threadId, ApprovalRequestId.make(requestId!), {
@@ -3634,9 +3633,10 @@ describe("ClaudeAdapterLive", () => {
assert.deepEqual(resolvedEvent.value.payload.answers, {
"Which framework?": "React",
});
assert.deepEqual(resolvedEvent.value.providerRefs, {
providerItemId: ProviderItemId.make("tool-ask-1"),
});
assert.equal(
resolvedEvent.value.providerRefs?.providerItemId,
ProviderItemId.make("tool-ask-1"),
);
// The canUseTool promise should resolve with the answers in SDK format.
const permissionResult = yield* Effect.promise(() => permissionPromise);
@@ -1014,17 +1014,21 @@ function streamKindFromDeltaType(deltaType: string): ClaudeTextStreamKind {
}
function nativeProviderRefs(
_context: ClaudeSessionContext,
context: ClaudeSessionContext,
options?: {
readonly providerItemId?: string | undefined;
},
): NonNullable<ProviderRuntimeEvent["providerRefs"]> {
// The Claude SDK session id is the provider-native identity that usage
// accounting keys cumulative counters on; carry it on every event.
const sessionRef = context.resumeSessionId ? { providerSessionId: context.resumeSessionId } : {};
if (options?.providerItemId) {
return {
...sessionRef,
providerItemId: ProviderItemId.make(options.providerItemId),
};
}
return {};
return sessionRef;
}
function extractAssistantTextBlocks(message: SDKMessage): Array<string> {
@@ -1136,6 +1136,10 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
NodeAssert.deepEqual(firstEvent.value.payload.usage, {
usedTokens: 126,
totalProcessedTokens: 11_839,
totalInputTokens: 11_833,
totalCachedInputTokens: 3456,
totalOutputTokens: 6,
totalReasoningOutputTokens: 0,
maxTokens: 258_400,
inputTokens: 120,
cachedInputTokens: 0,
@@ -1148,6 +1152,9 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
lastReasoningOutputTokens: 0,
compactsAutomatically: true,
});
// The Codex-native thread id must ride providerRefs so usage accounting
// can separate concurrent provider sessions on one canonical thread.
NodeAssert.equal(firstEvent.value.providerRefs?.providerSessionId, "thread-1");
}),
);
});
@@ -168,9 +168,17 @@ function normalizeCodexTokenUsage(
const cachedInputTokens = usage.last.cachedInputTokens;
const outputTokens = usage.last.outputTokens;
const reasoningOutputTokens = usage.last.reasoningOutputTokens;
const totalInputTokens = usage.total.inputTokens;
const totalCachedInputTokens = usage.total.cachedInputTokens;
const totalOutputTokens = usage.total.outputTokens;
const totalReasoningOutputTokens = usage.total.reasoningOutputTokens;
return {
usedTokens,
...(totalInputTokens !== undefined ? { totalInputTokens } : {}),
...(totalCachedInputTokens !== undefined ? { totalCachedInputTokens } : {}),
...(totalOutputTokens !== undefined ? { totalOutputTokens } : {}),
...(totalReasoningOutputTokens !== undefined ? { totalReasoningOutputTokens } : {}),
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
? { totalProcessedTokens }
: {}),
@@ -741,10 +749,17 @@ function mapToRuntimeEvents(
if (!normalizedUsage) {
return [];
}
const base = runtimeEventBase(event, canonicalThreadId);
// The Codex-native thread id disambiguates cumulative counters when
// several provider sessions (subagents) share one canonical T3 thread.
const nativeThreadId = payload?.threadId;
return [
{
type: "thread.token-usage.updated",
...runtimeEventBase(event, canonicalThreadId),
...base,
...(nativeThreadId
? { providerRefs: { ...base.providerRefs, providerSessionId: nativeThreadId } }
: {}),
payload: {
usage: normalizedUsage,
},
+27 -17
View File
@@ -80,6 +80,7 @@ import * as ExternalLauncher from "./process/externalLauncher.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import { OrchestrationListenerCallbackError } from "./orchestration/Errors.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionUsageRepository } from "./persistence/Services/ProjectionUsage.ts";
import { SqlitePersistenceMemory } from "./persistence/Layers/Sqlite.ts";
import { PersistenceSqlError } from "./persistence/Errors.ts";
import * as ProviderRegistry from "./provider/Services/ProviderRegistry.ts";
@@ -713,23 +714,32 @@ const buildAppUnderTest = (options?: {
}),
),
Layer.provide(
Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({
getTurnDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
getFullThreadDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
...options?.layers?.checkpointDiffQuery,
}),
Layer.mergeAll(
Layer.mock(ProjectionUsageRepository)({
upsertFact: () => Effect.void,
redactThread: () => Effect.void,
listFacts: () => Effect.succeed([]),
earliestObservedAt: () => Effect.succeed(null),
sumBySessionModel: () => Effect.succeed([]),
}),
Layer.mock(CheckpointDiffQuery.CheckpointDiffQuery)({
getTurnDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
getFullThreadDiff: () =>
Effect.succeed({
threadId: defaultThreadId,
fromTurnCount: 0,
toTurnCount: 0,
diff: "",
}),
...options?.layers?.checkpointDiffQuery,
}),
),
),
);
+36
View File
@@ -71,6 +71,8 @@ import * as ExternalLauncher from "./process/externalLauncher.ts";
import { normalizeDispatchCommand } from "./orchestration/Normalizer.ts";
import * as OrchestrationEngine from "./orchestration/Services/OrchestrationEngine.ts";
import * as ProjectionSnapshotQuery from "./orchestration/Services/ProjectionSnapshotQuery.ts";
import { ProjectionUsageRepository } from "./persistence/Services/ProjectionUsage.ts";
import { summarizeUsageFacts } from "./orchestration/usageSummary.ts";
import {
observeRpcEffect as instrumentRpcEffect,
observeRpcStream as instrumentRpcStream,
@@ -302,6 +304,7 @@ const RPC_REQUIRED_SCOPE = new Map<string, AuthEnvironmentScope>([
[WS_METHODS.serverUpdateSettings, AuthOrchestrationOperateScope],
[WS_METHODS.serverDiscoverSourceControl, AuthOrchestrationReadScope],
[WS_METHODS.serverGetTraceDiagnostics, AuthOrchestrationReadScope],
[WS_METHODS.usageGetSummary, AuthOrchestrationReadScope],
[WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope],
[WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope],
[WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope],
@@ -405,6 +408,7 @@ const makeWsRpcLayer = (
const currentSessionId = currentSession.sessionId;
const crypto = yield* Crypto.Crypto;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const projectionUsageRepository = yield* ProjectionUsageRepository;
const orchestrationEngine = yield* OrchestrationEngine.OrchestrationEngineService;
const checkpointDiffQuery = yield* CheckpointDiffQuery.CheckpointDiffQuery;
const keybindings = yield* Keybindings.Keybindings;
@@ -1533,6 +1537,38 @@ const makeWsRpcLayer = (
"rpc.aggregate": "server",
},
),
[WS_METHODS.usageGetSummary]: (input) =>
observeRpcEffect(
WS_METHODS.usageGetSummary,
Effect.gen(function* () {
const facts = yield* projectionUsageRepository.listFacts({
...(input.since !== undefined ? { sinceIso: input.since } : {}),
...(input.until !== undefined ? { untilIso: input.until } : {}),
});
const earliestFactAt = yield* projectionUsageRepository.earliestObservedAt();
const projectIds = [
...new Set(facts.flatMap((fact) => (fact.projectId ? [fact.projectId] : []))),
];
const projectTitles = new Map<string, string | null>();
yield* Effect.forEach(
projectIds,
(projectId) =>
projectionSnapshotQuery.getProjectShellById(projectId).pipe(
Effect.map((shell) => {
projectTitles.set(projectId, Option.isSome(shell) ? shell.value.title : null);
}),
),
{ concurrency: 4 },
);
return summarizeUsageFacts({
facts,
timeZone: input.timeZone,
earliestFactAt,
projectTitle: (projectId: string) => projectTitles.get(projectId) ?? null,
});
}).pipe(Effect.orDie),
{ "rpc.aggregate": "usage" },
),
[WS_METHODS.serverGetProcessDiagnostics]: (_input) =>
observeRpcEffect(WS_METHODS.serverGetProcessDiagnostics, processDiagnostics.read, {
"rpc.aggregate": "server",
@@ -3,6 +3,7 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
ChartColumnIcon,
GitBranchIcon,
KeyboardIcon,
Link2Icon,
@@ -28,6 +29,7 @@ export type SettingsSectionPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/usage"
| "/settings/archived";
export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
@@ -40,6 +42,7 @@ export const SETTINGS_NAV_ITEMS: ReadonlyArray<{
{ label: "Providers", to: "/settings/providers", icon: BotIcon },
{ label: "Source Control", to: "/settings/source-control", icon: GitBranchIcon },
{ label: "Connections", to: "/settings/connections", icon: Link2Icon },
{ label: "Usage", to: "/settings/usage", icon: ChartColumnIcon },
{ label: "Archive", to: "/settings/archived", icon: ArchiveIcon },
];
@@ -0,0 +1,605 @@
import { useMemo } from "react";
import type { UsageDailyBucket, UsageModelBucket, UsageSummaryResponse } from "@t3tools/contracts";
import { cn } from "../../lib/utils";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { usePrimaryEnvironment } from "../../state/environments";
import { ClaudeAI, OpenAI } from "../Icons";
import { Button } from "../ui/button";
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
// Family color system from the approved mock: hue = harness, lightness =
// model within the family. Codex renders as off-white on dark surfaces.
const CLAUDE_COLOR = "#cf6b48";
const CODEX_COLOR = "#e8e8e3";
const harnessColor = (provider: string): string =>
provider === "claudeAgent" ? CLAUDE_COLOR : CODEX_COLOR;
const CLAUDE_MODEL_SHADES = ["#cf6b48", "#f2c1a4", "#a3492a"];
const CODEX_MODEL_SHADES = ["#e8e8e3", "#9c9c96"];
const NEUTRAL_SHADE = "#8a8880";
const T3_ACCENT = "#9085e9";
function isClaudeProvider(provider: string): boolean {
return provider === "claudeAgent";
}
function formatTokens(value: number): string {
if (value >= 1_000_000_000) return `${(value / 1_000_000_000).toFixed(2)}B`;
if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`;
if (value >= 1_000) return `${(value / 1_000).toFixed(0)}K`;
return `${value}`;
}
function formatMicroUsd(micro: number): string {
const usd = micro / 1_000_000;
if (usd >= 100) return `$${Math.round(usd).toLocaleString()}`;
return `$${usd.toFixed(2)}`;
}
function providerLogo(provider: string, className?: string) {
return isClaudeProvider(provider) ? (
<ClaudeAI className={cn("size-3.5 shrink-0", className)} />
) : (
<OpenAI className={cn("size-3.5 shrink-0", className)} />
);
}
interface DonutSlice {
readonly key: string;
readonly value: number;
readonly color: string;
readonly estimated?: boolean;
readonly groupColor: string;
readonly groupShare: number;
readonly groupStart: boolean;
}
function assignModelShades(models: ReadonlyArray<UsageModelBucket>): Map<string, string> {
const shades = new Map<string, string>();
let claudeIndex = 0;
let codexIndex = 0;
for (const bucket of models) {
if (isClaudeProvider(bucket.provider)) {
shades.set(bucket.model, CLAUDE_MODEL_SHADES[claudeIndex] ?? NEUTRAL_SHADE);
claudeIndex += 1;
} else {
shades.set(bucket.model, CODEX_MODEL_SHADES[codexIndex] ?? NEUTRAL_SHADE);
codexIndex += 1;
}
}
return shades;
}
function Donut({
slices,
center,
centerSub,
ariaLabel,
}: {
slices: ReadonlyArray<DonutSlice>;
center: string;
centerSub: string;
ariaLabel: string;
}) {
const total = slices.reduce((sum, slice) => sum + slice.value, 0);
const cx = 150;
const cy = 150;
const outer = 140;
const inner = 96;
const tau = Math.PI * 2;
const point = (angle: number, radius: number) =>
`${(cx + Math.cos(angle) * radius).toFixed(2)} ${(cy + Math.sin(angle) * radius).toFixed(2)}`;
let angle = -Math.PI / 2;
const paths: Array<{ d: string; color: string; estimated: boolean; title: string }> = [];
const labels: Array<{ x: number; y: number; text: string; dark: boolean }> = [];
let groupStartAngle = angle;
for (const slice of slices) {
if (slice.groupStart) {
groupStartAngle = angle;
}
const sweep = total > 0 ? (slice.value / total) * tau : 0;
const end = angle + sweep;
const gap = Math.min(0.014, sweep * 0.3);
const from = angle + gap / 2;
const to = end - gap / 2;
if (to > from) {
const large = to - from > Math.PI ? 1 : 0;
paths.push({
d: `M ${point(from, outer)} A ${outer} ${outer} 0 ${large} 1 ${point(to, outer)} L ${point(to, inner)} A ${inner} ${inner} 0 ${large} 0 ${point(from, inner)} Z`,
color: slice.color,
estimated: slice.estimated ?? false,
title: slice.key,
});
}
angle = end;
const groupShare = slice.groupShare;
const isGroupEnd =
slices.indexOf(slice) === slices.length - 1 || slices[slices.indexOf(slice) + 1]?.groupStart;
if (isGroupEnd && groupShare >= 0.08) {
const mid = (groupStartAngle + angle) / 2;
const radius = (outer + inner) / 2;
const hex = slice.groupColor.replace("#", "");
const luminance =
parseInt(hex.slice(0, 2), 16) * 0.299 +
parseInt(hex.slice(2, 4), 16) * 0.587 +
parseInt(hex.slice(4, 6), 16) * 0.114;
labels.push({
x: cx + Math.cos(mid) * radius,
y: cy + Math.sin(mid) * radius,
text: `${Math.round(groupShare * 100)}%`,
dark: luminance > 150,
});
}
}
return (
<div className="relative mx-auto w-full max-w-[270px]">
<svg viewBox="0 0 300 300" role="img" aria-label={ariaLabel}>
<defs>
<pattern
id="usage-est-stripes"
patternUnits="userSpaceOnUse"
width="7"
height="7"
patternTransform="rotate(45)"
>
<line x1="0" y1="0" x2="0" y2="7" stroke="rgba(0,0,0,0.35)" strokeWidth="2.5" />
</pattern>
</defs>
{paths.map((path) => (
<g key={path.title + path.d.slice(0, 24)}>
<path d={path.d} fill={path.color}>
<title>{path.title}</title>
</path>
{path.estimated ? <path d={path.d} fill="url(#usage-est-stripes)" /> : null}
</g>
))}
{labels.map((label) => (
<text
key={`${label.x}-${label.y}`}
x={label.x}
y={label.y}
textAnchor="middle"
dominantBaseline="middle"
style={{ fill: label.dark ? "#1a1a19" : "#fff", fontSize: 15, fontWeight: 680 }}
>
{label.text}
</text>
))}
</svg>
<div className="pointer-events-none absolute inset-0 flex flex-col items-center justify-center">
<div className="text-3xl font-semibold tracking-tight">{center}</div>
<div className="mt-1 text-[11px] text-muted-foreground">{centerSub}</div>
</div>
</div>
);
}
function DailyBars({ daily }: { daily: ReadonlyArray<UsageDailyBucket> }) {
const byDay = useMemo(() => {
const map = new Map<string, Array<UsageDailyBucket>>();
for (const bucket of daily) {
const list = map.get(bucket.day) ?? [];
list.push(bucket);
map.set(bucket.day, list);
}
return [...map.entries()].sort((a, b) => a[0].localeCompare(b[0]));
}, [daily]);
const maxDay = Math.max(
1,
...byDay.map(([, buckets]) => buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0)),
);
if (byDay.length === 0) {
return null;
}
return (
<div className="flex h-40 items-end gap-[3px] overflow-x-auto rounded-md bg-black/20 p-3">
{byDay.map(([day, buckets]) => {
const dayTotal = buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0);
return (
<div
key={day}
className="flex min-w-[14px] flex-1 flex-col-reverse gap-px"
title={`${day}: ${formatTokens(dayTotal)} tokens`}
>
{buckets.map((bucket) => (
<div
key={`${day}-${bucket.provider}-${bucket.model}`}
style={{
height: `${Math.max((bucket.totalTokens / maxDay) * 100, 1.5)}%`,
background: harnessColor(bucket.provider),
}}
className="w-full rounded-[2px]"
/>
))}
</div>
);
})}
</div>
);
}
function HourHeatmap({ summary }: { summary: UsageSummaryResponse }) {
const grid = useMemo(() => {
const cells = new Map<string, number>();
let max = 0;
for (const bucket of summary.hourOfWeek) {
cells.set(`${bucket.dayOfWeek}-${bucket.hour}`, bucket.turns);
max = Math.max(max, bucket.turns);
}
return { cells, max: Math.max(max, 1) };
}, [summary.hourOfWeek]);
const dayLabels = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
return (
<div className="overflow-x-auto">
<div className="grid min-w-[560px] grid-cols-[34px_repeat(24,1fr)] gap-[2px]">
<div />
{Array.from({ length: 24 }, (_, hour) => (
<div key={hour} className="text-center text-[9px] text-muted-foreground">
{hour % 6 === 0
? hour === 0
? "12a"
: hour < 12
? `${hour}a`
: hour === 12
? "12p"
: `${hour - 12}p`
: ""}
</div>
))}
{dayLabels.map((label, dayOfWeek) => (
<>
<div key={label} className="self-center text-[10px] text-muted-foreground">
{label}
</div>
{Array.from({ length: 24 }, (_, hour) => {
const turns = grid.cells.get(`${dayOfWeek}-${hour}`) ?? 0;
const alpha = turns === 0 ? 0 : 0.18 + 0.82 * Math.sqrt(turns / grid.max);
return (
<div
key={`${label}-${hour}`}
title={`${label} ${hour}:00 — ${turns} turn${turns === 1 ? "" : "s"}`}
className="aspect-[1.5] min-w-[14px] rounded-[3px]"
style={{
background:
turns === 0
? "rgba(255,255,255,0.03)"
: `rgba(144,133,233,${alpha.toFixed(2)})`,
}}
/>
);
})}
</>
))}
</div>
</div>
);
}
export function UsageSettingsPanel() {
const primaryEnvironment = usePrimaryEnvironment();
const environmentId = primaryEnvironment?.environmentId ?? null;
const timeZone = useMemo(() => Intl.DateTimeFormat().resolvedOptions().timeZone, []);
const { data, error, isPending, refresh } = useEnvironmentQuery(
environmentId === null
? null
: serverEnvironment.usageSummary({ environmentId, input: { timeZone } }),
);
const summary = data ?? null;
const modelShades = useMemo(
() => (summary ? assignModelShades(summary.byModel) : new Map<string, string>()),
[summary],
);
const tokenSlices = useMemo(() => {
if (!summary) return [];
const claude = summary.byModel.filter((bucket) => isClaudeProvider(bucket.provider));
const codex = summary.byModel.filter((bucket) => !isClaudeProvider(bucket.provider));
const total = Math.max(summary.totals.totalTokens, 1);
const groupTotal = (buckets: ReadonlyArray<UsageModelBucket>) =>
buckets.reduce((sum, bucket) => sum + bucket.totalTokens, 0);
const slices: Array<DonutSlice> = [];
for (const [group, groupColor] of [
[claude, CLAUDE_COLOR],
[codex, CODEX_COLOR],
] as const) {
group.forEach((bucket, index) => {
slices.push({
key: `${bucket.model}: ${formatTokens(bucket.totalTokens)} tokens`,
value: bucket.totalTokens,
color: modelShades.get(bucket.model) ?? NEUTRAL_SHADE,
groupColor,
groupShare: groupTotal(group) / total,
groupStart: index === 0,
});
});
}
return slices;
}, [summary, modelShades]);
const costSlices = useMemo(() => {
if (!summary) return [];
const priced = summary.byModel.filter(
(bucket) => bucket.exactCostMicroUsd > 0 || bucket.estimatedCostMicroUsd > 0,
);
const claude = priced.filter((bucket) => isClaudeProvider(bucket.provider));
const codex = priced.filter((bucket) => !isClaudeProvider(bucket.provider));
const total = Math.max(
priced.reduce(
(sum, bucket) => sum + bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd,
0,
),
1,
);
const groupTotal = (buckets: ReadonlyArray<UsageModelBucket>) =>
buckets.reduce(
(sum, bucket) => sum + bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd,
0,
);
const slices: Array<DonutSlice> = [];
for (const [group, groupColor] of [
[claude, CLAUDE_COLOR],
[codex, CODEX_COLOR],
] as const) {
group.forEach((bucket, index) => {
const value = bucket.exactCostMicroUsd + bucket.estimatedCostMicroUsd;
const estimated = bucket.exactCostMicroUsd === 0;
slices.push({
key: `${bucket.model}: ${formatMicroUsd(value)}${estimated ? " (est.)" : ""}`,
value,
color: modelShades.get(bucket.model) ?? NEUTRAL_SHADE,
estimated,
groupColor,
groupShare: groupTotal(group) / total,
groupStart: index === 0,
});
});
}
return slices;
}, [summary, modelShades]);
if (environmentId === null) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<p className="text-sm text-muted-foreground">Connect an environment to see usage.</p>
</SettingsPageContainer>
);
}
if (isPending && !summary) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<p className="text-sm text-muted-foreground">Loading usage…</p>
</SettingsPageContainer>
);
}
if (error || !summary) {
return (
<SettingsPageContainer>
<UsagePageHeader />
<div>
<p className="text-sm text-muted-foreground">Could not load usage data.</p>
<Button variant="outline" size="sm" className="mt-3" onClick={() => refresh()}>
Retry
</Button>
</div>
</SettingsPageContainer>
);
}
const exactCost = summary.totals.exactCostMicroUsd;
const estimatedCost = summary.totals.estimatedCostMicroUsd;
const cacheHitRate =
summary.totals.inputTokens + summary.totals.cachedInputTokens > 0
? (summary.totals.cachedInputTokens /
(summary.totals.inputTokens +
summary.totals.cachedInputTokens +
summary.totals.cacheCreationTokens)) *
100
: 0;
return (
<SettingsPageContainer>
<UsagePageHeader />
<SettingsSection title="Overview">
<div className="grid gap-8 md:grid-cols-2">
<div>
<div className="mb-3 text-center text-[13px] font-semibold">
Tokens
<span className="block text-[11px] font-normal text-muted-foreground">
all processed, by harness
</span>
</div>
<Donut
slices={tokenSlices}
center={formatTokens(summary.totals.totalTokens)}
centerSub={
summary.earliestFactAt ? `since ${summary.earliestFactAt.slice(0, 10)}` : "all time"
}
ariaLabel="Tokens by harness and model"
/>
</div>
<div>
<div className="mb-3 text-center text-[13px] font-semibold">
Cost
<span className="block text-[11px] font-normal text-muted-foreground">
exact where metered · striped slices are list-price estimates
</span>
</div>
<Donut
slices={costSlices}
center={formatMicroUsd(exactCost + estimatedCost)}
centerSub={`${formatMicroUsd(exactCost)} exact + ${formatMicroUsd(estimatedCost)} est.`}
ariaLabel="Cost by harness and model"
/>
</div>
</div>
<div className="mt-6 grid grid-cols-2 gap-2 lg:grid-cols-5">
<StatTile
label="Output tokens"
value={formatTokens(summary.totals.outputTokens)}
sub="generated text"
/>
<StatTile label="Exact spend" value={formatMicroUsd(exactCost)} sub="provider-metered" />
<StatTile
label="Estimated value"
value={`~${formatMicroUsd(estimatedCost)}`}
sub="list price · plan-covered"
/>
<StatTile label="Turns" value={`${summary.totals.turns}`} sub="recorded in ledger" />
<StatTile
label="Cache hit rate"
value={`${cacheHitRate.toFixed(1)}%`}
sub="of input tokens"
accent
/>
</div>
</SettingsSection>
<SettingsSection title="Tokens per day">
<DailyBars daily={summary.daily} />
</SettingsSection>
<SettingsSection title="When you use T3 Code">
<p className="mb-3 text-xs text-muted-foreground">
Turn starts by local hour and weekday ({timeZone}). Darker means more turns.
</p>
<HourHeatmap summary={summary} />
</SettingsSection>
<SettingsSection title="Models">
<table className="w-full text-[13px]">
<thead>
<tr className="border-b border-border/60 text-[11px] text-muted-foreground">
<th className="py-1.5 text-left font-medium">Model</th>
<th className="py-1.5 text-right font-medium">Turns</th>
<th className="py-1.5 text-right font-medium">Tokens</th>
<th className="py-1.5 text-right font-medium">Output</th>
<th className="py-1.5 text-right font-medium">Cost</th>
</tr>
</thead>
<tbody>
{summary.byModel.map((bucket) => (
<tr key={`${bucket.provider}-${bucket.model}`} className="border-b border-border/40">
<td className="flex items-center gap-2 py-2">
{providerLogo(bucket.provider)}
<span
className="inline-block size-2.5 rounded-[3px]"
style={{ background: modelShades.get(bucket.model) ?? NEUTRAL_SHADE }}
/>
{bucket.model}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{bucket.turns}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.totalTokens)}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.outputTokens)}
</td>
<td className="py-2 text-right tabular-nums text-muted-foreground">
{bucket.costSource === "exact"
? formatMicroUsd(bucket.exactCostMicroUsd)
: bucket.costSource === "estimated"
? `~${formatMicroUsd(bucket.estimatedCostMicroUsd)} est.`
: "—"}
</td>
</tr>
))}
</tbody>
</table>
{summary.unpricedModels.length > 0 ? (
<p className="mt-2 text-[11px] text-muted-foreground">
No pricing data for: {summary.unpricedModels.join(", ")} — shown as tokens only, never
$0.
</p>
) : null}
</SettingsSection>
<SettingsSection title="Projects">
<div className="flex flex-col gap-2">
{summary.byProject.slice(0, 8).map((bucket) => {
const max = Math.max(summary.byProject[0]?.totalTokens ?? 1, 1);
return (
<div
key={bucket.projectId ?? "none"}
className="grid grid-cols-[140px_1fr_72px] items-center gap-3 text-[12.5px]"
>
<span className="truncate text-muted-foreground">
{bucket.projectTitle ?? (bucket.projectId ? "(unknown)" : "(no project)")}
</span>
<div className="h-4 rounded bg-black/20">
<div
className="h-full rounded"
style={{
width: `${Math.max((bucket.totalTokens / max) * 100, 1.5)}%`,
background: T3_ACCENT,
}}
/>
</div>
<span className="text-right tabular-nums text-muted-foreground">
{formatTokens(bucket.totalTokens)}
</span>
</div>
);
})}
</div>
</SettingsSection>
<p className="mt-4 text-[11px] leading-relaxed text-muted-foreground">
Usage facts are recorded from live provider events into this environment's local ledger
(history begins when this feature shipped). Claude costs are exact, reported by the SDK per
turn. Codex reports no cost over its protocol; its dollars are list-price estimates and
always marked as such. Pricing catalog {summary.pricingVersion}.
</p>
</SettingsPageContainer>
);
}
function UsagePageHeader() {
return (
<div>
<h1 className="text-lg font-semibold">Usage</h1>
<p className="text-[13px] text-muted-foreground">
Local analytics from this environment's usage ledger. Nothing leaves your machines.
</p>
</div>
);
}
function StatTile({
label,
value,
sub,
accent,
}: {
label: string;
value: string;
sub: string;
accent?: boolean;
}) {
return (
<div className="rounded-lg border border-border/60 bg-black/20 px-3 py-2.5">
<div className="text-[11px] text-muted-foreground">{label}</div>
<div className={cn("text-lg font-semibold tracking-tight", accent && "text-emerald-500")}>
{value}
</div>
<div className="text-[10.5px] text-muted-foreground/80">{sub}</div>
</div>
);
}
+21
View File
@@ -14,6 +14,7 @@ import { Route as PairRouteImport } from './routes/pair'
import { Route as ConnectRouteImport } from './routes/connect'
import { Route as ChatRouteImport } from './routes/_chat'
import { Route as ChatIndexRouteImport } from './routes/_chat.index'
import { Route as SettingsUsageRouteImport } from './routes/settings.usage'
import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'
import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'
import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'
@@ -49,6 +50,11 @@ const ChatIndexRoute = ChatIndexRouteImport.update({
path: '/',
getParentRoute: () => ChatRoute,
} as any)
const SettingsUsageRoute = SettingsUsageRouteImport.update({
id: '/usage',
path: '/usage',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({
id: '/source-control',
path: '/source-control',
@@ -114,6 +120,7 @@ export interface FileRoutesByFullPath {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
}
@@ -129,6 +136,7 @@ export interface FileRoutesByTo {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/': typeof ChatIndexRoute
'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -147,6 +155,7 @@ export interface FileRoutesById {
'/settings/keybindings': typeof SettingsKeybindingsRoute
'/settings/providers': typeof SettingsProvidersRoute
'/settings/source-control': typeof SettingsSourceControlRoute
'/settings/usage': typeof SettingsUsageRoute
'/_chat/': typeof ChatIndexRoute
'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute
'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute
@@ -166,6 +175,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/$environmentId/$threadId'
| '/draft/$draftId'
fileRoutesByTo: FileRoutesByTo
@@ -181,6 +191,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/'
| '/$environmentId/$threadId'
| '/draft/$draftId'
@@ -198,6 +209,7 @@ export interface FileRouteTypes {
| '/settings/keybindings'
| '/settings/providers'
| '/settings/source-control'
| '/settings/usage'
| '/_chat/'
| '/_chat/$environmentId/$threadId'
| '/_chat/draft/$draftId'
@@ -283,6 +295,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsDiagnosticsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/usage': {
id: '/settings/usage'
path: '/usage'
fullPath: '/settings/usage'
preLoaderRoute: typeof SettingsUsageRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/connections': {
id: '/settings/connections'
path: '/connections'
@@ -343,6 +362,7 @@ interface SettingsRouteChildren {
SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute
SettingsProvidersRoute: typeof SettingsProvidersRoute
SettingsSourceControlRoute: typeof SettingsSourceControlRoute
SettingsUsageRoute: typeof SettingsUsageRoute
}
const SettingsRouteChildren: SettingsRouteChildren = {
@@ -353,6 +373,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsKeybindingsRoute: SettingsKeybindingsRoute,
SettingsProvidersRoute: SettingsProvidersRoute,
SettingsSourceControlRoute: SettingsSourceControlRoute,
SettingsUsageRoute: SettingsUsageRoute,
}
const SettingsRouteWithChildren = SettingsRoute._addFileChildren(
+7
View File
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { UsageSettingsPanel } from "../components/settings/UsageSettings";
export const Route = createFileRoute("/settings/usage")({
component: UsageSettingsPanel,
});
File diff suppressed because it is too large. Load diff
@@ -294,6 +294,10 @@ export function createServerEnvironmentAtoms<R, E>(
label: "environment-data:server:process-diagnostics",
tag: WS_METHODS.serverGetProcessDiagnostics,
}),
usageSummary: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:usage-summary",
tag: WS_METHODS.usageGetSummary,
}),
processResourceHistory: createEnvironmentRpcQueryAtomFamily(runtime, {
label: "environment-data:server:process-resource-history",
tag: WS_METHODS.serverGetProcessResourceHistory,
+1
View File
@@ -26,3 +26,4 @@ export * from "./review.ts";
export * from "./preview.ts";
export * from "./previewAutomation.ts";
export * from "./rpc.ts";
export * from "./usage.ts";
+28
View File
@@ -21,6 +21,7 @@ import {
TurnId,
} from "./baseSchemas.ts";
import { ProviderInstanceId } from "./providerInstance.ts";
import { UsageFact } from "./usage.ts";
export const ORCHESTRATION_WS_METHODS = {
dispatchCommand: "orchestration.dispatchCommand",
@@ -798,6 +799,17 @@ const ThreadRevertCompleteCommand = Schema.Struct({
createdAt: IsoDateTime,
});
const ThreadUsageRecordCommand = Schema.Struct({
type: Schema.Literal("thread.usage.record"),
commandId: CommandId,
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
projectId: Schema.NullOr(ProjectId),
facts: Schema.Array(UsageFact),
createdAt: IsoDateTime,
});
export type ThreadUsageRecordCommand = typeof ThreadUsageRecordCommand.Type;
const InternalOrchestrationCommand = Schema.Union([
ThreadSessionSetCommand,
ThreadMessageAssistantDeltaCommand,
@@ -806,6 +818,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadTurnDiffCompleteCommand,
ThreadActivityAppendCommand,
ThreadRevertCompleteCommand,
ThreadUsageRecordCommand,
]);
export type InternalOrchestrationCommand = typeof InternalOrchestrationCommand.Type;
@@ -838,6 +851,7 @@ export const OrchestrationEventType = Schema.Literals([
"thread.proposed-plan-upserted",
"thread.turn-diff-completed",
"thread.activity-appended",
"thread.usage-recorded",
]);
export type OrchestrationEventType = typeof OrchestrationEventType.Type;
@@ -1012,6 +1026,15 @@ export const ThreadActivityAppendedPayload = Schema.Struct({
activity: OrchestrationThreadActivity,
});
export const ThreadUsageRecordedPayload = Schema.Struct({
threadId: ThreadId,
turnId: Schema.NullOr(TurnId),
/** Project attribution captured at fact time (historical-at-use). */
projectId: Schema.NullOr(ProjectId),
facts: Schema.Array(UsageFact),
recordedAt: IsoDateTime,
});
export const OrchestrationEventMetadata = Schema.Struct({
providerTurnId: Schema.optional(TrimmedNonEmptyString),
providerItemId: Schema.optional(ProviderItemId),
@@ -1144,6 +1167,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.activity-appended"),
payload: ThreadActivityAppendedPayload,
}),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.usage-recorded"),
payload: ThreadUsageRecordedPayload,
}),
]);
export type OrchestrationEvent = typeof OrchestrationEvent.Type;
+12
View File
@@ -46,6 +46,10 @@ const ProviderRefs = Schema.Struct({
providerTurnId: Schema.optional(TrimmedNonEmptyStringSchema),
providerItemId: Schema.optional(ProviderItemId),
providerRequestId: Schema.optional(ProviderRequestId),
/** Provider-native session/thread identity (Claude session_id, Codex thread
* id). Required to attribute cumulative usage counters when several
* provider sessions run concurrently under one T3 thread. */
providerSessionId: Schema.optional(TrimmedNonEmptyStringSchema),
});
export type ProviderRefs = typeof ProviderRefs.Type;
@@ -320,6 +324,14 @@ export const ThreadTokenUsageSnapshot = Schema.Struct({
toolUses: Schema.optional(NonNegativeInt),
durationMs: Schema.optional(NonNegativeInt),
compactsAutomatically: Schema.optional(Schema.Boolean),
/** Session-cumulative counters (monotonic within one provider-native
* session). Present only when the adapter can report them; usage accounting
* derives interval deltas from these, never from the context-window fields
* above. `totalInputTokens` includes cached reads, mirroring the provider. */
totalInputTokens: Schema.optional(NonNegativeInt),
totalCachedInputTokens: Schema.optional(NonNegativeInt),
totalOutputTokens: Schema.optional(NonNegativeInt),
totalReasoningOutputTokens: Schema.optional(NonNegativeInt),
});
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
+9
View File
@@ -132,6 +132,7 @@ import {
ServerUpsertKeybindingResult,
} from "./server.ts";
import { ServerSettings, ServerSettingsError, ServerSettingsPatch } from "./settings.ts";
import { UsageSummaryRequest, UsageSummaryResponse } from "./usage.ts";
import {
SourceControlCloneRepositoryInput,
SourceControlCloneRepositoryResult,
@@ -211,6 +212,7 @@ export const WS_METHODS = {
serverUpdateSettings: "server.updateSettings",
serverDiscoverSourceControl: "server.discoverSourceControl",
serverGetTraceDiagnostics: "server.getTraceDiagnostics",
usageGetSummary: "usage.getSummary",
serverGetProcessDiagnostics: "server.getProcessDiagnostics",
serverGetProcessResourceHistory: "server.getProcessResourceHistory",
serverSignalProcess: "server.signalProcess",
@@ -303,6 +305,12 @@ export const WsServerGetTraceDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetTrace
error: EnvironmentAuthorizationError,
});
export const WsUsageGetSummaryRpc = Rpc.make(WS_METHODS.usageGetSummary, {
payload: UsageSummaryRequest,
success: UsageSummaryResponse,
error: EnvironmentAuthorizationError,
});
export const WsServerGetProcessDiagnosticsRpc = Rpc.make(WS_METHODS.serverGetProcessDiagnostics, {
payload: Schema.Struct({}),
success: ServerProcessDiagnosticsResult,
@@ -699,6 +707,7 @@ export const WsRpcGroup = RpcGroup.make(
WsServerUpdateSettingsRpc,
WsServerDiscoverSourceControlRpc,
WsServerGetTraceDiagnosticsRpc,
WsUsageGetSummaryRpc,
WsServerGetProcessDiagnosticsRpc,
WsServerGetProcessResourceHistoryRpc,
WsServerSignalProcessRpc,
+153
View File
@@ -0,0 +1,153 @@
import * as Schema from "effect/Schema";
import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts";
import { ProviderDriverKind, ProviderInstanceId } from "./providerInstance.ts";
// ---------------------------------------------------------------------------
// Usage facts
//
// A usage fact is an immutable accounting record: interval token counters (never
// cumulative) attributed to a provider-native session so that concurrent or
// resumed provider sessions on one T3 thread can never be conflated. Facts are
// persisted as `thread.usage-recorded` orchestration events and projected into
// `projection_usage_facts` / `projection_usage_daily` by a registered projector.
// ---------------------------------------------------------------------------
export const UsageFactId = TrimmedNonEmptyString.pipe(Schema.brand("UsageFactId"));
export type UsageFactId = typeof UsageFactId.Type;
/** Interval (delta) token counters. Adapters convert cumulative provider
* counters into deltas before a fact is emitted; a fact never carries a
* running total. `cachedInputTokens` are cache reads; `cacheCreationTokens`
* are cache writes — they are priced differently and never summed silently. */
export const UsageTokenCounters = Schema.Struct({
inputTokens: NonNegativeInt,
cachedInputTokens: NonNegativeInt,
cacheCreationTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
reasoningOutputTokens: NonNegativeInt,
});
export type UsageTokenCounters = typeof UsageTokenCounters.Type;
/** `final` — per-model settlement derived from a provider's terminal report
* (Claude modelUsage deltas). `interval` — an accumulated slice of a turn
* flushed before settlement (Codex per-update deltas); intervals and finals
* both sum linearly. `turn-total` — the provider's own turn-level cost figure
* kept only to reconcile against per-model facts, never added to them. */
export const UsageFactKind = Schema.Literals(["final", "interval", "turn-total"]);
export type UsageFactKind = typeof UsageFactKind.Type;
export const UsageFact = Schema.Struct({
factId: UsageFactId,
kind: UsageFactKind,
provider: ProviderDriverKind,
providerInstanceId: Schema.optional(ProviderInstanceId),
/** Provider-native session identity (Claude session_id, Codex thread id).
* Falls back to the T3 thread id when a driver exposes nothing better. */
providerSessionId: TrimmedNonEmptyString,
model: TrimmedNonEmptyString,
/** Model id exactly as the provider reported it (e.g. with `[1m]` suffix). */
modelRaw: TrimmedNonEmptyString,
reasoningEffort: Schema.optional(TrimmedNonEmptyString),
tokens: UsageTokenCounters,
/** Exact provider-reported cost in integer micro-USD. Absent when the
* provider does not meter (Codex); estimates are computed at query time and
* never stored. */
costMicroUsd: Schema.optional(NonNegativeInt),
/** True when the originating runtime event was rejected by the turn
* lifecycle guard (stale completion); recorded rather than dropped. */
stale: Schema.optional(Schema.Boolean),
observedAt: IsoDateTime,
});
export type UsageFact = typeof UsageFact.Type;
// ---------------------------------------------------------------------------
// Claude SDK modelUsage — typed replacement for the UnknownRecord that rides
// on `turn.completed`. Keys of the map are raw model ids.
// ---------------------------------------------------------------------------
export const ClaudeModelUsageEntry = Schema.Struct({
inputTokens: NonNegativeInt,
outputTokens: NonNegativeInt,
cacheReadInputTokens: NonNegativeInt,
cacheCreationInputTokens: NonNegativeInt,
costUSD: Schema.optional(Schema.Number),
});
export type ClaudeModelUsageEntry = typeof ClaudeModelUsageEntry.Type;
export const ClaudeModelUsageMap = Schema.Record(Schema.String, ClaudeModelUsageEntry);
export type ClaudeModelUsageMap = typeof ClaudeModelUsageMap.Type;
// ---------------------------------------------------------------------------
// usage.summary RPC — one dashboard-shaped request so the Usage page renders
// from a single round trip. All aggregates are integers (tokens) or integer
// micro-USD; grouping happens in the requested IANA timezone.
// ---------------------------------------------------------------------------
export const UsageSummaryRequest = Schema.Struct({
/** Inclusive ISO date-time lower bound; omit for all time. */
since: Schema.optional(IsoDateTime),
/** Exclusive ISO date-time upper bound; omit for now. */
until: Schema.optional(IsoDateTime),
/** IANA timezone used for calendar bucketing (daily, hour-of-week). */
timeZone: TrimmedNonEmptyString,
});
export type UsageSummaryRequest = typeof UsageSummaryRequest.Type;
export const UsageCostSource = Schema.Literals(["exact", "estimated", "none"]);
export type UsageCostSource = typeof UsageCostSource.Type;
const UsageAggregate = Schema.Struct({
...UsageTokenCounters.fields,
totalTokens: NonNegativeInt,
turns: NonNegativeInt,
exactCostMicroUsd: NonNegativeInt,
estimatedCostMicroUsd: NonNegativeInt,
});
export type UsageAggregate = typeof UsageAggregate.Type;
export const UsageModelBucket = Schema.Struct({
...UsageAggregate.fields,
provider: ProviderDriverKind,
model: TrimmedNonEmptyString,
costSource: UsageCostSource,
});
export type UsageModelBucket = typeof UsageModelBucket.Type;
export const UsageDailyBucket = Schema.Struct({
...UsageAggregate.fields,
/** Local calendar date (YYYY-MM-DD) in the request timezone. */
day: TrimmedNonEmptyString,
provider: ProviderDriverKind,
model: TrimmedNonEmptyString,
});
export type UsageDailyBucket = typeof UsageDailyBucket.Type;
export const UsageHourOfWeekBucket = Schema.Struct({
/** 0 = Sunday, per JS Date#getDay in the request timezone. */
dayOfWeek: NonNegativeInt,
hour: NonNegativeInt,
turns: NonNegativeInt,
totalTokens: NonNegativeInt,
});
export type UsageHourOfWeekBucket = typeof UsageHourOfWeekBucket.Type;
export const UsageProjectBucket = Schema.Struct({
...UsageAggregate.fields,
projectId: Schema.NullOr(ProjectId),
projectTitle: Schema.NullOr(TrimmedNonEmptyString),
});
export type UsageProjectBucket = typeof UsageProjectBucket.Type;
export const UsageSummaryResponse = Schema.Struct({
totals: UsageAggregate,
byModel: Schema.Array(UsageModelBucket),
daily: Schema.Array(UsageDailyBucket),
hourOfWeek: Schema.Array(UsageHourOfWeekBucket),
byProject: Schema.Array(UsageProjectBucket),
/** Models with token volume but no pricing entry — surfaced, never $0. */
unpricedModels: Schema.Array(TrimmedNonEmptyString),
pricingVersion: TrimmedNonEmptyString,
/** Earliest fact in the ledger, for "history starts here" honesty. */
earliestFactAt: Schema.NullOr(IsoDateTime),
});
export type UsageSummaryResponse = typeof UsageSummaryResponse.Type;
+4
View File
@@ -3,6 +3,10 @@
"private": true,
"type": "module",
"exports": {
"./usagePricing": {
"types": "./src/usagePricing.ts",
"import": "./src/usagePricing.ts"
},
"./projectFavicon": {
"types": "./src/projectFavicon.ts",
"import": "./src/projectFavicon.ts"
+79
View File
@@ -0,0 +1,79 @@
/**
* Versioned list-price catalog for estimating usage cost when a provider does
* not meter (Codex reports tokens only). Estimates are computed at query time
* from immutable token facts and are always labeled as estimates — they are
* never persisted and never blended with provider-reported exact cost.
*
* Rates are USD per million tokens, effective-dated so a price change never
* silently revalues history. `cacheWritePerMTok` covers cache-creation
* tokens; providers without a cache-write concept omit it.
*/
export interface UsageModelPricing {
readonly model: string;
/** Inclusive ISO date this rate takes effect. */
readonly effectiveFrom: string;
readonly inputPerMTok: number;
readonly cachedInputPerMTok: number;
readonly cacheWritePerMTok?: number;
readonly outputPerMTok: number;
}
export const USAGE_PRICING_VERSION = "2026-07-24";
const CATALOG: ReadonlyArray<UsageModelPricing> = [
// OpenAI list prices (verified against ccusage output to the cent).
{
model: "gpt-5.6-sol",
effectiveFrom: "2026-01-01",
inputPerMTok: 10,
cachedInputPerMTok: 1,
outputPerMTok: 60,
},
{
model: "gpt-5.5",
effectiveFrom: "2025-11-01",
inputPerMTok: 10,
cachedInputPerMTok: 1,
outputPerMTok: 60,
},
];
export interface UsageTokenBreakdown {
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly cacheCreationTokens: number;
readonly outputTokens: number;
}
function rateFor(model: string, observedAtIso: string): UsageModelPricing | undefined {
let best: UsageModelPricing | undefined;
for (const entry of CATALOG) {
if (entry.model !== model) continue;
if (entry.effectiveFrom > observedAtIso.slice(0, 10)) continue;
if (!best || entry.effectiveFrom > best.effectiveFrom) {
best = entry;
}
}
return best;
}
/** Integer micro-USD estimate, or undefined when the model has no rate (the
* caller surfaces it as unpriced rather than $0). */
export function estimateCostMicroUsd(
model: string,
observedAtIso: string,
tokens: UsageTokenBreakdown,
): number | undefined {
const rate = rateFor(model, observedAtIso);
if (!rate) {
return undefined;
}
const usd =
(tokens.inputTokens * rate.inputPerMTok +
tokens.cachedInputTokens * rate.cachedInputPerMTok +
tokens.cacheCreationTokens * (rate.cacheWritePerMTok ?? rate.inputPerMTok) +
tokens.outputTokens * rate.outputPerMTok) /
1_000_000;
return Math.round(usd * 1_000_000);
}