@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/index.cjs CHANGED
@@ -47,7 +47,11 @@ __export(runtime_kernel_exports, {
47
47
  ToolNode: () => ToolNode,
48
48
  UserNode: () => UserNode,
49
49
  WaitUserNode: () => WaitUserNode,
50
+ addLedgerAggregate: () => addLedgerAggregate,
51
+ addUsageTotals: () => addUsageTotals,
50
52
  agentHasToolTrigger: () => agentHasToolTrigger,
53
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
54
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
51
55
  appendStreamingProviderReasoningDetails: () => appendStreamingProviderReasoningDetails,
52
56
  applySystemReminders: () => applySystemReminders,
53
57
  audit: () => audit_exports,
@@ -56,6 +60,7 @@ __export(runtime_kernel_exports, {
56
60
  childRuns: () => child_runs_exports,
57
61
  compactProviderReasoningDetails: () => compactProviderReasoningDetails,
58
62
  compactReasoningDetailsInValue: () => compactReasoningDetailsInValue,
63
+ computeCost: () => computeCost,
59
64
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
60
65
  consoleAudit: () => consoleAudit,
61
66
  contextBudgetWarningTemplate: () => contextBudgetWarningTemplate,
@@ -64,13 +69,16 @@ __export(runtime_kernel_exports, {
64
69
  createCompositeAudit: () => createCompositeAudit,
65
70
  createConsoleAudit: () => createConsoleAudit,
66
71
  createContextCheckpointTool: () => createContextCheckpointTool,
72
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
67
73
  createDefaultGraphExecutor: () => createDefaultGraphExecutor,
68
74
  createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
69
75
  createDefaultTokenizerPort: () => createDefaultTokenizerPort,
70
76
  createEventStoreAudit: () => createEventStoreAudit,
71
77
  createFileAudit: () => createFileAudit,
72
78
  createGraphLoopHarness: () => createGraphLoopHarness,
79
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
73
80
  createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
81
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
74
82
  createSystemReminderRules: () => createSystemReminderRules,
75
83
  defaultPolicyEngine: () => defaultPolicyEngine,
76
84
  defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
@@ -107,6 +115,7 @@ __export(runtime_kernel_exports, {
107
115
  systemReminder: () => system_reminder_exports,
108
116
  telemetry: () => telemetry_exports,
109
117
  toDisplayStep: () => toDisplayStep,
118
+ tokenAccounting: () => token_accounting_exports,
110
119
  toolCallStreakTemplate: () => toolCallStreakTemplate,
111
120
  toolCallStreakTrigger: () => toolCallStreakTrigger,
112
121
  tools: () => tools_exports
@@ -248,14 +257,23 @@ __export(contracts_exports, {
248
257
  AuditScope: () => AuditScope,
249
258
  BaseEvent: () => BaseEvent,
250
259
  BaseSSEEvent: () => BaseSSEEvent,
260
+ CanonicalLlmUsage: () => CanonicalLlmUsage,
261
+ ContextBuildTokenEstimate: () => ContextBuildTokenEstimate,
262
+ ContextComponentTokenLedgerEntry: () => ContextComponentTokenLedgerEntry,
263
+ ContextTokenComponent: () => ContextTokenComponent,
264
+ ContextTokenComponentKind: () => ContextTokenComponentKind,
265
+ CostBreakdown: () => CostBreakdown,
251
266
  DEFAULT_MAX_STEPS: () => DEFAULT_MAX_STEPS,
252
267
  EventEnvelope: () => EventEnvelope,
253
268
  ExecutionTraceContext: () => ExecutionTraceContext,
254
269
  HistorySummaryMeta: () => HistorySummaryMeta,
255
270
  ImageInfoMeta: () => ImageInfoMeta,
271
+ LlmUsageTokenLedgerEntry: () => LlmUsageTokenLedgerEntry,
272
+ ObservationTruncationMeta: () => ObservationTruncationMeta,
256
273
  PersistentMetadata: () => PersistentMetadata,
257
274
  ProviderReasoningDetails: () => ProviderReasoningDetails,
258
275
  ProviderReasoningDetailsPayload: () => ProviderReasoningDetailsPayload,
276
+ RunTokenUsageAggregate: () => RunTokenUsageAggregate,
259
277
  RuntimeEvent: () => RuntimeEvent,
260
278
  SSEErrorEvent: () => SSEErrorEvent,
261
279
  SSEEvent: () => SSEEvent,
@@ -278,6 +296,18 @@ __export(contracts_exports, {
278
296
  Status: () => Status,
279
297
  SystemMessage: () => SystemMessage,
280
298
  TaskTrackingMeta: () => TaskTrackingMeta,
299
+ TokenCostComponent: () => TokenCostComponent,
300
+ TokenCountConfidence: () => TokenCountConfidence,
301
+ TokenCountSource: () => TokenCountSource,
302
+ TokenLedgerAggregate: () => TokenLedgerAggregate,
303
+ TokenLedgerEntry: () => TokenLedgerEntry,
304
+ TokenLedgerEntryKind: () => TokenLedgerEntryKind,
305
+ TokenPricing: () => TokenPricing,
306
+ TokenRoute: () => TokenRoute,
307
+ TokenRouteCapabilities: () => TokenRouteCapabilities,
308
+ TokenUsageCalibrationSample: () => TokenUsageCalibrationSample,
309
+ TokenUsageCalibrationTrace: () => TokenUsageCalibrationTrace,
310
+ TokenUsageTotals: () => TokenUsageTotals,
281
311
  ToolBindingSpec: () => ToolBindingSpec,
282
312
  ToolCallDecisionPayload: () => ToolCallDecisionPayload,
283
313
  ToolCallExtraContent: () => ToolCallExtraContent,
@@ -363,6 +393,12 @@ var ToolOutputMeta = zod.z.object({
363
393
  args: zod.z.record(zod.z.unknown()).optional(),
364
394
  tool_call_id: zod.z.string()
365
395
  });
396
+ var ObservationTruncationMeta = zod.z.object({
397
+ originalChars: zod.z.number().int().nonnegative(),
398
+ previewChars: zod.z.number().int().nonnegative(),
399
+ originalLines: zod.z.number().int().nonnegative().optional(),
400
+ previewLines: zod.z.number().int().nonnegative().optional()
401
+ });
366
402
  var ImageInfoMeta = zod.z.object({
367
403
  url: zod.z.string().optional(),
368
404
  width: zod.z.number().int().positive().optional(),
@@ -394,6 +430,7 @@ var PersistentMetadata = zod.z.object({
394
430
  tool_name: zod.z.string().optional(),
395
431
  args: zod.z.record(zod.z.unknown()).optional(),
396
432
  tool_call_id: zod.z.string().optional(),
433
+ observationTruncation: ObservationTruncationMeta.optional(),
397
434
  raw_output: zod.z.string().optional(),
398
435
  image_info: ImageInfoMeta.optional(),
399
436
  taskType: zod.z.string().optional(),
@@ -618,7 +655,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
618
655
  var AgentSpecTokenEstimationPolicy = zod.z.object({
619
656
  encoding: zod.z.string().min(1).optional(),
620
657
  avgCharsPerToken: zod.z.number().positive().optional(),
621
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
658
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
659
+ calibration: zod.z.object({
660
+ enabled: zod.z.boolean().optional(),
661
+ minSamples: zod.z.number().int().positive().optional(),
662
+ minCoefficient: zod.z.number().positive().optional(),
663
+ maxCoefficient: zod.z.number().positive().optional()
664
+ }).optional(),
665
+ remoteCount: zod.z.object({
666
+ enabled: zod.z.boolean().optional(),
667
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
668
+ }).optional()
622
669
  });
623
670
  var SYSTEM_REMINDER_BUILTIN_TRIGGER_KINDS = [
624
671
  "phase-equals",
@@ -1540,6 +1587,189 @@ var createSSEHistorySummaryEvent = (id, conversationId, turnId, summaryId, conte
1540
1587
  summary_seq: summarySeq,
1541
1588
  ...options
1542
1589
  });
1590
+ var TokenCountSource = zod.z.enum([
1591
+ "local-estimate",
1592
+ "provider-preflight-count",
1593
+ "provider-response-usage",
1594
+ "host-supplied",
1595
+ "test-fixture"
1596
+ ]);
1597
+ var TokenCountConfidence = zod.z.enum([
1598
+ "estimate",
1599
+ "provider-estimate",
1600
+ "actual"
1601
+ ]);
1602
+ var TokenRouteCapabilities = zod.z.object({
1603
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1604
+ supportsResponseUsage: zod.z.boolean().optional(),
1605
+ supportsImageInput: zod.z.boolean().optional(),
1606
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1607
+ supportsReasoningTokens: zod.z.boolean().optional()
1608
+ });
1609
+ var TokenRoute = zod.z.object({
1610
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1611
+ 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"),
1612
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1613
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1614
+ capabilities: TokenRouteCapabilities.optional()
1615
+ });
1616
+ var tokenCount = zod.z.number().int().nonnegative();
1617
+ var CanonicalLlmUsage = zod.z.object({
1618
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1619
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1620
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1621
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1622
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1623
+ 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"),
1624
+ source: TokenCountSource,
1625
+ confidence: TokenCountConfidence,
1626
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1627
+ });
1628
+ var tokenCount2 = zod.z.number().int().nonnegative();
1629
+ var tokenPrice = zod.z.number().finite().nonnegative();
1630
+ var TokenLedgerEntryKind = zod.z.enum([
1631
+ "llm-usage",
1632
+ "context-component"
1633
+ ]);
1634
+ var ContextTokenComponentKind = zod.z.enum([
1635
+ "system",
1636
+ "user",
1637
+ "assistant",
1638
+ "tool",
1639
+ "context-injection",
1640
+ "history-summary",
1641
+ "working-memory",
1642
+ "fence",
1643
+ "system-reminder",
1644
+ "other"
1645
+ ]);
1646
+ var TokenUsageTotals = zod.z.object({
1647
+ inputTokens: tokenCount2,
1648
+ outputTokens: tokenCount2,
1649
+ reasoningTokens: tokenCount2.optional(),
1650
+ cacheReadTokens: tokenCount2.optional(),
1651
+ cacheWriteTokens: tokenCount2.optional(),
1652
+ totalTokens: tokenCount2.optional(),
1653
+ usageCount: zod.z.number().int().nonnegative()
1654
+ });
1655
+ var ContextTokenComponent = zod.z.object({
1656
+ componentId: zod.z.string().min(1),
1657
+ kind: ContextTokenComponentKind,
1658
+ tokens: tokenCount2,
1659
+ source: TokenCountSource,
1660
+ confidence: TokenCountConfidence,
1661
+ label: zod.z.string().optional(),
1662
+ messageId: zod.z.string().optional(),
1663
+ role: zod.z.string().optional(),
1664
+ action: zod.z.string().optional(),
1665
+ kept: zod.z.boolean().optional(),
1666
+ truncatedAtExecution: zod.z.boolean().optional(),
1667
+ originalTokensEstimate: tokenCount2.optional(),
1668
+ droppedTokensEstimate: tokenCount2.optional()
1669
+ });
1670
+ var TokenLedgerEntryBase = zod.z.object({
1671
+ id: zod.z.string().min(1),
1672
+ runId: zod.z.string().optional(),
1673
+ parentRunId: zod.z.string().optional(),
1674
+ conversationId: zod.z.string().optional(),
1675
+ turnId: zod.z.string().optional(),
1676
+ stepId: zod.z.string().optional(),
1677
+ route: TokenRoute.optional(),
1678
+ createdAt: zod.z.number().int().nonnegative().optional()
1679
+ });
1680
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1681
+ kind: zod.z.literal("llm-usage"),
1682
+ modelId: zod.z.string().optional(),
1683
+ usage: CanonicalLlmUsage
1684
+ });
1685
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1686
+ kind: zod.z.literal("context-component"),
1687
+ components: zod.z.array(ContextTokenComponent),
1688
+ totalTokens: tokenCount2
1689
+ });
1690
+ var TokenLedgerEntry = zod.z.discriminatedUnion("kind", [
1691
+ LlmUsageTokenLedgerEntry,
1692
+ ContextComponentTokenLedgerEntry
1693
+ ]);
1694
+ var TokenLedgerAggregate = zod.z.object({
1695
+ llmUsage: TokenUsageTotals.optional(),
1696
+ contextTokens: tokenCount2,
1697
+ entryCount: zod.z.number().int().nonnegative(),
1698
+ llmCallCount: zod.z.number().int().nonnegative(),
1699
+ contextComponentCount: zod.z.number().int().nonnegative()
1700
+ });
1701
+ var RunTokenUsageAggregate = zod.z.object({
1702
+ /**
1703
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1704
+ */
1705
+ own: TokenLedgerAggregate,
1706
+ children: TokenLedgerAggregate.optional()
1707
+ });
1708
+ var TokenCostComponent = zod.z.enum([
1709
+ "input",
1710
+ "output",
1711
+ "reasoning",
1712
+ "cacheRead",
1713
+ "cacheWrite"
1714
+ ]);
1715
+ var TokenPricing = zod.z.object({
1716
+ currency: zod.z.string().min(1),
1717
+ unit: zod.z.literal("per_1m_tokens"),
1718
+ input: tokenPrice.optional(),
1719
+ output: tokenPrice.optional(),
1720
+ reasoning: tokenPrice.optional(),
1721
+ cacheRead: tokenPrice.optional(),
1722
+ cacheWrite: tokenPrice.optional()
1723
+ });
1724
+ var CostBreakdown = zod.z.object({
1725
+ status: zod.z.enum(["computed", "unknown"]),
1726
+ currency: zod.z.string().optional(),
1727
+ inputCost: tokenPrice.optional(),
1728
+ outputCost: tokenPrice.optional(),
1729
+ reasoningCost: tokenPrice.optional(),
1730
+ cacheReadCost: tokenPrice.optional(),
1731
+ cacheWriteCost: tokenPrice.optional(),
1732
+ totalCost: tokenPrice.optional(),
1733
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1734
+ });
1735
+ var tokenCount3 = zod.z.number().int().nonnegative();
1736
+ var actualCalibrationSource = zod.z.enum([
1737
+ "provider-response-usage",
1738
+ "host-supplied",
1739
+ "test-fixture"
1740
+ ]);
1741
+ var TokenUsageCalibrationSample = zod.z.object({
1742
+ route: TokenRoute,
1743
+ localEstimateTokens: tokenCount3,
1744
+ actualInputTokens: tokenCount3,
1745
+ source: actualCalibrationSource,
1746
+ confidence: zod.z.literal("actual"),
1747
+ observedAt: zod.z.number().int().nonnegative().optional(),
1748
+ runId: zod.z.string().optional(),
1749
+ ledgerEntryId: zod.z.string().optional()
1750
+ });
1751
+ var TokenUsageCalibrationTrace = zod.z.object({
1752
+ enabled: zod.z.boolean(),
1753
+ applied: zod.z.boolean(),
1754
+ route: TokenRoute.optional(),
1755
+ sampleCount: zod.z.number().int().nonnegative(),
1756
+ coefficient: zod.z.number().positive().optional(),
1757
+ minSamples: zod.z.number().int().positive().optional(),
1758
+ minCoefficient: zod.z.number().positive().optional(),
1759
+ maxCoefficient: zod.z.number().positive().optional(),
1760
+ localEstimateTokens: tokenCount3.optional(),
1761
+ calibratedEstimateTokens: tokenCount3.optional(),
1762
+ deltaTokens: zod.z.number().int().optional(),
1763
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1764
+ });
1765
+ var ContextBuildTokenEstimate = zod.z.object({
1766
+ route: TokenRoute.optional(),
1767
+ localEstimateTokens: tokenCount3,
1768
+ calibratedEstimateTokens: tokenCount3,
1769
+ finalTokens: tokenCount3,
1770
+ source: zod.z.literal("local-estimate"),
1771
+ confidence: zod.z.literal("estimate")
1772
+ });
1543
1773
 
1544
1774
  // src/runtime-kernel/graph-engine/engine.ts
1545
1775
  var logger = new Logger("GraphExecutor");
@@ -1943,6 +2173,190 @@ var noopAudit = {
1943
2173
  flush() {
1944
2174
  }
1945
2175
  };
2176
+ var TokenCalculator = class {
2177
+ static BYTES_PER_TOKEN_LATIN = 4;
2178
+ static BYTES_PER_TOKEN_CJK = 3;
2179
+ static OVERHEAD_PER_MESSAGE = 5;
2180
+ static OVERHEAD_PER_TOOL_CALL = 10;
2181
+ static encoderCache = /* @__PURE__ */ new Map();
2182
+ static DEFAULT_ENCODING = "cl100k_base";
2183
+ static SUPPORTED_ENCODINGS = [
2184
+ "gpt2",
2185
+ "r50k_base",
2186
+ "p50k_base",
2187
+ "p50k_edit",
2188
+ "cl100k_base",
2189
+ "o200k_base"
2190
+ ];
2191
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
2192
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
2193
+ if (this.isSupportedEncodingName(normalized)) {
2194
+ return normalized;
2195
+ }
2196
+ if (normalized.includes("deepseek")) {
2197
+ return "cl100k_base";
2198
+ }
2199
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
2200
+ return "o200k_base";
2201
+ }
2202
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
2203
+ return "cl100k_base";
2204
+ }
2205
+ return this.DEFAULT_ENCODING;
2206
+ }
2207
+ static isSupportedEncodingName(value) {
2208
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
2209
+ }
2210
+ static getEncoder(modelIdentifierOrEncoding) {
2211
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
2212
+ const cached = this.encoderCache.get(encodingName);
2213
+ if (cached) {
2214
+ return cached;
2215
+ }
2216
+ const encoder = tiktoken.get_encoding(encodingName);
2217
+ this.encoderCache.set(encodingName, encoder);
2218
+ return encoder;
2219
+ }
2220
+ static estimateTokensRough(text, _modelIdentifier) {
2221
+ if (!text) return 0;
2222
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
2223
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
2224
+ const byteLength = new TextEncoder().encode(text).length;
2225
+ return Math.ceil(byteLength / ratio);
2226
+ }
2227
+ static estimateTokens(text, options = {}) {
2228
+ if (!text) return 0;
2229
+ if (options.encoding) {
2230
+ try {
2231
+ return this.estimateTokensPrecise(text, options.encoding);
2232
+ } catch {
2233
+ }
2234
+ }
2235
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
2236
+ return Math.ceil(text.length / avgCharsPerToken);
2237
+ }
2238
+ static estimateTokensPrecise(text, modelIdentifier) {
2239
+ if (!text) return 0;
2240
+ const encoder = this.getEncoder(modelIdentifier);
2241
+ return encoder.encode(text).length;
2242
+ }
2243
+ static estimateMessageTokens(message, options = {}) {
2244
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
2245
+ if (message.content) {
2246
+ totalTokens += this.estimateTokens(String(message.content), options);
2247
+ }
2248
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
2249
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
2250
+ for (const toolCall of toolCalls) {
2251
+ totalTokens += toolCallOverhead;
2252
+ const fn = toolCall["function"];
2253
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
2254
+ const fnRecord = fn;
2255
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
2256
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
2257
+ }
2258
+ }
2259
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
2260
+ if (toolCallId) {
2261
+ totalTokens += this.estimateTokens(toolCallId, options);
2262
+ }
2263
+ return totalTokens;
2264
+ }
2265
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
2266
+ return this.estimateMessageTokens(message, {
2267
+ encoding: modelIdentifier,
2268
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
2269
+ });
2270
+ }
2271
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
2272
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2273
+ }
2274
+ static extractToolCallsForTokenEstimate(message) {
2275
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
2276
+ if (Array.isArray(direct)) return direct;
2277
+ const metadata = "metadata" in message ? message.metadata : void 0;
2278
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
2279
+ const metadataRecord = metadata;
2280
+ const metadataToolCalls = metadataRecord["tool_calls"];
2281
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2282
+ }
2283
+ static extractToolCallIdForTokenEstimate(message) {
2284
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
2285
+ return message.tool_call_id;
2286
+ }
2287
+ const metadata = "metadata" in message ? message.metadata : void 0;
2288
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
2289
+ const metadataRecord = metadata;
2290
+ const toolCallId = metadataRecord["tool_call_id"];
2291
+ return typeof toolCallId === "string" ? toolCallId : void 0;
2292
+ }
2293
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
2294
+ if (!text || maxTokens <= 0) return "";
2295
+ const encoder = this.getEncoder(modelIdentifier);
2296
+ const tokens = encoder.encode(text);
2297
+ if (tokens.length <= maxTokens) {
2298
+ return text;
2299
+ }
2300
+ let truncatedTokens;
2301
+ const ellipsis = "...";
2302
+ switch (strategy) {
2303
+ case "start":
2304
+ truncatedTokens = tokens.slice(0, maxTokens);
2305
+ return encoder.decode(truncatedTokens) + ellipsis;
2306
+ case "end":
2307
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
2308
+ return ellipsis + encoder.decode(truncatedTokens);
2309
+ case "middle": {
2310
+ const half = Math.floor(maxTokens / 2);
2311
+ const head = tokens.slice(0, half);
2312
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
2313
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
2314
+ }
2315
+ default:
2316
+ truncatedTokens = tokens.slice(0, maxTokens);
2317
+ return encoder.decode(truncatedTokens) + ellipsis;
2318
+ }
2319
+ }
2320
+ static cleanup() {
2321
+ for (const encoder of this.encoderCache.values()) {
2322
+ encoder.free();
2323
+ }
2324
+ this.encoderCache.clear();
2325
+ }
2326
+ };
2327
+ function normalizePositiveNumber(value, fallback) {
2328
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2329
+ }
2330
+ function normalizeNonNegativeInteger(value, fallback) {
2331
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2332
+ return fallback;
2333
+ }
2334
+ return Math.max(0, Math.floor(value));
2335
+ }
2336
+
2337
+ // src/shared/defaultTokenizerPort.ts
2338
+ var DefaultTokenizerPort = class {
2339
+ constructor(config = {}) {
2340
+ this.config = config;
2341
+ }
2342
+ config;
2343
+ estimateText(text, _modelId) {
2344
+ return TokenCalculator.estimateTokens(text, {
2345
+ encoding: this.config.encoding,
2346
+ avgCharsPerToken: this.config.avgCharsPerToken
2347
+ });
2348
+ }
2349
+ estimateMessage(message, _modelId) {
2350
+ return TokenCalculator.estimateMessageTokens(message, {
2351
+ encoding: this.config.encoding,
2352
+ avgCharsPerToken: this.config.avgCharsPerToken,
2353
+ toolCallOverhead: this.config.toolCallOverhead
2354
+ });
2355
+ }
2356
+ };
2357
+ function createDefaultTokenizerPort(config = {}) {
2358
+ return new DefaultTokenizerPort(config);
2359
+ }
1946
2360
 
1947
2361
  // src/shared/ids.ts
1948
2362
  function isoRandomUUID() {
@@ -2091,282 +2505,162 @@ function normalizeToolCalls(rawCalls) {
2091
2505
  ...toolCall,
2092
2506
  function: { ...toolCall.function, arguments: pieces[0] }
2093
2507
  });
2094
- for (let index = 1; index < pieces.length; index += 1) {
2095
- expanded.push({
2096
- ...toolCall,
2097
- id: generateMessageId(),
2098
- function: { ...toolCall.function, arguments: pieces[index] }
2099
- });
2100
- }
2101
- continue;
2102
- }
2103
- expanded.push({
2104
- ...toolCall
2105
- });
2106
- }
2107
- return expanded;
2108
- }
2109
- function parsePrimaryToolArgs(toolCall) {
2110
- if (!toolCall?.function?.arguments) {
2111
- return {};
2112
- }
2113
- try {
2114
- const parsed = JSON.parse(toolCall.function.arguments);
2115
- return typeof parsed === "object" && parsed !== null ? parsed : {};
2116
- } catch {
2117
- return {};
2118
- }
2119
- }
2120
- function resolveUsage(response) {
2121
- if (!response || typeof response === "string") {
2122
- return void 0;
2123
- }
2124
- return response.usage;
2125
- }
2126
- function resolveToolCalls(response) {
2127
- if (!response || typeof response === "string") {
2128
- return void 0;
2129
- }
2130
- return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
2131
- }
2132
- function resolveReasoningDetails(response) {
2133
- if (!response || typeof response === "string") {
2134
- return void 0;
2135
- }
2136
- return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2137
- }
2138
- function resolveToolNamesForAudit(ctx) {
2139
- if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2140
- return [];
2141
- }
2142
- return ctx.toolSchemas.map((tool) => tool.function.name);
2143
- }
2144
-
2145
- // src/shared/llmAuditRecorder.ts
2146
- var recorder = null;
2147
- function setLlmAuditRecorder(next) {
2148
- recorder = next;
2149
- }
2150
- function recordBeforeContextManager(params) {
2151
- recorder?.recordBeforeContextManager?.(params);
2152
- }
2153
- function recordAfterContextManager(params) {
2154
- recorder?.recordAfterContextManager?.(params);
2155
- }
2156
- function recordAfterContextManagerOnSystemReminderHit(params) {
2157
- recorder?.recordAfterContextManagerOnSystemReminderHit?.(params);
2158
- }
2159
- function recordToolProtocolError(params) {
2160
- recorder?.recordToolProtocolError?.(params);
2161
- }
2162
- function recordRunTranscript(params) {
2163
- recorder?.recordRunTranscript?.(params);
2164
- }
2165
-
2166
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2167
- var contextAuditMiddleware = async (ctx, stage, next) => {
2168
- if (stage.id === "build_context") {
2169
- recordBeforeContextManager({
2170
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
2171
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2172
- });
2173
- }
2174
- await next();
2175
- if (stage.id !== "apply_system_reminder") {
2176
- return;
2177
- }
2178
- const toolNamesForAudit = resolveToolNamesForAudit(ctx);
2179
- recordAfterContextManager({
2180
- mode: ctx.mode,
2181
- llmMessages: ctx.llmMessages,
2182
- toolNames: toolNamesForAudit,
2183
- contextTrace: ctx.contextTrace
2184
- });
2185
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2186
- recordAfterContextManagerOnSystemReminderHit({
2187
- mode: ctx.mode,
2188
- llmMessages: ctx.llmMessages,
2189
- toolNames: toolNamesForAudit,
2190
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2191
- contextTrace: ctx.contextTrace
2192
- });
2193
- }
2194
- };
2195
- var TokenCalculator = class {
2196
- static BYTES_PER_TOKEN_LATIN = 4;
2197
- static BYTES_PER_TOKEN_CJK = 3;
2198
- static OVERHEAD_PER_MESSAGE = 5;
2199
- static OVERHEAD_PER_TOOL_CALL = 10;
2200
- static encoderCache = /* @__PURE__ */ new Map();
2201
- static DEFAULT_ENCODING = "cl100k_base";
2202
- static SUPPORTED_ENCODINGS = [
2203
- "gpt2",
2204
- "r50k_base",
2205
- "p50k_base",
2206
- "p50k_edit",
2207
- "cl100k_base",
2208
- "o200k_base"
2209
- ];
2210
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
2211
- const normalized = (modelIdentifier || "").trim().toLowerCase();
2212
- if (this.isSupportedEncodingName(normalized)) {
2213
- return normalized;
2214
- }
2215
- if (normalized.includes("deepseek")) {
2216
- return "cl100k_base";
2217
- }
2218
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
2219
- return "o200k_base";
2220
- }
2221
- if (normalized.includes("gemini") || normalized.includes("claude")) {
2222
- return "cl100k_base";
2223
- }
2224
- return this.DEFAULT_ENCODING;
2225
- }
2226
- static isSupportedEncodingName(value) {
2227
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
2228
- }
2229
- static getEncoder(modelIdentifierOrEncoding) {
2230
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
2231
- const cached = this.encoderCache.get(encodingName);
2232
- if (cached) {
2233
- return cached;
2234
- }
2235
- const encoder = tiktoken.get_encoding(encodingName);
2236
- this.encoderCache.set(encodingName, encoder);
2237
- return encoder;
2238
- }
2239
- static estimateTokensRough(text, _modelIdentifier) {
2240
- if (!text) return 0;
2241
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
2242
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
2243
- const byteLength = new TextEncoder().encode(text).length;
2244
- return Math.ceil(byteLength / ratio);
2245
- }
2246
- static estimateTokens(text, options = {}) {
2247
- if (!text) return 0;
2248
- if (options.encoding) {
2249
- try {
2250
- return this.estimateTokensPrecise(text, options.encoding);
2251
- } catch {
2252
- }
2253
- }
2254
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
2255
- return Math.ceil(text.length / avgCharsPerToken);
2256
- }
2257
- static estimateTokensPrecise(text, modelIdentifier) {
2258
- if (!text) return 0;
2259
- const encoder = this.getEncoder(modelIdentifier);
2260
- return encoder.encode(text).length;
2261
- }
2262
- static estimateMessageTokens(message, options = {}) {
2263
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
2264
- if (message.content) {
2265
- totalTokens += this.estimateTokens(String(message.content), options);
2266
- }
2267
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
2268
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
2269
- for (const toolCall of toolCalls) {
2270
- totalTokens += toolCallOverhead;
2271
- const fn = toolCall["function"];
2272
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
2273
- const fnRecord = fn;
2274
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
2275
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
2276
- }
2277
- }
2278
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
2279
- if (toolCallId) {
2280
- totalTokens += this.estimateTokens(toolCallId, options);
2281
- }
2282
- return totalTokens;
2283
- }
2284
- static estimateMessageTokensPrecise(message, modelIdentifier) {
2285
- return this.estimateMessageTokens(message, {
2286
- encoding: modelIdentifier,
2287
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
2288
- });
2289
- }
2290
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
2291
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2292
- }
2293
- static extractToolCallsForTokenEstimate(message) {
2294
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
2295
- if (Array.isArray(direct)) return direct;
2296
- const metadata = "metadata" in message ? message.metadata : void 0;
2297
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
2298
- const metadataRecord = metadata;
2299
- const metadataToolCalls = metadataRecord["tool_calls"];
2300
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2301
- }
2302
- static extractToolCallIdForTokenEstimate(message) {
2303
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
2304
- return message.tool_call_id;
2305
- }
2306
- const metadata = "metadata" in message ? message.metadata : void 0;
2307
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
2308
- const metadataRecord = metadata;
2309
- const toolCallId = metadataRecord["tool_call_id"];
2310
- return typeof toolCallId === "string" ? toolCallId : void 0;
2311
- }
2312
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
2313
- if (!text || maxTokens <= 0) return "";
2314
- const encoder = this.getEncoder(modelIdentifier);
2315
- const tokens = encoder.encode(text);
2316
- if (tokens.length <= maxTokens) {
2317
- return text;
2318
- }
2319
- let truncatedTokens;
2320
- const ellipsis = "...";
2321
- switch (strategy) {
2322
- case "start":
2323
- truncatedTokens = tokens.slice(0, maxTokens);
2324
- return encoder.decode(truncatedTokens) + ellipsis;
2325
- case "end":
2326
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
2327
- return ellipsis + encoder.decode(truncatedTokens);
2328
- case "middle": {
2329
- const half = Math.floor(maxTokens / 2);
2330
- const head = tokens.slice(0, half);
2331
- const tail = tokens.slice(tokens.length - (maxTokens - half));
2332
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
2508
+ for (let index = 1; index < pieces.length; index += 1) {
2509
+ expanded.push({
2510
+ ...toolCall,
2511
+ id: generateMessageId(),
2512
+ function: { ...toolCall.function, arguments: pieces[index] }
2513
+ });
2333
2514
  }
2334
- default:
2335
- truncatedTokens = tokens.slice(0, maxTokens);
2336
- return encoder.decode(truncatedTokens) + ellipsis;
2515
+ continue;
2337
2516
  }
2517
+ expanded.push({
2518
+ ...toolCall
2519
+ });
2338
2520
  }
2339
- static cleanup() {
2340
- for (const encoder of this.encoderCache.values()) {
2341
- encoder.free();
2342
- }
2343
- this.encoderCache.clear();
2521
+ return expanded;
2522
+ }
2523
+ function parsePrimaryToolArgs(toolCall) {
2524
+ if (!toolCall?.function?.arguments) {
2525
+ return {};
2526
+ }
2527
+ try {
2528
+ const parsed = JSON.parse(toolCall.function.arguments);
2529
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
2530
+ } catch {
2531
+ return {};
2344
2532
  }
2345
- };
2346
- function normalizePositiveNumber(value, fallback) {
2347
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2348
2533
  }
2349
- function normalizeNonNegativeInteger(value, fallback) {
2350
- if (typeof value !== "number" || !Number.isFinite(value)) {
2351
- return fallback;
2534
+ function resolveUsage(response) {
2535
+ if (!response || typeof response === "string") {
2536
+ return void 0;
2352
2537
  }
2353
- return Math.max(0, Math.floor(value));
2538
+ return response.usage;
2539
+ }
2540
+ function resolveCanonicalUsage(response) {
2541
+ if (!response || typeof response === "string") {
2542
+ return void 0;
2543
+ }
2544
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2545
+ return parsed.success ? parsed.data : void 0;
2546
+ }
2547
+ function resolveToolCalls(response) {
2548
+ if (!response || typeof response === "string") {
2549
+ return void 0;
2550
+ }
2551
+ return Array.isArray(response.tool_calls) ? response.tool_calls : void 0;
2552
+ }
2553
+ function resolveReasoningDetails(response) {
2554
+ if (!response || typeof response === "string") {
2555
+ return void 0;
2556
+ }
2557
+ return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2558
+ }
2559
+ function resolveToolNamesForAudit(ctx) {
2560
+ if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2561
+ return [];
2562
+ }
2563
+ return ctx.toolSchemas.map((tool) => tool.function.name);
2564
+ }
2565
+
2566
+ // src/shared/llmAuditRecorder.ts
2567
+ var recorder = null;
2568
+ function setLlmAuditRecorder(next) {
2569
+ recorder = next;
2570
+ }
2571
+ function recordBeforeContextManager(params) {
2572
+ recorder?.recordBeforeContextManager?.(params);
2573
+ }
2574
+ function recordAfterContextManager(params) {
2575
+ recorder?.recordAfterContextManager?.(params);
2576
+ }
2577
+ function recordAfterContextManagerOnSystemReminderHit(params) {
2578
+ recorder?.recordAfterContextManagerOnSystemReminderHit?.(params);
2579
+ }
2580
+ function recordToolProtocolError(params) {
2581
+ recorder?.recordToolProtocolError?.(params);
2354
2582
  }
2583
+ function recordRunTranscript(params) {
2584
+ recorder?.recordRunTranscript?.(params);
2585
+ }
2586
+
2587
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2588
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2589
+ if (stage.id === "build_context") {
2590
+ recordBeforeContextManager({
2591
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2592
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2593
+ });
2594
+ }
2595
+ await next();
2596
+ if (stage.id !== "apply_system_reminder") {
2597
+ return;
2598
+ }
2599
+ const toolNamesForAudit = resolveToolNamesForAudit(ctx);
2600
+ recordAfterContextManager({
2601
+ mode: ctx.mode,
2602
+ llmMessages: ctx.llmMessages,
2603
+ toolNames: toolNamesForAudit,
2604
+ contextTrace: ctx.contextTrace
2605
+ });
2606
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2607
+ recordAfterContextManagerOnSystemReminderHit({
2608
+ mode: ctx.mode,
2609
+ llmMessages: ctx.llmMessages,
2610
+ toolNames: toolNamesForAudit,
2611
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2612
+ contextTrace: ctx.contextTrace
2613
+ });
2614
+ }
2615
+ };
2355
2616
  var als = new async_hooks.AsyncLocalStorage();
2356
- function normalizeLlmUsage(usage) {
2617
+ function readTokenCount(record, key) {
2618
+ const value = record[key];
2619
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2620
+ }
2621
+ function readRecord(record, key) {
2622
+ const value = record[key];
2623
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2624
+ return Object.fromEntries(Object.entries(value));
2625
+ }
2626
+ function normalizedUsageFromCanonical(canonicalUsage) {
2627
+ return {
2628
+ promptTokens: canonicalUsage.inputTokens,
2629
+ completionTokens: canonicalUsage.outputTokens,
2630
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2631
+ canonicalUsage
2632
+ };
2633
+ }
2634
+ function normalizeCanonicalLlmUsage(usage) {
2357
2635
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
2358
2636
  const rec = usage;
2359
- const promptTokensRaw = rec["prompt_tokens"];
2360
- const completionTokensRaw = rec["completion_tokens"];
2361
- const totalTokensRaw = rec["total_tokens"];
2362
- const tokensRaw = rec["tokens"];
2363
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
2364
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
2365
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
2366
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
2367
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
2368
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
2369
- return { promptTokens, completionTokens, totalTokens };
2637
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2638
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2639
+ if (inputTokens === void 0 || outputTokens === void 0) {
2640
+ return void 0;
2641
+ }
2642
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2643
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2644
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2645
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2646
+ const totalTokens = readTokenCount(rec, "total_tokens");
2647
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2648
+ return void 0;
2649
+ }
2650
+ return {
2651
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2652
+ outputTokens,
2653
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2654
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2655
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2656
+ source: "provider-response-usage",
2657
+ confidence: "actual",
2658
+ rawUsage: usage
2659
+ };
2660
+ }
2661
+ function normalizeLlmUsage(usage) {
2662
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2663
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
2370
2664
  }
2371
2665
  function recordLlmCallTelemetry(entry) {
2372
2666
  const store = als.getStore();
@@ -2390,17 +2684,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2390
2684
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2391
2685
  return;
2392
2686
  }
2393
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2687
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2688
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2394
2689
  const respText = extractResponseText(ctx.llmResp);
2395
2690
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2396
2691
  try {
2397
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2398
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2399
- return {
2400
- promptTokens,
2401
- completionTokens,
2402
- totalTokens: promptTokens + completionTokens
2403
- };
2692
+ const promptTokens = ctx.llmMessages.reduce(
2693
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2694
+ 0
2695
+ );
2696
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2697
+ return normalizedUsageFromCanonical({
2698
+ inputTokens: promptTokens,
2699
+ outputTokens: completionTokens,
2700
+ totalTokens: promptTokens + completionTokens,
2701
+ source: "local-estimate",
2702
+ confidence: "estimate"
2703
+ });
2404
2704
  } catch {
2405
2705
  return void 0;
2406
2706
  }
@@ -2410,7 +2710,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2410
2710
  stream: ctx.input.stream === true,
2411
2711
  startedAt: ctx.llmCallStartedAt,
2412
2712
  durationMs: ctx.llmCallDurationMs,
2413
- usage: normalizedUsage
2713
+ usage: normalizedUsage,
2714
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2414
2715
  });
2415
2716
  ctx.telemetry.emit({
2416
2717
  kind: "llm_call",
@@ -2418,6 +2719,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2418
2719
  stream: ctx.input.stream === true,
2419
2720
  durationMs: ctx.llmCallDurationMs,
2420
2721
  usage: normalizedUsage,
2722
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2421
2723
  scope: {
2422
2724
  conversationId: ctx.conversationId || void 0,
2423
2725
  turnId: ctx.turnId,
@@ -2561,10 +2863,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2561
2863
  return [
2562
2864
  `\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`,
2563
2865
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2564
- "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",
2866
+ "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",
2565
2867
  `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`,
2566
2868
  ' \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',
2567
- "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"
2869
+ "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"
2568
2870
  ].join("\n");
2569
2871
  };
2570
2872
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2872,6 +3174,219 @@ function createApplySystemReminderStage() {
2872
3174
  };
2873
3175
  }
2874
3176
 
3177
+ // src/runtime-kernel/token-accounting/index.ts
3178
+ var token_accounting_exports = {};
3179
+ __export(token_accounting_exports, {
3180
+ addLedgerAggregate: () => addLedgerAggregate,
3181
+ addUsageTotals: () => addUsageTotals,
3182
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
3183
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
3184
+ computeCost: () => computeCost,
3185
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
3186
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
3187
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
3188
+ });
3189
+
3190
+ // src/runtime-kernel/token-accounting/functions.ts
3191
+ var EMPTY_LEDGER_AGGREGATE = {
3192
+ contextTokens: 0,
3193
+ entryCount: 0,
3194
+ llmCallCount: 0,
3195
+ contextComponentCount: 0
3196
+ };
3197
+ var TOKEN_PRICE_UNIT = 1e6;
3198
+ function sumReportedOptional(values) {
3199
+ const reported = values.filter((value) => value !== void 0);
3200
+ if (reported.length === 0) {
3201
+ return void 0;
3202
+ }
3203
+ return reported.reduce((total, value) => total + value, 0);
3204
+ }
3205
+ function sumTotalTokens(usages) {
3206
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
3207
+ return void 0;
3208
+ }
3209
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
3210
+ }
3211
+ function aggregateCanonicalUsage(usages) {
3212
+ if (usages.length === 0) {
3213
+ return void 0;
3214
+ }
3215
+ return {
3216
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
3217
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
3218
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
3219
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
3220
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
3221
+ totalTokens: sumTotalTokens(usages),
3222
+ usageCount: usages.length
3223
+ };
3224
+ }
3225
+ function createLlmUsageLedgerEntry(input) {
3226
+ return {
3227
+ ...input,
3228
+ kind: "llm-usage"
3229
+ };
3230
+ }
3231
+ function createContextComponentLedgerEntry(input) {
3232
+ return {
3233
+ ...input,
3234
+ kind: "context-component",
3235
+ components: [...input.components],
3236
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
3237
+ };
3238
+ }
3239
+ function addUsageTotals(left, right) {
3240
+ if (!left) {
3241
+ return right;
3242
+ }
3243
+ if (!right) {
3244
+ return left;
3245
+ }
3246
+ return {
3247
+ inputTokens: left.inputTokens + right.inputTokens,
3248
+ outputTokens: left.outputTokens + right.outputTokens,
3249
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
3250
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
3251
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
3252
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
3253
+ usageCount: left.usageCount + right.usageCount
3254
+ };
3255
+ }
3256
+ function addLedgerAggregate(left, right) {
3257
+ return {
3258
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
3259
+ contextTokens: left.contextTokens + right.contextTokens,
3260
+ entryCount: left.entryCount + right.entryCount,
3261
+ llmCallCount: left.llmCallCount + right.llmCallCount,
3262
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
3263
+ };
3264
+ }
3265
+ function aggregateTokenLedgerEntries(entries) {
3266
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
3267
+ return entries.reduce((aggregate, entry) => {
3268
+ if (entry.kind === "llm-usage") {
3269
+ return {
3270
+ ...aggregate,
3271
+ entryCount: aggregate.entryCount + 1,
3272
+ llmCallCount: aggregate.llmCallCount + 1
3273
+ };
3274
+ }
3275
+ return {
3276
+ ...aggregate,
3277
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
3278
+ entryCount: aggregate.entryCount + 1,
3279
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
3280
+ };
3281
+ }, {
3282
+ ...EMPTY_LEDGER_AGGREGATE,
3283
+ llmUsage: aggregateCanonicalUsage(llmUsages)
3284
+ });
3285
+ }
3286
+ function createRunTokenUsageAggregate(input) {
3287
+ const children = input.childAggregates?.reduce(
3288
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
3289
+ EMPTY_LEDGER_AGGREGATE
3290
+ );
3291
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
3292
+ }
3293
+ function componentCost(tokens, pricePerMillion) {
3294
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
3295
+ }
3296
+ function needsPrice(tokens) {
3297
+ return tokens !== void 0 && tokens > 0;
3298
+ }
3299
+ function missingPriceComponents(usage, pricing) {
3300
+ const missing = [];
3301
+ if (!pricing) {
3302
+ if (needsPrice(usage.inputTokens)) {
3303
+ missing.push("input");
3304
+ }
3305
+ if (needsPrice(usage.outputTokens)) {
3306
+ missing.push("output");
3307
+ }
3308
+ if (needsPrice(usage.reasoningTokens)) {
3309
+ missing.push("reasoning");
3310
+ }
3311
+ if (needsPrice(usage.cacheReadTokens)) {
3312
+ missing.push("cacheRead");
3313
+ }
3314
+ if (needsPrice(usage.cacheWriteTokens)) {
3315
+ missing.push("cacheWrite");
3316
+ }
3317
+ return missing;
3318
+ }
3319
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
3320
+ missing.push("input");
3321
+ }
3322
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
3323
+ missing.push("output");
3324
+ }
3325
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
3326
+ missing.push("reasoning");
3327
+ }
3328
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
3329
+ missing.push("cacheRead");
3330
+ }
3331
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
3332
+ missing.push("cacheWrite");
3333
+ }
3334
+ return missing;
3335
+ }
3336
+ function reportedComponentCost(tokens, pricePerMillion) {
3337
+ if (tokens === void 0) {
3338
+ return void 0;
3339
+ }
3340
+ if (tokens === 0) {
3341
+ return 0;
3342
+ }
3343
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
3344
+ }
3345
+ function requiredComponentCost(tokens, pricePerMillion) {
3346
+ if (tokens === 0) {
3347
+ return 0;
3348
+ }
3349
+ return componentCost(tokens, pricePerMillion ?? 0);
3350
+ }
3351
+ function sumComputedCosts(costs) {
3352
+ let total = 0;
3353
+ for (const cost of costs) {
3354
+ total += cost ?? 0;
3355
+ }
3356
+ return total;
3357
+ }
3358
+ function computeCost(usage, pricing) {
3359
+ const missing = missingPriceComponents(usage, pricing);
3360
+ if (!pricing || missing.length > 0) {
3361
+ return {
3362
+ status: "unknown",
3363
+ ...pricing ? { currency: pricing.currency } : {},
3364
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
3365
+ };
3366
+ }
3367
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
3368
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
3369
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
3370
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
3371
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
3372
+ return {
3373
+ status: "computed",
3374
+ currency: pricing.currency,
3375
+ inputCost,
3376
+ outputCost,
3377
+ reasoningCost,
3378
+ cacheReadCost,
3379
+ cacheWriteCost,
3380
+ totalCost: sumComputedCosts([
3381
+ inputCost,
3382
+ outputCost,
3383
+ reasoningCost,
3384
+ cacheReadCost,
3385
+ cacheWriteCost
3386
+ ])
3387
+ };
3388
+ }
3389
+
2875
3390
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2876
3391
  var logger4 = new Logger("GraphAgentExecutor");
2877
3392
  function createBuildContextStage(dependencies) {
@@ -2888,6 +3403,23 @@ function createBuildContextStage(dependencies) {
2888
3403
  ctx.mode = contextBuildResult.mode;
2889
3404
  ctx.llmMessages = contextBuildResult.llmMessages;
2890
3405
  ctx.contextTrace = contextBuildResult.contextTrace;
3406
+ if (contextBuildResult.tokenEstimate) {
3407
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
3408
+ ctx.telemetry.emit({
3409
+ kind: "context_build",
3410
+ modelId: ctx.modelId,
3411
+ mode: contextBuildResult.mode,
3412
+ tokenEstimate: contextBuildResult.tokenEstimate,
3413
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
3414
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
3415
+ scope: {
3416
+ conversationId: ctx.conversationId,
3417
+ runId: ctx.input.toolContext?.runId,
3418
+ parentRunId: ctx.input.toolContext?.parentRunId,
3419
+ turnId: ctx.turnId
3420
+ }
3421
+ });
3422
+ }
2891
3423
  for (const event of contextBuildResult.summaryEvents) {
2892
3424
  if (!isHistorySummaryEvent(event)) {
2893
3425
  continue;
@@ -2902,6 +3434,24 @@ function createBuildContextStage(dependencies) {
2902
3434
  }
2903
3435
  };
2904
3436
  }
3437
+ function createContextLedgerEntry(ctx, contextBuildResult) {
3438
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
3439
+ if (keptComponents.length === 0) {
3440
+ return void 0;
3441
+ }
3442
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
3443
+ const createdAt = Date.now();
3444
+ return createContextComponentLedgerEntry({
3445
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
3446
+ conversationId: ctx.conversationId,
3447
+ runId,
3448
+ parentRunId: ctx.input.toolContext?.parentRunId,
3449
+ turnId: ctx.turnId,
3450
+ route: contextBuildResult.tokenEstimate?.route,
3451
+ createdAt,
3452
+ components: keptComponents
3453
+ });
3454
+ }
2905
3455
 
2906
3456
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2907
3457
  function createBuildDecisionStage(dependencies) {
@@ -3145,6 +3695,7 @@ var GraphAgentExecutor = class {
3145
3695
  modelCatalog;
3146
3696
  telemetryPort;
3147
3697
  auditPort;
3698
+ tokenizer;
3148
3699
  stages;
3149
3700
  middlewares;
3150
3701
  constructor(dependencies) {
@@ -3158,6 +3709,7 @@ var GraphAgentExecutor = class {
3158
3709
  });
3159
3710
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
3160
3711
  this.auditPort = dependencies.auditPort ?? noopAudit;
3712
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
3161
3713
  this.stages = [
3162
3714
  createPrepareCallStage({
3163
3715
  modelResolver: this.modelResolver,
@@ -3201,7 +3753,8 @@ var GraphAgentExecutor = class {
3201
3753
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
3202
3754
  turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3203
3755
  telemetry: this.telemetryPort,
3204
- audit: this.auditPort
3756
+ audit: this.auditPort,
3757
+ tokenizer: this.tokenizer
3205
3758
  };
3206
3759
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
3207
3760
  stream: input.stream === true,
@@ -4166,11 +4719,11 @@ function buildToolOutputUiMeta(params) {
4166
4719
  }
4167
4720
  async function applyObservationGovernance(params) {
4168
4721
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
4169
- return;
4722
+ return {};
4170
4723
  }
4171
4724
  const policy = resolveToolObservationGovernancePolicy(params.policy);
4172
4725
  if (!policy.enabled) {
4173
- return;
4726
+ return {};
4174
4727
  }
4175
4728
  const truncated = await params.observationPreview.truncateObservation({
4176
4729
  context: params.toolContext,
@@ -4184,13 +4737,37 @@ async function applyObservationGovernance(params) {
4184
4737
  })
4185
4738
  });
4186
4739
  if (!truncated.truncated) {
4187
- return;
4740
+ return {};
4188
4741
  }
4189
4742
  params.parsed["observation"] = truncated.preview;
4190
4743
  const data = params.parsed["data"];
4191
4744
  if (isRecord9(data) && !("tool_output_store" in data)) {
4192
4745
  data["tool_output_store"] = { blob_id: truncated.blob_id };
4193
4746
  }
4747
+ return {
4748
+ observationTruncation: buildObservationTruncationMeta({
4749
+ originalText: params.structuredObservation,
4750
+ previewText: truncated.preview,
4751
+ originalChars: truncated.originalChars,
4752
+ previewChars: truncated.previewChars,
4753
+ originalLines: truncated.originalLines,
4754
+ previewLines: truncated.previewLines
4755
+ })
4756
+ };
4757
+ }
4758
+ function buildObservationTruncationMeta(input) {
4759
+ return {
4760
+ originalChars: input.originalChars ?? input.originalText.length,
4761
+ previewChars: input.previewChars ?? input.previewText.length,
4762
+ originalLines: input.originalLines ?? countLines(input.originalText),
4763
+ previewLines: input.previewLines ?? countLines(input.previewText)
4764
+ };
4765
+ }
4766
+ function countLines(value) {
4767
+ if (value.length === 0) {
4768
+ return 0;
4769
+ }
4770
+ return value.split(/\r\n|\r|\n/).length;
4194
4771
  }
4195
4772
 
4196
4773
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -5158,7 +5735,7 @@ var ToolNode = class {
5158
5735
  parentRunId: context.toolContext.parentRunId
5159
5736
  });
5160
5737
  applyProtocolFuseState(context.local);
5161
- await applyObservationGovernance({
5738
+ const observationGovernance = await applyObservationGovernance({
5162
5739
  parsed: context.parsed,
5163
5740
  toolName: context.toolName,
5164
5741
  toolContext: context.toolContext,
@@ -5185,6 +5762,12 @@ var ToolNode = class {
5185
5762
  runtimeToolOutput,
5186
5763
  execIdempotency: context.exec.idempotency
5187
5764
  });
5765
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5766
+ runtimeToolOutput.metadata = {
5767
+ ...runtimeToolOutput.metadata ?? {},
5768
+ observationTruncation: observationGovernance.observationTruncation
5769
+ };
5770
+ }
5188
5771
  const remainingCalls = context.calls.slice(1);
5189
5772
  context.state.local = buildSuccessLocalState({
5190
5773
  local: context.local,
@@ -7019,6 +7602,7 @@ async function callLlmStream(params) {
7019
7602
  const streamAnswerId = generateMessageId();
7020
7603
  let streamChunkSeq = 0;
7021
7604
  let capturedUsage = void 0;
7605
+ let capturedCanonicalUsage = void 0;
7022
7606
  const toolAccumulator = new ToolCallStreamAccumulator([
7023
7607
  "markdown_edit",
7024
7608
  "text_to_image",
@@ -7077,6 +7661,10 @@ async function callLlmStream(params) {
7077
7661
  if (typeof chunk !== "object" || chunk === null) {
7078
7662
  return;
7079
7663
  }
7664
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7665
+ if (parsedCanonicalUsage.success) {
7666
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7667
+ }
7080
7668
  if (chunk.content) {
7081
7669
  emitThoughtComplete(thoughtSegmenter.onBoundary());
7082
7670
  fullResponse += chunk.content;
@@ -7161,6 +7749,12 @@ async function callLlmStream(params) {
7161
7749
  const onUsage = (usage) => {
7162
7750
  capturedUsage = usage;
7163
7751
  };
7752
+ const onCanonicalUsage = (usage) => {
7753
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7754
+ if (parsed.success) {
7755
+ capturedCanonicalUsage = parsed.data;
7756
+ }
7757
+ };
7164
7758
  await aiEngine.chatCompletionStream(
7165
7759
  modelId,
7166
7760
  messages,
@@ -7173,7 +7767,8 @@ async function callLlmStream(params) {
7173
7767
  onError,
7174
7768
  onFinish,
7175
7769
  onThought,
7176
- onUsage
7770
+ onUsage,
7771
+ onCanonicalUsage
7177
7772
  );
7178
7773
  if (streamError) {
7179
7774
  throw streamError;
@@ -7181,12 +7776,13 @@ async function callLlmStream(params) {
7181
7776
  emitThoughtComplete(thoughtSegmenter.finalize());
7182
7777
  const mergedToolCalls = toolAccumulator.getToolCalls();
7183
7778
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
7184
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7779
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
7185
7780
  return {
7186
7781
  content: fullResponse,
7187
7782
  tool_calls: mergedToolCalls,
7188
7783
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
7189
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7784
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7785
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
7190
7786
  };
7191
7787
  }
7192
7788
  return fullResponse;
@@ -7236,6 +7832,10 @@ function tryCloudQuotaFallback({
7236
7832
  }
7237
7833
 
7238
7834
  // src/runtime-kernel/llm/usage-telemetry.ts
7835
+ function parseCanonicalUsage(value) {
7836
+ const parsed = CanonicalLlmUsage.safeParse(value);
7837
+ return parsed.success ? parsed.data : void 0;
7838
+ }
7239
7839
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
7240
7840
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
7241
7841
  return normalizeCompletionResponse(response);
@@ -7246,6 +7846,7 @@ function normalizeCompletionResponse(response) {
7246
7846
  }
7247
7847
  if (isRecord19(response)) {
7248
7848
  const usage = response["usage"];
7849
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7249
7850
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
7250
7851
  if (parsedToolCalls) {
7251
7852
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -7253,7 +7854,8 @@ function normalizeCompletionResponse(response) {
7253
7854
  content: typeof response["content"] === "string" ? response["content"] : "",
7254
7855
  tool_calls: parsedToolCalls,
7255
7856
  reasoning_details: reasoningDetails,
7256
- ...usage !== void 0 ? { usage } : {}
7857
+ ...usage !== void 0 ? { usage } : {},
7858
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7257
7859
  };
7258
7860
  }
7259
7861
  }
@@ -7263,10 +7865,12 @@ function normalizeCompletionResponse(response) {
7263
7865
  if (typeof response === "object") {
7264
7866
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
7265
7867
  const usage = response["usage"];
7868
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7266
7869
  return {
7267
7870
  content: typeof response["content"] === "string" ? response["content"] : "",
7268
7871
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
7269
- ...usage !== void 0 ? { usage } : {}
7872
+ ...usage !== void 0 ? { usage } : {},
7873
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7270
7874
  };
7271
7875
  }
7272
7876
  if (isRecord19(response)) {
@@ -7520,30 +8124,6 @@ var LlmCaller = class {
7520
8124
  }
7521
8125
  };
7522
8126
 
7523
- // src/shared/defaultTokenizerPort.ts
7524
- var DefaultTokenizerPort = class {
7525
- constructor(config = {}) {
7526
- this.config = config;
7527
- }
7528
- config;
7529
- estimateText(text, _modelId) {
7530
- return TokenCalculator.estimateTokens(text, {
7531
- encoding: this.config.encoding,
7532
- avgCharsPerToken: this.config.avgCharsPerToken
7533
- });
7534
- }
7535
- estimateMessage(message, _modelId) {
7536
- return TokenCalculator.estimateMessageTokens(message, {
7537
- encoding: this.config.encoding,
7538
- avgCharsPerToken: this.config.avgCharsPerToken,
7539
- toolCallOverhead: this.config.toolCallOverhead
7540
- });
7541
- }
7542
- };
7543
- function createDefaultTokenizerPort(config = {}) {
7544
- return new DefaultTokenizerPort(config);
7545
- }
7546
-
7547
8127
  // src/runtime-kernel/child-runs/index.ts
7548
8128
  var child_runs_exports = {};
7549
8129
  __export(child_runs_exports, {
@@ -9153,6 +9733,7 @@ __export(telemetry_exports, {
9153
9733
  var TELEMETRY_EVENT_KINDS = [
9154
9734
  "llm_call",
9155
9735
  "tool_call",
9736
+ "context_build",
9156
9737
  "graph_node",
9157
9738
  "run_lifecycle"
9158
9739
  ];