@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/testkit.js CHANGED
@@ -104,7 +104,11 @@ __export(runtime_kernel_exports, {
104
104
  ToolNode: () => ToolNode,
105
105
  UserNode: () => UserNode,
106
106
  WaitUserNode: () => WaitUserNode,
107
+ addLedgerAggregate: () => addLedgerAggregate,
108
+ addUsageTotals: () => addUsageTotals,
107
109
  agentHasToolTrigger: () => agentHasToolTrigger,
110
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
111
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
108
112
  appendStreamingProviderReasoningDetails: () => appendStreamingProviderReasoningDetails,
109
113
  applySystemReminders: () => applySystemReminders,
110
114
  audit: () => audit_exports,
@@ -113,6 +117,7 @@ __export(runtime_kernel_exports, {
113
117
  childRuns: () => child_runs_exports,
114
118
  compactProviderReasoningDetails: () => compactProviderReasoningDetails,
115
119
  compactReasoningDetailsInValue: () => compactReasoningDetailsInValue,
120
+ computeCost: () => computeCost,
116
121
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
117
122
  consoleAudit: () => consoleAudit,
118
123
  contextBudgetWarningTemplate: () => contextBudgetWarningTemplate,
@@ -121,13 +126,16 @@ __export(runtime_kernel_exports, {
121
126
  createCompositeAudit: () => createCompositeAudit,
122
127
  createConsoleAudit: () => createConsoleAudit,
123
128
  createContextCheckpointTool: () => createContextCheckpointTool,
129
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
124
130
  createDefaultGraphExecutor: () => createDefaultGraphExecutor,
125
131
  createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
126
132
  createDefaultTokenizerPort: () => createDefaultTokenizerPort,
127
133
  createEventStoreAudit: () => createEventStoreAudit,
128
134
  createFileAudit: () => createFileAudit,
129
135
  createGraphLoopHarness: () => createGraphLoopHarness,
136
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
130
137
  createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
138
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
131
139
  createSystemReminderRules: () => createSystemReminderRules,
132
140
  defaultPolicyEngine: () => defaultPolicyEngine,
133
141
  defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
@@ -164,6 +172,7 @@ __export(runtime_kernel_exports, {
164
172
  systemReminder: () => system_reminder_exports,
165
173
  telemetry: () => telemetry_exports,
166
174
  toDisplayStep: () => toDisplayStep,
175
+ tokenAccounting: () => token_accounting_exports,
167
176
  toolCallStreakTemplate: () => toolCallStreakTemplate,
168
177
  toolCallStreakTrigger: () => toolCallStreakTrigger,
169
178
  tools: () => tools_exports
@@ -297,6 +306,12 @@ z.object({
297
306
  args: z.record(z.unknown()).optional(),
298
307
  tool_call_id: z.string()
299
308
  });
309
+ var ObservationTruncationMeta = z.object({
310
+ originalChars: z.number().int().nonnegative(),
311
+ previewChars: z.number().int().nonnegative(),
312
+ originalLines: z.number().int().nonnegative().optional(),
313
+ previewLines: z.number().int().nonnegative().optional()
314
+ });
300
315
  var ImageInfoMeta = z.object({
301
316
  url: z.string().optional(),
302
317
  width: z.number().int().positive().optional(),
@@ -328,6 +343,7 @@ var PersistentMetadata = z.object({
328
343
  tool_name: z.string().optional(),
329
344
  args: z.record(z.unknown()).optional(),
330
345
  tool_call_id: z.string().optional(),
346
+ observationTruncation: ObservationTruncationMeta.optional(),
331
347
  raw_output: z.string().optional(),
332
348
  image_info: ImageInfoMeta.optional(),
333
349
  taskType: z.string().optional(),
@@ -474,7 +490,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
474
490
  var AgentSpecTokenEstimationPolicy = z.object({
475
491
  encoding: z.string().min(1).optional(),
476
492
  avgCharsPerToken: z.number().positive().optional(),
477
- toolCallOverhead: z.number().int().nonnegative().optional()
493
+ toolCallOverhead: z.number().int().nonnegative().optional(),
494
+ calibration: z.object({
495
+ enabled: z.boolean().optional(),
496
+ minSamples: z.number().int().positive().optional(),
497
+ minCoefficient: z.number().positive().optional(),
498
+ maxCoefficient: z.number().positive().optional()
499
+ }).optional(),
500
+ remoteCount: z.object({
501
+ enabled: z.boolean().optional(),
502
+ failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
503
+ }).optional()
478
504
  });
479
505
  var AgentSpecSystemReminderTrigger = z.object({
480
506
  kind: z.string().min(1),
@@ -1172,6 +1198,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1172
1198
  error,
1173
1199
  ...options
1174
1200
  });
1201
+ var TokenCountSource = z.enum([
1202
+ "local-estimate",
1203
+ "provider-preflight-count",
1204
+ "provider-response-usage",
1205
+ "host-supplied",
1206
+ "test-fixture"
1207
+ ]);
1208
+ var TokenCountConfidence = z.enum([
1209
+ "estimate",
1210
+ "provider-estimate",
1211
+ "actual"
1212
+ ]);
1213
+ var TokenRouteCapabilities = z.object({
1214
+ supportsRemoteTokenCount: z.boolean().optional(),
1215
+ supportsResponseUsage: z.boolean().optional(),
1216
+ supportsImageInput: z.boolean().optional(),
1217
+ supportsCachedInputBilling: z.boolean().optional(),
1218
+ supportsReasoningTokens: z.boolean().optional()
1219
+ });
1220
+ var TokenRoute = z.object({
1221
+ providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1222
+ 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"),
1223
+ modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
1224
+ providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1225
+ capabilities: TokenRouteCapabilities.optional()
1226
+ });
1227
+ var tokenCount = z.number().int().nonnegative();
1228
+ var CanonicalLlmUsage = z.object({
1229
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1230
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1231
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1232
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1233
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1234
+ 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"),
1235
+ source: TokenCountSource,
1236
+ confidence: TokenCountConfidence,
1237
+ rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1238
+ });
1239
+ var tokenCount2 = z.number().int().nonnegative();
1240
+ var tokenPrice = z.number().finite().nonnegative();
1241
+ z.enum([
1242
+ "llm-usage",
1243
+ "context-component"
1244
+ ]);
1245
+ var ContextTokenComponentKind = z.enum([
1246
+ "system",
1247
+ "user",
1248
+ "assistant",
1249
+ "tool",
1250
+ "context-injection",
1251
+ "history-summary",
1252
+ "working-memory",
1253
+ "fence",
1254
+ "system-reminder",
1255
+ "other"
1256
+ ]);
1257
+ var TokenUsageTotals = z.object({
1258
+ inputTokens: tokenCount2,
1259
+ outputTokens: tokenCount2,
1260
+ reasoningTokens: tokenCount2.optional(),
1261
+ cacheReadTokens: tokenCount2.optional(),
1262
+ cacheWriteTokens: tokenCount2.optional(),
1263
+ totalTokens: tokenCount2.optional(),
1264
+ usageCount: z.number().int().nonnegative()
1265
+ });
1266
+ var ContextTokenComponent = z.object({
1267
+ componentId: z.string().min(1),
1268
+ kind: ContextTokenComponentKind,
1269
+ tokens: tokenCount2,
1270
+ source: TokenCountSource,
1271
+ confidence: TokenCountConfidence,
1272
+ label: z.string().optional(),
1273
+ messageId: z.string().optional(),
1274
+ role: z.string().optional(),
1275
+ action: z.string().optional(),
1276
+ kept: z.boolean().optional(),
1277
+ truncatedAtExecution: z.boolean().optional(),
1278
+ originalTokensEstimate: tokenCount2.optional(),
1279
+ droppedTokensEstimate: tokenCount2.optional()
1280
+ });
1281
+ var TokenLedgerEntryBase = z.object({
1282
+ id: z.string().min(1),
1283
+ runId: z.string().optional(),
1284
+ parentRunId: z.string().optional(),
1285
+ conversationId: z.string().optional(),
1286
+ turnId: z.string().optional(),
1287
+ stepId: z.string().optional(),
1288
+ route: TokenRoute.optional(),
1289
+ createdAt: z.number().int().nonnegative().optional()
1290
+ });
1291
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1292
+ kind: z.literal("llm-usage"),
1293
+ modelId: z.string().optional(),
1294
+ usage: CanonicalLlmUsage
1295
+ });
1296
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1297
+ kind: z.literal("context-component"),
1298
+ components: z.array(ContextTokenComponent),
1299
+ totalTokens: tokenCount2
1300
+ });
1301
+ z.discriminatedUnion("kind", [
1302
+ LlmUsageTokenLedgerEntry,
1303
+ ContextComponentTokenLedgerEntry
1304
+ ]);
1305
+ var TokenLedgerAggregate = z.object({
1306
+ llmUsage: TokenUsageTotals.optional(),
1307
+ contextTokens: tokenCount2,
1308
+ entryCount: z.number().int().nonnegative(),
1309
+ llmCallCount: z.number().int().nonnegative(),
1310
+ contextComponentCount: z.number().int().nonnegative()
1311
+ });
1312
+ z.object({
1313
+ /**
1314
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1315
+ */
1316
+ own: TokenLedgerAggregate,
1317
+ children: TokenLedgerAggregate.optional()
1318
+ });
1319
+ var TokenCostComponent = z.enum([
1320
+ "input",
1321
+ "output",
1322
+ "reasoning",
1323
+ "cacheRead",
1324
+ "cacheWrite"
1325
+ ]);
1326
+ z.object({
1327
+ currency: z.string().min(1),
1328
+ unit: z.literal("per_1m_tokens"),
1329
+ input: tokenPrice.optional(),
1330
+ output: tokenPrice.optional(),
1331
+ reasoning: tokenPrice.optional(),
1332
+ cacheRead: tokenPrice.optional(),
1333
+ cacheWrite: tokenPrice.optional()
1334
+ });
1335
+ z.object({
1336
+ status: z.enum(["computed", "unknown"]),
1337
+ currency: z.string().optional(),
1338
+ inputCost: tokenPrice.optional(),
1339
+ outputCost: tokenPrice.optional(),
1340
+ reasoningCost: tokenPrice.optional(),
1341
+ cacheReadCost: tokenPrice.optional(),
1342
+ cacheWriteCost: tokenPrice.optional(),
1343
+ totalCost: tokenPrice.optional(),
1344
+ missingPriceComponents: z.array(TokenCostComponent).optional()
1345
+ });
1346
+ var tokenCount3 = z.number().int().nonnegative();
1347
+ var actualCalibrationSource = z.enum([
1348
+ "provider-response-usage",
1349
+ "host-supplied",
1350
+ "test-fixture"
1351
+ ]);
1352
+ z.object({
1353
+ route: TokenRoute,
1354
+ localEstimateTokens: tokenCount3,
1355
+ actualInputTokens: tokenCount3,
1356
+ source: actualCalibrationSource,
1357
+ confidence: z.literal("actual"),
1358
+ observedAt: z.number().int().nonnegative().optional(),
1359
+ runId: z.string().optional(),
1360
+ ledgerEntryId: z.string().optional()
1361
+ });
1362
+ z.object({
1363
+ enabled: z.boolean(),
1364
+ applied: z.boolean(),
1365
+ route: TokenRoute.optional(),
1366
+ sampleCount: z.number().int().nonnegative(),
1367
+ coefficient: z.number().positive().optional(),
1368
+ minSamples: z.number().int().positive().optional(),
1369
+ minCoefficient: z.number().positive().optional(),
1370
+ maxCoefficient: z.number().positive().optional(),
1371
+ localEstimateTokens: tokenCount3.optional(),
1372
+ calibratedEstimateTokens: tokenCount3.optional(),
1373
+ deltaTokens: z.number().int().optional(),
1374
+ sampleLedgerEntryIds: z.array(z.string()).optional()
1375
+ });
1376
+ z.object({
1377
+ route: TokenRoute.optional(),
1378
+ localEstimateTokens: tokenCount3,
1379
+ calibratedEstimateTokens: tokenCount3,
1380
+ finalTokens: tokenCount3,
1381
+ source: z.literal("local-estimate"),
1382
+ confidence: z.literal("estimate")
1383
+ });
1175
1384
 
1176
1385
  // src/runtime-kernel/graph-engine/engine.ts
1177
1386
  var logger = new Logger("GraphExecutor");
@@ -1575,6 +1784,190 @@ var noopAudit = {
1575
1784
  flush() {
1576
1785
  }
1577
1786
  };
1787
+ var TokenCalculator = class {
1788
+ static BYTES_PER_TOKEN_LATIN = 4;
1789
+ static BYTES_PER_TOKEN_CJK = 3;
1790
+ static OVERHEAD_PER_MESSAGE = 5;
1791
+ static OVERHEAD_PER_TOOL_CALL = 10;
1792
+ static encoderCache = /* @__PURE__ */ new Map();
1793
+ static DEFAULT_ENCODING = "cl100k_base";
1794
+ static SUPPORTED_ENCODINGS = [
1795
+ "gpt2",
1796
+ "r50k_base",
1797
+ "p50k_base",
1798
+ "p50k_edit",
1799
+ "cl100k_base",
1800
+ "o200k_base"
1801
+ ];
1802
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1803
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1804
+ if (this.isSupportedEncodingName(normalized)) {
1805
+ return normalized;
1806
+ }
1807
+ if (normalized.includes("deepseek")) {
1808
+ return "cl100k_base";
1809
+ }
1810
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1811
+ return "o200k_base";
1812
+ }
1813
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1814
+ return "cl100k_base";
1815
+ }
1816
+ return this.DEFAULT_ENCODING;
1817
+ }
1818
+ static isSupportedEncodingName(value) {
1819
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1820
+ }
1821
+ static getEncoder(modelIdentifierOrEncoding) {
1822
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1823
+ const cached = this.encoderCache.get(encodingName);
1824
+ if (cached) {
1825
+ return cached;
1826
+ }
1827
+ const encoder = get_encoding(encodingName);
1828
+ this.encoderCache.set(encodingName, encoder);
1829
+ return encoder;
1830
+ }
1831
+ static estimateTokensRough(text, _modelIdentifier) {
1832
+ if (!text) return 0;
1833
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1834
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1835
+ const byteLength = new TextEncoder().encode(text).length;
1836
+ return Math.ceil(byteLength / ratio);
1837
+ }
1838
+ static estimateTokens(text, options = {}) {
1839
+ if (!text) return 0;
1840
+ if (options.encoding) {
1841
+ try {
1842
+ return this.estimateTokensPrecise(text, options.encoding);
1843
+ } catch {
1844
+ }
1845
+ }
1846
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1847
+ return Math.ceil(text.length / avgCharsPerToken);
1848
+ }
1849
+ static estimateTokensPrecise(text, modelIdentifier) {
1850
+ if (!text) return 0;
1851
+ const encoder = this.getEncoder(modelIdentifier);
1852
+ return encoder.encode(text).length;
1853
+ }
1854
+ static estimateMessageTokens(message, options = {}) {
1855
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1856
+ if (message.content) {
1857
+ totalTokens += this.estimateTokens(String(message.content), options);
1858
+ }
1859
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1860
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1861
+ for (const toolCall of toolCalls) {
1862
+ totalTokens += toolCallOverhead;
1863
+ const fn = toolCall["function"];
1864
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1865
+ const fnRecord = fn;
1866
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1867
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1868
+ }
1869
+ }
1870
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1871
+ if (toolCallId) {
1872
+ totalTokens += this.estimateTokens(toolCallId, options);
1873
+ }
1874
+ return totalTokens;
1875
+ }
1876
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1877
+ return this.estimateMessageTokens(message, {
1878
+ encoding: modelIdentifier,
1879
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1880
+ });
1881
+ }
1882
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1883
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1884
+ }
1885
+ static extractToolCallsForTokenEstimate(message) {
1886
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1887
+ if (Array.isArray(direct)) return direct;
1888
+ const metadata = "metadata" in message ? message.metadata : void 0;
1889
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1890
+ const metadataRecord = metadata;
1891
+ const metadataToolCalls = metadataRecord["tool_calls"];
1892
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1893
+ }
1894
+ static extractToolCallIdForTokenEstimate(message) {
1895
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1896
+ return message.tool_call_id;
1897
+ }
1898
+ const metadata = "metadata" in message ? message.metadata : void 0;
1899
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1900
+ const metadataRecord = metadata;
1901
+ const toolCallId = metadataRecord["tool_call_id"];
1902
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1903
+ }
1904
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1905
+ if (!text || maxTokens <= 0) return "";
1906
+ const encoder = this.getEncoder(modelIdentifier);
1907
+ const tokens = encoder.encode(text);
1908
+ if (tokens.length <= maxTokens) {
1909
+ return text;
1910
+ }
1911
+ let truncatedTokens;
1912
+ const ellipsis = "...";
1913
+ switch (strategy) {
1914
+ case "start":
1915
+ truncatedTokens = tokens.slice(0, maxTokens);
1916
+ return encoder.decode(truncatedTokens) + ellipsis;
1917
+ case "end":
1918
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1919
+ return ellipsis + encoder.decode(truncatedTokens);
1920
+ case "middle": {
1921
+ const half = Math.floor(maxTokens / 2);
1922
+ const head = tokens.slice(0, half);
1923
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1924
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1925
+ }
1926
+ default:
1927
+ truncatedTokens = tokens.slice(0, maxTokens);
1928
+ return encoder.decode(truncatedTokens) + ellipsis;
1929
+ }
1930
+ }
1931
+ static cleanup() {
1932
+ for (const encoder of this.encoderCache.values()) {
1933
+ encoder.free();
1934
+ }
1935
+ this.encoderCache.clear();
1936
+ }
1937
+ };
1938
+ function normalizePositiveNumber(value, fallback) {
1939
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1940
+ }
1941
+ function normalizeNonNegativeInteger(value, fallback) {
1942
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1943
+ return fallback;
1944
+ }
1945
+ return Math.max(0, Math.floor(value));
1946
+ }
1947
+
1948
+ // src/shared/defaultTokenizerPort.ts
1949
+ var DefaultTokenizerPort = class {
1950
+ constructor(config = {}) {
1951
+ this.config = config;
1952
+ }
1953
+ config;
1954
+ estimateText(text, _modelId) {
1955
+ return TokenCalculator.estimateTokens(text, {
1956
+ encoding: this.config.encoding,
1957
+ avgCharsPerToken: this.config.avgCharsPerToken
1958
+ });
1959
+ }
1960
+ estimateMessage(message, _modelId) {
1961
+ return TokenCalculator.estimateMessageTokens(message, {
1962
+ encoding: this.config.encoding,
1963
+ avgCharsPerToken: this.config.avgCharsPerToken,
1964
+ toolCallOverhead: this.config.toolCallOverhead
1965
+ });
1966
+ }
1967
+ };
1968
+ function createDefaultTokenizerPort(config = {}) {
1969
+ return new DefaultTokenizerPort(config);
1970
+ }
1578
1971
 
1579
1972
  // src/shared/ids.ts
1580
1973
  function isoRandomUUID() {
@@ -1755,237 +2148,117 @@ function resolveUsage(response) {
1755
2148
  }
1756
2149
  return response.usage;
1757
2150
  }
1758
- function resolveToolCalls(response) {
2151
+ function resolveCanonicalUsage(response) {
1759
2152
  if (!response || typeof response === "string") {
1760
2153
  return void 0;
1761
2154
  }
1762
- return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
2155
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2156
+ return parsed.success ? parsed.data : void 0;
1763
2157
  }
1764
- function resolveReasoningDetails(response) {
2158
+ function resolveToolCalls(response) {
1765
2159
  if (!response || typeof response === "string") {
1766
- return void 0;
1767
- }
1768
- return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
1769
- }
1770
- function resolveToolNamesForAudit(ctx) {
1771
- if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
1772
- return [];
1773
- }
1774
- return ctx.toolSchemas.map((tool) => tool.function.name);
1775
- }
1776
- function recordBeforeContextManager(params) {
1777
- }
1778
- function recordAfterContextManager(params) {
1779
- }
1780
- function recordAfterContextManagerOnSystemReminderHit(params) {
1781
- }
1782
- function recordToolProtocolError(params) {
1783
- }
1784
- function recordRunTranscript(params) {
1785
- }
1786
-
1787
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
1788
- var contextAuditMiddleware = async (ctx, stage, next) => {
1789
- if (stage.id === "build_context") {
1790
- recordBeforeContextManager({
1791
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
1792
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1793
- });
1794
- }
1795
- await next();
1796
- if (stage.id !== "apply_system_reminder") {
1797
- return;
1798
- }
1799
- resolveToolNamesForAudit(ctx);
1800
- recordAfterContextManager({
1801
- mode: ctx.mode,
1802
- llmMessages: ctx.llmMessages,
1803
- contextTrace: ctx.contextTrace
1804
- });
1805
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
1806
- recordAfterContextManagerOnSystemReminderHit({
1807
- mode: ctx.mode,
1808
- llmMessages: ctx.llmMessages,
1809
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
1810
- contextTrace: ctx.contextTrace
1811
- });
1812
- }
1813
- };
1814
- var TokenCalculator = class {
1815
- static BYTES_PER_TOKEN_LATIN = 4;
1816
- static BYTES_PER_TOKEN_CJK = 3;
1817
- static OVERHEAD_PER_MESSAGE = 5;
1818
- static OVERHEAD_PER_TOOL_CALL = 10;
1819
- static encoderCache = /* @__PURE__ */ new Map();
1820
- static DEFAULT_ENCODING = "cl100k_base";
1821
- static SUPPORTED_ENCODINGS = [
1822
- "gpt2",
1823
- "r50k_base",
1824
- "p50k_base",
1825
- "p50k_edit",
1826
- "cl100k_base",
1827
- "o200k_base"
1828
- ];
1829
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1830
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1831
- if (this.isSupportedEncodingName(normalized)) {
1832
- return normalized;
1833
- }
1834
- if (normalized.includes("deepseek")) {
1835
- return "cl100k_base";
1836
- }
1837
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1838
- return "o200k_base";
1839
- }
1840
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1841
- return "cl100k_base";
1842
- }
1843
- return this.DEFAULT_ENCODING;
1844
- }
1845
- static isSupportedEncodingName(value) {
1846
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1847
- }
1848
- static getEncoder(modelIdentifierOrEncoding) {
1849
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1850
- const cached = this.encoderCache.get(encodingName);
1851
- if (cached) {
1852
- return cached;
1853
- }
1854
- const encoder = get_encoding(encodingName);
1855
- this.encoderCache.set(encodingName, encoder);
1856
- return encoder;
1857
- }
1858
- static estimateTokensRough(text, _modelIdentifier) {
1859
- if (!text) return 0;
1860
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1861
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1862
- const byteLength = new TextEncoder().encode(text).length;
1863
- return Math.ceil(byteLength / ratio);
1864
- }
1865
- static estimateTokens(text, options = {}) {
1866
- if (!text) return 0;
1867
- if (options.encoding) {
1868
- try {
1869
- return this.estimateTokensPrecise(text, options.encoding);
1870
- } catch {
1871
- }
1872
- }
1873
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1874
- return Math.ceil(text.length / avgCharsPerToken);
1875
- }
1876
- static estimateTokensPrecise(text, modelIdentifier) {
1877
- if (!text) return 0;
1878
- const encoder = this.getEncoder(modelIdentifier);
1879
- return encoder.encode(text).length;
1880
- }
1881
- static estimateMessageTokens(message, options = {}) {
1882
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1883
- if (message.content) {
1884
- totalTokens += this.estimateTokens(String(message.content), options);
1885
- }
1886
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1887
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1888
- for (const toolCall of toolCalls) {
1889
- totalTokens += toolCallOverhead;
1890
- const fn = toolCall["function"];
1891
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1892
- const fnRecord = fn;
1893
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1894
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1895
- }
1896
- }
1897
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1898
- if (toolCallId) {
1899
- totalTokens += this.estimateTokens(toolCallId, options);
1900
- }
1901
- return totalTokens;
1902
- }
1903
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1904
- return this.estimateMessageTokens(message, {
1905
- encoding: modelIdentifier,
1906
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1907
- });
2160
+ return void 0;
1908
2161
  }
1909
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1910
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2162
+ return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
2163
+ }
2164
+ function resolveReasoningDetails(response) {
2165
+ if (!response || typeof response === "string") {
2166
+ return void 0;
1911
2167
  }
1912
- static extractToolCallsForTokenEstimate(message) {
1913
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1914
- if (Array.isArray(direct)) return direct;
1915
- const metadata = "metadata" in message ? message.metadata : void 0;
1916
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1917
- const metadataRecord = metadata;
1918
- const metadataToolCalls = metadataRecord["tool_calls"];
1919
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2168
+ return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2169
+ }
2170
+ function resolveToolNamesForAudit(ctx) {
2171
+ if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2172
+ return [];
1920
2173
  }
1921
- static extractToolCallIdForTokenEstimate(message) {
1922
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1923
- return message.tool_call_id;
1924
- }
1925
- const metadata = "metadata" in message ? message.metadata : void 0;
1926
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1927
- const metadataRecord = metadata;
1928
- const toolCallId = metadataRecord["tool_call_id"];
1929
- return typeof toolCallId === "string" ? toolCallId : void 0;
2174
+ return ctx.toolSchemas.map((tool) => tool.function.name);
2175
+ }
2176
+ function recordBeforeContextManager(params) {
2177
+ }
2178
+ function recordAfterContextManager(params) {
2179
+ }
2180
+ function recordAfterContextManagerOnSystemReminderHit(params) {
2181
+ }
2182
+ function recordToolProtocolError(params) {
2183
+ }
2184
+ function recordRunTranscript(params) {
2185
+ }
2186
+
2187
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2188
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2189
+ if (stage.id === "build_context") {
2190
+ recordBeforeContextManager({
2191
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2192
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2193
+ });
1930
2194
  }
1931
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1932
- if (!text || maxTokens <= 0) return "";
1933
- const encoder = this.getEncoder(modelIdentifier);
1934
- const tokens = encoder.encode(text);
1935
- if (tokens.length <= maxTokens) {
1936
- return text;
1937
- }
1938
- let truncatedTokens;
1939
- const ellipsis = "...";
1940
- switch (strategy) {
1941
- case "start":
1942
- truncatedTokens = tokens.slice(0, maxTokens);
1943
- return encoder.decode(truncatedTokens) + ellipsis;
1944
- case "end":
1945
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1946
- return ellipsis + encoder.decode(truncatedTokens);
1947
- case "middle": {
1948
- const half = Math.floor(maxTokens / 2);
1949
- const head = tokens.slice(0, half);
1950
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1951
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1952
- }
1953
- default:
1954
- truncatedTokens = tokens.slice(0, maxTokens);
1955
- return encoder.decode(truncatedTokens) + ellipsis;
1956
- }
2195
+ await next();
2196
+ if (stage.id !== "apply_system_reminder") {
2197
+ return;
1957
2198
  }
1958
- static cleanup() {
1959
- for (const encoder of this.encoderCache.values()) {
1960
- encoder.free();
1961
- }
1962
- this.encoderCache.clear();
2199
+ resolveToolNamesForAudit(ctx);
2200
+ recordAfterContextManager({
2201
+ mode: ctx.mode,
2202
+ llmMessages: ctx.llmMessages,
2203
+ contextTrace: ctx.contextTrace
2204
+ });
2205
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2206
+ recordAfterContextManagerOnSystemReminderHit({
2207
+ mode: ctx.mode,
2208
+ llmMessages: ctx.llmMessages,
2209
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2210
+ contextTrace: ctx.contextTrace
2211
+ });
1963
2212
  }
1964
2213
  };
1965
- function normalizePositiveNumber(value, fallback) {
1966
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2214
+ var als = new AsyncLocalStorage();
2215
+ function readTokenCount(record, key) {
2216
+ const value = record[key];
2217
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1967
2218
  }
1968
- function normalizeNonNegativeInteger(value, fallback) {
1969
- if (typeof value !== "number" || !Number.isFinite(value)) {
1970
- return fallback;
1971
- }
1972
- return Math.max(0, Math.floor(value));
2219
+ function readRecord(record, key) {
2220
+ const value = record[key];
2221
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2222
+ return Object.fromEntries(Object.entries(value));
1973
2223
  }
1974
- var als = new AsyncLocalStorage();
1975
- function normalizeLlmUsage(usage) {
2224
+ function normalizedUsageFromCanonical(canonicalUsage) {
2225
+ return {
2226
+ promptTokens: canonicalUsage.inputTokens,
2227
+ completionTokens: canonicalUsage.outputTokens,
2228
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2229
+ canonicalUsage
2230
+ };
2231
+ }
2232
+ function normalizeCanonicalLlmUsage(usage) {
1976
2233
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1977
2234
  const rec = usage;
1978
- const promptTokensRaw = rec["prompt_tokens"];
1979
- const completionTokensRaw = rec["completion_tokens"];
1980
- const totalTokensRaw = rec["total_tokens"];
1981
- const tokensRaw = rec["tokens"];
1982
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1983
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1984
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1985
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1986
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1987
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1988
- return { promptTokens, completionTokens, totalTokens };
2235
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2236
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2237
+ if (inputTokens === void 0 || outputTokens === void 0) {
2238
+ return void 0;
2239
+ }
2240
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2241
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2242
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2243
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2244
+ const totalTokens = readTokenCount(rec, "total_tokens");
2245
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2246
+ return void 0;
2247
+ }
2248
+ return {
2249
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2250
+ outputTokens,
2251
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2252
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2253
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2254
+ source: "provider-response-usage",
2255
+ confidence: "actual",
2256
+ rawUsage: usage
2257
+ };
2258
+ }
2259
+ function normalizeLlmUsage(usage) {
2260
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2261
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1989
2262
  }
1990
2263
  function recordLlmCallTelemetry(entry) {
1991
2264
  const store = als.getStore();
@@ -1999,17 +2272,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1999
2272
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2000
2273
  return;
2001
2274
  }
2002
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2275
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2276
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2003
2277
  const respText = extractResponseText(ctx.llmResp);
2004
2278
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2005
2279
  try {
2006
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2007
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2008
- return {
2009
- promptTokens,
2010
- completionTokens,
2011
- totalTokens: promptTokens + completionTokens
2012
- };
2280
+ const promptTokens = ctx.llmMessages.reduce(
2281
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2282
+ 0
2283
+ );
2284
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2285
+ return normalizedUsageFromCanonical({
2286
+ inputTokens: promptTokens,
2287
+ outputTokens: completionTokens,
2288
+ totalTokens: promptTokens + completionTokens,
2289
+ source: "local-estimate",
2290
+ confidence: "estimate"
2291
+ });
2013
2292
  } catch {
2014
2293
  return void 0;
2015
2294
  }
@@ -2019,7 +2298,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2019
2298
  stream: ctx.input.stream === true,
2020
2299
  startedAt: ctx.llmCallStartedAt,
2021
2300
  durationMs: ctx.llmCallDurationMs,
2022
- usage: normalizedUsage
2301
+ usage: normalizedUsage,
2302
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2023
2303
  });
2024
2304
  ctx.telemetry.emit({
2025
2305
  kind: "llm_call",
@@ -2027,6 +2307,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2027
2307
  stream: ctx.input.stream === true,
2028
2308
  durationMs: ctx.llmCallDurationMs,
2029
2309
  usage: normalizedUsage,
2310
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2030
2311
  scope: {
2031
2312
  conversationId: ctx.conversationId || void 0,
2032
2313
  turnId: ctx.turnId,
@@ -2170,10 +2451,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2170
2451
  return [
2171
2452
  `\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`,
2172
2453
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2173
- "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",
2454
+ "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",
2174
2455
  `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`,
2175
2456
  ' \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',
2176
- "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"
2457
+ "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"
2177
2458
  ].join("\n");
2178
2459
  };
2179
2460
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2481,6 +2762,219 @@ function createApplySystemReminderStage() {
2481
2762
  };
2482
2763
  }
2483
2764
 
2765
+ // src/runtime-kernel/token-accounting/index.ts
2766
+ var token_accounting_exports = {};
2767
+ __export(token_accounting_exports, {
2768
+ addLedgerAggregate: () => addLedgerAggregate,
2769
+ addUsageTotals: () => addUsageTotals,
2770
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
2771
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
2772
+ computeCost: () => computeCost,
2773
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
2774
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
2775
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
2776
+ });
2777
+
2778
+ // src/runtime-kernel/token-accounting/functions.ts
2779
+ var EMPTY_LEDGER_AGGREGATE = {
2780
+ contextTokens: 0,
2781
+ entryCount: 0,
2782
+ llmCallCount: 0,
2783
+ contextComponentCount: 0
2784
+ };
2785
+ var TOKEN_PRICE_UNIT = 1e6;
2786
+ function sumReportedOptional(values) {
2787
+ const reported = values.filter((value) => value !== void 0);
2788
+ if (reported.length === 0) {
2789
+ return void 0;
2790
+ }
2791
+ return reported.reduce((total, value) => total + value, 0);
2792
+ }
2793
+ function sumTotalTokens(usages) {
2794
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
2795
+ return void 0;
2796
+ }
2797
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
2798
+ }
2799
+ function aggregateCanonicalUsage(usages) {
2800
+ if (usages.length === 0) {
2801
+ return void 0;
2802
+ }
2803
+ return {
2804
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
2805
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
2806
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
2807
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
2808
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
2809
+ totalTokens: sumTotalTokens(usages),
2810
+ usageCount: usages.length
2811
+ };
2812
+ }
2813
+ function createLlmUsageLedgerEntry(input) {
2814
+ return {
2815
+ ...input,
2816
+ kind: "llm-usage"
2817
+ };
2818
+ }
2819
+ function createContextComponentLedgerEntry(input) {
2820
+ return {
2821
+ ...input,
2822
+ kind: "context-component",
2823
+ components: [...input.components],
2824
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2825
+ };
2826
+ }
2827
+ function addUsageTotals(left, right) {
2828
+ if (!left) {
2829
+ return right;
2830
+ }
2831
+ if (!right) {
2832
+ return left;
2833
+ }
2834
+ return {
2835
+ inputTokens: left.inputTokens + right.inputTokens,
2836
+ outputTokens: left.outputTokens + right.outputTokens,
2837
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
2838
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
2839
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
2840
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
2841
+ usageCount: left.usageCount + right.usageCount
2842
+ };
2843
+ }
2844
+ function addLedgerAggregate(left, right) {
2845
+ return {
2846
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
2847
+ contextTokens: left.contextTokens + right.contextTokens,
2848
+ entryCount: left.entryCount + right.entryCount,
2849
+ llmCallCount: left.llmCallCount + right.llmCallCount,
2850
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
2851
+ };
2852
+ }
2853
+ function aggregateTokenLedgerEntries(entries) {
2854
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
2855
+ return entries.reduce((aggregate, entry) => {
2856
+ if (entry.kind === "llm-usage") {
2857
+ return {
2858
+ ...aggregate,
2859
+ entryCount: aggregate.entryCount + 1,
2860
+ llmCallCount: aggregate.llmCallCount + 1
2861
+ };
2862
+ }
2863
+ return {
2864
+ ...aggregate,
2865
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
2866
+ entryCount: aggregate.entryCount + 1,
2867
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
2868
+ };
2869
+ }, {
2870
+ ...EMPTY_LEDGER_AGGREGATE,
2871
+ llmUsage: aggregateCanonicalUsage(llmUsages)
2872
+ });
2873
+ }
2874
+ function createRunTokenUsageAggregate(input) {
2875
+ const children = input.childAggregates?.reduce(
2876
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
2877
+ EMPTY_LEDGER_AGGREGATE
2878
+ );
2879
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
2880
+ }
2881
+ function componentCost(tokens, pricePerMillion) {
2882
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
2883
+ }
2884
+ function needsPrice(tokens) {
2885
+ return tokens !== void 0 && tokens > 0;
2886
+ }
2887
+ function missingPriceComponents(usage, pricing) {
2888
+ const missing = [];
2889
+ if (!pricing) {
2890
+ if (needsPrice(usage.inputTokens)) {
2891
+ missing.push("input");
2892
+ }
2893
+ if (needsPrice(usage.outputTokens)) {
2894
+ missing.push("output");
2895
+ }
2896
+ if (needsPrice(usage.reasoningTokens)) {
2897
+ missing.push("reasoning");
2898
+ }
2899
+ if (needsPrice(usage.cacheReadTokens)) {
2900
+ missing.push("cacheRead");
2901
+ }
2902
+ if (needsPrice(usage.cacheWriteTokens)) {
2903
+ missing.push("cacheWrite");
2904
+ }
2905
+ return missing;
2906
+ }
2907
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
2908
+ missing.push("input");
2909
+ }
2910
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
2911
+ missing.push("output");
2912
+ }
2913
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
2914
+ missing.push("reasoning");
2915
+ }
2916
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
2917
+ missing.push("cacheRead");
2918
+ }
2919
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
2920
+ missing.push("cacheWrite");
2921
+ }
2922
+ return missing;
2923
+ }
2924
+ function reportedComponentCost(tokens, pricePerMillion) {
2925
+ if (tokens === void 0) {
2926
+ return void 0;
2927
+ }
2928
+ if (tokens === 0) {
2929
+ return 0;
2930
+ }
2931
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
2932
+ }
2933
+ function requiredComponentCost(tokens, pricePerMillion) {
2934
+ if (tokens === 0) {
2935
+ return 0;
2936
+ }
2937
+ return componentCost(tokens, pricePerMillion ?? 0);
2938
+ }
2939
+ function sumComputedCosts(costs) {
2940
+ let total = 0;
2941
+ for (const cost of costs) {
2942
+ total += cost ?? 0;
2943
+ }
2944
+ return total;
2945
+ }
2946
+ function computeCost(usage, pricing) {
2947
+ const missing = missingPriceComponents(usage, pricing);
2948
+ if (!pricing || missing.length > 0) {
2949
+ return {
2950
+ status: "unknown",
2951
+ ...pricing ? { currency: pricing.currency } : {},
2952
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
2953
+ };
2954
+ }
2955
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
2956
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
2957
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
2958
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
2959
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
2960
+ return {
2961
+ status: "computed",
2962
+ currency: pricing.currency,
2963
+ inputCost,
2964
+ outputCost,
2965
+ reasoningCost,
2966
+ cacheReadCost,
2967
+ cacheWriteCost,
2968
+ totalCost: sumComputedCosts([
2969
+ inputCost,
2970
+ outputCost,
2971
+ reasoningCost,
2972
+ cacheReadCost,
2973
+ cacheWriteCost
2974
+ ])
2975
+ };
2976
+ }
2977
+
2484
2978
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2485
2979
  var logger4 = new Logger("GraphAgentExecutor");
2486
2980
  function createBuildContextStage(dependencies) {
@@ -2497,6 +2991,23 @@ function createBuildContextStage(dependencies) {
2497
2991
  ctx.mode = contextBuildResult.mode;
2498
2992
  ctx.llmMessages = contextBuildResult.llmMessages;
2499
2993
  ctx.contextTrace = contextBuildResult.contextTrace;
2994
+ if (contextBuildResult.tokenEstimate) {
2995
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2996
+ ctx.telemetry.emit({
2997
+ kind: "context_build",
2998
+ modelId: ctx.modelId,
2999
+ mode: contextBuildResult.mode,
3000
+ tokenEstimate: contextBuildResult.tokenEstimate,
3001
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
3002
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
3003
+ scope: {
3004
+ conversationId: ctx.conversationId,
3005
+ runId: ctx.input.toolContext?.runId,
3006
+ parentRunId: ctx.input.toolContext?.parentRunId,
3007
+ turnId: ctx.turnId
3008
+ }
3009
+ });
3010
+ }
2500
3011
  for (const event of contextBuildResult.summaryEvents) {
2501
3012
  if (!isHistorySummaryEvent(event)) {
2502
3013
  continue;
@@ -2511,6 +3022,24 @@ function createBuildContextStage(dependencies) {
2511
3022
  }
2512
3023
  };
2513
3024
  }
3025
+ function createContextLedgerEntry(ctx, contextBuildResult) {
3026
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
3027
+ if (keptComponents.length === 0) {
3028
+ return void 0;
3029
+ }
3030
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
3031
+ const createdAt = Date.now();
3032
+ return createContextComponentLedgerEntry({
3033
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
3034
+ conversationId: ctx.conversationId,
3035
+ runId,
3036
+ parentRunId: ctx.input.toolContext?.parentRunId,
3037
+ turnId: ctx.turnId,
3038
+ route: contextBuildResult.tokenEstimate?.route,
3039
+ createdAt,
3040
+ components: keptComponents
3041
+ });
3042
+ }
2514
3043
 
2515
3044
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2516
3045
  function createBuildDecisionStage(dependencies) {
@@ -2754,6 +3283,7 @@ var GraphAgentExecutor = class {
2754
3283
  modelCatalog;
2755
3284
  telemetryPort;
2756
3285
  auditPort;
3286
+ tokenizer;
2757
3287
  stages;
2758
3288
  middlewares;
2759
3289
  constructor(dependencies) {
@@ -2767,6 +3297,7 @@ var GraphAgentExecutor = class {
2767
3297
  });
2768
3298
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2769
3299
  this.auditPort = dependencies.auditPort ?? noopAudit;
3300
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2770
3301
  this.stages = [
2771
3302
  createPrepareCallStage({
2772
3303
  modelResolver: this.modelResolver,
@@ -2810,7 +3341,8 @@ var GraphAgentExecutor = class {
2810
3341
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2811
3342
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2812
3343
  telemetry: this.telemetryPort,
2813
- audit: this.auditPort
3344
+ audit: this.auditPort,
3345
+ tokenizer: this.tokenizer
2814
3346
  };
2815
3347
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2816
3348
  stream: input.stream === true,
@@ -3775,11 +4307,11 @@ function buildToolOutputUiMeta(params) {
3775
4307
  }
3776
4308
  async function applyObservationGovernance(params) {
3777
4309
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3778
- return;
4310
+ return {};
3779
4311
  }
3780
4312
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3781
4313
  if (!policy.enabled) {
3782
- return;
4314
+ return {};
3783
4315
  }
3784
4316
  const truncated = await params.observationPreview.truncateObservation({
3785
4317
  context: params.toolContext,
@@ -3793,13 +4325,37 @@ async function applyObservationGovernance(params) {
3793
4325
  })
3794
4326
  });
3795
4327
  if (!truncated.truncated) {
3796
- return;
4328
+ return {};
3797
4329
  }
3798
4330
  params.parsed["observation"] = truncated.preview;
3799
4331
  const data = params.parsed["data"];
3800
4332
  if (isRecord9(data) && !("tool_output_store" in data)) {
3801
4333
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3802
4334
  }
4335
+ return {
4336
+ observationTruncation: buildObservationTruncationMeta({
4337
+ originalText: params.structuredObservation,
4338
+ previewText: truncated.preview,
4339
+ originalChars: truncated.originalChars,
4340
+ previewChars: truncated.previewChars,
4341
+ originalLines: truncated.originalLines,
4342
+ previewLines: truncated.previewLines
4343
+ })
4344
+ };
4345
+ }
4346
+ function buildObservationTruncationMeta(input) {
4347
+ return {
4348
+ originalChars: input.originalChars ?? input.originalText.length,
4349
+ previewChars: input.previewChars ?? input.previewText.length,
4350
+ originalLines: input.originalLines ?? countLines(input.originalText),
4351
+ previewLines: input.previewLines ?? countLines(input.previewText)
4352
+ };
4353
+ }
4354
+ function countLines(value) {
4355
+ if (value.length === 0) {
4356
+ return 0;
4357
+ }
4358
+ return value.split(/\r\n|\r|\n/).length;
3803
4359
  }
3804
4360
 
3805
4361
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4762,7 +5318,7 @@ var ToolNode = class {
4762
5318
  parentRunId: context.toolContext.parentRunId
4763
5319
  });
4764
5320
  applyProtocolFuseState(context.local);
4765
- await applyObservationGovernance({
5321
+ const observationGovernance = await applyObservationGovernance({
4766
5322
  parsed: context.parsed,
4767
5323
  toolName: context.toolName,
4768
5324
  toolContext: context.toolContext,
@@ -4789,6 +5345,12 @@ var ToolNode = class {
4789
5345
  runtimeToolOutput,
4790
5346
  execIdempotency: context.exec.idempotency
4791
5347
  });
5348
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5349
+ runtimeToolOutput.metadata = {
5350
+ ...runtimeToolOutput.metadata ?? {},
5351
+ observationTruncation: observationGovernance.observationTruncation
5352
+ };
5353
+ }
4792
5354
  const remainingCalls = context.calls.slice(1);
4793
5355
  context.state.local = buildSuccessLocalState({
4794
5356
  local: context.local,
@@ -6623,6 +7185,7 @@ async function callLlmStream(params) {
6623
7185
  const streamAnswerId = generateMessageId();
6624
7186
  let streamChunkSeq = 0;
6625
7187
  let capturedUsage = void 0;
7188
+ let capturedCanonicalUsage = void 0;
6626
7189
  const toolAccumulator = new ToolCallStreamAccumulator([
6627
7190
  "markdown_edit",
6628
7191
  "text_to_image",
@@ -6681,6 +7244,10 @@ async function callLlmStream(params) {
6681
7244
  if (typeof chunk !== "object" || chunk === null) {
6682
7245
  return;
6683
7246
  }
7247
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7248
+ if (parsedCanonicalUsage.success) {
7249
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7250
+ }
6684
7251
  if (chunk.content) {
6685
7252
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6686
7253
  fullResponse += chunk.content;
@@ -6765,6 +7332,12 @@ async function callLlmStream(params) {
6765
7332
  const onUsage = (usage) => {
6766
7333
  capturedUsage = usage;
6767
7334
  };
7335
+ const onCanonicalUsage = (usage) => {
7336
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7337
+ if (parsed.success) {
7338
+ capturedCanonicalUsage = parsed.data;
7339
+ }
7340
+ };
6768
7341
  await aiEngine.chatCompletionStream(
6769
7342
  modelId,
6770
7343
  messages,
@@ -6777,7 +7350,8 @@ async function callLlmStream(params) {
6777
7350
  onError,
6778
7351
  onFinish,
6779
7352
  onThought,
6780
- onUsage
7353
+ onUsage,
7354
+ onCanonicalUsage
6781
7355
  );
6782
7356
  if (streamError) {
6783
7357
  throw streamError;
@@ -6785,12 +7359,13 @@ async function callLlmStream(params) {
6785
7359
  emitThoughtComplete(thoughtSegmenter.finalize());
6786
7360
  const mergedToolCalls = toolAccumulator.getToolCalls();
6787
7361
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6788
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7362
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6789
7363
  return {
6790
7364
  content: fullResponse,
6791
7365
  tool_calls: mergedToolCalls,
6792
7366
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6793
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7367
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7368
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6794
7369
  };
6795
7370
  }
6796
7371
  return fullResponse;
@@ -6840,6 +7415,10 @@ function tryCloudQuotaFallback({
6840
7415
  }
6841
7416
 
6842
7417
  // src/runtime-kernel/llm/usage-telemetry.ts
7418
+ function parseCanonicalUsage(value) {
7419
+ const parsed = CanonicalLlmUsage.safeParse(value);
7420
+ return parsed.success ? parsed.data : void 0;
7421
+ }
6843
7422
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6844
7423
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6845
7424
  return normalizeCompletionResponse(response);
@@ -6850,6 +7429,7 @@ function normalizeCompletionResponse(response) {
6850
7429
  }
6851
7430
  if (isRecord19(response)) {
6852
7431
  const usage = response["usage"];
7432
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6853
7433
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6854
7434
  if (parsedToolCalls) {
6855
7435
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6857,7 +7437,8 @@ function normalizeCompletionResponse(response) {
6857
7437
  content: typeof response["content"] === "string" ? response["content"] : "",
6858
7438
  tool_calls: parsedToolCalls,
6859
7439
  reasoning_details: reasoningDetails,
6860
- ...usage !== void 0 ? { usage } : {}
7440
+ ...usage !== void 0 ? { usage } : {},
7441
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6861
7442
  };
6862
7443
  }
6863
7444
  }
@@ -6867,10 +7448,12 @@ function normalizeCompletionResponse(response) {
6867
7448
  if (typeof response === "object") {
6868
7449
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6869
7450
  const usage = response["usage"];
7451
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6870
7452
  return {
6871
7453
  content: typeof response["content"] === "string" ? response["content"] : "",
6872
7454
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6873
- ...usage !== void 0 ? { usage } : {}
7455
+ ...usage !== void 0 ? { usage } : {},
7456
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6874
7457
  };
6875
7458
  }
6876
7459
  if (isRecord19(response)) {
@@ -7124,30 +7707,6 @@ var LlmCaller = class {
7124
7707
  }
7125
7708
  };
7126
7709
 
7127
- // src/shared/defaultTokenizerPort.ts
7128
- var DefaultTokenizerPort = class {
7129
- constructor(config = {}) {
7130
- this.config = config;
7131
- }
7132
- config;
7133
- estimateText(text, _modelId) {
7134
- return TokenCalculator.estimateTokens(text, {
7135
- encoding: this.config.encoding,
7136
- avgCharsPerToken: this.config.avgCharsPerToken
7137
- });
7138
- }
7139
- estimateMessage(message, _modelId) {
7140
- return TokenCalculator.estimateMessageTokens(message, {
7141
- encoding: this.config.encoding,
7142
- avgCharsPerToken: this.config.avgCharsPerToken,
7143
- toolCallOverhead: this.config.toolCallOverhead
7144
- });
7145
- }
7146
- };
7147
- function createDefaultTokenizerPort(config = {}) {
7148
- return new DefaultTokenizerPort(config);
7149
- }
7150
-
7151
7710
  // src/runtime-kernel/child-runs/index.ts
7152
7711
  var child_runs_exports = {};
7153
7712
  __export(child_runs_exports, {
@@ -8757,6 +9316,7 @@ __export(telemetry_exports, {
8757
9316
  var TELEMETRY_EVENT_KINDS = [
8758
9317
  "llm_call",
8759
9318
  "tool_call",
9319
+ "context_build",
8760
9320
  "graph_node",
8761
9321
  "run_lifecycle"
8762
9322
  ];
@@ -9517,6 +10077,27 @@ var summarizeToolOutput = (toolName, output, toolSummaryProvider, toolArgs, conf
9517
10077
  function isRecord25(value) {
9518
10078
  return !!value && typeof value === "object" && !Array.isArray(value);
9519
10079
  }
10080
+ function readObservationTruncationMeta(value) {
10081
+ if (!isRecord25(value)) {
10082
+ return void 0;
10083
+ }
10084
+ const originalChars = value["originalChars"];
10085
+ const previewChars = value["previewChars"];
10086
+ if (typeof originalChars !== "number" || !Number.isInteger(originalChars) || originalChars < 0) {
10087
+ return void 0;
10088
+ }
10089
+ if (typeof previewChars !== "number" || !Number.isInteger(previewChars) || previewChars < 0) {
10090
+ return void 0;
10091
+ }
10092
+ const originalLines = value["originalLines"];
10093
+ const previewLines = value["previewLines"];
10094
+ return {
10095
+ originalChars,
10096
+ previewChars,
10097
+ ...typeof originalLines === "number" && Number.isInteger(originalLines) && originalLines >= 0 ? { originalLines } : {},
10098
+ ...typeof previewLines === "number" && Number.isInteger(previewLines) && previewLines >= 0 ? { previewLines } : {}
10099
+ };
10100
+ }
9520
10101
  function isHistorySummaryEvent2(event) {
9521
10102
  return "type" in event && event.type === "history_summary";
9522
10103
  }
@@ -9629,6 +10210,7 @@ function convertEventToAiMessage(event) {
9629
10210
  }
9630
10211
  })();
9631
10212
  const outputContent = observationFromPayload ?? rawOutput;
10213
+ const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
9632
10214
  return {
9633
10215
  id: event.id,
9634
10216
  role: "tool",
@@ -9639,6 +10221,7 @@ function convertEventToAiMessage(event) {
9639
10221
  tool_call_id: event.tool_call_id,
9640
10222
  tool_name: event.tool_name,
9641
10223
  raw_output: rawOutput,
10224
+ ...observationTruncation ? { observationTruncation } : {},
9642
10225
  ...observationFromPayload ? { observation: observationFromPayload } : {}
9643
10226
  }
9644
10227
  };
@@ -10437,14 +11020,14 @@ function createRunSupervisorHarness(options = {}) {
10437
11020
  function failure2(id, title, message, details) {
10438
11021
  return details === void 0 ? { id, title, message } : { id, title, message, details };
10439
11022
  }
10440
- function readRecord(value) {
11023
+ function readRecord2(value) {
10441
11024
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
10442
11025
  }
10443
11026
  function readString4(value) {
10444
11027
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
10445
11028
  }
10446
11029
  function readEventRunId(event) {
10447
- const metadata = readRecord(event.metadata);
11030
+ const metadata = readRecord2(event.metadata);
10448
11031
  if (!metadata) {
10449
11032
  return void 0;
10450
11033
  }
@@ -10452,7 +11035,7 @@ function readEventRunId(event) {
10452
11035
  if (direct) {
10453
11036
  return direct;
10454
11037
  }
10455
- const runContext = readRecord(metadata.run_context);
11038
+ const runContext = readRecord2(metadata.run_context);
10456
11039
  return runContext ? readString4(runContext.runId) ?? readString4(runContext.run_id) : void 0;
10457
11040
  }
10458
11041
  function runIds(records) {