Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(usage): 修正三种 harness 的 token 速度计量与收尾显示

Dash3cd2c5925e0f
diff --git a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts
index 5144e88452..a3f8100bdc 100644
--- a/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts
+++ b/apps/desktop/src/renderer/__tests__/runningTokenRateHistory.test.ts
@@ -347,10 +347,10 @@ describe('host token speed (Pi extension algorithm)', () => {
expect(history.latestRate).toBe(70);
});
- it('reports the final average without adding a chart point, and continues the axis next turn', () => {
+ it('keeps the latest speed when the final average arrives, and continues the axis next turn', () => {
let history = recordTokenSpeed(emptyRateHistory(null), { startedAt: 1, speed: speed(100, 1500) });
history = recordTokenSpeed(history, { startedAt: 1, speed: speed(60, 2000, false) });
- expect(history.latestRate).toBe(60);
+ expect(history.latestRate).toBe(100);
expect(history.samples).toHaveLength(1);
history = recordTokenSpeed(history, { startedAt: 2, speed: speed(50, 1100) });
expect(history.samples.map((sample) => sample.durationMs)).toEqual([1500, 2600]);
diff --git a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx
index 2f90f5e316..390833b615 100644
--- a/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx
+++ b/apps/mobile/src/__tests__/runningTokenRateHistory.test.tsx
@@ -147,3 +147,11 @@ it('drops the previous rate when a new local turn starts during the terminal lin
).toBe('waiting');
expect(report({ outputTokens: 40, generationDurationMs: 1000 })).toBe('40');
});
+
+it('keeps the recent speed separate from the calibrated final average', () => {
+ expect(report({ tokenSpeed: { rate: 50, average: 40, tokens: 80, elapsedMs: 2000, streaming: true } })).toBe('50');
+ expect(report({ startedAt: null, tokenSpeed: { rate: 100, average: 100, tokens: 300, elapsedMs: 3000, streaming: false } })).toBe('50');
+ // A final report is not new evidence of recent throughput.
+ act(() => vi.advanceTimersByTime(60_000));
+ expect(report()).toBe('waiting');
+});
diff --git a/docs/dev-rules/protocol-compatibility.md b/docs/dev-rules/protocol-compatibility.md
index 7cf1c9888d..14627f6620 100644
--- a/docs/dev-rules/protocol-compatibility.md
+++ b/docs/dev-rules/protocol-compatibility.md
@@ -138,9 +138,13 @@ schema、数据库或 Mobile 原生指纹。完整管理需要两端客户端更
## 实时生成速度
既有 maker status 可选携带 `tokenSpeed`(`rate`、`average`、`tokens`、`elapsedMs`、
-`streaming`),由主机按 Pi `pi-token-speed` 扩展算法测得;仅用于显示,不参与费用、缓存或
-上下文计数。新客户端校验数值,非法即丢弃;旧主机省略时沿用原 usage 计数路径,旧客户端忽略
-新增字段。主机检测到挂起或时钟异常时,本轮后续帧不再携带该字段并标记
+`streaming`),由主机计算;Codex 使用真实输出用量与配对生成时长,最近三个有效区间按
+时长加权(包含请求后的首响应等待,排除工具与审批等待)。Claude Code / Pi 使用基于
+`pi-token-speed` 的流式文字/思考/所有工具参数估算,从首个内容块开始,工具调用生成
+结束即暂停。两种口径不能直接作为模型性能横向排名。收尾 `rate` 仍携带平均值以兼容旧端;
+新端只更新本轮平均,保留最近速度及曲线,不把最终校准当作新的速度样本。
+仅用于显示,不参与费用、缓存或上下文计数。新客户端校验数值,非法即丢弃;旧主机省略时
+沿用原 usage 计数路径,旧客户端忽略新增字段。主机检测到挂起或时钟异常时,本轮后续帧不再携带该字段并标记
`generationReliable: false`,客户端据此丢弃已保留的速度。无需服务端更新、新通道、权限或
数据库 migration。
diff --git a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts b/packages/maker-core/src/agents/claude-code/generation-timing.test.ts
index 4044f4314e..844bf3c03d 100644
--- a/packages/maker-core/src/agents/claude-code/generation-timing.test.ts
+++ b/packages/maker-core/src/agents/claude-code/generation-timing.test.ts
@@ -2017,7 +2017,7 @@ describe('claude live token speed', () => {
vi.useRealTimers();
});
- it('counts main-thread deltas, pauses on non-writing tools and reports the real average at the end', async () => {
+ it('counts main-thread deltas, pauses on tools and reports the real average at the end', async () => {
vi.useFakeTimers();
const ctx = createTranslatorCtx();
const queue = createAsyncQueue<AgentEvent>();
@@ -2038,7 +2038,7 @@ describe('claude live token speed', () => {
stream({ type: 'message_delta', usage: { output_tokens: 12 } }, 2_000);
// Subagent output is not the main thread's speed.
stream({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'x y z' } }, 5_000, 'toolu_1');
- expect(ctx.rt.generation.tokenSpeed.snapshot(5_000)).toMatchObject({ tokens: 4, elapsedMs: 1_000 });
+ expect(ctx.rt.generation.tokenSpeed.snapshot(5_000)).toMatchObject({ tokens: 15, elapsedMs: 1_000 });
stream({ type: 'message_start', message: { model: 'claude-sonnet-4.5', usage: { input_tokens: 10 } } }, 12_000);
stream({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }, 12_000);
stream({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'five six' } }, 12_000);
@@ -2129,15 +2129,21 @@ describe('claude live token speed', () => {
resetClaudeGenerationTiming(ctx.rt.generation);
});
- it('counts Write tool arguments as generated output', () => {
+ it.each(['Write', 'mcp__custom_tool'])('counts %s arguments and excludes execution time', (name) => {
+ vi.useFakeTimers();
+ vi.setSystemTime(1_000);
const ctx = createTranslatorCtx();
const queue = createAsyncQueue<AgentEvent>();
const stream = (event: Record<string, unknown>) =>
translateSdkMessage({ type: 'stream_event', event }, queue, ctx);
stream({ type: 'message_start', message: { model: 'claude-sonnet-4.5', usage: { input_tokens: 10 } } });
- stream({ type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_w', name: 'Write', input: {} } });
+ stream({ type: 'content_block_start', index: 0, content_block: { type: 'tool_use', id: 'toolu_w', name, input: {} } });
+ vi.setSystemTime(2_000);
stream({ type: 'content_block_delta', index: 0, delta: { type: 'input_json_delta', partial_json: '{"content":"a b c"}' } });
expect(ctx.rt.generation.tokenSpeed.snapshot()?.tokens).toBeGreaterThan(0);
+ stream({ type: 'content_block_stop', index: 0 });
+ vi.setSystemTime(12_000);
+ expect(ctx.rt.generation.tokenSpeed.snapshot()?.elapsedMs).toBe(1_000);
resetClaudeGenerationTiming(ctx.rt.generation);
queue.end();
});
diff --git a/packages/maker-core/src/agents/claude-code/translator.ts b/packages/maker-core/src/agents/claude-code/translator.ts
index 893aef0891..8f5a6e52d3 100644
--- a/packages/maker-core/src/agents/claude-code/translator.ts
+++ b/packages/maker-core/src/agents/claude-code/translator.ts
@@ -38,7 +38,6 @@ import {
import type { UsageTracker } from '../shared/usage-tracker.js';
import { isModelAccessDenied } from './model-access-error.js';
import { attachLiveGeneration, sampleGenerationDuration } from '../shared/live-generation-snapshot.js';
-import { isFileWritingTool } from '../shared/token-speed.js';
import {
beginClaudeGeneration,
beginClaudeGenerationAtRequestStart,
@@ -1697,7 +1696,7 @@ function observeClaudeTokenSpeed(
case 'content_block_delta': {
const delta = event.delta;
const text = delta?.type === 'input_json_delta'
- ? (isFileWritingTool(tools.get(index)) ? delta.partial_json : undefined)
+ ? (tools.has(index) ? delta.partial_json : undefined)
: delta?.text ?? delta?.thinking;
if (typeof text === 'string' && speed.recordDelta(text)) {
queue.push({ type: 'status', data: ccLiveStatus(ctx, 'Generating...', true), source: 'claude-code' });
@@ -1705,7 +1704,7 @@ function observeClaudeTokenSpeed(
return;
}
case 'content_block_stop':
- if (tools.has(index) && !isFileWritingTool(tools.get(index))) speed.pause();
+ if (tools.has(index)) speed.pause();
return;
}
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 75b8e50dd3..e53a8d40b5 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -18933,6 +18933,7 @@ describe('CodexAgent MCP thread context hooks', () => {
const expectSample = (outputTokens: number, generationDurationMs: number) =>
expect(handle.getUsageSnapshot()).toMatchObject({
outputTokens, generationDurationMs, generationReliable: true,
+ tokenSpeed: { tokens: outputTokens, elapsedMs: generationDurationMs, rate: 100, streaming: true },
});
expectSample(100, 1_000);
const tool = { id: 'tool-1', type: 'mcpToolCall', server: 'test', tool: 'read', arguments: {} };
@@ -18973,6 +18974,7 @@ describe('CodexAgent MCP thread context hooks', () => {
expect(events.find((event) => event.type === 'done')?.data.usage.durationMs).toBe(5_000);
expect(events.filter((event) => event.type === 'status').at(-1)?.data).toMatchObject({
status: 'Done', outputTokens: 500, generationDurationMs: 5_000,
+ tokenSpeed: { tokens: 500, elapsedMs: 5_000, average: 100, streaming: false },
});
await handle.send({ type: 'user', content: 'next turn' });
expect(handle.getUsageSnapshot().outputTokens).toBe(0);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index 33e8430e0f..4f4be5d6bd 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -3744,7 +3744,7 @@ assertRouteCurrent();
const usageTracker = new UsageTracker();
const translatorRt: CodexRuntimeState = newCodexRuntimeState();
const liveUsageSnapshot = () => attachLiveGeneration(usageTracker.snapshot(), {
- tokenSpeed: translatorRt.tokenSpeed.snapshot(),
+ tokenSpeed: translatorRt.generationTimingReliable ? translatorRt.tokenSpeed.snapshot() : undefined,
outputTokens: usageTracker.getTurnUsage().output,
durationMs: translatorRt.generationOutputDurationMs,
openStartedAt: translatorRt.generationStartedAt,
@@ -11058,7 +11058,7 @@ assertRouteCurrent();
const realTurnUsage = usageTracker.getTurnUsage();
const realTurnUsageSegments = usageTracker.getTurnUsageSegments();
finalizeCodexGenerationTurn(translatorRt, turn.id);
- translatorRt.tokenSpeed.stop(realTurnUsage.output);
+ translatorRt.tokenSpeed.stop();
const generationDurationMs = codexGenerationDurationMs(translatorRt);
const codexDoneUsage = {
promptTokens: realTurnUsage.input,
@@ -11279,7 +11279,7 @@ assertRouteCurrent();
data: {
status: 'Done',
...attachLiveGeneration(endSnap, {
- tokenSpeed: translatorRt.tokenSpeed.snapshot(),
+ tokenSpeed: translatorRt.generationTimingReliable ? translatorRt.tokenSpeed.snapshot() : undefined,
outputTokens: realTurnUsage.output,
durationMs: translatorRt.generationOutputDurationMs,
openStartedAt: null,
@@ -12345,6 +12345,14 @@ assertRouteCurrent();
translatorRt.generationDurationMs,
translatorRt.generationStartedAt,
);
+ if (translatorRt.generationTimingReliable) {
+ translatorRt.tokenSpeed.recordUsage(
+ usageTracker.getTurnUsage().output,
+ translatorRt.generationOutputDurationMs,
+ );
+ } else {
+ translatorRt.tokenSpeed.invalidate();
+ }
}
maybePushUsageRefresh();
// Maker Memory flush 观察 (A 轻版: 只打日志). makerMemoryEnabled 关时 controller 为 null。
diff --git a/packages/maker-core/src/agents/codex/translator.test.ts b/packages/maker-core/src/agents/codex/translator.test.ts
index b6a25ef5a4..3b96eadcac 100644
--- a/packages/maker-core/src/agents/codex/translator.test.ts
+++ b/packages/maker-core/src/agents/codex/translator.test.ts
@@ -516,12 +516,12 @@ describe('Codex generation timing', () => {
try {
const rt = newCodexRuntimeState();
beginCodexGenerationTurn(rt, 'turn-1', 1_000);
- rt.tokenSpeed.recordDelta('a b c d e f g h i j', 1_000);
+ rt.tokenSpeed.recordUsage(10, 1_000);
wallClockSpy.mockReturnValue(40_000);
finalizeCodexGenerationTurn(rt, 'turn-1', 2_000);
expect(codexGenerationDurationMs(rt)).toBeUndefined();
// The suspended wall clock would dilute the live speed too.
- expect(rt.tokenSpeed.snapshot(40_000)).toBeUndefined();
+ expect(rt.tokenSpeed.snapshot()).toBeUndefined();
} finally {
wallClockSpy.mockRestore();
}
@@ -2484,7 +2484,7 @@ it('carries the provider final phase from item start onto the first delta', asyn
expect(await collect(q)).toContainEqual({ type: 'text', source: 'codex', data: { text: 'Visible now', isFinal: false, agentMessageId: 'final', phase: 'final_answer' } });
});
-it('measures live tok/s from visible deltas and pauses while a command runs', () => {
+it('does not count visible summaries as output and pauses the usage clock while a command runs', () => {
vi.useFakeTimers();
try {
const rt = newCodexRuntimeState(), q = createAsyncQueue<AgentEvent>(), ctx = makeCtx(rt);
@@ -2493,12 +2493,13 @@ it('measures live tok/s from visible deltas and pauses while a command runs', ()
translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item: { type: 'agentMessage', id: 'm1', text: '' } }, q, ctx);
vi.setSystemTime(1_500);
translateAgentMessageDelta({ threadId: 'thread', turnId: 'turn', itemId: 'm1', delta: 'one two three four' }, q, ctx);
- expect(rt.tokenSpeed.snapshot()).toMatchObject({ streaming: true, tokens: 4, elapsedMs: 500 });
+ expect(rt.tokenSpeed.snapshot()).toBeUndefined();
translateItemNotification('started', { threadId: 'thread', turnId: 'turn', item: { type: 'commandExecution', id: 'c1', command: 'ls' } }, q, ctx);
vi.setSystemTime(9_500);
// The command is still running: its time is not generation time.
- expect(rt.tokenSpeed.snapshot()?.elapsedMs).toBe(500);
- rt.tokenSpeed.stop(20);
+ expect(rt.generationDurationMs).toBe(500);
+ rt.tokenSpeed.recordUsage(20, rt.generationDurationMs);
+ rt.tokenSpeed.stop();
expect(rt.tokenSpeed.snapshot()).toMatchObject({ streaming: false, tokens: 20, elapsedMs: 500, average: 40 });
} finally {
vi.useRealTimers();
diff --git a/packages/maker-core/src/agents/codex/translator.ts b/packages/maker-core/src/agents/codex/translator.ts
index 2fc6f689d4..726a47dc63 100644
--- a/packages/maker-core/src/agents/codex/translator.ts
+++ b/packages/maker-core/src/agents/codex/translator.ts
@@ -32,7 +32,7 @@ import {
stripInternalWebCitations,
} from '@cindy/maker-shared/internal-citation';
-import { TokenSpeedMeter } from '../shared/token-speed.js';
+import { UsageTokenSpeedMeter } from '../shared/token-speed.js';
import type { AgentEvent, AgentTaskStatus, AgentTaskUpdateEventData } from '../../types/events.js';
import { normalizeAccountRateLimitSnapshot } from '../../types/account-rate-limits.js';
import type { AsyncQueue } from '../shared/async-queue.js';
@@ -80,8 +80,8 @@ export interface CodexRuntimeState {
reasoningTextLen: Map<string, number>;
/** item.id → agentMessage 已 emit 文本字符长度(citation 归一化后的空间,见 handleAgentMessage)。 */
itemTextLen: Map<string, number>;
- /** Live tok/s shown in the status bar (Pi extension algorithm). */
- tokenSpeed: TokenSpeedMeter;
+ /** Live tok/s from accepted usage and its paired generation time. */
+ tokenSpeed: UsageTokenSpeedMeter;
/** Current model-active interval start; null while tools/approvals own the turn. */
generationStartedAt: number | null;
/** Tool/approval boundaries currently owning the turn. Generation resumes after all finish. */
@@ -133,7 +133,7 @@ export function newCodexRuntimeState(): CodexRuntimeState {
reasoningStartedAt: new Map(),
reasoningTextLen: new Map(),
itemTextLen: new Map(),
- tokenSpeed: new TokenSpeedMeter(),
+ tokenSpeed: new UsageTokenSpeedMeter(),
generationStartedAt: null,
generationPendingToolIds: new Set(),
generationDurationMs: 0,
@@ -319,9 +319,6 @@ function noteCodexGenerationBoundary(
// for pause pairing but fail closed for TPS.
rt.generationTimingReliable = false;
}
- if (phase === 'started' && (item.type === 'reasoning' || item.type === 'agentMessage')) {
- rt.tokenSpeed.start();
- }
if (
typeof item.type !== 'string' ||
!CODEX_GENERATION_PAUSE_ITEM_TYPES.has(item.type)
@@ -335,7 +332,6 @@ function noteCodexGenerationBoundary(
const pauseId = `item:${item.id}`;
if (phase === 'started') {
// The model finished emitting this call; its execution is not generation time.
- rt.tokenSpeed.pause(receivedAt);
pauseCodexGeneration(rt, turnId, pauseId, receivedAt);
return;
}
@@ -1118,7 +1114,6 @@ function emitAgentMessageProgress(
ctx.rt.itemRawText.set(itemId, rawText);
ctx.rt.itemTextLen.set(itemId, emitted.length);
if (delta.length === 0) return;
- ctx.rt.tokenSpeed.recordDelta(delta);
queue.push({
type: 'text',
data: { text: delta, isFinal: false, agentMessageId: itemId,
@@ -1334,7 +1329,6 @@ export function translateReasoningSummaryTextDelta(
ctx: CodexTranslateContext,
): void {
if (!params.delta) return;
- ctx.rt.tokenSpeed.recordDelta(params.delta);
ensureReasoningStarted(params.itemId, queue, ctx);
const prevLen = ctx.rt.reasoningTextLen.get(params.itemId) ?? 0;
ctx.rt.reasoningTextLen.set(params.itemId, prevLen + params.delta.length);
@@ -1369,7 +1363,6 @@ export function translateReasoningTextDelta(
ctx: CodexTranslateContext,
): void {
if (!params.delta) return;
- ctx.rt.tokenSpeed.recordDelta(params.delta);
ensureReasoningStarted(params.itemId, queue, ctx);
const prevLen = ctx.rt.reasoningTextLen.get(params.itemId) ?? 0;
ctx.rt.reasoningTextLen.set(params.itemId, prevLen + params.delta.length);
diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
index 68d8ed0cd0..979735aebf 100644
--- a/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
+++ b/packages/maker-core/src/agents/pi/__tests__/pi-translator.test.ts
@@ -2269,7 +2269,7 @@ describe('pi translator live token speed', () => {
const speedOf = (event: AgentEvent | undefined) =>
(event?.data as { tokenSpeed?: Record<string, unknown> } | undefined)?.tokenSpeed;
- it('counts streamed text, pauses on non-writing tools and snaps to real output at the end', () => {
+ it('counts streamed text, pauses on tools and snaps to real output at the end', () => {
vi.useFakeTimers();
try {
const ctx = createPiTranslateContext(noopLogger);
@@ -2287,10 +2287,11 @@ describe('pi translator live token speed', () => {
expect(live).toMatchObject({ streaming: true, tokens: 6, elapsedMs: 500 });
expect(live?.rate).toBeGreaterThan(0);
- // A bash call: its arguments are not counted and its execution is paused out.
+ // A bash call: count generated arguments, exclude execution time.
update({ type: 'toolcall_start', contentIndex: 1, toolCall: { name: 'bash' } }, 1_600);
update({ type: 'toolcall_delta', contentIndex: 1, delta: '{"command":"ls -la"}', toolCall: { name: 'bash' } }, 1_700);
update({ type: 'toolcall_end', contentIndex: 1, toolCall: { name: 'bash' } }, 2_000);
+ expect(ctx.tokenSpeed.snapshot(10_000)).toMatchObject({ tokens: 17, elapsedMs: 1_000 });
update({ type: 'text_delta', contentIndex: 0, delta: 'seven eight' }, 12_000);
vi.setSystemTime(12_500);
@@ -2333,7 +2334,7 @@ describe('pi translator live token speed', () => {
}
});
- it('counts file-writing tool arguments and starts each turn fresh', () => {
+ it.each(['write', 'mcp__custom_tool'])('counts %s arguments, excludes execution and starts each turn fresh', (name) => {
vi.useFakeTimers();
try {
const ctx = createPiTranslateContext(noopLogger);
@@ -2342,9 +2343,13 @@ describe('pi translator live token speed', () => {
translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: {
type: 'toolcall_delta', contentIndex: 0, delta: 'a b c',
- partial: { content: [{ type: 'toolCall', name: 'write' }] },
+ partial: { content: [{ type: 'toolCall', name }] },
} }), queue, ctx);
expect(speedOf(events.filter((e) => e.type === 'status').at(-1))).toMatchObject({ tokens: 3 });
+ vi.setSystemTime(2_000);
+ translatePiEvent(ev({ type: 'message_update', assistantMessageEvent: { type: 'toolcall_end', toolCall: { name } } }), queue, ctx);
+ vi.setSystemTime(12_000);
+ expect(ctx.tokenSpeed.snapshot()?.elapsedMs).toBe(1_000);
translatePiEvent(ev({ type: 'agent_settled' }), queue, ctx);
events.length = 0;
translatePiEvent(ev({ type: 'agent_start' }), queue, ctx);
diff --git a/packages/maker-core/src/agents/pi/translator.ts b/packages/maker-core/src/agents/pi/translator.ts
index 73eeef2dd8..b2af2bfaee 100644
--- a/packages/maker-core/src/agents/pi/translator.ts
+++ b/packages/maker-core/src/agents/pi/translator.ts
@@ -32,7 +32,7 @@ import {
import type { AgentEvent, AgentTaskUpdateEventData, UsageSnapshot } from '../../types/index.js';
import type { AsyncQueue } from '../shared/async-queue.js';
import { attachLiveGeneration } from '../shared/live-generation-snapshot.js';
-import { TokenSpeedMeter, isFileWritingTool } from '../shared/token-speed.js';
+import { TokenSpeedMeter } from '../shared/token-speed.js';
import type { UsageSegment } from '../shared/usage-tracker.js';
import {
UPSTREAM_OVERLOAD_REASON,
@@ -1233,8 +1233,6 @@ function observePiTokenSpeed(
ctx.tokenSpeed.start();
return;
case 'toolcall_delta':
- if (!isFileWritingTool(piDeltaToolName(delta))) return;
- // falls through
case 'text_delta':
case 'thinking_delta':
if (typeof delta.delta === 'string' && ctx.tokenSpeed.recordDelta(delta.delta)) {
@@ -1242,20 +1240,11 @@ function observePiTokenSpeed(
}
return;
case 'toolcall_end':
- if (!isFileWritingTool(piDeltaToolName(delta))) ctx.tokenSpeed.pause();
+ ctx.tokenSpeed.pause();
return;
}
}
-function piDeltaToolName(delta: Record<string, unknown>): unknown {
- const toolCall = delta.toolCall as { name?: unknown } | undefined;
- if (toolCall?.name !== undefined) return toolCall.name;
- const partial = delta.partial as { content?: Array<{ type?: unknown; name?: unknown }> } | undefined;
- const index = typeof delta.contentIndex === 'number' ? delta.contentIndex : 0;
- const block = partial?.content?.[index];
- return block?.type === 'toolCall' ? block.name : undefined;
-}
-
function handleAssistantDelta(
delta: Record<string, unknown>,
queue: AsyncQueue<AgentEvent>,
diff --git a/packages/maker-core/src/agents/shared/token-speed.test.ts b/packages/maker-core/src/agents/shared/token-speed.test.ts
index 5459202f17..46ceebf611 100644
--- a/packages/maker-core/src/agents/shared/token-speed.test.ts
+++ b/packages/maker-core/src/agents/shared/token-speed.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { estimateDeltaTokens, isFileWritingTool, TokenSpeedMeter } from './token-speed.js';
+import { estimateDeltaTokens, TokenSpeedMeter, UsageTokenSpeedMeter } from './token-speed.js';
describe('TokenSpeedMeter (pi-token-speed algorithm)', () => {
it('counts deltas with the word/punctuation estimate, one token per CJK character', () => {
@@ -165,9 +165,41 @@ describe('TokenSpeedMeter (pi-token-speed algorithm)', () => {
const due = [0, 50, 100, 260, 300, 520].map((t) => meter.recordDelta('a b c d e', t));
expect(due).toEqual([true, false, false, true, false, true]);
});
+});
- it('counts only file-writing tool arguments', () => {
- expect(['edit', 'write', 'Edit', 'Write', 'MultiEdit', 'NotebookEdit'].every(isFileWritingTool)).toBe(true);
- expect(['bash', 'Read', 'Grep', undefined].some(isFileWritingTool)).toBe(false);
+describe('UsageTokenSpeedMeter', () => {
+ it('uses the last three paired intervals weighted by duration, including hidden output', () => {
+ const meter = new UsageTokenSpeedMeter();
+ expect(meter.snapshot()).toBeUndefined();
+ meter.recordUsage(10, 500);
+ expect(meter.snapshot()?.rate).toBe(0);
+ meter.recordUsage(50, 1_000);
+ meter.recordUsage(150, 5_000);
+ expect(meter.snapshot()?.rate).toBe(30);
+ meter.recordUsage(190, 6_000);
+ meter.recordUsage(250, 8_000);
+ // Last three intervals: (100 + 40 + 60) / (4 + 1 + 2).
+ expect(meter.snapshot()?.rate).toBeCloseTo(200 / 7);
+ meter.recordUsage(250, 20_000);
+ expect(meter.snapshot()?.elapsedMs).toBe(8_000);
+ meter.stop();
+ expect(meter.snapshot()).toMatchObject({ streaming: false, average: 31.25, tokens: 250, elapsedMs: 8_000 });
+ meter.recordUsage(300, 30_000);
+ expect(meter.snapshot()?.tokens).toBe(250);
+ });
+
+ it('withdraws invalid or backwards measurements until the next turn', () => {
+ const meter = new UsageTokenSpeedMeter();
+ for (const [tokens, elapsed] of [[90, 2_000], [110, 900], [NaN, 2_000]]) {
+ meter.reset();
+ meter.recordUsage(100, 1_000);
+ meter.recordUsage(tokens, elapsed);
+ expect(meter.snapshot()).toBeUndefined();
+ }
+ meter.reset();
+ meter.recordUsage(20, 1_000);
+ expect(meter.snapshot()?.rate).toBe(20);
+ meter.invalidate();
+ expect(meter.snapshot()).toBeUndefined();
});
});
diff --git a/packages/maker-core/src/agents/shared/token-speed.ts b/packages/maker-core/src/agents/shared/token-speed.ts
index c11e94aef0..3dc46d3ed5 100644
--- a/packages/maker-core/src/agents/shared/token-speed.ts
+++ b/packages/maker-core/src/agents/shared/token-speed.ts
@@ -5,12 +5,12 @@ import type { TokenSpeedSnapshot } from '@cindy/maker-shared/usage-format';
* with its `estimate` count strategy and `average` end-of-stream behaviour:
*
* - one measurement per turn, started by the first content block;
- * - each text / thinking delta (and file-writing tool argument delta) is
+ * - each text / thinking delta (and every tool argument delta) is
* counted with the word-boundary estimate `/\w+|[^\s\w]/g`;
* - current speed = tokens in the last 1s window / time since the token
* before them, or since generation resumed (min 100ms); a window with
* fewer than 5 tokens keeps the previous reading;
- * - the clock pauses when a non file-writing tool call ends and resumes when
+ * - the clock pauses when a tool call ends and resumes when
* the next content block starts or the next counted delta arrives;
* - at turn end the count is snapped to the provider's real output and the
* speed becomes total tokens / elapsed generation time.
@@ -178,9 +178,67 @@ export class TokenSpeedMeter {
}
}
-/** Pi counts argument deltas of tools that write the model's output into files. */
-const FILE_WRITING_TOOLS = new Set(['edit', 'write', 'multiedit', 'notebookedit']);
+/**
+ * Codex streams reasoning summaries, not all generated tokens. Measure accepted
+ * provider usage against its paired generation clock instead of counting text.
+ * Smooth the last three intervals by time, never by averaging their rates.
+ */
+export class UsageTokenSpeedMeter {
+ private tokens = 0;
+ private elapsedMs = 0;
+ private baseline = { tokens: 0, elapsedMs: 0 };
+ private intervals: { tokens: number; elapsedMs: number }[] = [];
+ private streaming = true;
+ private invalid = false;
+
+ reset(): void {
+ this.tokens = 0;
+ this.elapsedMs = 0;
+ this.baseline = { tokens: 0, elapsedMs: 0 };
+ this.intervals = [];
+ this.streaming = true;
+ this.invalid = false;
+ }
+
+ invalidate(): void {
+ this.invalid = true;
+ }
-export function isFileWritingTool(name: unknown): boolean {
- return typeof name === 'string' && FILE_WRITING_TOOLS.has(name.toLowerCase());
+ recordUsage(tokens: number, elapsedMs: number): void {
+ if (this.invalid || !this.streaming) return;
+ if (!Number.isFinite(tokens) || !Number.isFinite(elapsedMs) ||
+ tokens < this.tokens || elapsedMs < this.elapsedMs) {
+ this.invalidate();
+ return;
+ }
+ // Repeated usage cannot pair old tokens with a newer clock.
+ if (tokens === this.tokens) return;
+ this.tokens = tokens;
+ this.elapsedMs = elapsedMs;
+ const duration = elapsedMs - this.baseline.elapsedMs;
+ if (duration < 1_000) return;
+ this.intervals.push({ tokens: tokens - this.baseline.tokens, elapsedMs: duration });
+ this.intervals = this.intervals.slice(-3);
+ this.baseline = { tokens, elapsedMs };
+ }
+
+ stop(): void {
+ this.streaming = false;
+ }
+
+ snapshot(): TokenSpeedSnapshot | undefined {
+ if (this.invalid || this.tokens <= 0 || this.elapsedMs <= 0) return undefined;
+ const total = this.intervals.reduce((sum, interval) => ({
+ tokens: sum.tokens + interval.tokens,
+ elapsedMs: sum.elapsedMs + interval.elapsedMs,
+ }), { tokens: 0, elapsedMs: 0 });
+ const average = this.tokens * 1_000 / this.elapsedMs;
+ return {
+ rate: this.streaming ? (total.elapsedMs > 0 ? total.tokens * 1_000 / total.elapsedMs : 0) : average,
+ average,
+ tokens: this.tokens,
+ elapsedMs: this.elapsedMs,
+ streaming: this.streaming,
+ };
+ }
}
diff --git a/packages/maker-shared/src/runningTokenRateHistory.ts b/packages/maker-shared/src/runningTokenRateHistory.ts
index 6bd1a90f8e..aaeca82025 100644
--- a/packages/maker-shared/src/runningTokenRateHistory.ts
+++ b/packages/maker-shared/src/runningTokenRateHistory.ts
@@ -170,7 +170,7 @@ export function clearRateHistoryCache(): void {
}
/**
- * Host-measured tok/s (Pi `pi-token-speed` algorithm, see maker-core
+ * Host-measured tok/s (usage intervals or streaming estimates, see maker-core
* `token-speed.ts`). Optional additive status field: old hosts omit it and the
* counter-based history above stays in charge.
*/
@@ -213,9 +213,11 @@ export function recordTokenSpeed(
lastReport: null,
speedOffsetMs: offset,
speedElapsedMs: speed.elapsedMs,
- // No reading yet this turn: keep showing the token count rather than "0 tok/s".
- latestRate: speed.streaming && speed.rate <= 0 ? (reset ? null : history.latestRate) : speed.rate,
- latestSampleAt: input.now ?? Date.now(),
+ // The final average has its own UI field. It is not a new recent-speed sample.
+ // Without a live reading this turn, keep showing the token count.
+ latestRate: speed.streaming && speed.rate > 0 ? speed.rate : (reset ? null : history.latestRate),
+ latestSampleAt: speed.streaming && speed.rate > 0
+ ? (input.now ?? Date.now()) : (reset ? undefined : history.latestSampleAt),
};
const at = offset + speed.elapsedMs;
const lastAt = reset ? offset : (history.samples.at(-1)?.durationMs ?? offset);