Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4e68e63de | ||
|
|
2ab0eb08a3 | ||
|
|
47470005c0 | ||
|
|
3c0e7fa7a3 | ||
|
|
ea69a017dd | ||
|
|
0cc49b27b7 | ||
|
|
b2a7fa3f44 |
No files matched your search
@@ -141,9 +141,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
'thread-1',
|
||||
'turn-1',
|
||||
'info',
|
||||
'runtime.note',
|
||||
'provider started',
|
||||
'{"stage":"start"}',
|
||||
'runtime.warning',
|
||||
'Runtime warning',
|
||||
'{"message":"provider started"}',
|
||||
'2026-02-24T00:00:06.000Z'
|
||||
)
|
||||
`;
|
||||
@@ -300,9 +300,9 @@ projectionSnapshotLayer("ProjectionSnapshotQuery", (it) => {
|
||||
{
|
||||
id: asEventId("activity-1"),
|
||||
tone: "info",
|
||||
kind: "runtime.note",
|
||||
summary: "provider started",
|
||||
payload: { stage: "start" },
|
||||
kind: "runtime.warning",
|
||||
summary: "Runtime warning",
|
||||
payload: { message: "provider started" },
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: "2026-02-24T00:00:06.000Z",
|
||||
},
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
OrchestrationCheckpointFile,
|
||||
OrchestrationProposedPlanId,
|
||||
OrchestrationReadModel,
|
||||
OrchestrationThreadActivity,
|
||||
ProjectScript,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
@@ -16,7 +17,6 @@ import {
|
||||
type OrchestrationProject,
|
||||
type OrchestrationSession,
|
||||
type OrchestrationThread,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { Effect, Layer, Schema, Struct } from "effect";
|
||||
import * as SqlClient from "effect/unstable/sql/SqlClient";
|
||||
@@ -454,16 +454,18 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
|
||||
for (const row of activityRows) {
|
||||
updatedAt = maxIso(updatedAt, row.createdAt);
|
||||
const threadActivities = activitiesByThread.get(row.threadId) ?? [];
|
||||
threadActivities.push({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
});
|
||||
threadActivities.push(
|
||||
Schema.decodeUnknownSync(OrchestrationThreadActivity)({
|
||||
id: row.activityId,
|
||||
tone: row.tone,
|
||||
kind: row.kind,
|
||||
summary: row.summary,
|
||||
payload: row.payload,
|
||||
turnId: row.turnId,
|
||||
...(row.sequence !== null ? { sequence: row.sequence } : {}),
|
||||
createdAt: row.createdAt,
|
||||
}),
|
||||
);
|
||||
activitiesByThread.set(row.threadId, threadActivities);
|
||||
}
|
||||
|
||||
|
||||
@@ -166,8 +166,7 @@ const make = Effect.gen(function* () {
|
||||
| "provider.turn.start.failed"
|
||||
| "provider.turn.interrupt.failed"
|
||||
| "provider.approval.respond.failed"
|
||||
| "provider.user-input.respond.failed"
|
||||
| "provider.session.stop.failed";
|
||||
| "provider.user-input.respond.failed";
|
||||
readonly summary: string;
|
||||
readonly detail: string;
|
||||
readonly turnId: TurnId | null;
|
||||
|
||||
@@ -1898,6 +1898,185 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
expect(checkpoint?.checkpointRef).toBe("provider-diff:evt-turn-diff-updated");
|
||||
});
|
||||
|
||||
it("projects context window updates into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
lastInputTokens: 1000,
|
||||
lastCachedInputTokens: 500,
|
||||
lastOutputTokens: 50,
|
||||
lastReasoningOutputTokens: 25,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity).toBeDefined();
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 1075,
|
||||
totalProcessedTokens: 10_200,
|
||||
maxTokens: 128_000,
|
||||
inputTokens: 1000,
|
||||
cachedInputTokens: 500,
|
||||
outputTokens: 50,
|
||||
reasoningOutputTokens: 25,
|
||||
lastUsedTokens: 1075,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Codex camelCase token usage payloads into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-camel"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastOutputTokens: 6,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects Claude usage snapshots with context window into normalized thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: asEventId("evt-thread-token-usage-updated-claude-window"),
|
||||
provider: "claudeAgent",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
},
|
||||
},
|
||||
raw: {
|
||||
source: "claude.sdk.message",
|
||||
method: "claude/result/success",
|
||||
payload: {},
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
),
|
||||
);
|
||||
|
||||
const usageActivity = thread.activities.find(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-window.updated",
|
||||
);
|
||||
expect(usageActivity?.payload).toMatchObject({
|
||||
usedTokens: 31_251,
|
||||
lastUsedTokens: 31_251,
|
||||
maxTokens: 200_000,
|
||||
toolUses: 25,
|
||||
durationMs: 43_567,
|
||||
});
|
||||
});
|
||||
|
||||
it("projects compacted thread state into context compaction activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
harness.emit({
|
||||
type: "thread.state.changed",
|
||||
eventId: asEventId("evt-thread-compacted"),
|
||||
provider: "codex",
|
||||
createdAt: now,
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
payload: {
|
||||
state: "compacted",
|
||||
detail: { source: "provider" },
|
||||
},
|
||||
});
|
||||
|
||||
const thread = await waitForThread(harness.engine, (entry) =>
|
||||
entry.activities.some(
|
||||
(activity: ProviderRuntimeTestActivity) => activity.kind === "context-compaction",
|
||||
),
|
||||
);
|
||||
|
||||
const activity = thread.activities.find(
|
||||
(candidate: ProviderRuntimeTestActivity) => candidate.kind === "context-compaction",
|
||||
);
|
||||
expect(activity?.summary).toBe("Context compacted");
|
||||
expect(activity?.tone).toBe("info");
|
||||
});
|
||||
|
||||
it("projects Codex task lifecycle chunks into thread activities", async () => {
|
||||
const harness = await createHarness();
|
||||
const now = new Date().toISOString();
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
CheckpointRef,
|
||||
isToolLifecycleItemType,
|
||||
ThreadId,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivity,
|
||||
type ProviderRuntimeEvent,
|
||||
@@ -101,6 +102,15 @@ function asString(value: unknown): string | undefined {
|
||||
return typeof value === "string" ? value : undefined;
|
||||
}
|
||||
|
||||
function buildContextWindowActivityPayload(
|
||||
event: ProviderRuntimeEvent,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (event.type !== "thread.token-usage.updated" || event.payload.usage.usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
return event.payload.usage;
|
||||
}
|
||||
|
||||
function runtimePayloadRecord(event: ProviderRuntimeEvent): Record<string, unknown> | undefined {
|
||||
const payload = (event as { payload?: unknown }).payload;
|
||||
if (!payload || typeof payload !== "object") {
|
||||
@@ -409,6 +419,48 @@ function runtimeEventToActivities(
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.state.changed": {
|
||||
if (event.payload.state !== "compacted") {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "context-compaction",
|
||||
summary: "Context compacted",
|
||||
payload: {
|
||||
state: event.payload.state,
|
||||
...(event.payload.detail !== undefined ? { detail: event.payload.detail } : {}),
|
||||
},
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "thread.token-usage.updated": {
|
||||
const payload = buildContextWindowActivityPayload(event);
|
||||
if (!payload) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
id: event.eventId,
|
||||
createdAt: event.createdAt,
|
||||
tone: "info",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
payload,
|
||||
turnId: toTurnId(event.turnId) ?? null,
|
||||
...maybeSequence,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
case "item.updated": {
|
||||
if (!isToolLifecycleItemType(event.payload.itemType)) {
|
||||
return [];
|
||||
|
||||
@@ -719,7 +719,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -885,7 +884,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1066,7 +1064,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1124,7 +1121,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
@@ -1132,7 +1128,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
],
|
||||
);
|
||||
|
||||
const turnCompleted = runtimeEvents[4];
|
||||
const turnCompleted = runtimeEvents.find((event) => event.type === "turn.completed");
|
||||
assert.equal(turnCompleted?.type, "turn.completed");
|
||||
if (turnCompleted?.type === "turn.completed") {
|
||||
assert.equal(String(turnCompleted.turnId), String(turn.turnId));
|
||||
@@ -1140,7 +1136,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(turnCompleted.payload.errorMessage, "Claude runtime interrupted.");
|
||||
}
|
||||
|
||||
const sessionExited = runtimeEvents[5];
|
||||
const sessionExited = runtimeEvents.find((event) => event.type === "session.exited");
|
||||
assert.equal(sessionExited?.type, "session.exited");
|
||||
|
||||
assert.equal(yield* adapter.hasSession(THREAD_ID), false);
|
||||
@@ -1158,7 +1154,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 5).pipe(
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
@@ -1200,6 +1196,127 @@ describe("ClaudeAdapterLive", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits thread token usage updates from Claude task progress", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 6).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "system",
|
||||
subtype: "task_progress",
|
||||
task_id: "task-usage-1",
|
||||
description: "Thinking through the patch",
|
||||
usage: {
|
||||
total_tokens: 321,
|
||||
tool_uses: 2,
|
||||
duration_ms: 654,
|
||||
},
|
||||
session_id: "sdk-session-task-usage",
|
||||
uuid: "task-usage-progress-1",
|
||||
} as unknown as SDKMessage);
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
const progressEvent = runtimeEvents.find((event) => event.type === "task.progress");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 321,
|
||||
lastUsedTokens: 321,
|
||||
toolUses: 2,
|
||||
durationMs: 654,
|
||||
},
|
||||
});
|
||||
}
|
||||
assert.equal(progressEvent?.type, "task.progress");
|
||||
if (usageEvent && progressEvent) {
|
||||
assert.notStrictEqual(usageEvent.eventId, progressEvent.eventId);
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect("emits Claude context window on result completion usage snapshots", () => {
|
||||
const harness = makeHarness();
|
||||
return Effect.gen(function* () {
|
||||
const adapter = yield* ClaudeAdapter;
|
||||
|
||||
const runtimeEventsFiber = yield* Stream.take(adapter.streamEvents, 7).pipe(
|
||||
Stream.runCollect,
|
||||
Effect.forkChild,
|
||||
);
|
||||
|
||||
yield* adapter.startSession({
|
||||
threadId: THREAD_ID,
|
||||
provider: "claudeAgent",
|
||||
runtimeMode: "full-access",
|
||||
});
|
||||
|
||||
yield* adapter.sendTurn({
|
||||
threadId: THREAD_ID,
|
||||
input: "hello",
|
||||
attachments: [],
|
||||
});
|
||||
|
||||
harness.query.emit({
|
||||
type: "result",
|
||||
subtype: "success",
|
||||
is_error: false,
|
||||
duration_ms: 1234,
|
||||
duration_api_ms: 1200,
|
||||
num_turns: 1,
|
||||
result: "done",
|
||||
stop_reason: "end_turn",
|
||||
session_id: "sdk-session-result-usage",
|
||||
usage: {
|
||||
input_tokens: 4,
|
||||
cache_creation_input_tokens: 2715,
|
||||
cache_read_input_tokens: 21144,
|
||||
output_tokens: 679,
|
||||
},
|
||||
modelUsage: {
|
||||
"claude-opus-4-6": {
|
||||
contextWindow: 200000,
|
||||
maxOutputTokens: 64000,
|
||||
},
|
||||
},
|
||||
} as unknown as SDKMessage);
|
||||
harness.query.finish();
|
||||
|
||||
const runtimeEvents = Array.from(yield* Fiber.join(runtimeEventsFiber));
|
||||
const usageEvent = runtimeEvents.find((event) => event.type === "thread.token-usage.updated");
|
||||
assert.equal(usageEvent?.type, "thread.token-usage.updated");
|
||||
if (usageEvent?.type === "thread.token-usage.updated") {
|
||||
assert.deepEqual(usageEvent.payload, {
|
||||
usage: {
|
||||
usedTokens: 24542,
|
||||
lastUsedTokens: 24542,
|
||||
inputTokens: 23863,
|
||||
outputTokens: 679,
|
||||
maxTokens: 200000,
|
||||
},
|
||||
});
|
||||
}
|
||||
}).pipe(
|
||||
Effect.provideService(Random.Random, makeDeterministicRandomService()),
|
||||
Effect.provide(harness.layer),
|
||||
);
|
||||
});
|
||||
|
||||
it.effect(
|
||||
"emits completion only after turn result when assistant frames arrive before deltas",
|
||||
() => {
|
||||
@@ -1266,7 +1383,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1411,7 +1527,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1419,6 +1534,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
"item.completed",
|
||||
"content.delta",
|
||||
"item.completed",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1506,7 +1622,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1694,7 +1809,6 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
@@ -1801,10 +1915,10 @@ describe("ClaudeAdapterLive", () => {
|
||||
runtimeEvents.map((event) => event.type),
|
||||
[
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"turn.started",
|
||||
"thread.started",
|
||||
"turn.completed",
|
||||
],
|
||||
);
|
||||
|
||||
@@ -1814,7 +1928,7 @@ describe("ClaudeAdapterLive", () => {
|
||||
assert.equal(sessionStarted.threadId, THREAD_ID);
|
||||
}
|
||||
|
||||
const threadStarted = runtimeEvents[4];
|
||||
const threadStarted = runtimeEvents.find((event) => event.type === "thread.started");
|
||||
assert.equal(threadStarted?.type, "thread.started");
|
||||
if (threadStarted?.type === "thread.started") {
|
||||
assert.equal(threadStarted.threadId, THREAD_ID);
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
type ProviderRuntimeTurnStatus,
|
||||
type ProviderSendTurnInput,
|
||||
type ProviderSession,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
type RuntimeContentStreamKind,
|
||||
RuntimeItemId,
|
||||
@@ -156,6 +157,7 @@ interface ClaudeSessionContext {
|
||||
}>;
|
||||
readonly inFlightTools: Map<number, ToolInFlight>;
|
||||
turnState: ClaudeTurnState | undefined;
|
||||
lastKnownContextWindow: number | undefined;
|
||||
lastAssistantUuid: string | undefined;
|
||||
lastThreadStartedId: string | undefined;
|
||||
stopped: boolean;
|
||||
@@ -259,6 +261,82 @@ function asRuntimeItemId(value: string): RuntimeItemId {
|
||||
return RuntimeItemId.makeUnsafe(value);
|
||||
}
|
||||
|
||||
function maxClaudeContextWindowFromModelUsage(modelUsage: unknown): number | undefined {
|
||||
if (!modelUsage || typeof modelUsage !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let maxContextWindow: number | undefined;
|
||||
for (const value of Object.values(modelUsage as Record<string, unknown>)) {
|
||||
if (!value || typeof value !== "object") {
|
||||
continue;
|
||||
}
|
||||
const contextWindow = (value as { contextWindow?: unknown }).contextWindow;
|
||||
if (
|
||||
typeof contextWindow !== "number" ||
|
||||
!Number.isFinite(contextWindow) ||
|
||||
contextWindow <= 0
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
maxContextWindow = Math.max(maxContextWindow ?? 0, contextWindow);
|
||||
}
|
||||
|
||||
return maxContextWindow;
|
||||
}
|
||||
|
||||
function normalizeClaudeTokenUsage(
|
||||
usage: unknown,
|
||||
contextWindow?: number,
|
||||
): ThreadTokenUsageSnapshot | undefined {
|
||||
if (!usage || typeof usage !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const record = usage as Record<string, unknown>;
|
||||
const directUsedTokens =
|
||||
typeof record.total_tokens === "number" && Number.isFinite(record.total_tokens)
|
||||
? record.total_tokens
|
||||
: undefined;
|
||||
const inputTokens =
|
||||
(typeof record.input_tokens === "number" && Number.isFinite(record.input_tokens)
|
||||
? record.input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_creation_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_creation_input_tokens)
|
||||
? record.cache_creation_input_tokens
|
||||
: 0) +
|
||||
(typeof record.cache_read_input_tokens === "number" &&
|
||||
Number.isFinite(record.cache_read_input_tokens)
|
||||
? record.cache_read_input_tokens
|
||||
: 0);
|
||||
const outputTokens =
|
||||
typeof record.output_tokens === "number" && Number.isFinite(record.output_tokens)
|
||||
? record.output_tokens
|
||||
: 0;
|
||||
const derivedUsedTokens = inputTokens + outputTokens;
|
||||
const usedTokens = directUsedTokens ?? (derivedUsedTokens > 0 ? derivedUsedTokens : undefined);
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
lastUsedTokens: usedTokens,
|
||||
...(inputTokens > 0 ? { inputTokens } : {}),
|
||||
...(outputTokens > 0 ? { outputTokens } : {}),
|
||||
...(typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0
|
||||
? { maxTokens: contextWindow }
|
||||
: {}),
|
||||
...(typeof record.tool_uses === "number" && Number.isFinite(record.tool_uses)
|
||||
? { toolUses: record.tool_uses }
|
||||
: {}),
|
||||
...(typeof record.duration_ms === "number" && Number.isFinite(record.duration_ms)
|
||||
? { durationMs: record.duration_ms }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
function asCanonicalTurnId(value: TurnId): TurnId {
|
||||
return value;
|
||||
}
|
||||
@@ -1287,8 +1365,34 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
result?: SDKResultMessage,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const resultUsage =
|
||||
result?.usage && typeof result.usage === "object" ? { ...result.usage } : undefined;
|
||||
const resultContextWindow = maxClaudeContextWindowFromModelUsage(result?.modelUsage);
|
||||
const usageSnapshot = normalizeClaudeTokenUsage(
|
||||
resultUsage,
|
||||
resultContextWindow ?? context.lastKnownContextWindow,
|
||||
);
|
||||
if (resultContextWindow !== undefined) {
|
||||
context.lastKnownContextWindow = resultContextWindow;
|
||||
}
|
||||
|
||||
const turnState = context.turnState;
|
||||
if (!turnState) {
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: {},
|
||||
});
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
@@ -1356,6 +1460,22 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
items: [...turnState.items],
|
||||
});
|
||||
|
||||
if (usageSnapshot) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: usageStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: usageStamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
turnId: turnState.turnId,
|
||||
payload: {
|
||||
usage: usageSnapshot,
|
||||
},
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
});
|
||||
}
|
||||
|
||||
const stamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "turn.completed",
|
||||
@@ -1846,15 +1966,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
};
|
||||
|
||||
switch (message.subtype) {
|
||||
case "init":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "session.configured",
|
||||
payload: {
|
||||
config: message as Record<string, unknown>,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "status":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -1876,43 +1987,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_started":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.started",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
hookName: message.hook_name,
|
||||
hookEvent: message.hook_event,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_progress":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.progress",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
output: message.output,
|
||||
stdout: message.stdout,
|
||||
stderr: message.stderr,
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "hook_response":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "hook.completed",
|
||||
payload: {
|
||||
hookId: message.hook_id,
|
||||
outcome: message.outcome,
|
||||
output: message.output,
|
||||
stdout: message.stdout,
|
||||
stderr: message.stderr,
|
||||
...(typeof message.exit_code === "number" ? { exitCode: message.exit_code } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "task_started":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
@@ -1925,6 +1999,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
return;
|
||||
case "task_progress":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.progress",
|
||||
@@ -1938,6 +2030,24 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
return;
|
||||
case "task_notification":
|
||||
if (message.usage) {
|
||||
const normalizedUsage = normalizeClaudeTokenUsage(
|
||||
message.usage,
|
||||
context.lastKnownContextWindow,
|
||||
);
|
||||
if (normalizedUsage) {
|
||||
const usageStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
eventId: usageStamp.eventId,
|
||||
createdAt: usageStamp.createdAt,
|
||||
type: "thread.token-usage.updated",
|
||||
payload: {
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "task.completed",
|
||||
@@ -1949,27 +2059,11 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
},
|
||||
});
|
||||
return;
|
||||
case "init":
|
||||
case "hook_started":
|
||||
case "hook_progress":
|
||||
case "hook_response":
|
||||
case "files_persisted":
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "files.persisted",
|
||||
payload: {
|
||||
files: Array.isArray(message.files)
|
||||
? message.files.map((file: { filename: string; file_id: string }) => ({
|
||||
filename: file.filename,
|
||||
fileId: file.file_id,
|
||||
}))
|
||||
: [],
|
||||
...(Array.isArray(message.failed)
|
||||
? {
|
||||
failed: message.failed.map((entry: { filename: string; error: string }) => ({
|
||||
filename: entry.filename,
|
||||
error: entry.error,
|
||||
})),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
default:
|
||||
yield* emitRuntimeWarning(
|
||||
@@ -1982,78 +2076,9 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
});
|
||||
|
||||
const handleSdkTelemetryMessage = (
|
||||
context: ClaudeSessionContext,
|
||||
message: SDKMessage,
|
||||
): Effect.Effect<void> =>
|
||||
Effect.gen(function* () {
|
||||
const stamp = yield* makeEventStamp();
|
||||
const base = {
|
||||
eventId: stamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: stamp.createdAt,
|
||||
threadId: context.session.threadId,
|
||||
...(context.turnState ? { turnId: asCanonicalTurnId(context.turnState.turnId) } : {}),
|
||||
providerRefs: nativeProviderRefs(context),
|
||||
raw: {
|
||||
source: "claude.sdk.message" as const,
|
||||
method: sdkNativeMethod(message),
|
||||
messageType: message.type,
|
||||
payload: message,
|
||||
},
|
||||
};
|
||||
|
||||
if (message.type === "tool_progress") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.progress",
|
||||
payload: {
|
||||
toolUseId: message.tool_use_id,
|
||||
toolName: message.tool_name,
|
||||
elapsedSeconds: message.elapsed_time_seconds,
|
||||
...(message.task_id ? { summary: `task:${message.task_id}` } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "tool_use_summary") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "tool.summary",
|
||||
payload: {
|
||||
summary: message.summary,
|
||||
...(message.preceding_tool_use_ids.length > 0
|
||||
? { precedingToolUseIds: message.preceding_tool_use_ids }
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "auth_status") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "auth.status",
|
||||
payload: {
|
||||
isAuthenticating: message.isAuthenticating,
|
||||
output: message.output,
|
||||
...(message.error ? { error: message.error } : {}),
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "rate_limit_event") {
|
||||
yield* offerRuntimeEvent({
|
||||
...base,
|
||||
type: "account.rate-limits.updated",
|
||||
payload: {
|
||||
rateLimits: message,
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
});
|
||||
_context: ClaudeSessionContext,
|
||||
_message: SDKMessage,
|
||||
): Effect.Effect<void> => Effect.void;
|
||||
|
||||
const handleSdkMessage = (
|
||||
context: ClaudeSessionContext,
|
||||
@@ -2634,6 +2659,7 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
turns: [],
|
||||
inFlightTools,
|
||||
turnState: undefined,
|
||||
lastKnownContextWindow: undefined,
|
||||
lastAssistantUuid: resumeState?.resumeSessionAt,
|
||||
lastThreadStartedId: undefined,
|
||||
stopped: false,
|
||||
@@ -2652,28 +2678,6 @@ function makeClaudeAdapter(options?: ClaudeAdapterLiveOptions) {
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
const configuredStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.configured",
|
||||
eventId: configuredStamp.eventId,
|
||||
provider: PROVIDER,
|
||||
createdAt: configuredStamp.createdAt,
|
||||
threadId,
|
||||
payload: {
|
||||
config: {
|
||||
...(input.model ? { model: input.model } : {}),
|
||||
...(input.cwd ? { cwd: input.cwd } : {}),
|
||||
...(effectiveEffort ? { effort: effectiveEffort } : {}),
|
||||
...(permissionMode ? { permissionMode } : {}),
|
||||
...(providerOptions?.maxThinkingTokens !== undefined
|
||||
? { maxThinkingTokens: providerOptions.maxThinkingTokens }
|
||||
: {}),
|
||||
...(fastMode ? { fastMode: true } : {}),
|
||||
},
|
||||
},
|
||||
providerRefs: {},
|
||||
});
|
||||
|
||||
const readyStamp = yield* makeEventStamp();
|
||||
yield* offerRuntimeEvent({
|
||||
type: "session.state.changed",
|
||||
|
||||
@@ -839,6 +839,70 @@ lifecycleLayer("CodexAdapterLive lifecycle", (it) => {
|
||||
assert.equal(firstEvent.value.payload.taskId, "turn-child");
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("unwraps Codex token usage payloads for context window events", () =>
|
||||
Effect.gen(function* () {
|
||||
const adapter = yield* CodexAdapter;
|
||||
const firstEventFiber = yield* Stream.runHead(adapter.streamEvents).pipe(Effect.forkChild);
|
||||
|
||||
lifecycleManager.emit("event", {
|
||||
id: asEventId("evt-codex-thread-token-usage-updated"),
|
||||
kind: "notification",
|
||||
provider: "codex",
|
||||
threadId: asThreadId("thread-1"),
|
||||
turnId: asTurnId("turn-1"),
|
||||
createdAt: new Date().toISOString(),
|
||||
method: "thread/tokenUsage/updated",
|
||||
payload: {
|
||||
threadId: "thread-1",
|
||||
turnId: "turn-1",
|
||||
tokenUsage: {
|
||||
total: {
|
||||
inputTokens: 11_833,
|
||||
cachedInputTokens: 3456,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 11_839,
|
||||
},
|
||||
last: {
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
totalTokens: 126,
|
||||
},
|
||||
modelContextWindow: 258_400,
|
||||
},
|
||||
},
|
||||
} satisfies ProviderEvent);
|
||||
|
||||
const firstEvent = yield* Fiber.join(firstEventFiber);
|
||||
assert.equal(firstEvent._tag, "Some");
|
||||
if (firstEvent._tag !== "Some") {
|
||||
return;
|
||||
}
|
||||
assert.equal(firstEvent.value.type, "thread.token-usage.updated");
|
||||
if (firstEvent.value.type !== "thread.token-usage.updated") {
|
||||
return;
|
||||
}
|
||||
|
||||
assert.deepEqual(firstEvent.value.payload.usage, {
|
||||
usedTokens: 126,
|
||||
totalProcessedTokens: 11_839,
|
||||
maxTokens: 258_400,
|
||||
inputTokens: 120,
|
||||
cachedInputTokens: 0,
|
||||
outputTokens: 6,
|
||||
reasoningOutputTokens: 0,
|
||||
lastUsedTokens: 126,
|
||||
lastInputTokens: 120,
|
||||
lastCachedInputTokens: 0,
|
||||
lastOutputTokens: 6,
|
||||
lastReasoningOutputTokens: 0,
|
||||
compactsAutomatically: true,
|
||||
});
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
afterAll(() => {
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
type CanonicalRequestType,
|
||||
type ProviderEvent,
|
||||
type ProviderRuntimeEvent,
|
||||
type ThreadTokenUsageSnapshot,
|
||||
type ProviderUserInputAnswers,
|
||||
RuntimeItemId,
|
||||
RuntimeRequestId,
|
||||
@@ -109,6 +110,48 @@ function asNumber(value: unknown): number | undefined {
|
||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function normalizeCodexTokenUsage(value: unknown): ThreadTokenUsageSnapshot | undefined {
|
||||
const usage = asObject(value);
|
||||
const totalUsage = asObject(usage?.total_token_usage ?? usage?.total);
|
||||
const lastUsage = asObject(usage?.last_token_usage ?? usage?.last);
|
||||
|
||||
const totalProcessedTokens =
|
||||
asNumber(totalUsage?.total_tokens) ?? asNumber(totalUsage?.totalTokens);
|
||||
const usedTokens =
|
||||
asNumber(lastUsage?.total_tokens) ?? asNumber(lastUsage?.totalTokens) ?? totalProcessedTokens;
|
||||
if (usedTokens === undefined || usedTokens <= 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const maxTokens = asNumber(usage?.model_context_window) ?? asNumber(usage?.modelContextWindow);
|
||||
const inputTokens = asNumber(lastUsage?.input_tokens) ?? asNumber(lastUsage?.inputTokens);
|
||||
const cachedInputTokens =
|
||||
asNumber(lastUsage?.cached_input_tokens) ?? asNumber(lastUsage?.cachedInputTokens);
|
||||
const outputTokens = asNumber(lastUsage?.output_tokens) ?? asNumber(lastUsage?.outputTokens);
|
||||
const reasoningOutputTokens =
|
||||
asNumber(lastUsage?.reasoning_output_tokens) ?? asNumber(lastUsage?.reasoningOutputTokens);
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
...(totalProcessedTokens !== undefined && totalProcessedTokens > usedTokens
|
||||
? { totalProcessedTokens }
|
||||
: {}),
|
||||
...(maxTokens !== undefined ? { maxTokens } : {}),
|
||||
...(inputTokens !== undefined ? { inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined ? { reasoningOutputTokens } : {}),
|
||||
...(usedTokens !== undefined ? { lastUsedTokens: usedTokens } : {}),
|
||||
...(inputTokens !== undefined ? { lastInputTokens: inputTokens } : {}),
|
||||
...(cachedInputTokens !== undefined ? { lastCachedInputTokens: cachedInputTokens } : {}),
|
||||
...(outputTokens !== undefined ? { lastOutputTokens: outputTokens } : {}),
|
||||
...(reasoningOutputTokens !== undefined
|
||||
? { lastReasoningOutputTokens: reasoningOutputTokens }
|
||||
: {}),
|
||||
compactsAutomatically: true,
|
||||
};
|
||||
}
|
||||
|
||||
function toTurnId(value: string | undefined): TurnId | undefined {
|
||||
return value?.trim() ? TurnId.makeUnsafe(value) : undefined;
|
||||
}
|
||||
@@ -708,12 +751,17 @@ function mapToRuntimeEvents(
|
||||
}
|
||||
|
||||
if (event.method === "thread/tokenUsage/updated") {
|
||||
const tokenUsage = asObject(payload?.tokenUsage);
|
||||
const normalizedUsage = normalizeCodexTokenUsage(tokenUsage ?? event.payload);
|
||||
if (!normalizedUsage) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
type: "thread.token-usage.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
usage: event.payload ?? {},
|
||||
usage: normalizedUsage,
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -757,18 +805,6 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "turn/aborted") {
|
||||
return [
|
||||
{
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
type: "turn.aborted",
|
||||
payload: {
|
||||
reason: event.message ?? "Turn aborted",
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "turn/plan/updated") {
|
||||
const steps = Array.isArray(payload?.plan) ? payload.plan : [];
|
||||
return [
|
||||
@@ -903,23 +939,6 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "item/mcpToolCall/progress") {
|
||||
return [
|
||||
{
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
type: "tool.progress",
|
||||
payload: {
|
||||
...(asString(payload?.toolUseId) ? { toolUseId: asString(payload?.toolUseId) } : {}),
|
||||
...(asString(payload?.toolName) ? { toolName: asString(payload?.toolName) } : {}),
|
||||
...(asString(payload?.summary) ? { summary: asString(payload?.summary) } : {}),
|
||||
...(asNumber(payload?.elapsedSeconds) !== undefined
|
||||
? { elapsedSeconds: asNumber(payload?.elapsedSeconds) }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "serverRequest/resolved") {
|
||||
const requestType =
|
||||
toRequestTypeFromResolvedPayload(payload) !== "unknown"
|
||||
@@ -1059,148 +1078,6 @@ function mapToRuntimeEvents(
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "model/rerouted") {
|
||||
return [
|
||||
{
|
||||
type: "model.rerouted",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
fromModel: asString(payload?.fromModel) ?? "unknown",
|
||||
toModel: asString(payload?.toModel) ?? "unknown",
|
||||
reason: asString(payload?.reason) ?? "unknown",
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "deprecationNotice") {
|
||||
return [
|
||||
{
|
||||
type: "deprecation.notice",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
summary: asString(payload?.summary) ?? "Deprecation notice",
|
||||
...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "configWarning") {
|
||||
return [
|
||||
{
|
||||
type: "config.warning",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
summary: asString(payload?.summary) ?? "Configuration warning",
|
||||
...(asString(payload?.details) ? { details: asString(payload?.details) } : {}),
|
||||
...(asString(payload?.path) ? { path: asString(payload?.path) } : {}),
|
||||
...(payload?.range !== undefined ? { range: payload.range } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "account/updated") {
|
||||
return [
|
||||
{
|
||||
type: "account.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
account: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "account/rateLimits/updated") {
|
||||
return [
|
||||
{
|
||||
type: "account.rate-limits.updated",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
rateLimits: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "mcpServer/oauthLogin/completed") {
|
||||
return [
|
||||
{
|
||||
type: "mcp.oauth.completed",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
success: payload?.success === true,
|
||||
...(asString(payload?.name) ? { name: asString(payload?.name) } : {}),
|
||||
...(asString(payload?.error) ? { error: asString(payload?.error) } : {}),
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/started") {
|
||||
const realtimeSessionId = asString(payload?.realtimeSessionId);
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.started",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
realtimeSessionId,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/itemAdded") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.item-added",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
item: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/outputAudio/delta") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.audio.delta",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
audio: event.payload ?? {},
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/error") {
|
||||
const message = asString(payload?.message) ?? event.message ?? "Realtime error";
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.error",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
message,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "thread/realtime/closed") {
|
||||
return [
|
||||
{
|
||||
type: "thread.realtime.closed",
|
||||
...runtimeEventBase(event, canonicalThreadId),
|
||||
payload: {
|
||||
reason: event.message,
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
if (event.method === "error") {
|
||||
const message =
|
||||
asString(asObject(payload?.error)?.message) ?? event.message ?? "Provider runtime error";
|
||||
|
||||
@@ -141,12 +141,14 @@ import {
|
||||
type TerminalContextDraft,
|
||||
type TerminalContextSelection,
|
||||
} from "../lib/terminalContext";
|
||||
import { deriveLatestContextWindowSnapshot } from "../lib/contextWindow";
|
||||
import { shouldUseCompactComposerFooter } from "./composerFooterLayout";
|
||||
import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore";
|
||||
import { ComposerPromptEditor, type ComposerPromptEditorHandle } from "./ComposerPromptEditor";
|
||||
import { PullRequestThreadDialog } from "./PullRequestThreadDialog";
|
||||
import { MessagesTimeline } from "./chat/MessagesTimeline";
|
||||
import { ChatHeader } from "./chat/ChatHeader";
|
||||
import { ContextWindowMeter } from "./chat/ContextWindowMeter";
|
||||
import { buildExpandedImagePreview, ExpandedImagePreview } from "./chat/ExpandedImagePreview";
|
||||
import { AVAILABLE_PROVIDER_OPTIONS, ProviderModelPicker } from "./chat/ProviderModelPicker";
|
||||
import { ComposerCommandItem, ComposerCommandMenu } from "./chat/ComposerCommandMenu";
|
||||
@@ -480,6 +482,10 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
const diffOpen = rawSearch.diff === "1";
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeLatestTurn = activeThread?.latestTurn ?? null;
|
||||
const activeContextWindow = useMemo(
|
||||
() => deriveLatestContextWindowSnapshot(activeThread?.activities ?? []),
|
||||
[activeThread?.activities],
|
||||
);
|
||||
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
|
||||
const activeProject = projects.find((p) => p.id === activeThread?.projectId);
|
||||
|
||||
@@ -3894,6 +3900,9 @@ export default function ChatView({ threadId }: ChatViewProps) {
|
||||
data-chat-composer-actions="right"
|
||||
className="flex shrink-0 items-center gap-2"
|
||||
>
|
||||
{activeContextWindow ? (
|
||||
<ContextWindowMeter usage={activeContextWindow} />
|
||||
) : null}
|
||||
{isPreparingWorktree ? (
|
||||
<span className="text-muted-foreground/70 text-xs">
|
||||
Preparing worktree...
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
import { type ContextWindowSnapshot, formatContextWindowTokens } from "~/lib/contextWindow";
|
||||
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
|
||||
|
||||
function formatPercentage(value: number | null): string | null {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return null;
|
||||
}
|
||||
if (value < 10) {
|
||||
return `${value.toFixed(1).replace(/\.0$/, "")}%`;
|
||||
}
|
||||
return `${Math.round(value)}%`;
|
||||
}
|
||||
|
||||
export function ContextWindowMeter(props: { usage: ContextWindowSnapshot }) {
|
||||
const { usage } = props;
|
||||
const usedPercentage = formatPercentage(usage.usedPercentage);
|
||||
const normalizedPercentage = Math.max(0, Math.min(100, usage.usedPercentage ?? 0));
|
||||
const radius = 9.75;
|
||||
const circumference = 2 * Math.PI * radius;
|
||||
const dashOffset = circumference - (normalizedPercentage / 100) * circumference;
|
||||
|
||||
return (
|
||||
<Popover>
|
||||
<PopoverTrigger
|
||||
openOnHover
|
||||
delay={150}
|
||||
closeDelay={0}
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="group inline-flex items-center justify-center rounded-full transition-opacity hover:opacity-85"
|
||||
aria-label={
|
||||
usage.maxTokens !== null && usedPercentage
|
||||
? `Context window ${usedPercentage} used`
|
||||
: `Context window ${formatContextWindowTokens(usage.usedTokens)} tokens used`
|
||||
}
|
||||
>
|
||||
<span className="relative flex h-6 w-6 items-center justify-center">
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
className="-rotate-90 absolute inset-0 h-full w-full transform-gpu"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="color-mix(in oklab, var(--color-muted) 70%, transparent)"
|
||||
strokeWidth="3"
|
||||
/>
|
||||
<circle
|
||||
cx="12"
|
||||
cy="12"
|
||||
r={radius}
|
||||
fill="none"
|
||||
stroke="var(--color-muted-foreground)"
|
||||
strokeWidth="3"
|
||||
strokeLinecap="round"
|
||||
strokeDasharray={circumference}
|
||||
strokeDashoffset={dashOffset}
|
||||
className="transition-[stroke-dashoffset] duration-500 ease-out motion-reduce:transition-none"
|
||||
/>
|
||||
</svg>
|
||||
<span
|
||||
className={cn(
|
||||
"relative flex h-[15px] w-[15px] items-center justify-center rounded-full bg-background text-[8px] font-medium",
|
||||
"text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{usage.usedPercentage !== null
|
||||
? Math.round(usage.usedPercentage)
|
||||
: formatContextWindowTokens(usage.usedTokens)}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PopoverPopup tooltipStyle side="top" align="end" className="w-max max-w-none px-3 py-2">
|
||||
<div className="space-y-1.5 leading-tight">
|
||||
<div className="text-[11px] font-medium uppercase tracking-[0.08em] text-muted-foreground">
|
||||
Context window
|
||||
</div>
|
||||
{usage.maxTokens !== null && usedPercentage ? (
|
||||
<div className="whitespace-nowrap text-xs font-medium text-foreground">
|
||||
<span>{usedPercentage}</span>
|
||||
<span className="mx-1">⋅</span>
|
||||
<span>{formatContextWindowTokens(usage.usedTokens)}</span>
|
||||
<span>/</span>
|
||||
<span>{formatContextWindowTokens(usage.maxTokens ?? null)} context used</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm text-foreground">
|
||||
{formatContextWindowTokens(usage.usedTokens)} tokens used so far
|
||||
</div>
|
||||
)}
|
||||
{(usage.totalProcessedTokens ?? null) !== null &&
|
||||
(usage.totalProcessedTokens ?? 0) > usage.usedTokens ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Total processed: {formatContextWindowTokens(usage.totalProcessedTokens ?? null)}{" "}
|
||||
tokens
|
||||
</div>
|
||||
) : null}
|
||||
{usage.compactsAutomatically ? (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Automatically compacts its context when needed.
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</PopoverPopup>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -96,4 +96,48 @@ describe("MessagesTimeline", () => {
|
||||
expect(markup).toContain("lucide-terminal");
|
||||
expect(markup).toContain("yoo what's ");
|
||||
});
|
||||
|
||||
it("renders context compaction entries in the normal work log", async () => {
|
||||
const { MessagesTimeline } = await import("./MessagesTimeline");
|
||||
const markup = renderToStaticMarkup(
|
||||
<MessagesTimeline
|
||||
hasMessages
|
||||
isWorking={false}
|
||||
activeTurnInProgress={false}
|
||||
activeTurnStartedAt={null}
|
||||
scrollContainer={null}
|
||||
timelineEntries={[
|
||||
{
|
||||
id: "entry-1",
|
||||
kind: "work",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
entry: {
|
||||
id: "work-1",
|
||||
createdAt: "2026-03-17T19:12:28.000Z",
|
||||
label: "Context compacted",
|
||||
tone: "info",
|
||||
},
|
||||
},
|
||||
]}
|
||||
completionDividerBeforeEntryId={null}
|
||||
completionSummary={null}
|
||||
turnDiffSummaryByAssistantMessageId={new Map()}
|
||||
nowIso="2026-03-17T19:12:30.000Z"
|
||||
expandedWorkGroups={{}}
|
||||
onToggleWorkGroup={() => {}}
|
||||
onOpenTurnDiff={() => {}}
|
||||
revertTurnCountByUserMessageId={new Map()}
|
||||
onRevertUserMessage={() => {}}
|
||||
isRevertingCheckpoint={false}
|
||||
onImageExpand={() => {}}
|
||||
markdownCwd={undefined}
|
||||
resolvedTheme="light"
|
||||
timestampFormat="locale"
|
||||
workspaceRoot={undefined}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(markup).toContain("Context compacted");
|
||||
expect(markup).toContain("Work log");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EventId,
|
||||
type OrchestrationThreadActivity,
|
||||
type OrchestrationThreadActivityKind,
|
||||
TurnId,
|
||||
} from "@t3tools/contracts";
|
||||
|
||||
import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "./contextWindow";
|
||||
|
||||
function makeActivity(
|
||||
id: string,
|
||||
kind: OrchestrationThreadActivityKind,
|
||||
payload: unknown,
|
||||
): OrchestrationThreadActivity {
|
||||
return {
|
||||
id: EventId.makeUnsafe(id),
|
||||
tone: kind.startsWith("tool.") ? "tool" : "info",
|
||||
kind,
|
||||
summary: kind,
|
||||
payload,
|
||||
turnId: TurnId.makeUnsafe("turn-1"),
|
||||
createdAt: "2026-03-23T00:00:00.000Z",
|
||||
} as OrchestrationThreadActivity;
|
||||
}
|
||||
|
||||
describe("contextWindow", () => {
|
||||
it("derives the latest valid context window snapshot", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {
|
||||
usedTokens: 1000,
|
||||
}),
|
||||
makeActivity("activity-2", "tool.started", {}),
|
||||
makeActivity("activity-3", "context-window.updated", {
|
||||
usedTokens: 14_000,
|
||||
maxTokens: 258_000,
|
||||
compactsAutomatically: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(snapshot).not.toBeNull();
|
||||
expect(snapshot?.usedTokens).toBe(14_000);
|
||||
expect(snapshot?.totalProcessedTokens).toBeNull();
|
||||
expect(snapshot?.maxTokens).toBe(258_000);
|
||||
expect(snapshot?.compactsAutomatically).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores malformed payloads", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {}),
|
||||
]);
|
||||
|
||||
expect(snapshot).toBeNull();
|
||||
});
|
||||
|
||||
it("formats compact token counts", () => {
|
||||
expect(formatContextWindowTokens(999)).toBe("999");
|
||||
expect(formatContextWindowTokens(1400)).toBe("1.4k");
|
||||
expect(formatContextWindowTokens(14_000)).toBe("14k");
|
||||
expect(formatContextWindowTokens(258_000)).toBe("258k");
|
||||
});
|
||||
|
||||
it("includes total processed tokens when available", () => {
|
||||
const snapshot = deriveLatestContextWindowSnapshot([
|
||||
makeActivity("activity-1", "context-window.updated", {
|
||||
usedTokens: 81_659,
|
||||
totalProcessedTokens: 748_126,
|
||||
maxTokens: 258_400,
|
||||
lastUsedTokens: 81_659,
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(snapshot?.usedTokens).toBe(81_659);
|
||||
expect(snapshot?.totalProcessedTokens).toBe(748_126);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { OrchestrationThreadActivity, ThreadTokenUsageSnapshot } from "@t3tools/contracts";
|
||||
|
||||
type NullableContextWindowUsage = {
|
||||
readonly [Key in keyof ThreadTokenUsageSnapshot]: undefined extends ThreadTokenUsageSnapshot[Key]
|
||||
? Exclude<ThreadTokenUsageSnapshot[Key], undefined> | null
|
||||
: ThreadTokenUsageSnapshot[Key];
|
||||
};
|
||||
|
||||
export type ContextWindowSnapshot = NullableContextWindowUsage & {
|
||||
readonly remainingTokens: number | null;
|
||||
readonly usedPercentage: number | null;
|
||||
readonly remainingPercentage: number | null;
|
||||
readonly updatedAt: string;
|
||||
};
|
||||
|
||||
export function deriveLatestContextWindowSnapshot(
|
||||
activities: ReadonlyArray<OrchestrationThreadActivity>,
|
||||
): ContextWindowSnapshot | null {
|
||||
for (let index = activities.length - 1; index >= 0; index -= 1) {
|
||||
const activity = activities[index];
|
||||
if (!activity || activity.kind !== "context-window.updated") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const {
|
||||
payload: {
|
||||
usedTokens,
|
||||
totalProcessedTokens,
|
||||
maxTokens,
|
||||
inputTokens,
|
||||
cachedInputTokens,
|
||||
outputTokens,
|
||||
reasoningOutputTokens,
|
||||
lastUsedTokens,
|
||||
lastInputTokens,
|
||||
lastCachedInputTokens,
|
||||
lastOutputTokens,
|
||||
lastReasoningOutputTokens,
|
||||
toolUses,
|
||||
durationMs,
|
||||
compactsAutomatically,
|
||||
},
|
||||
} = activity;
|
||||
if (!Number.isFinite(usedTokens) || usedTokens <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const usedPercentage =
|
||||
maxTokens !== undefined && maxTokens > 0
|
||||
? Math.min(100, (usedTokens / maxTokens) * 100)
|
||||
: null;
|
||||
const remainingTokens =
|
||||
maxTokens !== undefined ? Math.max(0, Math.round(maxTokens - usedTokens)) : null;
|
||||
const remainingPercentage = usedPercentage !== null ? Math.max(0, 100 - usedPercentage) : null;
|
||||
|
||||
return {
|
||||
usedTokens,
|
||||
totalProcessedTokens: totalProcessedTokens ?? null,
|
||||
maxTokens: maxTokens ?? null,
|
||||
remainingTokens,
|
||||
usedPercentage,
|
||||
remainingPercentage,
|
||||
inputTokens: inputTokens ?? null,
|
||||
cachedInputTokens: cachedInputTokens ?? null,
|
||||
outputTokens: outputTokens ?? null,
|
||||
reasoningOutputTokens: reasoningOutputTokens ?? null,
|
||||
lastUsedTokens: lastUsedTokens ?? null,
|
||||
lastInputTokens: lastInputTokens ?? null,
|
||||
lastCachedInputTokens: lastCachedInputTokens ?? null,
|
||||
lastOutputTokens: lastOutputTokens ?? null,
|
||||
lastReasoningOutputTokens: lastReasoningOutputTokens ?? null,
|
||||
toolUses: toolUses ?? null,
|
||||
durationMs: durationMs ?? null,
|
||||
compactsAutomatically: compactsAutomatically ?? false,
|
||||
updatedAt: activity.createdAt,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function formatContextWindowTokens(value: number | null): string {
|
||||
if (value === null || !Number.isFinite(value)) {
|
||||
return "0";
|
||||
}
|
||||
if (value < 1_000) {
|
||||
return `${Math.round(value)}`;
|
||||
}
|
||||
if (value < 10_000) {
|
||||
return `${(value / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
|
||||
}
|
||||
if (value < 1_000_000) {
|
||||
return `${Math.round(value / 1_000)}k`;
|
||||
}
|
||||
return `${(value / 1_000_000).toFixed(1).replace(/\.0$/, "")}m`;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
MessageId,
|
||||
ThreadId,
|
||||
TurnId,
|
||||
type OrchestrationThreadActivityKind,
|
||||
type OrchestrationThreadActivity,
|
||||
} from "@t3tools/contracts";
|
||||
import { describe, expect, it } from "vitest";
|
||||
@@ -25,7 +26,7 @@ import {
|
||||
function makeActivity(overrides: {
|
||||
id?: string;
|
||||
createdAt?: string;
|
||||
kind?: string;
|
||||
kind?: OrchestrationThreadActivityKind;
|
||||
summary?: string;
|
||||
tone?: OrchestrationThreadActivity["tone"];
|
||||
payload?: Record<string, unknown>;
|
||||
@@ -42,7 +43,7 @@ function makeActivity(overrides: {
|
||||
payload,
|
||||
turnId: overrides.turnId ? TurnId.makeUnsafe(overrides.turnId) : null,
|
||||
...(overrides.sequence !== undefined ? { sequence: overrides.sequence } : {}),
|
||||
};
|
||||
} as OrchestrationThreadActivity;
|
||||
}
|
||||
|
||||
describe("derivePendingApprovals", () => {
|
||||
@@ -966,6 +967,51 @@ describe("deriveTimelineEntries", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("deriveWorkLogEntries context window handling", () => {
|
||||
it("excludes context window updates from the work log", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeActivity({
|
||||
id: "context-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-window.updated",
|
||||
summary: "Context window updated",
|
||||
tone: "info",
|
||||
}),
|
||||
makeActivity({
|
||||
id: "tool-1",
|
||||
turnId: "turn-1",
|
||||
kind: "tool.completed",
|
||||
summary: "Ran command",
|
||||
tone: "tool",
|
||||
}),
|
||||
],
|
||||
TurnId.makeUnsafe("turn-1"),
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Ran command");
|
||||
});
|
||||
|
||||
it("keeps context compaction activities as normal work log entries", () => {
|
||||
const entries = deriveWorkLogEntries(
|
||||
[
|
||||
makeActivity({
|
||||
id: "compaction-1",
|
||||
turnId: "turn-1",
|
||||
kind: "context-compaction",
|
||||
summary: "Context compacted",
|
||||
tone: "info",
|
||||
}),
|
||||
],
|
||||
TurnId.makeUnsafe("turn-1"),
|
||||
);
|
||||
|
||||
expect(entries).toHaveLength(1);
|
||||
expect(entries[0]?.label).toBe("Context compacted");
|
||||
});
|
||||
});
|
||||
|
||||
describe("hasToolActivityForTurn", () => {
|
||||
it("returns false when turn id is missing", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
@@ -979,7 +1025,7 @@ describe("hasToolActivityForTurn", () => {
|
||||
it("returns true only for matching tool activity in the target turn", () => {
|
||||
const activities: OrchestrationThreadActivity[] = [
|
||||
makeActivity({ id: "tool-1", turnId: "turn-1", kind: "tool.completed", tone: "tool" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "turn.completed", tone: "info" }),
|
||||
makeActivity({ id: "info-1", turnId: "turn-2", kind: "task.completed", tone: "info" }),
|
||||
];
|
||||
|
||||
expect(hasToolActivityForTurn(activities, TurnId.makeUnsafe("turn-1"))).toBe(true);
|
||||
|
||||
@@ -463,6 +463,7 @@ export function deriveWorkLogEntries(
|
||||
.filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
|
||||
.filter((activity) => activity.kind !== "tool.started")
|
||||
.filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
|
||||
.filter((activity) => activity.kind !== "context-window.updated")
|
||||
.filter((activity) => activity.summary !== "Checkpoint captured")
|
||||
.filter((activity) => !isPlanBoundaryToolActivity(activity))
|
||||
.map(toDerivedWorkLogEntry);
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
TrimmedNonEmptyString,
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
import { ThreadTokenUsageSnapshot } from "./threadUsage";
|
||||
|
||||
export const ORCHESTRATION_WS_METHODS = {
|
||||
getSnapshot: "orchestration.getSnapshot",
|
||||
@@ -238,16 +239,197 @@ export const OrchestrationThreadActivityTone = Schema.Literals([
|
||||
]);
|
||||
export type OrchestrationThreadActivityTone = typeof OrchestrationThreadActivityTone.Type;
|
||||
|
||||
export const OrchestrationThreadActivity = Schema.Struct({
|
||||
export const OrchestrationThreadActivityKind = Schema.Literals([
|
||||
"approval.requested",
|
||||
"approval.resolved",
|
||||
"runtime.error",
|
||||
"runtime.warning",
|
||||
"turn.plan.updated",
|
||||
"user-input.requested",
|
||||
"user-input.resolved",
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.completed",
|
||||
"context-compaction",
|
||||
"context-window.updated",
|
||||
"tool.updated",
|
||||
"tool.completed",
|
||||
"tool.started",
|
||||
"checkpoint.revert.failed",
|
||||
"checkpoint.capture.failed",
|
||||
"checkpoint.captured",
|
||||
"provider.turn.start.failed",
|
||||
"provider.turn.interrupt.failed",
|
||||
"provider.approval.respond.failed",
|
||||
"provider.user-input.respond.failed",
|
||||
]);
|
||||
export type OrchestrationThreadActivityKind = typeof OrchestrationThreadActivityKind.Type;
|
||||
|
||||
const OrchestrationThreadActivityBaseFields = {
|
||||
id: EventId,
|
||||
tone: OrchestrationThreadActivityTone,
|
||||
kind: TrimmedNonEmptyString,
|
||||
summary: TrimmedNonEmptyString,
|
||||
payload: Schema.Unknown,
|
||||
turnId: Schema.NullOr(TurnId),
|
||||
sequence: Schema.optional(NonNegativeInt),
|
||||
createdAt: IsoDateTime,
|
||||
} as const;
|
||||
|
||||
const ApprovalRequestedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
requestKind: Schema.optional(ProviderRequestKind),
|
||||
requestType: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const ApprovalResolvedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
requestKind: Schema.optional(ProviderRequestKind),
|
||||
requestType: Schema.optional(TrimmedNonEmptyString),
|
||||
decision: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const RuntimeErrorActivityPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const RuntimeWarningActivityPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const RuntimePlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyString,
|
||||
status: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const TurnPlanUpdatedActivityPayload = Schema.Struct({
|
||||
plan: Schema.Array(RuntimePlanStep),
|
||||
explanation: Schema.optional(Schema.NullOr(TrimmedNonEmptyString)),
|
||||
});
|
||||
|
||||
const UserInputRequestedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
questions: Schema.Array(Schema.Unknown),
|
||||
});
|
||||
|
||||
const UserInputResolvedActivityPayload = Schema.Struct({
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
answers: Schema.Record(Schema.String, Schema.Unknown),
|
||||
});
|
||||
|
||||
const TaskStartedActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
taskType: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const TaskProgressActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
detail: TrimmedNonEmptyString,
|
||||
summary: Schema.optional(TrimmedNonEmptyString),
|
||||
lastToolName: Schema.optional(TrimmedNonEmptyString),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const TaskCompletedActivityPayload = Schema.Struct({
|
||||
taskId: TrimmedNonEmptyString,
|
||||
status: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
usage: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const ContextCompactionActivityPayload = Schema.Struct({
|
||||
state: Schema.Literal("compacted"),
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const ToolStartedOrCompletedActivityPayload = Schema.Struct({
|
||||
itemType: TrimmedNonEmptyString,
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
const ToolUpdatedActivityPayload = Schema.Struct({
|
||||
itemType: TrimmedNonEmptyString,
|
||||
status: Schema.optional(TrimmedNonEmptyString),
|
||||
detail: Schema.optional(TrimmedNonEmptyString),
|
||||
data: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
|
||||
const CheckpointRevertFailedActivityPayload = Schema.Struct({
|
||||
turnCount: NonNegativeInt,
|
||||
detail: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const CheckpointCaptureFailedActivityPayload = Schema.Struct({
|
||||
detail: TrimmedNonEmptyString,
|
||||
});
|
||||
|
||||
const CheckpointCapturedActivityPayload = Schema.Struct({
|
||||
turnCount: NonNegativeInt,
|
||||
status: OrchestrationCheckpointStatus,
|
||||
});
|
||||
|
||||
const ProviderFailureActivityPayload = Schema.Struct({
|
||||
detail: TrimmedNonEmptyString,
|
||||
requestId: Schema.optional(TrimmedNonEmptyString),
|
||||
});
|
||||
|
||||
function makeThreadActivitySchema<
|
||||
Kind extends OrchestrationThreadActivityKind,
|
||||
Payload extends Schema.Schema<any>,
|
||||
>(kind: Kind, tone: OrchestrationThreadActivityTone, payload: Payload) {
|
||||
return Schema.Struct({
|
||||
...OrchestrationThreadActivityBaseFields,
|
||||
tone: Schema.Literal(tone),
|
||||
kind: Schema.Literal(kind),
|
||||
payload,
|
||||
});
|
||||
}
|
||||
|
||||
export const OrchestrationThreadActivity = Schema.Union([
|
||||
makeThreadActivitySchema("approval.requested", "approval", ApprovalRequestedActivityPayload),
|
||||
makeThreadActivitySchema("approval.resolved", "approval", ApprovalResolvedActivityPayload),
|
||||
makeThreadActivitySchema("runtime.error", "error", RuntimeErrorActivityPayload),
|
||||
makeThreadActivitySchema("runtime.warning", "info", RuntimeWarningActivityPayload),
|
||||
makeThreadActivitySchema("turn.plan.updated", "info", TurnPlanUpdatedActivityPayload),
|
||||
makeThreadActivitySchema("user-input.requested", "info", UserInputRequestedActivityPayload),
|
||||
makeThreadActivitySchema("user-input.resolved", "info", UserInputResolvedActivityPayload),
|
||||
makeThreadActivitySchema("task.started", "info", TaskStartedActivityPayload),
|
||||
makeThreadActivitySchema("task.progress", "info", TaskProgressActivityPayload),
|
||||
makeThreadActivitySchema("task.completed", "info", TaskCompletedActivityPayload),
|
||||
makeThreadActivitySchema("context-compaction", "info", ContextCompactionActivityPayload),
|
||||
makeThreadActivitySchema("context-window.updated", "info", ThreadTokenUsageSnapshot),
|
||||
makeThreadActivitySchema("tool.updated", "tool", ToolUpdatedActivityPayload),
|
||||
makeThreadActivitySchema("tool.completed", "tool", ToolStartedOrCompletedActivityPayload),
|
||||
makeThreadActivitySchema("tool.started", "tool", ToolStartedOrCompletedActivityPayload),
|
||||
makeThreadActivitySchema(
|
||||
"checkpoint.revert.failed",
|
||||
"error",
|
||||
CheckpointRevertFailedActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"checkpoint.capture.failed",
|
||||
"error",
|
||||
CheckpointCaptureFailedActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema("checkpoint.captured", "info", CheckpointCapturedActivityPayload),
|
||||
makeThreadActivitySchema("provider.turn.start.failed", "error", ProviderFailureActivityPayload),
|
||||
makeThreadActivitySchema(
|
||||
"provider.turn.interrupt.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"provider.approval.respond.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
makeThreadActivitySchema(
|
||||
"provider.user-input.respond.failed",
|
||||
"error",
|
||||
ProviderFailureActivityPayload,
|
||||
),
|
||||
]);
|
||||
export type OrchestrationThreadActivity = typeof OrchestrationThreadActivity.Type;
|
||||
|
||||
const OrchestrationLatestTurnState = Schema.Literals([
|
||||
|
||||
@@ -139,4 +139,29 @@ describe("ProviderRuntimeEvent", () => {
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("decodes normalized thread token usage snapshots", () => {
|
||||
const parsed = decodeRuntimeEvent({
|
||||
type: "thread.token-usage.updated",
|
||||
eventId: "event-token-usage-1",
|
||||
provider: "claudeAgent",
|
||||
createdAt: "2026-02-28T00:00:04.000Z",
|
||||
threadId: "thread-1",
|
||||
payload: {
|
||||
usage: {
|
||||
usedTokens: 31251,
|
||||
maxTokens: 200000,
|
||||
toolUses: 25,
|
||||
durationMs: 43567,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(parsed.type).toBe("thread.token-usage.updated");
|
||||
if (parsed.type !== "thread.token-usage.updated") {
|
||||
throw new Error("expected thread.token-usage.updated");
|
||||
}
|
||||
expect(parsed.payload.usage.maxTokens).toBe(200000);
|
||||
expect(parsed.payload.usage.usedTokens).toBe(31251);
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,8 @@ import {
|
||||
TurnId,
|
||||
} from "./baseSchemas";
|
||||
import { ProviderKind } from "./orchestration";
|
||||
export { ThreadTokenUsageSnapshot } from "./threadUsage";
|
||||
import { ThreadTokenUsageSnapshot as ThreadTokenUsageSnapshotSchema } from "./threadUsage";
|
||||
|
||||
const TrimmedNonEmptyStringSchema = TrimmedNonEmptyString;
|
||||
const UnknownRecordSchema = Schema.Record(Schema.String, Schema.Unknown);
|
||||
@@ -141,21 +143,14 @@ export type CanonicalRequestType = typeof CanonicalRequestType.Type;
|
||||
|
||||
const ProviderRuntimeEventType = Schema.Literals([
|
||||
"session.started",
|
||||
"session.configured",
|
||||
"session.state.changed",
|
||||
"session.exited",
|
||||
"thread.started",
|
||||
"thread.state.changed",
|
||||
"thread.metadata.updated",
|
||||
"thread.token-usage.updated",
|
||||
"thread.realtime.started",
|
||||
"thread.realtime.item-added",
|
||||
"thread.realtime.audio.delta",
|
||||
"thread.realtime.error",
|
||||
"thread.realtime.closed",
|
||||
"turn.started",
|
||||
"turn.completed",
|
||||
"turn.aborted",
|
||||
"turn.plan.updated",
|
||||
"turn.proposed.delta",
|
||||
"turn.proposed.completed",
|
||||
@@ -171,41 +166,20 @@ const ProviderRuntimeEventType = Schema.Literals([
|
||||
"task.started",
|
||||
"task.progress",
|
||||
"task.completed",
|
||||
"hook.started",
|
||||
"hook.progress",
|
||||
"hook.completed",
|
||||
"tool.progress",
|
||||
"tool.summary",
|
||||
"auth.status",
|
||||
"account.updated",
|
||||
"account.rate-limits.updated",
|
||||
"mcp.status.updated",
|
||||
"mcp.oauth.completed",
|
||||
"model.rerouted",
|
||||
"config.warning",
|
||||
"deprecation.notice",
|
||||
"files.persisted",
|
||||
"runtime.warning",
|
||||
"runtime.error",
|
||||
]);
|
||||
export type ProviderRuntimeEventType = typeof ProviderRuntimeEventType.Type;
|
||||
|
||||
const SessionStartedType = Schema.Literal("session.started");
|
||||
const SessionConfiguredType = Schema.Literal("session.configured");
|
||||
const SessionStateChangedType = Schema.Literal("session.state.changed");
|
||||
const SessionExitedType = Schema.Literal("session.exited");
|
||||
const ThreadStartedType = Schema.Literal("thread.started");
|
||||
const ThreadStateChangedType = Schema.Literal("thread.state.changed");
|
||||
const ThreadMetadataUpdatedType = Schema.Literal("thread.metadata.updated");
|
||||
const ThreadTokenUsageUpdatedType = Schema.Literal("thread.token-usage.updated");
|
||||
const ThreadRealtimeStartedType = Schema.Literal("thread.realtime.started");
|
||||
const ThreadRealtimeItemAddedType = Schema.Literal("thread.realtime.item-added");
|
||||
const ThreadRealtimeAudioDeltaType = Schema.Literal("thread.realtime.audio.delta");
|
||||
const ThreadRealtimeErrorType = Schema.Literal("thread.realtime.error");
|
||||
const ThreadRealtimeClosedType = Schema.Literal("thread.realtime.closed");
|
||||
const TurnStartedType = Schema.Literal("turn.started");
|
||||
const TurnCompletedType = Schema.Literal("turn.completed");
|
||||
const TurnAbortedType = Schema.Literal("turn.aborted");
|
||||
const TurnPlanUpdatedType = Schema.Literal("turn.plan.updated");
|
||||
const TurnProposedDeltaType = Schema.Literal("turn.proposed.delta");
|
||||
const TurnProposedCompletedType = Schema.Literal("turn.proposed.completed");
|
||||
@@ -221,20 +195,6 @@ const UserInputResolvedType = Schema.Literal("user-input.resolved");
|
||||
const TaskStartedType = Schema.Literal("task.started");
|
||||
const TaskProgressType = Schema.Literal("task.progress");
|
||||
const TaskCompletedType = Schema.Literal("task.completed");
|
||||
const HookStartedType = Schema.Literal("hook.started");
|
||||
const HookProgressType = Schema.Literal("hook.progress");
|
||||
const HookCompletedType = Schema.Literal("hook.completed");
|
||||
const ToolProgressType = Schema.Literal("tool.progress");
|
||||
const ToolSummaryType = Schema.Literal("tool.summary");
|
||||
const AuthStatusType = Schema.Literal("auth.status");
|
||||
const AccountUpdatedType = Schema.Literal("account.updated");
|
||||
const AccountRateLimitsUpdatedType = Schema.Literal("account.rate-limits.updated");
|
||||
const McpStatusUpdatedType = Schema.Literal("mcp.status.updated");
|
||||
const McpOauthCompletedType = Schema.Literal("mcp.oauth.completed");
|
||||
const ModelReroutedType = Schema.Literal("model.rerouted");
|
||||
const ConfigWarningType = Schema.Literal("config.warning");
|
||||
const DeprecationNoticeType = Schema.Literal("deprecation.notice");
|
||||
const FilesPersistedType = Schema.Literal("files.persisted");
|
||||
const RuntimeWarningType = Schema.Literal("runtime.warning");
|
||||
const RuntimeErrorType = Schema.Literal("runtime.error");
|
||||
|
||||
@@ -257,11 +217,6 @@ const SessionStartedPayload = Schema.Struct({
|
||||
});
|
||||
export type SessionStartedPayload = typeof SessionStartedPayload.Type;
|
||||
|
||||
const SessionConfiguredPayload = Schema.Struct({
|
||||
config: UnknownRecordSchema,
|
||||
});
|
||||
export type SessionConfiguredPayload = typeof SessionConfiguredPayload.Type;
|
||||
|
||||
const SessionStateChangedPayload = Schema.Struct({
|
||||
state: RuntimeSessionState,
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -294,35 +249,10 @@ const ThreadMetadataUpdatedPayload = Schema.Struct({
|
||||
export type ThreadMetadataUpdatedPayload = typeof ThreadMetadataUpdatedPayload.Type;
|
||||
|
||||
const ThreadTokenUsageUpdatedPayload = Schema.Struct({
|
||||
usage: Schema.Unknown,
|
||||
usage: ThreadTokenUsageSnapshotSchema,
|
||||
});
|
||||
export type ThreadTokenUsageUpdatedPayload = typeof ThreadTokenUsageUpdatedPayload.Type;
|
||||
|
||||
const ThreadRealtimeStartedPayload = Schema.Struct({
|
||||
realtimeSessionId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ThreadRealtimeStartedPayload = typeof ThreadRealtimeStartedPayload.Type;
|
||||
|
||||
const ThreadRealtimeItemAddedPayload = Schema.Struct({
|
||||
item: Schema.Unknown,
|
||||
});
|
||||
export type ThreadRealtimeItemAddedPayload = typeof ThreadRealtimeItemAddedPayload.Type;
|
||||
|
||||
const ThreadRealtimeAudioDeltaPayload = Schema.Struct({
|
||||
audio: Schema.Unknown,
|
||||
});
|
||||
export type ThreadRealtimeAudioDeltaPayload = typeof ThreadRealtimeAudioDeltaPayload.Type;
|
||||
|
||||
const ThreadRealtimeErrorPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type ThreadRealtimeErrorPayload = typeof ThreadRealtimeErrorPayload.Type;
|
||||
|
||||
const ThreadRealtimeClosedPayload = Schema.Struct({
|
||||
reason: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type ThreadRealtimeClosedPayload = typeof ThreadRealtimeClosedPayload.Type;
|
||||
|
||||
const TurnStartedPayload = Schema.Struct({
|
||||
model: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
effort: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
@@ -339,11 +269,6 @@ const TurnCompletedPayload = Schema.Struct({
|
||||
});
|
||||
export type TurnCompletedPayload = typeof TurnCompletedPayload.Type;
|
||||
|
||||
const TurnAbortedPayload = Schema.Struct({
|
||||
reason: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type TurnAbortedPayload = typeof TurnAbortedPayload.Type;
|
||||
|
||||
const RuntimePlanStep = Schema.Struct({
|
||||
step: TrimmedNonEmptyStringSchema,
|
||||
status: RuntimePlanStepStatus,
|
||||
@@ -453,113 +378,6 @@ const TaskCompletedPayload = Schema.Struct({
|
||||
});
|
||||
export type TaskCompletedPayload = typeof TaskCompletedPayload.Type;
|
||||
|
||||
const HookStartedPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
hookName: TrimmedNonEmptyStringSchema,
|
||||
hookEvent: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type HookStartedPayload = typeof HookStartedPayload.Type;
|
||||
|
||||
const HookProgressPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
output: Schema.optional(Schema.String),
|
||||
stdout: Schema.optional(Schema.String),
|
||||
stderr: Schema.optional(Schema.String),
|
||||
});
|
||||
export type HookProgressPayload = typeof HookProgressPayload.Type;
|
||||
|
||||
const HookCompletedPayload = Schema.Struct({
|
||||
hookId: TrimmedNonEmptyStringSchema,
|
||||
outcome: Schema.Literals(["success", "error", "cancelled"]),
|
||||
output: Schema.optional(Schema.String),
|
||||
stdout: Schema.optional(Schema.String),
|
||||
stderr: Schema.optional(Schema.String),
|
||||
exitCode: Schema.optional(Schema.Int),
|
||||
});
|
||||
export type HookCompletedPayload = typeof HookCompletedPayload.Type;
|
||||
|
||||
const ToolProgressPayload = Schema.Struct({
|
||||
toolUseId: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
toolName: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
summary: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
elapsedSeconds: Schema.optional(Schema.Number),
|
||||
});
|
||||
export type ToolProgressPayload = typeof ToolProgressPayload.Type;
|
||||
|
||||
const ToolSummaryPayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
precedingToolUseIds: Schema.optional(Schema.Array(TrimmedNonEmptyStringSchema)),
|
||||
});
|
||||
export type ToolSummaryPayload = typeof ToolSummaryPayload.Type;
|
||||
|
||||
const AuthStatusPayload = Schema.Struct({
|
||||
isAuthenticating: Schema.optional(Schema.Boolean),
|
||||
output: Schema.optional(Schema.Array(Schema.String)),
|
||||
error: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type AuthStatusPayload = typeof AuthStatusPayload.Type;
|
||||
|
||||
const AccountUpdatedPayload = Schema.Struct({
|
||||
account: Schema.Unknown,
|
||||
});
|
||||
export type AccountUpdatedPayload = typeof AccountUpdatedPayload.Type;
|
||||
|
||||
const AccountRateLimitsUpdatedPayload = Schema.Struct({
|
||||
rateLimits: Schema.Unknown,
|
||||
});
|
||||
export type AccountRateLimitsUpdatedPayload = typeof AccountRateLimitsUpdatedPayload.Type;
|
||||
|
||||
const McpStatusUpdatedPayload = Schema.Struct({
|
||||
status: Schema.Unknown,
|
||||
});
|
||||
export type McpStatusUpdatedPayload = typeof McpStatusUpdatedPayload.Type;
|
||||
|
||||
const McpOauthCompletedPayload = Schema.Struct({
|
||||
success: Schema.Boolean,
|
||||
name: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
error: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type McpOauthCompletedPayload = typeof McpOauthCompletedPayload.Type;
|
||||
|
||||
const ModelReroutedPayload = Schema.Struct({
|
||||
fromModel: TrimmedNonEmptyStringSchema,
|
||||
toModel: TrimmedNonEmptyStringSchema,
|
||||
reason: TrimmedNonEmptyStringSchema,
|
||||
});
|
||||
export type ModelReroutedPayload = typeof ModelReroutedPayload.Type;
|
||||
|
||||
const ConfigWarningPayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
details: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
path: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
range: Schema.optional(Schema.Unknown),
|
||||
});
|
||||
export type ConfigWarningPayload = typeof ConfigWarningPayload.Type;
|
||||
|
||||
const DeprecationNoticePayload = Schema.Struct({
|
||||
summary: TrimmedNonEmptyStringSchema,
|
||||
details: Schema.optional(TrimmedNonEmptyStringSchema),
|
||||
});
|
||||
export type DeprecationNoticePayload = typeof DeprecationNoticePayload.Type;
|
||||
|
||||
const FilesPersistedPayload = Schema.Struct({
|
||||
files: Schema.Array(
|
||||
Schema.Struct({
|
||||
filename: TrimmedNonEmptyStringSchema,
|
||||
fileId: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
failed: Schema.optional(
|
||||
Schema.Array(
|
||||
Schema.Struct({
|
||||
filename: TrimmedNonEmptyStringSchema,
|
||||
error: TrimmedNonEmptyStringSchema,
|
||||
}),
|
||||
),
|
||||
),
|
||||
});
|
||||
export type FilesPersistedPayload = typeof FilesPersistedPayload.Type;
|
||||
|
||||
const RuntimeWarningPayload = Schema.Struct({
|
||||
message: TrimmedNonEmptyStringSchema,
|
||||
detail: Schema.optional(Schema.Unknown),
|
||||
@@ -580,14 +398,6 @@ const ProviderRuntimeSessionStartedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeSessionStartedEvent = typeof ProviderRuntimeSessionStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeSessionConfiguredEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionConfiguredType,
|
||||
payload: SessionConfiguredPayload,
|
||||
});
|
||||
export type ProviderRuntimeSessionConfiguredEvent =
|
||||
typeof ProviderRuntimeSessionConfiguredEvent.Type;
|
||||
|
||||
const ProviderRuntimeSessionStateChangedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: SessionStateChangedType,
|
||||
@@ -634,46 +444,6 @@ const ProviderRuntimeThreadTokenUsageUpdatedEvent = Schema.Struct({
|
||||
export type ProviderRuntimeThreadTokenUsageUpdatedEvent =
|
||||
typeof ProviderRuntimeThreadTokenUsageUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeStartedType,
|
||||
payload: ThreadRealtimeStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeStartedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeItemAddedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeItemAddedType,
|
||||
payload: ThreadRealtimeItemAddedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeItemAddedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeItemAddedEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeAudioDeltaEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeAudioDeltaType,
|
||||
payload: ThreadRealtimeAudioDeltaPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeAudioDeltaEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeAudioDeltaEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeErrorEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeErrorType,
|
||||
payload: ThreadRealtimeErrorPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeErrorEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeErrorEvent.Type;
|
||||
|
||||
const ProviderRuntimeThreadRealtimeClosedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ThreadRealtimeClosedType,
|
||||
payload: ThreadRealtimeClosedPayload,
|
||||
});
|
||||
export type ProviderRuntimeThreadRealtimeClosedEvent =
|
||||
typeof ProviderRuntimeThreadRealtimeClosedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnStartedType,
|
||||
@@ -688,13 +458,6 @@ const ProviderRuntimeTurnCompletedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeTurnCompletedEvent = typeof ProviderRuntimeTurnCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnAbortedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnAbortedType,
|
||||
payload: TurnAbortedPayload,
|
||||
});
|
||||
export type ProviderRuntimeTurnAbortedEvent = typeof ProviderRuntimeTurnAbortedEvent.Type;
|
||||
|
||||
const ProviderRuntimeTurnPlanUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: TurnPlanUpdatedType,
|
||||
@@ -804,107 +567,6 @@ const ProviderRuntimeTaskCompletedEvent = Schema.Struct({
|
||||
});
|
||||
export type ProviderRuntimeTaskCompletedEvent = typeof ProviderRuntimeTaskCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookStartedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookStartedType,
|
||||
payload: HookStartedPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookStartedEvent = typeof ProviderRuntimeHookStartedEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookProgressEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookProgressType,
|
||||
payload: HookProgressPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookProgressEvent = typeof ProviderRuntimeHookProgressEvent.Type;
|
||||
|
||||
const ProviderRuntimeHookCompletedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: HookCompletedType,
|
||||
payload: HookCompletedPayload,
|
||||
});
|
||||
export type ProviderRuntimeHookCompletedEvent = typeof ProviderRuntimeHookCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeToolProgressEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ToolProgressType,
|
||||
payload: ToolProgressPayload,
|
||||
});
|
||||
export type ProviderRuntimeToolProgressEvent = typeof ProviderRuntimeToolProgressEvent.Type;
|
||||
|
||||
const ProviderRuntimeToolSummaryEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ToolSummaryType,
|
||||
payload: ToolSummaryPayload,
|
||||
});
|
||||
export type ProviderRuntimeToolSummaryEvent = typeof ProviderRuntimeToolSummaryEvent.Type;
|
||||
|
||||
const ProviderRuntimeAuthStatusEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AuthStatusType,
|
||||
payload: AuthStatusPayload,
|
||||
});
|
||||
export type ProviderRuntimeAuthStatusEvent = typeof ProviderRuntimeAuthStatusEvent.Type;
|
||||
|
||||
const ProviderRuntimeAccountUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AccountUpdatedType,
|
||||
payload: AccountUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeAccountUpdatedEvent = typeof ProviderRuntimeAccountUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeAccountRateLimitsUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: AccountRateLimitsUpdatedType,
|
||||
payload: AccountRateLimitsUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeAccountRateLimitsUpdatedEvent =
|
||||
typeof ProviderRuntimeAccountRateLimitsUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeMcpStatusUpdatedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: McpStatusUpdatedType,
|
||||
payload: McpStatusUpdatedPayload,
|
||||
});
|
||||
export type ProviderRuntimeMcpStatusUpdatedEvent = typeof ProviderRuntimeMcpStatusUpdatedEvent.Type;
|
||||
|
||||
const ProviderRuntimeMcpOauthCompletedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: McpOauthCompletedType,
|
||||
payload: McpOauthCompletedPayload,
|
||||
});
|
||||
export type ProviderRuntimeMcpOauthCompletedEvent =
|
||||
typeof ProviderRuntimeMcpOauthCompletedEvent.Type;
|
||||
|
||||
const ProviderRuntimeModelReroutedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ModelReroutedType,
|
||||
payload: ModelReroutedPayload,
|
||||
});
|
||||
export type ProviderRuntimeModelReroutedEvent = typeof ProviderRuntimeModelReroutedEvent.Type;
|
||||
|
||||
const ProviderRuntimeConfigWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: ConfigWarningType,
|
||||
payload: ConfigWarningPayload,
|
||||
});
|
||||
export type ProviderRuntimeConfigWarningEvent = typeof ProviderRuntimeConfigWarningEvent.Type;
|
||||
|
||||
const ProviderRuntimeDeprecationNoticeEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: DeprecationNoticeType,
|
||||
payload: DeprecationNoticePayload,
|
||||
});
|
||||
export type ProviderRuntimeDeprecationNoticeEvent =
|
||||
typeof ProviderRuntimeDeprecationNoticeEvent.Type;
|
||||
|
||||
const ProviderRuntimeFilesPersistedEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: FilesPersistedType,
|
||||
payload: FilesPersistedPayload,
|
||||
});
|
||||
export type ProviderRuntimeFilesPersistedEvent = typeof ProviderRuntimeFilesPersistedEvent.Type;
|
||||
|
||||
const ProviderRuntimeWarningEvent = Schema.Struct({
|
||||
...ProviderRuntimeEventBase.fields,
|
||||
type: RuntimeWarningType,
|
||||
@@ -921,21 +583,14 @@ export type ProviderRuntimeErrorEvent = typeof ProviderRuntimeErrorEvent.Type;
|
||||
|
||||
export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeSessionStartedEvent,
|
||||
ProviderRuntimeSessionConfiguredEvent,
|
||||
ProviderRuntimeSessionStateChangedEvent,
|
||||
ProviderRuntimeSessionExitedEvent,
|
||||
ProviderRuntimeThreadStartedEvent,
|
||||
ProviderRuntimeThreadStateChangedEvent,
|
||||
ProviderRuntimeThreadMetadataUpdatedEvent,
|
||||
ProviderRuntimeThreadTokenUsageUpdatedEvent,
|
||||
ProviderRuntimeThreadRealtimeStartedEvent,
|
||||
ProviderRuntimeThreadRealtimeItemAddedEvent,
|
||||
ProviderRuntimeThreadRealtimeAudioDeltaEvent,
|
||||
ProviderRuntimeThreadRealtimeErrorEvent,
|
||||
ProviderRuntimeThreadRealtimeClosedEvent,
|
||||
ProviderRuntimeTurnStartedEvent,
|
||||
ProviderRuntimeTurnCompletedEvent,
|
||||
ProviderRuntimeTurnAbortedEvent,
|
||||
ProviderRuntimeTurnPlanUpdatedEvent,
|
||||
ProviderRuntimeTurnProposedDeltaEvent,
|
||||
ProviderRuntimeTurnProposedCompletedEvent,
|
||||
@@ -951,20 +606,6 @@ export const ProviderRuntimeEventV2 = Schema.Union([
|
||||
ProviderRuntimeTaskStartedEvent,
|
||||
ProviderRuntimeTaskProgressEvent,
|
||||
ProviderRuntimeTaskCompletedEvent,
|
||||
ProviderRuntimeHookStartedEvent,
|
||||
ProviderRuntimeHookProgressEvent,
|
||||
ProviderRuntimeHookCompletedEvent,
|
||||
ProviderRuntimeToolProgressEvent,
|
||||
ProviderRuntimeToolSummaryEvent,
|
||||
ProviderRuntimeAuthStatusEvent,
|
||||
ProviderRuntimeAccountUpdatedEvent,
|
||||
ProviderRuntimeAccountRateLimitsUpdatedEvent,
|
||||
ProviderRuntimeMcpStatusUpdatedEvent,
|
||||
ProviderRuntimeMcpOauthCompletedEvent,
|
||||
ProviderRuntimeModelReroutedEvent,
|
||||
ProviderRuntimeConfigWarningEvent,
|
||||
ProviderRuntimeDeprecationNoticeEvent,
|
||||
ProviderRuntimeFilesPersistedEvent,
|
||||
ProviderRuntimeWarningEvent,
|
||||
ProviderRuntimeErrorEvent,
|
||||
]);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { Schema } from "effect";
|
||||
|
||||
import { NonNegativeInt, PositiveInt } from "./baseSchemas";
|
||||
|
||||
export const ThreadTokenUsageSnapshot = Schema.Struct({
|
||||
usedTokens: NonNegativeInt,
|
||||
totalProcessedTokens: Schema.optional(NonNegativeInt),
|
||||
maxTokens: Schema.optional(PositiveInt),
|
||||
inputTokens: Schema.optional(NonNegativeInt),
|
||||
cachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
outputTokens: Schema.optional(NonNegativeInt),
|
||||
reasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastUsedTokens: Schema.optional(NonNegativeInt),
|
||||
lastInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastCachedInputTokens: Schema.optional(NonNegativeInt),
|
||||
lastOutputTokens: Schema.optional(NonNegativeInt),
|
||||
lastReasoningOutputTokens: Schema.optional(NonNegativeInt),
|
||||
toolUses: Schema.optional(NonNegativeInt),
|
||||
durationMs: Schema.optional(NonNegativeInt),
|
||||
compactsAutomatically: Schema.optional(Schema.Boolean),
|
||||
});
|
||||
export type ThreadTokenUsageSnapshot = typeof ThreadTokenUsageSnapshot.Type;
|
||||
Reference in new issue
Block a user