feat(server): measure provider turn token usage (#9132)
This commit is contained in:
1 parent
dab5f6e6e0
commit
1587f248dd
14 files changed
+3865
-20
No files matched your search
@@ -24,6 +24,7 @@ import {
|
||||
import { createModelSelection } from "@t3tools/shared/model";
|
||||
import { assert, describe, it } from "@effect/vitest";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
import * as Layer from "effect/Layer";
|
||||
@@ -1899,7 +1900,8 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 8).pipe(
|
||||
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.takeUntil((event) => event.type === "turn.completed"),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1937,6 +1939,17 @@ describe("ClaudeAdapterLive", () => {
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_started",
|
||||
task_id: "task-agent-1",
|
||||
description: "Review the database layer",
|
||||
task_type: "local_agent",
|
||||
tool_use_id: "tool-task-1",
|
||||
uuid: "task-agent-1-uuid",
|
||||
session_id: "sdk-session-task",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
harness.query.emit({
|
||||
type: "assistant",
|
||||
session_id: "sdk-session-task",
|
||||
@@ -1953,6 +1966,12 @@ describe("ClaudeAdapterLive", () => {
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
errors: [],
|
||||
usage: {
|
||||
input_tokens: 100,
|
||||
cache_read_input_tokens: 40,
|
||||
cache_creation_input_tokens: 10,
|
||||
output_tokens: 20,
|
||||
},
|
||||
session_id: "sdk-session-task",
|
||||
uuid: "result-task-1",
|
||||
} as unknown as SDKMessage);
|
||||
@@ -1964,6 +1983,11 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(toolStarted.payload.itemType, "collab_agent_tool_call");
|
||||
assert.equal(toolStarted.payload.title, "Subagent task");
|
||||
}
|
||||
const completed = runtimeEvents.find((event) => event.type === "turn.completed");
|
||||
assert.equal(completed?.type, "turn.completed");
|
||||
if (completed?.type === "turn.completed") {
|
||||
assert.equal(completed.payload.tokenUsage?.hasSubagents, true);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -1975,7 +1999,8 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
const runtimeEventsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.takeUntil((event) => event.type === "turn.completed"),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1998,6 +2023,12 @@ describe("ClaudeAdapterLive", () => {
|
||||
is_error: false,
|
||||
errors: ["Error: Request was aborted."],
|
||||
stop_reason: "tool_use",
|
||||
usage: {
|
||||
input_tokens: 12,
|
||||
cache_read_input_tokens: 3,
|
||||
cache_creation_input_tokens: 1,
|
||||
output_tokens: 4,
|
||||
},
|
||||
session_id: "sdk-session-abort",
|
||||
uuid: "result-abort",
|
||||
} as unknown as SDKMessage);
|
||||
@@ -2011,6 +2042,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"thread.token-usage.updated",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
@@ -2022,6 +2054,15 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(turnCompleted.payload.state, "interrupted");
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Error: Request was aborted.");
|
||||
assert.equal(turnCompleted.payload.stopReason, "tool_use");
|
||||
assert.deepEqual(turnCompleted.payload.tokenUsage, {
|
||||
usageStatus: "partial",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 16,
|
||||
cachedInputTokens: 3,
|
||||
cacheCreationTokens: 1,
|
||||
outputTokens: 4,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
@@ -2509,7 +2550,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
session_id: "sdk-session-result-usage",
|
||||
usage: {
|
||||
input_tokens: 400,
|
||||
cache_read_input_tokens: 90,
|
||||
cache_creation_input_tokens: 10,
|
||||
output_tokens: 50,
|
||||
output_tokens_details: { thinking_tokens: 30 },
|
||||
},
|
||||
modelUsage: {
|
||||
[SYNTHETIC_CLAUDE_CAPABLE_MODEL]: {
|
||||
@@ -2527,16 +2571,211 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.deepEqual(usageEvent.payload.usage, {
|
||||
usedTokens: 200,
|
||||
lastUsedTokens: 200,
|
||||
totalProcessedTokens: 450,
|
||||
totalProcessedTokens: 550,
|
||||
inputTokens: 180,
|
||||
outputTokens: 20,
|
||||
maxTokens: 200000,
|
||||
});
|
||||
}
|
||||
assert.equal(
|
||||
runtimeEvents.find((event) => event.type === "turn.completed")?.type,
|
||||
"turn.completed",
|
||||
const completed = runtimeEvents.find((event) => event.type === "turn.completed");
|
||||
assert.equal(completed?.type, "turn.completed");
|
||||
if (completed?.type === "turn.completed") {
|
||||
assert.deepEqual(completed.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 500,
|
||||
cachedInputTokens: 90,
|
||||
cacheCreationTokens: 10,
|
||||
reasoningTokens: 30,
|
||||
outputTokens: 50,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("treats omitted Claude cache counters as zero contributions", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "uncached turn",
|
||||
attachments: [],
|
||||
});
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 100,
|
||||
duration_api_ms: 90,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-uncached-usage",
|
||||
usage: {
|
||||
input_tokens: 42,
|
||||
output_tokens: 9,
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const completed = yield* Fiber.join(completedFiber);
|
||||
assert.equal(completed._tag, "Some");
|
||||
if (completed._tag === "Some" && completed.value.type === "turn.completed") {
|
||||
assert.deepEqual(completed.value.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 42,
|
||||
outputTokens: 9,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("uses per-turn result usage across consecutive Claude turns", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
const firstTurnSettled = yield* Deferred.make<void>();
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.tap((event) =>
|
||||
event.type === "session.state.changed" && event.payload.reason === "api_retry:1/2"
|
||||
? Deferred.succeed(firstTurnSettled, undefined).pipe(Effect.asVoid)
|
||||
: Effect.void,
|
||||
),
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: ProviderDriverKind.make("claudeAgent"),
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "first turn",
|
||||
attachments: [],
|
||||
});
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 100,
|
||||
duration_api_ms: 90,
|
||||
num_turns: 1,
|
||||
result: "first",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-consecutive-usage",
|
||||
usage: {
|
||||
input_tokens: 100,
|
||||
cache_read_input_tokens: 20,
|
||||
cache_creation_input_tokens: 5,
|
||||
output_tokens: 10,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
inputTokens: 10_000,
|
||||
outputTokens: 1_000,
|
||||
cacheReadInputTokens: 2_000,
|
||||
cacheCreationInputTokens: 500,
|
||||
webSearchRequests: 0,
|
||||
costUSD: 1,
|
||||
contextWindow: 200_000,
|
||||
maxOutputTokens: 64_000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "api_retry",
|
||||
attempt: 1,
|
||||
max_retries: 2,
|
||||
retry_delay_ms: 1,
|
||||
error_status: 502,
|
||||
error: { type: "api_error" },
|
||||
session_id: "sdk-session-consecutive-usage",
|
||||
uuid: "consecutive-usage-barrier",
|
||||
} as unknown as SDKMessage);
|
||||
yield* Deferred.await(firstTurnSettled);
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "second turn",
|
||||
attachments: [],
|
||||
});
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 80,
|
||||
duration_api_ms: 70,
|
||||
num_turns: 2,
|
||||
result: "second",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-consecutive-usage",
|
||||
usage: {
|
||||
input_tokens: 30,
|
||||
cache_read_input_tokens: 2,
|
||||
cache_creation_input_tokens: 3,
|
||||
output_tokens: 7,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
inputTokens: 20_000,
|
||||
outputTokens: 2_000,
|
||||
cacheReadInputTokens: 4_000,
|
||||
cacheCreationInputTokens: 1_000,
|
||||
webSearchRequests: 0,
|
||||
costUSD: 2,
|
||||
contextWindow: 200_000,
|
||||
maxOutputTokens: 64_000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const completed = Array.from(yield* Fiber.join(completedFiber));
|
||||
assert.equal(completed[0]?.type, "turn.completed");
|
||||
assert.equal(completed[1]?.type, "turn.completed");
|
||||
if (completed[0]?.type === "turn.completed" && completed[1]?.type === "turn.completed") {
|
||||
assert.deepEqual(completed[0].payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 125,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 10,
|
||||
hasSubagents: false,
|
||||
});
|
||||
assert.deepEqual(completed[1].payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 35,
|
||||
cachedInputTokens: 2,
|
||||
cacheCreationTokens: 3,
|
||||
outputTokens: 7,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
@@ -2941,6 +3180,11 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
assert.equal(turnCompleted.payload.state, "interrupted");
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
|
||||
assert.deepEqual(turnCompleted.payload.tokenUsage, {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
|
||||
const sessionExited = runtimeEvents[5];
|
||||
|
||||
@@ -24,6 +24,7 @@ import { isWorkspaceImagePreviewPath } from "@t3tools/shared/filePreview";
|
||||
import { type ClaudeScopedLimitNames, claudeRateLimitEventToUpdate } from "./claudeUsageLimits.ts";
|
||||
import {
|
||||
ApprovalRequestId,
|
||||
classifyTaskAgentKind,
|
||||
type CanonicalItemType,
|
||||
type CanonicalRequestType,
|
||||
type ClaudeSettings,
|
||||
@@ -38,6 +39,7 @@ import {
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type TurnTokenUsage,
|
||||
type ProviderUserInputAnswers,
|
||||
type RuntimeContentStreamKind,
|
||||
RuntimeItemId,
|
||||
@@ -154,6 +156,7 @@ interface ClaudeTurnState {
|
||||
readonly capturedProposedPlanKeys: Set<string>;
|
||||
latestAssistantUsage: unknown | undefined;
|
||||
compactedSinceLatestAssistantUsage: boolean;
|
||||
hasSubagents: boolean;
|
||||
nextSyntheticAssistantBlockIndex: number;
|
||||
}
|
||||
|
||||
@@ -643,6 +646,85 @@ function normalizeClaudeActiveTokenUsage(
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeClaudeTurnTokenUsage(
|
||||
result: SDKResultMessage | undefined,
|
||||
hasSubagents: boolean,
|
||||
terminalStatus: ProviderRuntimeTurnStatus,
|
||||
): TurnTokenUsage {
|
||||
const usage = result?.usage as Record<string, unknown> | undefined;
|
||||
if (!usage) {
|
||||
return {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents,
|
||||
};
|
||||
}
|
||||
|
||||
const uncachedInputTokens = finiteNonNegativeInteger(usage.input_tokens);
|
||||
const cachedInputTokens = finiteNonNegativeInteger(usage.cache_read_input_tokens);
|
||||
const cacheCreationTokens = finiteNonNegativeInteger(usage.cache_creation_input_tokens);
|
||||
const rawOutputTokens = finiteNonNegativeInteger(usage.output_tokens);
|
||||
const outputDetails = usage.output_tokens_details as Record<string, unknown> | undefined;
|
||||
const thinkingTokens = finiteNonNegativeInteger(outputDetails?.thinking_tokens);
|
||||
const cachedInputContribution = usage.cache_read_input_tokens == null ? 0 : cachedInputTokens;
|
||||
const cacheCreationContribution =
|
||||
usage.cache_creation_input_tokens == null ? 0 : cacheCreationTokens;
|
||||
const inputTokens =
|
||||
uncachedInputTokens !== undefined &&
|
||||
cachedInputContribution !== undefined &&
|
||||
cacheCreationContribution !== undefined
|
||||
? uncachedInputTokens + cachedInputContribution + cacheCreationContribution
|
||||
: undefined;
|
||||
const hasKnownUsage =
|
||||
uncachedInputTokens !== undefined ||
|
||||
cachedInputTokens !== undefined ||
|
||||
cacheCreationTokens !== undefined ||
|
||||
rawOutputTokens !== undefined;
|
||||
const hasPositiveUsage =
|
||||
(uncachedInputTokens ?? 0) +
|
||||
(cachedInputTokens ?? 0) +
|
||||
(cacheCreationTokens ?? 0) +
|
||||
(rawOutputTokens ?? 0) >
|
||||
0;
|
||||
|
||||
if (!hasKnownUsage || (result?.subtype !== "success" && !hasPositiveUsage)) {
|
||||
return {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents,
|
||||
};
|
||||
}
|
||||
|
||||
const commonUsage = {
|
||||
usageScope: "main_agent",
|
||||
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||
...(cacheCreationTokens !== undefined ? { cacheCreationTokens } : {}),
|
||||
...(thinkingTokens !== undefined && rawOutputTokens !== undefined
|
||||
? { reasoningTokens: Math.min(rawOutputTokens, thinkingTokens) }
|
||||
: {}),
|
||||
hasSubagents,
|
||||
} as const;
|
||||
if (
|
||||
terminalStatus === "completed" &&
|
||||
result?.subtype === "success" &&
|
||||
inputTokens !== undefined &&
|
||||
rawOutputTokens !== undefined
|
||||
) {
|
||||
return {
|
||||
...commonUsage,
|
||||
usageStatus: "complete",
|
||||
inputTokens,
|
||||
outputTokens: rawOutputTokens,
|
||||
};
|
||||
}
|
||||
return {
|
||||
...commonUsage,
|
||||
usageStatus: "partial",
|
||||
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||
...(rawOutputTokens !== undefined ? { outputTokens: rawOutputTokens } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function compactBoundaryTokenUsageSnapshot(
|
||||
message: Record<string, unknown>,
|
||||
contextWindow?: number,
|
||||
@@ -2503,6 +2585,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
? { totalCostUsd: result.total_cost_usd }
|
||||
: {}),
|
||||
...(errorMessage ? { errorMessage } : {}),
|
||||
tokenUsage: normalizeClaudeTurnTokenUsage(result, turnState.hasSubagents, status),
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
});
|
||||
@@ -3047,6 +3130,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
latestAssistantUsage: undefined,
|
||||
compactedSinceLatestAssistantUsage: false,
|
||||
hasSubagents: false,
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
context.session = {
|
||||
@@ -3353,6 +3437,15 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
)
|
||||
: undefined;
|
||||
const owningAgentId = launchingTool?.agentId;
|
||||
if (
|
||||
context.turnState &&
|
||||
classifyTaskAgentKind({
|
||||
taskType: message.task_type,
|
||||
...(owningAgentId ? { agentId: owningAgentId } : {}),
|
||||
}) === "agent"
|
||||
) {
|
||||
context.turnState.hasSubagents = true;
|
||||
}
|
||||
// Model/effort: the Agent tool's input carries explicit overrides;
|
||||
// absent ones inherit the session's selection (SDK behavior).
|
||||
// Subagent assistant snapshots refine model with the authoritative API
|
||||
@@ -4746,6 +4839,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
|
||||
capturedProposedPlanKeys: new Set(),
|
||||
latestAssistantUsage: undefined,
|
||||
compactedSinceLatestAssistantUsage: false,
|
||||
hasSubagents: false,
|
||||
nextSyntheticAssistantBlockIndex: -1,
|
||||
};
|
||||
|
||||
|
||||
@@ -597,7 +597,453 @@ function startLifecycleRuntime() {
|
||||
});
|
||||
}
|
||||
|
||||
function codexTokenUsageEvent(input: {
|
||||
readonly id: string;
|
||||
readonly turnId: string;
|
||||
readonly inputTokens: number;
|
||||
readonly cachedInputTokens: number;
|
||||
readonly cacheCreationTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly reasoningTokens: number;
|
||||
readonly last?: {
|
||||
readonly inputTokens: number;
|
||||
readonly cachedInputTokens: number;
|
||||
readonly cacheCreationTokens: number;
|
||||
readonly outputTokens: number;
|
||||
readonly reasoningTokens: number;
|
||||
};
|
||||
}): ProviderEvent {
|
||||
const totalTokens = input.inputTokens + input.outputTokens;
|
||||
const last = input.last ?? input;
|
||||
return {
|
||||
id: asEventId(input.id),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId(input.turnId),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "thread/tokenUsage/updated",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: input.turnId,
|
||||
tokenUsage: {
|
||||
total: {
|
||||
inputTokens: input.inputTokens,
|
||||
cachedInputTokens: input.cachedInputTokens,
|
||||
cacheWriteInputTokens: input.cacheCreationTokens,
|
||||
outputTokens: input.outputTokens,
|
||||
reasoningOutputTokens: input.reasoningTokens,
|
||||
totalTokens,
|
||||
},
|
||||
last: {
|
||||
inputTokens: last.inputTokens,
|
||||
cachedInputTokens: last.cachedInputTokens,
|
||||
cacheWriteInputTokens: last.cacheCreationTokens,
|
||||
outputTokens: last.outputTokens,
|
||||
reasoningOutputTokens: last.reasoningTokens,
|
||||
totalTokens: last.inputTokens + last.outputTokens,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function codexTurnEvent(method: "turn/started" | "turn/completed", turnId: string): ProviderEvent {
|
||||
return {
|
||||
id: asEventId(`evt-${method}-${turnId}`),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId(turnId),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method,
|
||||
payload:
|
||||
method === "turn/started"
|
||||
? {}
|
||||
: {
|
||||
threadId: "thread-1",
|
||||
turn: { id: turnId, items: [], status: "completed" },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
it.effect("calculates one Codex turn total from cumulative counters", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-usage"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-usage-1",
|
||||
turnId: "turn-usage",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 40,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 8,
|
||||
}),
|
||||
);
|
||||
// Codex can repeat both notifications without new work.
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-usage"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-usage-duplicate",
|
||||
turnId: "turn-usage",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 40,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 8,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit({
|
||||
id: asEventId("evt-collab-activity"),
|
||||
kind: "notification",
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-usage"),
|
||||
createdAt: "2026-01-01T00:00:00.000Z",
|
||||
method: "collabAgent/activity",
|
||||
payload: {
|
||||
agentThreadId: "child-1",
|
||||
agentPath: "/root/child-1",
|
||||
activityKind: "started",
|
||||
},
|
||||
});
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-usage-2",
|
||||
turnId: "turn-usage",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 60,
|
||||
cacheCreationTokens: 15,
|
||||
outputTokens: 30,
|
||||
reasoningTokens: 12,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-usage"));
|
||||
|
||||
const completed = yield* Fiber.join(completedFiber);
|
||||
NodeAssert.equal(completed._tag, "Some");
|
||||
if (completed._tag === "Some" && completed.value.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(completed.value.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 60,
|
||||
cacheCreationTokens: 15,
|
||||
outputTokens: 30,
|
||||
reasoningTokens: 12,
|
||||
hasSubagents: true,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not charge a late prior-turn update to the next Codex turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-first"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-late-1",
|
||||
turnId: "turn-first",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 40,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 8,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-first"));
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-second"));
|
||||
// A late update for the finished turn lands after the next turn starts.
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-late-2",
|
||||
turnId: "turn-first",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 60,
|
||||
cacheCreationTokens: 15,
|
||||
outputTokens: 30,
|
||||
reasoningTokens: 12,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-late-3",
|
||||
turnId: "turn-second",
|
||||
inputTokens: 170,
|
||||
cachedInputTokens: 65,
|
||||
cacheCreationTokens: 16,
|
||||
outputTokens: 35,
|
||||
reasoningTokens: 14,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-second"));
|
||||
|
||||
const completed = Array.from(yield* Fiber.join(completedFiber));
|
||||
const second = completed[1];
|
||||
NodeAssert.equal(second?.type, "turn.completed");
|
||||
if (second?.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(second.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 20,
|
||||
cachedInputTokens: 5,
|
||||
cacheCreationTokens: 1,
|
||||
outputTokens: 5,
|
||||
reasoningTokens: 2,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("clamps Codex cache and reasoning subsets to their totals", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-clamp"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-clamp-1",
|
||||
turnId: "turn-clamp",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 140,
|
||||
cacheCreationTokens: 120,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 30,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-clamp"));
|
||||
|
||||
const completed = yield* Fiber.join(completedFiber);
|
||||
NodeAssert.equal(completed._tag, "Some");
|
||||
if (completed._tag === "Some" && completed.value.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(completed.value.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 100,
|
||||
cacheCreationTokens: 100,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 20,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("counts the last response when Codex resets its running total mid-turn", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-reset"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-reset-1",
|
||||
turnId: "turn-reset",
|
||||
inputTokens: 5_000,
|
||||
cachedInputTokens: 4_000,
|
||||
cacheCreationTokens: 100,
|
||||
outputTokens: 500,
|
||||
reasoningTokens: 200,
|
||||
last: {
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 80,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 8,
|
||||
},
|
||||
}),
|
||||
);
|
||||
// Codex restarted its cumulative total. The new total is smaller than
|
||||
// the previous one, so only `last` is counted for this update.
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-reset-2",
|
||||
turnId: "turn-reset",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 90,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 30,
|
||||
reasoningTokens: 12,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-reset"));
|
||||
|
||||
const completed = yield* Fiber.join(completedFiber);
|
||||
NodeAssert.equal(completed._tag, "Some");
|
||||
if (completed._tag === "Some" && completed.value.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(completed.value.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 250,
|
||||
cachedInputTokens: 170,
|
||||
cacheCreationTokens: 15,
|
||||
outputTokens: 50,
|
||||
reasoningTokens: 20,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("uses the last response usage when no prior Codex total exists", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("codex"),
|
||||
threadId: asThreadId("thread-1"),
|
||||
resumeCursor: { threadId: "provider-thread-1" },
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const runtime = lifecycleRuntimeFactory.lastRuntime;
|
||||
NodeAssert.ok(runtime);
|
||||
const firstCompletionsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
// Resumed thread: the cumulative total already holds old history, so the
|
||||
// first update must count only `last`.
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-resumed"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-resume-baseline",
|
||||
turnId: "turn-resumed",
|
||||
inputTokens: 1_000,
|
||||
cachedInputTokens: 400,
|
||||
cacheCreationTokens: 100,
|
||||
outputTokens: 200,
|
||||
reasoningTokens: 80,
|
||||
last: {
|
||||
inputTokens: 300,
|
||||
cachedInputTokens: 120,
|
||||
cacheCreationTokens: 30,
|
||||
outputTokens: 60,
|
||||
reasoningTokens: 24,
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-resumed"));
|
||||
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-after-resume"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-after-resume",
|
||||
turnId: "turn-after-resume",
|
||||
inputTokens: 1_100,
|
||||
cachedInputTokens: 440,
|
||||
cacheCreationTokens: 110,
|
||||
outputTokens: 220,
|
||||
reasoningTokens: 88,
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-after-resume"));
|
||||
|
||||
const firstCompletions = Array.from(yield* Fiber.join(firstCompletionsFiber));
|
||||
|
||||
yield* adapter.rollbackThread(asThreadId("thread-1"), 1);
|
||||
const rollbackCompletionFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
// Rollback drops the baseline and Codex shrinks its total, so the first
|
||||
// update after it counts only `last` again.
|
||||
yield* runtime.emit(codexTurnEvent("turn/started", "turn-after-rollback"));
|
||||
yield* runtime.emit(
|
||||
codexTokenUsageEvent({
|
||||
id: "evt-after-rollback",
|
||||
turnId: "turn-after-rollback",
|
||||
inputTokens: 1_050,
|
||||
cachedInputTokens: 420,
|
||||
cacheCreationTokens: 105,
|
||||
outputTokens: 210,
|
||||
reasoningTokens: 84,
|
||||
last: {
|
||||
inputTokens: 50,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 10,
|
||||
reasoningTokens: 4,
|
||||
},
|
||||
}),
|
||||
);
|
||||
yield* runtime.emit(codexTurnEvent("turn/completed", "turn-after-rollback"));
|
||||
|
||||
const rollbackCompletion = yield* Fiber.join(rollbackCompletionFiber);
|
||||
const completions = [
|
||||
...firstCompletions,
|
||||
...(rollbackCompletion._tag === "Some" ? [rollbackCompletion.value] : []),
|
||||
];
|
||||
NodeAssert.deepStrictEqual(
|
||||
completions.map((event) =>
|
||||
event.type === "turn.completed" ? event.payload.tokenUsage : undefined,
|
||||
),
|
||||
[
|
||||
{
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 300,
|
||||
cachedInputTokens: 120,
|
||||
cacheCreationTokens: 30,
|
||||
outputTokens: 60,
|
||||
reasoningTokens: 24,
|
||||
hasSubagents: false,
|
||||
},
|
||||
{
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 100,
|
||||
cachedInputTokens: 40,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 20,
|
||||
reasoningTokens: 8,
|
||||
hasSubagents: false,
|
||||
},
|
||||
{
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 50,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 10,
|
||||
reasoningTokens: 4,
|
||||
hasSubagents: false,
|
||||
},
|
||||
],
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("carries child model metadata through every task event", () =>
|
||||
Effect.gen(function* () {
|
||||
const { adapter, runtime } = yield* startLifecycleRuntime();
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
RuntimeRequestId,
|
||||
RuntimeTaskId,
|
||||
type RuntimeTaskUsage,
|
||||
type TurnTokenUsage,
|
||||
ProviderApprovalDecision,
|
||||
ThreadId,
|
||||
ProviderSendTurnInput,
|
||||
@@ -99,9 +100,34 @@ interface CodexAdapterSessionContext {
|
||||
readonly scope: Scope.Closeable;
|
||||
readonly runtime: CodexSessionRuntimeShape;
|
||||
readonly eventFiber: Fiber.Fiber<void, never>;
|
||||
readonly turnTokenUsage: CodexTurnTokenUsageState;
|
||||
stopped: boolean;
|
||||
}
|
||||
|
||||
type CodexCumulativeTokenUsage = {
|
||||
readonly inputTokens: number;
|
||||
readonly cachedInputTokens: number;
|
||||
readonly cacheCreationTokens?: number;
|
||||
readonly outputTokens: number;
|
||||
readonly reasoningTokens: number;
|
||||
};
|
||||
|
||||
interface CodexTurnTokenUsageAccumulator {
|
||||
inputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
cacheCreationTokens: number | undefined;
|
||||
outputTokens: number;
|
||||
reasoningTokens: number;
|
||||
observed: boolean;
|
||||
hasSubagents: boolean;
|
||||
}
|
||||
|
||||
interface CodexTurnTokenUsageState {
|
||||
baseline: CodexCumulativeTokenUsage | undefined;
|
||||
activeTurnId: string | undefined;
|
||||
readonly byTurnId: Map<string, CodexTurnTokenUsageAccumulator>;
|
||||
}
|
||||
|
||||
function mapCodexRuntimeError(
|
||||
threadId: ThreadId,
|
||||
method: string,
|
||||
@@ -429,6 +455,162 @@ function normalizeCodexTokenUsage(
|
||||
};
|
||||
}
|
||||
|
||||
function codexTokenUsageBreakdown(
|
||||
usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification__TokenUsageBreakdown,
|
||||
): CodexCumulativeTokenUsage {
|
||||
return {
|
||||
inputTokens: usage.inputTokens,
|
||||
cachedInputTokens: usage.cachedInputTokens,
|
||||
...(usage.cacheWriteInputTokens !== undefined
|
||||
? { cacheCreationTokens: usage.cacheWriteInputTokens }
|
||||
: {}),
|
||||
outputTokens: usage.outputTokens,
|
||||
reasoningTokens: usage.reasoningOutputTokens,
|
||||
};
|
||||
}
|
||||
|
||||
function makeCodexTurnTokenUsageState(): CodexTurnTokenUsageState {
|
||||
return {
|
||||
baseline: undefined,
|
||||
activeTurnId: undefined,
|
||||
byTurnId: new Map(),
|
||||
};
|
||||
}
|
||||
|
||||
function getCodexTurnAccumulator(
|
||||
state: CodexTurnTokenUsageState,
|
||||
turnId: string,
|
||||
): CodexTurnTokenUsageAccumulator {
|
||||
const existing = state.byTurnId.get(turnId);
|
||||
if (existing) return existing;
|
||||
const created: CodexTurnTokenUsageAccumulator = {
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
observed: false,
|
||||
hasSubagents: false,
|
||||
};
|
||||
state.byTurnId.set(turnId, created);
|
||||
return created;
|
||||
}
|
||||
|
||||
/**
|
||||
* Usage added by one `thread/tokenUsage/updated` notification. Codex reports a
|
||||
* running `total` for the thread and `last`, the usage of the newest model
|
||||
* response. Within a turn the growth of `total` equals `last`. Without a prior
|
||||
* total (first update after resume or rollback), or when Codex reset the
|
||||
* running total, `last` is the delta.
|
||||
*/
|
||||
function codexTurnTokenUsageDelta(
|
||||
previous: CodexCumulativeTokenUsage | undefined,
|
||||
current: CodexCumulativeTokenUsage,
|
||||
last: CodexCumulativeTokenUsage,
|
||||
): CodexCumulativeTokenUsage {
|
||||
if (
|
||||
previous === undefined ||
|
||||
current.inputTokens < previous.inputTokens ||
|
||||
current.cachedInputTokens < previous.cachedInputTokens ||
|
||||
current.outputTokens < previous.outputTokens ||
|
||||
current.reasoningTokens < previous.reasoningTokens
|
||||
) {
|
||||
return last;
|
||||
}
|
||||
return {
|
||||
inputTokens: current.inputTokens - previous.inputTokens,
|
||||
cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,
|
||||
...(current.cacheCreationTokens !== undefined &&
|
||||
previous.cacheCreationTokens !== undefined &&
|
||||
current.cacheCreationTokens >= previous.cacheCreationTokens
|
||||
? { cacheCreationTokens: current.cacheCreationTokens - previous.cacheCreationTokens }
|
||||
: {}),
|
||||
outputTokens: current.outputTokens - previous.outputTokens,
|
||||
reasoningTokens: current.reasoningTokens - previous.reasoningTokens,
|
||||
};
|
||||
}
|
||||
|
||||
function accumulateCodexTurnTokenUsage(
|
||||
state: CodexTurnTokenUsageState,
|
||||
turnId: string,
|
||||
usage: EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification["tokenUsage"],
|
||||
): void {
|
||||
const current = codexTokenUsageBreakdown(usage.total);
|
||||
if (state.activeTurnId !== turnId) {
|
||||
// The total is thread-wide, so every update moves the baseline. A late
|
||||
// update for a finished turn is not counted toward the live turn.
|
||||
state.baseline = current;
|
||||
return;
|
||||
}
|
||||
|
||||
const accumulator = getCodexTurnAccumulator(state, turnId);
|
||||
const delta = codexTurnTokenUsageDelta(
|
||||
state.baseline,
|
||||
current,
|
||||
codexTokenUsageBreakdown(usage.last),
|
||||
);
|
||||
state.baseline = current;
|
||||
|
||||
if (
|
||||
delta.inputTokens > 0 ||
|
||||
delta.cachedInputTokens > 0 ||
|
||||
delta.outputTokens > 0 ||
|
||||
delta.reasoningTokens > 0
|
||||
) {
|
||||
accumulator.observed = true;
|
||||
}
|
||||
accumulator.inputTokens += delta.inputTokens;
|
||||
accumulator.cachedInputTokens += delta.cachedInputTokens;
|
||||
accumulator.outputTokens += delta.outputTokens;
|
||||
accumulator.reasoningTokens += delta.reasoningTokens;
|
||||
if (delta.cacheCreationTokens === undefined) {
|
||||
accumulator.cacheCreationTokens = undefined;
|
||||
} else if (accumulator.cacheCreationTokens !== undefined) {
|
||||
accumulator.cacheCreationTokens += delta.cacheCreationTokens;
|
||||
}
|
||||
}
|
||||
|
||||
function completeCodexTurnTokenUsage(
|
||||
state: CodexTurnTokenUsageState,
|
||||
turnId: string,
|
||||
completed: boolean,
|
||||
): TurnTokenUsage {
|
||||
const usage = state.byTurnId.get(turnId);
|
||||
state.byTurnId.delete(turnId);
|
||||
if (state.activeTurnId === turnId) state.activeTurnId = undefined;
|
||||
if (!usage) {
|
||||
return {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: false,
|
||||
};
|
||||
}
|
||||
|
||||
if (!usage.observed) {
|
||||
return {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: usage.hasSubagents,
|
||||
};
|
||||
}
|
||||
|
||||
// Codex counts cache reads and writes inside inputTokens. Clamp the
|
||||
// subsets so the record keeps the documented relationships even if a
|
||||
// counter drifts.
|
||||
return {
|
||||
usageStatus: completed ? "complete" : "partial",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: usage.inputTokens,
|
||||
cachedInputTokens: Math.min(usage.inputTokens, usage.cachedInputTokens),
|
||||
...(usage.cacheCreationTokens !== undefined
|
||||
? { cacheCreationTokens: Math.min(usage.inputTokens, usage.cacheCreationTokens) }
|
||||
: {}),
|
||||
outputTokens: usage.outputTokens,
|
||||
reasoningTokens: Math.min(usage.outputTokens, usage.reasoningTokens),
|
||||
hasSubagents: usage.hasSubagents,
|
||||
};
|
||||
}
|
||||
|
||||
function toTurnStatus(
|
||||
value: EffectCodexSchema.V2TurnCompletedNotification["turn"]["status"] | "cancelled",
|
||||
): "completed" | "failed" | "cancelled" | "interrupted" {
|
||||
@@ -2063,6 +2245,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
const turnTokenUsage = makeCodexTurnTokenUsageState();
|
||||
const sessionScope = yield* Scope.make("sequential");
|
||||
let sessionScopeTransferred = false;
|
||||
yield* Effect.addFinalizer(() =>
|
||||
@@ -2091,7 +2274,64 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
const eventFiber = yield* Stream.runForEach(runtime.events, (event) =>
|
||||
Effect.gen(function* () {
|
||||
yield* writeNativeEvent(event);
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId);
|
||||
if (event.method === "turn/started" && event.turnId) {
|
||||
if (turnTokenUsage.activeTurnId !== event.turnId) {
|
||||
turnTokenUsage.byTurnId.clear();
|
||||
turnTokenUsage.activeTurnId = event.turnId;
|
||||
getCodexTurnAccumulator(turnTokenUsage, event.turnId);
|
||||
}
|
||||
} else if (event.method === "thread/tokenUsage/updated") {
|
||||
const payload = readPayload(
|
||||
EffectCodexSchema.V2ThreadTokenUsageUpdatedNotification,
|
||||
event.payload,
|
||||
);
|
||||
if (payload) {
|
||||
accumulateCodexTurnTokenUsage(turnTokenUsage, payload.turnId, payload.tokenUsage);
|
||||
}
|
||||
} else if (turnTokenUsage.activeTurnId) {
|
||||
const collabPayload =
|
||||
typeof event.payload === "object" && event.payload !== null
|
||||
? (event.payload as Record<string, unknown>)
|
||||
: undefined;
|
||||
const isCollabSpawn =
|
||||
event.method === "collabAgent/started" ||
|
||||
(event.method === "collabAgent/activity" &&
|
||||
collabPayload?.activityKind === "started");
|
||||
if (isCollabSpawn && event.turnId === turnTokenUsage.activeTurnId) {
|
||||
getCodexTurnAccumulator(turnTokenUsage, turnTokenUsage.activeTurnId).hasSubagents =
|
||||
true;
|
||||
}
|
||||
}
|
||||
|
||||
const runtimeEvents = mapToRuntimeEvents(event, event.threadId).map((runtimeEvent) => {
|
||||
if (runtimeEvent.type === "turn.completed" && runtimeEvent.turnId) {
|
||||
return {
|
||||
...runtimeEvent,
|
||||
payload: {
|
||||
...runtimeEvent.payload,
|
||||
tokenUsage: completeCodexTurnTokenUsage(
|
||||
turnTokenUsage,
|
||||
String(runtimeEvent.turnId),
|
||||
runtimeEvent.payload.state === "completed",
|
||||
),
|
||||
},
|
||||
} satisfies ProviderRuntimeEvent;
|
||||
}
|
||||
if (runtimeEvent.type === "turn.aborted" && runtimeEvent.turnId) {
|
||||
return {
|
||||
...runtimeEvent,
|
||||
payload: {
|
||||
...runtimeEvent.payload,
|
||||
tokenUsage: completeCodexTurnTokenUsage(
|
||||
turnTokenUsage,
|
||||
String(runtimeEvent.turnId),
|
||||
false,
|
||||
),
|
||||
},
|
||||
} satisfies ProviderRuntimeEvent;
|
||||
}
|
||||
return runtimeEvent;
|
||||
});
|
||||
if (runtimeEvents.length === 0) {
|
||||
yield* Effect.logDebug("ignoring unhandled Codex provider event", {
|
||||
method: event.method,
|
||||
@@ -2129,6 +2369,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
scope: sessionScope,
|
||||
runtime,
|
||||
eventFiber,
|
||||
turnTokenUsage,
|
||||
stopped: false,
|
||||
});
|
||||
sessionScopeTransferred = true;
|
||||
@@ -2262,7 +2503,17 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
|
||||
}
|
||||
|
||||
return requireSession(threadId).pipe(
|
||||
Effect.flatMap((session) => session.runtime.rollbackThread(numTurns)),
|
||||
Effect.flatMap((session) =>
|
||||
session.runtime.rollbackThread(numTurns).pipe(
|
||||
Effect.tap(() =>
|
||||
Effect.sync(() => {
|
||||
session.turnTokenUsage.baseline = undefined;
|
||||
session.turnTokenUsage.activeTurnId = undefined;
|
||||
session.turnTokenUsage.byTurnId.clear();
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
Effect.mapError((cause) =>
|
||||
cause._tag === "ProviderAdapterSessionNotFoundError"
|
||||
? cause
|
||||
|
||||
@@ -3,6 +3,8 @@ import * as NodeServices from "@effect/platform-node/NodeServices";
|
||||
import { it } from "@effect/vitest";
|
||||
import * as Cause from "effect/Cause";
|
||||
import * as Context from "effect/Context";
|
||||
import * as Crypto from "effect/Crypto";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as Exit from "effect/Exit";
|
||||
import * as Fiber from "effect/Fiber";
|
||||
@@ -2086,6 +2088,557 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("marks subagents when a child is proven related by ancestry lookup", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-child-ancestry-usage");
|
||||
// The child's `session.created` event was missed. Only the ancestry
|
||||
// lookup can prove that `ses_child` belongs to this thread.
|
||||
runtimeMock.state.sessionParentById.set("ses_child", "http://127.0.0.1:9999/session");
|
||||
runtimeMock.state.sessionStatus = "busy";
|
||||
const busy = promiseWithResolvers<unknown>();
|
||||
const childPermission = promiseWithResolvers<unknown>();
|
||||
const idle = promiseWithResolvers<unknown>();
|
||||
runtimeMock.state.subscribedEvents = [busy.promise, childPermission.promise, idle.promise];
|
||||
|
||||
const eventsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
(event.type === "request.opened" || event.type === "turn.completed"),
|
||||
),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "approval-required",
|
||||
});
|
||||
const sendFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "Delegate to a child",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
busy.resolve({
|
||||
id: "evt-child-ancestry-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
yield* Fiber.join(sendFiber);
|
||||
|
||||
const requestOpened = promiseWithResolvers<void>();
|
||||
runtimeMock.state.sessionGetObserved = (sessionID) => {
|
||||
if (sessionID === "ses_child") requestOpened.resolve(undefined);
|
||||
};
|
||||
childPermission.resolve({
|
||||
id: "evt-child-ancestry-permission",
|
||||
type: "permission.asked",
|
||||
properties: permissionRequest("per_child_ancestry", "ses_child"),
|
||||
});
|
||||
yield* Effect.promise(() => requestOpened.promise);
|
||||
yield* Effect.yieldNow;
|
||||
runtimeMock.state.sessionStatus = "idle";
|
||||
idle.resolve({
|
||||
id: "evt-child-ancestry-idle",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "idle" },
|
||||
},
|
||||
});
|
||||
|
||||
const events = Array.from(yield* Fiber.join(eventsFiber).pipe(Effect.timeout("1 second")));
|
||||
NodeAssert.deepEqual(
|
||||
events.map((event) => event.type),
|
||||
["request.opened", "turn.completed"],
|
||||
);
|
||||
const completed = events[1];
|
||||
if (completed?.type === "turn.completed") {
|
||||
NodeAssert.deepEqual(completed.payload.tokenUsage, {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: true,
|
||||
});
|
||||
}
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("sums owned OpenCode step usage and marks unresolved usage partial", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-step-usage");
|
||||
const busy = promiseWithResolvers<unknown>();
|
||||
const firstStep = promiseWithResolvers<unknown>();
|
||||
const assistantMessage = promiseWithResolvers<unknown>();
|
||||
const duplicateStep = promiseWithResolvers<unknown>();
|
||||
const secondStep = promiseWithResolvers<unknown>();
|
||||
const unresolvedHeader = promiseWithResolvers<unknown>();
|
||||
const unresolvedStep = promiseWithResolvers<unknown>();
|
||||
const recoveredStep = promiseWithResolvers<unknown>();
|
||||
const recoveredIncompleteHeader = promiseWithResolvers<unknown>();
|
||||
const recoveredCompleteHeader = promiseWithResolvers<unknown>();
|
||||
const childSession = promiseWithResolvers<unknown>();
|
||||
const idle = promiseWithResolvers<unknown>();
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
busy.promise,
|
||||
firstStep.promise,
|
||||
assistantMessage.promise,
|
||||
duplicateStep.promise,
|
||||
secondStep.promise,
|
||||
unresolvedHeader.promise,
|
||||
unresolvedStep.promise,
|
||||
recoveredStep.promise,
|
||||
recoveredIncompleteHeader.promise,
|
||||
recoveredCompleteHeader.promise,
|
||||
childSession.promise,
|
||||
idle.promise,
|
||||
];
|
||||
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.threadId === threadId && event.type === "turn.completed"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
const sendFiber = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "Use two model steps",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
busy.resolve({
|
||||
id: "evt-step-usage-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
yield* Fiber.join(sendFiber);
|
||||
const promptMessageId = (runtimeMock.state.promptCalls[0] as { messageID: string }).messageID;
|
||||
|
||||
const stepPart = {
|
||||
id: "step-usage-1",
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
messageID: "assistant-step-usage-1",
|
||||
type: "step-finish",
|
||||
reason: "tool-calls",
|
||||
cost: 0,
|
||||
tokens: {
|
||||
input: 100,
|
||||
output: 20,
|
||||
reasoning: 5,
|
||||
cache: { read: 40, write: 10 },
|
||||
},
|
||||
} as const;
|
||||
firstStep.resolve({
|
||||
id: "evt-step-usage-1",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: stepPart,
|
||||
},
|
||||
});
|
||||
assistantMessage.resolve({
|
||||
id: "evt-step-usage-assistant",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-step-usage-1",
|
||||
role: "assistant",
|
||||
parentID: promptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
duplicateStep.resolve({
|
||||
id: "evt-step-usage-1-duplicate",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: stepPart,
|
||||
},
|
||||
});
|
||||
secondStep.resolve({
|
||||
id: "evt-step-usage-2",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
...stepPart,
|
||||
id: "step-usage-2",
|
||||
tokens: {
|
||||
input: 50,
|
||||
output: 10,
|
||||
reasoning: 2,
|
||||
cache: { read: 10, write: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
unresolvedHeader.resolve({
|
||||
id: "evt-step-usage-unresolved-header",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-step-usage-without-parent",
|
||||
role: "assistant",
|
||||
},
|
||||
},
|
||||
});
|
||||
unresolvedStep.resolve({
|
||||
id: "evt-step-usage-unresolved",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
...stepPart,
|
||||
id: "step-usage-unresolved",
|
||||
messageID: "assistant-step-usage-without-parent",
|
||||
tokens: {
|
||||
input: 1_000,
|
||||
output: 1_000,
|
||||
reasoning: 0,
|
||||
cache: { read: 0, write: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
recoveredStep.resolve({
|
||||
id: "evt-step-usage-recovered",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
...stepPart,
|
||||
id: "step-usage-recovered",
|
||||
messageID: "assistant-step-usage-recovered",
|
||||
tokens: {
|
||||
input: 30,
|
||||
output: 10,
|
||||
reasoning: 2,
|
||||
cache: { read: 5, write: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
recoveredIncompleteHeader.resolve({
|
||||
id: "evt-step-usage-recovered-incomplete-header",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-step-usage-recovered",
|
||||
role: "assistant",
|
||||
parentID: "",
|
||||
},
|
||||
},
|
||||
});
|
||||
recoveredCompleteHeader.resolve({
|
||||
id: "evt-step-usage-recovered-complete-header",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-step-usage-recovered",
|
||||
role: "assistant",
|
||||
parentID: promptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
childSession.resolve({
|
||||
id: "evt-step-usage-child",
|
||||
type: "session.created",
|
||||
properties: {
|
||||
info: {
|
||||
id: "child-step-usage",
|
||||
parentID: "http://127.0.0.1:9999/session",
|
||||
},
|
||||
},
|
||||
});
|
||||
idle.resolve({
|
||||
id: "evt-step-usage-idle",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "idle" },
|
||||
},
|
||||
});
|
||||
|
||||
const completed = yield* Fiber.join(completedFiber).pipe(Effect.timeout("1 second"));
|
||||
NodeAssert.equal(completed._tag, "Some");
|
||||
if (completed._tag === "Some" && completed.value.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(completed.value.payload.tokenUsage, {
|
||||
usageStatus: "partial",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 246,
|
||||
cachedInputTokens: 55,
|
||||
cacheCreationTokens: 11,
|
||||
outputTokens: 49,
|
||||
reasoningTokens: 9,
|
||||
hasSubagents: true,
|
||||
});
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("keeps the next turn usage while the prior completion is delayed", () =>
|
||||
Effect.gen(function* () {
|
||||
const threadId = asThreadId("thread-token-usage-terminal-handoff");
|
||||
const firstBusy = promiseWithResolvers<unknown>();
|
||||
const firstAssistantMessage = promiseWithResolvers<unknown>();
|
||||
const firstStep = promiseWithResolvers<unknown>();
|
||||
const firstIdle = promiseWithResolvers<unknown>();
|
||||
const secondBusy = promiseWithResolvers<unknown>();
|
||||
const secondAssistantMessage = promiseWithResolvers<unknown>();
|
||||
const secondStep = promiseWithResolvers<unknown>();
|
||||
const secondIdle = promiseWithResolvers<unknown>();
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
firstBusy.promise,
|
||||
firstAssistantMessage.promise,
|
||||
firstStep.promise,
|
||||
firstIdle.promise,
|
||||
secondBusy.promise,
|
||||
secondAssistantMessage.promise,
|
||||
secondStep.promise,
|
||||
secondIdle.promise,
|
||||
];
|
||||
|
||||
const firstStepWriteStarted = yield* Deferred.make<void>();
|
||||
const firstStepWriteRelease = yield* Deferred.make<void>();
|
||||
const terminalUuidStarted = yield* Deferred.make<void>();
|
||||
const terminalUuidRelease = yield* Deferred.make<void>();
|
||||
let blockFirstStepWrite = true;
|
||||
let blockNextUuid = false;
|
||||
const nodeCrypto = yield* Crypto.Crypto;
|
||||
const gatedCrypto = {
|
||||
...nodeCrypto,
|
||||
randomUUIDv4: Effect.suspend(() => {
|
||||
if (!blockNextUuid) return nodeCrypto.randomUUIDv4;
|
||||
blockNextUuid = false;
|
||||
return Deferred.succeed(terminalUuidStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(terminalUuidRelease)),
|
||||
Effect.andThen(nodeCrypto.randomUUIDv4),
|
||||
);
|
||||
}),
|
||||
} satisfies Crypto.Crypto;
|
||||
const adapter = yield* makeOpenCodeAdapter(openCodeAdapterTestSettings, {
|
||||
nativeEventLogger: {
|
||||
filePath: "memory://opencode-token-usage-terminal-handoff",
|
||||
write: (record) => {
|
||||
const eventType = (record as { event?: { type?: unknown } }).event?.type;
|
||||
if (blockFirstStepWrite && eventType === "message.part.updated") {
|
||||
blockFirstStepWrite = false;
|
||||
return Deferred.succeed(firstStepWriteStarted, undefined).pipe(
|
||||
Effect.andThen(Deferred.await(firstStepWriteRelease)),
|
||||
);
|
||||
}
|
||||
return Effect.void;
|
||||
},
|
||||
close: () => Effect.void,
|
||||
},
|
||||
}).pipe(Effect.provideService(Crypto.Crypto, gatedCrypto));
|
||||
|
||||
const completedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.threadId === threadId && event.type === "turn.completed"),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstSend = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "Run the first token handoff turn",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
firstBusy.resolve({
|
||||
id: "evt-token-handoff-first-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
const firstTurn = yield* Fiber.join(firstSend);
|
||||
const firstPromptMessageId = (runtimeMock.state.promptCalls[0] as { messageID: string })
|
||||
.messageID;
|
||||
firstAssistantMessage.resolve({
|
||||
id: "evt-token-handoff-first-assistant",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-token-handoff-first",
|
||||
role: "assistant",
|
||||
parentID: firstPromptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
firstStep.resolve({
|
||||
id: "evt-token-handoff-first-step",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
id: "step-token-handoff-first",
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
messageID: "assistant-token-handoff-first",
|
||||
type: "step-finish",
|
||||
reason: "stop",
|
||||
cost: 0,
|
||||
tokens: {
|
||||
input: 100,
|
||||
output: 20,
|
||||
reasoning: 5,
|
||||
cache: { read: 40, write: 10 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* Deferred.await(firstStepWriteStarted);
|
||||
blockNextUuid = true;
|
||||
firstIdle.resolve({
|
||||
id: "evt-token-handoff-first-idle",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "idle" },
|
||||
},
|
||||
});
|
||||
yield* Deferred.succeed(firstStepWriteRelease, undefined);
|
||||
yield* Deferred.await(terminalUuidStarted);
|
||||
|
||||
runtimeMock.state.sessionStatus = "busy";
|
||||
const secondTurn = yield* adapter.sendTurn({
|
||||
threadId,
|
||||
input: "Run the second token handoff turn",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
});
|
||||
NodeAssert.notEqual(secondTurn.turnId, firstTurn.turnId);
|
||||
const secondPromptMessageId = (runtimeMock.state.promptCalls[1] as { messageID: string })
|
||||
.messageID;
|
||||
yield* Deferred.succeed(terminalUuidRelease, undefined);
|
||||
|
||||
secondBusy.resolve({
|
||||
id: "evt-token-handoff-second-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
secondAssistantMessage.resolve({
|
||||
id: "evt-token-handoff-second-assistant",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-token-handoff-second",
|
||||
role: "assistant",
|
||||
parentID: secondPromptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
secondStep.resolve({
|
||||
id: "evt-token-handoff-second-step",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
id: "step-token-handoff-second",
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
messageID: "assistant-token-handoff-second",
|
||||
type: "step-finish",
|
||||
reason: "stop",
|
||||
cost: 0,
|
||||
tokens: {
|
||||
input: 90,
|
||||
output: 13,
|
||||
reasoning: 3,
|
||||
cache: { read: 20, write: 5 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
secondIdle.resolve({
|
||||
id: "evt-token-handoff-second-idle",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "idle" },
|
||||
},
|
||||
});
|
||||
|
||||
const completed = Array.from(
|
||||
yield* Fiber.join(completedFiber).pipe(Effect.timeout("1 second")),
|
||||
);
|
||||
NodeAssert.deepStrictEqual(
|
||||
completed.map((event) =>
|
||||
event.type === "turn.completed" ? event.payload.tokenUsage : undefined,
|
||||
),
|
||||
[
|
||||
{
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 150,
|
||||
cachedInputTokens: 40,
|
||||
cacheCreationTokens: 10,
|
||||
outputTokens: 25,
|
||||
reasoningTokens: 5,
|
||||
hasSubagents: false,
|
||||
},
|
||||
{
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 115,
|
||||
cachedInputTokens: 20,
|
||||
cacheCreationTokens: 5,
|
||||
outputTokens: 16,
|
||||
reasoningTokens: 3,
|
||||
hasSubagents: false,
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores a stale admission status response after the next turn starts", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
@@ -2203,6 +2756,188 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("ignores a late prior-turn step after the next prompt is admitted", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const threadId = asThreadId("thread-token-usage-late-prior-step");
|
||||
const firstBusy = promiseWithResolvers<unknown>();
|
||||
const firstAssistant = promiseWithResolvers<unknown>();
|
||||
const secondBusy = promiseWithResolvers<unknown>();
|
||||
const secondAssistant = promiseWithResolvers<unknown>();
|
||||
const lateFirstStep = promiseWithResolvers<unknown>();
|
||||
const secondStep = promiseWithResolvers<unknown>();
|
||||
const secondIdle = promiseWithResolvers<unknown>();
|
||||
runtimeMock.state.subscribedEvents = [
|
||||
firstBusy.promise,
|
||||
firstAssistant.promise,
|
||||
secondBusy.promise,
|
||||
secondAssistant.promise,
|
||||
lateFirstStep.promise,
|
||||
secondStep.promise,
|
||||
secondIdle.promise,
|
||||
];
|
||||
|
||||
const terminalsFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter(
|
||||
(event) =>
|
||||
event.threadId === threadId &&
|
||||
(event.type === "turn.aborted" || event.type === "turn.completed"),
|
||||
),
|
||||
Stream.take(2),
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId,
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
const firstSend = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "Start the interrupted turn",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
firstBusy.resolve({
|
||||
id: "evt-token-late-first-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
yield* Fiber.join(firstSend);
|
||||
const firstPromptMessageId = (runtimeMock.state.promptCalls[0] as { messageID: string })
|
||||
.messageID;
|
||||
firstAssistant.resolve({
|
||||
id: "evt-token-late-first-assistant",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-token-late-first",
|
||||
role: "assistant",
|
||||
parentID: firstPromptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
yield* Effect.yieldNow;
|
||||
yield* adapter.interruptTurn(threadId);
|
||||
|
||||
const secondSend = yield* adapter
|
||||
.sendTurn({
|
||||
threadId,
|
||||
input: "Start the next turn",
|
||||
modelSelection: createModelSelection(
|
||||
ProviderInstanceId.make("opencode"),
|
||||
"opencode/kimi-k3",
|
||||
),
|
||||
})
|
||||
.pipe(Effect.forkChild);
|
||||
while (runtimeMock.state.promptCalls.length < 2) {
|
||||
yield* Effect.yieldNow;
|
||||
}
|
||||
secondBusy.resolve({
|
||||
id: "evt-token-late-second-busy",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "busy" },
|
||||
},
|
||||
});
|
||||
yield* Fiber.join(secondSend);
|
||||
const secondPromptMessageId = (runtimeMock.state.promptCalls[1] as { messageID: string })
|
||||
.messageID;
|
||||
secondAssistant.resolve({
|
||||
id: "evt-token-late-second-assistant",
|
||||
type: "message.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
info: {
|
||||
id: "assistant-token-late-second",
|
||||
role: "assistant",
|
||||
parentID: secondPromptMessageId,
|
||||
},
|
||||
},
|
||||
});
|
||||
lateFirstStep.resolve({
|
||||
id: "evt-token-late-first-step",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
id: "step-token-late-first",
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
messageID: "assistant-token-late-first",
|
||||
type: "step-finish",
|
||||
reason: "stop",
|
||||
cost: 0,
|
||||
tokens: {
|
||||
input: 1_000,
|
||||
output: 1_000,
|
||||
reasoning: 0,
|
||||
cache: { read: 0, write: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
secondStep.resolve({
|
||||
id: "evt-token-late-second-step",
|
||||
type: "message.part.updated",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
part: {
|
||||
id: "step-token-late-second",
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
messageID: "assistant-token-late-second",
|
||||
type: "step-finish",
|
||||
reason: "stop",
|
||||
cost: 0,
|
||||
tokens: {
|
||||
input: 40,
|
||||
output: 10,
|
||||
reasoning: 2,
|
||||
cache: { read: 5, write: 1 },
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
secondIdle.resolve({
|
||||
id: "evt-token-late-second-idle",
|
||||
type: "session.status",
|
||||
properties: {
|
||||
sessionID: "http://127.0.0.1:9999/session",
|
||||
status: { type: "idle" },
|
||||
},
|
||||
});
|
||||
|
||||
const terminals = Array.from(
|
||||
yield* Fiber.join(terminalsFiber).pipe(Effect.timeout("1 second")),
|
||||
);
|
||||
const secondCompleted = terminals.find((event) => event.type === "turn.completed");
|
||||
NodeAssert.equal(secondCompleted?.type, "turn.completed");
|
||||
if (secondCompleted?.type === "turn.completed") {
|
||||
NodeAssert.deepStrictEqual(secondCompleted.payload.tokenUsage, {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: 46,
|
||||
cachedInputTokens: 5,
|
||||
cacheCreationTokens: 1,
|
||||
outputTokens: 12,
|
||||
reasoningTokens: 2,
|
||||
hasSubagents: false,
|
||||
});
|
||||
}
|
||||
|
||||
yield* adapter.stopSession(threadId);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reconciles a sole idle when the matching prompt echo arrives later", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
@@ -5432,6 +6167,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* OpenCodeAdapter;
|
||||
const startedFiber = yield* adapter.streamEvents.pipe(
|
||||
Stream.filter((event) => event.type === "turn.started"),
|
||||
Stream.runHead,
|
||||
Effect.forkChild,
|
||||
);
|
||||
yield* adapter.startSession({
|
||||
provider: ProviderDriverKind.make("opencode"),
|
||||
threadId: asThreadId("thread-custom-instance"),
|
||||
@@ -5470,6 +6210,11 @@ it.layer(OpenCodeAdapterTestLayer)("OpenCodeAdapterLive", (it) => {
|
||||
}),
|
||||
parts: [{ type: "text", text: "Fix it" }],
|
||||
});
|
||||
const started = yield* Fiber.join(startedFiber);
|
||||
NodeAssert.equal(started._tag, "Some");
|
||||
if (started._tag === "Some" && started.value.type === "turn.started") {
|
||||
NodeAssert.equal(started.value.payload.effort, undefined);
|
||||
}
|
||||
}).pipe(Effect.provide(adapterLayer));
|
||||
});
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
RuntimeRequestId,
|
||||
ThreadId,
|
||||
type ToolLifecycleItemType,
|
||||
type TurnTokenUsage,
|
||||
TurnId,
|
||||
type UserInputQuestion,
|
||||
} from "@t3tools/contracts";
|
||||
@@ -338,6 +339,7 @@ interface OpenCodeSessionContext {
|
||||
readonly partById: Map<string, Part>;
|
||||
readonly emittedTextByPartId: Map<string, string>;
|
||||
readonly completedAssistantPartIds: Set<string>;
|
||||
turnTokenUsage: OpenCodeTurnTokenUsageAccumulator | undefined;
|
||||
activeTurnId: TurnId | undefined;
|
||||
activeAgent: string | undefined;
|
||||
activeVariant: string | undefined;
|
||||
@@ -368,6 +370,75 @@ interface OpenCodeSessionContext {
|
||||
readonly sessionScope: Scope.Closeable;
|
||||
}
|
||||
|
||||
interface OpenCodeTurnTokenUsageAccumulator {
|
||||
readonly partIds: Set<string>;
|
||||
readonly promptMessageIds: Set<string>;
|
||||
readonly assistantOwnershipByMessageId: Map<string, "owned" | "other" | "unknown">;
|
||||
readonly unresolvedStepPartIds: Set<string>;
|
||||
inputTokens: number;
|
||||
cachedInputTokens: number;
|
||||
cacheCreationTokens: number;
|
||||
outputTokens: number;
|
||||
reasoningTokens: number;
|
||||
complete: boolean;
|
||||
hasSubagents: boolean;
|
||||
}
|
||||
|
||||
function makeOpenCodeTurnTokenUsageAccumulator(): OpenCodeTurnTokenUsageAccumulator {
|
||||
return {
|
||||
partIds: new Set(),
|
||||
promptMessageIds: new Set(),
|
||||
assistantOwnershipByMessageId: new Map(),
|
||||
unresolvedStepPartIds: new Set(),
|
||||
inputTokens: 0,
|
||||
cachedInputTokens: 0,
|
||||
cacheCreationTokens: 0,
|
||||
outputTokens: 0,
|
||||
reasoningTokens: 0,
|
||||
complete: true,
|
||||
hasSubagents: false,
|
||||
};
|
||||
}
|
||||
|
||||
function accumulateOpenCodeStepUsage(
|
||||
accumulator: OpenCodeTurnTokenUsageAccumulator,
|
||||
part: Extract<Part, { readonly type: "step-finish" }>,
|
||||
): void {
|
||||
if (accumulator.partIds.has(part.id)) return;
|
||||
accumulator.partIds.add(part.id);
|
||||
accumulator.inputTokens += part.tokens.input + part.tokens.cache.read + part.tokens.cache.write;
|
||||
accumulator.cachedInputTokens += part.tokens.cache.read;
|
||||
accumulator.cacheCreationTokens += part.tokens.cache.write;
|
||||
accumulator.outputTokens += part.tokens.output + part.tokens.reasoning;
|
||||
accumulator.reasoningTokens += part.tokens.reasoning;
|
||||
}
|
||||
|
||||
function takeOpenCodeTurnTokenUsage(
|
||||
context: OpenCodeSessionContext,
|
||||
complete: boolean,
|
||||
): TurnTokenUsage {
|
||||
const usage = context.turnTokenUsage;
|
||||
context.turnTokenUsage = undefined;
|
||||
if (!usage || usage.partIds.size === 0) {
|
||||
return {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: usage?.hasSubagents ?? false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
usageStatus:
|
||||
complete && usage.complete && usage.unresolvedStepPartIds.size === 0 ? "complete" : "partial",
|
||||
usageScope: "main_agent",
|
||||
inputTokens: usage.inputTokens,
|
||||
cachedInputTokens: usage.cachedInputTokens,
|
||||
cacheCreationTokens: usage.cacheCreationTokens,
|
||||
outputTokens: usage.outputTokens,
|
||||
reasoningTokens: Math.min(usage.outputTokens, usage.reasoningTokens),
|
||||
hasSubagents: usage.hasSubagents,
|
||||
};
|
||||
}
|
||||
|
||||
export interface OpenCodeAdapterLiveOptions {
|
||||
readonly instanceId?: ProviderInstanceId;
|
||||
readonly environment?: NodeJS.ProcessEnv;
|
||||
@@ -1032,6 +1103,7 @@ export function makeOpenCodeAdapter(
|
||||
) {
|
||||
context.pendingIdleReconciliation = undefined;
|
||||
}
|
||||
const tokenUsage = takeOpenCodeTurnTokenUsage(context, true);
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
@@ -1061,6 +1133,7 @@ export function makeOpenCodeAdapter(
|
||||
type: "turn.completed",
|
||||
payload: {
|
||||
state: "completed",
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
});
|
||||
@@ -1198,6 +1271,7 @@ export function makeOpenCodeAdapter(
|
||||
deleteContextIfCurrent(context);
|
||||
return;
|
||||
}
|
||||
const tokenUsage = takeOpenCodeTurnTokenUsage(context, false);
|
||||
context.promptAdmission = undefined;
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
@@ -1219,6 +1293,7 @@ export function makeOpenCodeAdapter(
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: detail,
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
yield* emit({
|
||||
@@ -1396,7 +1471,13 @@ export function makeOpenCodeAdapter(
|
||||
if (cancellation) {
|
||||
context.cancellation = undefined;
|
||||
}
|
||||
let tokenUsage: TurnTokenUsage = {
|
||||
usageStatus: "unavailable",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: false,
|
||||
};
|
||||
if (context.activeTurnId === turnId) {
|
||||
tokenUsage = takeOpenCodeTurnTokenUsage(context, false);
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
@@ -1416,6 +1497,7 @@ export function makeOpenCodeAdapter(
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: "Interrupted by user.",
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
if (cancellation) {
|
||||
@@ -1550,6 +1632,16 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
});
|
||||
|
||||
// Records a child session of this thread. A child seen during a live turn
|
||||
// means that turn used subagents, whether the relation came from a
|
||||
// `session.created` event or a later ancestry lookup after reconnect.
|
||||
const addRelatedOpenCodeSession = (context: OpenCodeSessionContext, sessionId: string) => {
|
||||
context.relatedSessionIds.add(sessionId);
|
||||
if (context.activeTurnId && context.turnTokenUsage) {
|
||||
context.turnTokenUsage.hasSubagents = true;
|
||||
}
|
||||
};
|
||||
|
||||
const isRelatedOpenCodeSession = Effect.fn("isRelatedOpenCodeSession")(function* (
|
||||
context: OpenCodeSessionContext,
|
||||
candidateSessionId: string,
|
||||
@@ -1581,7 +1673,7 @@ export function makeOpenCodeAdapter(
|
||||
let sessionId: string | undefined = candidateSessionId;
|
||||
for (let depth = 0; sessionId !== undefined && depth < 32; depth += 1) {
|
||||
if (context.relatedSessionIds.has(sessionId)) {
|
||||
context.relatedSessionIds.add(candidateSessionId);
|
||||
addRelatedOpenCodeSession(context, candidateSessionId);
|
||||
return true;
|
||||
}
|
||||
if (seen.has(sessionId)) {
|
||||
@@ -2078,6 +2170,9 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
yield* schedulePendingRequestRecovery(context);
|
||||
if (!isFirstConnection) {
|
||||
if (context.turnTokenUsage) {
|
||||
context.turnTokenUsage.complete = false;
|
||||
}
|
||||
yield* schedulePromptAdmissionRecovery(context, event);
|
||||
if (context.activeTurnId !== undefined && context.promptAdmission === undefined) {
|
||||
yield* scheduleIdleReconciliation(context, context.activeTurnId, event);
|
||||
@@ -2097,7 +2192,7 @@ export function makeOpenCodeAdapter(
|
||||
if (event.type === "session.created" || event.type === "session.updated") {
|
||||
const session = event.properties.info;
|
||||
if (session.parentID && context.relatedSessionIds.has(session.parentID)) {
|
||||
context.relatedSessionIds.add(session.id);
|
||||
addRelatedOpenCodeSession(context, session.id);
|
||||
}
|
||||
} else if (event.type === "session.deleted") {
|
||||
context.relatedSessionIds.delete(event.properties.info.id);
|
||||
@@ -2221,10 +2316,36 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
context.messageRoleById.set(event.properties.info.id, event.properties.info.role);
|
||||
if (event.properties.info.role === "assistant") {
|
||||
const usage = context.turnTokenUsage;
|
||||
const parentMessageId =
|
||||
typeof event.properties.info.parentID === "string" &&
|
||||
event.properties.info.parentID.trim().length > 0
|
||||
? event.properties.info.parentID
|
||||
: undefined;
|
||||
const observedOwnership =
|
||||
parentMessageId === undefined
|
||||
? "unknown"
|
||||
: usage?.promptMessageIds.has(parentMessageId)
|
||||
? "owned"
|
||||
: "other";
|
||||
const priorOwnership = usage?.assistantOwnershipByMessageId.get(
|
||||
event.properties.info.id,
|
||||
);
|
||||
const ownership =
|
||||
priorOwnership === undefined || priorOwnership === "unknown"
|
||||
? observedOwnership
|
||||
: priorOwnership;
|
||||
if (usage) {
|
||||
usage.assistantOwnershipByMessageId.set(event.properties.info.id, ownership);
|
||||
}
|
||||
for (const part of context.partById.values()) {
|
||||
if (part.messageID !== event.properties.info.id) {
|
||||
continue;
|
||||
}
|
||||
if (usage && part.type === "step-finish") {
|
||||
if (ownership !== "unknown") usage.unresolvedStepPartIds.delete(part.id);
|
||||
if (ownership === "owned") accumulateOpenCodeStepUsage(usage, part);
|
||||
}
|
||||
yield* emitAssistantTextDelta(context, part, turnId, event);
|
||||
}
|
||||
}
|
||||
@@ -2290,6 +2411,21 @@ export function makeOpenCodeAdapter(
|
||||
context.partById.set(part.id, part);
|
||||
const messageRole = messageRoleForPart(context, part);
|
||||
|
||||
if (turnId && part.type === "step-finish" && context.turnTokenUsage) {
|
||||
const ownership = context.turnTokenUsage.assistantOwnershipByMessageId.get(
|
||||
part.messageID,
|
||||
);
|
||||
if (ownership === "owned") {
|
||||
accumulateOpenCodeStepUsage(context.turnTokenUsage, part);
|
||||
} else if (
|
||||
ownership === "unknown" ||
|
||||
(ownership === undefined &&
|
||||
context.messageRoleById.get(part.messageID) !== "assistant")
|
||||
) {
|
||||
context.turnTokenUsage.unresolvedStepPartIds.add(part.id);
|
||||
}
|
||||
}
|
||||
|
||||
if (messageRole === "assistant") {
|
||||
yield* emitAssistantTextDelta(context, part, turnId, event);
|
||||
}
|
||||
@@ -2483,6 +2619,7 @@ export function makeOpenCodeAdapter(
|
||||
terminalCancellation.turnSettled = true;
|
||||
terminalCancellation.acknowledged = true;
|
||||
}
|
||||
const tokenUsage = activeTurnId ? takeOpenCodeTurnTokenUsage(context, false) : undefined;
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
context.activeVariant = undefined;
|
||||
@@ -2507,6 +2644,7 @@ export function makeOpenCodeAdapter(
|
||||
payload: {
|
||||
state: "failed",
|
||||
errorMessage: message,
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -2826,6 +2964,7 @@ export function makeOpenCodeAdapter(
|
||||
emittedTextByPartId: new Map(),
|
||||
messageRoleById: new Map(),
|
||||
completedAssistantPartIds: new Set(),
|
||||
turnTokenUsage: undefined,
|
||||
activeTurnId: undefined,
|
||||
activeAgent: undefined,
|
||||
activeVariant: undefined,
|
||||
@@ -2998,6 +3137,10 @@ export function makeOpenCodeAdapter(
|
||||
context.promptAdmission = promptAdmission;
|
||||
|
||||
context.activeTurnId = turnId;
|
||||
if (steeringTurnId === undefined) {
|
||||
context.turnTokenUsage = makeOpenCodeTurnTokenUsageAccumulator();
|
||||
}
|
||||
context.turnTokenUsage?.promptMessageIds.add(messageId);
|
||||
context.activeAgent = agent ?? (input.interactionMode === "plan" ? "plan" : undefined);
|
||||
context.activeVariant = variant;
|
||||
if (steeringTurnId === undefined) {
|
||||
@@ -3022,7 +3165,6 @@ export function makeOpenCodeAdapter(
|
||||
type: "turn.started",
|
||||
payload: {
|
||||
model: modelSelection?.model ?? context.session.model,
|
||||
...(variant ? { effort: variant } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -3087,6 +3229,7 @@ export function makeOpenCodeAdapter(
|
||||
}
|
||||
return;
|
||||
}
|
||||
const tokenUsage = takeOpenCodeTurnTokenUsage(context, false);
|
||||
context.promptAdmission = undefined;
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
@@ -3103,7 +3246,10 @@ export function makeOpenCodeAdapter(
|
||||
yield* emit({
|
||||
...(yield* buildEventBase({ threadId: input.threadId, turnId })),
|
||||
type: "turn.aborted",
|
||||
payload: { reason: requestError.detail },
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -3131,6 +3277,7 @@ export function makeOpenCodeAdapter(
|
||||
});
|
||||
return;
|
||||
}
|
||||
const tokenUsage = takeOpenCodeTurnTokenUsage(context, false);
|
||||
context.promptAdmission = undefined;
|
||||
context.activeTurnId = undefined;
|
||||
context.activeAgent = undefined;
|
||||
@@ -3154,6 +3301,7 @@ export function makeOpenCodeAdapter(
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: requestError.detail,
|
||||
tokenUsage,
|
||||
},
|
||||
});
|
||||
}),
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -31,6 +31,7 @@ import {
|
||||
} from "@t3tools/contracts";
|
||||
import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations";
|
||||
import { causeErrorTag } from "@t3tools/shared/observability";
|
||||
import { getModelSelectionStringOptionValue } from "@t3tools/shared/model";
|
||||
import * as DateTime from "effect/DateTime";
|
||||
import * as Deferred from "effect/Deferred";
|
||||
import * as Effect from "effect/Effect";
|
||||
@@ -96,6 +97,75 @@ export interface ProviderServiceLiveOptions {
|
||||
readonly revokeMcpCredential?: typeof McpSessionRegistry.revokeActiveMcpThread;
|
||||
}
|
||||
|
||||
interface TurnAnalyticsMetadata {
|
||||
readonly requestId: number;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly startedAtMs: number;
|
||||
readonly mixedModels: boolean;
|
||||
readonly model?: string;
|
||||
readonly effort?: string;
|
||||
readonly interactionMode?: string;
|
||||
readonly runtimeMode?: string;
|
||||
}
|
||||
|
||||
interface ActiveTurnAnalytics {
|
||||
readonly metadata: TurnAnalyticsMetadata;
|
||||
readonly requestAssociated: boolean;
|
||||
}
|
||||
|
||||
interface DeferredTurnAnalyticsCompletion {
|
||||
readonly completionKey: string;
|
||||
readonly completedAtMs: number;
|
||||
readonly terminalProperties: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
interface TurnAnalyticsSessionState {
|
||||
readonly pendingByRequestId: Map<number, TurnAnalyticsMetadata>;
|
||||
readonly activeByTurnId: Map<string, ActiveTurnAnalytics>;
|
||||
readonly deferredCompletionsByTurnId: Map<string, DeferredTurnAnalyticsCompletion>;
|
||||
}
|
||||
|
||||
interface TurnAnalyticsState {
|
||||
readonly sessions: Map<string, TurnAnalyticsSessionState>;
|
||||
readonly completedKeys: Set<string>;
|
||||
readonly completedOrder: Array<string>;
|
||||
}
|
||||
|
||||
const MAX_COMPLETED_TURN_ANALYTICS_KEYS = 512;
|
||||
const MAX_ACTIVE_TURN_ANALYTICS_PER_SESSION = 8;
|
||||
|
||||
function setActiveTurnAnalytics(
|
||||
session: TurnAnalyticsSessionState,
|
||||
turnId: string,
|
||||
active: ActiveTurnAnalytics,
|
||||
): void {
|
||||
session.activeByTurnId.set(turnId, active);
|
||||
while (session.activeByTurnId.size > MAX_ACTIVE_TURN_ANALYTICS_PER_SESSION) {
|
||||
const oldestTurnId = session.activeByTurnId.keys().next().value;
|
||||
if (oldestTurnId === undefined) return;
|
||||
session.activeByTurnId.delete(oldestTurnId);
|
||||
}
|
||||
}
|
||||
|
||||
function turnAnalyticsSessionKey(instanceId: ProviderInstanceId, threadId: ThreadId): string {
|
||||
return `${String(instanceId)}\u0000${String(threadId)}`;
|
||||
}
|
||||
|
||||
function turnAnalyticsCompletionKey(
|
||||
instanceId: ProviderInstanceId,
|
||||
threadId: ThreadId,
|
||||
turnId: string,
|
||||
): string {
|
||||
return `${turnAnalyticsSessionKey(instanceId, threadId)}\u0000${turnId}`;
|
||||
}
|
||||
|
||||
function turnEffort(modelSelection: ProviderSendTurnInput["modelSelection"]): string | undefined {
|
||||
return (
|
||||
getModelSelectionStringOptionValue(modelSelection, "reasoningEffort") ??
|
||||
getModelSelectionStringOptionValue(modelSelection, "effort")
|
||||
);
|
||||
}
|
||||
|
||||
type ProviderServiceMethod<Name extends keyof ProviderService.ProviderService["Service"]> =
|
||||
ProviderService.ProviderService["Service"][Name];
|
||||
|
||||
@@ -258,7 +328,366 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
yield* Deferred.succeed(pending.completion, terminal);
|
||||
return true;
|
||||
});
|
||||
const turnAnalytics = yield* Ref.make<TurnAnalyticsState>({
|
||||
sessions: new Map(),
|
||||
completedKeys: new Set(),
|
||||
completedOrder: [],
|
||||
});
|
||||
let turnAnalyticsRequestId = 0;
|
||||
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
|
||||
|
||||
const finishTurnAnalytics = (
|
||||
state: TurnAnalyticsState,
|
||||
input: {
|
||||
readonly sessionKey: string;
|
||||
readonly turnId: string;
|
||||
readonly completion: DeferredTurnAnalyticsCompletion;
|
||||
},
|
||||
): Readonly<Record<string, unknown>> | undefined => {
|
||||
if (state.completedKeys.has(input.completion.completionKey)) return undefined;
|
||||
state.completedKeys.add(input.completion.completionKey);
|
||||
state.completedOrder.push(input.completion.completionKey);
|
||||
while (state.completedOrder.length > MAX_COMPLETED_TURN_ANALYTICS_KEYS) {
|
||||
const expired = state.completedOrder.shift();
|
||||
if (expired) state.completedKeys.delete(expired);
|
||||
}
|
||||
|
||||
const session = state.sessions.get(input.sessionKey);
|
||||
const metadata = session?.activeByTurnId.get(input.turnId)?.metadata;
|
||||
session?.activeByTurnId.delete(input.turnId);
|
||||
session?.deferredCompletionsByTurnId.delete(input.turnId);
|
||||
if (
|
||||
session &&
|
||||
session.activeByTurnId.size === 0 &&
|
||||
session.pendingByRequestId.size === 0 &&
|
||||
session.deferredCompletionsByTurnId.size === 0
|
||||
) {
|
||||
state.sessions.delete(input.sessionKey);
|
||||
}
|
||||
|
||||
return {
|
||||
...input.completion.terminalProperties,
|
||||
...(metadata?.model ? { model: metadata.model } : {}),
|
||||
...(metadata?.effort ? { effort: metadata.effort } : {}),
|
||||
...(metadata?.interactionMode ? { interactionMode: metadata.interactionMode } : {}),
|
||||
...(metadata?.runtimeMode ? { runtimeMode: metadata.runtimeMode } : {}),
|
||||
...(metadata ? { mixedModels: metadata.mixedModels } : {}),
|
||||
...(metadata
|
||||
? { durationMs: Math.max(0, input.completion.completedAtMs - metadata.startedAtMs) }
|
||||
: {}),
|
||||
};
|
||||
};
|
||||
|
||||
const recordCompletedTurnProperties = (
|
||||
properties: ReadonlyArray<Readonly<Record<string, unknown>>>,
|
||||
) =>
|
||||
Effect.forEach(properties, (entry) => analytics.record("provider.turn.completed", entry), {
|
||||
discard: true,
|
||||
});
|
||||
|
||||
const clearTurnAnalyticsSession = (providerInstanceId: ProviderInstanceId, threadId: ThreadId) =>
|
||||
Effect.gen(function* () {
|
||||
const properties = yield* Ref.modify(turnAnalytics, (state) => {
|
||||
const sessionKey = turnAnalyticsSessionKey(providerInstanceId, threadId);
|
||||
const session = state.sessions.get(sessionKey);
|
||||
const completed: Array<Readonly<Record<string, unknown>>> = [];
|
||||
if (session) {
|
||||
for (const [turnId, completion] of session.deferredCompletionsByTurnId) {
|
||||
const entry = finishTurnAnalytics(state, { sessionKey, turnId, completion });
|
||||
if (entry) completed.push(entry);
|
||||
}
|
||||
}
|
||||
state.sessions.delete(sessionKey);
|
||||
return [completed, state] as const;
|
||||
});
|
||||
yield* recordCompletedTurnProperties(properties);
|
||||
});
|
||||
|
||||
const beginTurnAnalytics = Effect.fn("beginTurnAnalytics")(function* (input: {
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly provider: ProviderDriverKind;
|
||||
readonly threadId: ThreadId;
|
||||
readonly modelSelection: ProviderSendTurnInput["modelSelection"];
|
||||
readonly interactionMode: ProviderSendTurnInput["interactionMode"];
|
||||
readonly runtimeMode: string | undefined;
|
||||
}) {
|
||||
const startedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
turnAnalyticsRequestId += 1;
|
||||
const requestId = turnAnalyticsRequestId;
|
||||
const effort = turnEffort(input.modelSelection);
|
||||
return yield* Ref.modify(turnAnalytics, (state) => {
|
||||
const key = turnAnalyticsSessionKey(input.providerInstanceId, input.threadId);
|
||||
const session = state.sessions.get(key) ?? {
|
||||
pendingByRequestId: new Map(),
|
||||
activeByTurnId: new Map(),
|
||||
deferredCompletionsByTurnId: new Map(),
|
||||
};
|
||||
const metadata: TurnAnalyticsMetadata = {
|
||||
provider: input.provider,
|
||||
startedAtMs,
|
||||
mixedModels: false,
|
||||
requestId,
|
||||
...(input.modelSelection?.model ? { model: input.modelSelection.model } : {}),
|
||||
...(effort ? { effort } : {}),
|
||||
...(input.interactionMode ? { interactionMode: input.interactionMode } : {}),
|
||||
...(input.runtimeMode ? { runtimeMode: input.runtimeMode } : {}),
|
||||
};
|
||||
session.pendingByRequestId.set(requestId, metadata);
|
||||
state.sessions.set(key, session);
|
||||
return [metadata, state] as const;
|
||||
});
|
||||
});
|
||||
|
||||
const clearPendingTurnAnalytics = (input: {
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly requestId: number;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const properties = yield* Ref.modify(turnAnalytics, (state) => {
|
||||
const sessionKey = turnAnalyticsSessionKey(input.providerInstanceId, input.threadId);
|
||||
const session = state.sessions.get(sessionKey);
|
||||
if (!session)
|
||||
return [[] as ReadonlyArray<Readonly<Record<string, unknown>>>, state] as const;
|
||||
session.pendingByRequestId.delete(input.requestId);
|
||||
const completed: Array<Readonly<Record<string, unknown>>> = [];
|
||||
if (session.pendingByRequestId.size === 0) {
|
||||
for (const [turnId, completion] of session.deferredCompletionsByTurnId) {
|
||||
const entry = finishTurnAnalytics(state, { sessionKey, turnId, completion });
|
||||
if (entry) completed.push(entry);
|
||||
}
|
||||
}
|
||||
if (
|
||||
session.activeByTurnId.size === 0 &&
|
||||
session.pendingByRequestId.size === 0 &&
|
||||
session.deferredCompletionsByTurnId.size === 0
|
||||
) {
|
||||
state.sessions.delete(sessionKey);
|
||||
}
|
||||
return [completed, state] as const;
|
||||
});
|
||||
yield* recordCompletedTurnProperties(properties);
|
||||
});
|
||||
|
||||
const associateTurnAnalytics = (input: {
|
||||
readonly providerInstanceId: ProviderInstanceId;
|
||||
readonly threadId: ThreadId;
|
||||
readonly turnId: string;
|
||||
readonly metadata: TurnAnalyticsMetadata;
|
||||
}) =>
|
||||
Effect.gen(function* () {
|
||||
const properties = yield* Ref.modify(turnAnalytics, (state) => {
|
||||
const completionKey = turnAnalyticsCompletionKey(
|
||||
input.providerInstanceId,
|
||||
input.threadId,
|
||||
input.turnId,
|
||||
);
|
||||
const sessionKey = turnAnalyticsSessionKey(input.providerInstanceId, input.threadId);
|
||||
const session = state.sessions.get(sessionKey);
|
||||
if (!session || state.completedKeys.has(completionKey)) {
|
||||
if (session) {
|
||||
session.pendingByRequestId.delete(input.metadata.requestId);
|
||||
if (
|
||||
session.activeByTurnId.size === 0 &&
|
||||
session.pendingByRequestId.size === 0 &&
|
||||
session.deferredCompletionsByTurnId.size === 0
|
||||
) {
|
||||
state.sessions.delete(sessionKey);
|
||||
}
|
||||
}
|
||||
return [[] as ReadonlyArray<Readonly<Record<string, unknown>>>, state] as const;
|
||||
}
|
||||
const existing = session.activeByTurnId.get(input.turnId);
|
||||
const existingMetadata = existing?.metadata;
|
||||
const base = existing?.requestAssociated ? existing.metadata : input.metadata;
|
||||
setActiveTurnAnalytics(session, input.turnId, {
|
||||
requestAssociated: true,
|
||||
metadata: {
|
||||
...base,
|
||||
...(existingMetadata?.model
|
||||
? { model: existingMetadata.model }
|
||||
: input.metadata.model
|
||||
? { model: input.metadata.model }
|
||||
: {}),
|
||||
...(existingMetadata?.effort
|
||||
? { effort: existingMetadata.effort }
|
||||
: input.metadata.effort
|
||||
? { effort: input.metadata.effort }
|
||||
: {}),
|
||||
...(base?.interactionMode
|
||||
? {}
|
||||
: input.metadata.interactionMode
|
||||
? { interactionMode: input.metadata.interactionMode }
|
||||
: {}),
|
||||
...(base?.runtimeMode
|
||||
? {}
|
||||
: input.metadata.runtimeMode
|
||||
? { runtimeMode: input.metadata.runtimeMode }
|
||||
: {}),
|
||||
mixedModels: existingMetadata?.mixedModels ?? input.metadata.mixedModels,
|
||||
},
|
||||
});
|
||||
session.pendingByRequestId.delete(input.metadata.requestId);
|
||||
const completion = session.deferredCompletionsByTurnId.get(input.turnId);
|
||||
const completed = completion
|
||||
? finishTurnAnalytics(state, {
|
||||
sessionKey,
|
||||
turnId: input.turnId,
|
||||
completion,
|
||||
})
|
||||
: undefined;
|
||||
return [completed ? [completed] : [], state] as const;
|
||||
});
|
||||
yield* recordCompletedTurnProperties(properties);
|
||||
});
|
||||
|
||||
const observeTurnStartedForAnalytics = Effect.fn("observeTurnStartedForAnalytics")(function* (
|
||||
source: { readonly instanceId: ProviderInstanceId; readonly provider: ProviderDriverKind },
|
||||
event: Extract<ProviderRuntimeEvent, { readonly type: "turn.started" }>,
|
||||
) {
|
||||
if (!event.turnId) return;
|
||||
const observedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
yield* Ref.update(turnAnalytics, (state) => {
|
||||
const completionKey = turnAnalyticsCompletionKey(
|
||||
source.instanceId,
|
||||
event.threadId,
|
||||
String(event.turnId),
|
||||
);
|
||||
if (state.completedKeys.has(completionKey)) return state;
|
||||
const sessionKey = turnAnalyticsSessionKey(source.instanceId, event.threadId);
|
||||
const session = state.sessions.get(sessionKey) ?? {
|
||||
pendingByRequestId: new Map(),
|
||||
activeByTurnId: new Map(),
|
||||
deferredCompletionsByTurnId: new Map(),
|
||||
};
|
||||
// A start never binds send metadata on its own. Claude can start a
|
||||
// synthetic turn for leftover agent output while sendTurn is still
|
||||
// preparing the real turn, so only the adapter's sendTurn response
|
||||
// links a request to its turn. Completions that land before that
|
||||
// response wait in deferredCompletionsByTurnId.
|
||||
const current = session.activeByTurnId.get(String(event.turnId));
|
||||
const metadata: TurnAnalyticsMetadata = {
|
||||
...(current?.metadata ?? {
|
||||
requestId: ++turnAnalyticsRequestId,
|
||||
provider: source.provider,
|
||||
startedAtMs: observedAtMs,
|
||||
mixedModels: false,
|
||||
}),
|
||||
...(event.payload.model ? { model: event.payload.model } : {}),
|
||||
...(event.payload.effort ? { effort: event.payload.effort } : {}),
|
||||
};
|
||||
setActiveTurnAnalytics(session, String(event.turnId), {
|
||||
metadata,
|
||||
requestAssociated: current?.requestAssociated ?? false,
|
||||
});
|
||||
state.sessions.set(sessionKey, session);
|
||||
return state;
|
||||
});
|
||||
});
|
||||
|
||||
const observeModelReroutedForAnalytics = (
|
||||
source: { readonly instanceId: ProviderInstanceId },
|
||||
event: Extract<ProviderRuntimeEvent, { readonly type: "model.rerouted" }>,
|
||||
) =>
|
||||
Ref.update(turnAnalytics, (state) => {
|
||||
const session = state.sessions.get(
|
||||
turnAnalyticsSessionKey(source.instanceId, event.threadId),
|
||||
);
|
||||
if (!session) return state;
|
||||
if (event.turnId) {
|
||||
const current = session.activeByTurnId.get(String(event.turnId));
|
||||
if (current) {
|
||||
session.activeByTurnId.set(String(event.turnId), {
|
||||
...current,
|
||||
metadata: { ...current.metadata, mixedModels: true },
|
||||
});
|
||||
}
|
||||
} else {
|
||||
for (const [turnId, current] of session.activeByTurnId) {
|
||||
session.activeByTurnId.set(turnId, {
|
||||
...current,
|
||||
metadata: { ...current.metadata, mixedModels: true },
|
||||
});
|
||||
}
|
||||
}
|
||||
return state;
|
||||
});
|
||||
|
||||
const recordTurnCompletedAnalytics = Effect.fn("recordTurnCompletedAnalytics")(function* (
|
||||
source: { readonly instanceId: ProviderInstanceId; readonly provider: ProviderDriverKind },
|
||||
event: Extract<ProviderRuntimeEvent, { readonly type: "turn.completed" | "turn.aborted" }>,
|
||||
) {
|
||||
if (!event.turnId) return;
|
||||
const completedAtMs = DateTime.toEpochMillis(yield* DateTime.now);
|
||||
const tokenUsage = event.payload.tokenUsage;
|
||||
const completion: DeferredTurnAnalyticsCompletion = {
|
||||
completionKey: turnAnalyticsCompletionKey(
|
||||
source.instanceId,
|
||||
event.threadId,
|
||||
String(event.turnId),
|
||||
),
|
||||
completedAtMs,
|
||||
terminalProperties: {
|
||||
provider: source.provider,
|
||||
terminalStatus:
|
||||
event.type === "turn.completed"
|
||||
? event.payload.state
|
||||
: event.payload.reason.toLowerCase().includes("interrupt")
|
||||
? "interrupted"
|
||||
: "cancelled",
|
||||
usageStatus: tokenUsage?.usageStatus ?? "unavailable",
|
||||
usageScope: tokenUsage?.usageScope ?? "main_agent",
|
||||
...(tokenUsage ? { hasSubagents: tokenUsage.hasSubagents } : {}),
|
||||
...(tokenUsage?.inputTokens !== undefined ? { inputTokens: tokenUsage.inputTokens } : {}),
|
||||
...(tokenUsage?.cachedInputTokens !== undefined
|
||||
? { cachedInputTokens: tokenUsage.cachedInputTokens }
|
||||
: {}),
|
||||
...(tokenUsage?.cacheCreationTokens !== undefined
|
||||
? { cacheCreationTokens: tokenUsage.cacheCreationTokens }
|
||||
: {}),
|
||||
...(tokenUsage?.outputTokens !== undefined
|
||||
? { outputTokens: tokenUsage.outputTokens }
|
||||
: {}),
|
||||
...(tokenUsage?.reasoningTokens !== undefined
|
||||
? { reasoningTokens: tokenUsage.reasoningTokens }
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
const properties = yield* Ref.modify(turnAnalytics, (state) => {
|
||||
if (state.completedKeys.has(completion.completionKey)) {
|
||||
return [[] as ReadonlyArray<Readonly<Record<string, unknown>>>, state] as const;
|
||||
}
|
||||
const turnId = String(event.turnId);
|
||||
const sessionKey = turnAnalyticsSessionKey(source.instanceId, event.threadId);
|
||||
const session = state.sessions.get(sessionKey);
|
||||
if (session?.deferredCompletionsByTurnId.has(turnId)) {
|
||||
return [[] as ReadonlyArray<Readonly<Record<string, unknown>>>, state] as const;
|
||||
}
|
||||
const active = session?.activeByTurnId.get(turnId);
|
||||
const needsAssociation =
|
||||
(session?.pendingByRequestId.size ?? 0) > 0 && active?.requestAssociated !== true;
|
||||
if (!session || !needsAssociation) {
|
||||
const completed = finishTurnAnalytics(state, { sessionKey, turnId, completion });
|
||||
return [completed ? [completed] : [], state] as const;
|
||||
}
|
||||
|
||||
session.deferredCompletionsByTurnId.set(turnId, completion);
|
||||
const completed: Array<Readonly<Record<string, unknown>>> = [];
|
||||
while (session.deferredCompletionsByTurnId.size > MAX_ACTIVE_TURN_ANALYTICS_PER_SESSION) {
|
||||
const oldest = session.deferredCompletionsByTurnId.entries().next().value;
|
||||
if (!oldest) break;
|
||||
const [oldestTurnId, oldestCompletion] = oldest;
|
||||
const entry = finishTurnAnalytics(state, {
|
||||
sessionKey,
|
||||
turnId: oldestTurnId,
|
||||
completion: oldestCompletion,
|
||||
});
|
||||
if (entry) completed.push(entry);
|
||||
}
|
||||
return [completed, state] as const;
|
||||
});
|
||||
yield* recordCompletedTurnProperties(properties);
|
||||
});
|
||||
/**
|
||||
* Attach the `t3-code` MCP server to the session that is about to start.
|
||||
*
|
||||
@@ -437,6 +866,18 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
provider: canonicalEvent.provider,
|
||||
eventType: canonicalEvent.type,
|
||||
});
|
||||
if (canonicalEvent.type === "turn.started") {
|
||||
yield* observeTurnStartedForAnalytics(source, canonicalEvent);
|
||||
} else if (canonicalEvent.type === "model.rerouted") {
|
||||
yield* observeModelReroutedForAnalytics(source, canonicalEvent);
|
||||
} else if (
|
||||
canonicalEvent.type === "turn.completed" ||
|
||||
canonicalEvent.type === "turn.aborted"
|
||||
) {
|
||||
yield* recordTurnCompletedAnalytics(source, canonicalEvent);
|
||||
} else if (canonicalEvent.type === "session.exited") {
|
||||
yield* clearTurnAnalyticsSession(source.instanceId, canonicalEvent.threadId);
|
||||
}
|
||||
if (
|
||||
isCompactedEvent(canonicalEvent) &&
|
||||
timedOutNativeCompactions.delete(canonicalEvent.threadId)
|
||||
@@ -790,6 +1231,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
"provider.cwd.effective": effectiveCwd ?? "",
|
||||
});
|
||||
const adapter = yield* registry.getByInstance(resolvedInstanceId);
|
||||
yield* clearTurnAnalyticsSession(resolvedInstanceId, threadId);
|
||||
yield* prepareMcpSession(threadId, resolvedInstanceId);
|
||||
const session = yield* adapter
|
||||
.startSession({
|
||||
@@ -953,7 +1395,35 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
// rather than issuing a new one: sessions that go a long time between
|
||||
// browser tool calls used to lose the toolkit outright.
|
||||
yield* McpSessionRegistry.touchActiveMcpThread(input.threadId);
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
const analyticsModelSelection =
|
||||
input.modelSelection?.instanceId === routed.instanceId ? input.modelSelection : undefined;
|
||||
const turn = yield* Effect.acquireUseRelease(
|
||||
beginTurnAnalytics({
|
||||
providerInstanceId: routed.instanceId,
|
||||
provider: routed.adapter.provider,
|
||||
threadId: input.threadId,
|
||||
modelSelection: analyticsModelSelection,
|
||||
interactionMode: input.interactionMode,
|
||||
runtimeMode: routed.runtimeMode,
|
||||
}),
|
||||
(turnMetadata) =>
|
||||
Effect.gen(function* () {
|
||||
const turn = yield* routed.adapter.sendTurn(input);
|
||||
yield* associateTurnAnalytics({
|
||||
providerInstanceId: routed.instanceId,
|
||||
threadId: input.threadId,
|
||||
turnId: String(turn.turnId),
|
||||
metadata: turnMetadata,
|
||||
});
|
||||
return turn;
|
||||
}),
|
||||
(turnMetadata) =>
|
||||
clearPendingTurnAnalytics({
|
||||
providerInstanceId: routed.instanceId,
|
||||
threadId: input.threadId,
|
||||
requestId: turnMetadata.requestId,
|
||||
}),
|
||||
);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
provider: routed.adapter.provider,
|
||||
@@ -1254,6 +1724,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
yield* settleCompaction(input.threadId, pendingCompaction, "turn.aborted");
|
||||
}
|
||||
timedOutNativeCompactions.delete(input.threadId);
|
||||
yield* clearTurnAnalyticsSession(routed.instanceId, input.threadId);
|
||||
yield* clearMcpSession(input.threadId);
|
||||
yield* directory.upsert({
|
||||
threadId: input.threadId,
|
||||
@@ -1471,6 +1942,18 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
|
||||
);
|
||||
|
||||
const runStopAll = Effect.fn("runStopAll")(function* () {
|
||||
const properties = yield* Ref.modify(turnAnalytics, (state) => {
|
||||
const completed: Array<Readonly<Record<string, unknown>>> = [];
|
||||
for (const [sessionKey, session] of state.sessions) {
|
||||
for (const [turnId, completion] of session.deferredCompletionsByTurnId) {
|
||||
const entry = finishTurnAnalytics(state, { sessionKey, turnId, completion });
|
||||
if (entry) completed.push(entry);
|
||||
}
|
||||
}
|
||||
state.sessions.clear();
|
||||
return [completed, state] as const;
|
||||
});
|
||||
yield* recordCompletedTurnProperties(properties);
|
||||
const threadIds = yield* directory.listThreadIds();
|
||||
const currentAdapters = yield* getAdapterEntries;
|
||||
const activeSessions = yield* Effect.forEach(currentAdapters, ([instanceId, adapter]) =>
|
||||
|
||||
@@ -148,4 +148,47 @@ it.layer(NodeServices.layer)("AnalyticsService test", (it) => {
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("does not send batch requests when telemetry is disabled", () =>
|
||||
Effect.gen(function* () {
|
||||
const capturedPaths: Array<string> = [];
|
||||
const serverConfigLayer = ServerConfig.ServerConfig.layerTest(process.cwd(), {
|
||||
prefix: "t3-telemetry-disabled-",
|
||||
});
|
||||
const telemetryLayer = AnalyticsService.layer.pipe(Layer.provideMerge(serverConfigLayer));
|
||||
const configLayer = ConfigProvider.layer(
|
||||
ConfigProvider.fromUnknown({
|
||||
T3CODE_TELEMETRY_ENABLED: false,
|
||||
T3CODE_POSTHOG_KEY: "phc_test_key",
|
||||
T3CODE_POSTHOG_HOST: "http://localhost",
|
||||
}),
|
||||
);
|
||||
const batchServerLayer = HttpServer.serve(
|
||||
Effect.gen(function* () {
|
||||
const request = yield* HttpServerRequest.HttpServerRequest;
|
||||
capturedPaths.push(request.url);
|
||||
return HttpServerResponse.jsonUnsafe({});
|
||||
}),
|
||||
);
|
||||
const runtimeLayer = telemetryLayer.pipe(
|
||||
Layer.provide(configLayer),
|
||||
Layer.provide(
|
||||
Layer.mergeAll(
|
||||
Layer.succeed(HostProcessPlatform, "linux"),
|
||||
Layer.succeed(HostProcessArchitecture, "arm64"),
|
||||
),
|
||||
),
|
||||
Layer.provideMerge(NodeHttpServer.layerTest),
|
||||
);
|
||||
|
||||
yield* Effect.gen(function* () {
|
||||
yield* Layer.launch(batchServerLayer).pipe(Effect.forkScoped);
|
||||
const analytics = yield* AnalyticsService.AnalyticsService;
|
||||
yield* analytics.record("test.disabled", { index: 1 });
|
||||
yield* analytics.flush;
|
||||
}).pipe(Effect.provide(runtimeLayer));
|
||||
|
||||
assert.deepEqual(capturedPaths, []);
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -7,6 +7,7 @@
|
||||
- [Keyboard shortcuts](./user/keybindings.md)
|
||||
- [Organizing threads](./user/thread-sidebar.md)
|
||||
- [Review usage](./user/usage.md)
|
||||
- [Anonymous usage data](./user/telemetry.md)
|
||||
- [Customize a project icon](./user/project-settings.md)
|
||||
- [Mobile appearance](./user/mobile-appearance.md)
|
||||
- [Environment themes](./user/environment-theme.md)
|
||||
|
||||
@@ -23,6 +23,54 @@ time.
|
||||
client metadata because a provider turn can continue after the requesting
|
||||
client disconnects.
|
||||
|
||||
## Provider turn events
|
||||
|
||||
`provider.turn.completed` records one anonymous event when a provider emits a
|
||||
canonical completed or aborted turn. The event reports normalized main-agent
|
||||
token counts when the provider supplies enough data.
|
||||
|
||||
| Property | Values and meaning |
|
||||
| --------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `provider` | Provider driver, such as `codex`, `claudeAgent`, or `opencode`. Use this as the harness breakdown. |
|
||||
| `model` | Selected or provider-reported model when known. This is metadata, not proof that one model produced every token. |
|
||||
| `effort` | Selected or provider-reported reasoning effort when known. |
|
||||
| `interactionMode` | Turn interaction mode, `default` or `plan`, when known. |
|
||||
| `runtimeMode` | Session permission mode when known. |
|
||||
| `mixedModels` | `true` when T3 Code observed `model.rerouted` during the turn. This does not split token counts by model. |
|
||||
| `durationMs` | Time from the observed turn start or accepted send request to the terminal event. Omitted when start metadata is not available. |
|
||||
| `terminalStatus` | `completed`, `failed`, `interrupted`, or `cancelled`. |
|
||||
| `usageStatus` | `complete`, `partial`, or `unavailable`. |
|
||||
| `usageScope` | `main_agent`. Child-agent token use is not included. |
|
||||
| `hasSubagents` | Whether the adapter observed child agents during the turn. Omitted when the adapter does not provide a normalized usage report. |
|
||||
| `inputTokens` | Total main-agent input tokens. This includes uncached input, cache reads, and cache creation or writes. |
|
||||
| `cachedInputTokens` | Cache-read tokens. This is a subset of `inputTokens`. |
|
||||
| `cacheCreationTokens` | Cache creation or write tokens. This is a subset of `inputTokens`. |
|
||||
| `outputTokens` | Total main-agent output tokens, including reasoning tokens. |
|
||||
| `reasoningTokens` | Reasoning tokens when the provider reports them separately. This is a subset of `outputTokens`. |
|
||||
|
||||
`complete` means the provider supplied full input and output totals for the
|
||||
turn. `partial` means each included count is valid, but T3 Code did not observe
|
||||
the full turn. This can happen after an interruption, provider failure, or
|
||||
reconnect. `unavailable` means the provider did not supply trustworthy counts.
|
||||
Numeric properties are omitted when their values are unknown. They are not set
|
||||
to zero.
|
||||
|
||||
Codex uses deltas from its cumulative token totals, and falls back to the
|
||||
newest response's `last` usage when no prior total exists or the total was
|
||||
reset. Claude uses the final result's per-turn `usage` value and does not use
|
||||
cumulative `modelUsage`.
|
||||
OpenCode sums unique main-session step totals. Cursor, Grok, and Antigravity
|
||||
usage stays `unavailable` until their ACP token fields and scope are verified.
|
||||
|
||||
The completed event count does not have to match `provider.turn.sent`. For
|
||||
example, Claude can emit synthetic turns without a matching send request.
|
||||
Duplicate terminal events for the same provider instance, thread, and turn
|
||||
produce one analytics event.
|
||||
|
||||
Collection is best effort and starts with the first server release that
|
||||
contains this event. T3 Code does not scan provider history or backfill older
|
||||
turns.
|
||||
|
||||
## Recommended properties
|
||||
|
||||
Client properties appear on the three client events when the connected client
|
||||
@@ -94,6 +142,20 @@ In PostHog Data management, use the event and property descriptions from this
|
||||
document. Mark the recommended properties as verified. Keep `clientType`
|
||||
visible with its legacy description so old reports remain understandable.
|
||||
|
||||
Create a second saved dashboard named `Provider token efficiency`. Start each
|
||||
token insight with these filters:
|
||||
|
||||
- `usageStatus = complete`
|
||||
- `hasSubagents = false`
|
||||
- `mixedModels = false`
|
||||
|
||||
Break down input tokens, output tokens, and their ratio by `provider`. Compare
|
||||
the same `model`, `effort`, `interactionMode`, and `terminalStatus`. Without
|
||||
these filters, model choice, reasoning level, plan mode, failures, and child
|
||||
agents can look like harness differences. Keep separate views for median turn
|
||||
usage and aggregate `sum(outputTokens) / sum(inputTokens)`. Do not average each
|
||||
turn's ratio because small-input turns can dominate that result.
|
||||
|
||||
## Collection and release boundary
|
||||
|
||||
Client values are best effort. Invalid values are ignored and never reject a
|
||||
@@ -101,9 +163,12 @@ connection. Browser clients use user-agent data for broad OS, browser, phone,
|
||||
and tablet groups. They do not infer CPU architecture or an exact OS version
|
||||
from `navigator.platform`.
|
||||
|
||||
This change does not collect URLs, tokens, prompts, IP addresses, or
|
||||
user-assigned device names. It measures authenticated product use. It does not
|
||||
measure a person who visits the hosted app without connecting to a server.
|
||||
This change does not collect URLs, authentication tokens, prompts, IP
|
||||
addresses, or user-assigned device names. The token event does not include
|
||||
thread IDs, turn IDs, provider instance IDs, event IDs, request IDs, raw
|
||||
provider payloads, or child-agent output. It does not scan provider history on
|
||||
disk or start external work. It measures authenticated product use. It does
|
||||
not measure a person who visits the hosted app without connecting to a server.
|
||||
|
||||
The new fields start with the first client and server release that contains
|
||||
this metadata path. Historical events cannot reliably identify the client OS,
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
# Anonymous usage data
|
||||
|
||||
The T3 server sends anonymous product events to PostHog. These events include
|
||||
the provider, model, reasoning effort, permission mode, turn result, duration,
|
||||
and normalized main-agent token totals when the provider reports them.
|
||||
|
||||
T3 Code does not send prompts, responses, file contents, raw provider events,
|
||||
thread IDs, turn IDs, provider instance IDs, authentication tokens, or child
|
||||
agent output. Token totals can be complete, partial, or unavailable. Child
|
||||
agent token use is not included.
|
||||
|
||||
Set `T3CODE_TELEMETRY_ENABLED=false` before you start the T3 server to stop
|
||||
product events from being recorded or sent. The server still derives an
|
||||
anonymous identifier during startup and can create its local fallback
|
||||
identifier file.
|
||||
@@ -6,6 +6,52 @@ import { classifyTaskAgentKind, ProviderRuntimeEvent } from "./providerRuntime.t
|
||||
const decodeRuntimeEvent = Schema.decodeUnknownSync(ProviderRuntimeEvent);
|
||||
|
||||
describe("ProviderRuntimeEvent", () => {
|
||||
it("requires input and output totals for complete turn usage", () => {
|
||||
const completeEvent = {
|
||||
type: "turn.completed",
|
||||
eventId: "event-complete-usage",
|
||||
provider: "codex",
|
||||
createdAt: "2026-02-28T00:00:00.000Z",
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
payload: {
|
||||
state: "completed",
|
||||
tokenUsage: {
|
||||
usageStatus: "complete",
|
||||
usageScope: "main_agent",
|
||||
hasSubagents: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => decodeRuntimeEvent(completeEvent)).toThrow();
|
||||
expect(
|
||||
decodeRuntimeEvent({
|
||||
...completeEvent,
|
||||
payload: {
|
||||
...completeEvent.payload,
|
||||
tokenUsage: {
|
||||
...completeEvent.payload.tokenUsage,
|
||||
inputTokens: 10,
|
||||
outputTokens: 2,
|
||||
},
|
||||
},
|
||||
}).type,
|
||||
).toBe("turn.completed");
|
||||
expect(
|
||||
decodeRuntimeEvent({
|
||||
...completeEvent,
|
||||
payload: {
|
||||
...completeEvent.payload,
|
||||
tokenUsage: {
|
||||
...completeEvent.payload.tokenUsage,
|
||||
usageStatus: "partial",
|
||||
},
|
||||
},
|
||||
}).type,
|
||||
).toBe("turn.completed");
|
||||
});
|
||||
|
||||
it("accepts fork-provided driver kinds as branded slugs", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "session.started",
|
||||
|
||||
@@ -367,6 +367,35 @@ const TurnStartedPayload = Schema.Struct({
|
||||
});
|
||||
export type TurnStartedPayload = typeof TurnStartedPayload.Type;
|
||||
|
||||
/**
|
||||
* Normalized main-agent usage for one turn. Input includes cache reads and
|
||||
* writes. Output includes reasoning, and reasoningTokens is an optional subset.
|
||||
* Complete means the provider supplied full input and output totals. Partial
|
||||
* means every included count is valid, but the full turn total is not known.
|
||||
*/
|
||||
const TurnTokenUsageCommonFields = {
|
||||
usageScope: Schema.Literal("main_agent"),
|
||||
cachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
cacheCreationTokens: Schema.optional(NonNegativeInt),
|
||||
reasoningTokens: Schema.optional(NonNegativeInt),
|
||||
hasSubagents: Schema.Boolean,
|
||||
};
|
||||
export const TurnTokenUsage = Schema.Union([
|
||||
Schema.Struct({
|
||||
...TurnTokenUsageCommonFields,
|
||||
usageStatus: Schema.Literal("complete"),
|
||||
inputTokens: NonNegativeInt,
|
||||
outputTokens: NonNegativeInt,
|
||||
}),
|
||||
Schema.Struct({
|
||||
...TurnTokenUsageCommonFields,
|
||||
usageStatus: Schema.Literals(["partial", "unavailable"]),
|
||||
inputTokens: Schema.optional(NonNegativeInt),
|
||||
outputTokens: Schema.optional(NonNegativeInt),
|
||||
}),
|
||||
]);
|
||||
export type TurnTokenUsage = typeof TurnTokenUsage.Type;
|
||||
|
||||
const TurnCompletedPayload = Schema.Struct({
|
||||
state: RuntimeTurnState,
|
||||
stopReason: Schema.optional(Schema.NullOr(TrimmedNonEmptyStringSchema)),
|
||||
@@ -374,11 +403,13 @@ const TurnCompletedPayload = Schema.Struct({
|
||||
modelUsage: Schema.optional(UnknownRecordSchema),
|
||||
totalCostUsd: Schema.optional(Schema.Number),
|
||||
errorMessage: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
tokenUsage: Schema.optional(TurnTokenUsage),
|
||||
});
|
||||
export type TurnCompletedPayload = typeof TurnCompletedPayload.Type;
|
||||
|
||||
const TurnAbortedPayload = Schema.Struct({
|
||||
reason: TrimmedNonEmptyStringSchema,
|
||||
tokenUsage: Schema.optional(TurnTokenUsage),
|
||||
});
|
||||
export type TurnAbortedPayload = typeof TurnAbortedPayload.Type;
|
||||
|
||||
|
||||
Reference in new issue
Block a user