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