@useavalon/caelence-agent 0.1.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.
Files changed (161) hide show
  1. package/README.md +201 -0
  2. package/bin/harness.ts +10 -0
  3. package/package.json +75 -0
  4. package/skills/copy-editor/SKILL.md +74 -0
  5. package/skills/copy-editor/references/anti-slop.md +62 -0
  6. package/skills/copy-editor/references/ui-states.md +46 -0
  7. package/skills/copy-editor/scripts/lint-copy.py +78 -0
  8. package/skills/copy-harry-dry/SKILL.md +120 -0
  9. package/skills/copy-rmbc/SKILL.md +97 -0
  10. package/skills/copywriting/SKILL.md +73 -0
  11. package/skills/impeccable/SKILL.md +133 -0
  12. package/skills/impeccable/references/visual-slop.md +36 -0
  13. package/src/cli/main.test.ts +36 -0
  14. package/src/cli/main.ts +384 -0
  15. package/src/cli/media-models.ts +82 -0
  16. package/src/cli/models.ts +43 -0
  17. package/src/cli/openrouter-live.test.ts +35 -0
  18. package/src/cli/openrouter-live.ts +72 -0
  19. package/src/cli/openrouter-modality.test.ts +25 -0
  20. package/src/cli/openrouter-modality.ts +83 -0
  21. package/src/cli/picker.test.ts +53 -0
  22. package/src/cli/picker.ts +48 -0
  23. package/src/cli/plain-text.ts +15 -0
  24. package/src/cli/slash-dispatch.test.ts +213 -0
  25. package/src/cli/slash-dispatch.ts +298 -0
  26. package/src/cli/slash.test.ts +113 -0
  27. package/src/cli/slash.ts +119 -0
  28. package/src/cli/theme.test.ts +10 -0
  29. package/src/cli/theme.ts +44 -0
  30. package/src/cli/tui-layout.test.ts +33 -0
  31. package/src/cli/tui-layout.ts +33 -0
  32. package/src/cli/tui-screen.test.ts +33 -0
  33. package/src/cli/tui-screen.ts +13 -0
  34. package/src/cli/tui.tsx +735 -0
  35. package/src/config.ts +86 -0
  36. package/src/core/approval.test.ts +60 -0
  37. package/src/core/approval.ts +83 -0
  38. package/src/core/auto-router.test.ts +31 -0
  39. package/src/core/auto-router.ts +66 -0
  40. package/src/core/errors.ts +67 -0
  41. package/src/core/events.ts +85 -0
  42. package/src/core/hooks.test.ts +66 -0
  43. package/src/core/hooks.ts +94 -0
  44. package/src/core/ids.ts +6 -0
  45. package/src/core/instructions.test.ts +49 -0
  46. package/src/core/instructions.ts +44 -0
  47. package/src/core/logger.ts +45 -0
  48. package/src/core/mcp.ts +191 -0
  49. package/src/core/mode.test.ts +63 -0
  50. package/src/core/mode.ts +60 -0
  51. package/src/core/run-turn.test.ts +339 -0
  52. package/src/core/run-turn.ts +487 -0
  53. package/src/core/session.test.ts +203 -0
  54. package/src/core/session.ts +349 -0
  55. package/src/core/stdio-mcp.ts +143 -0
  56. package/src/core/strands.ts +262 -0
  57. package/src/core/usage.test.ts +69 -0
  58. package/src/core/usage.ts +171 -0
  59. package/src/desktop/bridge.test.ts +331 -0
  60. package/src/desktop/bridge.ts +729 -0
  61. package/src/desktop/open-local.test.ts +40 -0
  62. package/src/desktop/open-local.ts +52 -0
  63. package/src/desktop/preview-cache.test.ts +36 -0
  64. package/src/desktop/preview-cache.ts +63 -0
  65. package/src/desktop/secrets.test.ts +44 -0
  66. package/src/desktop/secrets.ts +60 -0
  67. package/src/evals/runner.test.ts +43 -0
  68. package/src/evals/runner.ts +225 -0
  69. package/src/index.ts +132 -0
  70. package/src/init.test.ts +54 -0
  71. package/src/init.ts +117 -0
  72. package/src/integrations/catalog-data.json +424 -0
  73. package/src/integrations/catalog.ts +81 -0
  74. package/src/integrations/connect.ts +231 -0
  75. package/src/integrations/integrations.test.ts +329 -0
  76. package/src/integrations/marks/airtable.svg +1 -0
  77. package/src/integrations/marks/algolia-mcp.svg +1 -0
  78. package/src/integrations/marks/canva.jpg +0 -0
  79. package/src/integrations/marks/cloudflare-mcp.svg +1 -0
  80. package/src/integrations/marks/contentful-mcp.svg +1 -0
  81. package/src/integrations/marks/craft.png +0 -0
  82. package/src/integrations/marks/dinero.png +0 -0
  83. package/src/integrations/marks/figma.svg +1 -0
  84. package/src/integrations/marks/gitlab.svg +1 -0
  85. package/src/integrations/marks/google-calendar.svg +1 -0
  86. package/src/integrations/marks/google-docs.svg +1 -0
  87. package/src/integrations/marks/google-drive.svg +1 -0
  88. package/src/integrations/marks/google-gmail.svg +1 -0
  89. package/src/integrations/marks/google-sheets.svg +1 -0
  90. package/src/integrations/marks/google-slides.svg +1 -0
  91. package/src/integrations/marks/granola.png +0 -0
  92. package/src/integrations/marks/jira.svg +1 -0
  93. package/src/integrations/marks/linear.svg +1 -0
  94. package/src/integrations/marks/microsoft-365.svg +7 -0
  95. package/src/integrations/marks/miro.svg +1 -0
  96. package/src/integrations/marks/mixpanel-mcp.svg +1 -0
  97. package/src/integrations/marks/monday.png +0 -0
  98. package/src/integrations/marks/mux-mcp.png +0 -0
  99. package/src/integrations/marks/neon-mcp.svg +1 -0
  100. package/src/integrations/marks/notion.svg +1 -0
  101. package/src/integrations/marks/paddle-mcp.svg +1 -0
  102. package/src/integrations/marks/posthog-mcp.svg +1 -0
  103. package/src/integrations/marks/prismic-mcp.svg +1 -0
  104. package/src/integrations/marks/replicate-mcp.svg +1 -0
  105. package/src/integrations/marks/resend-mcp.svg +1 -0
  106. package/src/integrations/marks/sanity-mcp.svg +1 -0
  107. package/src/integrations/marks/sceneplane.png +0 -0
  108. package/src/integrations/marks/sentry-mcp.svg +1 -0
  109. package/src/integrations/marks/stripe-mcp.svg +1 -0
  110. package/src/integrations/marks/supabase-mcp.svg +1 -0
  111. package/src/integrations/marks/upstash-mcp.svg +1 -0
  112. package/src/integrations/marks/vercel.svg +1 -0
  113. package/src/integrations/marks/webflow.svg +1 -0
  114. package/src/integrations/mcp-oauth.test.ts +39 -0
  115. package/src/integrations/mcp-oauth.ts +330 -0
  116. package/src/integrations/oauth-clients.test.ts +77 -0
  117. package/src/integrations/oauth-clients.ts +127 -0
  118. package/src/integrations/oauth.ts +145 -0
  119. package/src/integrations/remote-mcp.ts +307 -0
  120. package/src/integrations/store.ts +149 -0
  121. package/src/media/openrouter-generate.test.ts +80 -0
  122. package/src/media/openrouter-generate.ts +178 -0
  123. package/src/media/prefs.ts +54 -0
  124. package/src/observability/categories.ts +41 -0
  125. package/src/observability/create.test.ts +56 -0
  126. package/src/observability/create.ts +45 -0
  127. package/src/observability/experiments.ts +113 -0
  128. package/src/observability/fake.ts +191 -0
  129. package/src/observability/index.ts +57 -0
  130. package/src/observability/judges.ts +91 -0
  131. package/src/observability/langfuse.ts +275 -0
  132. package/src/observability/noop.ts +33 -0
  133. package/src/observability/observability.test.ts +113 -0
  134. package/src/observability/prompts.ts +98 -0
  135. package/src/observability/regression-items.ts +158 -0
  136. package/src/observability/sanitize.test.ts +26 -0
  137. package/src/observability/sanitize.ts +57 -0
  138. package/src/observability/types.ts +122 -0
  139. package/src/observability/version.ts +41 -0
  140. package/src/product.ts +2 -0
  141. package/src/runtime.test.ts +98 -0
  142. package/src/runtime.ts +438 -0
  143. package/src/skills/author-skill.ts +49 -0
  144. package/src/skills/create-skill.test.ts +108 -0
  145. package/src/skills/create-skill.ts +70 -0
  146. package/src/skills/loader.test.ts +122 -0
  147. package/src/skills/loader.ts +162 -0
  148. package/src/skills/registry.test.ts +190 -0
  149. package/src/skills/registry.ts +402 -0
  150. package/src/skills/skill-command.ts +53 -0
  151. package/src/skills/user-dir.ts +8 -0
  152. package/src/tools/git.test.ts +71 -0
  153. package/src/tools/git.ts +126 -0
  154. package/src/tools/local.ts +258 -0
  155. package/src/tools/paths.test.ts +24 -0
  156. package/src/tools/paths.ts +39 -0
  157. package/src/tools/read-skill.ts +43 -0
  158. package/src/tools/subagent.test.ts +77 -0
  159. package/src/tools/subagent.ts +74 -0
  160. package/src/tools/todo.test.ts +25 -0
  161. package/src/tools/todo.ts +70 -0
@@ -0,0 +1,262 @@
1
+ /**
2
+ * The only module that imports @strands-agents/sdk.
3
+ */
4
+
5
+ import type { JSONSchema, Model, StreamOptions, ToolSpec } from "@strands-agents/sdk";
6
+ import { Agent, Message, type ModelStreamUpdateEvent, TextBlock, tool } from "@strands-agents/sdk";
7
+ import { OpenAIModel } from "@strands-agents/sdk/models/openai";
8
+ import { PRODUCT_NAME } from "../product.ts";
9
+ import { withAutoRouterFetch } from "./auto-router.ts";
10
+ import { errorMessage } from "./errors.ts";
11
+ import type {
12
+ AgentEventEmitter,
13
+ MainModelProvider,
14
+ ProviderStreamEvent,
15
+ ProviderTurnRequest,
16
+ } from "./events.ts";
17
+ import type { ToolResult } from "./mcp.ts";
18
+ import { createUsageTrackingFetch, type TokenUsage } from "./usage.ts";
19
+
20
+ export const DEFAULT_MAIN_MODEL_MAX_TOKENS = 8192;
21
+
22
+ export interface AgentTool {
23
+ name: string;
24
+ description: string;
25
+ inputSchema: Record<string, unknown>;
26
+ invoke(input: Record<string, unknown>): Promise<ToolResult>;
27
+ }
28
+
29
+ export interface AgentConstructionInput {
30
+ systemPrompt: string;
31
+ tools: AgentTool[];
32
+ provider: MainModelProvider;
33
+ messages: Array<{ role: "user" | "assistant"; content: string }>;
34
+ maxTokens?: number;
35
+ }
36
+
37
+ export interface ConstructedAgent {
38
+ run(
39
+ userMessage: string,
40
+ emit: AgentEventEmitter,
41
+ options?: { signal?: AbortSignal },
42
+ ): Promise<void>;
43
+ }
44
+
45
+ export type ConstructAgent = (input: AgentConstructionInput) => ConstructedAgent;
46
+
47
+ export interface StrandsBackedProvider extends MainModelProvider {
48
+ readonly sdkModel: Model;
49
+ setReasoningSink?(sink: ((text: string) => void) | undefined): void;
50
+ }
51
+
52
+ function isStrandsBackedProvider(p: MainModelProvider): p is StrandsBackedProvider {
53
+ return "sdkModel" in p && (p as StrandsBackedProvider).sdkModel !== undefined;
54
+ }
55
+
56
+ function parseToolInput(raw: string): Record<string, unknown> {
57
+ if (raw.trim() === "") return {};
58
+ try {
59
+ const parsed = JSON.parse(raw);
60
+ return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : {};
61
+ } catch {
62
+ return {};
63
+ }
64
+ }
65
+
66
+ async function* streamModelAsProviderEvents(
67
+ model: Model,
68
+ request: ProviderTurnRequest,
69
+ signal?: AbortSignal,
70
+ ): AsyncIterable<ProviderStreamEvent> {
71
+ const messages = request.messages.map(
72
+ (m) => new Message({ role: m.role, content: [new TextBlock(m.content)] }),
73
+ );
74
+ const options: StreamOptions = {};
75
+ if (request.system) options.systemPrompt = request.system;
76
+ if (request.tools?.length) {
77
+ options.toolSpecs = request.tools.map(
78
+ (t): ToolSpec => ({
79
+ name: t.name,
80
+ description: t.description,
81
+ inputSchema: t.inputSchema as JSONSchema,
82
+ }),
83
+ );
84
+ }
85
+
86
+ let pendingTool: { id: string; name: string; input: string } | undefined;
87
+ try {
88
+ for await (const event of model.stream(messages, options)) {
89
+ if (signal?.aborted) {
90
+ yield { type: "done" };
91
+ return;
92
+ }
93
+ switch (event.type) {
94
+ case "modelContentBlockStartEvent":
95
+ if (event.start?.type === "toolUseStart") {
96
+ pendingTool = { id: event.start.toolUseId, name: event.start.name, input: "" };
97
+ }
98
+ break;
99
+ case "modelContentBlockDeltaEvent":
100
+ if (event.delta.type === "textDelta") {
101
+ if (event.delta.text.length > 0) yield { type: "text_delta", text: event.delta.text };
102
+ } else if (
103
+ event.delta.type === "reasoningContentDelta" &&
104
+ event.delta.text &&
105
+ event.delta.text.length > 0
106
+ ) {
107
+ yield { type: "reasoning_delta", text: event.delta.text };
108
+ } else if (event.delta.type === "toolUseInputDelta" && pendingTool) {
109
+ pendingTool.input += event.delta.input;
110
+ }
111
+ break;
112
+ case "modelContentBlockStopEvent":
113
+ if (pendingTool) {
114
+ yield {
115
+ type: "tool_call",
116
+ id: pendingTool.id,
117
+ name: pendingTool.name,
118
+ input: parseToolInput(pendingTool.input),
119
+ };
120
+ pendingTool = undefined;
121
+ }
122
+ break;
123
+ default:
124
+ break;
125
+ }
126
+ }
127
+ yield { type: "done" };
128
+ } catch (err) {
129
+ yield { type: "error", message: errorMessage(err) };
130
+ }
131
+ }
132
+
133
+ function wrapModelAsProvider(
134
+ model: Model,
135
+ kind: string,
136
+ modelId: string,
137
+ takeUsage?: () => TokenUsage | undefined,
138
+ ): StrandsBackedProvider {
139
+ return {
140
+ kind,
141
+ modelId,
142
+ sdkModel: model,
143
+ takeUsage,
144
+ stream(request, streamOptions) {
145
+ return streamModelAsProviderEvents(model, request, streamOptions?.signal);
146
+ },
147
+ };
148
+ }
149
+
150
+ export function constructOpenRouterProvider(options: {
151
+ apiKey: string;
152
+ model: string;
153
+ baseUrl: string;
154
+ maxTokens?: number;
155
+ sessionId?: () => string | undefined;
156
+ }): MainModelProvider {
157
+ let lastUsage: TokenUsage | undefined;
158
+ let reasoningSink: ((text: string) => void) | undefined;
159
+ const model = new OpenAIModel({
160
+ api: "chat",
161
+ apiKey: options.apiKey,
162
+ modelId: options.model,
163
+ maxTokens: options.maxTokens ?? DEFAULT_MAIN_MODEL_MAX_TOKENS,
164
+ params: {
165
+ reasoning: { effort: "low", exclude: false },
166
+ stream_options: { include_usage: true },
167
+ },
168
+ clientConfig: {
169
+ baseURL: options.baseUrl.replace(/\/+$/, ""),
170
+ defaultHeaders: {
171
+ "HTTP-Referer": "https://caelence.com",
172
+ "X-Title": PRODUCT_NAME,
173
+ },
174
+ fetch: createUsageTrackingFetch(
175
+ (usage) => {
176
+ lastUsage = usage;
177
+ },
178
+ withAutoRouterFetch(globalThis.fetch, {
179
+ model: options.model,
180
+ sessionId: options.sessionId,
181
+ }),
182
+ (text) => reasoningSink?.(text),
183
+ ),
184
+ },
185
+ });
186
+ const wrapped = wrapModelAsProvider(model, "openrouter", options.model, () => {
187
+ const usage = lastUsage;
188
+ lastUsage = undefined;
189
+ return usage;
190
+ });
191
+ wrapped.setReasoningSink = (sink) => {
192
+ reasoningSink = sink;
193
+ };
194
+ return wrapped;
195
+ }
196
+
197
+ function toolResultToReturn(result: ToolResult): unknown {
198
+ if (result.structuredContent) return result.structuredContent;
199
+ return result.content.map((block) => block.text).join("\n");
200
+ }
201
+
202
+ export function createConstructAgent(): ConstructAgent {
203
+ return (input: AgentConstructionInput): ConstructedAgent => {
204
+ if (!isStrandsBackedProvider(input.provider)) {
205
+ throw new Error("createConstructAgent requires a Strands-backed MainModelProvider.");
206
+ }
207
+ const provider = input.provider;
208
+ const model = provider.sdkModel;
209
+ const tools = input.tools.map((agentTool: AgentTool) =>
210
+ tool({
211
+ name: agentTool.name,
212
+ description: agentTool.description,
213
+ inputSchema: agentTool.inputSchema as JSONSchema,
214
+ callback: async (rawInput: unknown) => {
215
+ const result = await agentTool.invoke((rawInput ?? {}) as Record<string, unknown>);
216
+ return toolResultToReturn(result) as never;
217
+ },
218
+ }),
219
+ );
220
+ const seededMessages = input.messages.map(
221
+ (m) => new Message({ role: m.role, content: [new TextBlock(m.content)] }),
222
+ );
223
+ const agent = new Agent({
224
+ model,
225
+ systemPrompt: input.systemPrompt,
226
+ tools,
227
+ ...(seededMessages.length > 0 ? { messages: seededMessages } : {}),
228
+ });
229
+
230
+ return {
231
+ async run(userMessage, emit, options) {
232
+ const invokeOptions = options?.signal ? { cancelSignal: options.signal } : {};
233
+ provider.setReasoningSink?.((text) => emit({ kind: "reasoning_delta", text }));
234
+ try {
235
+ for await (const event of agent.stream(userMessage, invokeOptions)) {
236
+ if (event.type === "modelStreamUpdateEvent") {
237
+ const modelEvent = (event as ModelStreamUpdateEvent).event;
238
+ if (modelEvent.type !== "modelContentBlockDeltaEvent") continue;
239
+ if (modelEvent.delta.type === "textDelta" && modelEvent.delta.text.length > 0) {
240
+ emit({ kind: "text_delta", text: modelEvent.delta.text });
241
+ } else if (
242
+ modelEvent.delta.type === "reasoningContentDelta" &&
243
+ modelEvent.delta.text &&
244
+ modelEvent.delta.text.length > 0
245
+ ) {
246
+ emit({ kind: "reasoning_delta", text: modelEvent.delta.text });
247
+ }
248
+ }
249
+ }
250
+ } catch (err) {
251
+ if (options?.signal?.aborted) return;
252
+ const name =
253
+ err && typeof err === "object" ? (err as { name?: unknown }).name : undefined;
254
+ if (name === "AbortError" || name === "CancelledError") return;
255
+ throw err;
256
+ } finally {
257
+ provider.setReasoningSink?.(undefined);
258
+ }
259
+ },
260
+ };
261
+ };
262
+ }
@@ -0,0 +1,69 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { addUsage, formatUsage, parseTokenUsage, reasoningTextFromChunk } from "./usage.ts";
3
+
4
+ describe("token usage", () => {
5
+ test("parses OpenAI and OpenRouter shapes", () => {
6
+ expect(
7
+ parseTokenUsage({
8
+ usage: { prompt_tokens: 10, completion_tokens: 4, total_tokens: 14, cost: 0.002 },
9
+ }),
10
+ ).toEqual({
11
+ promptTokens: 10,
12
+ completionTokens: 4,
13
+ totalTokens: 14,
14
+ costUsd: 0.002,
15
+ });
16
+ expect(parseTokenUsage({ promptTokens: 2, completionTokens: 3 })).toEqual({
17
+ promptTokens: 2,
18
+ completionTokens: 3,
19
+ totalTokens: 5,
20
+ });
21
+ expect(parseTokenUsage({ hello: 1 })).toBeUndefined();
22
+ });
23
+
24
+ test("adds usage and only keeps cost when a side reported it", () => {
25
+ expect(addUsage({ promptTokens: 1, completionTokens: 2, totalTokens: 3 }, undefined)).toEqual({
26
+ promptTokens: 1,
27
+ completionTokens: 2,
28
+ totalTokens: 3,
29
+ });
30
+ expect(
31
+ addUsage(
32
+ { promptTokens: 1, completionTokens: 1, totalTokens: 2 },
33
+ { promptTokens: 4, completionTokens: 5, totalTokens: 9, costUsd: 0.1 },
34
+ ),
35
+ ).toEqual({
36
+ promptTokens: 5,
37
+ completionTokens: 6,
38
+ totalTokens: 11,
39
+ costUsd: 0.1,
40
+ });
41
+ });
42
+
43
+ test("formatUsage does not invent a dollar amount", () => {
44
+ expect(formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15 })).toBe(
45
+ "12 in · 3 out",
46
+ );
47
+ expect(
48
+ formatUsage({ promptTokens: 12, completionTokens: 3, totalTokens: 15, costUsd: 0.2 }),
49
+ ).toBe("12 in · 3 out · $0.20");
50
+ });
51
+
52
+ test("reads OpenRouter reasoning deltas from chat chunks", () => {
53
+ expect(
54
+ reasoningTextFromChunk({
55
+ choices: [{ delta: { reasoning: "look at the page" } }],
56
+ }),
57
+ ).toBe("look at the page");
58
+ expect(
59
+ reasoningTextFromChunk({
60
+ choices: [{ delta: { reasoning_content: "step" } }],
61
+ }),
62
+ ).toBe("step");
63
+ expect(
64
+ reasoningTextFromChunk({
65
+ choices: [{ delta: { content: "hello" } }],
66
+ }),
67
+ ).toBeUndefined();
68
+ });
69
+ });
@@ -0,0 +1,171 @@
1
+ export interface TokenUsage {
2
+ promptTokens: number;
3
+ completionTokens: number;
4
+ totalTokens: number;
5
+ costUsd?: number;
6
+ }
7
+
8
+ function asFinite(value: unknown): number | undefined {
9
+ const n = typeof value === "number" ? value : typeof value === "string" ? Number(value) : NaN;
10
+ return Number.isFinite(n) ? n : undefined;
11
+ }
12
+
13
+ export function parseTokenUsage(value: unknown): TokenUsage | undefined {
14
+ if (!value || typeof value !== "object") return undefined;
15
+ const rec = value as Record<string, unknown>;
16
+ const usage =
17
+ rec.usage && typeof rec.usage === "object" ? (rec.usage as Record<string, unknown>) : rec;
18
+ const prompt = asFinite(usage.prompt_tokens ?? usage.input_tokens ?? usage.promptTokens);
19
+ const completion = asFinite(
20
+ usage.completion_tokens ?? usage.output_tokens ?? usage.completionTokens,
21
+ );
22
+ if (prompt === undefined && completion === undefined) return undefined;
23
+ const total =
24
+ asFinite(usage.total_tokens ?? usage.totalTokens) ?? (prompt ?? 0) + (completion ?? 0);
25
+ const cost = asFinite(usage.cost ?? usage.total_cost ?? usage.costUsd);
26
+ return {
27
+ promptTokens: prompt ?? 0,
28
+ completionTokens: completion ?? 0,
29
+ totalTokens: total,
30
+ ...(cost !== undefined ? { costUsd: cost } : {}),
31
+ };
32
+ }
33
+
34
+ export function addUsage(
35
+ a: TokenUsage | undefined,
36
+ b: TokenUsage | undefined,
37
+ ): TokenUsage | undefined {
38
+ if (!a) return b;
39
+ if (!b) return a;
40
+ const cost =
41
+ a.costUsd !== undefined || b.costUsd !== undefined
42
+ ? (a.costUsd ?? 0) + (b.costUsd ?? 0)
43
+ : undefined;
44
+ return {
45
+ promptTokens: a.promptTokens + b.promptTokens,
46
+ completionTokens: a.completionTokens + b.completionTokens,
47
+ totalTokens: a.totalTokens + b.totalTokens,
48
+ ...(cost !== undefined ? { costUsd: cost } : {}),
49
+ };
50
+ }
51
+
52
+ export function formatUsage(usage: TokenUsage): string {
53
+ const tokens = `${usage.promptTokens} in · ${usage.completionTokens} out`;
54
+ if (usage.costUsd === undefined) return tokens;
55
+ const cost = usage.costUsd < 0.01 ? usage.costUsd.toFixed(4) : usage.costUsd.toFixed(2);
56
+ return `${tokens} · $${cost}`;
57
+ }
58
+
59
+ function stringDelta(value: unknown): string | undefined {
60
+ return typeof value === "string" && value.length > 0 ? value : undefined;
61
+ }
62
+
63
+ function reasoningFromDelta(delta: unknown): string | undefined {
64
+ if (!delta || typeof delta !== "object") return undefined;
65
+ const rec = delta as Record<string, unknown>;
66
+ const direct = stringDelta(rec.reasoning) ?? stringDelta(rec.reasoning_content);
67
+ if (direct) return direct;
68
+ const details = rec.reasoning_details;
69
+ if (!Array.isArray(details)) return undefined;
70
+ const parts: string[] = [];
71
+ for (const item of details) {
72
+ if (!item || typeof item !== "object") continue;
73
+ const row = item as Record<string, unknown>;
74
+ if (typeof row.type === "string" && row.type.includes("encrypted")) continue;
75
+ const text = stringDelta(row.text) ?? stringDelta(row.reasoning);
76
+ if (text) parts.push(text);
77
+ }
78
+ return parts.length > 0 ? parts.join("") : undefined;
79
+ }
80
+
81
+ /** OpenRouter/OpenAI chat chunk → incremental reasoning, if the model sent any. */
82
+ export function reasoningTextFromChunk(value: unknown): string | undefined {
83
+ if (!value || typeof value !== "object") return undefined;
84
+ const rec = value as Record<string, unknown>;
85
+ const choices = rec.choices;
86
+ const choice = Array.isArray(choices) ? choices[0] : undefined;
87
+ if (choice && typeof choice === "object") {
88
+ const row = choice as Record<string, unknown>;
89
+ return reasoningFromDelta(row.delta);
90
+ }
91
+ return reasoningFromDelta(rec.delta);
92
+ }
93
+
94
+ function scanSseLine(
95
+ line: string,
96
+ onUsage: (usage: TokenUsage) => void,
97
+ onReasoning?: (text: string) => void,
98
+ ): void {
99
+ const trimmed = line.trim();
100
+ if (!trimmed.startsWith("data:")) return;
101
+ const raw = trimmed.slice(5).trim();
102
+ if (!raw || raw === "[DONE]") return;
103
+ try {
104
+ const parsed = JSON.parse(raw) as unknown;
105
+ const usage = parseTokenUsage(parsed);
106
+ if (usage) onUsage(usage);
107
+ const reasoning = reasoningTextFromChunk(parsed);
108
+ if (reasoning) onReasoning?.(reasoning);
109
+ } catch {
110
+ // ignore partial SSE frames
111
+ }
112
+ }
113
+
114
+ async function pumpSse(
115
+ body: ReadableStream<Uint8Array>,
116
+ onUsage: (usage: TokenUsage) => void,
117
+ onReasoning?: (text: string) => void,
118
+ ): Promise<void> {
119
+ const reader = body.getReader();
120
+ const decoder = new TextDecoder();
121
+ let buf = "";
122
+ try {
123
+ while (true) {
124
+ const { done, value } = await reader.read();
125
+ if (value) buf += decoder.decode(value, { stream: !done });
126
+ const parts = buf.split("\n");
127
+ buf = done ? "" : (parts.pop() ?? "");
128
+ for (const line of parts) scanSseLine(line, onUsage, onReasoning);
129
+ if (done) {
130
+ if (buf) scanSseLine(buf, onUsage, onReasoning);
131
+ break;
132
+ }
133
+ }
134
+ } catch {
135
+ // probe side can fail independently of the model stream
136
+ }
137
+ }
138
+
139
+ type FetchFn = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
140
+
141
+ /** Tee a fetch so streamed OpenRouter/OpenAI usage and reasoning are captured. */
142
+ export function createUsageTrackingFetch(
143
+ onUsage: (usage: TokenUsage) => void,
144
+ baseFetch: FetchFn = fetch,
145
+ onReasoning?: (text: string) => void,
146
+ ): FetchFn {
147
+ return async (input, init) => {
148
+ const res = await baseFetch(input, init);
149
+ const contentType = res.headers.get("content-type") ?? "";
150
+ if (!res.body) return res;
151
+ if (contentType.includes("text/event-stream")) {
152
+ const [out, probe] = res.body.tee();
153
+ void pumpSse(probe, onUsage, onReasoning);
154
+ return new Response(out, res);
155
+ }
156
+ if (contentType.includes("application/json")) {
157
+ const text = await res.text();
158
+ try {
159
+ const parsed = JSON.parse(text) as unknown;
160
+ const usage = parseTokenUsage(parsed);
161
+ if (usage) onUsage(usage);
162
+ const reasoning = reasoningTextFromChunk(parsed);
163
+ if (reasoning) onReasoning?.(reasoning);
164
+ } catch {
165
+ // keep the body even if JSON is unexpected
166
+ }
167
+ return new Response(text, res);
168
+ }
169
+ return res;
170
+ };
171
+ }