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