@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
@@ -139,6 +139,12 @@ z.object({
139
139
  args: z.record(z.unknown()).optional(),
140
140
  tool_call_id: z.string()
141
141
  });
142
+ var ObservationTruncationMeta = z.object({
143
+ originalChars: z.number().int().nonnegative(),
144
+ previewChars: z.number().int().nonnegative(),
145
+ originalLines: z.number().int().nonnegative().optional(),
146
+ previewLines: z.number().int().nonnegative().optional()
147
+ });
142
148
  var ImageInfoMeta = z.object({
143
149
  url: z.string().optional(),
144
150
  width: z.number().int().positive().optional(),
@@ -170,6 +176,7 @@ var PersistentMetadata = z.object({
170
176
  tool_name: z.string().optional(),
171
177
  args: z.record(z.unknown()).optional(),
172
178
  tool_call_id: z.string().optional(),
179
+ observationTruncation: ObservationTruncationMeta.optional(),
173
180
  raw_output: z.string().optional(),
174
181
  image_info: ImageInfoMeta.optional(),
175
182
  taskType: z.string().optional(),
@@ -316,7 +323,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
316
323
  var AgentSpecTokenEstimationPolicy = z.object({
317
324
  encoding: z.string().min(1).optional(),
318
325
  avgCharsPerToken: z.number().positive().optional(),
319
- toolCallOverhead: z.number().int().nonnegative().optional()
326
+ toolCallOverhead: z.number().int().nonnegative().optional(),
327
+ calibration: z.object({
328
+ enabled: z.boolean().optional(),
329
+ minSamples: z.number().int().positive().optional(),
330
+ minCoefficient: z.number().positive().optional(),
331
+ maxCoefficient: z.number().positive().optional()
332
+ }).optional(),
333
+ remoteCount: z.object({
334
+ enabled: z.boolean().optional(),
335
+ failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
336
+ }).optional()
320
337
  });
321
338
  var AgentSpecSystemReminderTrigger = z.object({
322
339
  kind: z.string().min(1),
@@ -1014,6 +1031,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1014
1031
  error,
1015
1032
  ...options
1016
1033
  });
1034
+ var TokenCountSource = z.enum([
1035
+ "local-estimate",
1036
+ "provider-preflight-count",
1037
+ "provider-response-usage",
1038
+ "host-supplied",
1039
+ "test-fixture"
1040
+ ]);
1041
+ var TokenCountConfidence = z.enum([
1042
+ "estimate",
1043
+ "provider-estimate",
1044
+ "actual"
1045
+ ]);
1046
+ var TokenRouteCapabilities = z.object({
1047
+ supportsRemoteTokenCount: z.boolean().optional(),
1048
+ supportsResponseUsage: z.boolean().optional(),
1049
+ supportsImageInput: z.boolean().optional(),
1050
+ supportsCachedInputBilling: z.boolean().optional(),
1051
+ supportsReasoningTokens: z.boolean().optional()
1052
+ });
1053
+ var TokenRoute = z.object({
1054
+ providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1055
+ baseURL: 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"),
1056
+ modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
1057
+ providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1058
+ capabilities: TokenRouteCapabilities.optional()
1059
+ });
1060
+ var tokenCount = z.number().int().nonnegative();
1061
+ var CanonicalLlmUsage = z.object({
1062
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1063
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1064
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1065
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1066
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1067
+ 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"),
1068
+ source: TokenCountSource,
1069
+ confidence: TokenCountConfidence,
1070
+ rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1071
+ });
1072
+ var tokenCount2 = z.number().int().nonnegative();
1073
+ var tokenPrice = z.number().finite().nonnegative();
1074
+ z.enum([
1075
+ "llm-usage",
1076
+ "context-component"
1077
+ ]);
1078
+ var ContextTokenComponentKind = z.enum([
1079
+ "system",
1080
+ "user",
1081
+ "assistant",
1082
+ "tool",
1083
+ "context-injection",
1084
+ "history-summary",
1085
+ "working-memory",
1086
+ "fence",
1087
+ "system-reminder",
1088
+ "other"
1089
+ ]);
1090
+ var TokenUsageTotals = z.object({
1091
+ inputTokens: tokenCount2,
1092
+ outputTokens: tokenCount2,
1093
+ reasoningTokens: tokenCount2.optional(),
1094
+ cacheReadTokens: tokenCount2.optional(),
1095
+ cacheWriteTokens: tokenCount2.optional(),
1096
+ totalTokens: tokenCount2.optional(),
1097
+ usageCount: z.number().int().nonnegative()
1098
+ });
1099
+ var ContextTokenComponent = z.object({
1100
+ componentId: z.string().min(1),
1101
+ kind: ContextTokenComponentKind,
1102
+ tokens: tokenCount2,
1103
+ source: TokenCountSource,
1104
+ confidence: TokenCountConfidence,
1105
+ label: z.string().optional(),
1106
+ messageId: z.string().optional(),
1107
+ role: z.string().optional(),
1108
+ action: z.string().optional(),
1109
+ kept: z.boolean().optional(),
1110
+ truncatedAtExecution: z.boolean().optional(),
1111
+ originalTokensEstimate: tokenCount2.optional(),
1112
+ droppedTokensEstimate: tokenCount2.optional()
1113
+ });
1114
+ var TokenLedgerEntryBase = z.object({
1115
+ id: z.string().min(1),
1116
+ runId: z.string().optional(),
1117
+ parentRunId: z.string().optional(),
1118
+ conversationId: z.string().optional(),
1119
+ turnId: z.string().optional(),
1120
+ stepId: z.string().optional(),
1121
+ route: TokenRoute.optional(),
1122
+ createdAt: z.number().int().nonnegative().optional()
1123
+ });
1124
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1125
+ kind: z.literal("llm-usage"),
1126
+ modelId: z.string().optional(),
1127
+ usage: CanonicalLlmUsage
1128
+ });
1129
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1130
+ kind: z.literal("context-component"),
1131
+ components: z.array(ContextTokenComponent),
1132
+ totalTokens: tokenCount2
1133
+ });
1134
+ z.discriminatedUnion("kind", [
1135
+ LlmUsageTokenLedgerEntry,
1136
+ ContextComponentTokenLedgerEntry
1137
+ ]);
1138
+ var TokenLedgerAggregate = z.object({
1139
+ llmUsage: TokenUsageTotals.optional(),
1140
+ contextTokens: tokenCount2,
1141
+ entryCount: z.number().int().nonnegative(),
1142
+ llmCallCount: z.number().int().nonnegative(),
1143
+ contextComponentCount: z.number().int().nonnegative()
1144
+ });
1145
+ z.object({
1146
+ /**
1147
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1148
+ */
1149
+ own: TokenLedgerAggregate,
1150
+ children: TokenLedgerAggregate.optional()
1151
+ });
1152
+ var TokenCostComponent = z.enum([
1153
+ "input",
1154
+ "output",
1155
+ "reasoning",
1156
+ "cacheRead",
1157
+ "cacheWrite"
1158
+ ]);
1159
+ z.object({
1160
+ currency: z.string().min(1),
1161
+ unit: z.literal("per_1m_tokens"),
1162
+ input: tokenPrice.optional(),
1163
+ output: tokenPrice.optional(),
1164
+ reasoning: tokenPrice.optional(),
1165
+ cacheRead: tokenPrice.optional(),
1166
+ cacheWrite: tokenPrice.optional()
1167
+ });
1168
+ z.object({
1169
+ status: z.enum(["computed", "unknown"]),
1170
+ currency: z.string().optional(),
1171
+ inputCost: tokenPrice.optional(),
1172
+ outputCost: tokenPrice.optional(),
1173
+ reasoningCost: tokenPrice.optional(),
1174
+ cacheReadCost: tokenPrice.optional(),
1175
+ cacheWriteCost: tokenPrice.optional(),
1176
+ totalCost: tokenPrice.optional(),
1177
+ missingPriceComponents: z.array(TokenCostComponent).optional()
1178
+ });
1179
+ var tokenCount3 = z.number().int().nonnegative();
1180
+ var actualCalibrationSource = z.enum([
1181
+ "provider-response-usage",
1182
+ "host-supplied",
1183
+ "test-fixture"
1184
+ ]);
1185
+ z.object({
1186
+ route: TokenRoute,
1187
+ localEstimateTokens: tokenCount3,
1188
+ actualInputTokens: tokenCount3,
1189
+ source: actualCalibrationSource,
1190
+ confidence: z.literal("actual"),
1191
+ observedAt: z.number().int().nonnegative().optional(),
1192
+ runId: z.string().optional(),
1193
+ ledgerEntryId: z.string().optional()
1194
+ });
1195
+ z.object({
1196
+ enabled: z.boolean(),
1197
+ applied: z.boolean(),
1198
+ route: TokenRoute.optional(),
1199
+ sampleCount: z.number().int().nonnegative(),
1200
+ coefficient: z.number().positive().optional(),
1201
+ minSamples: z.number().int().positive().optional(),
1202
+ minCoefficient: z.number().positive().optional(),
1203
+ maxCoefficient: z.number().positive().optional(),
1204
+ localEstimateTokens: tokenCount3.optional(),
1205
+ calibratedEstimateTokens: tokenCount3.optional(),
1206
+ deltaTokens: z.number().int().optional(),
1207
+ sampleLedgerEntryIds: z.array(z.string()).optional()
1208
+ });
1209
+ z.object({
1210
+ route: TokenRoute.optional(),
1211
+ localEstimateTokens: tokenCount3,
1212
+ calibratedEstimateTokens: tokenCount3,
1213
+ finalTokens: tokenCount3,
1214
+ source: z.literal("local-estimate"),
1215
+ confidence: z.literal("estimate")
1216
+ });
1017
1217
 
1018
1218
  // src/runtime-kernel/graph-engine/engine.ts
1019
1219
  var logger = new Logger("GraphExecutor");
@@ -1417,6 +1617,190 @@ var noopAudit = {
1417
1617
  flush() {
1418
1618
  }
1419
1619
  };
1620
+ var TokenCalculator = class {
1621
+ static BYTES_PER_TOKEN_LATIN = 4;
1622
+ static BYTES_PER_TOKEN_CJK = 3;
1623
+ static OVERHEAD_PER_MESSAGE = 5;
1624
+ static OVERHEAD_PER_TOOL_CALL = 10;
1625
+ static encoderCache = /* @__PURE__ */ new Map();
1626
+ static DEFAULT_ENCODING = "cl100k_base";
1627
+ static SUPPORTED_ENCODINGS = [
1628
+ "gpt2",
1629
+ "r50k_base",
1630
+ "p50k_base",
1631
+ "p50k_edit",
1632
+ "cl100k_base",
1633
+ "o200k_base"
1634
+ ];
1635
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1636
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1637
+ if (this.isSupportedEncodingName(normalized)) {
1638
+ return normalized;
1639
+ }
1640
+ if (normalized.includes("deepseek")) {
1641
+ return "cl100k_base";
1642
+ }
1643
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1644
+ return "o200k_base";
1645
+ }
1646
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1647
+ return "cl100k_base";
1648
+ }
1649
+ return this.DEFAULT_ENCODING;
1650
+ }
1651
+ static isSupportedEncodingName(value) {
1652
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1653
+ }
1654
+ static getEncoder(modelIdentifierOrEncoding) {
1655
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1656
+ const cached = this.encoderCache.get(encodingName);
1657
+ if (cached) {
1658
+ return cached;
1659
+ }
1660
+ const encoder = get_encoding(encodingName);
1661
+ this.encoderCache.set(encodingName, encoder);
1662
+ return encoder;
1663
+ }
1664
+ static estimateTokensRough(text, _modelIdentifier) {
1665
+ if (!text) return 0;
1666
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1667
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1668
+ const byteLength = new TextEncoder().encode(text).length;
1669
+ return Math.ceil(byteLength / ratio);
1670
+ }
1671
+ static estimateTokens(text, options = {}) {
1672
+ if (!text) return 0;
1673
+ if (options.encoding) {
1674
+ try {
1675
+ return this.estimateTokensPrecise(text, options.encoding);
1676
+ } catch {
1677
+ }
1678
+ }
1679
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1680
+ return Math.ceil(text.length / avgCharsPerToken);
1681
+ }
1682
+ static estimateTokensPrecise(text, modelIdentifier) {
1683
+ if (!text) return 0;
1684
+ const encoder = this.getEncoder(modelIdentifier);
1685
+ return encoder.encode(text).length;
1686
+ }
1687
+ static estimateMessageTokens(message, options = {}) {
1688
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1689
+ if (message.content) {
1690
+ totalTokens += this.estimateTokens(String(message.content), options);
1691
+ }
1692
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1693
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1694
+ for (const toolCall of toolCalls) {
1695
+ totalTokens += toolCallOverhead;
1696
+ const fn = toolCall["function"];
1697
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1698
+ const fnRecord = fn;
1699
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1700
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1701
+ }
1702
+ }
1703
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1704
+ if (toolCallId) {
1705
+ totalTokens += this.estimateTokens(toolCallId, options);
1706
+ }
1707
+ return totalTokens;
1708
+ }
1709
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1710
+ return this.estimateMessageTokens(message, {
1711
+ encoding: modelIdentifier,
1712
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1713
+ });
1714
+ }
1715
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1716
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1717
+ }
1718
+ static extractToolCallsForTokenEstimate(message) {
1719
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1720
+ if (Array.isArray(direct)) return direct;
1721
+ const metadata = "metadata" in message ? message.metadata : void 0;
1722
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1723
+ const metadataRecord = metadata;
1724
+ const metadataToolCalls = metadataRecord["tool_calls"];
1725
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1726
+ }
1727
+ static extractToolCallIdForTokenEstimate(message) {
1728
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1729
+ return message.tool_call_id;
1730
+ }
1731
+ const metadata = "metadata" in message ? message.metadata : void 0;
1732
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1733
+ const metadataRecord = metadata;
1734
+ const toolCallId = metadataRecord["tool_call_id"];
1735
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1736
+ }
1737
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1738
+ if (!text || maxTokens <= 0) return "";
1739
+ const encoder = this.getEncoder(modelIdentifier);
1740
+ const tokens = encoder.encode(text);
1741
+ if (tokens.length <= maxTokens) {
1742
+ return text;
1743
+ }
1744
+ let truncatedTokens;
1745
+ const ellipsis = "...";
1746
+ switch (strategy) {
1747
+ case "start":
1748
+ truncatedTokens = tokens.slice(0, maxTokens);
1749
+ return encoder.decode(truncatedTokens) + ellipsis;
1750
+ case "end":
1751
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1752
+ return ellipsis + encoder.decode(truncatedTokens);
1753
+ case "middle": {
1754
+ const half = Math.floor(maxTokens / 2);
1755
+ const head = tokens.slice(0, half);
1756
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1757
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1758
+ }
1759
+ default:
1760
+ truncatedTokens = tokens.slice(0, maxTokens);
1761
+ return encoder.decode(truncatedTokens) + ellipsis;
1762
+ }
1763
+ }
1764
+ static cleanup() {
1765
+ for (const encoder of this.encoderCache.values()) {
1766
+ encoder.free();
1767
+ }
1768
+ this.encoderCache.clear();
1769
+ }
1770
+ };
1771
+ function normalizePositiveNumber(value, fallback) {
1772
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1773
+ }
1774
+ function normalizeNonNegativeInteger(value, fallback) {
1775
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1776
+ return fallback;
1777
+ }
1778
+ return Math.max(0, Math.floor(value));
1779
+ }
1780
+
1781
+ // src/shared/defaultTokenizerPort.ts
1782
+ var DefaultTokenizerPort = class {
1783
+ constructor(config = {}) {
1784
+ this.config = config;
1785
+ }
1786
+ config;
1787
+ estimateText(text, _modelId) {
1788
+ return TokenCalculator.estimateTokens(text, {
1789
+ encoding: this.config.encoding,
1790
+ avgCharsPerToken: this.config.avgCharsPerToken
1791
+ });
1792
+ }
1793
+ estimateMessage(message, _modelId) {
1794
+ return TokenCalculator.estimateMessageTokens(message, {
1795
+ encoding: this.config.encoding,
1796
+ avgCharsPerToken: this.config.avgCharsPerToken,
1797
+ toolCallOverhead: this.config.toolCallOverhead
1798
+ });
1799
+ }
1800
+ };
1801
+ function createDefaultTokenizerPort(config = {}) {
1802
+ return new DefaultTokenizerPort(config);
1803
+ }
1420
1804
 
1421
1805
  // src/shared/ids.ts
1422
1806
  function isoRandomUUID() {
@@ -1597,237 +1981,117 @@ function resolveUsage(response) {
1597
1981
  }
1598
1982
  return response.usage;
1599
1983
  }
1600
- function resolveToolCalls(response) {
1984
+ function resolveCanonicalUsage(response) {
1601
1985
  if (!response || typeof response === "string") {
1602
- return void 0;
1603
- }
1604
- return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
1605
- }
1606
- function resolveReasoningDetails(response) {
1607
- if (!response || typeof response === "string") {
1608
- return void 0;
1609
- }
1610
- return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
1611
- }
1612
- function resolveToolNamesForAudit(ctx) {
1613
- if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
1614
- return [];
1615
- }
1616
- return ctx.toolSchemas.map((tool) => tool.function.name);
1617
- }
1618
- function recordBeforeContextManager(params) {
1619
- }
1620
- function recordAfterContextManager(params) {
1621
- }
1622
- function recordAfterContextManagerOnSystemReminderHit(params) {
1623
- }
1624
- function recordToolProtocolError(params) {
1625
- }
1626
- function recordRunTranscript(params) {
1627
- }
1628
-
1629
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
1630
- var contextAuditMiddleware = async (ctx, stage, next) => {
1631
- if (stage.id === "build_context") {
1632
- recordBeforeContextManager({
1633
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
1634
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1635
- });
1636
- }
1637
- await next();
1638
- if (stage.id !== "apply_system_reminder") {
1639
- return;
1640
- }
1641
- resolveToolNamesForAudit(ctx);
1642
- recordAfterContextManager({
1643
- mode: ctx.mode,
1644
- llmMessages: ctx.llmMessages,
1645
- contextTrace: ctx.contextTrace
1646
- });
1647
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
1648
- recordAfterContextManagerOnSystemReminderHit({
1649
- mode: ctx.mode,
1650
- llmMessages: ctx.llmMessages,
1651
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
1652
- contextTrace: ctx.contextTrace
1653
- });
1654
- }
1655
- };
1656
- var TokenCalculator = class {
1657
- static BYTES_PER_TOKEN_LATIN = 4;
1658
- static BYTES_PER_TOKEN_CJK = 3;
1659
- static OVERHEAD_PER_MESSAGE = 5;
1660
- static OVERHEAD_PER_TOOL_CALL = 10;
1661
- static encoderCache = /* @__PURE__ */ new Map();
1662
- static DEFAULT_ENCODING = "cl100k_base";
1663
- static SUPPORTED_ENCODINGS = [
1664
- "gpt2",
1665
- "r50k_base",
1666
- "p50k_base",
1667
- "p50k_edit",
1668
- "cl100k_base",
1669
- "o200k_base"
1670
- ];
1671
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1672
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1673
- if (this.isSupportedEncodingName(normalized)) {
1674
- return normalized;
1675
- }
1676
- if (normalized.includes("deepseek")) {
1677
- return "cl100k_base";
1678
- }
1679
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1680
- return "o200k_base";
1681
- }
1682
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1683
- return "cl100k_base";
1684
- }
1685
- return this.DEFAULT_ENCODING;
1686
- }
1687
- static isSupportedEncodingName(value) {
1688
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1689
- }
1690
- static getEncoder(modelIdentifierOrEncoding) {
1691
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1692
- const cached = this.encoderCache.get(encodingName);
1693
- if (cached) {
1694
- return cached;
1695
- }
1696
- const encoder = get_encoding(encodingName);
1697
- this.encoderCache.set(encodingName, encoder);
1698
- return encoder;
1699
- }
1700
- static estimateTokensRough(text, _modelIdentifier) {
1701
- if (!text) return 0;
1702
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1703
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1704
- const byteLength = new TextEncoder().encode(text).length;
1705
- return Math.ceil(byteLength / ratio);
1706
- }
1707
- static estimateTokens(text, options = {}) {
1708
- if (!text) return 0;
1709
- if (options.encoding) {
1710
- try {
1711
- return this.estimateTokensPrecise(text, options.encoding);
1712
- } catch {
1713
- }
1714
- }
1715
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1716
- return Math.ceil(text.length / avgCharsPerToken);
1717
- }
1718
- static estimateTokensPrecise(text, modelIdentifier) {
1719
- if (!text) return 0;
1720
- const encoder = this.getEncoder(modelIdentifier);
1721
- return encoder.encode(text).length;
1722
- }
1723
- static estimateMessageTokens(message, options = {}) {
1724
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1725
- if (message.content) {
1726
- totalTokens += this.estimateTokens(String(message.content), options);
1727
- }
1728
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1729
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1730
- for (const toolCall of toolCalls) {
1731
- totalTokens += toolCallOverhead;
1732
- const fn = toolCall["function"];
1733
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1734
- const fnRecord = fn;
1735
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1736
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1737
- }
1738
- }
1739
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1740
- if (toolCallId) {
1741
- totalTokens += this.estimateTokens(toolCallId, options);
1742
- }
1743
- return totalTokens;
1986
+ return void 0;
1744
1987
  }
1745
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1746
- return this.estimateMessageTokens(message, {
1747
- encoding: modelIdentifier,
1748
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1749
- });
1988
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
1989
+ return parsed.success ? parsed.data : void 0;
1990
+ }
1991
+ function resolveToolCalls(response) {
1992
+ if (!response || typeof response === "string") {
1993
+ return void 0;
1750
1994
  }
1751
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1752
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1995
+ return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
1996
+ }
1997
+ function resolveReasoningDetails(response) {
1998
+ if (!response || typeof response === "string") {
1999
+ return void 0;
1753
2000
  }
1754
- static extractToolCallsForTokenEstimate(message) {
1755
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1756
- if (Array.isArray(direct)) return direct;
1757
- const metadata = "metadata" in message ? message.metadata : void 0;
1758
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1759
- const metadataRecord = metadata;
1760
- const metadataToolCalls = metadataRecord["tool_calls"];
1761
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2001
+ return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2002
+ }
2003
+ function resolveToolNamesForAudit(ctx) {
2004
+ if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2005
+ return [];
1762
2006
  }
1763
- static extractToolCallIdForTokenEstimate(message) {
1764
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1765
- return message.tool_call_id;
1766
- }
1767
- const metadata = "metadata" in message ? message.metadata : void 0;
1768
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1769
- const metadataRecord = metadata;
1770
- const toolCallId = metadataRecord["tool_call_id"];
1771
- return typeof toolCallId === "string" ? toolCallId : void 0;
2007
+ return ctx.toolSchemas.map((tool) => tool.function.name);
2008
+ }
2009
+ function recordBeforeContextManager(params) {
2010
+ }
2011
+ function recordAfterContextManager(params) {
2012
+ }
2013
+ function recordAfterContextManagerOnSystemReminderHit(params) {
2014
+ }
2015
+ function recordToolProtocolError(params) {
2016
+ }
2017
+ function recordRunTranscript(params) {
2018
+ }
2019
+
2020
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2021
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2022
+ if (stage.id === "build_context") {
2023
+ recordBeforeContextManager({
2024
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2025
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2026
+ });
1772
2027
  }
1773
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1774
- if (!text || maxTokens <= 0) return "";
1775
- const encoder = this.getEncoder(modelIdentifier);
1776
- const tokens = encoder.encode(text);
1777
- if (tokens.length <= maxTokens) {
1778
- return text;
1779
- }
1780
- let truncatedTokens;
1781
- const ellipsis = "...";
1782
- switch (strategy) {
1783
- case "start":
1784
- truncatedTokens = tokens.slice(0, maxTokens);
1785
- return encoder.decode(truncatedTokens) + ellipsis;
1786
- case "end":
1787
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1788
- return ellipsis + encoder.decode(truncatedTokens);
1789
- case "middle": {
1790
- const half = Math.floor(maxTokens / 2);
1791
- const head = tokens.slice(0, half);
1792
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1793
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1794
- }
1795
- default:
1796
- truncatedTokens = tokens.slice(0, maxTokens);
1797
- return encoder.decode(truncatedTokens) + ellipsis;
1798
- }
2028
+ await next();
2029
+ if (stage.id !== "apply_system_reminder") {
2030
+ return;
1799
2031
  }
1800
- static cleanup() {
1801
- for (const encoder of this.encoderCache.values()) {
1802
- encoder.free();
1803
- }
1804
- this.encoderCache.clear();
2032
+ resolveToolNamesForAudit(ctx);
2033
+ recordAfterContextManager({
2034
+ mode: ctx.mode,
2035
+ llmMessages: ctx.llmMessages,
2036
+ contextTrace: ctx.contextTrace
2037
+ });
2038
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2039
+ recordAfterContextManagerOnSystemReminderHit({
2040
+ mode: ctx.mode,
2041
+ llmMessages: ctx.llmMessages,
2042
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2043
+ contextTrace: ctx.contextTrace
2044
+ });
1805
2045
  }
1806
2046
  };
1807
- function normalizePositiveNumber(value, fallback) {
1808
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2047
+ var als = new AsyncLocalStorage();
2048
+ function readTokenCount(record, key) {
2049
+ const value = record[key];
2050
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1809
2051
  }
1810
- function normalizeNonNegativeInteger(value, fallback) {
1811
- if (typeof value !== "number" || !Number.isFinite(value)) {
1812
- return fallback;
1813
- }
1814
- return Math.max(0, Math.floor(value));
2052
+ function readRecord(record, key) {
2053
+ const value = record[key];
2054
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2055
+ return Object.fromEntries(Object.entries(value));
1815
2056
  }
1816
- var als = new AsyncLocalStorage();
1817
- function normalizeLlmUsage(usage) {
2057
+ function normalizedUsageFromCanonical(canonicalUsage) {
2058
+ return {
2059
+ promptTokens: canonicalUsage.inputTokens,
2060
+ completionTokens: canonicalUsage.outputTokens,
2061
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2062
+ canonicalUsage
2063
+ };
2064
+ }
2065
+ function normalizeCanonicalLlmUsage(usage) {
1818
2066
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1819
2067
  const rec = usage;
1820
- const promptTokensRaw = rec["prompt_tokens"];
1821
- const completionTokensRaw = rec["completion_tokens"];
1822
- const totalTokensRaw = rec["total_tokens"];
1823
- const tokensRaw = rec["tokens"];
1824
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1825
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1826
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1827
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1828
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1829
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1830
- return { promptTokens, completionTokens, totalTokens };
2068
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2069
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2070
+ if (inputTokens === void 0 || outputTokens === void 0) {
2071
+ return void 0;
2072
+ }
2073
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2074
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2075
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2076
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2077
+ const totalTokens = readTokenCount(rec, "total_tokens");
2078
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2079
+ return void 0;
2080
+ }
2081
+ return {
2082
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2083
+ outputTokens,
2084
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2085
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2086
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2087
+ source: "provider-response-usage",
2088
+ confidence: "actual",
2089
+ rawUsage: usage
2090
+ };
2091
+ }
2092
+ function normalizeLlmUsage(usage) {
2093
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2094
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1831
2095
  }
1832
2096
  function recordLlmCallTelemetry(entry) {
1833
2097
  const store = als.getStore();
@@ -1841,17 +2105,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1841
2105
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1842
2106
  return;
1843
2107
  }
1844
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2108
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2109
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1845
2110
  const respText = extractResponseText(ctx.llmResp);
1846
2111
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1847
2112
  try {
1848
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1849
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1850
- return {
1851
- promptTokens,
1852
- completionTokens,
1853
- totalTokens: promptTokens + completionTokens
1854
- };
2113
+ const promptTokens = ctx.llmMessages.reduce(
2114
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2115
+ 0
2116
+ );
2117
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2118
+ return normalizedUsageFromCanonical({
2119
+ inputTokens: promptTokens,
2120
+ outputTokens: completionTokens,
2121
+ totalTokens: promptTokens + completionTokens,
2122
+ source: "local-estimate",
2123
+ confidence: "estimate"
2124
+ });
1855
2125
  } catch {
1856
2126
  return void 0;
1857
2127
  }
@@ -1861,7 +2131,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1861
2131
  stream: ctx.input.stream === true,
1862
2132
  startedAt: ctx.llmCallStartedAt,
1863
2133
  durationMs: ctx.llmCallDurationMs,
1864
- usage: normalizedUsage
2134
+ usage: normalizedUsage,
2135
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1865
2136
  });
1866
2137
  ctx.telemetry.emit({
1867
2138
  kind: "llm_call",
@@ -1869,6 +2140,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1869
2140
  stream: ctx.input.stream === true,
1870
2141
  durationMs: ctx.llmCallDurationMs,
1871
2142
  usage: normalizedUsage,
2143
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1872
2144
  scope: {
1873
2145
  conversationId: ctx.conversationId || void 0,
1874
2146
  turnId: ctx.turnId,
@@ -2012,10 +2284,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2012
2284
  return [
2013
2285
  `\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`,
2014
2286
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2015
- "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",
2287
+ "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",
2016
2288
  `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`,
2017
2289
  ' \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',
2018
- "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"
2290
+ "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"
2019
2291
  ].join("\n");
2020
2292
  };
2021
2293
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2323,6 +2595,219 @@ function createApplySystemReminderStage() {
2323
2595
  };
2324
2596
  }
2325
2597
 
2598
+ // src/runtime-kernel/token-accounting/index.ts
2599
+ var token_accounting_exports = {};
2600
+ __export(token_accounting_exports, {
2601
+ addLedgerAggregate: () => addLedgerAggregate,
2602
+ addUsageTotals: () => addUsageTotals,
2603
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
2604
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
2605
+ computeCost: () => computeCost,
2606
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
2607
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
2608
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
2609
+ });
2610
+
2611
+ // src/runtime-kernel/token-accounting/functions.ts
2612
+ var EMPTY_LEDGER_AGGREGATE = {
2613
+ contextTokens: 0,
2614
+ entryCount: 0,
2615
+ llmCallCount: 0,
2616
+ contextComponentCount: 0
2617
+ };
2618
+ var TOKEN_PRICE_UNIT = 1e6;
2619
+ function sumReportedOptional(values) {
2620
+ const reported = values.filter((value) => value !== void 0);
2621
+ if (reported.length === 0) {
2622
+ return void 0;
2623
+ }
2624
+ return reported.reduce((total, value) => total + value, 0);
2625
+ }
2626
+ function sumTotalTokens(usages) {
2627
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
2628
+ return void 0;
2629
+ }
2630
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
2631
+ }
2632
+ function aggregateCanonicalUsage(usages) {
2633
+ if (usages.length === 0) {
2634
+ return void 0;
2635
+ }
2636
+ return {
2637
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
2638
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
2639
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
2640
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
2641
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
2642
+ totalTokens: sumTotalTokens(usages),
2643
+ usageCount: usages.length
2644
+ };
2645
+ }
2646
+ function createLlmUsageLedgerEntry(input) {
2647
+ return {
2648
+ ...input,
2649
+ kind: "llm-usage"
2650
+ };
2651
+ }
2652
+ function createContextComponentLedgerEntry(input) {
2653
+ return {
2654
+ ...input,
2655
+ kind: "context-component",
2656
+ components: [...input.components],
2657
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2658
+ };
2659
+ }
2660
+ function addUsageTotals(left, right) {
2661
+ if (!left) {
2662
+ return right;
2663
+ }
2664
+ if (!right) {
2665
+ return left;
2666
+ }
2667
+ return {
2668
+ inputTokens: left.inputTokens + right.inputTokens,
2669
+ outputTokens: left.outputTokens + right.outputTokens,
2670
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
2671
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
2672
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
2673
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
2674
+ usageCount: left.usageCount + right.usageCount
2675
+ };
2676
+ }
2677
+ function addLedgerAggregate(left, right) {
2678
+ return {
2679
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
2680
+ contextTokens: left.contextTokens + right.contextTokens,
2681
+ entryCount: left.entryCount + right.entryCount,
2682
+ llmCallCount: left.llmCallCount + right.llmCallCount,
2683
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
2684
+ };
2685
+ }
2686
+ function aggregateTokenLedgerEntries(entries) {
2687
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
2688
+ return entries.reduce((aggregate, entry) => {
2689
+ if (entry.kind === "llm-usage") {
2690
+ return {
2691
+ ...aggregate,
2692
+ entryCount: aggregate.entryCount + 1,
2693
+ llmCallCount: aggregate.llmCallCount + 1
2694
+ };
2695
+ }
2696
+ return {
2697
+ ...aggregate,
2698
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
2699
+ entryCount: aggregate.entryCount + 1,
2700
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
2701
+ };
2702
+ }, {
2703
+ ...EMPTY_LEDGER_AGGREGATE,
2704
+ llmUsage: aggregateCanonicalUsage(llmUsages)
2705
+ });
2706
+ }
2707
+ function createRunTokenUsageAggregate(input) {
2708
+ const children = input.childAggregates?.reduce(
2709
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
2710
+ EMPTY_LEDGER_AGGREGATE
2711
+ );
2712
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
2713
+ }
2714
+ function componentCost(tokens, pricePerMillion) {
2715
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
2716
+ }
2717
+ function needsPrice(tokens) {
2718
+ return tokens !== void 0 && tokens > 0;
2719
+ }
2720
+ function missingPriceComponents(usage, pricing) {
2721
+ const missing = [];
2722
+ if (!pricing) {
2723
+ if (needsPrice(usage.inputTokens)) {
2724
+ missing.push("input");
2725
+ }
2726
+ if (needsPrice(usage.outputTokens)) {
2727
+ missing.push("output");
2728
+ }
2729
+ if (needsPrice(usage.reasoningTokens)) {
2730
+ missing.push("reasoning");
2731
+ }
2732
+ if (needsPrice(usage.cacheReadTokens)) {
2733
+ missing.push("cacheRead");
2734
+ }
2735
+ if (needsPrice(usage.cacheWriteTokens)) {
2736
+ missing.push("cacheWrite");
2737
+ }
2738
+ return missing;
2739
+ }
2740
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
2741
+ missing.push("input");
2742
+ }
2743
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
2744
+ missing.push("output");
2745
+ }
2746
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
2747
+ missing.push("reasoning");
2748
+ }
2749
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
2750
+ missing.push("cacheRead");
2751
+ }
2752
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
2753
+ missing.push("cacheWrite");
2754
+ }
2755
+ return missing;
2756
+ }
2757
+ function reportedComponentCost(tokens, pricePerMillion) {
2758
+ if (tokens === void 0) {
2759
+ return void 0;
2760
+ }
2761
+ if (tokens === 0) {
2762
+ return 0;
2763
+ }
2764
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
2765
+ }
2766
+ function requiredComponentCost(tokens, pricePerMillion) {
2767
+ if (tokens === 0) {
2768
+ return 0;
2769
+ }
2770
+ return componentCost(tokens, pricePerMillion ?? 0);
2771
+ }
2772
+ function sumComputedCosts(costs) {
2773
+ let total = 0;
2774
+ for (const cost of costs) {
2775
+ total += cost ?? 0;
2776
+ }
2777
+ return total;
2778
+ }
2779
+ function computeCost(usage, pricing) {
2780
+ const missing = missingPriceComponents(usage, pricing);
2781
+ if (!pricing || missing.length > 0) {
2782
+ return {
2783
+ status: "unknown",
2784
+ ...pricing ? { currency: pricing.currency } : {},
2785
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
2786
+ };
2787
+ }
2788
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
2789
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
2790
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
2791
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
2792
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
2793
+ return {
2794
+ status: "computed",
2795
+ currency: pricing.currency,
2796
+ inputCost,
2797
+ outputCost,
2798
+ reasoningCost,
2799
+ cacheReadCost,
2800
+ cacheWriteCost,
2801
+ totalCost: sumComputedCosts([
2802
+ inputCost,
2803
+ outputCost,
2804
+ reasoningCost,
2805
+ cacheReadCost,
2806
+ cacheWriteCost
2807
+ ])
2808
+ };
2809
+ }
2810
+
2326
2811
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2327
2812
  var logger4 = new Logger("GraphAgentExecutor");
2328
2813
  function createBuildContextStage(dependencies) {
@@ -2339,6 +2824,23 @@ function createBuildContextStage(dependencies) {
2339
2824
  ctx.mode = contextBuildResult.mode;
2340
2825
  ctx.llmMessages = contextBuildResult.llmMessages;
2341
2826
  ctx.contextTrace = contextBuildResult.contextTrace;
2827
+ if (contextBuildResult.tokenEstimate) {
2828
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2829
+ ctx.telemetry.emit({
2830
+ kind: "context_build",
2831
+ modelId: ctx.modelId,
2832
+ mode: contextBuildResult.mode,
2833
+ tokenEstimate: contextBuildResult.tokenEstimate,
2834
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2835
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2836
+ scope: {
2837
+ conversationId: ctx.conversationId,
2838
+ runId: ctx.input.toolContext?.runId,
2839
+ parentRunId: ctx.input.toolContext?.parentRunId,
2840
+ turnId: ctx.turnId
2841
+ }
2842
+ });
2843
+ }
2342
2844
  for (const event of contextBuildResult.summaryEvents) {
2343
2845
  if (!isHistorySummaryEvent(event)) {
2344
2846
  continue;
@@ -2353,6 +2855,24 @@ function createBuildContextStage(dependencies) {
2353
2855
  }
2354
2856
  };
2355
2857
  }
2858
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2859
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2860
+ if (keptComponents.length === 0) {
2861
+ return void 0;
2862
+ }
2863
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2864
+ const createdAt = Date.now();
2865
+ return createContextComponentLedgerEntry({
2866
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2867
+ conversationId: ctx.conversationId,
2868
+ runId,
2869
+ parentRunId: ctx.input.toolContext?.parentRunId,
2870
+ turnId: ctx.turnId,
2871
+ route: contextBuildResult.tokenEstimate?.route,
2872
+ createdAt,
2873
+ components: keptComponents
2874
+ });
2875
+ }
2356
2876
 
2357
2877
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2358
2878
  function createBuildDecisionStage(dependencies) {
@@ -2596,6 +3116,7 @@ var GraphAgentExecutor = class {
2596
3116
  modelCatalog;
2597
3117
  telemetryPort;
2598
3118
  auditPort;
3119
+ tokenizer;
2599
3120
  stages;
2600
3121
  middlewares;
2601
3122
  constructor(dependencies) {
@@ -2609,6 +3130,7 @@ var GraphAgentExecutor = class {
2609
3130
  });
2610
3131
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2611
3132
  this.auditPort = dependencies.auditPort ?? noopAudit;
3133
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2612
3134
  this.stages = [
2613
3135
  createPrepareCallStage({
2614
3136
  modelResolver: this.modelResolver,
@@ -2652,7 +3174,8 @@ var GraphAgentExecutor = class {
2652
3174
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2653
3175
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2654
3176
  telemetry: this.telemetryPort,
2655
- audit: this.auditPort
3177
+ audit: this.auditPort,
3178
+ tokenizer: this.tokenizer
2656
3179
  };
2657
3180
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2658
3181
  stream: input.stream === true,
@@ -3617,11 +4140,11 @@ function buildToolOutputUiMeta(params) {
3617
4140
  }
3618
4141
  async function applyObservationGovernance(params) {
3619
4142
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3620
- return;
4143
+ return {};
3621
4144
  }
3622
4145
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3623
4146
  if (!policy.enabled) {
3624
- return;
4147
+ return {};
3625
4148
  }
3626
4149
  const truncated = await params.observationPreview.truncateObservation({
3627
4150
  context: params.toolContext,
@@ -3635,13 +4158,37 @@ async function applyObservationGovernance(params) {
3635
4158
  })
3636
4159
  });
3637
4160
  if (!truncated.truncated) {
3638
- return;
4161
+ return {};
3639
4162
  }
3640
4163
  params.parsed["observation"] = truncated.preview;
3641
4164
  const data = params.parsed["data"];
3642
4165
  if (isRecord9(data) && !("tool_output_store" in data)) {
3643
4166
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3644
4167
  }
4168
+ return {
4169
+ observationTruncation: buildObservationTruncationMeta({
4170
+ originalText: params.structuredObservation,
4171
+ previewText: truncated.preview,
4172
+ originalChars: truncated.originalChars,
4173
+ previewChars: truncated.previewChars,
4174
+ originalLines: truncated.originalLines,
4175
+ previewLines: truncated.previewLines
4176
+ })
4177
+ };
4178
+ }
4179
+ function buildObservationTruncationMeta(input) {
4180
+ return {
4181
+ originalChars: input.originalChars ?? input.originalText.length,
4182
+ previewChars: input.previewChars ?? input.previewText.length,
4183
+ originalLines: input.originalLines ?? countLines(input.originalText),
4184
+ previewLines: input.previewLines ?? countLines(input.previewText)
4185
+ };
4186
+ }
4187
+ function countLines(value) {
4188
+ if (value.length === 0) {
4189
+ return 0;
4190
+ }
4191
+ return value.split(/\r\n|\r|\n/).length;
3645
4192
  }
3646
4193
 
3647
4194
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4604,7 +5151,7 @@ var ToolNode = class {
4604
5151
  parentRunId: context.toolContext.parentRunId
4605
5152
  });
4606
5153
  applyProtocolFuseState(context.local);
4607
- await applyObservationGovernance({
5154
+ const observationGovernance = await applyObservationGovernance({
4608
5155
  parsed: context.parsed,
4609
5156
  toolName: context.toolName,
4610
5157
  toolContext: context.toolContext,
@@ -4631,6 +5178,12 @@ var ToolNode = class {
4631
5178
  runtimeToolOutput,
4632
5179
  execIdempotency: context.exec.idempotency
4633
5180
  });
5181
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5182
+ runtimeToolOutput.metadata = {
5183
+ ...runtimeToolOutput.metadata ?? {},
5184
+ observationTruncation: observationGovernance.observationTruncation
5185
+ };
5186
+ }
4634
5187
  const remainingCalls = context.calls.slice(1);
4635
5188
  context.state.local = buildSuccessLocalState({
4636
5189
  local: context.local,
@@ -6465,6 +7018,7 @@ async function callLlmStream(params) {
6465
7018
  const streamAnswerId = generateMessageId();
6466
7019
  let streamChunkSeq = 0;
6467
7020
  let capturedUsage = void 0;
7021
+ let capturedCanonicalUsage = void 0;
6468
7022
  const toolAccumulator = new ToolCallStreamAccumulator([
6469
7023
  "markdown_edit",
6470
7024
  "text_to_image",
@@ -6523,6 +7077,10 @@ async function callLlmStream(params) {
6523
7077
  if (typeof chunk !== "object" || chunk === null) {
6524
7078
  return;
6525
7079
  }
7080
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7081
+ if (parsedCanonicalUsage.success) {
7082
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7083
+ }
6526
7084
  if (chunk.content) {
6527
7085
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6528
7086
  fullResponse += chunk.content;
@@ -6607,6 +7165,12 @@ async function callLlmStream(params) {
6607
7165
  const onUsage = (usage) => {
6608
7166
  capturedUsage = usage;
6609
7167
  };
7168
+ const onCanonicalUsage = (usage) => {
7169
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7170
+ if (parsed.success) {
7171
+ capturedCanonicalUsage = parsed.data;
7172
+ }
7173
+ };
6610
7174
  await aiEngine.chatCompletionStream(
6611
7175
  modelId,
6612
7176
  messages,
@@ -6619,7 +7183,8 @@ async function callLlmStream(params) {
6619
7183
  onError,
6620
7184
  onFinish,
6621
7185
  onThought,
6622
- onUsage
7186
+ onUsage,
7187
+ onCanonicalUsage
6623
7188
  );
6624
7189
  if (streamError) {
6625
7190
  throw streamError;
@@ -6627,12 +7192,13 @@ async function callLlmStream(params) {
6627
7192
  emitThoughtComplete(thoughtSegmenter.finalize());
6628
7193
  const mergedToolCalls = toolAccumulator.getToolCalls();
6629
7194
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6630
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7195
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6631
7196
  return {
6632
7197
  content: fullResponse,
6633
7198
  tool_calls: mergedToolCalls,
6634
7199
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6635
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7200
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7201
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6636
7202
  };
6637
7203
  }
6638
7204
  return fullResponse;
@@ -6682,6 +7248,10 @@ function tryCloudQuotaFallback({
6682
7248
  }
6683
7249
 
6684
7250
  // src/runtime-kernel/llm/usage-telemetry.ts
7251
+ function parseCanonicalUsage(value) {
7252
+ const parsed = CanonicalLlmUsage.safeParse(value);
7253
+ return parsed.success ? parsed.data : void 0;
7254
+ }
6685
7255
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6686
7256
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6687
7257
  return normalizeCompletionResponse(response);
@@ -6692,6 +7262,7 @@ function normalizeCompletionResponse(response) {
6692
7262
  }
6693
7263
  if (isRecord19(response)) {
6694
7264
  const usage = response["usage"];
7265
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6695
7266
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6696
7267
  if (parsedToolCalls) {
6697
7268
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6699,7 +7270,8 @@ function normalizeCompletionResponse(response) {
6699
7270
  content: typeof response["content"] === "string" ? response["content"] : "",
6700
7271
  tool_calls: parsedToolCalls,
6701
7272
  reasoning_details: reasoningDetails,
6702
- ...usage !== void 0 ? { usage } : {}
7273
+ ...usage !== void 0 ? { usage } : {},
7274
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6703
7275
  };
6704
7276
  }
6705
7277
  }
@@ -6709,10 +7281,12 @@ function normalizeCompletionResponse(response) {
6709
7281
  if (typeof response === "object") {
6710
7282
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6711
7283
  const usage = response["usage"];
7284
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6712
7285
  return {
6713
7286
  content: typeof response["content"] === "string" ? response["content"] : "",
6714
7287
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6715
- ...usage !== void 0 ? { usage } : {}
7288
+ ...usage !== void 0 ? { usage } : {},
7289
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6716
7290
  };
6717
7291
  }
6718
7292
  if (isRecord19(response)) {
@@ -6966,30 +7540,6 @@ var LlmCaller = class {
6966
7540
  }
6967
7541
  };
6968
7542
 
6969
- // src/shared/defaultTokenizerPort.ts
6970
- var DefaultTokenizerPort = class {
6971
- constructor(config = {}) {
6972
- this.config = config;
6973
- }
6974
- config;
6975
- estimateText(text, _modelId) {
6976
- return TokenCalculator.estimateTokens(text, {
6977
- encoding: this.config.encoding,
6978
- avgCharsPerToken: this.config.avgCharsPerToken
6979
- });
6980
- }
6981
- estimateMessage(message, _modelId) {
6982
- return TokenCalculator.estimateMessageTokens(message, {
6983
- encoding: this.config.encoding,
6984
- avgCharsPerToken: this.config.avgCharsPerToken,
6985
- toolCallOverhead: this.config.toolCallOverhead
6986
- });
6987
- }
6988
- };
6989
- function createDefaultTokenizerPort(config = {}) {
6990
- return new DefaultTokenizerPort(config);
6991
- }
6992
-
6993
7543
  // src/runtime-kernel/child-runs/index.ts
6994
7544
  var child_runs_exports = {};
6995
7545
  __export(child_runs_exports, {
@@ -8599,6 +9149,7 @@ __export(telemetry_exports, {
8599
9149
  var TELEMETRY_EVENT_KINDS = [
8600
9150
  "llm_call",
8601
9151
  "tool_call",
9152
+ "context_build",
8602
9153
  "graph_node",
8603
9154
  "run_lifecycle"
8604
9155
  ];
@@ -8774,6 +9325,6 @@ function createGraphLoopHarness(options) {
8774
9325
  };
8775
9326
  }
8776
9327
 
8777
- export { AnswerNode, AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, CommonParameterTypes, CompositeAuditPort, ContextCheckpointTool, DEFAULT_CONTEXT_CHECKPOINT_TOOL_NAME, DefaultTokenizerPort, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventBusSubRunTracePublisher, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, LLMPolicyEngine, LlmCaller, LlmNode, MemoryCheckpointer, MemoryEventStore, ModelResolver, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolNode, UserNode, WaitUserNode, agentHasToolTrigger, appendStreamingProviderReasoningDetails, applySystemReminders, audit_exports as audit, budgetWarningTrigger, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, compactProviderReasoningDetails, compactReasoningDetailsInValue, computeToolIdempotencyKey, consoleAudit, contextBudgetWarningTemplate, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextCheckpointTool, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createGraphLoopHarness, createMonotonicEventIdFactory, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, lastStepsHintTemplate, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, periodicTaskstateReflectionTemplate, phaseEqualsTrigger, readContextCheckpointToolName, readNonEmptyStrings, readToolContextModelId, readToolContextPersistedHistory, readToolContextRunContext, readToolContextUserQuery, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
9328
+ export { AnswerNode, AuditEnvelopePersistenceError, BUILTIN_SYSTEM_REMINDER_TEMPLATES, BUILTIN_SYSTEM_REMINDER_TRIGGERS, BaseTool, CommonParameterTypes, CompositeAuditPort, ContextCheckpointTool, DEFAULT_CONTEXT_CHECKPOINT_TOOL_NAME, DefaultTokenizerPort, ENGINE_ERROR_CODES, ENGINE_STATE_SCHEMA_VERSION, EventBusSubRunTracePublisher, EventStoreAuditPort, FileAuditPort, GraphAgentExecutor, GraphExecutor, LLMPolicyEngine, LlmCaller, LlmNode, MemoryCheckpointer, MemoryEventStore, ModelResolver, SYSTEM_REMINDER_RULES, SystemReminderRegistry, ToolNode, UserNode, WaitUserNode, addLedgerAggregate, addUsageTotals, agentHasToolTrigger, aggregateCanonicalUsage, aggregateTokenLedgerEntries, appendStreamingProviderReasoningDetails, applySystemReminders, audit_exports as audit, budgetWarningTrigger, child_run_trace_exports as childRunTrace, child_runs_exports as childRuns, compactProviderReasoningDetails, compactReasoningDetailsInValue, computeCost, computeToolIdempotencyKey, consoleAudit, contextBudgetWarningTemplate, copyToolContextRuntimeCapability, countToolCallsInCurrentRequest, createCompositeAudit, createConsoleAudit, createContextCheckpointTool, createContextComponentLedgerEntry, createDefaultGraphExecutor, createDefaultSystemReminderRegistry, createDefaultTokenizerPort, createEventStoreAudit, createFileAudit, createGraphLoopHarness, createLlmUsageLedgerEntry, createMonotonicEventIdFactory, createRunTokenUsageAggregate, createSystemReminderRules, defaultPolicyEngine, defaultSystemReminderRegistry, emitAuditEnvelope, emitSandboxDecisionAudit, enrichment_exports as enrichment, ensureToolContextRuntimeCapability, events_exports as events, execution_exports as execution, findCachedToolOutputByIdempotencyKey, getToolContextRuntimeBinding, graph_engine_exports as graph, lastStepsHintTemplate, llm_exports as llm, maxStepsForceFinalAnswerTemplate, noopAudit, normalizeToolArgs, periodicTaskstateReflectionTemplate, phaseEqualsTrigger, readContextCheckpointToolName, readNonEmptyStrings, readToolContextModelId, readToolContextPersistedHistory, readToolContextRunContext, readToolContextUserQuery, readToolContextWorkingHistory, remainingStepsLeqTrigger, requestEnricherRegistry, run_context_exports as runContext, run_supervisor_exports as runSupervisor, stepCountModuloTrigger, stripRuntimeReservedToolContextPatch, summarizeCheckpoint, system_reminder_exports as systemReminder, telemetry_exports as telemetry, toDisplayStep, token_accounting_exports as tokenAccounting, toolCallStreakTemplate, toolCallStreakTrigger, tools_exports as tools };
8778
9329
  //# sourceMappingURL=runtime-kernel.js.map
8779
9330
  //# sourceMappingURL=runtime-kernel.js.map