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