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