TypeScript
fix(server): token telemetry counts each request once and only confirmed models (#29001)
Theo Browneb92c8f473990
diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.tsindex 06b62e0e03b..a7b1f7e2e03 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts@@ -5457,6 +5457,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {outputTokens: queryExits ? 40 : 46,cachedInputTokens: queryExits ? 2000 : 11455,cacheCreationTokens: queryExits ? 500 : 2847,+ ...(queryExits ? {} : { models: ["claude-sonnet-4-6"] }),},);}diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.tsindex 4f26e50e576..5b4a4ad84d4 100644--- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts@@ -21,7 +21,14 @@ import {} from "./claudeWorkflowProgress.ts";import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";-import { normalizeClaudeTurnTokenUsage } from "../../provider/ClaudeTurnTokenUsage.ts";+import {+ addClaudeLedgerUsage,+ claudeLedgerDelta,+ claudeModelLedger,+ normalizeClaudeTurnTokenUsage,+ type ClaudeLedgerUsage,+ type ClaudeModelLedger,+} from "../../provider/ClaudeTurnTokenUsage.ts";import { toMcpElicitationResponse } from "../../provider/CodexMcpElicitation.ts";import {type CanUseTool,@@ -4071,6 +4078,9 @@ interface ActiveClaudeTurnContext {compactionFailure: { readonly message: string | undefined } | null;// Steers end segments whose usage is excluded from the final result; bill them too, oldest first.readonly steeredSegmentUsage: Array<SDKResultMessage["usage"]>;+ // Ledger growth of the steered segments; undefined once any segment's growth is unknown.+ steeredLedgerUsage: ClaudeLedgerUsage | undefined;+ readonly rootModels: Set<string>;readonly subagentsByTaskId: Map<string, ActiveClaudeSubagent>;readonly subagentsByToolUseId: Map<string, ActiveClaudeSubagent>;readonly promptUuid: string | null;@@ -4122,6 +4132,8 @@ interface ClaudeLiveQueryContext {permissionMode: PermissionMode;stopping: boolean;readonly subagentsFromEarlierProcesses: ReadonlySet<ActiveClaudeSubagent>;+ // The SDK's per-process model ledger at the last result; a new process starts at zero.+ modelLedger: ClaudeModelLedger | undefined;// Per process, not per session: a relative temp dir follows the cwd this CLI// was launched in, and a later turn's cwd can differ.readonly taskOutputRoot: string | undefined;@@ -4775,6 +4787,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (const interruptedTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());const steeredTurns = yield* Ref.make(new Set<OrchestrationV2ProviderTurn["id"]>());const queryContext = yield* Ref.make<ClaudeLiveQueryContext | null>(null);+ // Wake buffers replay result frames, so ledger growth is measured once on arrival.+ const resultLedgerUsage = new WeakMap<SDKMessage, ClaudeLedgerUsage>();// A worktree handoff changes the project settings even within one session.let bypassCache: { cwd: string | null; availability: ClaudeBypassAvailability } | null =null;@@ -7613,6 +7627,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (input.context.subagentsByToolUseId.size > 0,input.status,input.context.steeredSegmentUsage,+ {+ rootModels: input.context.rootModels,+ ...(input.result === undefined+ ? {}+ : {+ ledger: addClaudeLedgerUsage(+ input.context.steeredLedgerUsage,+ resultLedgerUsage.get(input.result),+ ),+ }),+ },),},}),@@ -8528,6 +8553,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (if (message.type === "assistant" && input.replayed !== true) {if (message.parent_tool_use_id === null) {+ // CLI notices and API errors arrive as assistant messages from "<synthetic>".+ if (message.message.model && message.message.model !== "<synthetic>") {+ context.rootModels.add(message.message.model);+ }// Subagent uuids exist only in the sidechain transcript, so resume and fork cannot target them.context.nativeMessageCursor = message.uuid;context.latestAssistantRateLimit =@@ -9409,6 +9438,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (const wasSteered = (yield* Ref.get(steeredTurns)).has(context.providerTurnId);if (!interrupted && wasSteered && isClaudeActiveSteeringAbortResult(message)) {context.steeredSegmentUsage.push(message.usage);+ context.steeredLedgerUsage = addClaudeLedgerUsage(+ context.steeredLedgerUsage,+ resultLedgerUsage.get(message),+ );return;}yield* Ref.update(steeredTurns, (current) => {@@ -10404,6 +10437,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ((subagent) => subagent.task.status === "running",),),+ modelLedger: new Map(),taskOutputRoot: claudeTaskOutputRoot(adapterOptions.environment,path,@@ -10432,6 +10466,16 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* () {context.permissionMode = message.permissionMode;}+ if (message.type === "result") {+ const ledger = claudeModelLedger(message.modelUsage);+ const growth = claudeLedgerDelta(context.modelLedger, ledger);+ if (growth !== undefined) resultLedgerUsage.set(message, growth);+ // A ledger that went backwards cannot anchor the next turn's growth.+ context.modelLedger =+ growth === undefined && context.modelLedger !== undefined+ ? undefined+ : ledger;+ }return handleSdkMessage({ query: querySession, message });}),),@@ -10577,6 +10621,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (latestAssistantRateLimit: null,compactionFailure: null,steeredSegmentUsage: [],+ steeredLedgerUsage: { inputTokens: 0, outputTokens: 0 },+ rootModels: new Set(),subagentsByTaskId: new Map(),subagentsByToolUseId: new Map(),promptUuid,diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex e6399ff36fd..fa6bb58a9dc 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -1830,6 +1830,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (const turnWaiters = yield* Ref.make(new Map<string, Deferred.Deferred<void, never>>());const subagentThreads = yield* Ref.make(new Map<string, CodexSubagentThreadContext>());const subagentSelections = new Map<string, Omit<ModelSelection, "instanceId">>();+ // A reroute names one turn; until new settings arrive, the thread's model is unknown.+ const reroutedTurnModels = new Map<string, string>();+ const reroutedThreads = new Set<string>();+ const reportedTurnModel = (nativeThreadId: string, nativeTurnId: string) => {+ const rerouted = reroutedTurnModels.get(nativeTurnId);+ reroutedTurnModels.delete(nativeTurnId);+ if (rerouted !== undefined) return rerouted;+ return reroutedThreads.has(nativeThreadId)+ ? undefined+ : subagentSelections.get(nativeThreadId)?.model;+ };const pendingSubagentTurns = yield* Ref.make(new Map<string, ReadonlyArray<PendingCodexSubagentTurnStarted>>(),);@@ -4475,15 +4486,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ();yield* client.handleServerNotification("thread/settings/updated", (payload) =>- updateSubagentSelection(- payload.threadId,- payload.threadSettings.model,- payload.threadSettings.effort,- payload.threadSettings.serviceTier,+ Effect.sync(() => reroutedThreads.delete(payload.threadId)).pipe(+ Effect.andThen(+ updateSubagentSelection(+ payload.threadId,+ payload.threadSettings.model,+ payload.threadSettings.effort,+ payload.threadSettings.serviceTier,+ ),+ ),),);yield* client.handleServerNotification("model/rerouted", (payload) =>- updateSubagentSelection(payload.threadId, payload.toModel),+ Effect.sync(() => {+ reroutedTurnModels.set(payload.turnId, payload.toModel);+ reroutedThreads.add(payload.threadId);+ }).pipe(Effect.andThen(updateSubagentSelection(payload.threadId, payload.toModel))),);yield* client.handleServerNotification("hook/completed", (payload) =>@@ -6127,6 +6145,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (),input.nativeTurnId,input.status === "completed",+ reportedTurnModel(+ input.context.providerThread.nativeThreadRef?.nativeId ?? "",+ input.nativeTurnId,+ ),),};if (!holdsForGoal) {diff --git a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.tsindex bb26a5dd53a..b4c319e8e9a 100644--- a/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/OpenCode2AdapterV2.test.ts@@ -2150,6 +2150,20 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {const { runtime, thread } = yield* resumed([out("session.prompt", { sessionID: SESSION, id: PROMPT_ID, text: "<any>" }),promptAccepted,+ event("session.step.started", {+ sessionID: SESSION,+ assistantMessageID: "msg_before_gap",+ agent: "build",+ model: { id: "big-pickle", providerID: "opencode", variant: "default" },+ started: 1,+ }),+ event("session.step.ended", {+ sessionID: SESSION,+ assistantMessageID: "msg_before_gap",+ finish: "tool-calls",+ cost: 0,+ tokens: { input: 100, output: 10, reasoning: 0, cache: { read: 0, write: 0 } },+ }),...reconnected({}, "succeeded"),]);const events = yield* runtime.events.pipe(@@ -2164,6 +2178,15 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {"command_execution:completed",]);assert.deepInclude(collected.at(-1), { type: "turn.terminal", status: "completed" });+ // Steps that ended during the gap sent no tokens or models, so both stay incomplete.+ const settled = collected.findLast(+ (event) =>+ event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,+ );+ const usage =+ settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined;+ assert.deepInclude(usage, { usageStatus: "partial", inputTokens: 100, outputTokens: 10 });+ assert.notProperty(usage, "models");}).pipe(Effect.scoped),);@@ -2879,6 +2902,40 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {}).pipe(Effect.scoped),);+ it.effect("leaves models unknown when a step ends without a seen start", () =>+ Effect.gen(function* () {+ const tokens = { input: 10, output: 1, reasoning: 0, cache: { read: 0, write: 0 } };+ const step = (id: string) => ({ sessionID: SESSION, assistantMessageID: id });+ const { runtime, thread } = yield* resumed([+ out("session.prompt", { sessionID: SESSION, text: "<any>" }),+ promptAccepted,+ event("session.step.started", {+ ...step("msg_seen"),+ agent: "build",+ model: { id: "big-pickle", providerID: "opencode", variant: "default" },+ started: 1,+ }),+ event("session.step.ended", { ...step("msg_seen"), finish: "tool-calls", cost: 0, tokens }),+ event("session.step.ended", { ...step("msg_unseen"), finish: "stop", cost: 0, tokens }),+ event("session.execution.succeeded", { sessionID: SESSION }),+ ]);+ const turn = yield* runtime.events.pipe(+ Stream.filter(+ (event) =>+ event.type === "provider_turn.updated" && event.providerTurn.completedAt !== null,+ ),+ Stream.runHead,+ Effect.forkScoped,+ );+ yield* runtime.startTurn(turnInput(thread));+ const settled = Option.getOrUndefined(yield* Fiber.join(turn));+ const usage =+ settled?.type === "provider_turn.updated" ? settled.providerTurn.turnTokenUsage : undefined;+ assert.deepInclude(usage, { usageStatus: "complete", inputTokens: 20, outputTokens: 2 });+ assert.notProperty(usage, "models");+ }).pipe(Effect.scoped),+ );+it.effect("reports cache writes as cache creation, not only as input", () =>Effect.gen(function* () {const { runtime, thread } = yield* resumed([diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.tsindex 7f1006f1c5e..927a9060dd4 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts@@ -45,6 +45,7 @@ import * as EventStore from "./EventStore.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProjectionStore from "./ProjectionStore.ts";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";+import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";@@ -325,12 +326,14 @@ it.effect("refreshes the failing instance snapshot after a committed usage_limit);it.effect("records accepted billed turn usage once without billing the context window", () => {- const recorded: Array<Readonly<Record<string, unknown>>> = [];- const layerAnalytics = Layer.succeed(ProviderEventIngestor.ProviderTurnAnalytics, {- record: (properties: Readonly<Record<string, unknown>>) =>+ const recorded: Array<ProviderUsageAnalytics.ProviderTurnReport> = [];+ const layerAnalytics = Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, {+ runStarted: () => Effect.void,+ turnCompleted: (report) =>Effect.sync(() => {- recorded.push(properties);+ recorded.push(report);}),+ runSettled: () => Effect.void,});return Effect.gen(function* () {const now = yield* DateTime.now;@@ -413,23 +416,9 @@ it.effect("records accepted billed turn usage once without billing the context wassert.isEmpty(ignored);assert.lengthOf(recorded, 1);assert.deepEqual(recorded[0], {- provider: CODEX_DRIVER,- terminalStatus: "completed",- usageStatus: "complete",- usageScope: "main_agent",- hasSubagents: false,- inputTokens: 40,- cachedInputTokens: 30,- outputTokens: 10,- model: modelSelection.model,- mixedModels: false,- runtimeMode: "full-access",- interactionMode: "default",- createdBy: "agent",- creationSource: "provider",- scheduled: false,- subagent: true,- durationMs: 120,+ driver: CODEX_DRIVER,+ providerTurn,+ context: input.analyticsContext,});}).pipe(Effect.provide(layerTest.pipe(Layer.provide(layerAnalytics))));});diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.tsindex 5a2aa39faec..f27580d909a 100644--- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts+++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts@@ -5,14 +5,9 @@ import {OrchestrationV2StoredEvent,type OrchestrationV2PlanArtifact,type OrchestrationV2Run,- type OrchestrationV2ProviderTurn,type OrchestrationV2Subagent,type OrchestrationV2ThreadProjection,type ModelSelection,- type OrchestrationV2Actor,- type OrchestrationV2CreationSource,- type RuntimeMode,- type ProviderInteractionMode,ProviderInstanceId,ProviderSessionId,ProviderThreadId,@@ -31,8 +26,11 @@ import * as SqlError from "effect/sql/SqlError";import { AgentScope } from "@t3tools/shared/AgentScope";import { isTemporaryWorktreeBranch } from "@t3tools/shared/git";-import { getModelSelectionStringOptionValue, modelSelectionsEqual } from "@t3tools/shared/model";-import * as AnalyticsService from "../telemetry/AnalyticsService.ts";+import { modelSelectionsEqual } from "@t3tools/shared/model";+import {+ ProviderTurnAnalytics,+ type ProviderTurnAnalyticsContext,+} from "../telemetry/ProviderUsageAnalytics.ts";import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts";import * as EventSink from "./EventSink.ts";@@ -85,88 +83,6 @@ export const ProviderEventIngestorV2Error = Schema.Union([]);export type ProviderEventIngestorV2Error = typeof ProviderEventIngestorV2Error.Type;-export interface ProviderTurnAnalyticsContext {- readonly modelSelection: ModelSelection;- readonly runtimeMode?: RuntimeMode;- readonly interactionMode?: ProviderInteractionMode;- readonly origin?: ProviderTurnOrigin;-}--/**- * Where the run's starting message came from. Most turns start without a- * person (provider continuations, agent sends, delegated subagents), so- * reports need this to tell user turns apart.- */-export interface ProviderTurnOrigin {- readonly createdBy: OrchestrationV2Actor;- readonly creationSource: OrchestrationV2CreationSource;- readonly scheduled: boolean;- readonly subagent: boolean;-}--export class ProviderTurnAnalytics extends Context.Reference<{- readonly record: (properties: Readonly<Record<string, unknown>>) => Effect.Effect<void>;-}>("t3/orchestration-v2/ProviderTurnAnalytics", {- defaultValue: () => ({ record: () => Effect.void }),-}) {}--export const layerAnalytics = Layer.effect(- ProviderTurnAnalytics,- Effect.gen(function* () {- const analytics = yield* AnalyticsService.AnalyticsService;- return {- record: Effect.fn("ProviderTurnAnalytics.record")(function (- properties: Readonly<Record<string, unknown>>,- ) {- return analytics.record("provider.turn.completed", properties);- }),- };- }),-);--function providerTurnAnalyticsProperties(input: {- readonly driver: ProviderAdapter.ProviderAdapterV2Event["driver"];- readonly providerTurn: OrchestrationV2ProviderTurn;- readonly context?: ProviderTurnAnalyticsContext;-}): Readonly<Record<string, unknown>> {- const usage = input.providerTurn.turnTokenUsage;- const modelSelection = input.context?.modelSelection;- const effort = modelSelection- ? (getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??- getModelSelectionStringOptionValue(modelSelection, "effort"))- : undefined;- return {- provider: input.driver,- terminalStatus: input.providerTurn.status,- usageStatus: usage?.usageStatus ?? "unavailable",- usageScope: usage?.usageScope ?? "main_agent",- ...(usage ? { hasSubagents: usage.hasSubagents } : {}),- ...(usage?.inputTokens === undefined ? {} : { inputTokens: usage.inputTokens }),- ...(usage?.cachedInputTokens === undefined- ? {}- : { cachedInputTokens: usage.cachedInputTokens }),- ...(usage?.cacheCreationTokens === undefined- ? {}- : { cacheCreationTokens: usage.cacheCreationTokens }),- ...(usage?.outputTokens === undefined ? {} : { outputTokens: usage.outputTokens }),- ...(usage?.reasoningTokens === undefined ? {} : { reasoningTokens: usage.reasoningTokens }),- ...(modelSelection ? { model: modelSelection.model, mixedModels: false } : {}),- ...(effort ? { effort } : {}),- ...(input.context?.runtimeMode ? { runtimeMode: input.context.runtimeMode } : {}),- ...(input.context?.interactionMode ? { interactionMode: input.context.interactionMode } : {}),- ...input.context?.origin,- ...(input.providerTurn.startedAt && input.providerTurn.completedAt- ? {- durationMs: Math.max(- 0,- DateTime.toEpochMillis(input.providerTurn.completedAt) -- DateTime.toEpochMillis(input.providerTurn.startedAt),- ),- }- : {}),- };-}-type TodoListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;function withPlanStepDurations(@@ -891,15 +807,13 @@ export const layer: Layer.Layer<const oldest = completedTurnAnalytics.values().next().value;if (oldest !== undefined) completedTurnAnalytics.delete(oldest);}- yield* analytics.record(- providerTurnAnalyticsProperties({- driver: input.event.driver,- providerTurn,- ...(input.analyticsContext === undefined- ? {}- : { context: input.analyticsContext }),- }),- );+ yield* analytics.turnCompleted({+ driver: input.event.driver,+ providerTurn,+ ...(input.analyticsContext === undefined+ ? {}+ : { context: input.analyticsContext }),+ });}),),(effect) =>diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.tsindex 05fc1b8545b..c9311433eec 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts@@ -51,6 +51,7 @@ import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"import * as ProviderSessionManager from "./ProviderSessionManager.ts";import * as ProviderTurnStart from "./ProviderTurnStartService.ts";import * as RunExecutionService from "./RunExecutionService.ts";+import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";import * as RuntimePolicy from "./RuntimePolicy.ts";const isDomainEvent = Schema.is(OrchestrationV2DomainEvent);@@ -301,6 +302,7 @@ function makeLocalCommandHarness(input: {readonly switchedProvider?: boolean;};}) {+ const settledRuns: Array<string> = [];const now = DateTime.makeUnsafe("2026-09-04T12:00:00Z");const threadId = ThreadId.make("thread-native-account-command");const runId = RunId.make("run-native-account-command");@@ -947,6 +949,11 @@ function makeLocalCommandHarness(input: {}),Layer.mock(ProviderAuthService.ProviderAuthService)({ tryHandlePromptCommand }),Layer.mock(RunExecutionService.RunExecutionServiceV2)({ startRootRun }),+ Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, {+ runStarted: () => Effect.void,+ turnCompleted: () => Effect.void,+ runSettled: (report) => Effect.sync(() => void settledRuns.push(report.status)),+ }),Layer.mock(RuntimePolicy.RuntimePolicyV2)({resolve: resolveRuntimePolicy,}),@@ -954,6 +961,7 @@ function makeLocalCommandHarness(input: {),);return {+ settledRuns,getThreadRecords,getTurnStartContext,setProjection: (next: OrchestrationV2ThreadProjection) => {@@ -1578,6 +1586,7 @@ effectIt.effect("terminalizes a starting run when its provider session cannot op);const projection = harness.projection();expect(projection.runs.at(-1)).toMatchObject({ status: "failed", startedAt: null });+ expect(harness.settledRuns).toEqual(["failed"]);expect(projection.attempts[0]).toMatchObject({ status: "failed", startedAt: null });expect(projection.nodes[0]).toMatchObject({ status: "failed", startedAt: null });expect(projection.turnItems).toMatchObject([@@ -1667,6 +1676,7 @@ effectIt.effect("does not overwrite a run interrupted while its provider sessionexpect(harness.startRootRun).not.toHaveBeenCalled();const projection = harness.projection();expect(projection.runs.at(-1)?.status).toBe("interrupted");+ expect(harness.settledRuns).toEqual([]);expect(projection.attempts[0]?.status).toBe("pending");expect(projection.nodes[0]?.status).toBe("pending");expect(projection.turnItems).toEqual([]);diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.tsindex 9a5ad6114e2..62a9e8b88e9 100644--- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts+++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts@@ -33,6 +33,7 @@ import * as ProviderAuthService from "../provider/ProviderAuthService.ts";import * as ServerSettings from "../serverSettings.ts";import { makeIsManagedWorktreePath } from "../worktreesDirectory.ts";import * as EventSink from "./EventSink.ts";+import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";import * as ContextHandoffService from "./ContextHandoffService.ts";import { isActiveRun } from "./CommandPolicy.ts";import {@@ -148,6 +149,7 @@ export const layer: Layer.Layer<ProviderTurnStartServiceV2,Effect.gen(function* () {const eventSink = yield* EventSink.EventSinkV2;+ const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics;const contextHandoffService = yield* ContextHandoffService.ContextHandoffServiceV2;const idAllocator = yield* IdAllocator.IdAllocatorV2;const fileSystem = yield* FileSystem.FileSystem;@@ -496,13 +498,22 @@ export const layer: Layer.Layer<} satisfies OrchestrationV2DomainEvent;}),);- yield* eventSink.writeIfRunCurrent({+ const written = yield* eventSink.writeIfRunCurrent({threadId: projection.thread.id,runId,activeAttemptId: attempt.id,expectedStatus: "starting",events,});+ // A steering restart that cannot start still ends a run whose earlier turns counted.+ if (written.committed) {+ yield* turnAnalytics.runSettled({+ runId,+ status,+ completedAt: now,+ childrenRunning: false,+ });+ }},);const settleStartFailure = Effect.fn("ProviderTurnStartService.settleStartFailure")(diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 1cbd164b9e6..f76148d01bf 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -47,6 +47,7 @@ import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as ProjectionStore from "./ProjectionStore.ts";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";+import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";import * as PreviewAgentActivity from "../preview/PreviewAgentActivity.ts";import * as RunExecutionService from "./RunExecutionService.ts";@@ -1413,10 +1414,21 @@ it.effect("ingests new member threads of an owned child after the root turn termconst subagentNodeId = NodeId.make("node:run-execution-late-child:subagent");const childMessageIngested = yield* Deferred.make<void>();const order = yield* Ref.make<ReadonlyArray<string>>([]);- const origins = yield* Ref.make<ReadonlyArray<readonly [string, unknown]>>([]);+ const origins = yield* Ref.make<ReadonlyArray<readonly [string, unknown, unknown]>>([]);+ const requests = yield* Ref.make<ReadonlyArray<string>>([]);const layerTest = RunExecutionService.layer.pipe(Layer.provide(Layer.mergeAll(+ Layer.succeed(ProviderUsageAnalytics.ProviderTurnAnalytics, {+ runStarted: (input) =>+ Ref.update(requests, (current) => [...current, `started:${input.runId}`]),+ turnCompleted: () => Effect.void,+ runSettled: (input) =>+ Ref.update(requests, (current) => [+ ...current,+ `settled:${input.runId}:${input.status}:children-running=${input.childrenRunning}`,+ ]),+ }),McpAppModelContext.layerEmpty,PreviewAgentActivity.layer,Layer.mock(CheckpointService.CheckpointServiceV2)({ captureBaseline: () => Effect.void }),@@ -1443,7 +1455,11 @@ it.effect("ingests new member threads of an owned child after the root turn termconst eventType = input.event.type;yield* Ref.update(origins, (current) => [...current,- [eventType, input.analyticsContext?.origin] as const,+ [+ eventType,+ input.analyticsContext?.origin,+ input.analyticsContext?.segment,+ ] as const,]);if (input.event.type === "app_thread.created" &&@@ -1603,6 +1619,7 @@ it.effect("ingests new member threads of an owned child after the root turn termattempt: {id: attemptId,providerTurnId: rootProviderTurnId,+ reason: "initial",} as OrchestrationV2RunAttempt,attemptId,providerTurnOrdinal: 1,@@ -1635,7 +1652,7 @@ it.effect("ingests new member threads of an owned child after the root turn termassert.deepEqual(yield* Ref.get(order), ["root-finalized", "member-thread", "child-message"]);// The run's message started the root; the parent agent started the child's turn.const recorded = yield* Ref.get(origins);- assert.deepEqual(recorded[0], [+ assert.deepEqual(recorded[0]?.slice(0, 2), ["app_thread.created",{ createdBy: "user", creationSource: "web", scheduled: false, subagent: false },]);@@ -1644,8 +1661,14 @@ it.effect("ingests new member threads of an owned child after the root turn term["provider_turn.updated",{ createdBy: "agent", creationSource: "provider", scheduled: false, subagent: true },+ "native_child",],);+ // The child outlives the root, so the request summary says its later turns are missing.+ assert.deepEqual(yield* Ref.get(requests), [+ `started:${runId}`,+ `settled:${runId}:completed:children-running=true`,+ ]);}),);diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex 780ee76437f..6a52fac4479 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -46,6 +46,7 @@ import * as EventSink from "./EventSink.ts";import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";import * as ProviderEventIngestor from "./ProviderEventIngestor.ts";+import * as ProviderUsageAnalytics from "../telemetry/ProviderUsageAnalytics.ts";import type { ProjectionStoreV2Error } from "./ProjectionStore.ts";import {knownProviderFailureMessage,@@ -98,7 +99,7 @@ function isSettledSubagentStatus(status: OrchestrationV2Subagent["status"]): boo}/** A provider-native subagent's turns arrive on its parent's run, but the parent agent started them. */-const NATIVE_SUBAGENT_TURN_ORIGIN: ProviderEventIngestor.ProviderTurnOrigin = {+const NATIVE_SUBAGENT_TURN_ORIGIN: ProviderUsageAnalytics.ProviderTurnOrigin = {createdBy: "agent",creationSource: "provider",scheduled: false,@@ -615,6 +616,7 @@ export const layer: Layer.Layer<const previewAgentActivity = yield* PreviewAgentActivity.PreviewAgentActivity;const turnItemPositions = yield* TurnItemPositionStore.TurnItemPositionStoreV2;const finalizationObserver = yield* RunFinalizationService.RunFinalizationObserver;+ const turnAnalytics = yield* ProviderUsageAnalytics.ProviderTurnAnalytics;const writeFinalRunEvents = Effect.fn("RunExecutionService.writeFinalRunEvents")(function* (input: {@@ -871,13 +873,19 @@ export const layer: Layer.Layer<} else {yield* eventSink.writeWithEffects(finalization);}+ yield* turnAnalytics.runSettled({+ runId: input.run.id,+ status: input.terminal.status,+ completedAt,+ childrenRunning: hasOpenSubagentProjection && cascadedSubagentEvents.length === 0,+ });yield* input.refreshAfterTurn;},);return RunExecutionServiceV2.of({startRootRun: Effect.fn("RunExecutionService.startRootRun")(function* (input) {- const rootTurnOrigin: ProviderEventIngestor.ProviderTurnOrigin = {+ const rootTurnOrigin: ProviderUsageAnalytics.ProviderTurnOrigin = {createdBy: input.message.createdBy,creationSource: input.message.creationSource,scheduled: input.message.scheduledTaskId !== undefined,@@ -997,6 +1005,25 @@ export const layer: Layer.Layer<const latestTurnItemOrdinal = yield* Ref.make(input.providerTurnOrdinal * 100);const latestProviderThread = yield* Ref.make(input.providerThread);const latestRootProviderTurn = yield* Ref.make<OrchestrationV2ProviderTurn | null>(null);+ // Later root turns in one attempt are provider continuations, such as Codex goal turns.+ let firstRootProviderTurnId: ProviderTurnId | undefined;+ const analyticsContext = {+ runId: input.run.id,+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimePolicy.runtimeMode,+ interactionMode: input.runtimePolicy.interactionMode,+ origin: rootTurnOrigin,+ ...(input.run.restartContinuationOfRunId === undefined+ ? {}+ : { restartContinuation: true }),+ } satisfies ProviderUsageAnalytics.ProviderTurnAnalyticsContext;+ if (input.attempt.reason === "initial") {+ yield* turnAnalytics.runStarted({+ runId: input.run.id,+ driver: input.providerThread.driver,+ context: { ...analyticsContext, segment: "initial" },+ });+ }const routeIdentity: ProviderEventRouteIdentity = {threadId: input.run.threadId,runId: input.run.id,@@ -1396,17 +1423,27 @@ export const layer: Layer.Layer<const isRootProviderThreadUpdate =event.type === "provider_thread.updated" &&event.providerThread.id === input.providerThread.id;+ const nativeChildTurn =+ event.type === "provider_turn.updated" &&+ event.providerTurn.providerThreadId !== input.providerThread.id;+ if (event.type === "provider_turn.updated" && !nativeChildTurn) {+ firstRootProviderTurnId ??= event.providerTurn.id;+ }const storedEvents = yield* providerEventIngestor.ingestNormalized({- analyticsContext: {- modelSelection: input.modelSelection,- runtimeMode: input.runtimePolicy.runtimeMode,- interactionMode: input.runtimePolicy.interactionMode,- origin:- event.type === "provider_turn.updated" &&- event.providerTurn.providerThreadId !== input.providerThread.id- ? NATIVE_SUBAGENT_TURN_ORIGIN- : rootTurnOrigin,- },+ analyticsContext: nativeChildTurn+ ? {+ ...analyticsContext,+ origin: NATIVE_SUBAGENT_TURN_ORIGIN,+ segment: "native_child",+ }+ : {+ ...analyticsContext,+ segment:+ event.type === "provider_turn.updated" &&+ event.providerTurn.id !== firstRootProviderTurnId+ ? "continuation"+ : input.attempt.reason,+ },providerSessionId: input.providerSessionId,providerInstanceId: input.run.providerInstanceId,threadId: input.run.threadId,diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.tsindex 0c357deefea..3e9359e3dcc 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_compact_after_peer_turn/output.ts@@ -51,4 +51,25 @@ export function assertClaudeCompactAfterPeerTurnOutput(assert.equal(runs[2]?.status, "completed");assert.deepEqual(runs[2]?.replies, ["PEER_ACK"]);assert.deepEqual(runs[2]?.compactions, []);++ const usage = projection.runs.map(+ (run) =>+ projection.providerTurns.find((turn) => turn.runAttemptId === run.activeAttemptId)+ ?.turnTokenUsage,+ );+ assert.deepInclude(usage[0], {+ outputTokens: 7,+ otherUsage: { inputTokens: 1015, outputTokens: 12 },+ });+ // /compact reports zero tokens as a local command.+ assert.deepInclude(usage[1], {+ usageStatus: "complete",+ inputTokens: 0,+ outputTokens: 0,+ localCommand: true,+ });+ // The peer result's ledger is empty, so neither it nor the next result has a baseline.+ assert.deepInclude(usage[2], { usageStatus: "complete", outputTokens: 4 });+ assert.notProperty(usage[1], "otherUsage");+ assert.notProperty(usage[2], "otherUsage");}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.tsindex cf8fac0d3a1..c5c114d441d 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_idle_resume/output.ts@@ -32,4 +32,15 @@ export function assertClaudeIdleResumeOutput("idle resume first turn complete","idle resume second turn complete",]);+ // The resumed process's ledger starts at zero, so the first turn is not counted again.+ assert.deepEqual(+ projection.providerTurns.map((turn) => [+ turn.turnTokenUsage?.outputTokens,+ turn.turnTokenUsage?.otherUsage,+ ]),+ [+ [7, { inputTokens: 0, outputTokens: 0 }],+ [7, { inputTokens: 0, outputTokens: 0 }],+ ],+ );}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.tsindex 99b218f215f..6d4866078ed 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_nested_subagent_model/output.ts@@ -56,4 +56,16 @@ export function assertClaudeNestedSubagentModelOutput(const nestedChild = result.projections.get(nested.childThreadId);assert.isDefined(nestedChild);assert.equal(nestedChild.thread.modelSelection.model, SUBAGENT_MODEL);++ // The result counts only the root; the process ledger adds both subagents' work once.+ assert.lengthOf(projection.providerTurns, 1);+ assert.deepInclude(projection.providerTurns[0]?.turnTokenUsage, {+ usageStatus: "complete",+ hasSubagents: true,+ inputTokens: 74_167,+ outputTokens: 236,+ reasoningTokens: 30,+ models: ["claude-sonnet-4-6"],+ otherUsage: { inputTokens: 87_409, outputTokens: 335 },+ });}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.tsindex fe3167b22cb..a8cf34999da 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_result_is_error/output.ts@@ -40,6 +40,8 @@ export function assertClaudeResultIsErrorOutput((turn) => turn.status !== "completed" && turn.status !== "running",);assert.equal(failedTurn?.status, "failed");+ // The API error's "<synthetic>" frame is a CLI notice, not a model that did work.+ assert.notProperty(failedTurn?.turnTokenUsage, "models");const errorItem = projection.turnItems.find((item) => item.runId === failedRun?.id && item.type === "error",diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjsonnew file mode 100644index 00000000000..6b90c579a26--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/codex_transcript.ndjson@@ -0,0 +1,47 @@+{"type":"transcript_start","provider":"codex","protocol":"codex.app-server","version":"0.156.1","scenario":"codex_model_reroute","metadata":{"source":"record-codex-app-server-replay-fixture","fileName":"multi_turn.ndjson","description":"The multi_turn recording with a model/rerouted notification added by hand to the first turn. The second turn gets no new thread settings.","model":"gpt-6-luna"}}+{"type":"expect_outbound","label":"initialize","frame":{"id":1,"method":"initialize","params":{"capabilities":{"experimentalApi":true,"optOutNotificationMethods":["turn/diff/updated"],"extensions":{"io.modelcontextprotocol/ui":{"mimeTypes":["text/html;profile=mcp-app"]}}},"clientInfo":{"name":"T3 Code","title":"T3 Code","version":"0.0.44"}}}}+{"type":"emit_inbound","label":"initialize","frame":{"id":1,"result":{"userAgent":"t3code_desktop/0.156.1 (Debian 13.0.0; x86_64) unknown (t3code_desktop; 0.1.0)","codexHome":"/home/replay-user/.codex","platformFamily":"unix","platformOs":"linux"}}}+{"type":"expect_outbound","label":"initialized","frame":{"method":"initialized"}}+{"type":"expect_outbound","label":"thread/start","frame":{"id":2,"method":"thread/start","params":{"config":{"tools.update_plan.enabled":true,"mcp_optional_startup_grace_ms":10000},"cwd":"<workspace>","model":"gpt-6-luna"}}}+{"type":"emit_inbound","label":"configWarning","frame":{"method":"configWarning","params":{"summary":"Codex could not find bubblewrap on PATH. Install bubblewrap with your OS package manager. See the sandbox prerequisites: https://developers.openai.com/codex/concepts/sandboxing#prerequisites. Codex will use the bundled bubblewrap in the meantime.","details":null},"emittedAtMs":1790295480414}}+{"type":"emit_inbound","label":"remoteControl/status/changed","frame":{"method":"remoteControl/status/changed","params":{"status":"disabled","serverName":"replay-host","installationId":"00000000-0000-4000-8000-000000000000","environmentId":null},"emittedAtMs":1790295480414}}+{"type":"emit_inbound","label":"thread/start","frame":{"id":2,"result":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]},"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"],"instructionSources":["/home/replay-user/.codex/AGENTS.md","/home/replay-user/t3code/AGENTS.md"],"approvalPolicy":"on-request","approvalsReviewer":"user","sandbox":{"type":"workspaceWrite","writableRoots":[],"networkAccess":false,"excludeTmpdirEnvVar":false,"excludeSlashTmp":false},"activePermissionProfile":{"id":":workspace","extends":null},"reasoningEffort":null,"multiAgentMode":"explicitRequestOnly"}}}+{"type":"expect_outbound","label":"turn/start","frame":{"id":3,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Respond with exactly: first fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}}+{"type":"emit_inbound","label":"thread/started","frame":{"method":"thread/started","params":{"thread":{"id":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","environments":[{"environmentId":"local","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","runtimeWorkspaceRoots":["/home/replay-user/t3code/packages/effect-codex-app-server"]}],"extra":null,"sessionId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","forkedFromId":null,"parentThreadId":null,"preview":"","ephemeral":false,"section":null,"sectionEnteredAt":null,"projectId":null,"historyMode":"paginated","modelProvider":"openai","model":"gpt-6-luna","reasoningEffort":null,"createdAt":1790295480,"updatedAt":1790295480,"recencyAt":1790295480,"status":{"type":"idle"},"path":"/home/replay-user/.codex/sessions/2026/09/24/rollout-2026-09-24T17-18-00-01a0d5ed-187d-70c2-b4b6-b6881a68de09.jsonl","cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","cliVersion":"0.156.1","originator":"t3code_desktop","source":"vscode","canAcceptDirectInput":true,"threadSource":null,"agentNickname":null,"agentRole":null,"gitInfo":null,"name":null,"daybreakEnabled":null,"turns":[]}},"emittedAtMs":1790295480656}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295480656}}+{"type":"emit_inbound","label":"thread/settings/updated","frame":{"method":"thread/settings/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","threadSettings":{"disabledPluginIds":[],"cwd":"/home/replay-user/t3code/packages/effect-codex-app-server","approvalPolicy":"never","approvalsReviewer":"user","sandboxPolicy":{"type":"dangerFullAccess"},"activePermissionProfile":null,"model":"gpt-6-luna","modelProvider":"openai","serviceTier":null,"effort":null,"summary":"detailed","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna","reasoning_effort":null,"developer_instructions":null}},"multiAgentMode":"explicitRequestOnly","personality":null}},"emittedAtMs":1790295480666}}+{"type":"emit_inbound","label":"turn/start","frame":{"id":3,"result":{"turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295480718}}+{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295480,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295480718}}+{"type":"emit_inbound","label":"model/rerouted","frame":{"method":"model/rerouted","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","fromModel":"gpt-6-luna","toModel":"gpt-6-astra","reason":"highRiskCyberActivity"}}}+{"type":"emit_inbound","label":"account/updated","frame":{"method":"account/updated","params":{"authMode":"chatgpt","planType":"unknown"},"emittedAtMs":1790295481015}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"starting","error":null,"failureReason":null},"emittedAtMs":1790295481236}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"codex_apps","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295481609}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-22a8-7e91-9510-1578c7566bc0","clientId":null,"content":[{"type":"text","text":"Respond with exactly: first fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","startedAtMs":1790295483054},"emittedAtMs":1790295483054}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-22a8-7e91-9510-1578c7566bc0","clientId":null,"content":[{"type":"text","text":"Respond with exactly: first fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","completedAtMs":1790295483054},"emittedAtMs":1790295483061}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","startedAtMs":1790295485125},"emittedAtMs":1790295485125}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":"first"},"emittedAtMs":1790295485125}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" fixture"},"emittedAtMs":1790295485125}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" turn"},"emittedAtMs":1790295485125}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","itemId":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","delta":" complete"},"emittedAtMs":1790295485125}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","completedAtMs":1790295485125},"emittedAtMs":1790295485134}}+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-1957-7a22-8399-d0172af342fd","tokenUsage":{"total":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"last":{"totalTokens":21426,"inputTokens":21418,"cachedInputTokens":6912,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295485211}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295485220}}+{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-1957-7a22-8399-d0172af342fd","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbcd76887d0ba52ca8fee9da2e1","text":"first fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295480,"completedAt":1790295485,"durationMs":4550}},"emittedAtMs":1790295485220}}+{"type":"expect_outbound","label":"turn/start","frame":{"id":4,"method":"turn/start","params":{"approvalPolicy":"never","approvalsReviewer":"user","cwd":"<workspace>","input":[{"text":"Respond with exactly: second fixture turn complete","type":"text"}],"model":"gpt-6-luna","sandboxPolicy":{"type":"dangerFullAccess"},"summary":"detailed","threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","collaborationMode":{"mode":"default","settings":{"model":"gpt-6-luna"}}}}}+{"type":"emit_inbound","label":"mcpServer/startupStatus/updated","frame":{"method":"mcpServer/startupStatus/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","name":"xcodebuildmcp","status":"ready","error":null,"failureReason":null},"emittedAtMs":1790295485265}}+{"type":"emit_inbound","label":"turn/start","frame":{"id":4,"result":{"turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":null,"completedAt":null,"durationMs":null}}}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"active","activeFlags":[]}},"emittedAtMs":1790295485286}}+{"type":"emit_inbound","label":"turn/started","frame":{"method":"turn/started","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[],"itemsView":"notLoaded","status":"inProgress","error":null,"startedAt":1790295485,"completedAt":null,"durationMs":null}},"emittedAtMs":1790295485286}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295485409},"emittedAtMs":1790295485409}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"userMessage","id":"01a0d5ed-2bdf-7093-9e82-b961af1fe132","clientId":null,"content":[{"type":"text","text":"Respond with exactly: second fixture turn complete","text_elements":[]}]},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","completedAtMs":1790295485409},"emittedAtMs":1790295485413}}+{"type":"emit_inbound","label":"item/started","frame":{"method":"item/started","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","startedAtMs":1790295487332},"emittedAtMs":1790295487332}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":"second"},"emittedAtMs":1790295487332}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" fixture"},"emittedAtMs":1790295487332}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" turn"},"emittedAtMs":1790295487332}}+{"type":"emit_inbound","label":"item/agentMessage/delta","frame":{"method":"item/agentMessage/delta","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","itemId":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","delta":" complete"},"emittedAtMs":1790295487332}}+{"type":"emit_inbound","label":"item/completed","frame":{"method":"item/completed","params":{"item":{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"second fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null},"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","completedAtMs":1790295487382},"emittedAtMs":1790295487398}}+{"type":"emit_inbound","label":"thread/tokenUsage/updated","frame":{"method":"thread/tokenUsage/updated","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turnId":"01a0d5ed-2b29-7353-a6d5-7745731173b7","tokenUsage":{"total":{"totalTokens":47211,"inputTokens":47195,"cachedInputTokens":28160,"cacheWriteInputTokens":0,"outputTokens":16,"reasoningOutputTokens":0},"last":{"totalTokens":25785,"inputTokens":25777,"cachedInputTokens":21248,"cacheWriteInputTokens":0,"outputTokens":8,"reasoningOutputTokens":0},"modelContextWindow":258400}},"emittedAtMs":1790295487407}}+{"type":"emit_inbound","label":"thread/status/changed","frame":{"method":"thread/status/changed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","status":{"type":"idle"}},"emittedAtMs":1790295487412}}+{"type":"emit_inbound","label":"turn/completed","frame":{"method":"turn/completed","params":{"threadId":"01a0d5ed-187d-70c2-b4b6-b6881a68de09","turn":{"id":"01a0d5ed-2b29-7353-a6d5-7745731173b7","items":[{"type":"agentMessage","id":"msg_06900ecb02a780a6016ab5bdbf08a087d08c1dafcd3f15697a","text":"second fixture turn complete","phase":"final_answer","memoryCitation":null,"delivery":null,"questions":null}],"itemsView":"summary","status":"completed","error":null,"startedAt":1790295485,"completedAt":1790295487,"durationMs":2138}},"emittedAtMs":1790295487412}}+{"type":"runtime_exit","status":"success"}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.tsnew file mode 100644index 00000000000..cca633fd5d7--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/codex_model_reroute/output.ts@@ -0,0 +1,21 @@+import { assert } from "@effect/vitest";+import type { ProviderReplayTranscript } from "@t3tools/contracts";++import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";+import { assertBaseProjection, projectionFor } from "../shared.ts";++export function assertCodexModelRerouteOutput(+ result: OrchestratorV2ScenarioResult,+ transcript: ProviderReplayTranscript,+) {+ assertBaseProjection({+ result,+ transcript,+ runCount: 2,+ runStatuses: ["completed", "completed"],+ });+ const [first, second] = projectionFor(result, transcript.scenario).providerTurns;+ // The reroute names the first turn only; without new settings the second turn's model is unknown.+ assert.deepEqual(first?.turnTokenUsage?.models, ["gpt-6-astra"]);+ assert.notProperty(second?.turnTokenUsage, "models");+}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts b/apps/server/src/orchestration-v2/testkit/fixtures/index.tsindex 1782f6f072a..f242c8e0a46 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/index.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/index.ts@@ -106,6 +106,8 @@ import { openCode2SimpleInput } from "./opencode2_simple/input.ts";import { openCode2SkillInput } from "./opencode2_skill/input.ts";import { assertOpenCode2SkillOutput } from "./opencode2_skill/output.ts";import { assertOpenCode2SimpleOutput } from "./opencode2_simple/output.ts";+import { assertOpenCode2MissingStepUsageOutput } from "./opencode2_missing_step_usage/output.ts";+import { assertCodexModelRerouteOutput } from "./codex_model_reroute/output.ts";import { openCode2ToolCallInput } from "./opencode2_tool_call/input.ts";import { assertOpenCode2ToolCallOutput } from "./opencode2_tool_call/output.ts";import { assertOpenCodeSubagentOutput } from "./opencode_subagent/output.ts";@@ -984,6 +986,21 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu},],},+ {+ name: "opencode2_missing_step_usage",+ buildInput: openCode2SimpleInput,+ providers: [+ {+ driver: ProviderDriverKind.make("opencode"),+ transcriptFile: new URL(+ "./opencode2_missing_step_usage/opencode_transcript.ndjson",+ import.meta.url,+ ),+ modelSelection: OPENCODE2_MODEL_SELECTION,+ assertOutput: assertOpenCode2MissingStepUsageOutput,+ },+ ],+ },{name: "opencode2_tool_call",buildInput: openCode2ToolCallInput,@@ -1221,6 +1238,18 @@ export const ORCHESTRATOR_REPLAY_FIXTURES: ReadonlyArray<OrchestratorReplayFixtu},],},+ {+ name: "codex_model_reroute",+ buildInput: multiTurnInput,+ providers: [+ {+ driver: ProviderDriverKind.make("codex"),+ transcriptFile: new URL("./codex_model_reroute/codex_transcript.ndjson", import.meta.url),+ modelSelection: CODEX_MODEL_SELECTION,+ assertOutput: assertCodexModelRerouteOutput,+ },+ ],+ },{name: "multi_turn",buildInput: multiTurnInput,diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/opencode_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/opencode_transcript.ndjsonnew file mode 100644index 00000000000..a15b2adbc1d--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/opencode_transcript.ndjson@@ -0,0 +1,55 @@+{"type": "transcript_start", "provider": "opencode", "protocol": "opencode2-http.sse", "version": "2.0.18", "scenario": "opencode2_missing_step_usage", "metadata": {"source": "opencode2-spike/recordings/simple.ndjson", "capturedAt": "2026-09-28", "nativeSessionId": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "description": "The opencode2_simple recording with a second step added by hand that fails without a token report, so the turn has one measured step and one missing report."}}+{"type": "expect_outbound", "label": "event.subscribe", "frame": {"type": "event.subscribe"}}+{"type": "expect_outbound", "label": "model.list", "frame": {"type": "model.list", "input": {"location[directory]": "<any>"}}}+{"type": "emit_inbound", "label": "model.list.response", "frame": {"type": "sdk.response", "operation": "model.list", "data": {"location": {"directory": "<work>"}, "data": [{"id": "space-bunny-free", "modelID": "space-bunny-free", "providerID": "opencode", "name": "Space Bunny Free", "compatibility": {"reasoningField": "reasoning_content"}, "package": "@opencode/ai/providers/openai-compatible", "settings": {"apiKey": "public", "baseURL": "https://opencode.ai/zen/v1", "provider": "opencode"}, "capabilities": {"tools": true, "input": ["text", "image", "video"], "output": ["text"]}, "variants": [{"id": "low", "settings": {"reasoningEffort": "low"}}, {"id": "medium", "settings": {"reasoningEffort": "medium"}}, {"id": "high", "settings": {"reasoningEffort": "high"}}, {"id": "xhigh", "settings": {"reasoningEffort": "xhigh"}}, {"id": "max", "settings": {"reasoningEffort": "max"}}], "time": {"released": 1790121600000}, "cost": [{"input": 0, "output": 0, "cache": {"read": 0, "write": 0}}], "status": "active", "enabled": true, "limit": {"context": 1048576, "input": 524288, "output": 524288}}, {"id": "big-pickle", "modelID": "big-pickle", "providerID": "opencode", "family": "big-pickle", "name": "Big Pickle", "compatibility": {"reasoningField": "reasoning_content"}, "package": "@opencode/ai/providers/openai-compatible", "settings": {"apiKey": "public", "baseURL": "https://opencode.ai/zen/v1", "provider": "opencode"}, "capabilities": {"tools": true, "input": ["text"], "output": ["text"]}, "variants": [], "time": {"released": 1760659200000}, "cost": [{"input": 0, "output": 0, "cache": {"read": 0, "write": 0}}], "status": "active", "enabled": true, "limit": {"context": 200000, "input": 160000, "output": 32000}}]}}}+{"type": "emit_inbound", "label": "server.connected", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73205b001QM7spc7rTwRevR", "type": "server.connected", "data": {}}}}+{"type": "expect_outbound", "label": "session.create", "frame": {"type": "session.create", "input": {"location": "<any>", "model": {"providerID": "opencode", "id": "space-bunny-free", "variant": "high"}, "permissions": "<any>"}}}+{"type": "emit_inbound", "label": "session.create.response", "frame": {"type": "sdk.response", "operation": "session.create", "data": {"data": {"id": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "projectID": "global", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "cost": 0, "tokens": {"input": 0, "output": 0, "reasoning": 0, "cache": {"read": 0, "write": 0}}, "time": {"created": 1790656585840, "updated": 1790656585840}, "title": "spike simple", "location": {"directory": "<work>"}}}}}+{"type": "emit_inbound", "label": "session.created", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732070001MeC12AQ1Ds6a0a", "created": 1790656585840, "type": "session.created", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "slug": "sunny-pixel", "version": "2.0.18", "projectID": "global", "location": {"directory": "<work>"}, "subpath": "", "title": "spike simple", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 0, "version": 1}}}}+{"type": "emit_inbound", "label": "project.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732078001oO5ghtqXkMav9d", "created": 1790656585848, "type": "project.updated", "data": {"id": "global", "canonical": "<work>", "vcs": "git", "time": {"created": 1790656063718, "updated": 1790656063718, "active": 1790656585847}, "sandboxes": []}}}}+{"type": "expect_outbound", "label": "session.instructions.entry.put", "frame": {"type": "session.instructions.entry.put", "input": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "key": "t3-code", "value": "<any>"}}}+{"type": "emit_inbound", "label": "session.instructions.entry.put.response", "frame": {"type": "sdk.response", "operation": "session.instructions.entry.put", "data": null}}+{"type": "expect_outbound", "label": "session.prompt", "frame": {"type": "session.prompt", "input": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "text": "<any>"}}}+{"type": "emit_inbound", "label": "session.prompt.response", "frame": {"type": "sdk.response", "operation": "session.prompt", "data": {"data": {"id": "msg_0eb732081001RntUJfRtTXOAjd", "sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "time": {"created": 1790656585859}, "type": "user", "payload": {"text": "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence."}, "delivery": "steer"}}}}+{"type": "emit_inbound", "label": "session.inbox.enqueued", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732083001UPoh8n1ciLGG4J", "created": 1790656585859, "type": "session.inbox.enqueued", "location": {"directory": "<work>"}, "data": {"inboxID": "msg_0eb732081001RntUJfRtTXOAjd", "sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "item": {"type": "user", "payload": {"text": "Think carefully step by step about whether 391 is prime, showing your reasoning, then answer in one short sentence."}, "delivery": "steer"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 1, "version": 1}}}}+{"type": "emit_inbound", "label": "session.execution.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732089001TRfMB4IJIUtJuG", "created": 1790656585865, "type": "session.execution.started", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 2, "version": 1}}}}+{"type": "emit_inbound", "label": "session.instructions.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732098001v3n3L11aMx0r6G", "created": 1790656585880, "metadata": {"instructions": {"initial": true}}, "type": "session.instructions.updated", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "delta": {"core/environment": "27a84baf7fee37fde05d49a6aaf0f184019068a15362a38f5d1ec17ac7e8f2b7", "core/date": "bf08b8486572ab3eef677a3c9ee12468e411ae41a8f4d2fb6cf02a6ca73f1986", "core/codemode": "616a7ad8b8e40e8a71eab238dfbbe9eaf0f4a9e6fdad853226d075bfe602e1e6", "core/skill-guidance": "0d001919496102654717308c72635523bf7c3cd99c81e058cc79f2947104f9a5"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 3, "version": 2}}}}+{"type": "emit_inbound", "label": "session.inbox.delivered", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73209d001wgPxWUQRwkXvBn", "created": 1790656585885, "type": "session.inbox.delivered", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "inboxID": "msg_0eb732081001RntUJfRtTXOAjd"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 4, "version": 1}}}}+{"type": "emit_inbound", "label": "session.step.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7326930015SMmHkSszcae37", "created": 1790656587411, "type": "session.step.started", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "agent": "build", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "started": 1790656585925}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 5, "version": 1}}}}+{"type": "emit_inbound", "label": "session.reasoning.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732699001FC5efnDXzkrBV3", "created": 1790656587417, "type": "session.reasoning.started", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "state": {"reasoningField": "reasoning_content"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 6, "version": 1}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732702001XkfhcVQWas7guy", "created": 1790656587522, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "Check divisibility up to sqrt("}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73277b001U6tDaZPzh5G8Ub", "created": 1790656587643, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "391) \u2248 19.77."}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.3", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732805001zRua1yhKskE6du", "created": 1790656587781, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " Primes: 2,3,5,7,"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.4", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73286e001XXnCtQeutby7Jh", "created": 1790656587886, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "11,13,17,19.\n\n391 is"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.5", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7328e8001vpkz0eDsHflXmv", "created": 1790656588008, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " odd, not div by 2"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.6", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732955001YnC9O9FAgIagoL", "created": 1790656588118, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": ". 3+9+"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.7", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732aaa001b129VgQ4aT7avM", "created": 1790656588458, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "1=13, not div by 3. Not by 5. 7: 7\u00d755=385, remainder 6. 11: 11\u00d7"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.8", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732b29001AMm839z4dDYXHE", "created": 1790656588585, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "35=385, remainder 6. 13: "}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.9", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732ba0001Ivdi55eX7RWaIN", "created": 1790656588704, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "13\u00d730=390, remainder 1. "}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.10", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732c1f001l5voAVE8zZty1G", "created": 1790656588832, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "17: 17\u00d723=391!"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.11", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732c95001xtU1t86iQ32FcX", "created": 1790656588949, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " 17\u00d723 = 391. Yes"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.12", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732d3b001F922FhdbWHFFh9", "created": 1790656589115, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": ": 17\u00d723 = 340 +"}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.13", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732db1001Llbce6UsLrsMtr", "created": 1790656589234, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " 51 = 391. So "}}}}+{"type": "emit_inbound", "label": "session.reasoning.delta.14", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732de6001fDagd9vuCaT77g", "created": 1790656589286, "type": "session.reasoning.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "391 is composite."}}}}+{"type": "emit_inbound", "label": "session.text.started", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732de7001zYvkQcsI5WOzgG", "created": 1790656589287, "type": "session.text.started", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 7, "version": 1}}}}+{"type": "emit_inbound", "label": "session.text.delta", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732e50001GdabW0WKYVl32T", "created": 1790656589392, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "\u221a391 \u2248 19.8,"}}}}+{"type": "emit_inbound", "label": "session.text.delta.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732ed2001IBPZhAC1kx4d1v", "created": 1790656589522, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " so I need to test primes "}}}}+{"type": "emit_inbound", "label": "session.text.delta.3", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732f38001E0KjfQvDXHZ7h1", "created": 1790656589624, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "2, 3, 5, 7, "}}}}+{"type": "emit_inbound", "label": "session.text.delta.4", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb732fad001JzcESOkjYwU5ik", "created": 1790656589741, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "11, 13, 17, 19: it's"}}}}+{"type": "emit_inbound", "label": "session.text.delta.5", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73301c001UBnr5x154Roys2", "created": 1790656589852, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " odd, digits sum to 13, doesn't"}}}}+{"type": "emit_inbound", "label": "session.text.delta.6", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73308e001sYejhe1LAMtvcI", "created": 1790656589966, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " end in 0/5, and 7\u00d7"}}}}+{"type": "emit_inbound", "label": "session.text.delta.7", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331030012XzmUwjcWGmPUe", "created": 1790656590084, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "55=385, 11"}}}}+{"type": "emit_inbound", "label": "session.text.delta.8", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331700018ST8kVeG36WRUV", "created": 1790656590192, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "\u00d735=385, 13\u00d730=390 leave remain"}}}}+{"type": "emit_inbound", "label": "session.text.delta.9", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7331df001Nm2KLtcVET4KlU", "created": 1790656590304, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": "ders \u2014 but 17\u00d723 = 391"}}}}+{"type": "emit_inbound", "label": "session.text.delta.10", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733251001HkPIEuVZxWlLIU", "created": 1790656590417, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " exactly, so the search"}}}}+{"type": "emit_inbound", "label": "session.text.delta.11", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7332bd001f1FZxccg5aNmhq", "created": 1790656590525, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " stops there.\n\n391 is not prime: it's the"}}}}+{"type": "emit_inbound", "label": "session.text.delta.12", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73333d001mIrQbkY6rbRMi3", "created": 1790656590654, "type": "session.text.delta", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "delta": " product 17 \u00d7 23."}}}}+{"type": "emit_inbound", "label": "session.reasoning.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333720010sLSSNU5xRXUwa", "created": 1790656590707, "type": "session.reasoning.ended", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "text": "Check divisibility up to sqrt(391) \u2248 19.77. Primes: 2,3,5,7,11,13,17,19.\n\n391 is odd, not div by 2. 3+9+1=13, not div by 3. Not by 5. 7: 7\u00d755=385, remainder 6. 11: 11\u00d735=385, remainder 6. 13: 13\u00d730=390, remainder 1. 17: 17\u00d723=391! 17\u00d723 = 391. Yes: 17\u00d723 = 340 + 51 = 391. So 391 is composite.", "state": {"reasoningField": "reasoning_content"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 8, "version": 1}}}}+{"type": "emit_inbound", "label": "session.text.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733378001jAPLwPeycQ4M5d", "created": 1790656590712, "type": "session.text.ended", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "ordinal": 0, "text": "\u221a391 \u2248 19.8, so I need to test primes 2, 3, 5, 7, 11, 13, 17, 19: it's odd, digits sum to 13, doesn't end in 0/5, and 7\u00d755=385, 11\u00d735=385, 13\u00d730=390 leave remainders \u2014 but 17\u00d723 = 391 exactly, so the search stops there.\n\n391 is not prime: it's the product 17 \u00d7 23."}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 9, "version": 1}}}}+{"type": "emit_inbound", "label": "session.step.streamed", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb73337f001Y6nJkjv1tXkqGt", "created": 1790656590719, "type": "session.step.streamed", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 10, "version": 1}}}}+{"type": "emit_inbound", "label": "session.step.ended", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733390001vg5GRCuNzMFbCA", "created": 1790656590736, "type": "session.step.ended", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7320a9001vve3OV5uNi2HRT", "finish": "stop", "rawFinish": "stop", "cost": 0, "tokens": {"input": 8701, "output": 113, "reasoning": 147, "cache": {"read": 489, "write": 0}}, "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "files": []}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 11, "version": 1}}}}+{"type": "emit_inbound", "label": "session.usage.updated", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733396001Ke5QhqiR5CdvP6", "created": 1790656590742, "type": "session.usage.updated", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "cost": 0, "tokens": {"input": 8701, "output": 113, "reasoning": 147, "cache": {"read": 489, "write": 0}}}}}}+{"type": "emit_inbound", "label": "session.step.started.2", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333a1001missingStepStart", "created": 1790656590750, "type": "session.step.started", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "agent": "build", "model": {"id": "space-bunny-free", "providerID": "opencode", "variant": "high"}, "assistantMessageID": "msg_0eb7333a0001missingStepUsage", "snapshot": "99482b54df6361365fa0ed7363ccf07edaa7fc93", "started": 1790656590750}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 12, "version": 1}}}}+{"type": "emit_inbound", "label": "session.step.failed", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb7333a2001missingStepFailed", "created": 1790656590760, "type": "session.step.failed", "location": {"directory": "<work>"}, "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "assistantMessageID": "msg_0eb7333a0001missingStepUsage", "error": {"type": "provider_error", "message": "Stream closed before usage was reported"}}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 13, "version": 1}}}}+{"type": "emit_inbound", "label": "session.execution.succeeded", "frame": {"type": "sdk.event", "event": {"id": "evt_0eb733399001NhwTrB32UU6d6H", "created": 1790656590745, "type": "session.execution.succeeded", "data": {"sessionID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk"}, "durable": {"aggregateID": "ses_f148cdfa1ffeIFwbC0FCx0fKpk", "seq": 14, "version": 1}}}}+{"type": "runtime_exit", "status": "success"}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.tsnew file mode 100644index 00000000000..68474abb954--- /dev/null+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_missing_step_usage/output.ts@@ -0,0 +1,22 @@+import { assert } from "@effect/vitest";+import type { ProviderReplayTranscript } from "@t3tools/contracts";++import type { OrchestratorV2ScenarioResult } from "../../OrchestratorScenario.ts";+import { assertBaseProjection, projectionFor } from "../shared.ts";++export function assertOpenCode2MissingStepUsageOutput(+ result: OrchestratorV2ScenarioResult,+ transcript: ProviderReplayTranscript,+) {+ assertBaseProjection({ result, transcript, runCount: 1, runStatuses: ["completed"] });+ const [providerTurn] = projectionFor(result, transcript.scenario).providerTurns;+ assert.equal(providerTurn?.status, "completed");+ // The measured step survives; the step without a report keeps the turn total partial.+ assert.deepInclude(providerTurn?.turnTokenUsage, {+ usageStatus: "partial",+ inputTokens: 8701 + 489,+ outputTokens: 113 + 147,+ reasoningTokens: 147,+ models: ["opencode/space-bunny-free"],+ });+}diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.tsindex 1626a079004..b56ac6c810f 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/opencode2_simple/output.ts@@ -41,6 +41,7 @@ export function assertOpenCode2SimpleOutput(cachedInputTokens: 489,outputTokens: 113 + 147,reasoningTokens: 147,+ models: ["opencode/space-bunny-free"],});assert.deepInclude(providerTurn?.tokenUsage, {usedTokens: 8701 + 489 + 113,diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.tsindex f87dd629760..d9f6d3e66c8 100644--- a/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts+++ b/apps/server/src/orchestration-v2/testkit/fixtures/subagent_v2/codex_output.ts@@ -83,4 +83,14 @@ export function assertSubagentV2Output("child thread must contain the post-root subagent response",);assert.equal(childProjection.providerTurns[0]?.status, "completed");++ // Codex reports each agent's counts on its own turn. Only the root's model was reported.+ assert.deepInclude(projection.providerTurns[0]?.turnTokenUsage, {+ usageStatus: "complete",+ outputTokens: 69,+ models: ["gpt-6-luna"],+ });+ const childUsage = childProjection.providerTurns[0]?.turnTokenUsage;+ assert.deepInclude(childUsage, { usageStatus: "complete", outputTokens: 6 });+ assert.notProperty(childUsage, "models");}diff --git a/apps/server/src/provider/ClaudeTurnTokenUsage.ts b/apps/server/src/provider/ClaudeTurnTokenUsage.tsindex 79eaaa60a11..2fa6a11bac1 100644--- a/apps/server/src/provider/ClaudeTurnTokenUsage.ts+++ b/apps/server/src/provider/ClaudeTurnTokenUsage.ts@@ -49,12 +49,96 @@ function withEarlierSegmentUsage(return total;}+/** Per-model totals from the SDK's `modelUsage`, which grows for the life of one CLI process. */+export type ClaudeModelLedger = ReadonlyMap<+ string,+ { readonly input: number; readonly output: number }+>;++export interface ClaudeLedgerUsage {+ readonly inputTokens: number;+ readonly outputTokens: number;+}++/** Unknown when absent or empty: a process that did model work never reports an empty ledger. */+export function claudeModelLedger(modelUsage: unknown): ClaudeModelLedger | undefined {+ if (typeof modelUsage !== "object" || modelUsage === null) return undefined;+ if (Object.keys(modelUsage).length === 0) return undefined;+ const ledger = new Map<string, { readonly input: number; readonly output: number }>();+ for (const [model, entry] of Object.entries(modelUsage as Record<string, unknown>)) {+ const fields = (entry ?? {}) as Record<string, unknown>;+ const input = finiteNonNegativeInteger(fields.inputTokens);+ const output = finiteNonNegativeInteger(fields.outputTokens);+ if (input === undefined || output === undefined) return undefined;+ const cacheRead = finiteNonNegativeInteger(fields.cacheReadInputTokens) ?? 0;+ const cacheWrite = finiteNonNegativeInteger(fields.cacheCreationInputTokens) ?? 0;+ ledger.set(model, { input: input + cacheRead + cacheWrite, output });+ }+ return ledger;+}++/** Ledger growth since `previous`. Unknown without a baseline or when a counter goes backwards. */+export function claudeLedgerDelta(+ previous: ClaudeModelLedger | undefined,+ current: ClaudeModelLedger | undefined,+): ClaudeLedgerUsage | undefined {+ if (previous === undefined || current === undefined) return undefined;+ let inputTokens = 0;+ let outputTokens = 0;+ for (const [model, before] of previous) {+ const after = current.get(model);+ if (after === undefined || after.input < before.input || after.output < before.output) {+ return undefined;+ }+ }+ for (const [model, after] of current) {+ const before = previous.get(model);+ inputTokens += after.input - (before?.input ?? 0);+ outputTokens += after.output - (before?.output ?? 0);+ }+ return { inputTokens, outputTokens };+}++export function addClaudeLedgerUsage(+ left: ClaudeLedgerUsage | undefined,+ right: ClaudeLedgerUsage | undefined,+): ClaudeLedgerUsage | undefined {+ return left === undefined || right === undefined+ ? undefined+ : {+ inputTokens: left.inputTokens + right.inputTokens,+ outputTokens: left.outputTokens + right.outputTokens,+ };+}++export interface ClaudeTurnObservations {+ // Models on the turn's root assistant messages.+ readonly rootModels?: ReadonlySet<string>;+ // Ledger growth across every result this turn consumed, including steered segments.+ readonly ledger?: ClaudeLedgerUsage | undefined;+}+export function normalizeClaudeTurnTokenUsage(- result: { readonly subtype: SDKResultMessage["subtype"]; readonly usage?: unknown } | undefined,+ result:+ | {+ readonly subtype: SDKResultMessage["subtype"];+ readonly usage?: unknown;+ readonly local_command?: unknown;+ }+ | undefined,hasSubagents: boolean,terminalStatus: RuntimeTurnState,earlierSegmentUsage: ReadonlyArray<unknown> = [],+ observed: ClaudeTurnObservations = {},): TurnTokenUsage {+ const observedFields = {+ ...(observed.rootModels !== undefined && observed.rootModels.size > 0+ ? { models: [...observed.rootModels] }+ : {}),+ ...(typeof result?.local_command === "string" && result.local_command.length > 0+ ? { localCommand: true }+ : {}),+ };const finalUsage = result?.usage as Record<string, unknown> | undefined;const usage = withEarlierSegmentUsage(finalUsage ?? {}, earlierSegmentUsage);const uncachedInputTokens = finiteNonNegativeInteger(usage.input_tokens);@@ -89,10 +173,25 @@ export function normalizeClaudeTurnTokenUsage(usageStatus: "unavailable",usageScope: "main_agent",hasSubagents,+ ...observedFields,};}+ // The result omits subagent and compaction work that the process-wide ledger records.+ const otherUsage =+ observed.ledger !== undefined &&+ inputTokens !== undefined &&+ rawOutputTokens !== undefined &&+ observed.ledger.inputTokens >= inputTokens &&+ observed.ledger.outputTokens >= rawOutputTokens+ ? {+ inputTokens: observed.ledger.inputTokens - inputTokens,+ outputTokens: observed.ledger.outputTokens - rawOutputTokens,+ }+ : undefined;const commonUsage = {+ ...observedFields,+ ...(otherUsage === undefined ? {} : { otherUsage }),usageScope: "main_agent",...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),...(cacheCreationTokens !== undefined ? { cacheCreationTokens } : {}),diff --git a/apps/server/src/provider/CodexTurnTokenUsage.ts b/apps/server/src/provider/CodexTurnTokenUsage.tsindex 7b0f20a123f..7b2524464b0 100644--- a/apps/server/src/provider/CodexTurnTokenUsage.ts+++ b/apps/server/src/provider/CodexTurnTokenUsage.ts@@ -133,27 +133,23 @@ export function accumulateCodexTurnTokenUsage(}}+/** `model` is the thread model Codex last reported, which a reroute replaces. */export function completeCodexTurnTokenUsage(state: CodexTurnTokenUsageState,turnId: string,completed: boolean,+ model?: string,): TurnTokenUsage {const usage = state.byTurnId.get(turnId);state.byTurnId.delete(turnId);if (state.activeTurnId === turnId) state.activeTurnId = undefined;- if (!usage) {+ const models = model === undefined ? {} : { models: [model] };+ if (!usage?.observed) {return {usageStatus: "unavailable",usageScope: "main_agent",- hasSubagents: false,- };- }-- if (!usage.observed) {- return {- usageStatus: "unavailable",- usageScope: "main_agent",- hasSubagents: usage.hasSubagents,+ hasSubagents: usage?.hasSubagents ?? false,+ ...models,};}@@ -169,5 +165,6 @@ export function completeCodexTurnTokenUsage(outputTokens: usage.outputTokens,reasoningTokens: Math.min(usage.outputTokens, usage.reasoningTokens),hasSubagents: usage.hasSubagents,+ ...models,};}diff --git a/apps/server/src/provider/TurnTokenUsage.test.ts b/apps/server/src/provider/TurnTokenUsage.test.tsindex 06802143e73..fb14511211e 100644--- a/apps/server/src/provider/TurnTokenUsage.test.ts+++ b/apps/server/src/provider/TurnTokenUsage.test.ts@@ -1,5 +1,9 @@import { describe, expect, it } from "vite-plus/test";-import { normalizeClaudeTurnTokenUsage } from "./ClaudeTurnTokenUsage.ts";+import {+ claudeLedgerDelta,+ claudeModelLedger,+ normalizeClaudeTurnTokenUsage,+} from "./ClaudeTurnTokenUsage.ts";import {accumulateCodexTurnTokenUsage,completeCodexTurnTokenUsage,@@ -209,6 +213,15 @@ describe("billable native turn usage", () => {},);+ it("measures Claude ledger growth only from a known, nondecreasing baseline", () => {+ const ledger = (output: number) =>+ claudeModelLedger({ "claude-sonnet-4-6": { inputTokens: 100, outputTokens: output } });+ expect(claudeLedgerDelta(ledger(10), ledger(25))).toEqual({ inputTokens: 0, outputTokens: 15 });+ expect(claudeLedgerDelta(ledger(25), ledger(10))).toBeUndefined();+ expect(claudeLedgerDelta(undefined, ledger(10))).toBeUndefined();+ expect(claudeModelLedger({})).toBeUndefined();+ });+it("adds Claude steering segments to the final measured result once", () => {expect(normalizeClaudeTurnTokenUsage(diff --git a/apps/server/src/server.ts b/apps/server/src/server.tsindex d0d51a0b241..9d7dc2f27b1 100644--- a/apps/server/src/server.ts+++ b/apps/server/src/server.ts@@ -47,7 +47,7 @@ import * as PullRequestReviewGuideService from "./pullRequest/PullRequestReviewGimport * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";import * as AnalyticsService from "./telemetry/AnalyticsService.ts";import * as DelegatedTaskAnalytics from "./telemetry/DelegatedTaskAnalytics.ts";-import * as ProviderEventIngestor from "./orchestration-v2/ProviderEventIngestor.ts";+import * as ProviderUsageAnalytics from "./telemetry/ProviderUsageAnalytics.ts";import * as ModelManifest from "./provider/ModelManifest.ts";import * as ResetCreditCoordinator from "./provider/resetCreditCoordinator.ts";import * as EventNdjsonLogger from "./provider/EventNdjsonLogger.ts";@@ -558,7 +558,7 @@ const layerScheduledTaskWebhookOrigin = Layer.effect(const layerOrchestrationV2Runtime = RuntimeLayer.layerProduction.pipe(Layer.provide(layerScheduledTaskWebhookOrigin),- Layer.provide(ProviderEventIngestor.layerAnalytics),+ Layer.provide(ProviderUsageAnalytics.layer),Layer.provide(layerCheckpointStore),Layer.provide(layerGitWorkflow),Layer.provide(diff --git a/apps/server/src/telemetry/ProviderDimensions.ts b/apps/server/src/telemetry/ProviderDimensions.tsindex 4e0447a1e2c..f81a22e844a 100644--- a/apps/server/src/telemetry/ProviderDimensions.ts+++ b/apps/server/src/telemetry/ProviderDimensions.ts@@ -4,6 +4,8 @@ import type {ServerProvider,} from "@t3tools/contracts";+import { BUNDLED_MODEL_MANIFEST } from "../provider/ModelManifest.ts";+/*** Drivers whose model catalogs are published by the vendor. Other drivers* (OpenCode, Pi, ACP agents) list models from the user's own configuration,@@ -39,6 +41,44 @@ export function providerDimensions(: { provider: provider.driver };}+const DATED_SNAPSHOT = /-\d{8}$/u;++// The bundled manifest is reviewed in this repo. Codex lists whatever its configured+// model provider serves, so only the manifest vouches for Codex, Claude, and Antigravity.+const MANIFEST_LABELS: ReadonlyMap<string, string> = new Map(+ Object.values(BUNDLED_MODEL_MANIFEST.providers ?? {}).flatMap((catalog) =>+ catalog.models.flatMap((model) =>+ [model.slug, ...(model.aliases ?? [])].map((name) => [name, model.slug] as const),+ ),+ ),+);+const REGISTRY_LABEL_DRIVERS: ReadonlySet<string> = new Set(["cursor", "grok"]);++/**+ * The vendor catalog slug that a native or routed model id names, such as+ * `anthropic/claude-opus-5-5` or a dated snapshot. Models outside the bundled+ * manifest and the Cursor and Grok catalogs, including user-added ones, return undefined.+ */+export function catalogModelLabel(+ providers: ReadonlyArray<ServerProvider>,+ model: string,+): string | undefined {+ const leaf = model.slice(model.lastIndexOf("/") + 1);+ const candidates = [model, leaf, leaf.replace(DATED_SNAPSHOT, "")];+ for (const candidate of candidates) {+ const label = MANIFEST_LABELS.get(candidate);+ if (label !== undefined) return label;+ }+ for (const provider of providers) {+ if (!REGISTRY_LABEL_DRIVERS.has(provider.driver)) continue;+ const match = provider.models.find(+ (entry) => !entry.isCustom && candidates.includes(entry.slug),+ );+ if (match !== undefined) return match.slug;+ }+ return undefined;+}+/** The thread fields agent analytics reads. Ids are used for lookups, never reported. */export type AgentThread = Pick<OrchestrationV2ThreadShell,diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.test.tsnew file mode 100644index 00000000000..4e277af4d11--- /dev/null+++ b/apps/server/src/telemetry/ProviderUsageAnalytics.test.ts@@ -0,0 +1,323 @@+import {+ NodeId,+ ProviderInstanceId,+ ProviderThreadId,+ ProviderTurnId,+ RunId,+ type OrchestrationV2ProviderTurn,+ type ServerProvider,+ type TurnTokenUsage,+} from "@t3tools/contracts";+import { describe, expect, it } from "@effect/vitest";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import * as ProviderRegistry from "../provider/ProviderRegistry.ts";+import * as AnalyticsService from "./AnalyticsService.ts";+import { catalogModelLabel } from "./ProviderDimensions.ts";+import {+ ProviderTurnAnalytics,+ RequestUsageLedger,+ layer,+ providerTurnProperties,+ type ProviderTurnAnalyticsContext,+ type ProviderTurnSegment,+} from "./ProviderUsageAnalytics.ts";++const providers = [+ // Codex lists whatever its configured model provider serves, including private deployments.+ { driver: "codex", models: [{ slug: "gpt-6-sol" }, { slug: "acme-azure-deployment" }] },+ { driver: "claudeAgent", models: [{ slug: "claude-opus-5-5" }, { slug: "claude-haiku-4-5" }] },+ { driver: "opencode", models: [{ slug: "ollama/acme-internal" }] },+].map(+ ({ driver, models }) =>+ ({+ instanceId: ProviderInstanceId.make(driver),+ driver,+ models: models.map((model) => ({ ...model, isCustom: false })),+ }) as unknown as ServerProvider,+);+const label = (model: string) => catalogModelLabel(providers, model);++const at = (ms: number) => DateTime.makeUnsafe(ms);+const complete = (input: number, output: number, extra: Partial<TurnTokenUsage> = {}) =>+ ({+ usageStatus: "complete",+ usageScope: "main_agent",+ hasSubagents: false,+ inputTokens: input,+ outputTokens: output,+ ...extra,+ }) as TurnTokenUsage;++const turn = (+ id: string,+ usage: TurnTokenUsage | undefined,+ status: OrchestrationV2ProviderTurn["status"] = "completed",+): OrchestrationV2ProviderTurn => ({+ id: ProviderTurnId.make(id),+ providerThreadId: ProviderThreadId.make("provider-thread"),+ nodeId: NodeId.make(`node:${id}`),+ runAttemptId: null,+ nativeTurnRef: null,+ ordinal: 1,+ status,+ startedAt: at(1_000),+ completedAt: at(4_000),+ ...(usage === undefined ? {} : { turnTokenUsage: usage }),+});++const context = (+ runId: string,+ segment: ProviderTurnSegment,+ model = "gpt-6-sol",+): ProviderTurnAnalyticsContext => ({+ runId: RunId.make(runId),+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model,+ options: [{ id: "reasoningEffort", value: "xhigh" }],+ },+ runtimeMode: "full-access",+ interactionMode: "default",+ origin: { createdBy: "user", creationSource: "web", scheduled: false, subagent: false },+ segment,+});++const settled = (runId: string, childrenRunning = false) => ({+ runId: RunId.make(runId),+ status: "completed" as const,+ completedAt: at(9_000),+ childrenRunning,+});++describe("provider usage reporting", () => {+ it.effect(+ "records one request across a continuation, a child, a replay, and a late child",+ () => {+ const recorded: Array<readonly [string, unknown]> = [];+ const layerTest = layer.pipe(+ Layer.provide(+ Layer.mergeAll(+ Layer.mock(AnalyticsService.AnalyticsService)({+ record: (event, properties) =>+ Effect.sync(() => void recorded.push([event, properties])),+ }),+ Layer.mock(ProviderRegistry.ProviderRegistry)({+ getProviders: Effect.succeed(providers),+ }),+ ),+ ),+ );+ return Effect.gen(function* () {+ const analytics = yield* ProviderTurnAnalytics;+ const root = context("run-a", "initial");+ yield* analytics.runStarted({ runId: RunId.make("run-a"), driver: "codex", context: root });+ const first = { driver: "codex", context: root };+ const firstTurn = turn("root", complete(100, 10, { models: ["gpt-6-sol"] }));+ yield* analytics.turnCompleted({ ...first, providerTurn: firstTurn });+ yield* analytics.turnCompleted({ ...first, providerTurn: firstTurn });+ yield* analytics.turnCompleted({+ driver: "codex",+ context: context("run-a", "continuation"),+ providerTurn: turn("goal", complete(50, 5, { models: ["gpt-6-sol"] })),+ });+ yield* analytics.turnCompleted({+ driver: "codex",+ context: context("run-a", "native_child"),+ providerTurn: turn("child", complete(20, 2)),+ });+ yield* analytics.runSettled(settled("run-a"));+ yield* analytics.turnCompleted({+ driver: "codex",+ context: context("run-a", "native_child"),+ providerTurn: turn("late-child", complete(7, 1)),+ });+ yield* analytics.runSettled(settled("run-a"));+ yield* analytics.runStarted({+ runId: RunId.make("run-b"),+ driver: "codex",+ context: context("run-b", "initial"),+ });+ yield* analytics.runSettled(settled("run-b"));++ const requests = recorded.filter(([event]) => event === "provider.request.completed");+ expect(recorded.filter(([event]) => event === "provider.turn.completed")).toHaveLength(5);+ expect(requests).toHaveLength(2);+ // The whole payload: no run, turn, or thread ids, prompts, or raw model names.+ expect(requests[0]?.[1]).toEqual({+ reportVersion: 2,+ provider: "codex",+ requestKind: "user",+ terminalStatus: "completed",+ lifecycleObserved: true,+ model: "gpt-6-sol",+ effort: "xhigh",+ runtimeMode: "full-access",+ interactionMode: "default",+ createdBy: "user",+ creationSource: "web",+ scheduled: false,+ subagent: false,+ providerTurns: 2,+ continuations: 1,+ steeringRestarts: 0,+ usageStatus: "complete",+ inputTokens: 150,+ outputTokens: 15,+ nativeChildTurns: 1,+ childUsageStatus: "complete",+ childInputTokens: 20,+ childOutputTokens: 2,+ durationMs: 8_000,+ });+ expect(requests[1]?.[1]).toMatchObject({ providerTurns: 0, usageStatus: "unavailable" });+ }).pipe(Effect.provide(layerTest));+ },+ );++ it("keeps a request partial when its start, a steered segment, or a counter is missing", () => {+ const ledger = new RequestUsageLedger();+ ledger.start(RunId.make("restarted"), "codex", {+ ...context("restarted", "initial"),+ restartContinuation: true,+ });+ ledger.add({+ driver: "codex",+ context: context("restarted", "initial"),+ providerTurn: turn("after-restart", complete(10, 1)),+ });+ expect(ledger.settle(settled("restarted"), label)).toMatchObject({+ restartContinuation: true,+ lifecycleObserved: false,+ usageStatus: "partial",+ inputTokens: 10,+ });++ ledger.start(RunId.make("steered"), "claudeAgent", context("steered", "initial"));+ ledger.add({+ driver: "claudeAgent",+ context: context("steered", "initial"),+ providerTurn: turn(+ "steered-away",+ { usageStatus: "partial", usageScope: "main_agent", hasSubagents: false, outputTokens: 4 },+ "interrupted",+ ),+ });+ ledger.add({+ driver: "claudeAgent",+ context: context("steered", "steering_restart"),+ providerTurn: turn("steered-to", complete(30, 6)),+ });+ expect(ledger.settle(settled("steered"), label)).toMatchObject({+ usageStatus: "partial",+ steeringRestarts: 1,+ inputTokens: 30,+ outputTokens: 10,+ });++ ledger.start(RunId.make("silent"), "grok", context("silent", "initial"));+ ledger.add({+ driver: "grok",+ context: context("silent", "initial"),+ providerTurn: turn("silent", undefined),+ });+ const silent = ledger.settle(settled("silent", true), label);+ expect(silent).toMatchObject({+ usageStatus: "unavailable",+ childrenRunning: true,+ childUsageStatus: "unavailable",+ });+ expect(silent).not.toHaveProperty("outputTokens");+ });++ it("confirms only the models a provider reported", () => {+ const opus = context("models", "initial", "claude-opus-5-5");+ const properties = (usage: TurnTokenUsage | undefined) =>+ providerTurnProperties(+ { driver: "claudeAgent", context: opus, providerTurn: turn("t", usage) },+ label,+ );+ expect(properties(complete(1, 1, { models: ["claude-haiku-4-5-20251001"] }))).toMatchObject({+ model: "claude-opus-5-5",+ observedModel: "claude-haiku-4-5",+ mixedModels: false,+ });+ const unconfirmed = properties(complete(1, 1));+ expect(unconfirmed).toMatchObject({ model: "claude-opus-5-5" });+ expect(unconfirmed).not.toHaveProperty("mixedModels");+ expect(properties(complete(1, 1, { models: ["a", "b"] }))).toMatchObject({ mixedModels: true });++ const ledger = new RequestUsageLedger();+ ledger.start(RunId.make("mixed"), "codex", context("mixed", "initial"));+ ledger.add({+ driver: "codex",+ context: context("mixed", "initial"),+ providerTurn: turn("root", complete(1, 1, { models: ["gpt-6-sol"] })),+ });+ ledger.add({+ driver: "codex",+ context: context("mixed", "native_child"),+ providerTurn: turn("child", complete(1, 1, { models: ["gpt-6-luna"] })),+ });+ expect(ledger.settle(settled("mixed"), label)).toMatchObject({ mixedModels: true });+ });++ it("keeps zero, absent, local-command, and ledger usage distinct", () => {+ const properties = (usage: TurnTokenUsage | undefined) =>+ providerTurnProperties(+ { driver: "claudeAgent", context: context("z", "initial"), providerTurn: turn("t", usage) },+ label,+ );+ expect(properties(complete(0, 0))).toMatchObject({+ usageStatus: "complete",+ usageReported: true,+ inputTokens: 0,+ outputTokens: 0,+ });+ const absent = properties(undefined);+ expect(absent).toMatchObject({ usageStatus: "unavailable", usageReported: false });+ expect(absent).not.toHaveProperty("outputTokens");+ expect(+ properties(+ complete(0, 0, { localCommand: true, otherUsage: { inputTokens: 900, outputTokens: 80 } }),+ ),+ ).toMatchObject({ localCommand: true, otherInputTokens: 900, otherOutputTokens: 80 });+ expect(properties(complete(74_167, 236, { reasoningTokens: 30 }))).toMatchObject({+ outputTokens: 236,+ reasoningTokens: 30,+ });+ });++ it("reports routed catalog models and closed efforts only", () => {+ const routed = (model: string, variant: string) =>+ providerTurnProperties(+ {+ driver: "opencode",+ context: {+ modelSelection: {+ instanceId: ProviderInstanceId.make("opencode"),+ model,+ options: [{ id: "variant", value: variant }],+ },+ },+ providerTurn: turn("t", complete(1, 1, { models: [model] })),+ },+ label,+ );+ expect(routed("my-proxy/claude-opus-5-5", "high")).toMatchObject({+ model: "claude-opus-5-5",+ observedModel: "claude-opus-5-5",+ effort: "high",+ });+ for (const local of [+ routed("ollama/acme-internal", "secret-variant"),+ routed("acme-azure-deployment", "high"),+ ]) {+ expect(local).not.toHaveProperty("model");+ expect(local).not.toHaveProperty("observedModel");+ }+ expect(routed("ollama/acme-internal", "secret-variant")).not.toHaveProperty("effort");+ });+});diff --git a/apps/server/src/telemetry/ProviderUsageAnalytics.ts b/apps/server/src/telemetry/ProviderUsageAnalytics.tsnew file mode 100644index 00000000000..96a00d59655--- /dev/null+++ b/apps/server/src/telemetry/ProviderUsageAnalytics.ts@@ -0,0 +1,407 @@+/**+ * Provider token reporting: one `provider.turn.completed` per provider turn and one+ * `provider.request.completed` per run, built from the same turns so each counts once.+ *+ * @module ProviderUsageAnalytics+ */+import type {+ ModelSelection,+ OrchestrationV2Actor,+ OrchestrationV2CreationSource,+ OrchestrationV2ProviderTurn,+ OrchestrationV2RunAttempt,+ ProviderInteractionMode,+ RunId,+ RuntimeMode,+ TurnTokenUsage,+} from "@t3tools/contracts";+import * as Context from "effect/Context";+import * as DateTime from "effect/DateTime";+import * as Effect from "effect/Effect";+import * as Layer from "effect/Layer";++import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";+import * as ProviderRegistry from "../provider/ProviderRegistry.ts";+import * as AnalyticsService from "./AnalyticsService.ts";+import { catalogModelLabel } from "./ProviderDimensions.ts";++// Bump when a field changes meaning, so reports can split old and new rows.+const REPORT_VERSION = 2;++/**+ * Where the run's starting message came from. Most turns start without a+ * person (provider continuations, agent sends, delegated subagents), so+ * reports need this to tell user turns apart.+ */+export interface ProviderTurnOrigin {+ readonly createdBy: OrchestrationV2Actor;+ readonly creationSource: OrchestrationV2CreationSource;+ readonly scheduled: boolean;+ readonly subagent: boolean;+}++/** What started this provider turn inside its run. */+export type ProviderTurnSegment =+ | OrchestrationV2RunAttempt["reason"]+ | "continuation"+ | "native_child";++export interface ProviderTurnAnalyticsContext {+ readonly runId?: RunId;+ readonly modelSelection: ModelSelection;+ readonly runtimeMode?: RuntimeMode;+ readonly interactionMode?: ProviderInteractionMode;+ readonly origin?: ProviderTurnOrigin;+ readonly segment?: ProviderTurnSegment;+ readonly restartContinuation?: boolean;+}++export interface ProviderTurnReport {+ readonly driver: string;+ readonly providerTurn: OrchestrationV2ProviderTurn;+ readonly context?: ProviderTurnAnalyticsContext;+}++export interface RunSettledReport {+ readonly runId: RunId;+ readonly status: OrchestrationV2ProviderTurn["status"];+ readonly completedAt: DateTime.Utc;+ // Run-owned children were still open when the run settled; their later turns are not added.+ readonly childrenRunning: boolean;+}++type Properties = Readonly<Record<string, unknown>>;+/** Maps a native model id to a vendor catalog label, or undefined to keep it out. */+export type ModelLabeler = (model: string) => string | undefined;++const TERMINAL_STATUSES: ReadonlySet<OrchestrationV2ProviderTurn["status"]> = new Set([+ "completed",+ "failed",+ "interrupted",+ "cancelled",+]);++const REPORTED_EFFORTS: ReadonlySet<string> = new Set([+ "none",+ "minimal",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultrathink",+ "ultracode",+ "brutal",+]);++const defined = (entries: Properties): Properties =>+ Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));++// OpenCode names its effort option `variant`, and variants can be user-defined.+function selectedEffort(selection: ModelSelection): string | undefined {+ const effort =+ getModelSelectionStringOptionValue(selection, "reasoningEffort") ??+ getModelSelectionStringOptionValue(selection, "effort") ??+ getModelSelectionStringOptionValue(selection, "variant");+ return effort !== undefined && REPORTED_EFFORTS.has(effort) ? effort : undefined;+}++/**+ * Confirmed models across counted work. Unknown when any piece of work has no+ * reported model, unless two distinct models were already seen.+ */+function modelObservation(+ models: ReadonlyArray<ReadonlyArray<string> | undefined>,+ label: ModelLabeler,+): Properties {+ const distinct = new Set(models.flatMap((entry) => entry ?? []));+ if (distinct.size > 1) return { mixedModels: true };+ if (distinct.size === 0 || models.some((entry) => entry === undefined || entry.length === 0)) {+ return {};+ }+ return defined({ mixedModels: false, observedModel: label([...distinct][0]!) });+}++function selectionProperties(+ context: ProviderTurnAnalyticsContext | undefined,+ label: ModelLabeler,+) {+ const selection = context?.modelSelection;+ return defined({+ model: selection === undefined ? undefined : label(selection.model),+ effort: selection === undefined ? undefined : selectedEffort(selection),+ runtimeMode: context?.runtimeMode,+ interactionMode: context?.interactionMode,+ ...context?.origin,+ });+}++function childKind(context: ProviderTurnAnalyticsContext | undefined) {+ if (context?.segment === "native_child") return "native";+ return context?.origin?.subagent === true ? "t3" : undefined;+}++function counters(usage: TurnTokenUsage | undefined): Properties {+ return defined({+ inputTokens: usage?.inputTokens,+ cachedInputTokens: usage?.cachedInputTokens,+ cacheCreationTokens: usage?.cacheCreationTokens,+ outputTokens: usage?.outputTokens,+ reasoningTokens: usage?.reasoningTokens,+ });+}++export function providerTurnProperties(+ report: ProviderTurnReport,+ label: ModelLabeler,+): Properties {+ const { providerTurn, context } = report;+ const usage = providerTurn.turnTokenUsage;+ return defined({+ reportVersion: REPORT_VERSION,+ provider: report.driver,+ terminalStatus: providerTurn.status,+ usageStatus: usage?.usageStatus ?? "unavailable",+ usageScope: usage?.usageScope ?? "main_agent",+ usageReported: usage !== undefined,+ hasSubagents: usage?.hasSubagents,+ ...counters(usage),+ localCommand: usage?.localCommand === true ? true : undefined,+ otherInputTokens: usage?.otherUsage?.inputTokens,+ otherOutputTokens: usage?.otherUsage?.outputTokens,+ ...selectionProperties(context, label),+ ...modelObservation([usage?.models], label),+ segment: context?.segment,+ childKind: childKind(context),+ durationMs:+ providerTurn.startedAt && providerTurn.completedAt+ ? Math.max(+ 0,+ DateTime.toEpochMillis(providerTurn.completedAt) -+ DateTime.toEpochMillis(providerTurn.startedAt),+ )+ : undefined,+ });+}++/** How the request reached the provider; only `user` counts as a person asking. */+function requestKind(origin: ProviderTurnOrigin | undefined) {+ if (origin === undefined) return "unknown";+ if (origin.scheduled) return "scheduled";+ if (origin.subagent) return "t3_child";+ if (origin.createdBy === "user") return "user";+ if (origin.creationSource === "provider") return "provider_continuation";+ return origin.createdBy;+}++function sumOf(+ usages: ReadonlyArray<TurnTokenUsage>,+ field:+ | "inputTokens"+ | "cachedInputTokens"+ | "cacheCreationTokens"+ | "outputTokens"+ | "reasoningTokens",+ requireAll: boolean,+): number | undefined {+ const values = usages.map((usage) => usage[field]);+ const known = values.filter((value) => value !== undefined);+ if (known.length === 0 || (requireAll && known.length < values.length)) return undefined;+ return known.reduce((sum, value) => sum + value, 0);+}++/** complete only when every turn is complete; partial when any turn has counts. */+function combinedStatus(usages: ReadonlyArray<TurnTokenUsage | undefined>) {+ if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) {+ return "complete";+ }+ return usages.some(+ (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined,+ )+ ? "partial"+ : "unavailable";+}++interface RequestTurn {+ readonly child: boolean;+ readonly segment: ProviderTurnSegment | undefined;+ readonly providerTurn: OrchestrationV2ProviderTurn;+}++interface RequestEntry {+ driver: string | undefined;+ context: ProviderTurnAnalyticsContext | undefined;+ readonly lifecycleObserved: boolean;+ readonly turns: Map<string, RequestTurn>;+}++const MAX_TRACKED_RUNS = 2048;++/**+ * Collects terminal provider turns per run in this process. A replayed turn+ * replaces its earlier copy, a settled run ignores late turns, and a run whose+ * initial attempt started before this process reports `lifecycleObserved: false`.+ */+export class RequestUsageLedger {+ private readonly open = new Map<RunId, RequestEntry>();+ private readonly settled = new Set<RunId>();++ start(runId: RunId, driver: string, context: ProviderTurnAnalyticsContext): void {+ if (this.settled.has(runId) || this.open.has(runId)) return;+ // A restart continuation carries on a run whose earlier turns this process never saw.+ const lifecycleObserved = context.restartContinuation !== true;+ this.open.set(runId, { driver, context, lifecycleObserved, turns: new Map() });+ evictOldest(this.open);+ }++ add(report: ProviderTurnReport): void {+ const runId = report.context?.runId;+ if (runId === undefined || this.settled.has(runId)) return;+ if (!TERMINAL_STATUSES.has(report.providerTurn.status)) return;+ let entry = this.open.get(runId);+ if (entry === undefined) {+ entry = { driver: undefined, context: undefined, lifecycleObserved: false, turns: new Map() };+ this.open.set(runId, entry);+ evictOldest(this.open);+ }+ const child = report.context?.segment === "native_child";+ if (!child) {+ entry.driver ??= report.driver;+ entry.context ??= report.context;+ }+ entry.turns.set(String(report.providerTurn.id), {+ child,+ segment: report.context?.segment,+ providerTurn: report.providerTurn,+ });+ }++ settle(report: RunSettledReport, label: ModelLabeler): Properties | undefined {+ if (this.settled.has(report.runId)) return undefined;+ this.settled.add(report.runId);+ evictOldest(this.settled);+ const entry = this.open.get(report.runId);+ this.open.delete(report.runId);+ if (entry === undefined) return undefined;++ const turns = [...entry.turns.values()];+ const root = turns.filter((turn) => !turn.child);+ const children = turns.filter((turn) => turn.child);+ const rootUsage = root.map((turn) => turn.providerTurn.turnTokenUsage);+ const childUsage = children.map((turn) => turn.providerTurn.turnTokenUsage);+ const { lifecycleObserved } = entry;+ const measuredRoot = rootUsage.filter((usage) => usage !== undefined);+ const status = combinedStatus(rootUsage);+ const rootComplete = status === "complete";+ const otherUsage = measuredRoot.map((usage) => usage.otherUsage);+ const allOtherKnown = otherUsage.length > 0 && otherUsage.every((usage) => usage !== undefined);+ const anyRootSubagents = measuredRoot.some((usage) => usage.hasSubagents);+ const measuredChildren = childUsage.filter((usage) => usage !== undefined);+ const childStatus =+ children.length === 0 && !anyRootSubagents && !report.childrenRunning+ ? "none"+ : children.length === 0+ ? "unavailable"+ : report.childrenRunning && combinedStatus(childUsage) === "complete"+ ? "partial"+ : combinedStatus(childUsage);+ const startedAt = turns+ .map((turn) => turn.providerTurn.startedAt)+ .filter((value) => value !== null)+ .map(DateTime.toEpochMillis);++ return defined({+ reportVersion: REPORT_VERSION,+ provider: entry.driver ?? "unknown",+ requestKind: requestKind(entry.context?.origin),+ restartContinuation: entry.context?.restartContinuation === true ? true : undefined,+ terminalStatus: report.status,+ lifecycleObserved,+ ...selectionProperties(entry.context, label),+ providerTurns: root.length,+ continuations: root.filter((turn) => turn.segment === "continuation").length,+ steeringRestarts: root.filter((turn) => turn.segment === "steering_restart").length,+ usageStatus: lifecycleObserved || status === "unavailable" ? status : "partial",+ inputTokens: sumOf(measuredRoot, "inputTokens", rootComplete),+ cachedInputTokens: sumOf(measuredRoot, "cachedInputTokens", true),+ cacheCreationTokens: sumOf(measuredRoot, "cacheCreationTokens", true),+ outputTokens: sumOf(measuredRoot, "outputTokens", rootComplete),+ reasoningTokens: sumOf(measuredRoot, "reasoningTokens", true),+ localCommand: measuredRoot.some((usage) => usage.localCommand === true) ? true : undefined,+ otherInputTokens: allOtherKnown+ ? otherUsage.reduce((sum, usage) => sum + (usage?.inputTokens ?? 0), 0)+ : undefined,+ otherOutputTokens: allOtherKnown+ ? otherUsage.reduce((sum, usage) => sum + (usage?.outputTokens ?? 0), 0)+ : undefined,+ nativeChildTurns: children.length,+ childUsageStatus: childStatus,+ childInputTokens: sumOf(measuredChildren, "inputTokens", false),+ childOutputTokens: sumOf(measuredChildren, "outputTokens", false),+ childrenRunning: report.childrenRunning ? true : undefined,+ ...modelObservation(+ [...rootUsage, ...childUsage].map((usage) => usage?.models),+ label,+ ),+ durationMs:+ startedAt.length === 0+ ? undefined+ : Math.max(0, DateTime.toEpochMillis(report.completedAt) - Math.min(...startedAt)),+ });+ }+}++function evictOldest(collection: Map<RunId, unknown> | Set<RunId>) {+ if (collection.size <= MAX_TRACKED_RUNS) return;+ const oldest = collection.keys().next().value;+ if (oldest !== undefined) collection.delete(oldest);+}++export class ProviderTurnAnalytics extends Context.Reference<{+ readonly runStarted: (input: {+ readonly runId: RunId;+ readonly driver: string;+ readonly context: ProviderTurnAnalyticsContext;+ }) => Effect.Effect<void>;+ readonly turnCompleted: (report: ProviderTurnReport) => Effect.Effect<void>;+ readonly runSettled: (report: RunSettledReport) => Effect.Effect<void>;+}>("t3/telemetry/ProviderTurnAnalytics", {+ defaultValue: () => ({+ runStarted: () => Effect.void,+ turnCompleted: () => Effect.void,+ runSettled: () => Effect.void,+ }),+}) {}++export const layer = Layer.effect(+ ProviderTurnAnalytics,+ Effect.gen(function* () {+ const analytics = yield* AnalyticsService.AnalyticsService;+ const registry = yield* ProviderRegistry.ProviderRegistry;+ const ledger = new RequestUsageLedger();+ const labeler = Effect.map(+ registry.getProviders,+ (providers): ModelLabeler =>+ (model) =>+ catalogModelLabel(providers, model),+ );+ return {+ runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) =>+ Effect.sync(() => ledger.start(input.runId, input.driver, input.context)),+ ),+ turnCompleted: Effect.fn("ProviderTurnAnalytics.turnCompleted")(function* (report) {+ ledger.add(report);+ yield* analytics.record(+ "provider.turn.completed",+ providerTurnProperties(report, yield* labeler),+ );+ }),+ runSettled: Effect.fn("ProviderTurnAnalytics.runSettled")(function* (report) {+ const properties = ledger.settle(report, yield* labeler);+ if (properties !== undefined) {+ yield* analytics.record("provider.request.completed", properties);+ }+ }),+ };+ }),+);diff --git a/docs/internals/product-analytics.md b/docs/internals/product-analytics.mdindex 3369d5832c4..2c6055d811a 100644--- a/docs/internals/product-analytics.md+++ b/docs/internals/product-analytics.md@@ -53,22 +53,61 @@ A command whose id was already accepted is a retry, so it records nothing again.One identity can appear in several client groups during a period; adding thosegroups double-counts users.-Provider send and completion counts need not match. Most completions start-without a person: provider continuations, agent sends, and delegated subagents.-`provider.turn.completed` carries the starting message's `createdBy` and-`creationSource`, plus `scheduled` and `subagent`; filter on them to count user-turns. Collection is best effort, with no scan or backfill of provider history.--Token totals cover the main agent. Child agents and model rerouting prevent a turn-from representing one provider/model combination's full cost. For provider-comparisons, require complete usage, no observed subagents, and no mixed models;-compare matching model, effort, interaction mode, and terminal status. Aggregate-output/input ratios should divide the summed totals. Averaging per-turn ratios-lets small-input turns dominate.--Unknown counts stay absent. Partial usage contains valid observed counts but-cannot establish a whole-turn total. Keep these distinctions when changing token-normalization or building reports.+Provider send and completion counts need not match. `provider.turn.completed`+is one provider turn, and `segment` says what started it: the run's first+attempt (`initial`), a `steering_restart`, a provider `continuation` such as a+Codex goal turn, or a `native_child` subagent. `createdBy`, `creationSource`,+`scheduled`, and `subagent` describe the run's starting message, and `childKind`+separates native subagents from T3-managed child threads. Use this event for+per-turn measurements, not for counting requests.++`provider.request.completed` is one run, recorded when the run settles in the+server process that ran it. It adds each root turn once, so continuations,+steering, and replayed provider events do not add rows. `requestKind: "user"`+counts what people asked for. Native subagent turns are summed apart from the+root (`childUsageStatus`, `childInputTokens`); T3-managed child threads report+their own requests as `t3_child`. A child still running at settlement is never+added later, and the summary sets `childrenRunning`. A server restart loses the+summary of a run in progress. A run that continues after a restart reports its+own usage with `restartContinuation` and `lifecycleObserved: false`; it cannot+recover the original request's count or kind. A run whose provider session never+opens has no summary, and a start the provider rejects reports+`providerTurns: 0`. A Stop that lands while a steering restart is starting ends+the run without a summary. Collection is best effort, with no scan or backfill of+provider history.++Counts cover the main agent. `otherInputTokens` and `otherOutputTokens` are what+a provider's own ledger recorded beyond it during the turn: Claude's per-process+`modelUsage` growth, which covers native subagents, compaction, and helper+calls. They need a baseline from the same process, so they stay absent when it+is unknown or the ledger goes backwards, and background work that ends between+turns lands in the next one. Claude subagents have no turns of their own, so+this never overlaps child turns.++`model` and `effort` are what the run selected. `observedModel` and+`mixedModels` appear only when the provider reported the models for the counted+work (Codex thread settings and reroutes, Claude root messages, OpenCode steps).+`mixedModels: false` without `reportVersion` was never checked. Model labels+come from the bundled model manifest and the Cursor and Grok catalogs, also for+routed ids such as `anthropic/claude-opus-5-5`, and efforts come from a closed+list, so user-configured names stay out.++Status and counters answer different questions. `usageReported: false` means+the adapter attached no usage; a harness where every row says so is unsupported,+not idle. `partial` keeps valid counts that cannot establish a whole-turn total,+such as an OpenCode step that ended without a report, an OpenCode stream+reconnect, or an interrupted segment.+Explicit zeros are sent and unknown counts stay absent. `localCommand` marks a+provider-local command such as Claude's `/compact`, whose result counters are not+model work. Reasoning tokens are a subset of output.++Charts built on these events should say "output tokens per measured provider+completion", compare matching provider, observed model, effort, interaction mode,+and terminal status, and show eligible and measured counts by harness, origin,+and status so unknown models and unsupported adapters stay in the denominator.+Divide summed totals for output/input ratios; averaging per-turn ratios lets+small-input turns dominate. Rows without `reportVersion` keep their missing+fields unknown; a missing origin is never a person.`feature.used` counts WebSocket requests that start a feature. RPCs are observed inthe RPC authorization middleware after the request succeeds; dispatched commandsdiff --git a/docs/user/telemetry.md b/docs/user/telemetry.mdindex 9e70561332e..3b7e8f9d5a2 100644--- a/docs/user/telemetry.md+++ b/docs/user/telemetry.md@@ -5,11 +5,12 @@ associated with a hashed account or installation identifier. To count how many iuses, the server also sends hashed account identifiers: your T3 Connect account, your OpenAI andClaude accounts when you are signed in, and a random identifier for each device that connects. The endpoint keeps a copy of eachevent and forwards events to PostHog. Events include the provider, model, reasoning effort,-permission mode, turn result, duration, release channel, and main-agent token totals when-available.+permission mode, turn and request results, duration, release channel, and token counts when+available. Child-agent token counts are reported separately from the main agent's. Model names+are sent only when they appear in a provider's public model list.Events do not include prompts, responses, file contents, authentication tokens, conversation IDs,-raw provider events, or child-agent output. Child-agent token use is excluded from the totals.+raw provider events, or child-agent output.T3 Code also sends relay connection traces to Axiom to diagnose T3 Connect connectivity.diff --git a/packages/contracts/src/providerRuntime.ts b/packages/contracts/src/providerRuntime.tsindex 4740a9fd0cc..4769bfd7955 100644--- a/packages/contracts/src/providerRuntime.ts+++ b/packages/contracts/src/providerRuntime.ts@@ -60,6 +60,14 @@ const TurnTokenUsageCommonFields = {cacheCreationTokens: Schema.optional(NonNegativeInt),reasoningTokens: Schema.optional(NonNegativeInt),hasSubagents: Schema.Boolean,+ // Native model ids the provider reported for the main agent's work. Absent means unknown.+ models: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)),+ // The provider ran a local command; its counters describe that result, not model work.+ localCommand: Schema.optional(Schema.Boolean),+ // Provider-ledger counts beyond the main agent, such as native subagents and compaction.+ otherUsage: Schema.optional(+ Schema.Struct({ inputTokens: NonNegativeInt, outputTokens: NonNegativeInt }),+ ),};export const TurnTokenUsage = Schema.Union([Schema.Struct({diff --git a/packages/provider-opencode/src/server/v2/adapter.ts b/packages/provider-opencode/src/server/v2/adapter.tsindex 74695bf6061..f49de61b246 100644--- a/packages/provider-opencode/src/server/v2/adapter.ts+++ b/packages/provider-opencode/src/server/v2/adapter.ts@@ -209,7 +209,12 @@ interface ActiveTurn {output: number;reasoning: number;};+ // Steps OpenCode started; a step that ends without tokens leaves the total partial.+ startedSteps: number;+ // A reconnect dropped events, so steps may have ended unseen.+ missedEvents: boolean;steps: number;+ readonly models: Set<string>;lastStep: Tokens | undefined;before: string | null | undefined;compaction: { readonly nativeId: string; readonly startedAt: DateTime.Utc } | undefined;@@ -629,16 +634,26 @@ const skillsNamed = (text: string, known: ReadonlySet<string>) => [),];-const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) =>- turn.steps === 0+const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["status"]) => {+ // A step whose start was missed, in a reconnect gap or as an unreadable event, ran on an unreported model.+ const models =+ turn.models.size === 0 || turn.missedEvents || turn.steps > turn.startedSteps+ ? {}+ : { models: [...turn.models] };+ return turn.steps === 0? {usageScope: "main_agent" as const,usageStatus: "unavailable" as const,hasSubagents: turn.usedSubagents,+ ...models,}: {+ ...models,usageScope: "main_agent" as const,- usageStatus: status === "completed" ? ("complete" as const) : ("partial" as const),+ usageStatus:+ status === "completed" && !turn.missedEvents && turn.steps >= turn.startedSteps+ ? ("complete" as const)+ : ("partial" as const),inputTokens: turn.usage.input,cachedInputTokens: turn.usage.cached,cacheCreationTokens: turn.usage.cacheWrite,@@ -646,6 +661,7 @@ const turnTokenUsage = (turn: ActiveTurn, status: OrchestrationV2ProviderTurn["sreasoningTokens: turn.usage.reasoning,hasSubagents: turn.usedSubagents,};+};export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: ProviderInstanceId) {const server = yield* OpenCode2Server.OpenCode2Server;@@ -1111,7 +1127,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prordinals: new Map(),nextOrdinal: providerTurn.ordinal * 100 + 1,usage: { input: 0, cached: 0, cacheWrite: 0, output: 0, reasoning: 0 },+ startedSteps: 0,+ missedEvents: false,steps: 0,+ models: new Set(),lastStep: undefined,before: undefined,compaction: undefined,@@ -2101,6 +2120,10 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prreturn yield* emitCompaction(state, turn, "completed", event.data.text);case "session.compaction.failed":return yield* emitCompaction(state, turn, "failed");+ case "session.step.started":+ turn.startedSteps += 1;+ turn.models.add(`${event.data.model.providerID}/${event.data.model.id}`);+ return;case "session.step.ended":case "session.step.failed": {const tokens = event.data.tokens;@@ -2568,6 +2591,7 @@ export const make = Effect.fn("OpenCode2Adapter.make")(function* (instanceId: Prfor (const [sessionId, state] of running) {const turn = state.active;if (turn === undefined) continue;+ turn.missedEvents = true;const ended = yield* backfill(sessionId, state);if (sessionId in active || state.active !== turn) continue;yield* finishTurn(