@codelia/core 0.1.91 → 0.1.93

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.
package/dist/index.cjs CHANGED
@@ -67,6 +67,7 @@ __export(index_exports, {
67
67
  createModelRegistry: () => createModelRegistry,
68
68
  createProviderResponseError: () => createProviderResponseError,
69
69
  defineTool: () => defineTool,
70
+ estimateUsageCostUsd: () => estimateUsageCostUsd,
70
71
  getDefaultSystemPromptPath: () => getDefaultSystemPromptPath,
71
72
  isProviderFailureError: () => isProviderFailureError,
72
73
  isUsableModelSpec: () => isUsableModelSpec,
@@ -1252,6 +1253,22 @@ var MOONSHOT_MODELS = [
1252
1253
  ];
1253
1254
 
1254
1255
  // src/models/registry.ts
1256
+ var isNonNegativeFinite = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1257
+ function estimateUsageCostUsd(usage, cost) {
1258
+ if (!usage || !cost || !isNonNegativeFinite(cost.input) || !isNonNegativeFinite(cost.output)) {
1259
+ return null;
1260
+ }
1261
+ const cacheRead = Math.max(0, usage.input_cached_tokens ?? 0);
1262
+ const cacheWrite = Math.max(0, usage.input_cache_creation_tokens ?? 0);
1263
+ const uncachedInput = Math.max(0, usage.input_tokens - cacheRead - cacheWrite);
1264
+ const reasoningTokens = Math.max(0, usage.output_reasoning_tokens ?? 0);
1265
+ const nonReasoningOutput = Math.max(0, usage.output_tokens - reasoningTokens);
1266
+ const cacheReadRate = isNonNegativeFinite(cost.cacheRead) ? cost.cacheRead : cost.input;
1267
+ const cacheWriteRate = isNonNegativeFinite(cost.cacheWrite) ? cost.cacheWrite : cost.input;
1268
+ const reasoningRate = isNonNegativeFinite(cost.reasoning) ? cost.reasoning : cost.output;
1269
+ const totalUsd = (uncachedInput * cost.input + cacheRead * cacheReadRate + cacheWrite * cacheWriteRate + nonReasoningOutput * cost.output + reasoningTokens * reasoningRate) / 1e6;
1270
+ return Number.isFinite(totalUsd) ? totalUsd : null;
1271
+ }
1255
1272
  function createModelRegistry(specs) {
1256
1273
  const registry2 = {
1257
1274
  modelsById: {},
@@ -1346,6 +1363,7 @@ function applyModelMetadata(registry2, index) {
1346
1363
  contextWindow: spec.contextWindow ?? entry.limits?.contextWindow,
1347
1364
  maxInputTokens: spec.maxInputTokens ?? entry.limits?.inputTokens,
1348
1365
  maxOutputTokens: spec.maxOutputTokens ?? entry.limits?.outputTokens,
1366
+ cost: spec.cost ?? entry.cost,
1349
1367
  supportsFast: spec.supportsFast ?? entry.capabilities?.supportsFast,
1350
1368
  supportsVision: spec.supportsVision ?? entry.capabilities?.supportsVision,
1351
1369
  supportsTools: spec.supportsTools ?? entry.capabilities?.supportsTools
@@ -2086,43 +2104,86 @@ var TokenUsageService = class {
2086
2104
  total_tokens: 0,
2087
2105
  total_input_tokens: 0,
2088
2106
  total_output_tokens: 0,
2107
+ total_output_reasoning_tokens: 0,
2089
2108
  total_cached_input_tokens: 0,
2090
2109
  total_cache_creation_tokens: 0,
2091
- total_cost_usd: 0,
2110
+ total_input_image_tokens: 0,
2111
+ cache_hit_calls: 0,
2112
+ cache_miss_calls: 0,
2113
+ cache_unknown_calls: 0,
2114
+ total_cost_usd: null,
2092
2115
  by_model: {}
2093
2116
  };
2094
2117
  }
2095
2118
  config;
2096
2119
  usageSummary;
2097
2120
  lastUsage = null;
2098
- updateUsageSummary(usage) {
2121
+ updateUsageSummary(usage, costUsd) {
2099
2122
  this.lastUsage = usage ?? null;
2100
2123
  if (!this.config.enabled || !usage) {
2101
2124
  return;
2102
2125
  }
2126
+ const hasCacheMetric = typeof usage.input_cached_tokens === "number";
2127
+ const cached = hasCacheMetric ? usage.input_cached_tokens ?? 0 : 0;
2128
+ const cacheCreation = usage.input_cache_creation_tokens ?? 0;
2129
+ const reasoning = usage.output_reasoning_tokens ?? 0;
2130
+ const image = usage.input_image_tokens ?? 0;
2131
+ const cacheState = hasCacheMetric ? cached > 0 ? "hit" : "miss" : "unknown";
2132
+ const validCost = typeof costUsd === "number" && Number.isFinite(costUsd) && costUsd >= 0 ? costUsd : null;
2103
2133
  this.usageSummary.total_calls++;
2104
2134
  this.usageSummary.total_tokens += usage.total_tokens;
2105
2135
  this.usageSummary.total_input_tokens += usage.input_tokens;
2106
2136
  this.usageSummary.total_output_tokens += usage.output_tokens;
2107
- this.usageSummary.total_cached_input_tokens += usage.input_cached_tokens ?? 0;
2108
- this.usageSummary.total_cache_creation_tokens += usage.input_cache_creation_tokens ?? 0;
2137
+ this.usageSummary.total_output_reasoning_tokens += reasoning;
2138
+ this.usageSummary.total_cached_input_tokens += cached;
2139
+ this.usageSummary.total_cache_creation_tokens += cacheCreation;
2140
+ this.usageSummary.total_input_image_tokens += image;
2141
+ if (cacheState === "hit") {
2142
+ this.usageSummary.cache_hit_calls++;
2143
+ } else if (cacheState === "miss") {
2144
+ this.usageSummary.cache_miss_calls++;
2145
+ } else {
2146
+ this.usageSummary.cache_unknown_calls++;
2147
+ }
2148
+ if (validCost !== null) {
2149
+ this.usageSummary.total_cost_usd = (this.usageSummary.total_cost_usd ?? 0) + validCost;
2150
+ }
2109
2151
  const model = usage.model ?? "unknown";
2110
- if (!this.usageSummary.by_model[model]) {
2152
+ const bucket = this.usageSummary.by_model[model];
2153
+ if (!bucket) {
2111
2154
  this.usageSummary.by_model[model] = {
2112
2155
  calls: 1,
2113
2156
  input_tokens: usage.input_tokens,
2114
2157
  output_tokens: usage.output_tokens,
2115
- cached_input_tokens: usage.input_cached_tokens ?? 0,
2116
- cache_creation_tokens: usage.input_cache_creation_tokens ?? 0,
2117
- total_tokens: usage.total_tokens
2158
+ output_reasoning_tokens: reasoning,
2159
+ cached_input_tokens: cached,
2160
+ cache_creation_tokens: cacheCreation,
2161
+ input_image_tokens: image,
2162
+ cache_hit_calls: cacheState === "hit" ? 1 : 0,
2163
+ cache_miss_calls: cacheState === "miss" ? 1 : 0,
2164
+ cache_unknown_calls: cacheState === "unknown" ? 1 : 0,
2165
+ total_tokens: usage.total_tokens,
2166
+ cost_usd: validCost
2118
2167
  };
2119
2168
  } else {
2120
- this.usageSummary.by_model[model].calls++;
2121
- this.usageSummary.by_model[model].input_tokens += usage.input_tokens;
2122
- this.usageSummary.by_model[model].output_tokens += usage.output_tokens;
2123
- this.usageSummary.by_model[model].cached_input_tokens += usage.input_cached_tokens ?? 0;
2124
- this.usageSummary.by_model[model].cache_creation_tokens += usage.input_cache_creation_tokens ?? 0;
2125
- this.usageSummary.by_model[model].total_tokens += usage.total_tokens;
2169
+ bucket.calls++;
2170
+ bucket.input_tokens += usage.input_tokens;
2171
+ bucket.output_tokens += usage.output_tokens;
2172
+ bucket.output_reasoning_tokens += reasoning;
2173
+ bucket.cached_input_tokens += cached;
2174
+ bucket.cache_creation_tokens += cacheCreation;
2175
+ bucket.input_image_tokens += image;
2176
+ if (cacheState === "hit") {
2177
+ bucket.cache_hit_calls++;
2178
+ } else if (cacheState === "miss") {
2179
+ bucket.cache_miss_calls++;
2180
+ } else {
2181
+ bucket.cache_unknown_calls++;
2182
+ }
2183
+ bucket.total_tokens += usage.total_tokens;
2184
+ if (validCost !== null) {
2185
+ bucket.cost_usd = (bucket.cost_usd ?? 0) + validCost;
2186
+ }
2126
2187
  }
2127
2188
  }
2128
2189
  getUsageSummary() {
@@ -2709,17 +2770,31 @@ var executeToolCall = async ({
2709
2770
  }
2710
2771
  };
2711
2772
  }
2773
+ let approvalWaitMs;
2712
2774
  if (canExecuteTool) {
2775
+ const approvalStartedAt = performance.now();
2713
2776
  try {
2714
2777
  const decision = await canExecuteTool(
2715
2778
  toolCall,
2716
2779
  toolCall.function.arguments,
2717
2780
  createToolContext(signal)
2718
2781
  );
2782
+ approvalWaitMs = Math.max(
2783
+ 0,
2784
+ Math.round(performance.now() - approvalStartedAt)
2785
+ );
2719
2786
  if (decision.decision === "deny") {
2720
- return permissionDeniedResult(toolCall, decision);
2787
+ return {
2788
+ ...permissionDeniedResult(toolCall, decision),
2789
+ approvalWaitMs,
2790
+ execDurationMs: 0
2791
+ };
2721
2792
  }
2722
2793
  } catch (error) {
2794
+ approvalWaitMs = Math.max(
2795
+ 0,
2796
+ Math.round(performance.now() - approvalStartedAt)
2797
+ );
2723
2798
  return {
2724
2799
  message: {
2725
2800
  role: "tool",
@@ -2727,15 +2802,36 @@ var executeToolCall = async ({
2727
2802
  tool_name: toolName,
2728
2803
  content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
2729
2804
  is_error: true
2730
- }
2805
+ },
2806
+ approvalWaitMs,
2807
+ execDurationMs: 0
2731
2808
  };
2732
2809
  }
2733
2810
  }
2811
+ let innerApprovalWaitMs = 0;
2812
+ let hasInnerApprovalWait = false;
2813
+ const execContext = createToolContext(signal);
2814
+ execContext.recordApprovalWaitMs = (durationMs) => {
2815
+ if (Number.isFinite(durationMs) && durationMs >= 0) {
2816
+ innerApprovalWaitMs += durationMs;
2817
+ hasInnerApprovalWait = true;
2818
+ }
2819
+ };
2820
+ const execStartedAt = performance.now();
2734
2821
  try {
2735
2822
  const result = await tool.executeRaw(
2736
2823
  toolCall.function.arguments,
2737
- createToolContext(signal)
2824
+ execContext
2825
+ );
2826
+ const totalWallMs = Math.max(
2827
+ 0,
2828
+ Math.round(performance.now() - execStartedAt)
2738
2829
  );
2830
+ const roundedInnerWait = hasInnerApprovalWait ? Math.max(0, Math.round(innerApprovalWaitMs)) : 0;
2831
+ if (hasInnerApprovalWait) {
2832
+ approvalWaitMs = (approvalWaitMs ?? 0) + roundedInnerWait;
2833
+ }
2834
+ const execDurationMs = hasInnerApprovalWait ? Math.max(0, totalWallMs - roundedInnerWait) : totalWallMs;
2739
2835
  const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2740
2836
  return {
2741
2837
  message: {
@@ -2744,11 +2840,26 @@ var executeToolCall = async ({
2744
2840
  tool_name: toolName,
2745
2841
  content: toolResultToContent(result),
2746
2842
  ...displayContent ? { display_content: displayContent } : {}
2747
- }
2843
+ },
2844
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2845
+ execDurationMs
2748
2846
  };
2749
2847
  } catch (error) {
2848
+ const totalWallMs = Math.max(
2849
+ 0,
2850
+ Math.round(performance.now() - execStartedAt)
2851
+ );
2852
+ const roundedInnerWait = hasInnerApprovalWait ? Math.max(0, Math.round(innerApprovalWaitMs)) : 0;
2853
+ if (hasInnerApprovalWait) {
2854
+ approvalWaitMs = (approvalWaitMs ?? 0) + roundedInnerWait;
2855
+ }
2856
+ const execDurationMs = hasInnerApprovalWait ? Math.max(0, totalWallMs - roundedInnerWait) : totalWallMs;
2750
2857
  if (error instanceof ToolPermissionDenied)
2751
- return permissionDeniedResult(toolCall, error.decision);
2858
+ return {
2859
+ ...permissionDeniedResult(toolCall, error.decision),
2860
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2861
+ execDurationMs: 0
2862
+ };
2752
2863
  if (error instanceof TaskComplete) {
2753
2864
  return {
2754
2865
  message: {
@@ -2758,7 +2869,9 @@ var executeToolCall = async ({
2758
2869
  content: "Task complete"
2759
2870
  },
2760
2871
  done: true,
2761
- finalMessage: error.finalMessage
2872
+ finalMessage: error.finalMessage,
2873
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2874
+ execDurationMs
2762
2875
  };
2763
2876
  }
2764
2877
  return {
@@ -2768,7 +2881,9 @@ var executeToolCall = async ({
2768
2881
  tool_name: toolName,
2769
2882
  content: `Error: ${error instanceof Error ? error.message : String(error)}`,
2770
2883
  is_error: true
2771
- }
2884
+ },
2885
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2886
+ execDurationMs
2772
2887
  };
2773
2888
  }
2774
2889
  };
@@ -2869,6 +2984,40 @@ var Agent = class {
2869
2984
  getLastUsage() {
2870
2985
  return this.usageService.getLastUsage();
2871
2986
  }
2987
+ getModelCost(modelName) {
2988
+ return resolveModel(
2989
+ this.modelRegistry,
2990
+ modelName ?? this.llm.model,
2991
+ this.llm.provider
2992
+ )?.cost;
2993
+ }
2994
+ /** Lightweight scalar context window snapshot without estimating category breakdown. */
2995
+ getContextSnapshot() {
2996
+ const spec = resolveModel(
2997
+ this.modelRegistry,
2998
+ this.llm.model,
2999
+ this.llm.provider
3000
+ );
3001
+ const limitTokens = spec?.maxInputTokens ?? spec?.contextWindow ?? null;
3002
+ const usage = this.usageService.getLastUsage();
3003
+ const leftPercent = this.getContextLeftPercent();
3004
+ if (!usage) {
3005
+ return {
3006
+ limit_tokens: limitTokens,
3007
+ used_tokens: null,
3008
+ input_tokens: null,
3009
+ left_percent: leftPercent,
3010
+ basis: "none"
3011
+ };
3012
+ }
3013
+ return {
3014
+ limit_tokens: limitTokens,
3015
+ used_tokens: usage.total_tokens,
3016
+ input_tokens: usage.input_tokens,
3017
+ left_percent: leftPercent,
3018
+ basis: "provider_usage"
3019
+ };
3020
+ }
2872
3021
  /** Context window usage with an estimated per-category breakdown. */
2873
3022
  getContextUsage() {
2874
3023
  return buildContextUsage({
@@ -2908,6 +3057,13 @@ var Agent = class {
2908
3057
  );
2909
3058
  if (shouldCompact && this.compactionService) {
2910
3059
  throwIfAborted(signal);
3060
+ const compactionStartedAt = this.monotonicNowMs();
3061
+ const messagesBefore = this.history.getViewMessages().length;
3062
+ const estimateHistoryTokens = () => this.getContextUsage().breakdown.reduce(
3063
+ (total, entry) => total + entry.tokens,
3064
+ 0
3065
+ );
3066
+ const estimatedTokensBefore = estimateHistoryTokens();
2911
3067
  const startEvent = {
2912
3068
  type: "compaction_start",
2913
3069
  timestamp: Date.now()
@@ -2940,10 +3096,31 @@ var Agent = class {
2940
3096
  if (compacted || options.force) {
2941
3097
  await this.llm.onHistoryCompacted?.(invokeContext);
2942
3098
  }
3099
+ const compactionDurationMs = elapsedMilliseconds(
3100
+ compactionStartedAt,
3101
+ this.monotonicNowMs
3102
+ );
3103
+ const messagesAfter = this.history.getViewMessages().length;
3104
+ const estimatedTokensAfter = estimateHistoryTokens();
2943
3105
  const completeEvent = {
2944
3106
  type: "compaction_complete",
2945
3107
  timestamp: Date.now(),
2946
- compacted
3108
+ compacted,
3109
+ duration_ms: compactionDurationMs,
3110
+ messages_before: messagesBefore,
3111
+ messages_after: messagesAfter,
3112
+ ...typeof estimatedTokensBefore === "number" && Number.isFinite(estimatedTokensBefore) ? {
3113
+ estimated_tokens_before: Math.max(
3114
+ 0,
3115
+ Math.round(estimatedTokensBefore)
3116
+ )
3117
+ } : {},
3118
+ ...typeof estimatedTokensAfter === "number" && Number.isFinite(estimatedTokensAfter) ? {
3119
+ estimated_tokens_after: Math.max(
3120
+ 0,
3121
+ Math.round(estimatedTokensAfter)
3122
+ )
3123
+ } : {}
2947
3124
  };
2948
3125
  yield completeEvent;
2949
3126
  }
@@ -3242,8 +3419,8 @@ var Agent = class {
3242
3419
  options.streamDeltas === true,
3243
3420
  seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3244
3421
  );
3245
- this.recordLlmResponse(session, seq, response);
3246
3422
  this.usageService.updateUsageSummary(response.usage);
3423
+ this.recordLlmResponse(session, seq, response);
3247
3424
  await this.recordOriginals(session, response.messages);
3248
3425
  this.history.commitModelResponse(response);
3249
3426
  const { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls } = collectModelOutput(response.messages);
@@ -3411,7 +3588,9 @@ var Agent = class {
3411
3588
  type: "step_complete",
3412
3589
  step_id: toolCall.id,
3413
3590
  status: execution.message.is_error ? "error" : "completed",
3414
- duration_ms: durationMs
3591
+ duration_ms: durationMs,
3592
+ ...execution.execDurationMs !== void 0 ? { exec_duration_ms: execution.execDurationMs } : {},
3593
+ ...execution.approvalWaitMs !== void 0 ? { approval_wait_ms: execution.approvalWaitMs } : {}
3415
3594
  };
3416
3595
  yield stepCompleteEvent;
3417
3596
  if (execution.done) {
@@ -3532,9 +3711,9 @@ var Agent = class {
3532
3711
  );
3533
3712
  if (seq !== null && observer)
3534
3713
  await observer.completed(seq, summary.usage, false);
3714
+ this.usageService.updateUsageSummary(summary.usage);
3535
3715
  this.recordLlmResponse(session, seq, summary);
3536
3716
  await this.recordOriginals(session, summary.messages);
3537
- this.usageService.updateUsageSummary(summary.usage);
3538
3717
  const { assistantTexts } = collectModelOutput(summary.messages);
3539
3718
  const finalResponse = `[Max Iterations Reached]
3540
3719
 
@@ -3558,14 +3737,10 @@ var import_sdk = __toESM(require("@anthropic-ai/sdk"), 1);
3558
3737
  // src/llm/provider-log.ts
3559
3738
  var import_node_fs = require("fs");
3560
3739
  var import_node_path = __toESM(require("path"), 1);
3561
- var envTruthy = (value) => {
3562
- if (!value) return false;
3563
- const normalized = value.trim().toLowerCase();
3564
- return normalized === "1" || normalized === "true";
3565
- };
3740
+ var import_logger = require("@codelia/logger");
3566
3741
  var getProviderLogSettings = () => {
3567
- const enabled = envTruthy(process.env.CODELIA_PROVIDER_LOG);
3568
- const dumpDirEnv = process.env.CODELIA_PROVIDER_LOG_DIR?.trim();
3742
+ const enabled = (0, import_logger.hasDebugTopic)("provider-log");
3743
+ const dumpDirEnv = (0, import_logger.getDebugDir)();
3569
3744
  const dumpDir = enabled ? dumpDirEnv && dumpDirEnv.length > 0 ? dumpDirEnv : import_node_path.default.resolve(process.cwd(), "tmp") : void 0;
3570
3745
  return { enabled, dumpDir };
3571
3746
  };
@@ -4251,13 +4426,14 @@ var toUsage = (response) => {
4251
4426
  if (!response.usage) return null;
4252
4427
  const baseInputTokens = response.usage.input_tokens ?? 0;
4253
4428
  const cacheCreateTokens = response.usage.cache_creation_input_tokens ?? 0;
4254
- const cacheReadTokens = response.usage.cache_read_input_tokens ?? 0;
4429
+ const hasCacheRead = typeof response.usage.cache_read_input_tokens === "number";
4430
+ const cacheReadTokens = hasCacheRead ? response.usage.cache_read_input_tokens ?? 0 : 0;
4255
4431
  const inputTokens = baseInputTokens + cacheCreateTokens + cacheReadTokens;
4256
4432
  const outputTokens = response.usage.output_tokens ?? 0;
4257
4433
  return {
4258
4434
  model: response.model ?? "",
4259
4435
  input_tokens: inputTokens,
4260
- input_cached_tokens: cacheReadTokens,
4436
+ ...hasCacheRead ? { input_cached_tokens: cacheReadTokens } : {},
4261
4437
  input_cache_creation_tokens: cacheCreateTokens,
4262
4438
  output_tokens: outputTokens,
4263
4439
  total_tokens: inputTokens + outputTokens
@@ -4639,6 +4815,9 @@ var ChatAnthropic = class {
4639
4815
  // src/llm/responses/chat.ts
4640
4816
  var import_openai3 = __toESM(require("openai"), 1);
4641
4817
 
4818
+ // src/llm/openai/response-accumulator.ts
4819
+ var import_logger2 = require("@codelia/logger");
4820
+
4642
4821
  // src/llm/openai/codex-metadata.ts
4643
4822
  var import_node_crypto4 = require("crypto");
4644
4823
  var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -4999,11 +5178,6 @@ var toFunctionCallOutput = (content) => {
4999
5178
 
5000
5179
  // src/llm/openai/response-accumulator.ts
5001
5180
  var isRecord4 = (value) => typeof value === "object" && value !== null;
5002
- var envTruthy2 = (value) => {
5003
- if (!value) return false;
5004
- const normalized = value.trim().toLowerCase();
5005
- return normalized === "1" || normalized === "true";
5006
- };
5007
5181
  var loggedUnhandledResponseEventTypes = /* @__PURE__ */ new Set();
5008
5182
  var cloneValue = (value) => {
5009
5183
  if (typeof structuredClone === "function") {
@@ -5361,7 +5535,7 @@ var OpenAiResponseAccumulator = class {
5361
5535
  return content[contentIndex];
5362
5536
  }
5363
5537
  logUnhandledResponseEvent(event) {
5364
- if (!envTruthy2(process.env.CODELIA_PROVIDER_LOG) && !envTruthy2(process.env.CODELIA_DEBUG)) {
5538
+ if (!(0, import_logger2.hasDebugTopic)("provider-log") && !(0, import_logger2.isDebugEnabled)()) {
5365
5539
  return;
5366
5540
  }
5367
5541
  if (!event.type.startsWith("response.")) {
@@ -6238,7 +6412,7 @@ function fromGoogleInteraction(value, requestedModel) {
6238
6412
  model: requestedModel,
6239
6413
  ...typeof interaction.model === "string" ? { provider_model: interaction.model } : {},
6240
6414
  input_tokens: input,
6241
- input_cached_tokens: token(usage.total_cached_tokens),
6415
+ ...typeof usage.total_cached_tokens === "number" ? { input_cached_tokens: token(usage.total_cached_tokens) } : {},
6242
6416
  output_tokens: output + thought,
6243
6417
  output_reasoning_tokens: thought,
6244
6418
  total_tokens: token(usage.total_tokens) || input + output + thought
@@ -6787,13 +6961,11 @@ var normalizeUsage = (accumulator) => {
6787
6961
  if (!usage) return null;
6788
6962
  const inputTokens = normalizeNumber(usage.prompt_tokens);
6789
6963
  const outputTokens = normalizeNumber(usage.completion_tokens);
6790
- const cachedTokens = normalizeNumber(
6791
- usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens
6792
- );
6964
+ const rawCachedTokens = usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens;
6793
6965
  return {
6794
6966
  model: accumulator.model ?? "",
6795
6967
  input_tokens: inputTokens,
6796
- ...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
6968
+ ...typeof rawCachedTokens === "number" ? { input_cached_tokens: normalizeNumber(rawCachedTokens) } : {},
6797
6969
  output_tokens: outputTokens,
6798
6970
  total_tokens: typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens
6799
6971
  };
@@ -7017,6 +7189,7 @@ var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent,
7017
7189
  };
7018
7190
 
7019
7191
  // src/llm/openai/websocket-transport.ts
7192
+ var import_logger3 = require("@codelia/logger");
7020
7193
  var import_ws = require("openai/resources/responses/ws");
7021
7194
  var WS_CONNECT_TIMEOUT_MS = 2e4;
7022
7195
  var WS_RESPONSE_IDLE_TIMEOUT_MS = 3e5;
@@ -7040,12 +7213,7 @@ var resolveTimeoutMs = (value, fallbackMs) => {
7040
7213
  }
7041
7214
  return Math.floor(value);
7042
7215
  };
7043
- var envTruthy3 = (value) => {
7044
- if (!value) return false;
7045
- const normalized = value.trim().toLowerCase();
7046
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
7047
- };
7048
- var WS_EVENT_TRACE_ENABLED = envTruthy3(process.env.CODELIA_DEBUG);
7216
+ var WS_EVENT_TRACE_ENABLED = (0, import_logger3.hasDebugTopic)("ws");
7049
7217
  var WS_EVENT_TRACE_PROGRESS_LOG_INTERVAL_MS = 5e3;
7050
7218
  var wsEventTraceStateBySource = /* @__PURE__ */ new Map();
7051
7219
  var getWsEventTraceState = (source) => {
@@ -9783,13 +9951,11 @@ var normalizeZaiUsage = (accumulator) => {
9783
9951
  const inputTokens = normalizeNumber2(usage.prompt_tokens);
9784
9952
  const outputTokens = normalizeNumber2(usage.completion_tokens);
9785
9953
  const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber2(usage.total_tokens) : inputTokens + outputTokens;
9786
- const cachedTokens = normalizeNumber2(
9787
- usage.prompt_tokens_details?.cached_tokens
9788
- );
9954
+ const rawCachedTokens = usage.prompt_tokens_details?.cached_tokens;
9789
9955
  return {
9790
9956
  model: accumulator.model ?? "",
9791
9957
  input_tokens: inputTokens,
9792
- ...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
9958
+ ...typeof rawCachedTokens === "number" ? { input_cached_tokens: normalizeNumber2(rawCachedTokens) } : {},
9793
9959
  output_tokens: outputTokens,
9794
9960
  total_tokens: totalTokens
9795
9961
  };
@@ -10268,6 +10434,7 @@ function defineTool(toolOptions) {
10268
10434
  createModelRegistry,
10269
10435
  createProviderResponseError,
10270
10436
  defineTool,
10437
+ estimateUsageCostUsd,
10271
10438
  getDefaultSystemPromptPath,
10272
10439
  isProviderFailureError,
10273
10440
  isUsableModelSpec,
package/dist/index.d.ts CHANGED
@@ -257,35 +257,6 @@ declare const responseDetails: {
257
257
  /** Explicitly trusted local diagnostics; never accept a provider message/body here. */
258
258
  declare const createProviderResponseError: (provider: ProviderName, reason: keyof typeof responseDetails) => ProviderFailureError;
259
259
 
260
- type ToolOutputCacheRecord = {
261
- tool_call_id: string;
262
- tool_name: string;
263
- content: string;
264
- is_error?: boolean;
265
- };
266
- type ToolOutputCacheReadOptions = {
267
- offset?: number;
268
- limit?: number;
269
- };
270
- type ToolOutputCacheReadLineOptions = {
271
- line_number: number;
272
- char_offset?: number;
273
- char_limit?: number;
274
- };
275
- type ToolOutputCacheSearchOptions = {
276
- pattern: string;
277
- regex?: boolean;
278
- before?: number;
279
- after?: number;
280
- max_matches?: number;
281
- };
282
- type ToolOutputCacheStore = {
283
- save: (record: ToolOutputCacheRecord) => Promise<ToolOutputRef> | ToolOutputRef;
284
- read?: (refId: string, options?: ToolOutputCacheReadOptions) => Promise<string> | string;
285
- readLine?: (refId: string, options: ToolOutputCacheReadLineOptions) => Promise<string> | string;
286
- grep?: (refId: string, options: ToolOutputCacheSearchOptions) => Promise<string> | string;
287
- };
288
-
289
260
  type ModelCost = {
290
261
  input?: number;
291
262
  output?: number;
@@ -323,6 +294,35 @@ interface ModelMetadataService {
323
294
  getAllModelEntries(): Promise<Record<string, Record<string, ModelEntry>>>;
324
295
  }
325
296
 
297
+ type ToolOutputCacheRecord = {
298
+ tool_call_id: string;
299
+ tool_name: string;
300
+ content: string;
301
+ is_error?: boolean;
302
+ };
303
+ type ToolOutputCacheReadOptions = {
304
+ offset?: number;
305
+ limit?: number;
306
+ };
307
+ type ToolOutputCacheReadLineOptions = {
308
+ line_number: number;
309
+ char_offset?: number;
310
+ char_limit?: number;
311
+ };
312
+ type ToolOutputCacheSearchOptions = {
313
+ pattern: string;
314
+ regex?: boolean;
315
+ before?: number;
316
+ after?: number;
317
+ max_matches?: number;
318
+ };
319
+ type ToolOutputCacheStore = {
320
+ save: (record: ToolOutputCacheRecord) => Promise<ToolOutputRef> | ToolOutputRef;
321
+ read?: (refId: string, options?: ToolOutputCacheReadOptions) => Promise<string> | string;
322
+ readLine?: (refId: string, options: ToolOutputCacheReadLineOptions) => Promise<string> | string;
323
+ grep?: (refId: string, options: ToolOutputCacheSearchOptions) => Promise<string> | string;
324
+ };
325
+
326
326
  type ResolveImage = (ref: _codelia_shared_types.ImageArtifactRef, signal?: AbortSignal) => Promise<ImagePart>;
327
327
  type AgentServices = {
328
328
  resolveImage?: ResolveImage;
@@ -344,12 +344,19 @@ type ModelSpec = {
344
344
  contextWindow?: number;
345
345
  maxInputTokens?: number;
346
346
  maxOutputTokens?: number;
347
+ cost?: ModelCost;
347
348
  supportsTools?: boolean;
348
349
  supportsVision?: boolean;
349
350
  supportsReasoning?: boolean;
350
351
  supportsFast?: boolean;
351
352
  supportsJsonSchema?: boolean;
352
353
  };
354
+ /**
355
+ * Estimates per-call USD cost from normalized usage (where `input_tokens`
356
+ * already includes cached and cache-creation tokens) and USD-per-1M-tokens
357
+ * `ModelCost`. Returns `null` when required list prices are unavailable.
358
+ */
359
+ declare function estimateUsageCostUsd(usage: ChatInvokeUsage | null | undefined, cost: ModelCost | undefined): number | null;
353
360
  type ModelRegistry = {
354
361
  modelsById: Record<string, ModelSpec>;
355
362
  aliasesByProvider: Record<string, Record<string, string>>;
@@ -402,23 +409,34 @@ declare class ToolOutputCacheService {
402
409
  private resolveContextBudgetTokens;
403
410
  }
404
411
 
412
+ type UsageByModel = {
413
+ calls: number;
414
+ input_tokens: number;
415
+ output_tokens: number;
416
+ output_reasoning_tokens: number;
417
+ cached_input_tokens: number;
418
+ cache_creation_tokens: number;
419
+ input_image_tokens: number;
420
+ cache_hit_calls: number;
421
+ cache_miss_calls: number;
422
+ cache_unknown_calls: number;
423
+ total_tokens: number;
424
+ cost_usd?: number | null;
425
+ };
405
426
  type UsageSummary = {
406
427
  total_calls: number;
407
428
  total_tokens: number;
408
429
  total_input_tokens: number;
409
430
  total_output_tokens: number;
431
+ total_output_reasoning_tokens: number;
410
432
  total_cached_input_tokens: number;
411
433
  total_cache_creation_tokens: number;
434
+ total_input_image_tokens: number;
435
+ cache_hit_calls: number;
436
+ cache_miss_calls: number;
437
+ cache_unknown_calls: number;
412
438
  total_cost_usd?: number | null;
413
- by_model: Record<string, {
414
- calls: number;
415
- input_tokens: number;
416
- output_tokens: number;
417
- cached_input_tokens: number;
418
- cache_creation_tokens: number;
419
- total_tokens: number;
420
- cost_usd?: number | null;
421
- }>;
439
+ by_model: Record<string, UsageByModel>;
422
440
  };
423
441
 
424
442
  type DependencyKey<T> = {
@@ -429,6 +447,8 @@ type ToolContext = {
429
447
  signal?: AbortSignal;
430
448
  logger?: Logger;
431
449
  now?: () => Date;
450
+ /** Optional runtime hook for reporting approval/review wait elapsed inside executeRaw. */
451
+ recordApprovalWaitMs?: (durationMs: number) => void;
432
452
  deps: Record<string, unknown>;
433
453
  resolve: <T>(key: DependencyKey<T>) => Promise<T>;
434
454
  };
@@ -454,6 +474,8 @@ type ToolExecution = {
454
474
  message: ToolMessage;
455
475
  done?: boolean;
456
476
  finalMessage?: string;
477
+ approvalWaitMs?: number;
478
+ execDurationMs?: number;
457
479
  };
458
480
 
459
481
  type ToolPermissionDecision = {
@@ -810,6 +832,15 @@ declare class Agent {
810
832
  getContextLeftPercent(): number | null;
811
833
  /** Last provider-reported usage; a new object per completed model call. */
812
834
  getLastUsage(): ChatInvokeUsage | null;
835
+ getModelCost(modelName?: string): ModelCost | undefined;
836
+ /** Lightweight scalar context window snapshot without estimating category breakdown. */
837
+ getContextSnapshot(): {
838
+ limit_tokens: number | null;
839
+ used_tokens: number | null;
840
+ input_tokens: number | null;
841
+ left_percent: number | null;
842
+ basis: "provider_usage" | "estimate" | "none";
843
+ };
813
844
  /** Context window usage with an estimated per-category breakdown. */
814
845
  getContextUsage(): ContextUsage;
815
846
  getHistoryMessages(): BaseMessage[];
@@ -1297,4 +1328,4 @@ declare class TaskComplete extends Error {
1297
1328
  constructor(finalMessage?: string);
1298
1329
  }
1299
1330
 
1300
- export { ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_MODELS, Agent, type AgentEventRecord, type AgentOptions, type AgentRunOptions, type AgentServices, type AgentSession, type ApprovalReviewFailureRecord, type BaseChatModel, type BaseMessage, ChatAnthropic, ChatDeepSeek, ChatGoogle, type ChatInvokeContext, type ChatInvokeInput, type ChatInvokeUsage, ChatMoonshot, ChatOpenAI, ChatOpenRouter, ChatResponses, type ChatStreamDelta, type ChatStreamDeltaSink, ChatXai, ChatZai, type ConversationApprovalContext, type ConversationApprovalProvenance, type ConversationApprovalScope, type ConversationInputOrigin, type ConversationMessage, type ConversationSearchResult, DEEPSEEK_DEFAULT_MODEL, DEEPSEEK_MODELS, DEFAULT_MODEL_REGISTRY, type DependencyKey, GOOGLE_DEFAULT_MODEL, GOOGLE_MODELS, type ImageTokenEstimate, type ImageTokenInput, type LlmRequestRecord, type LlmResponseRecord, type LlmUsageRecord, MOONSHOT_DEFAULT_MODEL, MOONSHOT_K3_1_MODELS, MOONSHOT_MODELS, type ModelCapabilities, type ModelCost, type ModelEntry, type ModelLimits, type ModelMetadataIndex, type ModelMetadataService, type ModelRegistry, type ModelSpec, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_REASONING_EFFORT, OPENAI_MODELS, type PolledMessage, type ProviderFailure, type ProviderFailureClassifier, ProviderFailureError, type ProviderFailureKind, type ResolveStorageOptions, type ResponsesInvokeOptions, type RetryDelaySource, type RunContextRecord, type RunEndRecord, type RunErrorRecord, type RunEventStoreFactory, type RunEventStoreInit, type RunStartRecord, type RunStatusRecord, type SessionHeader, type SessionRecord, type SessionState, type SessionStateStore, type SessionStateSummary, type SessionStore, type StorageLayout, type StoragePathService, type StoragePaths, type StringifyContentMode, type StringifyContentOptions, TaskComplete, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolExecution, type ToolOutputCacheConfig, type ToolOutputCacheReadOptions, type ToolOutputCacheRecord, type ToolOutputCacheSearchOptions, ToolOutputCacheService, type ToolOutputCacheStore, type ToolOutputRecord, type ToolOutputRef, type ToolPermissionClarificationField, type ToolPermissionDecision, ToolPermissionDenied, type ToolPermissionHook, type ToolResult, XAI_DEFAULT_MODEL, XAI_DEFAULT_REASONING_EFFORT, XAI_MODELS, ZAI_DEFAULT_MODEL, ZAI_MODELS, ZAI_REASONING_EFFORT_MODELS, applyModelMetadata, createModelRegistry, createProviderResponseError, defineTool, getDefaultSystemPromptPath, isProviderFailureError, isUsableModelSpec, listModels, prepareToolInvocation, registerModels, resolveDeepSeekEffort, resolveModel, resolveProviderModelId, stringifyContent, stringifyContentParts, supportsFastMode, toolPermissionClarificationFields };
1331
+ export { ANTHROPIC_DEFAULT_MODEL, ANTHROPIC_MODELS, Agent, type AgentEventRecord, type AgentOptions, type AgentRunOptions, type AgentServices, type AgentSession, type ApprovalReviewFailureRecord, type BaseChatModel, type BaseMessage, ChatAnthropic, ChatDeepSeek, ChatGoogle, type ChatInvokeContext, type ChatInvokeInput, type ChatInvokeUsage, ChatMoonshot, ChatOpenAI, ChatOpenRouter, ChatResponses, type ChatStreamDelta, type ChatStreamDeltaSink, ChatXai, ChatZai, type ConversationApprovalContext, type ConversationApprovalProvenance, type ConversationApprovalScope, type ConversationInputOrigin, type ConversationMessage, type ConversationSearchResult, DEEPSEEK_DEFAULT_MODEL, DEEPSEEK_MODELS, DEFAULT_MODEL_REGISTRY, type DependencyKey, GOOGLE_DEFAULT_MODEL, GOOGLE_MODELS, type ImageTokenEstimate, type ImageTokenInput, type LlmRequestRecord, type LlmResponseRecord, type LlmUsageRecord, MOONSHOT_DEFAULT_MODEL, MOONSHOT_K3_1_MODELS, MOONSHOT_MODELS, type ModelCapabilities, type ModelCost, type ModelEntry, type ModelLimits, type ModelMetadataIndex, type ModelMetadataService, type ModelRegistry, type ModelSpec, OPENAI_DEFAULT_MODEL, OPENAI_DEFAULT_REASONING_EFFORT, OPENAI_MODELS, type PolledMessage, type ProviderFailure, type ProviderFailureClassifier, ProviderFailureError, type ProviderFailureKind, type ResolveStorageOptions, type ResponsesInvokeOptions, type RetryDelaySource, type RunContextRecord, type RunEndRecord, type RunErrorRecord, type RunEventStoreFactory, type RunEventStoreInit, type RunStartRecord, type RunStatusRecord, type SessionHeader, type SessionRecord, type SessionState, type SessionStateStore, type SessionStateSummary, type SessionStore, type StorageLayout, type StoragePathService, type StoragePaths, type StringifyContentMode, type StringifyContentOptions, TaskComplete, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolExecution, type ToolOutputCacheConfig, type ToolOutputCacheReadOptions, type ToolOutputCacheRecord, type ToolOutputCacheSearchOptions, ToolOutputCacheService, type ToolOutputCacheStore, type ToolOutputRecord, type ToolOutputRef, type ToolPermissionClarificationField, type ToolPermissionDecision, ToolPermissionDenied, type ToolPermissionHook, type ToolResult, XAI_DEFAULT_MODEL, XAI_DEFAULT_REASONING_EFFORT, XAI_MODELS, ZAI_DEFAULT_MODEL, ZAI_MODELS, ZAI_REASONING_EFFORT_MODELS, applyModelMetadata, createModelRegistry, createProviderResponseError, defineTool, estimateUsageCostUsd, getDefaultSystemPromptPath, isProviderFailureError, isUsableModelSpec, listModels, prepareToolInvocation, registerModels, resolveDeepSeekEffort, resolveModel, resolveProviderModelId, stringifyContent, stringifyContentParts, supportsFastMode, toolPermissionClarificationFields };
package/dist/index.js CHANGED
@@ -1167,6 +1167,22 @@ var MOONSHOT_MODELS = [
1167
1167
  ];
1168
1168
 
1169
1169
  // src/models/registry.ts
1170
+ var isNonNegativeFinite = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
1171
+ function estimateUsageCostUsd(usage, cost) {
1172
+ if (!usage || !cost || !isNonNegativeFinite(cost.input) || !isNonNegativeFinite(cost.output)) {
1173
+ return null;
1174
+ }
1175
+ const cacheRead = Math.max(0, usage.input_cached_tokens ?? 0);
1176
+ const cacheWrite = Math.max(0, usage.input_cache_creation_tokens ?? 0);
1177
+ const uncachedInput = Math.max(0, usage.input_tokens - cacheRead - cacheWrite);
1178
+ const reasoningTokens = Math.max(0, usage.output_reasoning_tokens ?? 0);
1179
+ const nonReasoningOutput = Math.max(0, usage.output_tokens - reasoningTokens);
1180
+ const cacheReadRate = isNonNegativeFinite(cost.cacheRead) ? cost.cacheRead : cost.input;
1181
+ const cacheWriteRate = isNonNegativeFinite(cost.cacheWrite) ? cost.cacheWrite : cost.input;
1182
+ const reasoningRate = isNonNegativeFinite(cost.reasoning) ? cost.reasoning : cost.output;
1183
+ const totalUsd = (uncachedInput * cost.input + cacheRead * cacheReadRate + cacheWrite * cacheWriteRate + nonReasoningOutput * cost.output + reasoningTokens * reasoningRate) / 1e6;
1184
+ return Number.isFinite(totalUsd) ? totalUsd : null;
1185
+ }
1170
1186
  function createModelRegistry(specs) {
1171
1187
  const registry2 = {
1172
1188
  modelsById: {},
@@ -1261,6 +1277,7 @@ function applyModelMetadata(registry2, index) {
1261
1277
  contextWindow: spec.contextWindow ?? entry.limits?.contextWindow,
1262
1278
  maxInputTokens: spec.maxInputTokens ?? entry.limits?.inputTokens,
1263
1279
  maxOutputTokens: spec.maxOutputTokens ?? entry.limits?.outputTokens,
1280
+ cost: spec.cost ?? entry.cost,
1264
1281
  supportsFast: spec.supportsFast ?? entry.capabilities?.supportsFast,
1265
1282
  supportsVision: spec.supportsVision ?? entry.capabilities?.supportsVision,
1266
1283
  supportsTools: spec.supportsTools ?? entry.capabilities?.supportsTools
@@ -2001,43 +2018,86 @@ var TokenUsageService = class {
2001
2018
  total_tokens: 0,
2002
2019
  total_input_tokens: 0,
2003
2020
  total_output_tokens: 0,
2021
+ total_output_reasoning_tokens: 0,
2004
2022
  total_cached_input_tokens: 0,
2005
2023
  total_cache_creation_tokens: 0,
2006
- total_cost_usd: 0,
2024
+ total_input_image_tokens: 0,
2025
+ cache_hit_calls: 0,
2026
+ cache_miss_calls: 0,
2027
+ cache_unknown_calls: 0,
2028
+ total_cost_usd: null,
2007
2029
  by_model: {}
2008
2030
  };
2009
2031
  }
2010
2032
  config;
2011
2033
  usageSummary;
2012
2034
  lastUsage = null;
2013
- updateUsageSummary(usage) {
2035
+ updateUsageSummary(usage, costUsd) {
2014
2036
  this.lastUsage = usage ?? null;
2015
2037
  if (!this.config.enabled || !usage) {
2016
2038
  return;
2017
2039
  }
2040
+ const hasCacheMetric = typeof usage.input_cached_tokens === "number";
2041
+ const cached = hasCacheMetric ? usage.input_cached_tokens ?? 0 : 0;
2042
+ const cacheCreation = usage.input_cache_creation_tokens ?? 0;
2043
+ const reasoning = usage.output_reasoning_tokens ?? 0;
2044
+ const image = usage.input_image_tokens ?? 0;
2045
+ const cacheState = hasCacheMetric ? cached > 0 ? "hit" : "miss" : "unknown";
2046
+ const validCost = typeof costUsd === "number" && Number.isFinite(costUsd) && costUsd >= 0 ? costUsd : null;
2018
2047
  this.usageSummary.total_calls++;
2019
2048
  this.usageSummary.total_tokens += usage.total_tokens;
2020
2049
  this.usageSummary.total_input_tokens += usage.input_tokens;
2021
2050
  this.usageSummary.total_output_tokens += usage.output_tokens;
2022
- this.usageSummary.total_cached_input_tokens += usage.input_cached_tokens ?? 0;
2023
- this.usageSummary.total_cache_creation_tokens += usage.input_cache_creation_tokens ?? 0;
2051
+ this.usageSummary.total_output_reasoning_tokens += reasoning;
2052
+ this.usageSummary.total_cached_input_tokens += cached;
2053
+ this.usageSummary.total_cache_creation_tokens += cacheCreation;
2054
+ this.usageSummary.total_input_image_tokens += image;
2055
+ if (cacheState === "hit") {
2056
+ this.usageSummary.cache_hit_calls++;
2057
+ } else if (cacheState === "miss") {
2058
+ this.usageSummary.cache_miss_calls++;
2059
+ } else {
2060
+ this.usageSummary.cache_unknown_calls++;
2061
+ }
2062
+ if (validCost !== null) {
2063
+ this.usageSummary.total_cost_usd = (this.usageSummary.total_cost_usd ?? 0) + validCost;
2064
+ }
2024
2065
  const model = usage.model ?? "unknown";
2025
- if (!this.usageSummary.by_model[model]) {
2066
+ const bucket = this.usageSummary.by_model[model];
2067
+ if (!bucket) {
2026
2068
  this.usageSummary.by_model[model] = {
2027
2069
  calls: 1,
2028
2070
  input_tokens: usage.input_tokens,
2029
2071
  output_tokens: usage.output_tokens,
2030
- cached_input_tokens: usage.input_cached_tokens ?? 0,
2031
- cache_creation_tokens: usage.input_cache_creation_tokens ?? 0,
2032
- total_tokens: usage.total_tokens
2072
+ output_reasoning_tokens: reasoning,
2073
+ cached_input_tokens: cached,
2074
+ cache_creation_tokens: cacheCreation,
2075
+ input_image_tokens: image,
2076
+ cache_hit_calls: cacheState === "hit" ? 1 : 0,
2077
+ cache_miss_calls: cacheState === "miss" ? 1 : 0,
2078
+ cache_unknown_calls: cacheState === "unknown" ? 1 : 0,
2079
+ total_tokens: usage.total_tokens,
2080
+ cost_usd: validCost
2033
2081
  };
2034
2082
  } else {
2035
- this.usageSummary.by_model[model].calls++;
2036
- this.usageSummary.by_model[model].input_tokens += usage.input_tokens;
2037
- this.usageSummary.by_model[model].output_tokens += usage.output_tokens;
2038
- this.usageSummary.by_model[model].cached_input_tokens += usage.input_cached_tokens ?? 0;
2039
- this.usageSummary.by_model[model].cache_creation_tokens += usage.input_cache_creation_tokens ?? 0;
2040
- this.usageSummary.by_model[model].total_tokens += usage.total_tokens;
2083
+ bucket.calls++;
2084
+ bucket.input_tokens += usage.input_tokens;
2085
+ bucket.output_tokens += usage.output_tokens;
2086
+ bucket.output_reasoning_tokens += reasoning;
2087
+ bucket.cached_input_tokens += cached;
2088
+ bucket.cache_creation_tokens += cacheCreation;
2089
+ bucket.input_image_tokens += image;
2090
+ if (cacheState === "hit") {
2091
+ bucket.cache_hit_calls++;
2092
+ } else if (cacheState === "miss") {
2093
+ bucket.cache_miss_calls++;
2094
+ } else {
2095
+ bucket.cache_unknown_calls++;
2096
+ }
2097
+ bucket.total_tokens += usage.total_tokens;
2098
+ if (validCost !== null) {
2099
+ bucket.cost_usd = (bucket.cost_usd ?? 0) + validCost;
2100
+ }
2041
2101
  }
2042
2102
  }
2043
2103
  getUsageSummary() {
@@ -2624,17 +2684,31 @@ var executeToolCall = async ({
2624
2684
  }
2625
2685
  };
2626
2686
  }
2687
+ let approvalWaitMs;
2627
2688
  if (canExecuteTool) {
2689
+ const approvalStartedAt = performance.now();
2628
2690
  try {
2629
2691
  const decision = await canExecuteTool(
2630
2692
  toolCall,
2631
2693
  toolCall.function.arguments,
2632
2694
  createToolContext(signal)
2633
2695
  );
2696
+ approvalWaitMs = Math.max(
2697
+ 0,
2698
+ Math.round(performance.now() - approvalStartedAt)
2699
+ );
2634
2700
  if (decision.decision === "deny") {
2635
- return permissionDeniedResult(toolCall, decision);
2701
+ return {
2702
+ ...permissionDeniedResult(toolCall, decision),
2703
+ approvalWaitMs,
2704
+ execDurationMs: 0
2705
+ };
2636
2706
  }
2637
2707
  } catch (error) {
2708
+ approvalWaitMs = Math.max(
2709
+ 0,
2710
+ Math.round(performance.now() - approvalStartedAt)
2711
+ );
2638
2712
  return {
2639
2713
  message: {
2640
2714
  role: "tool",
@@ -2642,15 +2716,36 @@ var executeToolCall = async ({
2642
2716
  tool_name: toolName,
2643
2717
  content: `Permission check failed: ${error instanceof Error ? error.message : String(error)}`,
2644
2718
  is_error: true
2645
- }
2719
+ },
2720
+ approvalWaitMs,
2721
+ execDurationMs: 0
2646
2722
  };
2647
2723
  }
2648
2724
  }
2725
+ let innerApprovalWaitMs = 0;
2726
+ let hasInnerApprovalWait = false;
2727
+ const execContext = createToolContext(signal);
2728
+ execContext.recordApprovalWaitMs = (durationMs) => {
2729
+ if (Number.isFinite(durationMs) && durationMs >= 0) {
2730
+ innerApprovalWaitMs += durationMs;
2731
+ hasInnerApprovalWait = true;
2732
+ }
2733
+ };
2734
+ const execStartedAt = performance.now();
2649
2735
  try {
2650
2736
  const result = await tool.executeRaw(
2651
2737
  toolCall.function.arguments,
2652
- createToolContext(signal)
2738
+ execContext
2739
+ );
2740
+ const totalWallMs = Math.max(
2741
+ 0,
2742
+ Math.round(performance.now() - execStartedAt)
2653
2743
  );
2744
+ const roundedInnerWait = hasInnerApprovalWait ? Math.max(0, Math.round(innerApprovalWaitMs)) : 0;
2745
+ if (hasInnerApprovalWait) {
2746
+ approvalWaitMs = (approvalWaitMs ?? 0) + roundedInnerWait;
2747
+ }
2748
+ const execDurationMs = hasInnerApprovalWait ? Math.max(0, totalWallMs - roundedInnerWait) : totalWallMs;
2654
2749
  const displayContent = result.display_content && typeof result.display_content === "string" ? result.display_content : tool.displayResult;
2655
2750
  return {
2656
2751
  message: {
@@ -2659,11 +2754,26 @@ var executeToolCall = async ({
2659
2754
  tool_name: toolName,
2660
2755
  content: toolResultToContent(result),
2661
2756
  ...displayContent ? { display_content: displayContent } : {}
2662
- }
2757
+ },
2758
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2759
+ execDurationMs
2663
2760
  };
2664
2761
  } catch (error) {
2762
+ const totalWallMs = Math.max(
2763
+ 0,
2764
+ Math.round(performance.now() - execStartedAt)
2765
+ );
2766
+ const roundedInnerWait = hasInnerApprovalWait ? Math.max(0, Math.round(innerApprovalWaitMs)) : 0;
2767
+ if (hasInnerApprovalWait) {
2768
+ approvalWaitMs = (approvalWaitMs ?? 0) + roundedInnerWait;
2769
+ }
2770
+ const execDurationMs = hasInnerApprovalWait ? Math.max(0, totalWallMs - roundedInnerWait) : totalWallMs;
2665
2771
  if (error instanceof ToolPermissionDenied)
2666
- return permissionDeniedResult(toolCall, error.decision);
2772
+ return {
2773
+ ...permissionDeniedResult(toolCall, error.decision),
2774
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2775
+ execDurationMs: 0
2776
+ };
2667
2777
  if (error instanceof TaskComplete) {
2668
2778
  return {
2669
2779
  message: {
@@ -2673,7 +2783,9 @@ var executeToolCall = async ({
2673
2783
  content: "Task complete"
2674
2784
  },
2675
2785
  done: true,
2676
- finalMessage: error.finalMessage
2786
+ finalMessage: error.finalMessage,
2787
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2788
+ execDurationMs
2677
2789
  };
2678
2790
  }
2679
2791
  return {
@@ -2683,7 +2795,9 @@ var executeToolCall = async ({
2683
2795
  tool_name: toolName,
2684
2796
  content: `Error: ${error instanceof Error ? error.message : String(error)}`,
2685
2797
  is_error: true
2686
- }
2798
+ },
2799
+ ...approvalWaitMs !== void 0 ? { approvalWaitMs } : {},
2800
+ execDurationMs
2687
2801
  };
2688
2802
  }
2689
2803
  };
@@ -2784,6 +2898,40 @@ var Agent = class {
2784
2898
  getLastUsage() {
2785
2899
  return this.usageService.getLastUsage();
2786
2900
  }
2901
+ getModelCost(modelName) {
2902
+ return resolveModel(
2903
+ this.modelRegistry,
2904
+ modelName ?? this.llm.model,
2905
+ this.llm.provider
2906
+ )?.cost;
2907
+ }
2908
+ /** Lightweight scalar context window snapshot without estimating category breakdown. */
2909
+ getContextSnapshot() {
2910
+ const spec = resolveModel(
2911
+ this.modelRegistry,
2912
+ this.llm.model,
2913
+ this.llm.provider
2914
+ );
2915
+ const limitTokens = spec?.maxInputTokens ?? spec?.contextWindow ?? null;
2916
+ const usage = this.usageService.getLastUsage();
2917
+ const leftPercent = this.getContextLeftPercent();
2918
+ if (!usage) {
2919
+ return {
2920
+ limit_tokens: limitTokens,
2921
+ used_tokens: null,
2922
+ input_tokens: null,
2923
+ left_percent: leftPercent,
2924
+ basis: "none"
2925
+ };
2926
+ }
2927
+ return {
2928
+ limit_tokens: limitTokens,
2929
+ used_tokens: usage.total_tokens,
2930
+ input_tokens: usage.input_tokens,
2931
+ left_percent: leftPercent,
2932
+ basis: "provider_usage"
2933
+ };
2934
+ }
2787
2935
  /** Context window usage with an estimated per-category breakdown. */
2788
2936
  getContextUsage() {
2789
2937
  return buildContextUsage({
@@ -2823,6 +2971,13 @@ var Agent = class {
2823
2971
  );
2824
2972
  if (shouldCompact && this.compactionService) {
2825
2973
  throwIfAborted(signal);
2974
+ const compactionStartedAt = this.monotonicNowMs();
2975
+ const messagesBefore = this.history.getViewMessages().length;
2976
+ const estimateHistoryTokens = () => this.getContextUsage().breakdown.reduce(
2977
+ (total, entry) => total + entry.tokens,
2978
+ 0
2979
+ );
2980
+ const estimatedTokensBefore = estimateHistoryTokens();
2826
2981
  const startEvent = {
2827
2982
  type: "compaction_start",
2828
2983
  timestamp: Date.now()
@@ -2855,10 +3010,31 @@ var Agent = class {
2855
3010
  if (compacted || options.force) {
2856
3011
  await this.llm.onHistoryCompacted?.(invokeContext);
2857
3012
  }
3013
+ const compactionDurationMs = elapsedMilliseconds(
3014
+ compactionStartedAt,
3015
+ this.monotonicNowMs
3016
+ );
3017
+ const messagesAfter = this.history.getViewMessages().length;
3018
+ const estimatedTokensAfter = estimateHistoryTokens();
2858
3019
  const completeEvent = {
2859
3020
  type: "compaction_complete",
2860
3021
  timestamp: Date.now(),
2861
- compacted
3022
+ compacted,
3023
+ duration_ms: compactionDurationMs,
3024
+ messages_before: messagesBefore,
3025
+ messages_after: messagesAfter,
3026
+ ...typeof estimatedTokensBefore === "number" && Number.isFinite(estimatedTokensBefore) ? {
3027
+ estimated_tokens_before: Math.max(
3028
+ 0,
3029
+ Math.round(estimatedTokensBefore)
3030
+ )
3031
+ } : {},
3032
+ ...typeof estimatedTokensAfter === "number" && Number.isFinite(estimatedTokensAfter) ? {
3033
+ estimated_tokens_after: Math.max(
3034
+ 0,
3035
+ Math.round(estimatedTokensAfter)
3036
+ )
3037
+ } : {}
2862
3038
  };
2863
3039
  yield completeEvent;
2864
3040
  }
@@ -3157,8 +3333,8 @@ var Agent = class {
3157
3333
  options.streamDeltas === true,
3158
3334
  seq !== null && options.modelCallObserver ? { seq, observer: options.modelCallObserver } : void 0
3159
3335
  );
3160
- this.recordLlmResponse(session, seq, response);
3161
3336
  this.usageService.updateUsageSummary(response.usage);
3337
+ this.recordLlmResponse(session, seq, response);
3162
3338
  await this.recordOriginals(session, response.messages);
3163
3339
  this.history.commitModelResponse(response);
3164
3340
  const { reasoningTexts, assistantTexts, toolCalls, hostedToolCalls } = collectModelOutput(response.messages);
@@ -3326,7 +3502,9 @@ var Agent = class {
3326
3502
  type: "step_complete",
3327
3503
  step_id: toolCall.id,
3328
3504
  status: execution.message.is_error ? "error" : "completed",
3329
- duration_ms: durationMs
3505
+ duration_ms: durationMs,
3506
+ ...execution.execDurationMs !== void 0 ? { exec_duration_ms: execution.execDurationMs } : {},
3507
+ ...execution.approvalWaitMs !== void 0 ? { approval_wait_ms: execution.approvalWaitMs } : {}
3330
3508
  };
3331
3509
  yield stepCompleteEvent;
3332
3510
  if (execution.done) {
@@ -3447,9 +3625,9 @@ var Agent = class {
3447
3625
  );
3448
3626
  if (seq !== null && observer)
3449
3627
  await observer.completed(seq, summary.usage, false);
3628
+ this.usageService.updateUsageSummary(summary.usage);
3450
3629
  this.recordLlmResponse(session, seq, summary);
3451
3630
  await this.recordOriginals(session, summary.messages);
3452
- this.usageService.updateUsageSummary(summary.usage);
3453
3631
  const { assistantTexts } = collectModelOutput(summary.messages);
3454
3632
  const finalResponse = `[Max Iterations Reached]
3455
3633
 
@@ -3473,14 +3651,10 @@ import Anthropic from "@anthropic-ai/sdk";
3473
3651
  // src/llm/provider-log.ts
3474
3652
  import { promises as fs } from "fs";
3475
3653
  import path from "path";
3476
- var envTruthy = (value) => {
3477
- if (!value) return false;
3478
- const normalized = value.trim().toLowerCase();
3479
- return normalized === "1" || normalized === "true";
3480
- };
3654
+ import { getDebugDir, hasDebugTopic } from "@codelia/logger";
3481
3655
  var getProviderLogSettings = () => {
3482
- const enabled = envTruthy(process.env.CODELIA_PROVIDER_LOG);
3483
- const dumpDirEnv = process.env.CODELIA_PROVIDER_LOG_DIR?.trim();
3656
+ const enabled = hasDebugTopic("provider-log");
3657
+ const dumpDirEnv = getDebugDir();
3484
3658
  const dumpDir = enabled ? dumpDirEnv && dumpDirEnv.length > 0 ? dumpDirEnv : path.resolve(process.cwd(), "tmp") : void 0;
3485
3659
  return { enabled, dumpDir };
3486
3660
  };
@@ -4166,13 +4340,14 @@ var toUsage = (response) => {
4166
4340
  if (!response.usage) return null;
4167
4341
  const baseInputTokens = response.usage.input_tokens ?? 0;
4168
4342
  const cacheCreateTokens = response.usage.cache_creation_input_tokens ?? 0;
4169
- const cacheReadTokens = response.usage.cache_read_input_tokens ?? 0;
4343
+ const hasCacheRead = typeof response.usage.cache_read_input_tokens === "number";
4344
+ const cacheReadTokens = hasCacheRead ? response.usage.cache_read_input_tokens ?? 0 : 0;
4170
4345
  const inputTokens = baseInputTokens + cacheCreateTokens + cacheReadTokens;
4171
4346
  const outputTokens = response.usage.output_tokens ?? 0;
4172
4347
  return {
4173
4348
  model: response.model ?? "",
4174
4349
  input_tokens: inputTokens,
4175
- input_cached_tokens: cacheReadTokens,
4350
+ ...hasCacheRead ? { input_cached_tokens: cacheReadTokens } : {},
4176
4351
  input_cache_creation_tokens: cacheCreateTokens,
4177
4352
  output_tokens: outputTokens,
4178
4353
  total_tokens: inputTokens + outputTokens
@@ -4554,6 +4729,9 @@ var ChatAnthropic = class {
4554
4729
  // src/llm/responses/chat.ts
4555
4730
  import OpenAI from "openai";
4556
4731
 
4732
+ // src/llm/openai/response-accumulator.ts
4733
+ import { hasDebugTopic as hasDebugTopic2, isDebugEnabled } from "@codelia/logger";
4734
+
4557
4735
  // src/llm/openai/codex-metadata.ts
4558
4736
  import { createHash as createHash3 } from "crypto";
4559
4737
  var record2 = (value) => value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
@@ -4914,11 +5092,6 @@ var toFunctionCallOutput = (content) => {
4914
5092
 
4915
5093
  // src/llm/openai/response-accumulator.ts
4916
5094
  var isRecord4 = (value) => typeof value === "object" && value !== null;
4917
- var envTruthy2 = (value) => {
4918
- if (!value) return false;
4919
- const normalized = value.trim().toLowerCase();
4920
- return normalized === "1" || normalized === "true";
4921
- };
4922
5095
  var loggedUnhandledResponseEventTypes = /* @__PURE__ */ new Set();
4923
5096
  var cloneValue = (value) => {
4924
5097
  if (typeof structuredClone === "function") {
@@ -5276,7 +5449,7 @@ var OpenAiResponseAccumulator = class {
5276
5449
  return content[contentIndex];
5277
5450
  }
5278
5451
  logUnhandledResponseEvent(event) {
5279
- if (!envTruthy2(process.env.CODELIA_PROVIDER_LOG) && !envTruthy2(process.env.CODELIA_DEBUG)) {
5452
+ if (!hasDebugTopic2("provider-log") && !isDebugEnabled()) {
5280
5453
  return;
5281
5454
  }
5282
5455
  if (!event.type.startsWith("response.")) {
@@ -6153,7 +6326,7 @@ function fromGoogleInteraction(value, requestedModel) {
6153
6326
  model: requestedModel,
6154
6327
  ...typeof interaction.model === "string" ? { provider_model: interaction.model } : {},
6155
6328
  input_tokens: input,
6156
- input_cached_tokens: token(usage.total_cached_tokens),
6329
+ ...typeof usage.total_cached_tokens === "number" ? { input_cached_tokens: token(usage.total_cached_tokens) } : {},
6157
6330
  output_tokens: output + thought,
6158
6331
  output_reasoning_tokens: thought,
6159
6332
  total_tokens: token(usage.total_tokens) || input + output + thought
@@ -6702,13 +6875,11 @@ var normalizeUsage = (accumulator) => {
6702
6875
  if (!usage) return null;
6703
6876
  const inputTokens = normalizeNumber(usage.prompt_tokens);
6704
6877
  const outputTokens = normalizeNumber(usage.completion_tokens);
6705
- const cachedTokens = normalizeNumber(
6706
- usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens
6707
- );
6878
+ const rawCachedTokens = usage.cached_tokens ?? usage.prompt_tokens_details?.cached_tokens;
6708
6879
  return {
6709
6880
  model: accumulator.model ?? "",
6710
6881
  input_tokens: inputTokens,
6711
- ...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
6882
+ ...typeof rawCachedTokens === "number" ? { input_cached_tokens: normalizeNumber(rawCachedTokens) } : {},
6712
6883
  output_tokens: outputTokens,
6713
6884
  total_tokens: typeof usage.total_tokens === "number" ? normalizeNumber(usage.total_tokens) : inputTokens + outputTokens
6714
6885
  };
@@ -6932,6 +7103,7 @@ var invokeOpenAiHttp = async (client, request, signal, sessionIdHeader, onEvent,
6932
7103
  };
6933
7104
 
6934
7105
  // src/llm/openai/websocket-transport.ts
7106
+ import { hasDebugTopic as hasDebugTopic3 } from "@codelia/logger";
6935
7107
  import { ResponsesWS } from "openai/resources/responses/ws";
6936
7108
  var WS_CONNECT_TIMEOUT_MS = 2e4;
6937
7109
  var WS_RESPONSE_IDLE_TIMEOUT_MS = 3e5;
@@ -6955,12 +7127,7 @@ var resolveTimeoutMs = (value, fallbackMs) => {
6955
7127
  }
6956
7128
  return Math.floor(value);
6957
7129
  };
6958
- var envTruthy3 = (value) => {
6959
- if (!value) return false;
6960
- const normalized = value.trim().toLowerCase();
6961
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
6962
- };
6963
- var WS_EVENT_TRACE_ENABLED = envTruthy3(process.env.CODELIA_DEBUG);
7130
+ var WS_EVENT_TRACE_ENABLED = hasDebugTopic3("ws");
6964
7131
  var WS_EVENT_TRACE_PROGRESS_LOG_INTERVAL_MS = 5e3;
6965
7132
  var wsEventTraceStateBySource = /* @__PURE__ */ new Map();
6966
7133
  var getWsEventTraceState = (source) => {
@@ -9698,13 +9865,11 @@ var normalizeZaiUsage = (accumulator) => {
9698
9865
  const inputTokens = normalizeNumber2(usage.prompt_tokens);
9699
9866
  const outputTokens = normalizeNumber2(usage.completion_tokens);
9700
9867
  const totalTokens = typeof usage.total_tokens === "number" ? normalizeNumber2(usage.total_tokens) : inputTokens + outputTokens;
9701
- const cachedTokens = normalizeNumber2(
9702
- usage.prompt_tokens_details?.cached_tokens
9703
- );
9868
+ const rawCachedTokens = usage.prompt_tokens_details?.cached_tokens;
9704
9869
  return {
9705
9870
  model: accumulator.model ?? "",
9706
9871
  input_tokens: inputTokens,
9707
- ...cachedTokens > 0 ? { input_cached_tokens: cachedTokens } : {},
9872
+ ...typeof rawCachedTokens === "number" ? { input_cached_tokens: normalizeNumber2(rawCachedTokens) } : {},
9708
9873
  output_tokens: outputTokens,
9709
9874
  total_tokens: totalTokens
9710
9875
  };
@@ -10182,6 +10347,7 @@ export {
10182
10347
  createModelRegistry,
10183
10348
  createProviderResponseError,
10184
10349
  defineTool,
10350
+ estimateUsageCostUsd,
10185
10351
  getDefaultSystemPromptPath,
10186
10352
  isProviderFailureError,
10187
10353
  isUsableModelSpec,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@codelia/core",
3
- "version": "0.1.91",
3
+ "version": "0.1.93",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "files": [
@@ -26,8 +26,9 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@anthropic-ai/sdk": "^0.110.0",
29
- "@codelia/config": "0.1.91",
30
- "@codelia/shared-types": "0.1.91",
29
+ "@codelia/config": "0.1.93",
30
+ "@codelia/logger": "0.1.93",
31
+ "@codelia/shared-types": "0.1.93",
31
32
  "@google/genai": "2.32.0",
32
33
  "image-size": "^2.0.2",
33
34
  "json-schema": "^0.4.0",
package/prompts/AGENTS.md DELETED
@@ -1,16 +0,0 @@
1
- # prompts
2
-
3
- ## Scope
4
-
5
- - `system.md` is the shared default system prompt for Codelia.
6
- - Keep this prompt focused on cross-task, cross-repo operating rules.
7
-
8
- ## Structure
9
-
10
- - Organize the prompt by stable mental model: mission, priorities, workflow, tool use, safety, verification, task modes, and communication.
11
- - Put benchmark-specific or harness-specific behavior in adapters, not here.
12
- - Keep tool parameter details, limits, and edge cases in tool descriptions or runtime docs when possible.
13
- - Keep external-access guidance tool-agnostic and high-level: describe when facts, state, or operations depend on resources outside the workspace or local environment, but do not make external access a blanket substitute for local inspection and verification.
14
- - Avoid duplicating the same rule across multiple sections unless repetition is necessary for safety.
15
- - Keep the shared prompt collaborative and action-oriented: prefer early concrete exploration, and let stronger verification guidance dominate later in the task.
16
- - Keep subagent usage policy in the shared system prompt: interactive delegation requires explicit user authorization for the current task; unattended execution alone is not authorization. Keep parameter validation and limits in tool descriptions.