@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
@@ -44,6 +44,12 @@ zod.z.object({
44
44
  args: zod.z.record(zod.z.unknown()).optional(),
45
45
  tool_call_id: zod.z.string()
46
46
  });
47
+ var ObservationTruncationMeta = zod.z.object({
48
+ originalChars: zod.z.number().int().nonnegative(),
49
+ previewChars: zod.z.number().int().nonnegative(),
50
+ originalLines: zod.z.number().int().nonnegative().optional(),
51
+ previewLines: zod.z.number().int().nonnegative().optional()
52
+ });
47
53
  var ImageInfoMeta = zod.z.object({
48
54
  url: zod.z.string().optional(),
49
55
  width: zod.z.number().int().positive().optional(),
@@ -75,6 +81,7 @@ var PersistentMetadata = zod.z.object({
75
81
  tool_name: zod.z.string().optional(),
76
82
  args: zod.z.record(zod.z.unknown()).optional(),
77
83
  tool_call_id: zod.z.string().optional(),
84
+ observationTruncation: ObservationTruncationMeta.optional(),
78
85
  raw_output: zod.z.string().optional(),
79
86
  image_info: ImageInfoMeta.optional(),
80
87
  taskType: zod.z.string().optional(),
@@ -221,7 +228,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
221
228
  var AgentSpecTokenEstimationPolicy = zod.z.object({
222
229
  encoding: zod.z.string().min(1).optional(),
223
230
  avgCharsPerToken: zod.z.number().positive().optional(),
224
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
231
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
232
+ calibration: zod.z.object({
233
+ enabled: zod.z.boolean().optional(),
234
+ minSamples: zod.z.number().int().positive().optional(),
235
+ minCoefficient: zod.z.number().positive().optional(),
236
+ maxCoefficient: zod.z.number().positive().optional()
237
+ }).optional(),
238
+ remoteCount: zod.z.object({
239
+ enabled: zod.z.boolean().optional(),
240
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
241
+ }).optional()
225
242
  });
226
243
  var AgentSpecSystemReminderTrigger = zod.z.object({
227
244
  kind: zod.z.string().min(1),
@@ -1021,6 +1038,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1021
1038
  error,
1022
1039
  ...options
1023
1040
  });
1041
+ var TokenCountSource = zod.z.enum([
1042
+ "local-estimate",
1043
+ "provider-preflight-count",
1044
+ "provider-response-usage",
1045
+ "host-supplied",
1046
+ "test-fixture"
1047
+ ]);
1048
+ var TokenCountConfidence = zod.z.enum([
1049
+ "estimate",
1050
+ "provider-estimate",
1051
+ "actual"
1052
+ ]);
1053
+ var TokenRouteCapabilities = zod.z.object({
1054
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1055
+ supportsResponseUsage: zod.z.boolean().optional(),
1056
+ supportsImageInput: zod.z.boolean().optional(),
1057
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1058
+ supportsReasoningTokens: zod.z.boolean().optional()
1059
+ });
1060
+ var TokenRoute = zod.z.object({
1061
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1062
+ 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"),
1063
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1064
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1065
+ capabilities: TokenRouteCapabilities.optional()
1066
+ });
1067
+ var tokenCount = zod.z.number().int().nonnegative();
1068
+ var CanonicalLlmUsage = zod.z.object({
1069
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1070
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1071
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1072
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1073
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1074
+ 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"),
1075
+ source: TokenCountSource,
1076
+ confidence: TokenCountConfidence,
1077
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1078
+ });
1079
+ var tokenCount2 = zod.z.number().int().nonnegative();
1080
+ var tokenPrice = zod.z.number().finite().nonnegative();
1081
+ zod.z.enum([
1082
+ "llm-usage",
1083
+ "context-component"
1084
+ ]);
1085
+ var ContextTokenComponentKind = zod.z.enum([
1086
+ "system",
1087
+ "user",
1088
+ "assistant",
1089
+ "tool",
1090
+ "context-injection",
1091
+ "history-summary",
1092
+ "working-memory",
1093
+ "fence",
1094
+ "system-reminder",
1095
+ "other"
1096
+ ]);
1097
+ var TokenUsageTotals = zod.z.object({
1098
+ inputTokens: tokenCount2,
1099
+ outputTokens: tokenCount2,
1100
+ reasoningTokens: tokenCount2.optional(),
1101
+ cacheReadTokens: tokenCount2.optional(),
1102
+ cacheWriteTokens: tokenCount2.optional(),
1103
+ totalTokens: tokenCount2.optional(),
1104
+ usageCount: zod.z.number().int().nonnegative()
1105
+ });
1106
+ var ContextTokenComponent = zod.z.object({
1107
+ componentId: zod.z.string().min(1),
1108
+ kind: ContextTokenComponentKind,
1109
+ tokens: tokenCount2,
1110
+ source: TokenCountSource,
1111
+ confidence: TokenCountConfidence,
1112
+ label: zod.z.string().optional(),
1113
+ messageId: zod.z.string().optional(),
1114
+ role: zod.z.string().optional(),
1115
+ action: zod.z.string().optional(),
1116
+ kept: zod.z.boolean().optional(),
1117
+ truncatedAtExecution: zod.z.boolean().optional(),
1118
+ originalTokensEstimate: tokenCount2.optional(),
1119
+ droppedTokensEstimate: tokenCount2.optional()
1120
+ });
1121
+ var TokenLedgerEntryBase = zod.z.object({
1122
+ id: zod.z.string().min(1),
1123
+ runId: zod.z.string().optional(),
1124
+ parentRunId: zod.z.string().optional(),
1125
+ conversationId: zod.z.string().optional(),
1126
+ turnId: zod.z.string().optional(),
1127
+ stepId: zod.z.string().optional(),
1128
+ route: TokenRoute.optional(),
1129
+ createdAt: zod.z.number().int().nonnegative().optional()
1130
+ });
1131
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1132
+ kind: zod.z.literal("llm-usage"),
1133
+ modelId: zod.z.string().optional(),
1134
+ usage: CanonicalLlmUsage
1135
+ });
1136
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1137
+ kind: zod.z.literal("context-component"),
1138
+ components: zod.z.array(ContextTokenComponent),
1139
+ totalTokens: tokenCount2
1140
+ });
1141
+ zod.z.discriminatedUnion("kind", [
1142
+ LlmUsageTokenLedgerEntry,
1143
+ ContextComponentTokenLedgerEntry
1144
+ ]);
1145
+ var TokenLedgerAggregate = zod.z.object({
1146
+ llmUsage: TokenUsageTotals.optional(),
1147
+ contextTokens: tokenCount2,
1148
+ entryCount: zod.z.number().int().nonnegative(),
1149
+ llmCallCount: zod.z.number().int().nonnegative(),
1150
+ contextComponentCount: zod.z.number().int().nonnegative()
1151
+ });
1152
+ zod.z.object({
1153
+ /**
1154
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1155
+ */
1156
+ own: TokenLedgerAggregate,
1157
+ children: TokenLedgerAggregate.optional()
1158
+ });
1159
+ var TokenCostComponent = zod.z.enum([
1160
+ "input",
1161
+ "output",
1162
+ "reasoning",
1163
+ "cacheRead",
1164
+ "cacheWrite"
1165
+ ]);
1166
+ zod.z.object({
1167
+ currency: zod.z.string().min(1),
1168
+ unit: zod.z.literal("per_1m_tokens"),
1169
+ input: tokenPrice.optional(),
1170
+ output: tokenPrice.optional(),
1171
+ reasoning: tokenPrice.optional(),
1172
+ cacheRead: tokenPrice.optional(),
1173
+ cacheWrite: tokenPrice.optional()
1174
+ });
1175
+ zod.z.object({
1176
+ status: zod.z.enum(["computed", "unknown"]),
1177
+ currency: zod.z.string().optional(),
1178
+ inputCost: tokenPrice.optional(),
1179
+ outputCost: tokenPrice.optional(),
1180
+ reasoningCost: tokenPrice.optional(),
1181
+ cacheReadCost: tokenPrice.optional(),
1182
+ cacheWriteCost: tokenPrice.optional(),
1183
+ totalCost: tokenPrice.optional(),
1184
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1185
+ });
1186
+ var tokenCount3 = zod.z.number().int().nonnegative();
1187
+ var actualCalibrationSource = zod.z.enum([
1188
+ "provider-response-usage",
1189
+ "host-supplied",
1190
+ "test-fixture"
1191
+ ]);
1192
+ zod.z.object({
1193
+ route: TokenRoute,
1194
+ localEstimateTokens: tokenCount3,
1195
+ actualInputTokens: tokenCount3,
1196
+ source: actualCalibrationSource,
1197
+ confidence: zod.z.literal("actual"),
1198
+ observedAt: zod.z.number().int().nonnegative().optional(),
1199
+ runId: zod.z.string().optional(),
1200
+ ledgerEntryId: zod.z.string().optional()
1201
+ });
1202
+ zod.z.object({
1203
+ enabled: zod.z.boolean(),
1204
+ applied: zod.z.boolean(),
1205
+ route: TokenRoute.optional(),
1206
+ sampleCount: zod.z.number().int().nonnegative(),
1207
+ coefficient: zod.z.number().positive().optional(),
1208
+ minSamples: zod.z.number().int().positive().optional(),
1209
+ minCoefficient: zod.z.number().positive().optional(),
1210
+ maxCoefficient: zod.z.number().positive().optional(),
1211
+ localEstimateTokens: tokenCount3.optional(),
1212
+ calibratedEstimateTokens: tokenCount3.optional(),
1213
+ deltaTokens: zod.z.number().int().optional(),
1214
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1215
+ });
1216
+ zod.z.object({
1217
+ route: TokenRoute.optional(),
1218
+ localEstimateTokens: tokenCount3,
1219
+ calibratedEstimateTokens: tokenCount3,
1220
+ finalTokens: tokenCount3,
1221
+ source: zod.z.literal("local-estimate"),
1222
+ confidence: zod.z.literal("estimate")
1223
+ });
1024
1224
 
1025
1225
  // src/quickstart/toolSchema.ts
1026
1226
  function serializeToolProperty(property) {
@@ -1672,6 +1872,190 @@ var noopAudit = {
1672
1872
  flush() {
1673
1873
  }
1674
1874
  };
1875
+ var TokenCalculator = class {
1876
+ static BYTES_PER_TOKEN_LATIN = 4;
1877
+ static BYTES_PER_TOKEN_CJK = 3;
1878
+ static OVERHEAD_PER_MESSAGE = 5;
1879
+ static OVERHEAD_PER_TOOL_CALL = 10;
1880
+ static encoderCache = /* @__PURE__ */ new Map();
1881
+ static DEFAULT_ENCODING = "cl100k_base";
1882
+ static SUPPORTED_ENCODINGS = [
1883
+ "gpt2",
1884
+ "r50k_base",
1885
+ "p50k_base",
1886
+ "p50k_edit",
1887
+ "cl100k_base",
1888
+ "o200k_base"
1889
+ ];
1890
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1891
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1892
+ if (this.isSupportedEncodingName(normalized)) {
1893
+ return normalized;
1894
+ }
1895
+ if (normalized.includes("deepseek")) {
1896
+ return "cl100k_base";
1897
+ }
1898
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1899
+ return "o200k_base";
1900
+ }
1901
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1902
+ return "cl100k_base";
1903
+ }
1904
+ return this.DEFAULT_ENCODING;
1905
+ }
1906
+ static isSupportedEncodingName(value) {
1907
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1908
+ }
1909
+ static getEncoder(modelIdentifierOrEncoding) {
1910
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1911
+ const cached = this.encoderCache.get(encodingName);
1912
+ if (cached) {
1913
+ return cached;
1914
+ }
1915
+ const encoder = tiktoken.get_encoding(encodingName);
1916
+ this.encoderCache.set(encodingName, encoder);
1917
+ return encoder;
1918
+ }
1919
+ static estimateTokensRough(text, _modelIdentifier) {
1920
+ if (!text) return 0;
1921
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1922
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1923
+ const byteLength = new TextEncoder().encode(text).length;
1924
+ return Math.ceil(byteLength / ratio);
1925
+ }
1926
+ static estimateTokens(text, options = {}) {
1927
+ if (!text) return 0;
1928
+ if (options.encoding) {
1929
+ try {
1930
+ return this.estimateTokensPrecise(text, options.encoding);
1931
+ } catch {
1932
+ }
1933
+ }
1934
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1935
+ return Math.ceil(text.length / avgCharsPerToken);
1936
+ }
1937
+ static estimateTokensPrecise(text, modelIdentifier) {
1938
+ if (!text) return 0;
1939
+ const encoder = this.getEncoder(modelIdentifier);
1940
+ return encoder.encode(text).length;
1941
+ }
1942
+ static estimateMessageTokens(message, options = {}) {
1943
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1944
+ if (message.content) {
1945
+ totalTokens += this.estimateTokens(String(message.content), options);
1946
+ }
1947
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1948
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1949
+ for (const toolCall of toolCalls) {
1950
+ totalTokens += toolCallOverhead;
1951
+ const fn = toolCall["function"];
1952
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1953
+ const fnRecord = fn;
1954
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1955
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1956
+ }
1957
+ }
1958
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1959
+ if (toolCallId) {
1960
+ totalTokens += this.estimateTokens(toolCallId, options);
1961
+ }
1962
+ return totalTokens;
1963
+ }
1964
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1965
+ return this.estimateMessageTokens(message, {
1966
+ encoding: modelIdentifier,
1967
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1968
+ });
1969
+ }
1970
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1971
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1972
+ }
1973
+ static extractToolCallsForTokenEstimate(message) {
1974
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1975
+ if (Array.isArray(direct)) return direct;
1976
+ const metadata = "metadata" in message ? message.metadata : void 0;
1977
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1978
+ const metadataRecord = metadata;
1979
+ const metadataToolCalls = metadataRecord["tool_calls"];
1980
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1981
+ }
1982
+ static extractToolCallIdForTokenEstimate(message) {
1983
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1984
+ return message.tool_call_id;
1985
+ }
1986
+ const metadata = "metadata" in message ? message.metadata : void 0;
1987
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1988
+ const metadataRecord = metadata;
1989
+ const toolCallId = metadataRecord["tool_call_id"];
1990
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1991
+ }
1992
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1993
+ if (!text || maxTokens <= 0) return "";
1994
+ const encoder = this.getEncoder(modelIdentifier);
1995
+ const tokens = encoder.encode(text);
1996
+ if (tokens.length <= maxTokens) {
1997
+ return text;
1998
+ }
1999
+ let truncatedTokens;
2000
+ const ellipsis = "...";
2001
+ switch (strategy) {
2002
+ case "start":
2003
+ truncatedTokens = tokens.slice(0, maxTokens);
2004
+ return encoder.decode(truncatedTokens) + ellipsis;
2005
+ case "end":
2006
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
2007
+ return ellipsis + encoder.decode(truncatedTokens);
2008
+ case "middle": {
2009
+ const half = Math.floor(maxTokens / 2);
2010
+ const head = tokens.slice(0, half);
2011
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
2012
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
2013
+ }
2014
+ default:
2015
+ truncatedTokens = tokens.slice(0, maxTokens);
2016
+ return encoder.decode(truncatedTokens) + ellipsis;
2017
+ }
2018
+ }
2019
+ static cleanup() {
2020
+ for (const encoder of this.encoderCache.values()) {
2021
+ encoder.free();
2022
+ }
2023
+ this.encoderCache.clear();
2024
+ }
2025
+ };
2026
+ function normalizePositiveNumber(value, fallback) {
2027
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2028
+ }
2029
+ function normalizeNonNegativeInteger(value, fallback) {
2030
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2031
+ return fallback;
2032
+ }
2033
+ return Math.max(0, Math.floor(value));
2034
+ }
2035
+
2036
+ // src/shared/defaultTokenizerPort.ts
2037
+ var DefaultTokenizerPort = class {
2038
+ constructor(config = {}) {
2039
+ this.config = config;
2040
+ }
2041
+ config;
2042
+ estimateText(text, _modelId) {
2043
+ return TokenCalculator.estimateTokens(text, {
2044
+ encoding: this.config.encoding,
2045
+ avgCharsPerToken: this.config.avgCharsPerToken
2046
+ });
2047
+ }
2048
+ estimateMessage(message, _modelId) {
2049
+ return TokenCalculator.estimateMessageTokens(message, {
2050
+ encoding: this.config.encoding,
2051
+ avgCharsPerToken: this.config.avgCharsPerToken,
2052
+ toolCallOverhead: this.config.toolCallOverhead
2053
+ });
2054
+ }
2055
+ };
2056
+ function createDefaultTokenizerPort(config = {}) {
2057
+ return new DefaultTokenizerPort(config);
2058
+ }
1675
2059
 
1676
2060
  // src/runtime-kernel/llm/toolCallUtils.ts
1677
2061
  function isRecord2(value) {
@@ -1818,6 +2202,13 @@ function resolveUsage(response) {
1818
2202
  }
1819
2203
  return response.usage;
1820
2204
  }
2205
+ function resolveCanonicalUsage(response) {
2206
+ if (!response || typeof response === "string") {
2207
+ return void 0;
2208
+ }
2209
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2210
+ return parsed.success ? parsed.data : void 0;
2211
+ }
1821
2212
  function resolveToolCalls(response) {
1822
2213
  if (!response || typeof response === "string") {
1823
2214
  return void 0;
@@ -1872,181 +2263,54 @@ var contextAuditMiddleware = async (ctx, stage, next) => {
1872
2263
  });
1873
2264
  }
1874
2265
  };
1875
- var TokenCalculator = class {
1876
- static BYTES_PER_TOKEN_LATIN = 4;
1877
- static BYTES_PER_TOKEN_CJK = 3;
1878
- static OVERHEAD_PER_MESSAGE = 5;
1879
- static OVERHEAD_PER_TOOL_CALL = 10;
1880
- static encoderCache = /* @__PURE__ */ new Map();
1881
- static DEFAULT_ENCODING = "cl100k_base";
1882
- static SUPPORTED_ENCODINGS = [
1883
- "gpt2",
1884
- "r50k_base",
1885
- "p50k_base",
1886
- "p50k_edit",
1887
- "cl100k_base",
1888
- "o200k_base"
1889
- ];
1890
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1891
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1892
- if (this.isSupportedEncodingName(normalized)) {
1893
- return normalized;
1894
- }
1895
- if (normalized.includes("deepseek")) {
1896
- return "cl100k_base";
1897
- }
1898
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1899
- return "o200k_base";
1900
- }
1901
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1902
- return "cl100k_base";
1903
- }
1904
- return this.DEFAULT_ENCODING;
1905
- }
1906
- static isSupportedEncodingName(value) {
1907
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1908
- }
1909
- static getEncoder(modelIdentifierOrEncoding) {
1910
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1911
- const cached = this.encoderCache.get(encodingName);
1912
- if (cached) {
1913
- return cached;
1914
- }
1915
- const encoder = tiktoken.get_encoding(encodingName);
1916
- this.encoderCache.set(encodingName, encoder);
1917
- return encoder;
1918
- }
1919
- static estimateTokensRough(text, _modelIdentifier) {
1920
- if (!text) return 0;
1921
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1922
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1923
- const byteLength = new TextEncoder().encode(text).length;
1924
- return Math.ceil(byteLength / ratio);
1925
- }
1926
- static estimateTokens(text, options = {}) {
1927
- if (!text) return 0;
1928
- if (options.encoding) {
1929
- try {
1930
- return this.estimateTokensPrecise(text, options.encoding);
1931
- } catch {
1932
- }
1933
- }
1934
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1935
- return Math.ceil(text.length / avgCharsPerToken);
1936
- }
1937
- static estimateTokensPrecise(text, modelIdentifier) {
1938
- if (!text) return 0;
1939
- const encoder = this.getEncoder(modelIdentifier);
1940
- return encoder.encode(text).length;
1941
- }
1942
- static estimateMessageTokens(message, options = {}) {
1943
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1944
- if (message.content) {
1945
- totalTokens += this.estimateTokens(String(message.content), options);
1946
- }
1947
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1948
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1949
- for (const toolCall of toolCalls) {
1950
- totalTokens += toolCallOverhead;
1951
- const fn = toolCall["function"];
1952
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1953
- const fnRecord = fn;
1954
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1955
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1956
- }
1957
- }
1958
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1959
- if (toolCallId) {
1960
- totalTokens += this.estimateTokens(toolCallId, options);
1961
- }
1962
- return totalTokens;
1963
- }
1964
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1965
- return this.estimateMessageTokens(message, {
1966
- encoding: modelIdentifier,
1967
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1968
- });
1969
- }
1970
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1971
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1972
- }
1973
- static extractToolCallsForTokenEstimate(message) {
1974
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1975
- if (Array.isArray(direct)) return direct;
1976
- const metadata = "metadata" in message ? message.metadata : void 0;
1977
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1978
- const metadataRecord = metadata;
1979
- const metadataToolCalls = metadataRecord["tool_calls"];
1980
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1981
- }
1982
- static extractToolCallIdForTokenEstimate(message) {
1983
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1984
- return message.tool_call_id;
1985
- }
1986
- const metadata = "metadata" in message ? message.metadata : void 0;
1987
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1988
- const metadataRecord = metadata;
1989
- const toolCallId = metadataRecord["tool_call_id"];
1990
- return typeof toolCallId === "string" ? toolCallId : void 0;
1991
- }
1992
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1993
- if (!text || maxTokens <= 0) return "";
1994
- const encoder = this.getEncoder(modelIdentifier);
1995
- const tokens = encoder.encode(text);
1996
- if (tokens.length <= maxTokens) {
1997
- return text;
1998
- }
1999
- let truncatedTokens;
2000
- const ellipsis = "...";
2001
- switch (strategy) {
2002
- case "start":
2003
- truncatedTokens = tokens.slice(0, maxTokens);
2004
- return encoder.decode(truncatedTokens) + ellipsis;
2005
- case "end":
2006
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
2007
- return ellipsis + encoder.decode(truncatedTokens);
2008
- case "middle": {
2009
- const half = Math.floor(maxTokens / 2);
2010
- const head = tokens.slice(0, half);
2011
- const tail = tokens.slice(tokens.length - (maxTokens - half));
2012
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
2013
- }
2014
- default:
2015
- truncatedTokens = tokens.slice(0, maxTokens);
2016
- return encoder.decode(truncatedTokens) + ellipsis;
2017
- }
2018
- }
2019
- static cleanup() {
2020
- for (const encoder of this.encoderCache.values()) {
2021
- encoder.free();
2022
- }
2023
- this.encoderCache.clear();
2024
- }
2025
- };
2026
- function normalizePositiveNumber(value, fallback) {
2027
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2266
+ var als = new async_hooks.AsyncLocalStorage();
2267
+ function readTokenCount(record, key) {
2268
+ const value = record[key];
2269
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2028
2270
  }
2029
- function normalizeNonNegativeInteger(value, fallback) {
2030
- if (typeof value !== "number" || !Number.isFinite(value)) {
2031
- return fallback;
2032
- }
2033
- return Math.max(0, Math.floor(value));
2271
+ function readRecord(record, key) {
2272
+ const value = record[key];
2273
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2274
+ return Object.fromEntries(Object.entries(value));
2034
2275
  }
2035
- var als = new async_hooks.AsyncLocalStorage();
2036
- function normalizeLlmUsage(usage) {
2276
+ function normalizedUsageFromCanonical(canonicalUsage) {
2277
+ return {
2278
+ promptTokens: canonicalUsage.inputTokens,
2279
+ completionTokens: canonicalUsage.outputTokens,
2280
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2281
+ canonicalUsage
2282
+ };
2283
+ }
2284
+ function normalizeCanonicalLlmUsage(usage) {
2037
2285
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
2038
2286
  const rec = usage;
2039
- const promptTokensRaw = rec["prompt_tokens"];
2040
- const completionTokensRaw = rec["completion_tokens"];
2041
- const totalTokensRaw = rec["total_tokens"];
2042
- const tokensRaw = rec["tokens"];
2043
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
2044
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
2045
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
2046
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
2047
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
2048
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
2049
- return { promptTokens, completionTokens, totalTokens };
2287
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2288
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2289
+ if (inputTokens === void 0 || outputTokens === void 0) {
2290
+ return void 0;
2291
+ }
2292
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2293
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2294
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2295
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2296
+ const totalTokens = readTokenCount(rec, "total_tokens");
2297
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2298
+ return void 0;
2299
+ }
2300
+ return {
2301
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2302
+ outputTokens,
2303
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2304
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2305
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2306
+ source: "provider-response-usage",
2307
+ confidence: "actual",
2308
+ rawUsage: usage
2309
+ };
2310
+ }
2311
+ function normalizeLlmUsage(usage) {
2312
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2313
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
2050
2314
  }
2051
2315
  function recordLlmCallTelemetry(entry) {
2052
2316
  const store = als.getStore();
@@ -2060,17 +2324,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2060
2324
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2061
2325
  return;
2062
2326
  }
2063
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2327
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2328
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2064
2329
  const respText = extractResponseText(ctx.llmResp);
2065
2330
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2066
2331
  try {
2067
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2068
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2069
- return {
2070
- promptTokens,
2071
- completionTokens,
2072
- totalTokens: promptTokens + completionTokens
2073
- };
2332
+ const promptTokens = ctx.llmMessages.reduce(
2333
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2334
+ 0
2335
+ );
2336
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2337
+ return normalizedUsageFromCanonical({
2338
+ inputTokens: promptTokens,
2339
+ outputTokens: completionTokens,
2340
+ totalTokens: promptTokens + completionTokens,
2341
+ source: "local-estimate",
2342
+ confidence: "estimate"
2343
+ });
2074
2344
  } catch {
2075
2345
  return void 0;
2076
2346
  }
@@ -2080,7 +2350,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2080
2350
  stream: ctx.input.stream === true,
2081
2351
  startedAt: ctx.llmCallStartedAt,
2082
2352
  durationMs: ctx.llmCallDurationMs,
2083
- usage: normalizedUsage
2353
+ usage: normalizedUsage,
2354
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2084
2355
  });
2085
2356
  ctx.telemetry.emit({
2086
2357
  kind: "llm_call",
@@ -2088,6 +2359,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2088
2359
  stream: ctx.input.stream === true,
2089
2360
  durationMs: ctx.llmCallDurationMs,
2090
2361
  usage: normalizedUsage,
2362
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2091
2363
  scope: {
2092
2364
  conversationId: ctx.conversationId || void 0,
2093
2365
  turnId: ctx.turnId,
@@ -2231,10 +2503,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2231
2503
  return [
2232
2504
  `\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`,
2233
2505
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2234
- "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",
2506
+ "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",
2235
2507
  `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`,
2236
2508
  ' \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',
2237
- "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"
2509
+ "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"
2238
2510
  ].join("\n");
2239
2511
  };
2240
2512
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2542,6 +2814,16 @@ function createApplySystemReminderStage() {
2542
2814
  };
2543
2815
  }
2544
2816
 
2817
+ // src/runtime-kernel/token-accounting/functions.ts
2818
+ function createContextComponentLedgerEntry(input) {
2819
+ return {
2820
+ ...input,
2821
+ kind: "context-component",
2822
+ components: [...input.components],
2823
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2824
+ };
2825
+ }
2826
+
2545
2827
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2546
2828
  var logger4 = new Logger("GraphAgentExecutor");
2547
2829
  function createBuildContextStage(dependencies) {
@@ -2558,6 +2840,23 @@ function createBuildContextStage(dependencies) {
2558
2840
  ctx.mode = contextBuildResult.mode;
2559
2841
  ctx.llmMessages = contextBuildResult.llmMessages;
2560
2842
  ctx.contextTrace = contextBuildResult.contextTrace;
2843
+ if (contextBuildResult.tokenEstimate) {
2844
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2845
+ ctx.telemetry.emit({
2846
+ kind: "context_build",
2847
+ modelId: ctx.modelId,
2848
+ mode: contextBuildResult.mode,
2849
+ tokenEstimate: contextBuildResult.tokenEstimate,
2850
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2851
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2852
+ scope: {
2853
+ conversationId: ctx.conversationId,
2854
+ runId: ctx.input.toolContext?.runId,
2855
+ parentRunId: ctx.input.toolContext?.parentRunId,
2856
+ turnId: ctx.turnId
2857
+ }
2858
+ });
2859
+ }
2561
2860
  for (const event of contextBuildResult.summaryEvents) {
2562
2861
  if (!isHistorySummaryEvent(event)) {
2563
2862
  continue;
@@ -2572,6 +2871,24 @@ function createBuildContextStage(dependencies) {
2572
2871
  }
2573
2872
  };
2574
2873
  }
2874
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2875
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2876
+ if (keptComponents.length === 0) {
2877
+ return void 0;
2878
+ }
2879
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2880
+ const createdAt = Date.now();
2881
+ return createContextComponentLedgerEntry({
2882
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2883
+ conversationId: ctx.conversationId,
2884
+ runId,
2885
+ parentRunId: ctx.input.toolContext?.parentRunId,
2886
+ turnId: ctx.turnId,
2887
+ route: contextBuildResult.tokenEstimate?.route,
2888
+ createdAt,
2889
+ components: keptComponents
2890
+ });
2891
+ }
2575
2892
 
2576
2893
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2577
2894
  function createBuildDecisionStage(dependencies) {
@@ -2802,6 +3119,7 @@ var GraphAgentExecutor = class {
2802
3119
  modelCatalog;
2803
3120
  telemetryPort;
2804
3121
  auditPort;
3122
+ tokenizer;
2805
3123
  stages;
2806
3124
  middlewares;
2807
3125
  constructor(dependencies) {
@@ -2815,6 +3133,7 @@ var GraphAgentExecutor = class {
2815
3133
  });
2816
3134
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2817
3135
  this.auditPort = dependencies.auditPort ?? noopAudit;
3136
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2818
3137
  this.stages = [
2819
3138
  createPrepareCallStage({
2820
3139
  modelResolver: this.modelResolver,
@@ -2858,7 +3177,8 @@ var GraphAgentExecutor = class {
2858
3177
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2859
3178
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2860
3179
  telemetry: this.telemetryPort,
2861
- audit: this.auditPort
3180
+ audit: this.auditPort,
3181
+ tokenizer: this.tokenizer
2862
3182
  };
2863
3183
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2864
3184
  stream: input.stream === true,
@@ -3823,11 +4143,11 @@ function buildToolOutputUiMeta(params) {
3823
4143
  }
3824
4144
  async function applyObservationGovernance(params) {
3825
4145
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3826
- return;
4146
+ return {};
3827
4147
  }
3828
4148
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3829
4149
  if (!policy.enabled) {
3830
- return;
4150
+ return {};
3831
4151
  }
3832
4152
  const truncated = await params.observationPreview.truncateObservation({
3833
4153
  context: params.toolContext,
@@ -3841,13 +4161,37 @@ async function applyObservationGovernance(params) {
3841
4161
  })
3842
4162
  });
3843
4163
  if (!truncated.truncated) {
3844
- return;
4164
+ return {};
3845
4165
  }
3846
4166
  params.parsed["observation"] = truncated.preview;
3847
4167
  const data = params.parsed["data"];
3848
4168
  if (isRecord9(data) && !("tool_output_store" in data)) {
3849
4169
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3850
4170
  }
4171
+ return {
4172
+ observationTruncation: buildObservationTruncationMeta({
4173
+ originalText: params.structuredObservation,
4174
+ previewText: truncated.preview,
4175
+ originalChars: truncated.originalChars,
4176
+ previewChars: truncated.previewChars,
4177
+ originalLines: truncated.originalLines,
4178
+ previewLines: truncated.previewLines
4179
+ })
4180
+ };
4181
+ }
4182
+ function buildObservationTruncationMeta(input) {
4183
+ return {
4184
+ originalChars: input.originalChars ?? input.originalText.length,
4185
+ previewChars: input.previewChars ?? input.previewText.length,
4186
+ originalLines: input.originalLines ?? countLines(input.originalText),
4187
+ previewLines: input.previewLines ?? countLines(input.previewText)
4188
+ };
4189
+ }
4190
+ function countLines(value) {
4191
+ if (value.length === 0) {
4192
+ return 0;
4193
+ }
4194
+ return value.split(/\r\n|\r|\n/).length;
3851
4195
  }
3852
4196
 
3853
4197
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4723,7 +5067,7 @@ var ToolNode = class {
4723
5067
  parentRunId: context.toolContext.parentRunId
4724
5068
  });
4725
5069
  applyProtocolFuseState(context.local);
4726
- await applyObservationGovernance({
5070
+ const observationGovernance = await applyObservationGovernance({
4727
5071
  parsed: context.parsed,
4728
5072
  toolName: context.toolName,
4729
5073
  toolContext: context.toolContext,
@@ -4750,6 +5094,12 @@ var ToolNode = class {
4750
5094
  runtimeToolOutput,
4751
5095
  execIdempotency: context.exec.idempotency
4752
5096
  });
5097
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5098
+ runtimeToolOutput.metadata = {
5099
+ ...runtimeToolOutput.metadata ?? {},
5100
+ observationTruncation: observationGovernance.observationTruncation
5101
+ };
5102
+ }
4753
5103
  const remainingCalls = context.calls.slice(1);
4754
5104
  context.state.local = buildSuccessLocalState({
4755
5105
  local: context.local,
@@ -6111,6 +6461,7 @@ async function callLlmStream(params) {
6111
6461
  const streamAnswerId = generateMessageId();
6112
6462
  let streamChunkSeq = 0;
6113
6463
  let capturedUsage = void 0;
6464
+ let capturedCanonicalUsage = void 0;
6114
6465
  const toolAccumulator = new ToolCallStreamAccumulator([
6115
6466
  "markdown_edit",
6116
6467
  "text_to_image",
@@ -6169,6 +6520,10 @@ async function callLlmStream(params) {
6169
6520
  if (typeof chunk !== "object" || chunk === null) {
6170
6521
  return;
6171
6522
  }
6523
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
6524
+ if (parsedCanonicalUsage.success) {
6525
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
6526
+ }
6172
6527
  if (chunk.content) {
6173
6528
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6174
6529
  fullResponse += chunk.content;
@@ -6253,6 +6608,12 @@ async function callLlmStream(params) {
6253
6608
  const onUsage = (usage) => {
6254
6609
  capturedUsage = usage;
6255
6610
  };
6611
+ const onCanonicalUsage = (usage) => {
6612
+ const parsed = CanonicalLlmUsage.safeParse(usage);
6613
+ if (parsed.success) {
6614
+ capturedCanonicalUsage = parsed.data;
6615
+ }
6616
+ };
6256
6617
  await aiEngine.chatCompletionStream(
6257
6618
  modelId,
6258
6619
  messages,
@@ -6265,7 +6626,8 @@ async function callLlmStream(params) {
6265
6626
  onError,
6266
6627
  onFinish,
6267
6628
  onThought,
6268
- onUsage
6629
+ onUsage,
6630
+ onCanonicalUsage
6269
6631
  );
6270
6632
  if (streamError) {
6271
6633
  throw streamError;
@@ -6273,12 +6635,13 @@ async function callLlmStream(params) {
6273
6635
  emitThoughtComplete(thoughtSegmenter.finalize());
6274
6636
  const mergedToolCalls = toolAccumulator.getToolCalls();
6275
6637
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6276
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
6638
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6277
6639
  return {
6278
6640
  content: fullResponse,
6279
6641
  tool_calls: mergedToolCalls,
6280
6642
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6281
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
6643
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
6644
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6282
6645
  };
6283
6646
  }
6284
6647
  return fullResponse;
@@ -6328,6 +6691,10 @@ function tryCloudQuotaFallback({
6328
6691
  }
6329
6692
 
6330
6693
  // src/runtime-kernel/llm/usage-telemetry.ts
6694
+ function parseCanonicalUsage(value) {
6695
+ const parsed = CanonicalLlmUsage.safeParse(value);
6696
+ return parsed.success ? parsed.data : void 0;
6697
+ }
6331
6698
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6332
6699
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6333
6700
  return normalizeCompletionResponse(response);
@@ -6338,6 +6705,7 @@ function normalizeCompletionResponse(response) {
6338
6705
  }
6339
6706
  if (isRecord17(response)) {
6340
6707
  const usage = response["usage"];
6708
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6341
6709
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6342
6710
  if (parsedToolCalls) {
6343
6711
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6345,7 +6713,8 @@ function normalizeCompletionResponse(response) {
6345
6713
  content: typeof response["content"] === "string" ? response["content"] : "",
6346
6714
  tool_calls: parsedToolCalls,
6347
6715
  reasoning_details: reasoningDetails,
6348
- ...usage !== void 0 ? { usage } : {}
6716
+ ...usage !== void 0 ? { usage } : {},
6717
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6349
6718
  };
6350
6719
  }
6351
6720
  }
@@ -6355,10 +6724,12 @@ function normalizeCompletionResponse(response) {
6355
6724
  if (typeof response === "object") {
6356
6725
  if (isRecord17(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6357
6726
  const usage = response["usage"];
6727
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6358
6728
  return {
6359
6729
  content: typeof response["content"] === "string" ? response["content"] : "",
6360
6730
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6361
- ...usage !== void 0 ? { usage } : {}
6731
+ ...usage !== void 0 ? { usage } : {},
6732
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6362
6733
  };
6363
6734
  }
6364
6735
  if (isRecord17(response)) {