@useavalon/caelence-agent 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,8 @@
2
2
  * Agent event kinds. `error` and `completion` are the two terminal kinds.
3
3
  */
4
4
 
5
+ import type { TokenUsage } from "./usage.ts";
6
+
5
7
  export type AgentEvent =
6
8
  | { kind: "text_delta"; text: string }
7
9
  | { kind: "reasoning_delta"; text: string }
@@ -85,13 +87,9 @@ export interface MainModelProvider {
85
87
  request: ProviderTurnRequest,
86
88
  options?: { signal?: AbortSignal },
87
89
  ): AsyncIterable<ProviderStreamEvent>;
88
- /** Real usage from the last stream, if the provider reported it. */
89
- takeUsage?():
90
- | {
91
- promptTokens: number;
92
- completionTokens: number;
93
- totalTokens: number;
94
- costUsd?: number;
95
- }
96
- | undefined;
90
+ /**
91
+ * Billed usage for the turn's model calls, if the provider reported it.
92
+ * May return a promise so streamed OpenRouter usage can finish arriving.
93
+ */
94
+ takeUsage?(): TokenUsage | undefined | Promise<TokenUsage | undefined>;
97
95
  }
@@ -0,0 +1,37 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ DEFAULT_REASONING_EFFORT,
4
+ parseReasoningEffort,
5
+ REASONING_EFFORTS,
6
+ resolveReasoningEffort,
7
+ tryParseReasoningEffort,
8
+ } from "./reasoning.ts";
9
+
10
+ describe("reasoning effort", () => {
11
+ test("accepts OpenRouter effort values", () => {
12
+ expect(REASONING_EFFORTS).toEqual(["none", "minimal", "low", "medium", "high", "xhigh"]);
13
+ expect(tryParseReasoningEffort("HIGH")).toBe("high");
14
+ expect(tryParseReasoningEffort(" xhigh ")).toBe("xhigh");
15
+ expect(tryParseReasoningEffort("max")).toBeUndefined();
16
+ expect(parseReasoningEffort(undefined)).toBe(DEFAULT_REASONING_EFFORT);
17
+ expect(parseReasoningEffort("nope")).toBe("low");
18
+ });
19
+
20
+ test("prefers option, then env, then config", () => {
21
+ expect(
22
+ resolveReasoningEffort({
23
+ option: "medium",
24
+ config: "high",
25
+ env: { HARNESS_REASONING_EFFORT: "xhigh" },
26
+ }),
27
+ ).toBe("medium");
28
+ expect(
29
+ resolveReasoningEffort({
30
+ config: "high",
31
+ env: { HARNESS_REASONING_EFFORT: "xhigh" },
32
+ }),
33
+ ).toBe("xhigh");
34
+ expect(resolveReasoningEffort({ config: "minimal", env: {} })).toBe("minimal");
35
+ expect(resolveReasoningEffort({ env: { HARNESS_REASONING_EFFORT: "nope" } })).toBe("low");
36
+ });
37
+ });
@@ -0,0 +1,32 @@
1
+ /** OpenRouter `reasoning.effort` values. */
2
+ export const REASONING_EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh"] as const;
3
+ export type ReasoningEffort = (typeof REASONING_EFFORTS)[number];
4
+
5
+ export const DEFAULT_REASONING_EFFORT: ReasoningEffort = "low";
6
+
7
+ export const REASONING_EFFORT_USAGE = "Effort is none, minimal, low, medium, high, or xhigh.";
8
+
9
+ export function tryParseReasoningEffort(raw: string | undefined): ReasoningEffort | undefined {
10
+ const value = raw?.trim().toLowerCase();
11
+ return (REASONING_EFFORTS as readonly string[]).includes(value ?? "")
12
+ ? (value as ReasoningEffort)
13
+ : undefined;
14
+ }
15
+
16
+ export function parseReasoningEffort(raw: string | undefined): ReasoningEffort {
17
+ return tryParseReasoningEffort(raw) ?? DEFAULT_REASONING_EFFORT;
18
+ }
19
+
20
+ export function resolveReasoningEffort(input: {
21
+ option?: string;
22
+ config?: string;
23
+ env?: Record<string, string | undefined>;
24
+ }): ReasoningEffort {
25
+ const env = input.env ?? process.env;
26
+ return (
27
+ tryParseReasoningEffort(input.option) ??
28
+ tryParseReasoningEffort(env.HARNESS_REASONING_EFFORT) ??
29
+ tryParseReasoningEffort(input.config) ??
30
+ DEFAULT_REASONING_EFFORT
31
+ );
32
+ }
@@ -143,6 +143,118 @@ describe("runTurn", () => {
143
143
  }
144
144
  });
145
145
 
146
+ test("waits for async takeUsage so streamed cost is not dropped", async () => {
147
+ const cwd = await mkdtemp(join(tmpdir(), "harness-usage-async-"));
148
+ try {
149
+ const provider: MainModelProvider = {
150
+ kind: "fake",
151
+ modelId: "fake",
152
+ async *stream() {
153
+ yield { type: "done" };
154
+ },
155
+ async takeUsage() {
156
+ await Promise.resolve();
157
+ return {
158
+ promptTokens: 80_000,
159
+ completionTokens: 4_000,
160
+ totalTokens: 84_000,
161
+ costUsd: 5.4,
162
+ };
163
+ },
164
+ };
165
+ const events: AgentEvent[] = [];
166
+ await runTurn(
167
+ {
168
+ cwd,
169
+ name: "test",
170
+ systemPrompt: "test",
171
+ tools: [],
172
+ approval: createExecApprovalGate({ policy: "deny" }),
173
+ store: createFileSessionStore(cwd),
174
+ provider,
175
+ constructAgent: () => ({
176
+ async run(_message, emit) {
177
+ emit({ kind: "text_delta", text: "ok" });
178
+ },
179
+ }),
180
+ },
181
+ { message: "hi" },
182
+ (event) => events.push(event),
183
+ );
184
+ const usage = events.find((event) => event.kind === "usage");
185
+ expect(usage).toMatchObject({ kind: "usage", costUsd: 5.4, promptTokens: 80_000 });
186
+ } finally {
187
+ await rm(cwd, { recursive: true, force: true });
188
+ }
189
+ });
190
+
191
+ test("does not keep billed usage from a failed turn for the next turn", async () => {
192
+ const cwd = await mkdtemp(join(tmpdir(), "harness-usage-fail-"));
193
+ try {
194
+ let stored:
195
+ | { promptTokens: number; completionTokens: number; totalTokens: number; costUsd: number }
196
+ | undefined = {
197
+ promptTokens: 30,
198
+ completionTokens: 5,
199
+ totalTokens: 35,
200
+ costUsd: 0.03,
201
+ };
202
+ const provider: MainModelProvider = {
203
+ kind: "fake",
204
+ modelId: "fake",
205
+ async *stream() {
206
+ yield { type: "done" };
207
+ },
208
+ takeUsage() {
209
+ const usage = stored;
210
+ stored = undefined;
211
+ return usage;
212
+ },
213
+ };
214
+ const deps = {
215
+ cwd,
216
+ name: "test",
217
+ systemPrompt: "test",
218
+ tools: [],
219
+ approval: createExecApprovalGate({ policy: "deny" }),
220
+ store: createFileSessionStore(cwd),
221
+ provider,
222
+ };
223
+ const first: AgentEvent[] = [];
224
+ await runTurn(
225
+ {
226
+ ...deps,
227
+ constructAgent: () => ({
228
+ async run() {
229
+ throw new Error("model failed");
230
+ },
231
+ }),
232
+ },
233
+ { message: "hi" },
234
+ (event) => first.push(event),
235
+ );
236
+ expect(first.some((event) => event.kind === "usage")).toBe(false);
237
+ expect(first.some((event) => event.kind === "error")).toBe(true);
238
+
239
+ const second: AgentEvent[] = [];
240
+ await runTurn(
241
+ {
242
+ ...deps,
243
+ constructAgent: () => ({
244
+ async run(_message, emit) {
245
+ emit({ kind: "text_delta", text: "ok" });
246
+ },
247
+ }),
248
+ },
249
+ { message: "again" },
250
+ (event) => second.push(event),
251
+ );
252
+ expect(second.some((event) => event.kind === "usage")).toBe(false);
253
+ } finally {
254
+ await rm(cwd, { recursive: true, force: true });
255
+ }
256
+ });
257
+
146
258
  test("emits todos after todo_write and honors a denying pre_tool hook", async () => {
147
259
  const cwd = await mkdtemp(join(tmpdir(), "harness-todos-"));
148
260
  try {
@@ -336,7 +336,7 @@ export async function runTurn(
336
336
  async (gen) => {
337
337
  gen.update({ model: provider.modelId, input: { message: req.message } });
338
338
  await agent.run(req.message, capture, { signal: options.signal });
339
- const usage = provider.takeUsage?.();
339
+ const usage = await Promise.resolve(provider.takeUsage?.());
340
340
  gen.update({
341
341
  output: assistantText,
342
342
  ...(usage
@@ -375,6 +375,7 @@ export async function runTurn(
375
375
  });
376
376
  obs.score({ name: "generation_duration", value: Date.now() - startedAt });
377
377
  } catch (err) {
378
+ await Promise.resolve(provider.takeUsage?.());
378
379
  closeOpenTools("Turn stopped before this tool finished.");
379
380
  await persistChain;
380
381
  if (session) session = await finalize(deps, session, assistantText, thoughtText);
@@ -1,8 +1,10 @@
1
1
  import { describe, expect, it } from "bun:test";
2
2
  import {
3
+ type AgentConstructionInput,
3
4
  type ConstructAgent,
4
5
  constructOpenRouterProvider,
5
6
  createConstructAgent,
7
+ Offload,
6
8
  type StrandsBackedProvider,
7
9
  } from "../index.ts";
8
10
 
@@ -12,6 +14,7 @@ describe("strands exports", () => {
12
14
  it("exposes the agent constructor and OpenRouter provider from the package entry", () => {
13
15
  expect(typeof createConstructAgent).toBe("function");
14
16
  expect(typeof constructOpenRouterProvider).toBe("function");
17
+ expect(typeof Offload.drop).toBe("function");
15
18
  });
16
19
  });
17
20
 
@@ -45,13 +48,89 @@ describe("constructOpenRouterProvider", () => {
45
48
  expect(typeof provider.setReasoningSink).toBe("function");
46
49
  });
47
50
 
48
- it("reports no usage before any request has completed", () => {
51
+ it("sends the chosen reasoning effort on chat requests", async () => {
52
+ const bodies: unknown[] = [];
53
+ const realFetch = globalThis.fetch;
54
+ globalThis.fetch = (async (_url: unknown, init?: RequestInit) => {
55
+ if (typeof init?.body === "string") bodies.push(JSON.parse(init.body));
56
+ return new Response(JSON.stringify({ error: { message: "stop" } }), { status: 400 });
57
+ }) as unknown as typeof fetch;
58
+ try {
59
+ const provider = constructOpenRouterProvider({
60
+ apiKey: "sk-test",
61
+ model: "x-ai/grok",
62
+ baseUrl: BASE_URL,
63
+ reasoningEffort: "high",
64
+ });
65
+ for await (const _event of provider.stream({
66
+ messages: [{ role: "user", content: "hi" }],
67
+ })) {
68
+ // drain
69
+ }
70
+ } finally {
71
+ globalThis.fetch = realFetch;
72
+ }
73
+ expect(bodies.length).toBeGreaterThan(0);
74
+ const body = bodies[0] as { reasoning?: { effort?: string; exclude?: boolean } };
75
+ expect(body.reasoning).toEqual({ effort: "high", exclude: false });
76
+ });
77
+
78
+ it("reports no usage before any request has completed", async () => {
49
79
  const provider = constructOpenRouterProvider({
50
80
  apiKey: "sk-test",
51
81
  model: "x-ai/grok",
52
82
  baseUrl: BASE_URL,
53
83
  });
54
- expect(provider.takeUsage?.()).toBeUndefined();
84
+ expect(await provider.takeUsage?.()).toBeUndefined();
85
+ });
86
+
87
+ it("adds billed cost from every model call in the turn", async () => {
88
+ const remaining = [
89
+ { prompt_tokens: 10, completion_tokens: 2, total_tokens: 12, cost: 0.01 },
90
+ { prompt_tokens: 20, completion_tokens: 3, total_tokens: 23, cost: 0.02 },
91
+ ];
92
+ const realFetch = globalThis.fetch;
93
+ globalThis.fetch = (async () => {
94
+ const usage = remaining.shift() ?? {
95
+ prompt_tokens: 0,
96
+ completion_tokens: 0,
97
+ total_tokens: 0,
98
+ cost: 0,
99
+ };
100
+ const body = [
101
+ `data: ${JSON.stringify({ choices: [{ delta: { content: "ok" } }] })}\n\n`,
102
+ `data: ${JSON.stringify({
103
+ choices: [{ delta: {}, finish_reason: "stop" }],
104
+ usage,
105
+ })}\n\n`,
106
+ "data: [DONE]\n\n",
107
+ ].join("");
108
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
109
+ }) as unknown as typeof fetch;
110
+ try {
111
+ const provider = constructOpenRouterProvider({
112
+ apiKey: "sk-test",
113
+ model: "anthropic/claude-opus-4.5",
114
+ baseUrl: BASE_URL,
115
+ });
116
+ for (let i = 0; i < 2; i++) {
117
+ for await (const _event of provider.stream({
118
+ messages: [{ role: "user", content: "hi" }],
119
+ })) {
120
+ // drain
121
+ }
122
+ }
123
+ const usage = await provider.takeUsage?.();
124
+ expect(usage).toEqual({
125
+ promptTokens: 30,
126
+ completionTokens: 5,
127
+ totalTokens: 35,
128
+ costUsd: 0.03,
129
+ });
130
+ expect(await provider.takeUsage?.()).toBeUndefined();
131
+ } finally {
132
+ globalThis.fetch = realFetch;
133
+ }
55
134
  });
56
135
  });
57
136
 
@@ -86,4 +165,29 @@ describe("createConstructAgent", () => {
86
165
  });
87
166
  expect(typeof agent.run).toBe("function");
88
167
  });
168
+
169
+ it("asks the host for a context manager when constructing an agent", () => {
170
+ const seen: AgentConstructionInput[] = [];
171
+ const construct = createConstructAgent({
172
+ contextManager: (input) => {
173
+ seen.push(input);
174
+ return {
175
+ strategies: [Offload.drop("toolResults").when({ preserveRecent: 6 })],
176
+ };
177
+ },
178
+ });
179
+ const provider = constructOpenRouterProvider({
180
+ apiKey: "sk-test",
181
+ model: "m",
182
+ baseUrl: BASE_URL,
183
+ });
184
+ construct({
185
+ systemPrompt: "You are a test.",
186
+ tools: [],
187
+ provider,
188
+ messages: [],
189
+ });
190
+ expect(seen).toHaveLength(1);
191
+ expect(seen[0]?.systemPrompt).toBe("You are a test.");
192
+ });
89
193
  });
@@ -2,8 +2,21 @@
2
2
  * The only module that imports @strands-agents/sdk.
3
3
  */
4
4
 
5
- import type { JSONSchema, Model, StreamOptions, ToolSpec } from "@strands-agents/sdk";
6
- import { Agent, Message, type ModelStreamUpdateEvent, TextBlock, tool } from "@strands-agents/sdk";
5
+ import type {
6
+ ContextManagerStrategy,
7
+ JSONSchema,
8
+ Model,
9
+ StreamOptions,
10
+ ToolSpec,
11
+ } from "@strands-agents/sdk";
12
+ import {
13
+ Agent,
14
+ Message,
15
+ type ModelStreamUpdateEvent,
16
+ Offload,
17
+ TextBlock,
18
+ tool,
19
+ } from "@strands-agents/sdk";
7
20
  import { OpenAIModel } from "@strands-agents/sdk/models/openai";
8
21
  import { PRODUCT_NAME } from "../product.ts";
9
22
  import { withAutoRouterFetch } from "./auto-router.ts";
@@ -15,7 +28,8 @@ import type {
15
28
  ProviderTurnRequest,
16
29
  } from "./events.ts";
17
30
  import type { ToolResult } from "./mcp.ts";
18
- import { createUsageTrackingFetch, type TokenUsage } from "./usage.ts";
31
+ import { DEFAULT_REASONING_EFFORT, type ReasoningEffort } from "./reasoning.ts";
32
+ import { addUsage, createUsageTrackingFetch, type TokenUsage } from "./usage.ts";
19
33
 
20
34
  export const DEFAULT_MAIN_MODEL_MAX_TOKENS = 8192;
21
35
 
@@ -44,6 +58,14 @@ export interface ConstructedAgent {
44
58
 
45
59
  export type ConstructAgent = (input: AgentConstructionInput) => ConstructedAgent;
46
60
 
61
+ export type { ContextManagerStrategy };
62
+ export { Offload };
63
+
64
+ export interface CreateConstructAgentOptions {
65
+ /** Strands context management, decided per turn (e.g. clear old tool results past a size). */
66
+ contextManager?: (input: AgentConstructionInput) => ContextManagerStrategy | undefined;
67
+ }
68
+
47
69
  export interface StrandsBackedProvider extends MainModelProvider {
48
70
  readonly sdkModel: Model;
49
71
  setReasoningSink?(sink: ((text: string) => void) | undefined): void;
@@ -134,7 +156,7 @@ function wrapModelAsProvider(
134
156
  model: Model,
135
157
  kind: string,
136
158
  modelId: string,
137
- takeUsage?: () => TokenUsage | undefined,
159
+ takeUsage?: () => TokenUsage | undefined | Promise<TokenUsage | undefined>,
138
160
  ): StrandsBackedProvider {
139
161
  return {
140
162
  kind,
@@ -152,6 +174,8 @@ export function constructOpenRouterProvider(options: {
152
174
  model: string;
153
175
  baseUrl: string;
154
176
  maxTokens?: number;
177
+ /** OpenRouter reasoning effort. Defaults to low. */
178
+ reasoningEffort?: ReasoningEffort;
155
179
  sessionId?: () => string | undefined;
156
180
  /** `X-Title` sent to OpenRouter, so usage can be told apart by purpose. Defaults to the product name. */
157
181
  title?: string;
@@ -166,7 +190,8 @@ export function constructOpenRouterProvider(options: {
166
190
  },
167
191
  };
168
192
  }
169
- let lastUsage: TokenUsage | undefined;
193
+ let accumulated: TokenUsage | undefined;
194
+ const probes = new Set<Promise<void>>();
170
195
  let reasoningSink: ((text: string) => void) | undefined;
171
196
  const model = new OpenAIModel({
172
197
  api: "chat",
@@ -174,7 +199,10 @@ export function constructOpenRouterProvider(options: {
174
199
  modelId: options.model,
175
200
  maxTokens: options.maxTokens ?? DEFAULT_MAIN_MODEL_MAX_TOKENS,
176
201
  params: {
177
- reasoning: { effort: "low", exclude: false },
202
+ reasoning: {
203
+ effort: options.reasoningEffort ?? DEFAULT_REASONING_EFFORT,
204
+ exclude: false,
205
+ },
178
206
  },
179
207
  clientConfig: {
180
208
  baseURL: options.baseUrl.replace(/\/+$/, ""),
@@ -184,19 +212,24 @@ export function constructOpenRouterProvider(options: {
184
212
  },
185
213
  fetch: createUsageTrackingFetch(
186
214
  (usage) => {
187
- lastUsage = usage;
215
+ accumulated = addUsage(accumulated, usage);
188
216
  },
189
217
  withAutoRouterFetch(globalThis.fetch, {
190
218
  model: options.model,
191
219
  sessionId: options.sessionId,
192
220
  }),
193
221
  (text) => reasoningSink?.(text),
222
+ (done) => {
223
+ probes.add(done);
224
+ void done.finally(() => probes.delete(done));
225
+ },
194
226
  ),
195
227
  },
196
228
  });
197
- const wrapped = wrapModelAsProvider(model, "openrouter", options.model, () => {
198
- const usage = lastUsage;
199
- lastUsage = undefined;
229
+ const wrapped = wrapModelAsProvider(model, "openrouter", options.model, async () => {
230
+ await Promise.all([...probes]);
231
+ const usage = accumulated;
232
+ accumulated = undefined;
200
233
  return usage;
201
234
  });
202
235
  wrapped.setReasoningSink = (sink) => {
@@ -210,7 +243,7 @@ function toolResultToReturn(result: ToolResult): unknown {
210
243
  return result.content.map((block) => block.text).join("\n");
211
244
  }
212
245
 
213
- export function createConstructAgent(): ConstructAgent {
246
+ export function createConstructAgent(options: CreateConstructAgentOptions = {}): ConstructAgent {
214
247
  return (input: AgentConstructionInput): ConstructedAgent => {
215
248
  if (!isStrandsBackedProvider(input.provider)) {
216
249
  throw new Error("createConstructAgent requires a Strands-backed MainModelProvider.");
@@ -231,11 +264,13 @@ export function createConstructAgent(): ConstructAgent {
231
264
  const seededMessages = input.messages.map(
232
265
  (m) => new Message({ role: m.role, content: [new TextBlock(m.content)] }),
233
266
  );
267
+ const contextManager = options.contextManager?.(input);
234
268
  const agent = new Agent({
235
269
  model,
236
270
  systemPrompt: input.systemPrompt,
237
271
  tools,
238
272
  ...(seededMessages.length > 0 ? { messages: seededMessages } : {}),
273
+ ...(contextManager !== undefined ? { contextManager } : {}),
239
274
  });
240
275
 
241
276
  return {
@@ -1,5 +1,12 @@
1
1
  import { describe, expect, test } from "bun:test";
2
- import { addUsage, formatUsage, parseTokenUsage, reasoningTextFromChunk } from "./usage.ts";
2
+ import {
3
+ addUsage,
4
+ createUsageTrackingFetch,
5
+ formatUsage,
6
+ mergeRequestUsage,
7
+ parseTokenUsage,
8
+ reasoningTextFromChunk,
9
+ } from "./usage.ts";
3
10
 
4
11
  describe("token usage", () => {
5
12
  test("parses OpenAI and OpenRouter shapes", () => {
@@ -40,6 +47,20 @@ describe("token usage", () => {
40
47
  });
41
48
  });
42
49
 
50
+ test("mergeRequestUsage keeps billed cost when a later chunk reports zeros", () => {
51
+ expect(
52
+ mergeRequestUsage(
53
+ { promptTokens: 80_000, completionTokens: 4_000, totalTokens: 84_000, costUsd: 5.4 },
54
+ { promptTokens: 0, completionTokens: 0, totalTokens: 0, costUsd: 0 },
55
+ ),
56
+ ).toEqual({
57
+ promptTokens: 80_000,
58
+ completionTokens: 4_000,
59
+ totalTokens: 84_000,
60
+ costUsd: 5.4,
61
+ });
62
+ });
63
+
43
64
  test("formatUsage does not invent a dollar amount", () => {
44
65
  expect(formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15 })).toBe(
45
66
  "12 in · 3 out",
@@ -47,6 +68,14 @@ describe("token usage", () => {
47
68
  expect(
48
69
  formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15, costUsd: 0.2 }),
49
70
  ).toBe("12 in · 3 out · $0.20");
71
+ expect(
72
+ formatUsage({
73
+ promptTokens: 80_000,
74
+ completionTokens: 4_000,
75
+ totalTokens: 84_000,
76
+ costUsd: 5.4,
77
+ }),
78
+ ).toBe("80000 in · 4000 out · $5.40");
50
79
  });
51
80
 
52
81
  test("reads OpenRouter reasoning deltas from chat chunks", () => {
@@ -67,3 +96,53 @@ describe("token usage", () => {
67
96
  ).toBeUndefined();
68
97
  });
69
98
  });
99
+
100
+ function sseResponse(chunks: unknown[]): Response {
101
+ const body = chunks
102
+ .map((chunk) =>
103
+ chunk === "[DONE]" ? "data: [DONE]\n\n" : `data: ${JSON.stringify(chunk)}\n\n`,
104
+ )
105
+ .join("");
106
+ return new Response(body, { headers: { "content-type": "text/event-stream" } });
107
+ }
108
+
109
+ describe("createUsageTrackingFetch", () => {
110
+ test("reports billed cost once after the stream ends, not per chunk", async () => {
111
+ const seen: Array<{ promptTokens: number; costUsd?: number }> = [];
112
+ let probe: Promise<void> | undefined;
113
+ const tracked = createUsageTrackingFetch(
114
+ (usage) => seen.push({ promptTokens: usage.promptTokens, costUsd: usage.costUsd }),
115
+ async () =>
116
+ sseResponse([
117
+ { choices: [{ delta: { content: "hi" } }] },
118
+ {
119
+ choices: [{ delta: {}, finish_reason: "stop" }],
120
+ usage: {
121
+ prompt_tokens: 0,
122
+ completion_tokens: 0,
123
+ total_tokens: 0,
124
+ cost: 0,
125
+ },
126
+ },
127
+ {
128
+ choices: [{ delta: {}, finish_reason: "stop" }],
129
+ usage: {
130
+ prompt_tokens: 80_000,
131
+ completion_tokens: 4_000,
132
+ total_tokens: 84_000,
133
+ cost: 5.4,
134
+ },
135
+ },
136
+ "[DONE]",
137
+ ]),
138
+ undefined,
139
+ (done) => {
140
+ probe = done;
141
+ },
142
+ );
143
+ const res = await tracked("https://openrouter.ai/api/v1/chat/completions");
144
+ await res.text();
145
+ await probe;
146
+ expect(seen).toEqual([{ promptTokens: 80_000, costUsd: 5.4 }]);
147
+ });
148
+ });
package/src/core/usage.ts CHANGED
@@ -31,6 +31,25 @@ export function parseTokenUsage(value: unknown): TokenUsage | undefined {
31
31
  };
32
32
  }
33
33
 
34
+ /** Keep the richer snapshot from one streamed request. Later zero-token chunks must not wipe cost. */
35
+ export function mergeRequestUsage(prev: TokenUsage | undefined, next: TokenUsage): TokenUsage {
36
+ if (!prev) return next;
37
+ const nextCost = next.costUsd;
38
+ const prevCost = prev.costUsd;
39
+ const cost =
40
+ nextCost !== undefined && nextCost > 0
41
+ ? nextCost
42
+ : prevCost !== undefined && prevCost > 0
43
+ ? prevCost
44
+ : (nextCost ?? prevCost);
45
+ return {
46
+ promptTokens: Math.max(prev.promptTokens, next.promptTokens),
47
+ completionTokens: Math.max(prev.completionTokens, next.completionTokens),
48
+ totalTokens: Math.max(prev.totalTokens, next.totalTokens),
49
+ ...(cost !== undefined ? { costUsd: cost } : {}),
50
+ };
51
+ }
52
+
34
53
  export function addUsage(
35
54
  a: TokenUsage | undefined,
36
55
  b: TokenUsage | undefined,
@@ -119,21 +138,32 @@ async function pumpSse(
119
138
  const reader = body.getReader();
120
139
  const decoder = new TextDecoder();
121
140
  let buf = "";
141
+ let requestUsage: TokenUsage | undefined;
142
+ const recordUsage = (usage: TokenUsage) => {
143
+ requestUsage = mergeRequestUsage(requestUsage, usage);
144
+ };
122
145
  try {
123
146
  while (true) {
124
147
  const { done, value } = await reader.read();
125
148
  if (value) buf += decoder.decode(value, { stream: !done });
126
149
  const parts = buf.split("\n");
127
150
  buf = done ? "" : (parts.pop() ?? "");
128
- for (const line of parts) scanSseLine(line, onUsage, onReasoning);
151
+ for (const line of parts) scanSseLine(line, recordUsage, onReasoning);
129
152
  if (done) {
130
- if (buf) scanSseLine(buf, onUsage, onReasoning);
153
+ if (buf) scanSseLine(buf, recordUsage, onReasoning);
131
154
  break;
132
155
  }
133
156
  }
134
157
  } catch {
135
158
  // probe side can fail independently of the model stream
136
159
  }
160
+ if (requestUsage) {
161
+ try {
162
+ onUsage(requestUsage);
163
+ } catch {
164
+ // keep the probe settled even if the host callback throws
165
+ }
166
+ }
137
167
  }
138
168
 
139
169
  type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
@@ -143,6 +173,7 @@ export function createUsageTrackingFetch(
143
173
  onUsage: (usage: TokenUsage) => void,
144
174
  baseFetch: FetchFn = fetch,
145
175
  onReasoning?: (text: string) => void,
176
+ onProbe?: (done: Promise<void>) => void,
146
177
  ): FetchFn {
147
178
  return async (input, init) => {
148
179
  const res = await baseFetch(input, init);
@@ -150,7 +181,8 @@ export function createUsageTrackingFetch(
150
181
  if (!res.body) return res;
151
182
  if (contentType.includes("text/event-stream")) {
152
183
  const [out, probe] = res.body.tee();
153
- void pumpSse(probe, onUsage, onReasoning);
184
+ const done = pumpSse(probe, onUsage, onReasoning);
185
+ onProbe?.(done);
154
186
  return new Response(out, res);
155
187
  }
156
188
  if (contentType.includes("application/json")) {