@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
package/dist/cli.js CHANGED
@@ -76,6 +76,12 @@ z.object({
76
76
  args: z.record(z.unknown()).optional(),
77
77
  tool_call_id: z.string()
78
78
  });
79
+ var ObservationTruncationMeta = z.object({
80
+ originalChars: z.number().int().nonnegative(),
81
+ previewChars: z.number().int().nonnegative(),
82
+ originalLines: z.number().int().nonnegative().optional(),
83
+ previewLines: z.number().int().nonnegative().optional()
84
+ });
79
85
  var ImageInfoMeta = z.object({
80
86
  url: z.string().optional(),
81
87
  width: z.number().int().positive().optional(),
@@ -107,6 +113,7 @@ var PersistentMetadata = z.object({
107
113
  tool_name: z.string().optional(),
108
114
  args: z.record(z.unknown()).optional(),
109
115
  tool_call_id: z.string().optional(),
116
+ observationTruncation: ObservationTruncationMeta.optional(),
110
117
  raw_output: z.string().optional(),
111
118
  image_info: ImageInfoMeta.optional(),
112
119
  taskType: z.string().optional(),
@@ -253,7 +260,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
253
260
  var AgentSpecTokenEstimationPolicy = z.object({
254
261
  encoding: z.string().min(1).optional(),
255
262
  avgCharsPerToken: z.number().positive().optional(),
256
- toolCallOverhead: z.number().int().nonnegative().optional()
263
+ toolCallOverhead: z.number().int().nonnegative().optional(),
264
+ calibration: z.object({
265
+ enabled: z.boolean().optional(),
266
+ minSamples: z.number().int().positive().optional(),
267
+ minCoefficient: z.number().positive().optional(),
268
+ maxCoefficient: z.number().positive().optional()
269
+ }).optional(),
270
+ remoteCount: z.object({
271
+ enabled: z.boolean().optional(),
272
+ failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
273
+ }).optional()
257
274
  });
258
275
  var AgentSpecSystemReminderTrigger = z.object({
259
276
  kind: z.string().min(1),
@@ -949,6 +966,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
949
966
  error,
950
967
  ...options
951
968
  });
969
+ var TokenCountSource = z.enum([
970
+ "local-estimate",
971
+ "provider-preflight-count",
972
+ "provider-response-usage",
973
+ "host-supplied",
974
+ "test-fixture"
975
+ ]);
976
+ var TokenCountConfidence = z.enum([
977
+ "estimate",
978
+ "provider-estimate",
979
+ "actual"
980
+ ]);
981
+ var TokenRouteCapabilities = z.object({
982
+ supportsRemoteTokenCount: z.boolean().optional(),
983
+ supportsResponseUsage: z.boolean().optional(),
984
+ supportsImageInput: z.boolean().optional(),
985
+ supportsCachedInputBilling: z.boolean().optional(),
986
+ supportsReasoningTokens: z.boolean().optional()
987
+ });
988
+ var TokenRoute = z.object({
989
+ providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
990
+ 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"),
991
+ modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
992
+ providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
993
+ capabilities: TokenRouteCapabilities.optional()
994
+ });
995
+ var tokenCount = z.number().int().nonnegative();
996
+ var CanonicalLlmUsage = z.object({
997
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
998
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
999
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1000
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1001
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1002
+ 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"),
1003
+ source: TokenCountSource,
1004
+ confidence: TokenCountConfidence,
1005
+ rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1006
+ });
1007
+ var tokenCount2 = z.number().int().nonnegative();
1008
+ var tokenPrice = z.number().finite().nonnegative();
1009
+ z.enum([
1010
+ "llm-usage",
1011
+ "context-component"
1012
+ ]);
1013
+ var ContextTokenComponentKind = z.enum([
1014
+ "system",
1015
+ "user",
1016
+ "assistant",
1017
+ "tool",
1018
+ "context-injection",
1019
+ "history-summary",
1020
+ "working-memory",
1021
+ "fence",
1022
+ "system-reminder",
1023
+ "other"
1024
+ ]);
1025
+ var TokenUsageTotals = z.object({
1026
+ inputTokens: tokenCount2,
1027
+ outputTokens: tokenCount2,
1028
+ reasoningTokens: tokenCount2.optional(),
1029
+ cacheReadTokens: tokenCount2.optional(),
1030
+ cacheWriteTokens: tokenCount2.optional(),
1031
+ totalTokens: tokenCount2.optional(),
1032
+ usageCount: z.number().int().nonnegative()
1033
+ });
1034
+ var ContextTokenComponent = z.object({
1035
+ componentId: z.string().min(1),
1036
+ kind: ContextTokenComponentKind,
1037
+ tokens: tokenCount2,
1038
+ source: TokenCountSource,
1039
+ confidence: TokenCountConfidence,
1040
+ label: z.string().optional(),
1041
+ messageId: z.string().optional(),
1042
+ role: z.string().optional(),
1043
+ action: z.string().optional(),
1044
+ kept: z.boolean().optional(),
1045
+ truncatedAtExecution: z.boolean().optional(),
1046
+ originalTokensEstimate: tokenCount2.optional(),
1047
+ droppedTokensEstimate: tokenCount2.optional()
1048
+ });
1049
+ var TokenLedgerEntryBase = z.object({
1050
+ id: z.string().min(1),
1051
+ runId: z.string().optional(),
1052
+ parentRunId: z.string().optional(),
1053
+ conversationId: z.string().optional(),
1054
+ turnId: z.string().optional(),
1055
+ stepId: z.string().optional(),
1056
+ route: TokenRoute.optional(),
1057
+ createdAt: z.number().int().nonnegative().optional()
1058
+ });
1059
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1060
+ kind: z.literal("llm-usage"),
1061
+ modelId: z.string().optional(),
1062
+ usage: CanonicalLlmUsage
1063
+ });
1064
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1065
+ kind: z.literal("context-component"),
1066
+ components: z.array(ContextTokenComponent),
1067
+ totalTokens: tokenCount2
1068
+ });
1069
+ z.discriminatedUnion("kind", [
1070
+ LlmUsageTokenLedgerEntry,
1071
+ ContextComponentTokenLedgerEntry
1072
+ ]);
1073
+ var TokenLedgerAggregate = z.object({
1074
+ llmUsage: TokenUsageTotals.optional(),
1075
+ contextTokens: tokenCount2,
1076
+ entryCount: z.number().int().nonnegative(),
1077
+ llmCallCount: z.number().int().nonnegative(),
1078
+ contextComponentCount: z.number().int().nonnegative()
1079
+ });
1080
+ z.object({
1081
+ /**
1082
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1083
+ */
1084
+ own: TokenLedgerAggregate,
1085
+ children: TokenLedgerAggregate.optional()
1086
+ });
1087
+ var TokenCostComponent = z.enum([
1088
+ "input",
1089
+ "output",
1090
+ "reasoning",
1091
+ "cacheRead",
1092
+ "cacheWrite"
1093
+ ]);
1094
+ z.object({
1095
+ currency: z.string().min(1),
1096
+ unit: z.literal("per_1m_tokens"),
1097
+ input: tokenPrice.optional(),
1098
+ output: tokenPrice.optional(),
1099
+ reasoning: tokenPrice.optional(),
1100
+ cacheRead: tokenPrice.optional(),
1101
+ cacheWrite: tokenPrice.optional()
1102
+ });
1103
+ z.object({
1104
+ status: z.enum(["computed", "unknown"]),
1105
+ currency: z.string().optional(),
1106
+ inputCost: tokenPrice.optional(),
1107
+ outputCost: tokenPrice.optional(),
1108
+ reasoningCost: tokenPrice.optional(),
1109
+ cacheReadCost: tokenPrice.optional(),
1110
+ cacheWriteCost: tokenPrice.optional(),
1111
+ totalCost: tokenPrice.optional(),
1112
+ missingPriceComponents: z.array(TokenCostComponent).optional()
1113
+ });
1114
+ var tokenCount3 = z.number().int().nonnegative();
1115
+ var actualCalibrationSource = z.enum([
1116
+ "provider-response-usage",
1117
+ "host-supplied",
1118
+ "test-fixture"
1119
+ ]);
1120
+ z.object({
1121
+ route: TokenRoute,
1122
+ localEstimateTokens: tokenCount3,
1123
+ actualInputTokens: tokenCount3,
1124
+ source: actualCalibrationSource,
1125
+ confidence: z.literal("actual"),
1126
+ observedAt: z.number().int().nonnegative().optional(),
1127
+ runId: z.string().optional(),
1128
+ ledgerEntryId: z.string().optional()
1129
+ });
1130
+ z.object({
1131
+ enabled: z.boolean(),
1132
+ applied: z.boolean(),
1133
+ route: TokenRoute.optional(),
1134
+ sampleCount: z.number().int().nonnegative(),
1135
+ coefficient: z.number().positive().optional(),
1136
+ minSamples: z.number().int().positive().optional(),
1137
+ minCoefficient: z.number().positive().optional(),
1138
+ maxCoefficient: z.number().positive().optional(),
1139
+ localEstimateTokens: tokenCount3.optional(),
1140
+ calibratedEstimateTokens: tokenCount3.optional(),
1141
+ deltaTokens: z.number().int().optional(),
1142
+ sampleLedgerEntryIds: z.array(z.string()).optional()
1143
+ });
1144
+ z.object({
1145
+ route: TokenRoute.optional(),
1146
+ localEstimateTokens: tokenCount3,
1147
+ calibratedEstimateTokens: tokenCount3,
1148
+ finalTokens: tokenCount3,
1149
+ source: z.literal("local-estimate"),
1150
+ confidence: z.literal("estimate")
1151
+ });
952
1152
 
953
1153
  // src/quickstart/toolSchema.ts
954
1154
  function serializeToolProperty(property) {
@@ -1552,6 +1752,190 @@ var noopAudit = {
1552
1752
  flush() {
1553
1753
  }
1554
1754
  };
1755
+ var TokenCalculator = class {
1756
+ static BYTES_PER_TOKEN_LATIN = 4;
1757
+ static BYTES_PER_TOKEN_CJK = 3;
1758
+ static OVERHEAD_PER_MESSAGE = 5;
1759
+ static OVERHEAD_PER_TOOL_CALL = 10;
1760
+ static encoderCache = /* @__PURE__ */ new Map();
1761
+ static DEFAULT_ENCODING = "cl100k_base";
1762
+ static SUPPORTED_ENCODINGS = [
1763
+ "gpt2",
1764
+ "r50k_base",
1765
+ "p50k_base",
1766
+ "p50k_edit",
1767
+ "cl100k_base",
1768
+ "o200k_base"
1769
+ ];
1770
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1771
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1772
+ if (this.isSupportedEncodingName(normalized)) {
1773
+ return normalized;
1774
+ }
1775
+ if (normalized.includes("deepseek")) {
1776
+ return "cl100k_base";
1777
+ }
1778
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1779
+ return "o200k_base";
1780
+ }
1781
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1782
+ return "cl100k_base";
1783
+ }
1784
+ return this.DEFAULT_ENCODING;
1785
+ }
1786
+ static isSupportedEncodingName(value) {
1787
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1788
+ }
1789
+ static getEncoder(modelIdentifierOrEncoding) {
1790
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1791
+ const cached = this.encoderCache.get(encodingName);
1792
+ if (cached) {
1793
+ return cached;
1794
+ }
1795
+ const encoder = get_encoding(encodingName);
1796
+ this.encoderCache.set(encodingName, encoder);
1797
+ return encoder;
1798
+ }
1799
+ static estimateTokensRough(text, _modelIdentifier) {
1800
+ if (!text) return 0;
1801
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1802
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1803
+ const byteLength = new TextEncoder().encode(text).length;
1804
+ return Math.ceil(byteLength / ratio);
1805
+ }
1806
+ static estimateTokens(text, options = {}) {
1807
+ if (!text) return 0;
1808
+ if (options.encoding) {
1809
+ try {
1810
+ return this.estimateTokensPrecise(text, options.encoding);
1811
+ } catch {
1812
+ }
1813
+ }
1814
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1815
+ return Math.ceil(text.length / avgCharsPerToken);
1816
+ }
1817
+ static estimateTokensPrecise(text, modelIdentifier) {
1818
+ if (!text) return 0;
1819
+ const encoder = this.getEncoder(modelIdentifier);
1820
+ return encoder.encode(text).length;
1821
+ }
1822
+ static estimateMessageTokens(message, options = {}) {
1823
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1824
+ if (message.content) {
1825
+ totalTokens += this.estimateTokens(String(message.content), options);
1826
+ }
1827
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1828
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1829
+ for (const toolCall of toolCalls) {
1830
+ totalTokens += toolCallOverhead;
1831
+ const fn = toolCall["function"];
1832
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1833
+ const fnRecord = fn;
1834
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1835
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1836
+ }
1837
+ }
1838
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1839
+ if (toolCallId) {
1840
+ totalTokens += this.estimateTokens(toolCallId, options);
1841
+ }
1842
+ return totalTokens;
1843
+ }
1844
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1845
+ return this.estimateMessageTokens(message, {
1846
+ encoding: modelIdentifier,
1847
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1848
+ });
1849
+ }
1850
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1851
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1852
+ }
1853
+ static extractToolCallsForTokenEstimate(message) {
1854
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1855
+ if (Array.isArray(direct)) return direct;
1856
+ const metadata = "metadata" in message ? message.metadata : void 0;
1857
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1858
+ const metadataRecord = metadata;
1859
+ const metadataToolCalls = metadataRecord["tool_calls"];
1860
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1861
+ }
1862
+ static extractToolCallIdForTokenEstimate(message) {
1863
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1864
+ return message.tool_call_id;
1865
+ }
1866
+ const metadata = "metadata" in message ? message.metadata : void 0;
1867
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1868
+ const metadataRecord = metadata;
1869
+ const toolCallId = metadataRecord["tool_call_id"];
1870
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1871
+ }
1872
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1873
+ if (!text || maxTokens <= 0) return "";
1874
+ const encoder = this.getEncoder(modelIdentifier);
1875
+ const tokens = encoder.encode(text);
1876
+ if (tokens.length <= maxTokens) {
1877
+ return text;
1878
+ }
1879
+ let truncatedTokens;
1880
+ const ellipsis = "...";
1881
+ switch (strategy) {
1882
+ case "start":
1883
+ truncatedTokens = tokens.slice(0, maxTokens);
1884
+ return encoder.decode(truncatedTokens) + ellipsis;
1885
+ case "end":
1886
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1887
+ return ellipsis + encoder.decode(truncatedTokens);
1888
+ case "middle": {
1889
+ const half = Math.floor(maxTokens / 2);
1890
+ const head = tokens.slice(0, half);
1891
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1892
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1893
+ }
1894
+ default:
1895
+ truncatedTokens = tokens.slice(0, maxTokens);
1896
+ return encoder.decode(truncatedTokens) + ellipsis;
1897
+ }
1898
+ }
1899
+ static cleanup() {
1900
+ for (const encoder of this.encoderCache.values()) {
1901
+ encoder.free();
1902
+ }
1903
+ this.encoderCache.clear();
1904
+ }
1905
+ };
1906
+ function normalizePositiveNumber(value, fallback) {
1907
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1908
+ }
1909
+ function normalizeNonNegativeInteger(value, fallback) {
1910
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1911
+ return fallback;
1912
+ }
1913
+ return Math.max(0, Math.floor(value));
1914
+ }
1915
+
1916
+ // src/shared/defaultTokenizerPort.ts
1917
+ var DefaultTokenizerPort = class {
1918
+ constructor(config = {}) {
1919
+ this.config = config;
1920
+ }
1921
+ config;
1922
+ estimateText(text, _modelId) {
1923
+ return TokenCalculator.estimateTokens(text, {
1924
+ encoding: this.config.encoding,
1925
+ avgCharsPerToken: this.config.avgCharsPerToken
1926
+ });
1927
+ }
1928
+ estimateMessage(message, _modelId) {
1929
+ return TokenCalculator.estimateMessageTokens(message, {
1930
+ encoding: this.config.encoding,
1931
+ avgCharsPerToken: this.config.avgCharsPerToken,
1932
+ toolCallOverhead: this.config.toolCallOverhead
1933
+ });
1934
+ }
1935
+ };
1936
+ function createDefaultTokenizerPort(config = {}) {
1937
+ return new DefaultTokenizerPort(config);
1938
+ }
1555
1939
 
1556
1940
  // src/runtime-kernel/llm/toolCallUtils.ts
1557
1941
  function isRecord2(value) {
@@ -1698,6 +2082,13 @@ function resolveUsage(response) {
1698
2082
  }
1699
2083
  return response.usage;
1700
2084
  }
2085
+ function resolveCanonicalUsage(response) {
2086
+ if (!response || typeof response === "string") {
2087
+ return void 0;
2088
+ }
2089
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2090
+ return parsed.success ? parsed.data : void 0;
2091
+ }
1701
2092
  function resolveToolCalls(response) {
1702
2093
  if (!response || typeof response === "string") {
1703
2094
  return void 0;
@@ -1752,181 +2143,54 @@ var contextAuditMiddleware = async (ctx, stage, next) => {
1752
2143
  });
1753
2144
  }
1754
2145
  };
1755
- var TokenCalculator = class {
1756
- static BYTES_PER_TOKEN_LATIN = 4;
1757
- static BYTES_PER_TOKEN_CJK = 3;
1758
- static OVERHEAD_PER_MESSAGE = 5;
1759
- static OVERHEAD_PER_TOOL_CALL = 10;
1760
- static encoderCache = /* @__PURE__ */ new Map();
1761
- static DEFAULT_ENCODING = "cl100k_base";
1762
- static SUPPORTED_ENCODINGS = [
1763
- "gpt2",
1764
- "r50k_base",
1765
- "p50k_base",
1766
- "p50k_edit",
1767
- "cl100k_base",
1768
- "o200k_base"
1769
- ];
1770
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1771
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1772
- if (this.isSupportedEncodingName(normalized)) {
1773
- return normalized;
1774
- }
1775
- if (normalized.includes("deepseek")) {
1776
- return "cl100k_base";
1777
- }
1778
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1779
- return "o200k_base";
1780
- }
1781
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1782
- return "cl100k_base";
1783
- }
1784
- return this.DEFAULT_ENCODING;
1785
- }
1786
- static isSupportedEncodingName(value) {
1787
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1788
- }
1789
- static getEncoder(modelIdentifierOrEncoding) {
1790
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1791
- const cached = this.encoderCache.get(encodingName);
1792
- if (cached) {
1793
- return cached;
1794
- }
1795
- const encoder = get_encoding(encodingName);
1796
- this.encoderCache.set(encodingName, encoder);
1797
- return encoder;
1798
- }
1799
- static estimateTokensRough(text, _modelIdentifier) {
1800
- if (!text) return 0;
1801
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1802
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1803
- const byteLength = new TextEncoder().encode(text).length;
1804
- return Math.ceil(byteLength / ratio);
1805
- }
1806
- static estimateTokens(text, options = {}) {
1807
- if (!text) return 0;
1808
- if (options.encoding) {
1809
- try {
1810
- return this.estimateTokensPrecise(text, options.encoding);
1811
- } catch {
1812
- }
1813
- }
1814
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1815
- return Math.ceil(text.length / avgCharsPerToken);
1816
- }
1817
- static estimateTokensPrecise(text, modelIdentifier) {
1818
- if (!text) return 0;
1819
- const encoder = this.getEncoder(modelIdentifier);
1820
- return encoder.encode(text).length;
1821
- }
1822
- static estimateMessageTokens(message, options = {}) {
1823
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1824
- if (message.content) {
1825
- totalTokens += this.estimateTokens(String(message.content), options);
1826
- }
1827
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1828
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1829
- for (const toolCall of toolCalls) {
1830
- totalTokens += toolCallOverhead;
1831
- const fn = toolCall["function"];
1832
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1833
- const fnRecord = fn;
1834
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1835
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1836
- }
1837
- }
1838
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1839
- if (toolCallId) {
1840
- totalTokens += this.estimateTokens(toolCallId, options);
1841
- }
1842
- return totalTokens;
1843
- }
1844
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1845
- return this.estimateMessageTokens(message, {
1846
- encoding: modelIdentifier,
1847
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1848
- });
1849
- }
1850
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1851
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1852
- }
1853
- static extractToolCallsForTokenEstimate(message) {
1854
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1855
- if (Array.isArray(direct)) return direct;
1856
- const metadata = "metadata" in message ? message.metadata : void 0;
1857
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1858
- const metadataRecord = metadata;
1859
- const metadataToolCalls = metadataRecord["tool_calls"];
1860
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1861
- }
1862
- static extractToolCallIdForTokenEstimate(message) {
1863
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1864
- return message.tool_call_id;
1865
- }
1866
- const metadata = "metadata" in message ? message.metadata : void 0;
1867
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1868
- const metadataRecord = metadata;
1869
- const toolCallId = metadataRecord["tool_call_id"];
1870
- return typeof toolCallId === "string" ? toolCallId : void 0;
1871
- }
1872
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1873
- if (!text || maxTokens <= 0) return "";
1874
- const encoder = this.getEncoder(modelIdentifier);
1875
- const tokens = encoder.encode(text);
1876
- if (tokens.length <= maxTokens) {
1877
- return text;
1878
- }
1879
- let truncatedTokens;
1880
- const ellipsis = "...";
1881
- switch (strategy) {
1882
- case "start":
1883
- truncatedTokens = tokens.slice(0, maxTokens);
1884
- return encoder.decode(truncatedTokens) + ellipsis;
1885
- case "end":
1886
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1887
- return ellipsis + encoder.decode(truncatedTokens);
1888
- case "middle": {
1889
- const half = Math.floor(maxTokens / 2);
1890
- const head = tokens.slice(0, half);
1891
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1892
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1893
- }
1894
- default:
1895
- truncatedTokens = tokens.slice(0, maxTokens);
1896
- return encoder.decode(truncatedTokens) + ellipsis;
1897
- }
1898
- }
1899
- static cleanup() {
1900
- for (const encoder of this.encoderCache.values()) {
1901
- encoder.free();
1902
- }
1903
- this.encoderCache.clear();
1904
- }
1905
- };
1906
- function normalizePositiveNumber(value, fallback) {
1907
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2146
+ var als = new AsyncLocalStorage();
2147
+ function readTokenCount(record, key) {
2148
+ const value = record[key];
2149
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1908
2150
  }
1909
- function normalizeNonNegativeInteger(value, fallback) {
1910
- if (typeof value !== "number" || !Number.isFinite(value)) {
1911
- return fallback;
1912
- }
1913
- return Math.max(0, Math.floor(value));
2151
+ function readRecord(record, key) {
2152
+ const value = record[key];
2153
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2154
+ return Object.fromEntries(Object.entries(value));
1914
2155
  }
1915
- var als = new AsyncLocalStorage();
1916
- function normalizeLlmUsage(usage2) {
2156
+ function normalizedUsageFromCanonical(canonicalUsage) {
2157
+ return {
2158
+ promptTokens: canonicalUsage.inputTokens,
2159
+ completionTokens: canonicalUsage.outputTokens,
2160
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2161
+ canonicalUsage
2162
+ };
2163
+ }
2164
+ function normalizeCanonicalLlmUsage(usage2) {
1917
2165
  if (!usage2 || typeof usage2 !== "object" || Array.isArray(usage2)) return void 0;
1918
2166
  const rec = usage2;
1919
- const promptTokensRaw = rec["prompt_tokens"];
1920
- const completionTokensRaw = rec["completion_tokens"];
1921
- const totalTokensRaw = rec["total_tokens"];
1922
- const tokensRaw = rec["tokens"];
1923
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1924
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1925
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1926
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1927
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1928
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1929
- return { promptTokens, completionTokens, totalTokens };
2167
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2168
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2169
+ if (inputTokens === void 0 || outputTokens === void 0) {
2170
+ return void 0;
2171
+ }
2172
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2173
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2174
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2175
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2176
+ const totalTokens = readTokenCount(rec, "total_tokens");
2177
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2178
+ return void 0;
2179
+ }
2180
+ return {
2181
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2182
+ outputTokens,
2183
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2184
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2185
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2186
+ source: "provider-response-usage",
2187
+ confidence: "actual",
2188
+ rawUsage: usage2
2189
+ };
2190
+ }
2191
+ function normalizeLlmUsage(usage2) {
2192
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage2);
2193
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1930
2194
  }
1931
2195
  function recordLlmCallTelemetry(entry) {
1932
2196
  const store = als.getStore();
@@ -1940,17 +2204,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1940
2204
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1941
2205
  return;
1942
2206
  }
1943
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2207
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2208
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1944
2209
  const respText = extractResponseText(ctx.llmResp);
1945
2210
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1946
2211
  try {
1947
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1948
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1949
- return {
1950
- promptTokens,
1951
- completionTokens,
1952
- totalTokens: promptTokens + completionTokens
1953
- };
2212
+ const promptTokens = ctx.llmMessages.reduce(
2213
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2214
+ 0
2215
+ );
2216
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2217
+ return normalizedUsageFromCanonical({
2218
+ inputTokens: promptTokens,
2219
+ outputTokens: completionTokens,
2220
+ totalTokens: promptTokens + completionTokens,
2221
+ source: "local-estimate",
2222
+ confidence: "estimate"
2223
+ });
1954
2224
  } catch {
1955
2225
  return void 0;
1956
2226
  }
@@ -1960,7 +2230,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1960
2230
  stream: ctx.input.stream === true,
1961
2231
  startedAt: ctx.llmCallStartedAt,
1962
2232
  durationMs: ctx.llmCallDurationMs,
1963
- usage: normalizedUsage
2233
+ usage: normalizedUsage,
2234
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1964
2235
  });
1965
2236
  ctx.telemetry.emit({
1966
2237
  kind: "llm_call",
@@ -1968,6 +2239,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1968
2239
  stream: ctx.input.stream === true,
1969
2240
  durationMs: ctx.llmCallDurationMs,
1970
2241
  usage: normalizedUsage,
2242
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1971
2243
  scope: {
1972
2244
  conversationId: ctx.conversationId || void 0,
1973
2245
  turnId: ctx.turnId,
@@ -2111,10 +2383,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2111
2383
  return [
2112
2384
  `\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`,
2113
2385
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2114
- "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",
2386
+ "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",
2115
2387
  `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`,
2116
2388
  ' \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',
2117
- "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"
2389
+ "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"
2118
2390
  ].join("\n");
2119
2391
  };
2120
2392
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2422,6 +2694,16 @@ function createApplySystemReminderStage() {
2422
2694
  };
2423
2695
  }
2424
2696
 
2697
+ // src/runtime-kernel/token-accounting/functions.ts
2698
+ function createContextComponentLedgerEntry(input) {
2699
+ return {
2700
+ ...input,
2701
+ kind: "context-component",
2702
+ components: [...input.components],
2703
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2704
+ };
2705
+ }
2706
+
2425
2707
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2426
2708
  var logger4 = new Logger("GraphAgentExecutor");
2427
2709
  function createBuildContextStage(dependencies) {
@@ -2438,6 +2720,23 @@ function createBuildContextStage(dependencies) {
2438
2720
  ctx.mode = contextBuildResult.mode;
2439
2721
  ctx.llmMessages = contextBuildResult.llmMessages;
2440
2722
  ctx.contextTrace = contextBuildResult.contextTrace;
2723
+ if (contextBuildResult.tokenEstimate) {
2724
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2725
+ ctx.telemetry.emit({
2726
+ kind: "context_build",
2727
+ modelId: ctx.modelId,
2728
+ mode: contextBuildResult.mode,
2729
+ tokenEstimate: contextBuildResult.tokenEstimate,
2730
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2731
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2732
+ scope: {
2733
+ conversationId: ctx.conversationId,
2734
+ runId: ctx.input.toolContext?.runId,
2735
+ parentRunId: ctx.input.toolContext?.parentRunId,
2736
+ turnId: ctx.turnId
2737
+ }
2738
+ });
2739
+ }
2441
2740
  for (const event of contextBuildResult.summaryEvents) {
2442
2741
  if (!isHistorySummaryEvent(event)) {
2443
2742
  continue;
@@ -2452,6 +2751,24 @@ function createBuildContextStage(dependencies) {
2452
2751
  }
2453
2752
  };
2454
2753
  }
2754
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2755
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2756
+ if (keptComponents.length === 0) {
2757
+ return void 0;
2758
+ }
2759
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2760
+ const createdAt = Date.now();
2761
+ return createContextComponentLedgerEntry({
2762
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2763
+ conversationId: ctx.conversationId,
2764
+ runId,
2765
+ parentRunId: ctx.input.toolContext?.parentRunId,
2766
+ turnId: ctx.turnId,
2767
+ route: contextBuildResult.tokenEstimate?.route,
2768
+ createdAt,
2769
+ components: keptComponents
2770
+ });
2771
+ }
2455
2772
 
2456
2773
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2457
2774
  function createBuildDecisionStage(dependencies) {
@@ -2682,6 +2999,7 @@ var GraphAgentExecutor = class {
2682
2999
  modelCatalog;
2683
3000
  telemetryPort;
2684
3001
  auditPort;
3002
+ tokenizer;
2685
3003
  stages;
2686
3004
  middlewares;
2687
3005
  constructor(dependencies) {
@@ -2695,6 +3013,7 @@ var GraphAgentExecutor = class {
2695
3013
  });
2696
3014
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2697
3015
  this.auditPort = dependencies.auditPort ?? noopAudit;
3016
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2698
3017
  this.stages = [
2699
3018
  createPrepareCallStage({
2700
3019
  modelResolver: this.modelResolver,
@@ -2738,7 +3057,8 @@ var GraphAgentExecutor = class {
2738
3057
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2739
3058
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2740
3059
  telemetry: this.telemetryPort,
2741
- audit: this.auditPort
3060
+ audit: this.auditPort,
3061
+ tokenizer: this.tokenizer
2742
3062
  };
2743
3063
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2744
3064
  stream: input.stream === true,
@@ -3703,11 +4023,11 @@ function buildToolOutputUiMeta(params) {
3703
4023
  }
3704
4024
  async function applyObservationGovernance(params) {
3705
4025
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3706
- return;
4026
+ return {};
3707
4027
  }
3708
4028
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3709
4029
  if (!policy.enabled) {
3710
- return;
4030
+ return {};
3711
4031
  }
3712
4032
  const truncated = await params.observationPreview.truncateObservation({
3713
4033
  context: params.toolContext,
@@ -3721,13 +4041,37 @@ async function applyObservationGovernance(params) {
3721
4041
  })
3722
4042
  });
3723
4043
  if (!truncated.truncated) {
3724
- return;
4044
+ return {};
3725
4045
  }
3726
4046
  params.parsed["observation"] = truncated.preview;
3727
4047
  const data = params.parsed["data"];
3728
4048
  if (isRecord9(data) && !("tool_output_store" in data)) {
3729
4049
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3730
4050
  }
4051
+ return {
4052
+ observationTruncation: buildObservationTruncationMeta({
4053
+ originalText: params.structuredObservation,
4054
+ previewText: truncated.preview,
4055
+ originalChars: truncated.originalChars,
4056
+ previewChars: truncated.previewChars,
4057
+ originalLines: truncated.originalLines,
4058
+ previewLines: truncated.previewLines
4059
+ })
4060
+ };
4061
+ }
4062
+ function buildObservationTruncationMeta(input) {
4063
+ return {
4064
+ originalChars: input.originalChars ?? input.originalText.length,
4065
+ previewChars: input.previewChars ?? input.previewText.length,
4066
+ originalLines: input.originalLines ?? countLines(input.originalText),
4067
+ previewLines: input.previewLines ?? countLines(input.previewText)
4068
+ };
4069
+ }
4070
+ function countLines(value) {
4071
+ if (value.length === 0) {
4072
+ return 0;
4073
+ }
4074
+ return value.split(/\r\n|\r|\n/).length;
3731
4075
  }
3732
4076
 
3733
4077
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4603,7 +4947,7 @@ var ToolNode = class {
4603
4947
  parentRunId: context.toolContext.parentRunId
4604
4948
  });
4605
4949
  applyProtocolFuseState(context.local);
4606
- await applyObservationGovernance({
4950
+ const observationGovernance = await applyObservationGovernance({
4607
4951
  parsed: context.parsed,
4608
4952
  toolName: context.toolName,
4609
4953
  toolContext: context.toolContext,
@@ -4630,6 +4974,12 @@ var ToolNode = class {
4630
4974
  runtimeToolOutput,
4631
4975
  execIdempotency: context.exec.idempotency
4632
4976
  });
4977
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
4978
+ runtimeToolOutput.metadata = {
4979
+ ...runtimeToolOutput.metadata ?? {},
4980
+ observationTruncation: observationGovernance.observationTruncation
4981
+ };
4982
+ }
4633
4983
  const remainingCalls = context.calls.slice(1);
4634
4984
  context.state.local = buildSuccessLocalState({
4635
4985
  local: context.local,
@@ -5991,6 +6341,7 @@ async function callLlmStream(params) {
5991
6341
  const streamAnswerId = generateMessageId();
5992
6342
  let streamChunkSeq = 0;
5993
6343
  let capturedUsage = void 0;
6344
+ let capturedCanonicalUsage = void 0;
5994
6345
  const toolAccumulator = new ToolCallStreamAccumulator([
5995
6346
  "markdown_edit",
5996
6347
  "text_to_image",
@@ -6049,6 +6400,10 @@ async function callLlmStream(params) {
6049
6400
  if (typeof chunk !== "object" || chunk === null) {
6050
6401
  return;
6051
6402
  }
6403
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
6404
+ if (parsedCanonicalUsage.success) {
6405
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
6406
+ }
6052
6407
  if (chunk.content) {
6053
6408
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6054
6409
  fullResponse += chunk.content;
@@ -6133,6 +6488,12 @@ async function callLlmStream(params) {
6133
6488
  const onUsage = (usage2) => {
6134
6489
  capturedUsage = usage2;
6135
6490
  };
6491
+ const onCanonicalUsage = (usage2) => {
6492
+ const parsed = CanonicalLlmUsage.safeParse(usage2);
6493
+ if (parsed.success) {
6494
+ capturedCanonicalUsage = parsed.data;
6495
+ }
6496
+ };
6136
6497
  await aiEngine.chatCompletionStream(
6137
6498
  modelId,
6138
6499
  messages,
@@ -6145,7 +6506,8 @@ async function callLlmStream(params) {
6145
6506
  onError,
6146
6507
  onFinish,
6147
6508
  onThought,
6148
- onUsage
6509
+ onUsage,
6510
+ onCanonicalUsage
6149
6511
  );
6150
6512
  if (streamError) {
6151
6513
  throw streamError;
@@ -6153,12 +6515,13 @@ async function callLlmStream(params) {
6153
6515
  emitThoughtComplete(thoughtSegmenter.finalize());
6154
6516
  const mergedToolCalls = toolAccumulator.getToolCalls();
6155
6517
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6156
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
6518
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6157
6519
  return {
6158
6520
  content: fullResponse,
6159
6521
  tool_calls: mergedToolCalls,
6160
6522
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6161
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
6523
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
6524
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6162
6525
  };
6163
6526
  }
6164
6527
  return fullResponse;
@@ -6208,6 +6571,10 @@ function tryCloudQuotaFallback({
6208
6571
  }
6209
6572
 
6210
6573
  // src/runtime-kernel/llm/usage-telemetry.ts
6574
+ function parseCanonicalUsage(value) {
6575
+ const parsed = CanonicalLlmUsage.safeParse(value);
6576
+ return parsed.success ? parsed.data : void 0;
6577
+ }
6211
6578
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6212
6579
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6213
6580
  return normalizeCompletionResponse(response);
@@ -6218,6 +6585,7 @@ function normalizeCompletionResponse(response) {
6218
6585
  }
6219
6586
  if (isRecord17(response)) {
6220
6587
  const usage2 = response["usage"];
6588
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6221
6589
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6222
6590
  if (parsedToolCalls) {
6223
6591
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6225,7 +6593,8 @@ function normalizeCompletionResponse(response) {
6225
6593
  content: typeof response["content"] === "string" ? response["content"] : "",
6226
6594
  tool_calls: parsedToolCalls,
6227
6595
  reasoning_details: reasoningDetails,
6228
- ...usage2 !== void 0 ? { usage: usage2 } : {}
6596
+ ...usage2 !== void 0 ? { usage: usage2 } : {},
6597
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6229
6598
  };
6230
6599
  }
6231
6600
  }
@@ -6235,10 +6604,12 @@ function normalizeCompletionResponse(response) {
6235
6604
  if (typeof response === "object") {
6236
6605
  if (isRecord17(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6237
6606
  const usage2 = response["usage"];
6607
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6238
6608
  return {
6239
6609
  content: typeof response["content"] === "string" ? response["content"] : "",
6240
6610
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6241
- ...usage2 !== void 0 ? { usage: usage2 } : {}
6611
+ ...usage2 !== void 0 ? { usage: usage2 } : {},
6612
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6242
6613
  };
6243
6614
  }
6244
6615
  if (isRecord17(response)) {
@@ -7840,7 +8211,7 @@ function createQuickstartTemplateFiles(projectName) {
7840
8211
  start: 'linnkit run hello --input "\u4F60\u597D\uFF0C\u4ECB\u7ECD\u4E00\u4E0B\u4F60\u81EA\u5DF1"'
7841
8212
  },
7842
8213
  dependencies: {
7843
- "@linnlabs/linnkit": "^0.10.0",
8214
+ "@linnlabs/linnkit": "^0.16.0",
7844
8215
  zod: "^3.22.0"
7845
8216
  },
7846
8217
  devDependencies: {}