@linnlabs/linnkit 0.10.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/CHANGELOG.md +156 -1
  2. package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
  3. package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
  4. package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
  5. package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
  6. package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
  7. package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
  8. package/dist/cli.cjs +565 -194
  9. package/dist/cli.cjs.map +1 -1
  10. package/dist/cli.js +565 -194
  11. package/dist/cli.js.map +1 -1
  12. package/dist/context-manager.cjs +590 -26
  13. package/dist/context-manager.cjs.map +1 -1
  14. package/dist/context-manager.d.cts +84 -7
  15. package/dist/context-manager.d.ts +84 -7
  16. package/dist/context-manager.js +590 -26
  17. package/dist/context-manager.js.map +1 -1
  18. package/dist/{context-trace-BHKDS-eq.d.cts → context-trace-DrtvKac4.d.cts} +36 -3
  19. package/dist/{context-trace-CHbqHmyE.d.ts → context-trace-WV1HAZeB.d.ts} +36 -3
  20. package/dist/contracts.cjs +222 -1
  21. package/dist/contracts.cjs.map +1 -1
  22. package/dist/contracts.d.cts +5 -3
  23. package/dist/contracts.d.ts +5 -3
  24. package/dist/contracts.js +202 -2
  25. package/dist/contracts.js.map +1 -1
  26. package/dist/{defaultGraphExecutor-C2E59v_R.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +35 -7
  27. package/dist/{defaultGraphExecutor-B29_qTHy.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +35 -7
  28. package/dist/{index-BAaUP9yU.d.cts → index-BeQO0rx2.d.cts} +328 -263
  29. package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
  30. package/dist/{index-CKQzzZ5Y.d.cts → index-Crl5E4eF.d.cts} +26 -3
  31. package/dist/{index-C0DAjsdX.d.ts → index-DWGKvssS.d.ts} +2 -2
  32. package/dist/{index-D0mKxTR5.d.ts → index-X5lYU1Lj.d.ts} +26 -3
  33. package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
  34. package/dist/{index-BaVpVNi2.d.ts → index-wOZD-p2-.d.ts} +328 -263
  35. package/dist/{index-BnYCS8Zg.d.cts → index-wXVAHZ0D.d.cts} +2 -2
  36. package/dist/index.cjs +893 -312
  37. package/dist/index.cjs.map +1 -1
  38. package/dist/index.d.cts +17 -14
  39. package/dist/index.d.ts +17 -14
  40. package/dist/index.js +893 -312
  41. package/dist/index.js.map +1 -1
  42. package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
  43. package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
  44. package/dist/{ports-s-tSp3sB.d.cts → ports-Dugizzje.d.cts} +4 -0
  45. package/dist/{ports-DpPTFhSd.d.ts → ports-fhp84x_C.d.ts} +4 -0
  46. package/dist/ports.d.cts +8 -5
  47. package/dist/ports.d.ts +8 -5
  48. package/dist/quickstart.cjs +564 -193
  49. package/dist/quickstart.cjs.map +1 -1
  50. package/dist/quickstart.d.cts +9 -8
  51. package/dist/quickstart.d.ts +9 -8
  52. package/dist/quickstart.js +564 -193
  53. package/dist/quickstart.js.map +1 -1
  54. package/dist/{runAgent-C6F-399C.d.ts → runAgent-BmMSju8I.d.ts} +4 -4
  55. package/dist/{runAgent-ilEj66Ik.d.cts → runAgent-CKgcRSRH.d.cts} +4 -4
  56. package/dist/{runHandle-BNOqS-Bl.d.cts → runHandle-DH4VmQx6.d.cts} +4 -2
  57. package/dist/{runHandle-BdLXOFqF.d.ts → runHandle-o3p06Nva.d.ts} +4 -2
  58. package/dist/runtime-kernel/events.cjs +201 -1
  59. package/dist/runtime-kernel/events.cjs.map +1 -1
  60. package/dist/runtime-kernel/events.d.cts +3 -3
  61. package/dist/runtime-kernel/events.d.ts +3 -3
  62. package/dist/runtime-kernel/events.js +201 -1
  63. package/dist/runtime-kernel/events.js.map +1 -1
  64. package/dist/runtime-kernel.cjs +824 -264
  65. package/dist/runtime-kernel.cjs.map +1 -1
  66. package/dist/runtime-kernel.d.cts +14 -12
  67. package/dist/runtime-kernel.d.ts +14 -12
  68. package/dist/runtime-kernel.js +816 -265
  69. package/dist/runtime-kernel.js.map +1 -1
  70. package/dist/testkit.cjs +847 -264
  71. package/dist/testkit.cjs.map +1 -1
  72. package/dist/testkit.d.cts +14 -12
  73. package/dist/testkit.d.ts +14 -12
  74. package/dist/testkit.js +847 -264
  75. package/dist/testkit.js.map +1 -1
  76. package/dist/{agentSpec-Du4Iye0q.d.cts → token-accounting-CwpSPg4y.d.cts} +1265 -1
  77. package/dist/{agentSpec-Du4Iye0q.d.ts → token-accounting-CwpSPg4y.d.ts} +1265 -1
  78. package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
  79. package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
  80. package/dist/token-counter-CFfP8PQb.d.cts +26 -0
  81. package/dist/token-counter-SFyyTeaG.d.ts +26 -0
  82. package/dist/token-usage-CqwT7-5K.d.cts +133 -0
  83. package/dist/token-usage-CqwT7-5K.d.ts +133 -0
  84. package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
  85. package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
  86. package/docs/README.md +1 -1
  87. package/docs/integration/README.md +2 -2
  88. package/docs/integration/agent-registration-guide.md +2 -0
  89. package/docs/integration/context-engineering.md +53 -1
  90. package/docs/integration/context-fences.md +12 -0
  91. package/package.json +2 -2
@@ -141,6 +141,12 @@ zod.z.object({
141
141
  args: zod.z.record(zod.z.unknown()).optional(),
142
142
  tool_call_id: zod.z.string()
143
143
  });
144
+ var ObservationTruncationMeta = zod.z.object({
145
+ originalChars: zod.z.number().int().nonnegative(),
146
+ previewChars: zod.z.number().int().nonnegative(),
147
+ originalLines: zod.z.number().int().nonnegative().optional(),
148
+ previewLines: zod.z.number().int().nonnegative().optional()
149
+ });
144
150
  var ImageInfoMeta = zod.z.object({
145
151
  url: zod.z.string().optional(),
146
152
  width: zod.z.number().int().positive().optional(),
@@ -172,6 +178,7 @@ var PersistentMetadata = zod.z.object({
172
178
  tool_name: zod.z.string().optional(),
173
179
  args: zod.z.record(zod.z.unknown()).optional(),
174
180
  tool_call_id: zod.z.string().optional(),
181
+ observationTruncation: ObservationTruncationMeta.optional(),
175
182
  raw_output: zod.z.string().optional(),
176
183
  image_info: ImageInfoMeta.optional(),
177
184
  taskType: zod.z.string().optional(),
@@ -318,7 +325,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
318
325
  var AgentSpecTokenEstimationPolicy = zod.z.object({
319
326
  encoding: zod.z.string().min(1).optional(),
320
327
  avgCharsPerToken: zod.z.number().positive().optional(),
321
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
328
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
329
+ calibration: zod.z.object({
330
+ enabled: zod.z.boolean().optional(),
331
+ minSamples: zod.z.number().int().positive().optional(),
332
+ minCoefficient: zod.z.number().positive().optional(),
333
+ maxCoefficient: zod.z.number().positive().optional()
334
+ }).optional(),
335
+ remoteCount: zod.z.object({
336
+ enabled: zod.z.boolean().optional(),
337
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
338
+ }).optional()
322
339
  });
323
340
  var AgentSpecSystemReminderTrigger = zod.z.object({
324
341
  kind: zod.z.string().min(1),
@@ -1016,6 +1033,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1016
1033
  error,
1017
1034
  ...options
1018
1035
  });
1036
+ var TokenCountSource = zod.z.enum([
1037
+ "local-estimate",
1038
+ "provider-preflight-count",
1039
+ "provider-response-usage",
1040
+ "host-supplied",
1041
+ "test-fixture"
1042
+ ]);
1043
+ var TokenCountConfidence = zod.z.enum([
1044
+ "estimate",
1045
+ "provider-estimate",
1046
+ "actual"
1047
+ ]);
1048
+ var TokenRouteCapabilities = zod.z.object({
1049
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1050
+ supportsResponseUsage: zod.z.boolean().optional(),
1051
+ supportsImageInput: zod.z.boolean().optional(),
1052
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1053
+ supportsReasoningTokens: zod.z.boolean().optional()
1054
+ });
1055
+ var TokenRoute = zod.z.object({
1056
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1057
+ baseURL: zod.z.string().optional().describe("\u4E2D\u8F6C\u5E73\u53F0\u6216\u79C1\u6709 endpoint\uFF1B\u7528\u4E8E\u533A\u5206\u540C\u540D\u6A21\u578B\u7684\u4E0D\u540C route"),
1058
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1059
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1060
+ capabilities: TokenRouteCapabilities.optional()
1061
+ });
1062
+ var tokenCount = zod.z.number().int().nonnegative();
1063
+ var CanonicalLlmUsage = zod.z.object({
1064
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1065
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1066
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1067
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1068
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1069
+ totalTokens: tokenCount.optional().describe("provider \u62A5\u544A\u7684\u603B\u91CF\uFF1B\u53EF\u7F3A\u5931\uFF0C\u4E14\u4E0D\u4FDD\u8BC1\u7B49\u4E8E\u5404\u9879\u4E4B\u548C"),
1070
+ source: TokenCountSource,
1071
+ confidence: TokenCountConfidence,
1072
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1073
+ });
1074
+ var tokenCount2 = zod.z.number().int().nonnegative();
1075
+ var tokenPrice = zod.z.number().finite().nonnegative();
1076
+ zod.z.enum([
1077
+ "llm-usage",
1078
+ "context-component"
1079
+ ]);
1080
+ var ContextTokenComponentKind = zod.z.enum([
1081
+ "system",
1082
+ "user",
1083
+ "assistant",
1084
+ "tool",
1085
+ "context-injection",
1086
+ "history-summary",
1087
+ "working-memory",
1088
+ "fence",
1089
+ "system-reminder",
1090
+ "other"
1091
+ ]);
1092
+ var TokenUsageTotals = zod.z.object({
1093
+ inputTokens: tokenCount2,
1094
+ outputTokens: tokenCount2,
1095
+ reasoningTokens: tokenCount2.optional(),
1096
+ cacheReadTokens: tokenCount2.optional(),
1097
+ cacheWriteTokens: tokenCount2.optional(),
1098
+ totalTokens: tokenCount2.optional(),
1099
+ usageCount: zod.z.number().int().nonnegative()
1100
+ });
1101
+ var ContextTokenComponent = zod.z.object({
1102
+ componentId: zod.z.string().min(1),
1103
+ kind: ContextTokenComponentKind,
1104
+ tokens: tokenCount2,
1105
+ source: TokenCountSource,
1106
+ confidence: TokenCountConfidence,
1107
+ label: zod.z.string().optional(),
1108
+ messageId: zod.z.string().optional(),
1109
+ role: zod.z.string().optional(),
1110
+ action: zod.z.string().optional(),
1111
+ kept: zod.z.boolean().optional(),
1112
+ truncatedAtExecution: zod.z.boolean().optional(),
1113
+ originalTokensEstimate: tokenCount2.optional(),
1114
+ droppedTokensEstimate: tokenCount2.optional()
1115
+ });
1116
+ var TokenLedgerEntryBase = zod.z.object({
1117
+ id: zod.z.string().min(1),
1118
+ runId: zod.z.string().optional(),
1119
+ parentRunId: zod.z.string().optional(),
1120
+ conversationId: zod.z.string().optional(),
1121
+ turnId: zod.z.string().optional(),
1122
+ stepId: zod.z.string().optional(),
1123
+ route: TokenRoute.optional(),
1124
+ createdAt: zod.z.number().int().nonnegative().optional()
1125
+ });
1126
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1127
+ kind: zod.z.literal("llm-usage"),
1128
+ modelId: zod.z.string().optional(),
1129
+ usage: CanonicalLlmUsage
1130
+ });
1131
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1132
+ kind: zod.z.literal("context-component"),
1133
+ components: zod.z.array(ContextTokenComponent),
1134
+ totalTokens: tokenCount2
1135
+ });
1136
+ zod.z.discriminatedUnion("kind", [
1137
+ LlmUsageTokenLedgerEntry,
1138
+ ContextComponentTokenLedgerEntry
1139
+ ]);
1140
+ var TokenLedgerAggregate = zod.z.object({
1141
+ llmUsage: TokenUsageTotals.optional(),
1142
+ contextTokens: tokenCount2,
1143
+ entryCount: zod.z.number().int().nonnegative(),
1144
+ llmCallCount: zod.z.number().int().nonnegative(),
1145
+ contextComponentCount: zod.z.number().int().nonnegative()
1146
+ });
1147
+ zod.z.object({
1148
+ /**
1149
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1150
+ */
1151
+ own: TokenLedgerAggregate,
1152
+ children: TokenLedgerAggregate.optional()
1153
+ });
1154
+ var TokenCostComponent = zod.z.enum([
1155
+ "input",
1156
+ "output",
1157
+ "reasoning",
1158
+ "cacheRead",
1159
+ "cacheWrite"
1160
+ ]);
1161
+ zod.z.object({
1162
+ currency: zod.z.string().min(1),
1163
+ unit: zod.z.literal("per_1m_tokens"),
1164
+ input: tokenPrice.optional(),
1165
+ output: tokenPrice.optional(),
1166
+ reasoning: tokenPrice.optional(),
1167
+ cacheRead: tokenPrice.optional(),
1168
+ cacheWrite: tokenPrice.optional()
1169
+ });
1170
+ zod.z.object({
1171
+ status: zod.z.enum(["computed", "unknown"]),
1172
+ currency: zod.z.string().optional(),
1173
+ inputCost: tokenPrice.optional(),
1174
+ outputCost: tokenPrice.optional(),
1175
+ reasoningCost: tokenPrice.optional(),
1176
+ cacheReadCost: tokenPrice.optional(),
1177
+ cacheWriteCost: tokenPrice.optional(),
1178
+ totalCost: tokenPrice.optional(),
1179
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1180
+ });
1181
+ var tokenCount3 = zod.z.number().int().nonnegative();
1182
+ var actualCalibrationSource = zod.z.enum([
1183
+ "provider-response-usage",
1184
+ "host-supplied",
1185
+ "test-fixture"
1186
+ ]);
1187
+ zod.z.object({
1188
+ route: TokenRoute,
1189
+ localEstimateTokens: tokenCount3,
1190
+ actualInputTokens: tokenCount3,
1191
+ source: actualCalibrationSource,
1192
+ confidence: zod.z.literal("actual"),
1193
+ observedAt: zod.z.number().int().nonnegative().optional(),
1194
+ runId: zod.z.string().optional(),
1195
+ ledgerEntryId: zod.z.string().optional()
1196
+ });
1197
+ zod.z.object({
1198
+ enabled: zod.z.boolean(),
1199
+ applied: zod.z.boolean(),
1200
+ route: TokenRoute.optional(),
1201
+ sampleCount: zod.z.number().int().nonnegative(),
1202
+ coefficient: zod.z.number().positive().optional(),
1203
+ minSamples: zod.z.number().int().positive().optional(),
1204
+ minCoefficient: zod.z.number().positive().optional(),
1205
+ maxCoefficient: zod.z.number().positive().optional(),
1206
+ localEstimateTokens: tokenCount3.optional(),
1207
+ calibratedEstimateTokens: tokenCount3.optional(),
1208
+ deltaTokens: zod.z.number().int().optional(),
1209
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1210
+ });
1211
+ zod.z.object({
1212
+ route: TokenRoute.optional(),
1213
+ localEstimateTokens: tokenCount3,
1214
+ calibratedEstimateTokens: tokenCount3,
1215
+ finalTokens: tokenCount3,
1216
+ source: zod.z.literal("local-estimate"),
1217
+ confidence: zod.z.literal("estimate")
1218
+ });
1019
1219
 
1020
1220
  // src/runtime-kernel/graph-engine/engine.ts
1021
1221
  var logger = new Logger("GraphExecutor");
@@ -1419,6 +1619,190 @@ var noopAudit = {
1419
1619
  flush() {
1420
1620
  }
1421
1621
  };
1622
+ var TokenCalculator = class {
1623
+ static BYTES_PER_TOKEN_LATIN = 4;
1624
+ static BYTES_PER_TOKEN_CJK = 3;
1625
+ static OVERHEAD_PER_MESSAGE = 5;
1626
+ static OVERHEAD_PER_TOOL_CALL = 10;
1627
+ static encoderCache = /* @__PURE__ */ new Map();
1628
+ static DEFAULT_ENCODING = "cl100k_base";
1629
+ static SUPPORTED_ENCODINGS = [
1630
+ "gpt2",
1631
+ "r50k_base",
1632
+ "p50k_base",
1633
+ "p50k_edit",
1634
+ "cl100k_base",
1635
+ "o200k_base"
1636
+ ];
1637
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1638
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1639
+ if (this.isSupportedEncodingName(normalized)) {
1640
+ return normalized;
1641
+ }
1642
+ if (normalized.includes("deepseek")) {
1643
+ return "cl100k_base";
1644
+ }
1645
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1646
+ return "o200k_base";
1647
+ }
1648
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1649
+ return "cl100k_base";
1650
+ }
1651
+ return this.DEFAULT_ENCODING;
1652
+ }
1653
+ static isSupportedEncodingName(value) {
1654
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1655
+ }
1656
+ static getEncoder(modelIdentifierOrEncoding) {
1657
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1658
+ const cached = this.encoderCache.get(encodingName);
1659
+ if (cached) {
1660
+ return cached;
1661
+ }
1662
+ const encoder = tiktoken.get_encoding(encodingName);
1663
+ this.encoderCache.set(encodingName, encoder);
1664
+ return encoder;
1665
+ }
1666
+ static estimateTokensRough(text, _modelIdentifier) {
1667
+ if (!text) return 0;
1668
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1669
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1670
+ const byteLength = new TextEncoder().encode(text).length;
1671
+ return Math.ceil(byteLength / ratio);
1672
+ }
1673
+ static estimateTokens(text, options = {}) {
1674
+ if (!text) return 0;
1675
+ if (options.encoding) {
1676
+ try {
1677
+ return this.estimateTokensPrecise(text, options.encoding);
1678
+ } catch {
1679
+ }
1680
+ }
1681
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1682
+ return Math.ceil(text.length / avgCharsPerToken);
1683
+ }
1684
+ static estimateTokensPrecise(text, modelIdentifier) {
1685
+ if (!text) return 0;
1686
+ const encoder = this.getEncoder(modelIdentifier);
1687
+ return encoder.encode(text).length;
1688
+ }
1689
+ static estimateMessageTokens(message, options = {}) {
1690
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1691
+ if (message.content) {
1692
+ totalTokens += this.estimateTokens(String(message.content), options);
1693
+ }
1694
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1695
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1696
+ for (const toolCall of toolCalls) {
1697
+ totalTokens += toolCallOverhead;
1698
+ const fn = toolCall["function"];
1699
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1700
+ const fnRecord = fn;
1701
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1702
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1703
+ }
1704
+ }
1705
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1706
+ if (toolCallId) {
1707
+ totalTokens += this.estimateTokens(toolCallId, options);
1708
+ }
1709
+ return totalTokens;
1710
+ }
1711
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1712
+ return this.estimateMessageTokens(message, {
1713
+ encoding: modelIdentifier,
1714
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1715
+ });
1716
+ }
1717
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1718
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1719
+ }
1720
+ static extractToolCallsForTokenEstimate(message) {
1721
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1722
+ if (Array.isArray(direct)) return direct;
1723
+ const metadata = "metadata" in message ? message.metadata : void 0;
1724
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1725
+ const metadataRecord = metadata;
1726
+ const metadataToolCalls = metadataRecord["tool_calls"];
1727
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1728
+ }
1729
+ static extractToolCallIdForTokenEstimate(message) {
1730
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1731
+ return message.tool_call_id;
1732
+ }
1733
+ const metadata = "metadata" in message ? message.metadata : void 0;
1734
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1735
+ const metadataRecord = metadata;
1736
+ const toolCallId = metadataRecord["tool_call_id"];
1737
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1738
+ }
1739
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1740
+ if (!text || maxTokens <= 0) return "";
1741
+ const encoder = this.getEncoder(modelIdentifier);
1742
+ const tokens = encoder.encode(text);
1743
+ if (tokens.length <= maxTokens) {
1744
+ return text;
1745
+ }
1746
+ let truncatedTokens;
1747
+ const ellipsis = "...";
1748
+ switch (strategy) {
1749
+ case "start":
1750
+ truncatedTokens = tokens.slice(0, maxTokens);
1751
+ return encoder.decode(truncatedTokens) + ellipsis;
1752
+ case "end":
1753
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1754
+ return ellipsis + encoder.decode(truncatedTokens);
1755
+ case "middle": {
1756
+ const half = Math.floor(maxTokens / 2);
1757
+ const head = tokens.slice(0, half);
1758
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1759
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1760
+ }
1761
+ default:
1762
+ truncatedTokens = tokens.slice(0, maxTokens);
1763
+ return encoder.decode(truncatedTokens) + ellipsis;
1764
+ }
1765
+ }
1766
+ static cleanup() {
1767
+ for (const encoder of this.encoderCache.values()) {
1768
+ encoder.free();
1769
+ }
1770
+ this.encoderCache.clear();
1771
+ }
1772
+ };
1773
+ function normalizePositiveNumber(value, fallback) {
1774
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1775
+ }
1776
+ function normalizeNonNegativeInteger(value, fallback) {
1777
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1778
+ return fallback;
1779
+ }
1780
+ return Math.max(0, Math.floor(value));
1781
+ }
1782
+
1783
+ // src/shared/defaultTokenizerPort.ts
1784
+ var DefaultTokenizerPort = class {
1785
+ constructor(config = {}) {
1786
+ this.config = config;
1787
+ }
1788
+ config;
1789
+ estimateText(text, _modelId) {
1790
+ return TokenCalculator.estimateTokens(text, {
1791
+ encoding: this.config.encoding,
1792
+ avgCharsPerToken: this.config.avgCharsPerToken
1793
+ });
1794
+ }
1795
+ estimateMessage(message, _modelId) {
1796
+ return TokenCalculator.estimateMessageTokens(message, {
1797
+ encoding: this.config.encoding,
1798
+ avgCharsPerToken: this.config.avgCharsPerToken,
1799
+ toolCallOverhead: this.config.toolCallOverhead
1800
+ });
1801
+ }
1802
+ };
1803
+ function createDefaultTokenizerPort(config = {}) {
1804
+ return new DefaultTokenizerPort(config);
1805
+ }
1422
1806
 
1423
1807
  // src/shared/ids.ts
1424
1808
  function isoRandomUUID() {
@@ -1599,237 +1983,117 @@ function resolveUsage(response) {
1599
1983
  }
1600
1984
  return response.usage;
1601
1985
  }
1602
- function resolveToolCalls(response) {
1986
+ function resolveCanonicalUsage(response) {
1603
1987
  if (!response || typeof response === "string") {
1604
- return void 0;
1605
- }
1606
- return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
1607
- }
1608
- function resolveReasoningDetails(response) {
1609
- if (!response || typeof response === "string") {
1610
- return void 0;
1611
- }
1612
- return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
1613
- }
1614
- function resolveToolNamesForAudit(ctx) {
1615
- if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
1616
- return [];
1617
- }
1618
- return ctx.toolSchemas.map((tool) => tool.function.name);
1619
- }
1620
- function recordBeforeContextManager(params) {
1621
- }
1622
- function recordAfterContextManager(params) {
1623
- }
1624
- function recordAfterContextManagerOnSystemReminderHit(params) {
1625
- }
1626
- function recordToolProtocolError(params) {
1627
- }
1628
- function recordRunTranscript(params) {
1629
- }
1630
-
1631
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
1632
- var contextAuditMiddleware = async (ctx, stage, next) => {
1633
- if (stage.id === "build_context") {
1634
- recordBeforeContextManager({
1635
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
1636
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1637
- });
1638
- }
1639
- await next();
1640
- if (stage.id !== "apply_system_reminder") {
1641
- return;
1642
- }
1643
- resolveToolNamesForAudit(ctx);
1644
- recordAfterContextManager({
1645
- mode: ctx.mode,
1646
- llmMessages: ctx.llmMessages,
1647
- contextTrace: ctx.contextTrace
1648
- });
1649
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
1650
- recordAfterContextManagerOnSystemReminderHit({
1651
- mode: ctx.mode,
1652
- llmMessages: ctx.llmMessages,
1653
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
1654
- contextTrace: ctx.contextTrace
1655
- });
1656
- }
1657
- };
1658
- var TokenCalculator = class {
1659
- static BYTES_PER_TOKEN_LATIN = 4;
1660
- static BYTES_PER_TOKEN_CJK = 3;
1661
- static OVERHEAD_PER_MESSAGE = 5;
1662
- static OVERHEAD_PER_TOOL_CALL = 10;
1663
- static encoderCache = /* @__PURE__ */ new Map();
1664
- static DEFAULT_ENCODING = "cl100k_base";
1665
- static SUPPORTED_ENCODINGS = [
1666
- "gpt2",
1667
- "r50k_base",
1668
- "p50k_base",
1669
- "p50k_edit",
1670
- "cl100k_base",
1671
- "o200k_base"
1672
- ];
1673
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1674
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1675
- if (this.isSupportedEncodingName(normalized)) {
1676
- return normalized;
1677
- }
1678
- if (normalized.includes("deepseek")) {
1679
- return "cl100k_base";
1680
- }
1681
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1682
- return "o200k_base";
1683
- }
1684
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1685
- return "cl100k_base";
1686
- }
1687
- return this.DEFAULT_ENCODING;
1688
- }
1689
- static isSupportedEncodingName(value) {
1690
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1691
- }
1692
- static getEncoder(modelIdentifierOrEncoding) {
1693
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1694
- const cached = this.encoderCache.get(encodingName);
1695
- if (cached) {
1696
- return cached;
1697
- }
1698
- const encoder = tiktoken.get_encoding(encodingName);
1699
- this.encoderCache.set(encodingName, encoder);
1700
- return encoder;
1701
- }
1702
- static estimateTokensRough(text, _modelIdentifier) {
1703
- if (!text) return 0;
1704
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1705
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1706
- const byteLength = new TextEncoder().encode(text).length;
1707
- return Math.ceil(byteLength / ratio);
1708
- }
1709
- static estimateTokens(text, options = {}) {
1710
- if (!text) return 0;
1711
- if (options.encoding) {
1712
- try {
1713
- return this.estimateTokensPrecise(text, options.encoding);
1714
- } catch {
1715
- }
1716
- }
1717
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1718
- return Math.ceil(text.length / avgCharsPerToken);
1719
- }
1720
- static estimateTokensPrecise(text, modelIdentifier) {
1721
- if (!text) return 0;
1722
- const encoder = this.getEncoder(modelIdentifier);
1723
- return encoder.encode(text).length;
1724
- }
1725
- static estimateMessageTokens(message, options = {}) {
1726
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1727
- if (message.content) {
1728
- totalTokens += this.estimateTokens(String(message.content), options);
1729
- }
1730
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1731
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1732
- for (const toolCall of toolCalls) {
1733
- totalTokens += toolCallOverhead;
1734
- const fn = toolCall["function"];
1735
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1736
- const fnRecord = fn;
1737
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1738
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1739
- }
1740
- }
1741
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1742
- if (toolCallId) {
1743
- totalTokens += this.estimateTokens(toolCallId, options);
1744
- }
1745
- return totalTokens;
1988
+ return void 0;
1746
1989
  }
1747
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1748
- return this.estimateMessageTokens(message, {
1749
- encoding: modelIdentifier,
1750
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1751
- });
1990
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
1991
+ return parsed.success ? parsed.data : void 0;
1992
+ }
1993
+ function resolveToolCalls(response) {
1994
+ if (!response || typeof response === "string") {
1995
+ return void 0;
1752
1996
  }
1753
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1754
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1997
+ return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
1998
+ }
1999
+ function resolveReasoningDetails(response) {
2000
+ if (!response || typeof response === "string") {
2001
+ return void 0;
1755
2002
  }
1756
- static extractToolCallsForTokenEstimate(message) {
1757
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1758
- if (Array.isArray(direct)) return direct;
1759
- const metadata = "metadata" in message ? message.metadata : void 0;
1760
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1761
- const metadataRecord = metadata;
1762
- const metadataToolCalls = metadataRecord["tool_calls"];
1763
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2003
+ return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2004
+ }
2005
+ function resolveToolNamesForAudit(ctx) {
2006
+ if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2007
+ return [];
1764
2008
  }
1765
- static extractToolCallIdForTokenEstimate(message) {
1766
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1767
- return message.tool_call_id;
1768
- }
1769
- const metadata = "metadata" in message ? message.metadata : void 0;
1770
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1771
- const metadataRecord = metadata;
1772
- const toolCallId = metadataRecord["tool_call_id"];
1773
- return typeof toolCallId === "string" ? toolCallId : void 0;
2009
+ return ctx.toolSchemas.map((tool) => tool.function.name);
2010
+ }
2011
+ function recordBeforeContextManager(params) {
2012
+ }
2013
+ function recordAfterContextManager(params) {
2014
+ }
2015
+ function recordAfterContextManagerOnSystemReminderHit(params) {
2016
+ }
2017
+ function recordToolProtocolError(params) {
2018
+ }
2019
+ function recordRunTranscript(params) {
2020
+ }
2021
+
2022
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2023
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2024
+ if (stage.id === "build_context") {
2025
+ recordBeforeContextManager({
2026
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2027
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2028
+ });
1774
2029
  }
1775
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1776
- if (!text || maxTokens <= 0) return "";
1777
- const encoder = this.getEncoder(modelIdentifier);
1778
- const tokens = encoder.encode(text);
1779
- if (tokens.length <= maxTokens) {
1780
- return text;
1781
- }
1782
- let truncatedTokens;
1783
- const ellipsis = "...";
1784
- switch (strategy) {
1785
- case "start":
1786
- truncatedTokens = tokens.slice(0, maxTokens);
1787
- return encoder.decode(truncatedTokens) + ellipsis;
1788
- case "end":
1789
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1790
- return ellipsis + encoder.decode(truncatedTokens);
1791
- case "middle": {
1792
- const half = Math.floor(maxTokens / 2);
1793
- const head = tokens.slice(0, half);
1794
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1795
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1796
- }
1797
- default:
1798
- truncatedTokens = tokens.slice(0, maxTokens);
1799
- return encoder.decode(truncatedTokens) + ellipsis;
1800
- }
2030
+ await next();
2031
+ if (stage.id !== "apply_system_reminder") {
2032
+ return;
1801
2033
  }
1802
- static cleanup() {
1803
- for (const encoder of this.encoderCache.values()) {
1804
- encoder.free();
1805
- }
1806
- this.encoderCache.clear();
2034
+ resolveToolNamesForAudit(ctx);
2035
+ recordAfterContextManager({
2036
+ mode: ctx.mode,
2037
+ llmMessages: ctx.llmMessages,
2038
+ contextTrace: ctx.contextTrace
2039
+ });
2040
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2041
+ recordAfterContextManagerOnSystemReminderHit({
2042
+ mode: ctx.mode,
2043
+ llmMessages: ctx.llmMessages,
2044
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2045
+ contextTrace: ctx.contextTrace
2046
+ });
1807
2047
  }
1808
2048
  };
1809
- function normalizePositiveNumber(value, fallback) {
1810
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2049
+ var als = new async_hooks.AsyncLocalStorage();
2050
+ function readTokenCount(record, key) {
2051
+ const value = record[key];
2052
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1811
2053
  }
1812
- function normalizeNonNegativeInteger(value, fallback) {
1813
- if (typeof value !== "number" || !Number.isFinite(value)) {
1814
- return fallback;
1815
- }
1816
- return Math.max(0, Math.floor(value));
2054
+ function readRecord(record, key) {
2055
+ const value = record[key];
2056
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2057
+ return Object.fromEntries(Object.entries(value));
1817
2058
  }
1818
- var als = new async_hooks.AsyncLocalStorage();
1819
- function normalizeLlmUsage(usage) {
2059
+ function normalizedUsageFromCanonical(canonicalUsage) {
2060
+ return {
2061
+ promptTokens: canonicalUsage.inputTokens,
2062
+ completionTokens: canonicalUsage.outputTokens,
2063
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2064
+ canonicalUsage
2065
+ };
2066
+ }
2067
+ function normalizeCanonicalLlmUsage(usage) {
1820
2068
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1821
2069
  const rec = usage;
1822
- const promptTokensRaw = rec["prompt_tokens"];
1823
- const completionTokensRaw = rec["completion_tokens"];
1824
- const totalTokensRaw = rec["total_tokens"];
1825
- const tokensRaw = rec["tokens"];
1826
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1827
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1828
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1829
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1830
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1831
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1832
- return { promptTokens, completionTokens, totalTokens };
2070
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2071
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2072
+ if (inputTokens === void 0 || outputTokens === void 0) {
2073
+ return void 0;
2074
+ }
2075
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2076
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2077
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2078
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2079
+ const totalTokens = readTokenCount(rec, "total_tokens");
2080
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2081
+ return void 0;
2082
+ }
2083
+ return {
2084
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2085
+ outputTokens,
2086
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2087
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2088
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2089
+ source: "provider-response-usage",
2090
+ confidence: "actual",
2091
+ rawUsage: usage
2092
+ };
2093
+ }
2094
+ function normalizeLlmUsage(usage) {
2095
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2096
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1833
2097
  }
1834
2098
  function recordLlmCallTelemetry(entry) {
1835
2099
  const store = als.getStore();
@@ -1843,17 +2107,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1843
2107
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1844
2108
  return;
1845
2109
  }
1846
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2110
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2111
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1847
2112
  const respText = extractResponseText(ctx.llmResp);
1848
2113
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1849
2114
  try {
1850
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1851
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1852
- return {
1853
- promptTokens,
1854
- completionTokens,
1855
- totalTokens: promptTokens + completionTokens
1856
- };
2115
+ const promptTokens = ctx.llmMessages.reduce(
2116
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2117
+ 0
2118
+ );
2119
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2120
+ return normalizedUsageFromCanonical({
2121
+ inputTokens: promptTokens,
2122
+ outputTokens: completionTokens,
2123
+ totalTokens: promptTokens + completionTokens,
2124
+ source: "local-estimate",
2125
+ confidence: "estimate"
2126
+ });
1857
2127
  } catch {
1858
2128
  return void 0;
1859
2129
  }
@@ -1863,7 +2133,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1863
2133
  stream: ctx.input.stream === true,
1864
2134
  startedAt: ctx.llmCallStartedAt,
1865
2135
  durationMs: ctx.llmCallDurationMs,
1866
- usage: normalizedUsage
2136
+ usage: normalizedUsage,
2137
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1867
2138
  });
1868
2139
  ctx.telemetry.emit({
1869
2140
  kind: "llm_call",
@@ -1871,6 +2142,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1871
2142
  stream: ctx.input.stream === true,
1872
2143
  durationMs: ctx.llmCallDurationMs,
1873
2144
  usage: normalizedUsage,
2145
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1874
2146
  scope: {
1875
2147
  conversationId: ctx.conversationId || void 0,
1876
2148
  turnId: ctx.turnId,
@@ -2014,10 +2286,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2014
2286
  return [
2015
2287
  `\u26A0\uFE0F \u4E0A\u4E0B\u6587\u9884\u7B97\u544A\u8B66\uFF1A\u4F60\u5DF2\u6267\u884C\u4E86 ${displayStep}/${displayMax} \u6B65\uFF0C\u4E0A\u4E0B\u6587\u7A7A\u95F4\u5373\u5C06\u8017\u5C3D\u3002`,
2016
2288
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2017
- "1. \u8C03\u7528sharedmemory_write\u5DE5\u5177\uFF0C\u5C06\u5F53\u524D\u53D1\u73B0\u3001\u603B\u7ED3\u3001\u601D\u8003\u6216\u8005\u4EFB\u4F55\u91CD\u8981\u4FE1\u606F\u8BE6\u7EC6\u5199\u5165sharedmemory\u3002",
2289
+ "1. \u5148\u786E\u8BA4\u5173\u952E\u8FDB\u5C55\u3001\u7EA6\u675F\u3001\u4E0B\u4E00\u6B65\u5DF2\u7ECF\u8FDB\u5165 TaskState\uFF1B\u5982\u679C\u6CA1\u6709\uFF0C\u8BF7\u8C03\u7528 taskstate_write \u66F4\u65B0\u3002",
2018
2290
  `2. \u8C03\u7528 ${checkpointToolName} \u5DE5\u5177\uFF0C\u4F20\u5165 summary\uFF08\u9636\u6BB5\u8FC7\u6E21\u6458\u8981\uFF09\u548C taskstate\uFF08\u6700\u65B0\u4EFB\u52A1\u72B6\u6001\uFF09\u3002`,
2019
2291
  ' \u8FD9\u4F1A\u4E00\u6B21\u6027\u5B8C\u6210"\u4FDD\u5B58\u72B6\u6001 + \u6E05\u7406\u5386\u53F2"\uFF0Ccheckpoint tool_output \u4E2D\u4F1A\u4FDD\u7559\u4F60\u7684 TaskState \u5FEB\u7167\u3002',
2020
- "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u91CD\u8981\u4FE1\u606F\u4F1A\u901A\u8FC7sharedmemory\u4FDD\u5B58\u3002"
2292
+ "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u9700\u8981\u957F\u671F\u4EA4\u4ED8\u7ED9\u7528\u6237\u7684\u5185\u5BB9\u8BF7\u5199\u5165 Workspace \u6587\u4EF6\u3002"
2021
2293
  ].join("\n");
2022
2294
  };
2023
2295
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2325,6 +2597,219 @@ function createApplySystemReminderStage() {
2325
2597
  };
2326
2598
  }
2327
2599
 
2600
+ // src/runtime-kernel/token-accounting/index.ts
2601
+ var token_accounting_exports = {};
2602
+ __export(token_accounting_exports, {
2603
+ addLedgerAggregate: () => addLedgerAggregate,
2604
+ addUsageTotals: () => addUsageTotals,
2605
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
2606
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
2607
+ computeCost: () => computeCost,
2608
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
2609
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
2610
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
2611
+ });
2612
+
2613
+ // src/runtime-kernel/token-accounting/functions.ts
2614
+ var EMPTY_LEDGER_AGGREGATE = {
2615
+ contextTokens: 0,
2616
+ entryCount: 0,
2617
+ llmCallCount: 0,
2618
+ contextComponentCount: 0
2619
+ };
2620
+ var TOKEN_PRICE_UNIT = 1e6;
2621
+ function sumReportedOptional(values) {
2622
+ const reported = values.filter((value) => value !== void 0);
2623
+ if (reported.length === 0) {
2624
+ return void 0;
2625
+ }
2626
+ return reported.reduce((total, value) => total + value, 0);
2627
+ }
2628
+ function sumTotalTokens(usages) {
2629
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
2630
+ return void 0;
2631
+ }
2632
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
2633
+ }
2634
+ function aggregateCanonicalUsage(usages) {
2635
+ if (usages.length === 0) {
2636
+ return void 0;
2637
+ }
2638
+ return {
2639
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
2640
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
2641
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
2642
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
2643
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
2644
+ totalTokens: sumTotalTokens(usages),
2645
+ usageCount: usages.length
2646
+ };
2647
+ }
2648
+ function createLlmUsageLedgerEntry(input) {
2649
+ return {
2650
+ ...input,
2651
+ kind: "llm-usage"
2652
+ };
2653
+ }
2654
+ function createContextComponentLedgerEntry(input) {
2655
+ return {
2656
+ ...input,
2657
+ kind: "context-component",
2658
+ components: [...input.components],
2659
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2660
+ };
2661
+ }
2662
+ function addUsageTotals(left, right) {
2663
+ if (!left) {
2664
+ return right;
2665
+ }
2666
+ if (!right) {
2667
+ return left;
2668
+ }
2669
+ return {
2670
+ inputTokens: left.inputTokens + right.inputTokens,
2671
+ outputTokens: left.outputTokens + right.outputTokens,
2672
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
2673
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
2674
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
2675
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
2676
+ usageCount: left.usageCount + right.usageCount
2677
+ };
2678
+ }
2679
+ function addLedgerAggregate(left, right) {
2680
+ return {
2681
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
2682
+ contextTokens: left.contextTokens + right.contextTokens,
2683
+ entryCount: left.entryCount + right.entryCount,
2684
+ llmCallCount: left.llmCallCount + right.llmCallCount,
2685
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
2686
+ };
2687
+ }
2688
+ function aggregateTokenLedgerEntries(entries) {
2689
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
2690
+ return entries.reduce((aggregate, entry) => {
2691
+ if (entry.kind === "llm-usage") {
2692
+ return {
2693
+ ...aggregate,
2694
+ entryCount: aggregate.entryCount + 1,
2695
+ llmCallCount: aggregate.llmCallCount + 1
2696
+ };
2697
+ }
2698
+ return {
2699
+ ...aggregate,
2700
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
2701
+ entryCount: aggregate.entryCount + 1,
2702
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
2703
+ };
2704
+ }, {
2705
+ ...EMPTY_LEDGER_AGGREGATE,
2706
+ llmUsage: aggregateCanonicalUsage(llmUsages)
2707
+ });
2708
+ }
2709
+ function createRunTokenUsageAggregate(input) {
2710
+ const children = input.childAggregates?.reduce(
2711
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
2712
+ EMPTY_LEDGER_AGGREGATE
2713
+ );
2714
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
2715
+ }
2716
+ function componentCost(tokens, pricePerMillion) {
2717
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
2718
+ }
2719
+ function needsPrice(tokens) {
2720
+ return tokens !== void 0 && tokens > 0;
2721
+ }
2722
+ function missingPriceComponents(usage, pricing) {
2723
+ const missing = [];
2724
+ if (!pricing) {
2725
+ if (needsPrice(usage.inputTokens)) {
2726
+ missing.push("input");
2727
+ }
2728
+ if (needsPrice(usage.outputTokens)) {
2729
+ missing.push("output");
2730
+ }
2731
+ if (needsPrice(usage.reasoningTokens)) {
2732
+ missing.push("reasoning");
2733
+ }
2734
+ if (needsPrice(usage.cacheReadTokens)) {
2735
+ missing.push("cacheRead");
2736
+ }
2737
+ if (needsPrice(usage.cacheWriteTokens)) {
2738
+ missing.push("cacheWrite");
2739
+ }
2740
+ return missing;
2741
+ }
2742
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
2743
+ missing.push("input");
2744
+ }
2745
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
2746
+ missing.push("output");
2747
+ }
2748
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
2749
+ missing.push("reasoning");
2750
+ }
2751
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
2752
+ missing.push("cacheRead");
2753
+ }
2754
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
2755
+ missing.push("cacheWrite");
2756
+ }
2757
+ return missing;
2758
+ }
2759
+ function reportedComponentCost(tokens, pricePerMillion) {
2760
+ if (tokens === void 0) {
2761
+ return void 0;
2762
+ }
2763
+ if (tokens === 0) {
2764
+ return 0;
2765
+ }
2766
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
2767
+ }
2768
+ function requiredComponentCost(tokens, pricePerMillion) {
2769
+ if (tokens === 0) {
2770
+ return 0;
2771
+ }
2772
+ return componentCost(tokens, pricePerMillion ?? 0);
2773
+ }
2774
+ function sumComputedCosts(costs) {
2775
+ let total = 0;
2776
+ for (const cost of costs) {
2777
+ total += cost ?? 0;
2778
+ }
2779
+ return total;
2780
+ }
2781
+ function computeCost(usage, pricing) {
2782
+ const missing = missingPriceComponents(usage, pricing);
2783
+ if (!pricing || missing.length > 0) {
2784
+ return {
2785
+ status: "unknown",
2786
+ ...pricing ? { currency: pricing.currency } : {},
2787
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
2788
+ };
2789
+ }
2790
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
2791
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
2792
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
2793
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
2794
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
2795
+ return {
2796
+ status: "computed",
2797
+ currency: pricing.currency,
2798
+ inputCost,
2799
+ outputCost,
2800
+ reasoningCost,
2801
+ cacheReadCost,
2802
+ cacheWriteCost,
2803
+ totalCost: sumComputedCosts([
2804
+ inputCost,
2805
+ outputCost,
2806
+ reasoningCost,
2807
+ cacheReadCost,
2808
+ cacheWriteCost
2809
+ ])
2810
+ };
2811
+ }
2812
+
2328
2813
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2329
2814
  var logger4 = new Logger("GraphAgentExecutor");
2330
2815
  function createBuildContextStage(dependencies) {
@@ -2341,6 +2826,23 @@ function createBuildContextStage(dependencies) {
2341
2826
  ctx.mode = contextBuildResult.mode;
2342
2827
  ctx.llmMessages = contextBuildResult.llmMessages;
2343
2828
  ctx.contextTrace = contextBuildResult.contextTrace;
2829
+ if (contextBuildResult.tokenEstimate) {
2830
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2831
+ ctx.telemetry.emit({
2832
+ kind: "context_build",
2833
+ modelId: ctx.modelId,
2834
+ mode: contextBuildResult.mode,
2835
+ tokenEstimate: contextBuildResult.tokenEstimate,
2836
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2837
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2838
+ scope: {
2839
+ conversationId: ctx.conversationId,
2840
+ runId: ctx.input.toolContext?.runId,
2841
+ parentRunId: ctx.input.toolContext?.parentRunId,
2842
+ turnId: ctx.turnId
2843
+ }
2844
+ });
2845
+ }
2344
2846
  for (const event of contextBuildResult.summaryEvents) {
2345
2847
  if (!isHistorySummaryEvent(event)) {
2346
2848
  continue;
@@ -2355,6 +2857,24 @@ function createBuildContextStage(dependencies) {
2355
2857
  }
2356
2858
  };
2357
2859
  }
2860
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2861
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2862
+ if (keptComponents.length === 0) {
2863
+ return void 0;
2864
+ }
2865
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2866
+ const createdAt = Date.now();
2867
+ return createContextComponentLedgerEntry({
2868
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2869
+ conversationId: ctx.conversationId,
2870
+ runId,
2871
+ parentRunId: ctx.input.toolContext?.parentRunId,
2872
+ turnId: ctx.turnId,
2873
+ route: contextBuildResult.tokenEstimate?.route,
2874
+ createdAt,
2875
+ components: keptComponents
2876
+ });
2877
+ }
2358
2878
 
2359
2879
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2360
2880
  function createBuildDecisionStage(dependencies) {
@@ -2598,6 +3118,7 @@ var GraphAgentExecutor = class {
2598
3118
  modelCatalog;
2599
3119
  telemetryPort;
2600
3120
  auditPort;
3121
+ tokenizer;
2601
3122
  stages;
2602
3123
  middlewares;
2603
3124
  constructor(dependencies) {
@@ -2611,6 +3132,7 @@ var GraphAgentExecutor = class {
2611
3132
  });
2612
3133
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2613
3134
  this.auditPort = dependencies.auditPort ?? noopAudit;
3135
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2614
3136
  this.stages = [
2615
3137
  createPrepareCallStage({
2616
3138
  modelResolver: this.modelResolver,
@@ -2654,7 +3176,8 @@ var GraphAgentExecutor = class {
2654
3176
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2655
3177
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2656
3178
  telemetry: this.telemetryPort,
2657
- audit: this.auditPort
3179
+ audit: this.auditPort,
3180
+ tokenizer: this.tokenizer
2658
3181
  };
2659
3182
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2660
3183
  stream: input.stream === true,
@@ -3619,11 +4142,11 @@ function buildToolOutputUiMeta(params) {
3619
4142
  }
3620
4143
  async function applyObservationGovernance(params) {
3621
4144
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3622
- return;
4145
+ return {};
3623
4146
  }
3624
4147
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3625
4148
  if (!policy.enabled) {
3626
- return;
4149
+ return {};
3627
4150
  }
3628
4151
  const truncated = await params.observationPreview.truncateObservation({
3629
4152
  context: params.toolContext,
@@ -3637,13 +4160,37 @@ async function applyObservationGovernance(params) {
3637
4160
  })
3638
4161
  });
3639
4162
  if (!truncated.truncated) {
3640
- return;
4163
+ return {};
3641
4164
  }
3642
4165
  params.parsed["observation"] = truncated.preview;
3643
4166
  const data = params.parsed["data"];
3644
4167
  if (isRecord9(data) && !("tool_output_store" in data)) {
3645
4168
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3646
4169
  }
4170
+ return {
4171
+ observationTruncation: buildObservationTruncationMeta({
4172
+ originalText: params.structuredObservation,
4173
+ previewText: truncated.preview,
4174
+ originalChars: truncated.originalChars,
4175
+ previewChars: truncated.previewChars,
4176
+ originalLines: truncated.originalLines,
4177
+ previewLines: truncated.previewLines
4178
+ })
4179
+ };
4180
+ }
4181
+ function buildObservationTruncationMeta(input) {
4182
+ return {
4183
+ originalChars: input.originalChars ?? input.originalText.length,
4184
+ previewChars: input.previewChars ?? input.previewText.length,
4185
+ originalLines: input.originalLines ?? countLines(input.originalText),
4186
+ previewLines: input.previewLines ?? countLines(input.previewText)
4187
+ };
4188
+ }
4189
+ function countLines(value) {
4190
+ if (value.length === 0) {
4191
+ return 0;
4192
+ }
4193
+ return value.split(/\r\n|\r|\n/).length;
3647
4194
  }
3648
4195
 
3649
4196
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4606,7 +5153,7 @@ var ToolNode = class {
4606
5153
  parentRunId: context.toolContext.parentRunId
4607
5154
  });
4608
5155
  applyProtocolFuseState(context.local);
4609
- await applyObservationGovernance({
5156
+ const observationGovernance = await applyObservationGovernance({
4610
5157
  parsed: context.parsed,
4611
5158
  toolName: context.toolName,
4612
5159
  toolContext: context.toolContext,
@@ -4633,6 +5180,12 @@ var ToolNode = class {
4633
5180
  runtimeToolOutput,
4634
5181
  execIdempotency: context.exec.idempotency
4635
5182
  });
5183
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5184
+ runtimeToolOutput.metadata = {
5185
+ ...runtimeToolOutput.metadata ?? {},
5186
+ observationTruncation: observationGovernance.observationTruncation
5187
+ };
5188
+ }
4636
5189
  const remainingCalls = context.calls.slice(1);
4637
5190
  context.state.local = buildSuccessLocalState({
4638
5191
  local: context.local,
@@ -6467,6 +7020,7 @@ async function callLlmStream(params) {
6467
7020
  const streamAnswerId = generateMessageId();
6468
7021
  let streamChunkSeq = 0;
6469
7022
  let capturedUsage = void 0;
7023
+ let capturedCanonicalUsage = void 0;
6470
7024
  const toolAccumulator = new ToolCallStreamAccumulator([
6471
7025
  "markdown_edit",
6472
7026
  "text_to_image",
@@ -6525,6 +7079,10 @@ async function callLlmStream(params) {
6525
7079
  if (typeof chunk !== "object" || chunk === null) {
6526
7080
  return;
6527
7081
  }
7082
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7083
+ if (parsedCanonicalUsage.success) {
7084
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7085
+ }
6528
7086
  if (chunk.content) {
6529
7087
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6530
7088
  fullResponse += chunk.content;
@@ -6609,6 +7167,12 @@ async function callLlmStream(params) {
6609
7167
  const onUsage = (usage) => {
6610
7168
  capturedUsage = usage;
6611
7169
  };
7170
+ const onCanonicalUsage = (usage) => {
7171
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7172
+ if (parsed.success) {
7173
+ capturedCanonicalUsage = parsed.data;
7174
+ }
7175
+ };
6612
7176
  await aiEngine.chatCompletionStream(
6613
7177
  modelId,
6614
7178
  messages,
@@ -6621,7 +7185,8 @@ async function callLlmStream(params) {
6621
7185
  onError,
6622
7186
  onFinish,
6623
7187
  onThought,
6624
- onUsage
7188
+ onUsage,
7189
+ onCanonicalUsage
6625
7190
  );
6626
7191
  if (streamError) {
6627
7192
  throw streamError;
@@ -6629,12 +7194,13 @@ async function callLlmStream(params) {
6629
7194
  emitThoughtComplete(thoughtSegmenter.finalize());
6630
7195
  const mergedToolCalls = toolAccumulator.getToolCalls();
6631
7196
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6632
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7197
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6633
7198
  return {
6634
7199
  content: fullResponse,
6635
7200
  tool_calls: mergedToolCalls,
6636
7201
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6637
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7202
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7203
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6638
7204
  };
6639
7205
  }
6640
7206
  return fullResponse;
@@ -6684,6 +7250,10 @@ function tryCloudQuotaFallback({
6684
7250
  }
6685
7251
 
6686
7252
  // src/runtime-kernel/llm/usage-telemetry.ts
7253
+ function parseCanonicalUsage(value) {
7254
+ const parsed = CanonicalLlmUsage.safeParse(value);
7255
+ return parsed.success ? parsed.data : void 0;
7256
+ }
6687
7257
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6688
7258
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6689
7259
  return normalizeCompletionResponse(response);
@@ -6694,6 +7264,7 @@ function normalizeCompletionResponse(response) {
6694
7264
  }
6695
7265
  if (isRecord19(response)) {
6696
7266
  const usage = response["usage"];
7267
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6697
7268
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6698
7269
  if (parsedToolCalls) {
6699
7270
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6701,7 +7272,8 @@ function normalizeCompletionResponse(response) {
6701
7272
  content: typeof response["content"] === "string" ? response["content"] : "",
6702
7273
  tool_calls: parsedToolCalls,
6703
7274
  reasoning_details: reasoningDetails,
6704
- ...usage !== void 0 ? { usage } : {}
7275
+ ...usage !== void 0 ? { usage } : {},
7276
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6705
7277
  };
6706
7278
  }
6707
7279
  }
@@ -6711,10 +7283,12 @@ function normalizeCompletionResponse(response) {
6711
7283
  if (typeof response === "object") {
6712
7284
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6713
7285
  const usage = response["usage"];
7286
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6714
7287
  return {
6715
7288
  content: typeof response["content"] === "string" ? response["content"] : "",
6716
7289
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6717
- ...usage !== void 0 ? { usage } : {}
7290
+ ...usage !== void 0 ? { usage } : {},
7291
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6718
7292
  };
6719
7293
  }
6720
7294
  if (isRecord19(response)) {
@@ -6968,30 +7542,6 @@ var LlmCaller = class {
6968
7542
  }
6969
7543
  };
6970
7544
 
6971
- // src/shared/defaultTokenizerPort.ts
6972
- var DefaultTokenizerPort = class {
6973
- constructor(config = {}) {
6974
- this.config = config;
6975
- }
6976
- config;
6977
- estimateText(text, _modelId) {
6978
- return TokenCalculator.estimateTokens(text, {
6979
- encoding: this.config.encoding,
6980
- avgCharsPerToken: this.config.avgCharsPerToken
6981
- });
6982
- }
6983
- estimateMessage(message, _modelId) {
6984
- return TokenCalculator.estimateMessageTokens(message, {
6985
- encoding: this.config.encoding,
6986
- avgCharsPerToken: this.config.avgCharsPerToken,
6987
- toolCallOverhead: this.config.toolCallOverhead
6988
- });
6989
- }
6990
- };
6991
- function createDefaultTokenizerPort(config = {}) {
6992
- return new DefaultTokenizerPort(config);
6993
- }
6994
-
6995
7545
  // src/runtime-kernel/child-runs/index.ts
6996
7546
  var child_runs_exports = {};
6997
7547
  __export(child_runs_exports, {
@@ -8601,6 +9151,7 @@ __export(telemetry_exports, {
8601
9151
  var TELEMETRY_EVENT_KINDS = [
8602
9152
  "llm_call",
8603
9153
  "tool_call",
9154
+ "context_build",
8604
9155
  "graph_node",
8605
9156
  "run_lifecycle"
8606
9157
  ];
@@ -8804,7 +9355,11 @@ exports.SystemReminderRegistry = SystemReminderRegistry;
8804
9355
  exports.ToolNode = ToolNode;
8805
9356
  exports.UserNode = UserNode;
8806
9357
  exports.WaitUserNode = WaitUserNode;
9358
+ exports.addLedgerAggregate = addLedgerAggregate;
9359
+ exports.addUsageTotals = addUsageTotals;
8807
9360
  exports.agentHasToolTrigger = agentHasToolTrigger;
9361
+ exports.aggregateCanonicalUsage = aggregateCanonicalUsage;
9362
+ exports.aggregateTokenLedgerEntries = aggregateTokenLedgerEntries;
8808
9363
  exports.appendStreamingProviderReasoningDetails = appendStreamingProviderReasoningDetails;
8809
9364
  exports.applySystemReminders = applySystemReminders;
8810
9365
  exports.audit = audit_exports;
@@ -8813,6 +9368,7 @@ exports.childRunTrace = child_run_trace_exports;
8813
9368
  exports.childRuns = child_runs_exports;
8814
9369
  exports.compactProviderReasoningDetails = compactProviderReasoningDetails;
8815
9370
  exports.compactReasoningDetailsInValue = compactReasoningDetailsInValue;
9371
+ exports.computeCost = computeCost;
8816
9372
  exports.computeToolIdempotencyKey = computeToolIdempotencyKey;
8817
9373
  exports.consoleAudit = consoleAudit;
8818
9374
  exports.contextBudgetWarningTemplate = contextBudgetWarningTemplate;
@@ -8821,13 +9377,16 @@ exports.countToolCallsInCurrentRequest = countToolCallsInCurrentRequest;
8821
9377
  exports.createCompositeAudit = createCompositeAudit;
8822
9378
  exports.createConsoleAudit = createConsoleAudit;
8823
9379
  exports.createContextCheckpointTool = createContextCheckpointTool;
9380
+ exports.createContextComponentLedgerEntry = createContextComponentLedgerEntry;
8824
9381
  exports.createDefaultGraphExecutor = createDefaultGraphExecutor;
8825
9382
  exports.createDefaultSystemReminderRegistry = createDefaultSystemReminderRegistry;
8826
9383
  exports.createDefaultTokenizerPort = createDefaultTokenizerPort;
8827
9384
  exports.createEventStoreAudit = createEventStoreAudit;
8828
9385
  exports.createFileAudit = createFileAudit;
8829
9386
  exports.createGraphLoopHarness = createGraphLoopHarness;
9387
+ exports.createLlmUsageLedgerEntry = createLlmUsageLedgerEntry;
8830
9388
  exports.createMonotonicEventIdFactory = createMonotonicEventIdFactory;
9389
+ exports.createRunTokenUsageAggregate = createRunTokenUsageAggregate;
8831
9390
  exports.createSystemReminderRules = createSystemReminderRules;
8832
9391
  exports.defaultPolicyEngine = defaultPolicyEngine;
8833
9392
  exports.defaultSystemReminderRegistry = defaultSystemReminderRegistry;
@@ -8864,6 +9423,7 @@ exports.summarizeCheckpoint = summarizeCheckpoint;
8864
9423
  exports.systemReminder = system_reminder_exports;
8865
9424
  exports.telemetry = telemetry_exports;
8866
9425
  exports.toDisplayStep = toDisplayStep;
9426
+ exports.tokenAccounting = token_accounting_exports;
8867
9427
  exports.toolCallStreakTemplate = toolCallStreakTemplate;
8868
9428
  exports.toolCallStreakTrigger = toolCallStreakTrigger;
8869
9429
  exports.tools = tools_exports;