@standardagents/builder 0.24.5 → 0.24.7

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 (54) hide show
  1. package/dist/built-in-routes.js +303 -37
  2. package/dist/built-in-routes.js.map +1 -1
  3. package/dist/client/{ApiKeysView-CmObAp7n.js → ApiKeysView-C_QyBNy2.js} +1 -1
  4. package/dist/client/CenteredContentView-c7OLhxvd.js +1 -0
  5. package/dist/client/CompositionView-DqKI6dJ9.js +32 -0
  6. package/dist/client/{ConfirmDialog.vue_vue_type_script_setup_true_lang-A1C0eTY7.js → ConfirmDialog.vue_vue_type_script_setup_true_lang-DQIo2wlE.js} +1 -1
  7. package/dist/client/{CopyButton.vue_vue_type_script_setup_true_lang-D5q8qf4n.js → CopyButton.vue_vue_type_script_setup_true_lang-q-A7DQTq.js} +1 -1
  8. package/dist/client/{DataTable.vue_vue_type_script_setup_true_lang-DzPpurCp.js → DataTable.vue_vue_type_script_setup_true_lang-B0UNyBiO.js} +1 -1
  9. package/dist/client/{JsonViewer-CKqMMqjU.js → JsonViewer-DrA7M9_g.js} +1 -1
  10. package/dist/client/{LoginView-BY2NMQQF.js → LoginView-BxbNgfzz.js} +1 -1
  11. package/dist/client/{MarketplaceView-DVEMUvDq.js → MarketplaceView-DXrtN6-0.js} +1 -1
  12. package/dist/client/{Modal.vue_vue_type_script_setup_true_lang-1t6cxO9H.js → Modal.vue_vue_type_script_setup_true_lang-CLZzFYMW.js} +1 -1
  13. package/dist/client/{ModelModal.vue_vue_type_script_setup_true_lang-WFlATqyT.js → ModelModal.vue_vue_type_script_setup_true_lang-BaLZApRs.js} +1 -1
  14. package/dist/client/{ModelsView-_qZmXle8.js → ModelsView-CVtPgAVZ.js} +1 -1
  15. package/dist/client/{PromptEditView-DzY493YB.js → PromptEditView-Dhc0rBHD.js} +1 -1
  16. package/dist/client/{PromptModal-BQYwnWKw.js → PromptModal-DXt6M359.js} +1 -1
  17. package/dist/client/{PromptsView-DBiQ9X1g.js → PromptsView-y3yvzkjM.js} +1 -1
  18. package/dist/client/{ProvidersView-DEH34_v0.js → ProvidersView-DN-SmDPF.js} +1 -1
  19. package/dist/client/ThreadInspectorPane.vue_vue_type_script_setup_true_lang-lIW3rtYB.js +22 -0
  20. package/dist/client/ThreadsView-B1Xo2bP0.js +1 -0
  21. package/dist/client/{ToolsView-D-qvyctb.js → ToolsView-DYj_Mk9L.js} +1 -1
  22. package/dist/client/{UiCodeBlock.vue_vue_type_script_setup_true_lang-BawOR_eB.js → UiCodeBlock.vue_vue_type_script_setup_true_lang-BH3WC9G_.js} +1 -1
  23. package/dist/client/{UsersView-DaXRB61v.js → UsersView-BLNNFDUM.js} +1 -1
  24. package/dist/client/{VariablesView-DDomn-IB.js → VariablesView-D4-5tNwt.js} +1 -1
  25. package/dist/client/assets/{ThreadInspectorPane-CjK6SKEi.css → ThreadInspectorPane-CGrBd6US.css} +1 -1
  26. package/dist/client/assets/index-B38KmIlM.css +1 -0
  27. package/dist/client/{check-DKLwABgc.js → check-Dkzs1C3V.js} +1 -1
  28. package/dist/client/{chevron-right-DJJGHNE5.js → chevron-right-BGirddPg.js} +1 -1
  29. package/dist/client/{copy-CLWiDcxB.js → copy-C08OR8rY.js} +1 -1
  30. package/dist/client/{formkit-DcuuXZjC.js → formkit-YJ1Z7D5r.js} +1 -1
  31. package/dist/client/{index-DihZBCmQ.js → index-0OxNDXyK.js} +3 -3
  32. package/dist/client/index.html +4 -4
  33. package/dist/client/{package-CarOhnUs.js → package-guyzMTDG.js} +1 -1
  34. package/dist/client/{plus-zGapov7j.js → plus-DG3ZN5wg.js} +1 -1
  35. package/dist/client/{timeAgo-ASgzq6bq.js → timeAgo-D7V247YG.js} +1 -1
  36. package/dist/client/{useActionFeedback-uUrfjlCo.js → useActionFeedback-byARNQjQ.js} +1 -1
  37. package/dist/client/vue-BqC6IZDY.js +1 -0
  38. package/dist/{index-D7KMmRgr.d.ts → index-Bd--_E_1.d.ts} +18 -1
  39. package/dist/index.d.ts +1 -1
  40. package/dist/index.js +224 -41
  41. package/dist/index.js.map +1 -1
  42. package/dist/plugin.js +2 -0
  43. package/dist/plugin.js.map +1 -1
  44. package/dist/runtime.d.ts +19 -2
  45. package/dist/runtime.js +222 -41
  46. package/dist/runtime.js.map +1 -1
  47. package/dist/test.d.ts +1 -1
  48. package/package.json +5 -5
  49. package/dist/client/CenteredContentView-gJXa9UHE.js +0 -1
  50. package/dist/client/CompositionView-BohQwGLE.js +0 -32
  51. package/dist/client/ThreadInspectorPane.vue_vue_type_script_setup_true_lang-Dtd1VFrj.js +0 -22
  52. package/dist/client/ThreadsView-m1CAq3Aw.js +0 -1
  53. package/dist/client/assets/index-V68N0r_5.css +0 -1
  54. package/dist/client/vue-2tGL2Ulx.js +0 -1
@@ -1,7 +1,7 @@
1
1
  import { DurableObjectStorage } from '@cloudflare/workers-types';
2
2
  import { ZodObject, ZodRawShape } from 'zod';
3
3
  import { N as NamespacedRegistry } from './types-Bpe7IANZ.js';
4
- import { ToolResult as ToolResult$1, VariableDefinition, HookName, HookSignatures, ThreadState, HookMessage, HookToolCall, HookToolResult, ClientToolRequest, ClientToolResponse, CodeExecutionOptions, CodeExecutionResult, InjectMessageInput, QueueMessageInput, SubagentRegistryEntry, AgentDefinition, SkillMetadata, SkillFileInput, ControllerContext, Controller, ThreadEndpointHandler } from '@standardagents/spec';
4
+ import { ToolResult as ToolResult$1, VariableDefinition, HookName, HookSignatures, ThreadState, HookMessage, HookToolCall, HookToolResult, ClientToolRequest, ClientToolResponse, CodeExecutionOptions, CodeExecutionResult, InjectMessageInput, QueueMessageInput, SubagentRegistryEntry, ProviderUsagePricing, AgentDefinition, SkillMetadata, SkillFileInput, ControllerContext, Controller, ThreadEndpointHandler } from '@standardagents/spec';
5
5
 
6
6
  /**
7
7
  * Callback function to execute before stream closes
@@ -693,11 +693,19 @@ interface LLMResponse {
693
693
  };
694
694
  cost?: number;
695
695
  provider?: string;
696
+ /**
697
+ * Provider-reported unit prices (USD per million tokens) for the model
698
+ * that served this request, when the provider exposes a live catalog
699
+ * (e.g. OpenRouter). Used to split logged cost into input/cached/output.
700
+ */
701
+ pricing?: ProviderUsagePricing;
696
702
  };
697
703
  /** @internal Provider instance reference for async metadata fetching */
698
704
  _provider?: unknown;
699
705
  /** @internal True when the request routed through the Standard Agents platform passthrough */
700
706
  _viaPlatform?: boolean;
707
+ /** @internal Router-fee percent the platform proxy reported for this request's origin (hosted routing only) */
708
+ _routerFeePercent?: number;
701
709
  /** @internal Provider response ID for async metadata fetching */
702
710
  _providerResponseId?: string;
703
711
  /** @internal Aggregate response for logging */
@@ -847,6 +855,11 @@ interface LogData {
847
855
  cost_input?: number;
848
856
  cost_cached?: number;
849
857
  cost_output?: number;
858
+ /** Standard Agents router fee (hosted routing markup on the raw provider cost); 0/absent for BYOK. */
859
+ cost_router_fee?: number;
860
+ /** Fee percent the platform reported for this request (e.g. 10 or 2.5). */
861
+ router_fee_percent?: number;
862
+ /** Total including cost_router_fee when the request routed through the platform. */
850
863
  cost_total?: number;
851
864
  message_history_length?: number;
852
865
  tools_available?: number;
@@ -1049,6 +1062,10 @@ interface LogDetails {
1049
1062
  error_type: string | null;
1050
1063
  cost_input: number | null;
1051
1064
  cost_output: number | null;
1065
+ /** Standard Agents router fee included in cost_total (hosted routing only). */
1066
+ cost_router_fee: number | null;
1067
+ /** Router-fee percent the platform reported for this request (e.g. 10 or 2.5). */
1068
+ router_fee_percent: number | null;
1052
1069
  cost_total: number | null;
1053
1070
  message_history_length: number | null;
1054
1071
  tools_available: number | null;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { ModelDefinition, AgentDefinition } from './runtime.js';
2
2
  export { AgentBuilderEnv, AuthContext, AuthUser, BroadcastOptions, CodeExecutionBridge, DurableAgentBuilder, DurableThread, FlowStateSdk, FlowStateWithSdk, ImageContextConfig, InjectMessageOptions, LLMProviderInterface, NamespaceResolutionError, PromptContent, PromptDefinition, PromptIncludePart, PromptPart, PromptToolConfig, Provider, ProviderContentPart, ProviderFilePart, ProviderImagePart, ProviderRegistry, ProviderTextPart, SessionToolBinding, SessionToolConfig, SideConfig, SubagentToolConfig, SubpromptConfig, ThreadRegistryEntry, ToolConfig, UpdateThreadParams, User, authenticate, buildImageDescription, cat, createNamespaceContext, emitThreadEvent, enhanceFlowState, exists, find, forceTurn, generateImageDescription, getFileStats, getMessages, getMessagesToSummarize, getShortName, getThumbnail, getUnsummarizedImageAttachments, getVisibleAgentNames, getVisibleModelNames, getVisiblePromptNames, getVisibleToolNames, grep, hasImageAttachments, head, injectMessage, isQualifiedName, linkFile, mkdir, move, optimizeImageContext, parseQualifiedName, qualifyName, queueTool, readFile, readdir, reloadHistory, rename, replaceImagesWithDescriptions, requireAdmin, requireAuth, resolveAgent, resolveHook, resolveModel, resolvePrompt, resolveTool, rmdir, stat, tail, unlink, updateThread, writeFile, writeImage } from './runtime.js';
3
3
  export { AgentPluginOptions, agentbuilder, builder } from './plugin.js';
4
- export { A as Agent, m as AttachmentRef, f as BuilderThreadEndpointHandler, B as Controller, a as ControllerContext, E as Env, l as FileRecord, n as FileStats, j as FlowResult, F as FlowState, G as GrepResult, p as ImageContentPart, I as ImageMetadata, L as LLMResponse, M as Message, r as MessageContent, q as MultimodalContent, R as RequestContext, S as StorageBackend, k as TelemetryEvent, o as TextContentPart, b as ThreadEndpointContext, e as ThreadEnv, g as ThreadInstance, h as ThreadMetadata, T as ToolCall, i as ToolResult, c as createThreadEndpointHandler, d as defineController } from './index-D7KMmRgr.js';
4
+ export { A as Agent, m as AttachmentRef, f as BuilderThreadEndpointHandler, B as Controller, a as ControllerContext, E as Env, l as FileRecord, n as FileStats, j as FlowResult, F as FlowState, G as GrepResult, p as ImageContentPart, I as ImageMetadata, L as LLMResponse, M as Message, r as MessageContent, q as MultimodalContent, R as RequestContext, S as StorageBackend, k as TelemetryEvent, o as TextContentPart, b as ThreadEndpointContext, e as ThreadEnv, g as ThreadInstance, h as ThreadMetadata, T as ToolCall, i as ToolResult, c as createThreadEndpointHandler, d as defineController } from './index-Bd--_E_1.js';
5
5
  export { AgentType, DefinitionLoader, GlobalNamespaceContext, HookSignatures, ImageContent, ModelCapabilities, ModelProvider, NamespaceContext, PackageSignature, PackedExports, PackedMeta, PackedMetadata, PackedNamespaceContext, PromptInput, PromptTextPart, ProviderAssistantMessage, ProviderConfigSlot, ProviderConfigSlots, ProviderConfigValueSource, ProviderDefinition, ProviderError, ProviderErrorCode, ProviderFactory, ProviderFactoryConfig, ProviderFinishReason, ProviderGeneratedImage, ProviderMessage, ProviderMessageContent, ProviderMethodOverrides, ModelCapabilities as ProviderModelCapabilities, ProviderOverride, ProviderOverrideContext, ProviderReasoningDetail, ProviderRequest, ProviderResponse, ProviderStreamChunk, ProviderSyncOverride, ProviderSystemMessage, ProviderTool, ProviderToolCallPart, ProviderToolMessage, ProviderToolResultContent, ProviderUsage, ProviderUserMessage, ReasoningConfig, StructuredPrompt, TextContent, Tool, ToolArgs, ToolArgsNode, ToolArgsRawShape, ToolContent, belongsToPackage, defineAgent, defineHook, defineModel, definePrompt, defineProvider, defineTool, isPacked, isVisibleInNamespace, mapReasoningLevel, providerConst, providerEnv, providerValue } from '@standardagents/spec';
6
6
  export { C as ConstituentItem, D as DiscoveredPackage, N as NamespacedRegistry, P as PackingAnalysis, a as PackingOptions, b as PackingResult, c as UnpackOptions, d as UnpackResult } from './types-Bpe7IANZ.js';
7
7
  export { D as DiscoveryConfig, P as PackageDiscoveryService, d as discoverPackages } from './discovery-DiMJWisl.js';
package/dist/index.js CHANGED
@@ -217,6 +217,18 @@ function getFallbackPricing(providerName, modelId) {
217
217
  const pricing = getProviderModelPricing(providerName, modelId);
218
218
  return pricing ? toResolvedModelPricing(pricing) : null;
219
219
  }
220
+ function resolveUsageReportedPricing(usage) {
221
+ const pricing = usage.pricing;
222
+ if (!pricing || typeof pricing.inputPerMillion !== "number" || typeof pricing.outputPerMillion !== "number") {
223
+ return null;
224
+ }
225
+ return {
226
+ inputPrice: pricing.inputPerMillion,
227
+ outputPrice: pricing.outputPerMillion,
228
+ cachedPrice: pricing.cachedInputPerMillion,
229
+ source: "provider"
230
+ };
231
+ }
220
232
  function resolveModelPricing(modelDef, providerName) {
221
233
  if (typeof modelDef.inputPrice === "number" && typeof modelDef.outputPrice === "number") {
222
234
  return {
@@ -231,6 +243,12 @@ function resolveModelPricing(modelDef, providerName) {
231
243
  }
232
244
  return null;
233
245
  }
246
+ function calculateRouterFee(rawCost, feePercent) {
247
+ if (!(rawCost > 0) || !(feePercent > 0)) {
248
+ return 0;
249
+ }
250
+ return roundCost(rawCost * feePercent / 100);
251
+ }
234
252
  function calculateUsageCost(usage, pricing) {
235
253
  if (!pricing) {
236
254
  return null;
@@ -261,6 +279,66 @@ var init_pricing = __esm({
261
279
  TOKENS_PER_MILLION = 1e6;
262
280
  }
263
281
  });
282
+
283
+ // src/agents/providers/router-fee.ts
284
+ function requestUrl(input) {
285
+ if (typeof input === "string") return input;
286
+ if (input instanceof URL) return input.toString();
287
+ if (typeof input === "object" && input !== null && typeof input.url === "string") {
288
+ return input.url;
289
+ }
290
+ return null;
291
+ }
292
+ function observeResponse(url, headers) {
293
+ if (!url) return;
294
+ for (const origin of registeredOrigins) {
295
+ if (!url.startsWith(`${origin}/v1/proxy/`)) continue;
296
+ const raw = headers.get(ROUTER_FEE_HEADER);
297
+ if (raw !== null) {
298
+ const percent = Number(raw);
299
+ if (Number.isFinite(percent) && percent >= 0) {
300
+ observedFeePercentByOrigin.set(origin, percent);
301
+ }
302
+ }
303
+ return;
304
+ }
305
+ }
306
+ function installObserver() {
307
+ if (observerInstalled) return;
308
+ const original = globalThis.fetch;
309
+ if (typeof original !== "function") return;
310
+ const bound = original.bind(globalThis);
311
+ const wrapped = async (input, init) => {
312
+ const response = await bound(input, init);
313
+ try {
314
+ observeResponse(requestUrl(input), response.headers);
315
+ } catch {
316
+ }
317
+ return response;
318
+ };
319
+ try {
320
+ globalThis.fetch = wrapped;
321
+ observerInstalled = true;
322
+ } catch {
323
+ }
324
+ }
325
+ function registerPlatformProxyOrigin(origin) {
326
+ if (!origin) return;
327
+ registeredOrigins.add(origin.replace(/\/+$/, ""));
328
+ installObserver();
329
+ }
330
+ function getObservedRouterFeePercent(origin) {
331
+ return observedFeePercentByOrigin.get(origin.replace(/\/+$/, "")) ?? null;
332
+ }
333
+ var ROUTER_FEE_HEADER, registeredOrigins, observedFeePercentByOrigin, observerInstalled;
334
+ var init_router_fee = __esm({
335
+ "src/agents/providers/router-fee.ts"() {
336
+ ROUTER_FEE_HEADER = "X-Standard-Agents-Router-Fee-Percent";
337
+ registeredOrigins = /* @__PURE__ */ new Set();
338
+ observedFeePercentByOrigin = /* @__PURE__ */ new Map();
339
+ observerInstalled = false;
340
+ }
341
+ });
264
342
  async function readCompletedArg(partialJson, argName) {
265
343
  if (!partialJson || !argName) return void 0;
266
344
  try {
@@ -811,6 +889,7 @@ var init_ProviderRegistry = __esm({
811
889
  "src/agents/providers/ProviderRegistry.ts"() {
812
890
  init_TestProvider();
813
891
  init_platform_routing();
892
+ init_router_fee();
814
893
  init_factory();
815
894
  ProviderRegistryImpl = class {
816
895
  providerCache = /* @__PURE__ */ new Map();
@@ -905,21 +984,22 @@ var init_ProviderRegistry = __esm({
905
984
  apiKey: routing.apiKey,
906
985
  baseUrl: routing.baseUrl
907
986
  };
987
+ registerPlatformProxyOrigin(routing.origin);
908
988
  const fingerprint = this.getProviderFingerprint(`platform:${providerName}`, modelDef, config);
909
989
  const cached = this.providerCache.get(modelName);
910
990
  if (cached?.fingerprint === fingerprint) {
911
- return this.buildResult(cached.provider, modelDef, true);
991
+ return this.buildResult(cached.provider, modelDef, true, routing.origin);
912
992
  }
913
- return this.cacheAndReturn(modelName, providerFactory(config), modelDef, fingerprint, true);
993
+ return this.cacheAndReturn(modelName, providerFactory(config), modelDef, fingerprint, true, routing.origin);
914
994
  }
915
995
  throw new Error(`No API key found for provider: ${providerName}. Set the provider key or STANDARD_AGENTS_API_KEY.`);
916
996
  }
917
- buildResult(provider, modelDef, viaPlatform) {
918
- return { provider, modelName: modelDef.model, modelDef, viaPlatform };
997
+ buildResult(provider, modelDef, viaPlatform, platformProxyOrigin) {
998
+ return { provider, modelName: modelDef.model, modelDef, viaPlatform, platformProxyOrigin };
919
999
  }
920
- cacheAndReturn(modelName, provider, modelDef, fingerprint, viaPlatform) {
1000
+ cacheAndReturn(modelName, provider, modelDef, fingerprint, viaPlatform, platformProxyOrigin) {
921
1001
  this.providerCache.set(modelName, { provider, fingerprint, viaPlatform });
922
- return this.buildResult(provider, modelDef, viaPlatform);
1002
+ return this.buildResult(provider, modelDef, viaPlatform, platformProxyOrigin);
923
1003
  }
924
1004
  getProviderFingerprint(providerName, modelDef, config) {
925
1005
  return JSON.stringify({
@@ -1358,7 +1438,8 @@ function convertUsage(usage) {
1358
1438
  prompt_tokens_details: usage.cachedTokens ? { cached_tokens: usage.cachedTokens } : void 0,
1359
1439
  completion_tokens_details: usage.reasoningTokens ? { reasoning_tokens: usage.reasoningTokens } : void 0,
1360
1440
  cost: usage.cost,
1361
- provider: usage.provider
1441
+ provider: usage.provider,
1442
+ pricing: usage.pricing
1362
1443
  };
1363
1444
  }
1364
1445
  function inferProviderFromModelId(model) {
@@ -1382,6 +1463,7 @@ var NON_VISION_PLACEHOLDER_TEXT, STREAM_FIRST_CHUNK_TIMEOUT_MS, STREAM_STALL_TIM
1382
1463
  var init_LLMRequest = __esm({
1383
1464
  "src/agents/LLMRequest.ts"() {
1384
1465
  init_pricing();
1466
+ init_router_fee();
1385
1467
  init_types();
1386
1468
  init_FlowEngine();
1387
1469
  init_toolProgress();
@@ -1645,11 +1727,7 @@ var init_LLMRequest = __esm({
1645
1727
  */
1646
1728
  static async callModel(modelId, context, state, logId) {
1647
1729
  const { ProviderRegistry: ProviderRegistry2 } = await Promise.resolve().then(() => (init_providers(), providers_exports));
1648
- const { provider, modelName, modelDef, viaPlatform } = await ProviderRegistry2.getProvider(
1649
- modelId,
1650
- state.env,
1651
- state.thread.instance
1652
- );
1730
+ const { provider, modelName, modelDef, viaPlatform, platformProxyOrigin } = await ProviderRegistry2.getProvider(modelId, state.env, state.thread.instance);
1653
1731
  const streamAbort = new AbortController();
1654
1732
  const parentSignal = state.abortController?.signal;
1655
1733
  let onParentAbort;
@@ -1928,6 +2006,12 @@ var init_LLMRequest = __esm({
1928
2006
  };
1929
2007
  response._provider = provider;
1930
2008
  response._viaPlatform = viaPlatform;
2009
+ if (platformProxyOrigin) {
2010
+ const feePercent = getObservedRouterFeePercent(platformProxyOrigin);
2011
+ if (feePercent !== null) {
2012
+ response._routerFeePercent = feePercent;
2013
+ }
2014
+ }
1931
2015
  response._providerResponseId = providerResponseId;
1932
2016
  response._timing = {
1933
2017
  latencyMs: firstChunkAt > 0 ? firstChunkAt - requestSentAt : null,
@@ -2053,10 +2137,13 @@ var init_LLMRequest = __esm({
2053
2137
  const toolsCalled = response.tool_calls ? JSON.stringify(response.tool_calls.map((tc) => tc.function.name)) : null;
2054
2138
  const providerName = response._provider?.name;
2055
2139
  const standardAgentsRouterUsed = response._viaPlatform === true || providerName === "platform";
2056
- const resolvedPricing = resolveModelPricing(modelDef, providerName);
2140
+ const resolvedPricing = resolveModelPricing(modelDef) ?? resolveUsageReportedPricing(response.usage) ?? resolveModelPricing(modelDef, providerName);
2057
2141
  const calculatedCost = calculateUsageCost(response.usage, resolvedPricing);
2058
2142
  const providerReportedCost = typeof response.usage.cost === "number" ? response.usage.cost : typeof response.usage.cost === "string" ? parseFloat(response.usage.cost) : null;
2059
- const cost_total = providerReportedCost != null && !Number.isNaN(providerReportedCost) ? providerReportedCost : calculatedCost?.costTotal ?? null;
2143
+ const rawProviderCost = providerReportedCost != null && !Number.isNaN(providerReportedCost) ? providerReportedCost : calculatedCost?.costTotal ?? null;
2144
+ const routerFeePercent = standardAgentsRouterUsed && typeof response._routerFeePercent === "number" && response._routerFeePercent > 0 ? response._routerFeePercent : null;
2145
+ const costRouterFee = routerFeePercent !== null && rawProviderCost !== null ? calculateRouterFee(rawProviderCost, routerFeePercent) : null;
2146
+ const cost_total = rawProviderCost !== null && costRouterFee !== null && costRouterFee > 0 ? roundCost(rawProviderCost + costRouterFee) : rawProviderCost;
2060
2147
  const actualProvider = normalizeProviderMetadataValue(response.usage.provider) ?? null;
2061
2148
  const aggregateResponse = response._aggregate_response;
2062
2149
  const responseBody = aggregateResponse ? JSON.stringify(aggregateResponse) : JSON.stringify(response);
@@ -2122,6 +2209,8 @@ var init_LLMRequest = __esm({
2122
2209
  cost_input: calculatedCost?.costInput,
2123
2210
  cost_cached: calculatedCost?.costCached,
2124
2211
  cost_output: calculatedCost?.costOutput,
2212
+ cost_router_fee: costRouterFee ?? void 0,
2213
+ router_fee_percent: routerFeePercent ?? void 0,
2125
2214
  latency_ms: Date.now() - startTime,
2126
2215
  time_to_first_token_ms: timing?.latencyMs ?? void 0,
2127
2216
  generation_ms: timing?.generationMs ?? void 0,
@@ -2162,8 +2251,10 @@ var init_LLMRequest = __esm({
2162
2251
  actual_provider = ?17,
2163
2252
  standard_agents_router_used = ?18,
2164
2253
  time_to_first_token_ms = ?19,
2165
- generation_ms = ?20
2166
- WHERE id = ?21
2254
+ generation_ms = ?20,
2255
+ cost_router_fee = ?21,
2256
+ router_fee_percent = ?22
2257
+ WHERE id = ?23
2167
2258
  `,
2168
2259
  logData.response_body,
2169
2260
  logData.input_tokens,
@@ -2185,6 +2276,8 @@ var init_LLMRequest = __esm({
2185
2276
  standardAgentsRouterUsed ? 1 : 0,
2186
2277
  logData.time_to_first_token_ms ?? null,
2187
2278
  logData.generation_ms ?? null,
2279
+ logData.cost_router_fee ?? null,
2280
+ logData.router_fee_percent ?? null,
2188
2281
  logId
2189
2282
  );
2190
2283
  }
@@ -2523,9 +2616,24 @@ ${errorStack}` : ""}${errorDetails}`;
2523
2616
  updates.push(`actual_provider = ?${paramIndex++}`);
2524
2617
  values.push(actualProvider);
2525
2618
  }
2619
+ let updatedCostTotal;
2620
+ let updatedRouterFee;
2526
2621
  if (metadata.generation_cost !== void 0) {
2622
+ updatedCostTotal = metadata.generation_cost;
2623
+ const rawCost = typeof metadata.generation_cost === "number" ? metadata.generation_cost : Number(metadata.generation_cost);
2624
+ if (Number.isFinite(rawCost)) {
2625
+ const feePercent = await this.readRouterFeePercent(state, logId);
2626
+ if (feePercent !== null && feePercent > 0) {
2627
+ updatedRouterFee = calculateRouterFee(rawCost, feePercent);
2628
+ updatedCostTotal = roundCost(rawCost + updatedRouterFee);
2629
+ }
2630
+ }
2527
2631
  updates.push(`cost_total = ?${paramIndex++}`);
2528
- values.push(metadata.generation_cost);
2632
+ values.push(updatedCostTotal);
2633
+ if (updatedRouterFee !== void 0) {
2634
+ updates.push(`cost_router_fee = ?${paramIndex++}`);
2635
+ values.push(updatedRouterFee);
2636
+ }
2529
2637
  }
2530
2638
  if (updates.length === 0) {
2531
2639
  return;
@@ -2540,7 +2648,8 @@ ${errorStack}` : ""}${errorDetails}`;
2540
2648
  data: {
2541
2649
  id: logId,
2542
2650
  ...actualProvider !== void 0 && { actual_provider: actualProvider },
2543
- ...metadata.generation_cost !== void 0 && { cost_total: metadata.generation_cost }
2651
+ ...metadata.generation_cost !== void 0 && { cost_total: updatedCostTotal },
2652
+ ...updatedRouterFee !== void 0 && { cost_router_fee: updatedRouterFee }
2544
2653
  }
2545
2654
  });
2546
2655
  }
@@ -2548,6 +2657,23 @@ ${errorStack}` : ""}${errorDetails}`;
2548
2657
  console.error("Failed to update log with metadata (non-fatal):", error);
2549
2658
  }
2550
2659
  }
2660
+ /**
2661
+ * Router-fee percent recorded on a log row by logSuccess, or null when the
2662
+ * row has none (BYOK) or the storage shape doesn't expose it.
2663
+ */
2664
+ static async readRouterFeePercent(state, logId) {
2665
+ try {
2666
+ const cursor = await state.storage.sql.exec(
2667
+ `SELECT router_fee_percent FROM logs WHERE id = ?`,
2668
+ logId
2669
+ );
2670
+ const row = cursor?.toArray?.()[0];
2671
+ const percent = row?.router_fee_percent;
2672
+ return typeof percent === "number" && Number.isFinite(percent) ? percent : null;
2673
+ } catch {
2674
+ return null;
2675
+ }
2676
+ }
2551
2677
  };
2552
2678
  }
2553
2679
  });
@@ -13925,6 +14051,8 @@ declare module 'virtual:@standardagents/builder' {
13925
14051
  error_type: string | null;
13926
14052
  cost_input: number | null;
13927
14053
  cost_output: number | null;
14054
+ cost_router_fee: number | null;
14055
+ router_fee_percent: number | null;
13928
14056
  message_history_length: number | null;
13929
14057
  tools_available: number | null;
13930
14058
  tools_schema: string | null;
@@ -22936,8 +23064,28 @@ var migration32 = {
22936
23064
  }
22937
23065
  };
22938
23066
 
23067
+ // src/durable-objects/migrations/033_add_router_fee.ts
23068
+ var migration33 = {
23069
+ version: 33,
23070
+ name: "add_router_fee",
23071
+ async up(sql) {
23072
+ const tableInfo = sql.exec(`PRAGMA table_info(logs)`).toArray();
23073
+ const hasColumn = (name) => tableInfo.some((col) => col.name === name);
23074
+ if (!hasColumn("cost_router_fee")) {
23075
+ await sql.exec(`
23076
+ ALTER TABLE logs ADD COLUMN cost_router_fee REAL;
23077
+ `);
23078
+ }
23079
+ if (!hasColumn("router_fee_percent")) {
23080
+ await sql.exec(`
23081
+ ALTER TABLE logs ADD COLUMN router_fee_percent REAL;
23082
+ `);
23083
+ }
23084
+ }
23085
+ };
23086
+
22939
23087
  // src/durable-objects/migrations/index.ts
22940
- var migrations = [migration, migration2, migration3, migration4, migration5, migration6, migration7, migration8, migration9, migration10, migration11, migration12, migration13, migration14, migration15, migration16, migration17, migration18, migration19, migration20, migration21, migration22, migration23, migration24, migration25, migration26, migration27, migration28, migration29, migration30, migration31, migration32];
23088
+ var migrations = [migration, migration2, migration3, migration4, migration5, migration6, migration7, migration8, migration9, migration10, migration11, migration12, migration13, migration14, migration15, migration16, migration17, migration18, migration19, migration20, migration21, migration22, migration23, migration24, migration25, migration26, migration27, migration28, migration29, migration30, migration31, migration32, migration33];
22941
23089
  var LATEST_SCHEMA_VERSION = migrations.length;
22942
23090
 
22943
23091
  // src/durable-objects/DurableThread.ts
@@ -24417,8 +24565,10 @@ var DurableThread = class _DurableThread extends DurableObject {
24417
24565
  async setValue(key, value) {
24418
24566
  await this.ensureMigrated();
24419
24567
  this.assertValidThreadValueKey(key);
24568
+ const updatedAt = Date.now() * 1e3;
24420
24569
  if (value === null || value === void 0) {
24421
24570
  await this.ctx.storage.sql.exec(`DELETE FROM thread_values WHERE key = ?`, key);
24571
+ this.broadcastLog({ type: "kv_data", key, deleted: true, updated_at: updatedAt });
24422
24572
  return;
24423
24573
  }
24424
24574
  const serialized = this.serializeThreadValue(value);
@@ -24432,8 +24582,9 @@ var DurableThread = class _DurableThread extends DurableObject {
24432
24582
  `,
24433
24583
  key,
24434
24584
  serialized,
24435
- Date.now() * 1e3
24585
+ updatedAt
24436
24586
  );
24587
+ this.broadcastLog({ type: "kv_data", key, deleted: false, updated_at: updatedAt });
24437
24588
  }
24438
24589
  async listValues(options = {}) {
24439
24590
  await this.ensureMigrated();
@@ -25053,9 +25204,9 @@ var DurableThread = class _DurableThread extends DurableObject {
25053
25204
  * Each migration is run in order, starting from the current version + 1.
25054
25205
  */
25055
25206
  async runMigrations(fromVersion) {
25056
- for (const migration43 of migrations) {
25057
- if (migration43.version > fromVersion) {
25058
- await migration43.up(this.ctx.storage.sql);
25207
+ for (const migration44 of migrations) {
25208
+ if (migration44.version > fromVersion) {
25209
+ await migration44.up(this.ctx.storage.sql);
25059
25210
  }
25060
25211
  }
25061
25212
  }
@@ -26489,7 +26640,7 @@ ${resultContent}${attachmentSummary}`;
26489
26640
  SELECT
26490
26641
  id, message_id, provider, actual_provider, standard_agents_router_used, model, model_name, prompt_name,
26491
26642
  tools_called, queued_tools, provider_tools, parent_log_id, retry_of_log_id, error, cost_total,
26492
- input_tokens, output_tokens, total_tokens,
26643
+ input_tokens, cached_tokens, output_tokens, total_tokens,
26493
26644
  is_complete, created_at, request_body
26494
26645
  FROM logs
26495
26646
  ORDER BY created_at ${order}
@@ -26515,6 +26666,7 @@ ${resultContent}${attachmentSummary}`;
26515
26666
  error: row.error,
26516
26667
  cost_total: row.cost_total,
26517
26668
  input_tokens: row.input_tokens,
26669
+ cached_tokens: row.cached_tokens,
26518
26670
  output_tokens: row.output_tokens,
26519
26671
  total_tokens: row.total_tokens,
26520
26672
  is_complete: row.is_complete === 1,
@@ -26538,11 +26690,19 @@ ${resultContent}${attachmentSummary}`;
26538
26690
  await this.ensureMigrated();
26539
26691
  const byModel = {};
26540
26692
  let totalCost = 0;
26693
+ let inputCost = 0;
26694
+ let cachedCost = 0;
26695
+ let outputCost = 0;
26696
+ let routerFeeCost = 0;
26541
26697
  let requestCount = 0;
26542
26698
  const modelRows = await this.ctx.storage.sql.exec(
26543
26699
  `
26544
26700
  SELECT COALESCE(model_name, model, 'unknown') AS model_key,
26545
26701
  SUM(cost_total) AS total_cost,
26702
+ SUM(CASE WHEN cost_cached IS NOT NULL THEN cost_input END) AS input_cost,
26703
+ SUM(cost_cached) AS cached_cost,
26704
+ SUM(cost_output) AS output_cost,
26705
+ SUM(cost_router_fee) AS router_fee_cost,
26546
26706
  COUNT(*) AS request_count
26547
26707
  FROM logs
26548
26708
  WHERE cost_total IS NOT NULL
@@ -26550,15 +26710,35 @@ ${resultContent}${attachmentSummary}`;
26550
26710
  `
26551
26711
  );
26552
26712
  for (const row of modelRows.toArray()) {
26553
- byModel[row.model_key] = { totalCost: row.total_cost, count: row.request_count };
26713
+ byModel[row.model_key] = {
26714
+ totalCost: row.total_cost,
26715
+ inputCost: row.input_cost ?? 0,
26716
+ cachedCost: row.cached_cost ?? 0,
26717
+ outputCost: row.output_cost ?? 0,
26718
+ routerFeeCost: row.router_fee_cost ?? 0,
26719
+ count: row.request_count
26720
+ };
26554
26721
  totalCost += row.total_cost;
26722
+ inputCost += row.input_cost ?? 0;
26723
+ cachedCost += row.cached_cost ?? 0;
26724
+ outputCost += row.output_cost ?? 0;
26725
+ routerFeeCost += row.router_fee_cost ?? 0;
26555
26726
  requestCount += row.request_count;
26556
26727
  }
26557
26728
  const messageRow = await this.ctx.storage.sql.exec(
26558
26729
  `SELECT COUNT(DISTINCT message_id) AS message_count FROM logs WHERE cost_total IS NOT NULL`
26559
26730
  );
26560
26731
  const messageCount = messageRow.one().message_count || 0;
26561
- return { totalCost, requestCount, messageCount, byModel };
26732
+ return {
26733
+ totalCost,
26734
+ inputCost,
26735
+ cachedCost,
26736
+ outputCost,
26737
+ routerFeeCost,
26738
+ requestCount,
26739
+ messageCount,
26740
+ byModel
26741
+ };
26562
26742
  }
26563
26743
  /**
26564
26744
  * Get specific logs, optionally including all descendant logs.
@@ -26771,7 +26951,7 @@ ${resultContent}${attachmentSummary}`;
26771
26951
  l.request_body, l.request_headers, l.response_body, l.response_headers,
26772
26952
  l.status_code, l.reasoning_content, l.input_tokens, l.cached_tokens, l.output_tokens,
26773
26953
  l.reasoning_tokens, l.total_tokens, l.latency_ms, l.time_to_first_token_ms, l.generation_ms,
26774
- l.finish_reason, l.error, l.error_type, l.cost_input, l.cost_cached, l.cost_output, l.cost_total,
26954
+ l.finish_reason, l.error, l.error_type, l.cost_input, l.cost_cached, l.cost_output, l.cost_router_fee, l.router_fee_percent, l.cost_total,
26775
26955
  l.message_history_length, l.tools_available, l.prompt_name, l.tools_called,
26776
26956
  l.queued_tools, l.provider_tools, l.parent_log_id, l.tools_schema, l.system_prompt,
26777
26957
  l.errors, l.retry_of_log_id, l.tool_results, l.is_complete, l.created_at,
@@ -26863,6 +27043,8 @@ ${resultContent}${attachmentSummary}`;
26863
27043
  cost_input: row.cost_input,
26864
27044
  cost_cached: row.cost_cached,
26865
27045
  cost_output: row.cost_output,
27046
+ cost_router_fee: row.cost_router_fee,
27047
+ router_fee_percent: row.router_fee_percent,
26866
27048
  cost_total: row.cost_total,
26867
27049
  message_history_length: row.message_history_length,
26868
27050
  tools_available: row.tools_available,
@@ -27361,6 +27543,7 @@ ${resultContent}${attachmentSummary}`;
27361
27543
  * Broadcast a log record to all connected WebSocket clients
27362
27544
  */
27363
27545
  broadcastLog(log) {
27546
+ if (!this.logSockets || this.logSockets.size === 0) return;
27364
27547
  const payload = JSON.stringify(log);
27365
27548
  for (const ws of Array.from(this.logSockets)) {
27366
27549
  try {
@@ -28764,7 +28947,7 @@ ${resultContent}${attachmentSummary}`;
28764
28947
  };
28765
28948
 
28766
28949
  // src/durable-objects/agentbuilder-migrations/0001_initial.ts
28767
- var migration33 = {
28950
+ var migration34 = {
28768
28951
  version: 1,
28769
28952
  async up(sql) {
28770
28953
  sql.exec(`
@@ -28863,7 +29046,7 @@ var migration33 = {
28863
29046
  };
28864
29047
 
28865
29048
  // src/durable-objects/agentbuilder-migrations/0002_add_tenvs_properties.ts
28866
- var migration34 = {
29049
+ var migration35 = {
28867
29050
  version: 2,
28868
29051
  async up(sql) {
28869
29052
  sql.exec(`ALTER TABLE threads ADD COLUMN tenvs TEXT`);
@@ -28875,7 +29058,7 @@ var migration34 = {
28875
29058
  };
28876
29059
 
28877
29060
  // src/durable-objects/agentbuilder-migrations/0003_add_parent_and_terminated.ts
28878
- var migration35 = {
29061
+ var migration36 = {
28879
29062
  version: 3,
28880
29063
  async up(sql) {
28881
29064
  sql.exec(`ALTER TABLE threads ADD COLUMN parent TEXT REFERENCES threads(id)`);
@@ -28888,7 +29071,7 @@ var migration35 = {
28888
29071
  };
28889
29072
 
28890
29073
  // src/durable-objects/agentbuilder-migrations/0004_add_env_tables.ts
28891
- var migration36 = {
29074
+ var migration37 = {
28892
29075
  version: 4,
28893
29076
  async up(sql) {
28894
29077
  sql.exec(`ALTER TABLE threads ADD COLUMN env TEXT`);
@@ -28912,7 +29095,7 @@ var migration36 = {
28912
29095
  };
28913
29096
 
28914
29097
  // src/durable-objects/agentbuilder-migrations/0005_add_pending_subagent_env_requests.ts
28915
- var migration37 = {
29098
+ var migration38 = {
28916
29099
  version: 5,
28917
29100
  async up(sql) {
28918
29101
  sql.exec(`
@@ -28938,7 +29121,7 @@ var migration37 = {
28938
29121
  };
28939
29122
 
28940
29123
  // src/durable-objects/agentbuilder-migrations/0006_add_env_value_types.ts
28941
- var migration38 = {
29124
+ var migration39 = {
28942
29125
  version: 6,
28943
29126
  async up(sql) {
28944
29127
  sql.exec(
@@ -28953,7 +29136,7 @@ var migration38 = {
28953
29136
  };
28954
29137
 
28955
29138
  // src/durable-objects/agentbuilder-migrations/0007_platform_identity_replica.ts
28956
- var migration39 = {
29139
+ var migration40 = {
28957
29140
  version: 7,
28958
29141
  async up(sql) {
28959
29142
  sql.exec(`ALTER TABLE users ADD COLUMN platform_user_id TEXT`);
@@ -28982,7 +29165,7 @@ var migration39 = {
28982
29165
  };
28983
29166
 
28984
29167
  // src/durable-objects/agentbuilder-migrations/0008_add_skills.ts
28985
- var migration40 = {
29168
+ var migration41 = {
28986
29169
  version: 8,
28987
29170
  async up(sql) {
28988
29171
  sql.exec(`
@@ -29013,7 +29196,7 @@ var migration40 = {
29013
29196
  };
29014
29197
 
29015
29198
  // src/durable-objects/agentbuilder-migrations/0009_add_user_permissions.ts
29016
- var migration41 = {
29199
+ var migration42 = {
29017
29200
  version: 9,
29018
29201
  async up(sql) {
29019
29202
  sql.exec(`ALTER TABLE users ADD COLUMN permissions TEXT`);
@@ -29024,7 +29207,7 @@ var migration41 = {
29024
29207
  };
29025
29208
 
29026
29209
  // src/durable-objects/agentbuilder-migrations/0010_add_device_logins.ts
29027
- var migration42 = {
29210
+ var migration43 = {
29028
29211
  version: 10,
29029
29212
  async up(sql) {
29030
29213
  sql.exec(`
@@ -29044,7 +29227,7 @@ var migration42 = {
29044
29227
  };
29045
29228
 
29046
29229
  // src/durable-objects/agentbuilder-migrations/index.ts
29047
- var migrations2 = [migration33, migration34, migration35, migration36, migration37, migration38, migration39, migration40, migration41, migration42];
29230
+ var migrations2 = [migration34, migration35, migration36, migration37, migration38, migration39, migration40, migration41, migration42, migration43];
29048
29231
  var LATEST_SCHEMA_VERSION2 = 10;
29049
29232
 
29050
29233
  // src/utils/crypto.ts
@@ -29807,9 +29990,9 @@ ${result ?? error ?? "No result content."}${attachmentSummary}`;
29807
29990
  }
29808
29991
  }
29809
29992
  async runMigrations(fromVersion) {
29810
- for (const migration43 of migrations2) {
29811
- if (migration43.version > fromVersion) {
29812
- await migration43.up(this.ctx.storage.sql);
29993
+ for (const migration44 of migrations2) {
29994
+ if (migration44.version > fromVersion) {
29995
+ await migration44.up(this.ctx.storage.sql);
29813
29996
  }
29814
29997
  }
29815
29998
  }