@linnlabs/linnkit 0.9.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 (102) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/bin/linnkit.cjs +7 -0
  3. package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
  4. package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
  5. package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
  6. package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
  7. package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
  8. package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
  9. package/dist/cli.cjs +682 -258
  10. package/dist/cli.cjs.map +1 -1
  11. package/dist/cli.js +682 -258
  12. package/dist/cli.js.map +1 -1
  13. package/dist/context-manager.cjs +823 -57
  14. package/dist/context-manager.cjs.map +1 -1
  15. package/dist/context-manager.d.cts +132 -18
  16. package/dist/context-manager.d.ts +132 -18
  17. package/dist/context-manager.js +823 -58
  18. package/dist/context-manager.js.map +1 -1
  19. package/dist/{context-trace-HE2qY5Q-.d.cts → context-trace-DrtvKac4.d.cts} +37 -4
  20. package/dist/{context-trace-DRi5M4lX.d.ts → context-trace-WV1HAZeB.d.ts} +37 -4
  21. package/dist/contracts.cjs +225 -2
  22. package/dist/contracts.cjs.map +1 -1
  23. package/dist/contracts.d.cts +6 -4
  24. package/dist/contracts.d.ts +6 -4
  25. package/dist/contracts.js +205 -3
  26. package/dist/contracts.js.map +1 -1
  27. package/dist/{defaultGraphExecutor-BIjJj7WF.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +48 -19
  28. package/dist/{defaultGraphExecutor-BBswR8wn.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +48 -19
  29. package/dist/{index-BanRABEt.d.cts → index-BeQO0rx2.d.cts} +345 -268
  30. package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
  31. package/dist/{index-Dl5PLgAv.d.cts → index-Crl5E4eF.d.cts} +27 -4
  32. package/dist/{index-CJeWHopy.d.ts → index-DWGKvssS.d.ts} +3 -3
  33. package/dist/{index-CHqwkvGp.d.ts → index-X5lYU1Lj.d.ts} +27 -4
  34. package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
  35. package/dist/{index-Z8NXKNwI.d.ts → index-wOZD-p2-.d.ts} +345 -268
  36. package/dist/{index-DO4dQgf2.d.cts → index-wXVAHZ0D.d.cts} +3 -3
  37. package/dist/index.cjs +1011 -329
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +19 -16
  40. package/dist/index.d.ts +19 -16
  41. package/dist/index.js +1011 -329
  42. package/dist/index.js.map +1 -1
  43. package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
  44. package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
  45. package/dist/{ports-DnLuKfpE.d.ts → ports-Dugizzje.d.cts} +6 -2
  46. package/dist/{ports-DaatKJXp.d.cts → ports-fhp84x_C.d.ts} +6 -2
  47. package/dist/ports.d.cts +8 -5
  48. package/dist/ports.d.ts +8 -5
  49. package/dist/quickstart.cjs +683 -258
  50. package/dist/quickstart.cjs.map +1 -1
  51. package/dist/quickstart.d.cts +11 -10
  52. package/dist/quickstart.d.ts +11 -10
  53. package/dist/quickstart.js +683 -258
  54. package/dist/quickstart.js.map +1 -1
  55. package/dist/{runAgent-CPj_9e58.d.ts → runAgent-BmMSju8I.d.ts} +6 -6
  56. package/dist/{runAgent-HYKlXbVr.d.cts → runAgent-CKgcRSRH.d.cts} +6 -6
  57. package/dist/{runHandle-D3gPsD7B.d.cts → runHandle-DH4VmQx6.d.cts} +6 -4
  58. package/dist/{runHandle-CyXvzgzk.d.ts → runHandle-o3p06Nva.d.ts} +6 -4
  59. package/dist/runtime-kernel/events.cjs +202 -1
  60. package/dist/runtime-kernel/events.cjs.map +1 -1
  61. package/dist/runtime-kernel/events.d.cts +5 -5
  62. package/dist/runtime-kernel/events.d.ts +5 -5
  63. package/dist/runtime-kernel/events.js +202 -1
  64. package/dist/runtime-kernel/events.js.map +1 -1
  65. package/dist/runtime-kernel.cjs +999 -340
  66. package/dist/runtime-kernel.cjs.map +1 -1
  67. package/dist/runtime-kernel.d.cts +16 -14
  68. package/dist/runtime-kernel.d.ts +16 -14
  69. package/dist/runtime-kernel.js +990 -341
  70. package/dist/runtime-kernel.js.map +1 -1
  71. package/dist/testkit.cjs +1003 -321
  72. package/dist/testkit.cjs.map +1 -1
  73. package/dist/testkit.d.cts +16 -14
  74. package/dist/testkit.d.ts +16 -14
  75. package/dist/testkit.js +1003 -321
  76. package/dist/testkit.js.map +1 -1
  77. package/dist/{todo-B1PmDlp3.d.cts → todo-Ca8llpRQ.d.cts} +1 -1
  78. package/dist/{todo-B1PmDlp3.d.ts → todo-Ca8llpRQ.d.ts} +1 -1
  79. package/dist/{agentSpec-EkmviZjy.d.cts → token-accounting-CwpSPg4y.d.cts} +1280 -1
  80. package/dist/{agentSpec-EkmviZjy.d.ts → token-accounting-CwpSPg4y.d.ts} +1280 -1
  81. package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
  82. package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
  83. package/dist/token-counter-CFfP8PQb.d.cts +26 -0
  84. package/dist/token-counter-SFyyTeaG.d.ts +26 -0
  85. package/dist/token-usage-CqwT7-5K.d.cts +133 -0
  86. package/dist/token-usage-CqwT7-5K.d.ts +133 -0
  87. package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
  88. package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
  89. package/dist/{toolContracts-CLkQmhTG.d.cts → toolContracts-Bm3EZ1UM.d.cts} +13 -2
  90. package/dist/{toolContracts-Blll0241.d.ts → toolContracts-f8lzZBNa.d.ts} +13 -2
  91. package/docs/README.md +1 -1
  92. package/docs/integration/README.md +3 -3
  93. package/docs/integration/agent-registration-guide.md +3 -1
  94. package/docs/integration/child-runs.md +4 -1
  95. package/docs/integration/context-engineering.md +83 -16
  96. package/docs/integration/context-fences.md +44 -3
  97. package/docs/integration/llm-provider.md +1 -1
  98. package/docs/integration/persistence.md +1 -0
  99. package/docs/integration/run-supervisor.md +3 -0
  100. package/docs/integration/tool-development-guide.md +7 -5
  101. package/docs/integration/tool-history.md +43 -17
  102. package/package.json +4 -3
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,20 +60,25 @@ __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,
67
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
62
68
  countToolCallsInCurrentRequest: () => countToolCallsInCurrentRequest,
63
69
  createCompositeAudit: () => createCompositeAudit,
64
70
  createConsoleAudit: () => createConsoleAudit,
65
71
  createContextCheckpointTool: () => createContextCheckpointTool,
72
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
66
73
  createDefaultGraphExecutor: () => createDefaultGraphExecutor,
67
74
  createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
68
75
  createDefaultTokenizerPort: () => createDefaultTokenizerPort,
69
76
  createEventStoreAudit: () => createEventStoreAudit,
70
77
  createFileAudit: () => createFileAudit,
71
78
  createGraphLoopHarness: () => createGraphLoopHarness,
79
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
72
80
  createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
81
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
73
82
  createSystemReminderRules: () => createSystemReminderRules,
74
83
  defaultPolicyEngine: () => defaultPolicyEngine,
75
84
  defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
@@ -106,6 +115,7 @@ __export(runtime_kernel_exports, {
106
115
  systemReminder: () => system_reminder_exports,
107
116
  telemetry: () => telemetry_exports,
108
117
  toDisplayStep: () => toDisplayStep,
118
+ tokenAccounting: () => token_accounting_exports,
109
119
  toolCallStreakTemplate: () => toolCallStreakTemplate,
110
120
  toolCallStreakTrigger: () => toolCallStreakTrigger,
111
121
  tools: () => tools_exports
@@ -140,6 +150,7 @@ var Logger = class {
140
150
  constructor(moduleName) {
141
151
  this.moduleName = moduleName;
142
152
  }
153
+ moduleName;
143
154
  debug(message, data) {
144
155
  this.log(0 /* DEBUG */, "debug", message, data);
145
156
  }
@@ -246,14 +257,23 @@ __export(contracts_exports, {
246
257
  AuditScope: () => AuditScope,
247
258
  BaseEvent: () => BaseEvent,
248
259
  BaseSSEEvent: () => BaseSSEEvent,
260
+ CanonicalLlmUsage: () => CanonicalLlmUsage,
261
+ ContextBuildTokenEstimate: () => ContextBuildTokenEstimate,
262
+ ContextComponentTokenLedgerEntry: () => ContextComponentTokenLedgerEntry,
263
+ ContextTokenComponent: () => ContextTokenComponent,
264
+ ContextTokenComponentKind: () => ContextTokenComponentKind,
265
+ CostBreakdown: () => CostBreakdown,
249
266
  DEFAULT_MAX_STEPS: () => DEFAULT_MAX_STEPS,
250
267
  EventEnvelope: () => EventEnvelope,
251
268
  ExecutionTraceContext: () => ExecutionTraceContext,
252
269
  HistorySummaryMeta: () => HistorySummaryMeta,
253
270
  ImageInfoMeta: () => ImageInfoMeta,
271
+ LlmUsageTokenLedgerEntry: () => LlmUsageTokenLedgerEntry,
272
+ ObservationTruncationMeta: () => ObservationTruncationMeta,
254
273
  PersistentMetadata: () => PersistentMetadata,
255
274
  ProviderReasoningDetails: () => ProviderReasoningDetails,
256
275
  ProviderReasoningDetailsPayload: () => ProviderReasoningDetailsPayload,
276
+ RunTokenUsageAggregate: () => RunTokenUsageAggregate,
257
277
  RuntimeEvent: () => RuntimeEvent,
258
278
  SSEErrorEvent: () => SSEErrorEvent,
259
279
  SSEEvent: () => SSEEvent,
@@ -276,6 +296,18 @@ __export(contracts_exports, {
276
296
  Status: () => Status,
277
297
  SystemMessage: () => SystemMessage,
278
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,
279
311
  ToolBindingSpec: () => ToolBindingSpec,
280
312
  ToolCallDecisionPayload: () => ToolCallDecisionPayload,
281
313
  ToolCallExtraContent: () => ToolCallExtraContent,
@@ -361,6 +393,12 @@ var ToolOutputMeta = zod.z.object({
361
393
  args: zod.z.record(zod.z.unknown()).optional(),
362
394
  tool_call_id: zod.z.string()
363
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
+ });
364
402
  var ImageInfoMeta = zod.z.object({
365
403
  url: zod.z.string().optional(),
366
404
  width: zod.z.number().int().positive().optional(),
@@ -392,6 +430,7 @@ var PersistentMetadata = zod.z.object({
392
430
  tool_name: zod.z.string().optional(),
393
431
  args: zod.z.record(zod.z.unknown()).optional(),
394
432
  tool_call_id: zod.z.string().optional(),
433
+ observationTruncation: ObservationTruncationMeta.optional(),
395
434
  raw_output: zod.z.string().optional(),
396
435
  image_info: ImageInfoMeta.optional(),
397
436
  taskType: zod.z.string().optional(),
@@ -563,6 +602,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
563
602
  });
564
603
  var AgentSpecToolHistoryPolicy = zod.z.object({
565
604
  strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
605
+ retentionMode: zod.z.enum(["drop", "compress"]).optional(),
566
606
  keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
567
607
  keepLatestRuns: zod.z.number().int().nonnegative().optional(),
568
608
  maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
@@ -615,7 +655,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
615
655
  var AgentSpecTokenEstimationPolicy = zod.z.object({
616
656
  encoding: zod.z.string().min(1).optional(),
617
657
  avgCharsPerToken: zod.z.number().positive().optional(),
618
- 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()
619
669
  });
620
670
  var SYSTEM_REMINDER_BUILTIN_TRIGGER_KINDS = [
621
671
  "phase-equals",
@@ -685,12 +735,13 @@ var AgentSpecContextPolicy = zod.z.object({
685
735
  var DEFAULT_CONTEXT_POLICY = {
686
736
  profileId: "agent",
687
737
  budget: {
688
- maxTokens: 12e4,
738
+ maxTokens: 232e3,
689
739
  reservedForResponse: 2400,
690
740
  workingMemoryBudgetPercentage: 0.7
691
741
  },
692
742
  toolHistory: {
693
743
  strategy: "per-run",
744
+ retentionMode: "drop",
694
745
  keepLatestToolPairs: 2,
695
746
  keepLatestRuns: 1,
696
747
  maxInteractionGroups: 12,
@@ -1536,12 +1587,206 @@ var createSSEHistorySummaryEvent = (id, conversationId, turnId, summaryId, conte
1536
1587
  summary_seq: summarySeq,
1537
1588
  ...options
1538
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
+ });
1539
1773
 
1540
1774
  // src/runtime-kernel/graph-engine/engine.ts
1541
1775
  var logger = new Logger("GraphExecutor");
1542
1776
  function asLocalRecord(local) {
1543
1777
  return local && typeof local === "object" ? { ...local } : {};
1544
1778
  }
1779
+ function readNonEmptyString(value) {
1780
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1781
+ }
1782
+ function readRuntimeConversationId(state) {
1783
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1784
+ return readNonEmptyString(local?.conversationId);
1785
+ }
1786
+ function readRuntimeTurnId(state) {
1787
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1788
+ return readNonEmptyString(local?.turnId);
1789
+ }
1545
1790
  var GraphExecutor = class {
1546
1791
  constructor(checkpointer, config = {}) {
1547
1792
  this.checkpointer = checkpointer;
@@ -1551,6 +1796,7 @@ var GraphExecutor = class {
1551
1796
  };
1552
1797
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1553
1798
  }
1799
+ checkpointer;
1554
1800
  nodes = /* @__PURE__ */ new Map();
1555
1801
  ephemeralLocals = /* @__PURE__ */ new Map();
1556
1802
  config;
@@ -1558,8 +1804,8 @@ var GraphExecutor = class {
1558
1804
  registerNode(node) {
1559
1805
  this.nodes.set(node.id, node);
1560
1806
  }
1561
- async peekCheckpoint(conversationId) {
1562
- return await this.checkpointer.load(conversationId);
1807
+ async peekCheckpoint(checkpointKey) {
1808
+ return await this.checkpointer.load(checkpointKey);
1563
1809
  }
1564
1810
  sanitize(state) {
1565
1811
  const local = asLocalRecord(state.local);
@@ -1571,8 +1817,8 @@ var GraphExecutor = class {
1571
1817
  local
1572
1818
  };
1573
1819
  }
1574
- async prime(conversationId, local, nodeId = "user") {
1575
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1820
+ async prime(checkpointKey, local, nodeId = "user") {
1821
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1576
1822
  const localSansMemory = { ...local || {} };
1577
1823
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1578
1824
  const state = {
@@ -1580,10 +1826,10 @@ var GraphExecutor = class {
1580
1826
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1581
1827
  local: localSansMemory
1582
1828
  };
1583
- await this.checkpointer.save(conversationId, state);
1829
+ await this.checkpointer.save(checkpointKey, state);
1584
1830
  }
1585
- async setNode(conversationId, nodeId, localPatch) {
1586
- const current = await this.checkpointer.load(conversationId) || {
1831
+ async setNode(checkpointKey, nodeId, localPatch) {
1832
+ const current = await this.checkpointer.load(checkpointKey) || {
1587
1833
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1588
1834
  local: {}
1589
1835
  };
@@ -1594,19 +1840,46 @@ var GraphExecutor = class {
1594
1840
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1595
1841
  local: mergedLocal
1596
1842
  };
1597
- await this.checkpointer.save(conversationId, next);
1843
+ await this.checkpointer.save(checkpointKey, next);
1598
1844
  }
1599
- async runUntilYield(conversationId) {
1845
+ async runUntilYield(checkpointKey) {
1600
1846
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1601
1847
  let lifecyclePhase = "completed";
1848
+ let initialState = null;
1849
+ try {
1850
+ initialState = await this.loadInitialState(checkpointKey);
1851
+ } catch (err) {
1852
+ lifecyclePhase = "failed";
1853
+ this.telemetryPort.emit({
1854
+ kind: "run_lifecycle",
1855
+ runId,
1856
+ phase: "spawned",
1857
+ scope: {}
1858
+ });
1859
+ this.telemetryPort.emit({
1860
+ kind: "run_lifecycle",
1861
+ runId,
1862
+ phase: lifecyclePhase,
1863
+ scope: {}
1864
+ });
1865
+ throw err;
1866
+ }
1867
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1868
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1602
1869
  this.telemetryPort.emit({
1603
1870
  kind: "run_lifecycle",
1604
1871
  runId,
1605
1872
  phase: "spawned",
1606
- scope: { conversationId: conversationId || void 0 }
1873
+ scope: {
1874
+ conversationId: lifecycleConversationId,
1875
+ turnId: lifecycleTurnId
1876
+ }
1607
1877
  });
1608
1878
  try {
1609
- return await this.runUntilYieldInternal(conversationId);
1879
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1880
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1881
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1882
+ return result;
1610
1883
  } catch (err) {
1611
1884
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1612
1885
  throw err;
@@ -1615,17 +1888,23 @@ var GraphExecutor = class {
1615
1888
  kind: "run_lifecycle",
1616
1889
  runId,
1617
1890
  phase: lifecyclePhase,
1618
- scope: { conversationId: conversationId || void 0 }
1891
+ scope: {
1892
+ conversationId: lifecycleConversationId,
1893
+ turnId: lifecycleTurnId
1894
+ }
1619
1895
  });
1620
1896
  }
1621
1897
  }
1622
- async runUntilYieldInternal(conversationId) {
1623
- let state = await this.checkpointer.load(conversationId) || {
1898
+ async loadInitialState(checkpointKey) {
1899
+ return await this.checkpointer.load(checkpointKey) || {
1624
1900
  nodeId: "user",
1625
1901
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1626
1902
  local: {}
1627
1903
  };
1628
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1904
+ }
1905
+ async runUntilYieldInternal(checkpointKey, initialState) {
1906
+ let state = initialState;
1907
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1629
1908
  state = {
1630
1909
  ...state,
1631
1910
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1654,7 +1933,7 @@ var GraphExecutor = class {
1654
1933
  const signalRaw = state.local?.signal;
1655
1934
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1656
1935
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1657
- this.ephemeralLocals.delete(conversationId);
1936
+ this.ephemeralLocals.delete(checkpointKey);
1658
1937
  throwAbortError();
1659
1938
  }
1660
1939
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1702,8 +1981,8 @@ var GraphExecutor = class {
1702
1981
  checkpointCount
1703
1982
  });
1704
1983
  const cp2 = this.sanitize(state);
1705
- await this.checkpointer.save(conversationId, cp2);
1706
- this.ephemeralLocals.delete(conversationId);
1984
+ await this.checkpointer.save(checkpointKey, cp2);
1985
+ this.ephemeralLocals.delete(checkpointKey);
1707
1986
  return { events: allEvents, checkpoint: cp2, stepCount };
1708
1987
  }
1709
1988
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1714,18 +1993,18 @@ var GraphExecutor = class {
1714
1993
  });
1715
1994
  const nodeRunStartedAt = Date.now();
1716
1995
  const nodeIdForTelemetry = state.nodeId;
1996
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1717
1997
  let result;
1718
1998
  try {
1719
1999
  result = await node.run(state);
1720
2000
  } finally {
1721
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1722
2001
  this.telemetryPort.emit({
1723
2002
  kind: "graph_node",
1724
2003
  nodeId: nodeIdForTelemetry,
1725
2004
  durationMs: Date.now() - nodeRunStartedAt,
1726
2005
  scope: {
1727
- conversationId: conversationId || void 0,
1728
- turnId: turnIdForTelemetry
2006
+ conversationId: conversationIdForTelemetry,
2007
+ turnId: readRuntimeTurnId(state)
1729
2008
  }
1730
2009
  });
1731
2010
  }
@@ -1764,7 +2043,7 @@ var GraphExecutor = class {
1764
2043
  });
1765
2044
  state = { ...state, nodeId: nextNodeId };
1766
2045
  const cp2 = this.sanitize(state);
1767
- await this.checkpointer.save(conversationId, cp2);
2046
+ await this.checkpointer.save(checkpointKey, cp2);
1768
2047
  continue;
1769
2048
  }
1770
2049
  if (result.kind === "yield") {
@@ -1775,7 +2054,7 @@ var GraphExecutor = class {
1775
2054
  checkpointCount
1776
2055
  });
1777
2056
  const cp2 = this.sanitize(state);
1778
- await this.checkpointer.save(conversationId, cp2);
2057
+ await this.checkpointer.save(checkpointKey, cp2);
1779
2058
  return { events: allEvents, checkpoint: cp2, stepCount };
1780
2059
  }
1781
2060
  if (result.kind === "pause") {
@@ -1786,7 +2065,7 @@ var GraphExecutor = class {
1786
2065
  checkpointCount
1787
2066
  });
1788
2067
  const cp2 = this.sanitize(state);
1789
- await this.checkpointer.save(conversationId, cp2);
2068
+ await this.checkpointer.save(checkpointKey, cp2);
1790
2069
  return { events: allEvents, checkpoint: cp2, stepCount };
1791
2070
  }
1792
2071
  }
@@ -1797,8 +2076,8 @@ var GraphExecutor = class {
1797
2076
  checkpointCount
1798
2077
  });
1799
2078
  const cp = this.sanitize(state);
1800
- await this.checkpointer.save(conversationId, cp);
1801
- this.ephemeralLocals.delete(conversationId);
2079
+ await this.checkpointer.save(checkpointKey, cp);
2080
+ this.ephemeralLocals.delete(checkpointKey);
1802
2081
  return { events: allEvents, checkpoint: cp, stepCount };
1803
2082
  }
1804
2083
  };
@@ -1894,6 +2173,190 @@ var noopAudit = {
1894
2173
  flush() {
1895
2174
  }
1896
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
+ }
1897
2360
 
1898
2361
  // src/shared/ids.ts
1899
2362
  function isoRandomUUID() {
@@ -1995,15 +2458,15 @@ function splitConcatenatedJsonObjects(input) {
1995
2458
  }
1996
2459
 
1997
2460
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1998
- function readNonEmptyString(value) {
2461
+ function readNonEmptyString2(value) {
1999
2462
  if (typeof value !== "string") return void 0;
2000
2463
  const trimmed = value.trim();
2001
2464
  return trimmed.length > 0 ? trimmed : void 0;
2002
2465
  }
2003
2466
  function resolveConversationIdForRuntimeEvents(toolContext) {
2004
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
2467
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
2005
2468
  if (fromCamel) return fromCamel;
2006
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
2469
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
2007
2470
  if (fromSnake) return fromSnake;
2008
2471
  return generateMessageId();
2009
2472
  }
@@ -2074,6 +2537,13 @@ function resolveUsage(response) {
2074
2537
  }
2075
2538
  return response.usage;
2076
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
+ }
2077
2547
  function resolveToolCalls(response) {
2078
2548
  if (!response || typeof response === "string") {
2079
2549
  return void 0;
@@ -2110,214 +2580,87 @@ function recordAfterContextManagerOnSystemReminderHit(params) {
2110
2580
  function recordToolProtocolError(params) {
2111
2581
  recorder?.recordToolProtocolError?.(params);
2112
2582
  }
2113
- function recordRunTranscript(params) {
2114
- recorder?.recordRunTranscript?.(params);
2115
- }
2116
-
2117
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2118
- var contextAuditMiddleware = async (ctx, stage, next) => {
2119
- if (stage.id === "build_context") {
2120
- recordBeforeContextManager({
2121
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
2122
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2123
- });
2124
- }
2125
- await next();
2126
- if (stage.id !== "apply_system_reminder") {
2127
- return;
2128
- }
2129
- const toolNamesForAudit = resolveToolNamesForAudit(ctx);
2130
- recordAfterContextManager({
2131
- mode: ctx.mode,
2132
- llmMessages: ctx.llmMessages,
2133
- toolNames: toolNamesForAudit,
2134
- contextTrace: ctx.contextTrace
2135
- });
2136
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2137
- recordAfterContextManagerOnSystemReminderHit({
2138
- mode: ctx.mode,
2139
- llmMessages: ctx.llmMessages,
2140
- toolNames: toolNamesForAudit,
2141
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2142
- contextTrace: ctx.contextTrace
2143
- });
2144
- }
2145
- };
2146
- var TokenCalculator = class {
2147
- static BYTES_PER_TOKEN_LATIN = 4;
2148
- static BYTES_PER_TOKEN_CJK = 3;
2149
- static OVERHEAD_PER_MESSAGE = 5;
2150
- static OVERHEAD_PER_TOOL_CALL = 10;
2151
- static encoderCache = /* @__PURE__ */ new Map();
2152
- static DEFAULT_ENCODING = "cl100k_base";
2153
- static SUPPORTED_ENCODINGS = [
2154
- "gpt2",
2155
- "r50k_base",
2156
- "p50k_base",
2157
- "p50k_edit",
2158
- "cl100k_base",
2159
- "o200k_base"
2160
- ];
2161
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
2162
- const normalized = (modelIdentifier || "").trim().toLowerCase();
2163
- if (this.isSupportedEncodingName(normalized)) {
2164
- return normalized;
2165
- }
2166
- if (normalized.includes("deepseek")) {
2167
- return "cl100k_base";
2168
- }
2169
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
2170
- return "o200k_base";
2171
- }
2172
- if (normalized.includes("gemini") || normalized.includes("claude")) {
2173
- return "cl100k_base";
2174
- }
2175
- return this.DEFAULT_ENCODING;
2176
- }
2177
- static isSupportedEncodingName(value) {
2178
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
2179
- }
2180
- static getEncoder(modelIdentifierOrEncoding) {
2181
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
2182
- const cached = this.encoderCache.get(encodingName);
2183
- if (cached) {
2184
- return cached;
2185
- }
2186
- const encoder = tiktoken.get_encoding(encodingName);
2187
- this.encoderCache.set(encodingName, encoder);
2188
- return encoder;
2189
- }
2190
- static estimateTokensRough(text, _modelIdentifier) {
2191
- if (!text) return 0;
2192
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
2193
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
2194
- const byteLength = new TextEncoder().encode(text).length;
2195
- return Math.ceil(byteLength / ratio);
2196
- }
2197
- static estimateTokens(text, options = {}) {
2198
- if (!text) return 0;
2199
- if (options.encoding) {
2200
- try {
2201
- return this.estimateTokensPrecise(text, options.encoding);
2202
- } catch {
2203
- }
2204
- }
2205
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
2206
- return Math.ceil(text.length / avgCharsPerToken);
2207
- }
2208
- static estimateTokensPrecise(text, modelIdentifier) {
2209
- if (!text) return 0;
2210
- const encoder = this.getEncoder(modelIdentifier);
2211
- return encoder.encode(text).length;
2212
- }
2213
- static estimateMessageTokens(message, options = {}) {
2214
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
2215
- if (message.content) {
2216
- totalTokens += this.estimateTokens(String(message.content), options);
2217
- }
2218
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
2219
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
2220
- for (const toolCall of toolCalls) {
2221
- totalTokens += toolCallOverhead;
2222
- const fn = toolCall["function"];
2223
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
2224
- const fnRecord = fn;
2225
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
2226
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
2227
- }
2228
- }
2229
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
2230
- if (toolCallId) {
2231
- totalTokens += this.estimateTokens(toolCallId, options);
2232
- }
2233
- return totalTokens;
2234
- }
2235
- static estimateMessageTokensPrecise(message, modelIdentifier) {
2236
- return this.estimateMessageTokens(message, {
2237
- encoding: modelIdentifier,
2238
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
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 }
2239
2593
  });
2240
2594
  }
2241
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
2242
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2243
- }
2244
- static extractToolCallsForTokenEstimate(message) {
2245
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
2246
- if (Array.isArray(direct)) return direct;
2247
- const metadata = "metadata" in message ? message.metadata : void 0;
2248
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
2249
- const metadataRecord = metadata;
2250
- const metadataToolCalls = metadataRecord["tool_calls"];
2251
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2252
- }
2253
- static extractToolCallIdForTokenEstimate(message) {
2254
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
2255
- return message.tool_call_id;
2256
- }
2257
- const metadata = "metadata" in message ? message.metadata : void 0;
2258
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
2259
- const metadataRecord = metadata;
2260
- const toolCallId = metadataRecord["tool_call_id"];
2261
- return typeof toolCallId === "string" ? toolCallId : void 0;
2262
- }
2263
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
2264
- if (!text || maxTokens <= 0) return "";
2265
- const encoder = this.getEncoder(modelIdentifier);
2266
- const tokens = encoder.encode(text);
2267
- if (tokens.length <= maxTokens) {
2268
- return text;
2269
- }
2270
- let truncatedTokens;
2271
- const ellipsis = "...";
2272
- switch (strategy) {
2273
- case "start":
2274
- truncatedTokens = tokens.slice(0, maxTokens);
2275
- return encoder.decode(truncatedTokens) + ellipsis;
2276
- case "end":
2277
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
2278
- return ellipsis + encoder.decode(truncatedTokens);
2279
- case "middle": {
2280
- const half = Math.floor(maxTokens / 2);
2281
- const head = tokens.slice(0, half);
2282
- const tail = tokens.slice(tokens.length - (maxTokens - half));
2283
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
2284
- }
2285
- default:
2286
- truncatedTokens = tokens.slice(0, maxTokens);
2287
- return encoder.decode(truncatedTokens) + ellipsis;
2288
- }
2595
+ await next();
2596
+ if (stage.id !== "apply_system_reminder") {
2597
+ return;
2289
2598
  }
2290
- static cleanup() {
2291
- for (const encoder of this.encoderCache.values()) {
2292
- encoder.free();
2293
- }
2294
- this.encoderCache.clear();
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
+ });
2295
2614
  }
2296
2615
  };
2297
- function normalizePositiveNumber(value, fallback) {
2298
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2616
+ var als = new async_hooks.AsyncLocalStorage();
2617
+ function readTokenCount(record, key) {
2618
+ const value = record[key];
2619
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2299
2620
  }
2300
- function normalizeNonNegativeInteger(value, fallback) {
2301
- if (typeof value !== "number" || !Number.isFinite(value)) {
2302
- return fallback;
2303
- }
2304
- return Math.max(0, Math.floor(value));
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));
2305
2625
  }
2306
- var als = new async_hooks.AsyncLocalStorage();
2307
- function normalizeLlmUsage(usage) {
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) {
2308
2635
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
2309
2636
  const rec = usage;
2310
- const promptTokensRaw = rec["prompt_tokens"];
2311
- const completionTokensRaw = rec["completion_tokens"];
2312
- const totalTokensRaw = rec["total_tokens"];
2313
- const tokensRaw = rec["tokens"];
2314
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
2315
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
2316
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
2317
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
2318
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
2319
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
2320
- 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;
2321
2664
  }
2322
2665
  function recordLlmCallTelemetry(entry) {
2323
2666
  const store = als.getStore();
@@ -2341,17 +2684,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2341
2684
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2342
2685
  return;
2343
2686
  }
2344
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2687
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2688
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2345
2689
  const respText = extractResponseText(ctx.llmResp);
2346
2690
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2347
2691
  try {
2348
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2349
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2350
- return {
2351
- promptTokens,
2352
- completionTokens,
2353
- totalTokens: promptTokens + completionTokens
2354
- };
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
+ });
2355
2704
  } catch {
2356
2705
  return void 0;
2357
2706
  }
@@ -2361,7 +2710,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2361
2710
  stream: ctx.input.stream === true,
2362
2711
  startedAt: ctx.llmCallStartedAt,
2363
2712
  durationMs: ctx.llmCallDurationMs,
2364
- usage: normalizedUsage
2713
+ usage: normalizedUsage,
2714
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2365
2715
  });
2366
2716
  ctx.telemetry.emit({
2367
2717
  kind: "llm_call",
@@ -2369,6 +2719,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2369
2719
  stream: ctx.input.stream === true,
2370
2720
  durationMs: ctx.llmCallDurationMs,
2371
2721
  usage: normalizedUsage,
2722
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2372
2723
  scope: {
2373
2724
  conversationId: ctx.conversationId || void 0,
2374
2725
  turnId: ctx.turnId,
@@ -2385,7 +2736,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
2385
2736
  if (stage.id !== "execute_llm") {
2386
2737
  return;
2387
2738
  }
2388
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2739
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
2389
2740
  if (!normalized) {
2390
2741
  return;
2391
2742
  }
@@ -2512,10 +2863,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2512
2863
  return [
2513
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`,
2514
2865
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2515
- "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",
2516
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`,
2517
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',
2518
- "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"
2519
2870
  ].join("\n");
2520
2871
  };
2521
2872
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2823,6 +3174,219 @@ function createApplySystemReminderStage() {
2823
3174
  };
2824
3175
  }
2825
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
+
2826
3390
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2827
3391
  var logger4 = new Logger("GraphAgentExecutor");
2828
3392
  function createBuildContextStage(dependencies) {
@@ -2839,6 +3403,23 @@ function createBuildContextStage(dependencies) {
2839
3403
  ctx.mode = contextBuildResult.mode;
2840
3404
  ctx.llmMessages = contextBuildResult.llmMessages;
2841
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
+ }
2842
3423
  for (const event of contextBuildResult.summaryEvents) {
2843
3424
  if (!isHistorySummaryEvent(event)) {
2844
3425
  continue;
@@ -2853,6 +3434,24 @@ function createBuildContextStage(dependencies) {
2853
3434
  }
2854
3435
  };
2855
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
+ }
2856
3455
 
2857
3456
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2858
3457
  function createBuildDecisionStage(dependencies) {
@@ -2986,7 +3585,7 @@ function createExecuteLlmStage(dependencies) {
2986
3585
  streamEventHandler,
2987
3586
  ctx.signal,
2988
3587
  (fallbackModelId) => {
2989
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
3588
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2990
3589
  },
2991
3590
  (info) => {
2992
3591
  ctx.modelFallbackAudit = info;
@@ -3030,7 +3629,7 @@ function createPrepareCallStage(dependencies) {
3030
3629
  return {
3031
3630
  id: "prepare_call",
3032
3631
  async run(ctx) {
3033
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
3632
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
3034
3633
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
3035
3634
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
3036
3635
  await emitAuditEnvelope(ctx.audit, {
@@ -3096,19 +3695,21 @@ var GraphAgentExecutor = class {
3096
3695
  modelCatalog;
3097
3696
  telemetryPort;
3098
3697
  auditPort;
3698
+ tokenizer;
3099
3699
  stages;
3100
3700
  middlewares;
3101
3701
  constructor(dependencies) {
3102
3702
  this.llmCaller = dependencies.llmCaller;
3103
3703
  this.toolRuntime = dependencies.toolRuntime;
3104
3704
  this.contextBuilder = dependencies.contextBuilder;
3105
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3705
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
3106
3706
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
3107
3707
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
3108
3708
  modelCatalog: this.modelCatalog
3109
3709
  });
3110
3710
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
3111
3711
  this.auditPort = dependencies.auditPort ?? noopAudit;
3712
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
3112
3713
  this.stages = [
3113
3714
  createPrepareCallStage({
3114
3715
  modelResolver: this.modelResolver,
@@ -3150,9 +3751,10 @@ var GraphAgentExecutor = class {
3150
3751
  llmMessages: [],
3151
3752
  mode: input.request.mode === "chat" ? "chat" : "agent",
3152
3753
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
3153
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3754
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3154
3755
  telemetry: this.telemetryPort,
3155
- audit: this.auditPort
3756
+ audit: this.auditPort,
3757
+ tokenizer: this.tokenizer
3156
3758
  };
3157
3759
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
3158
3760
  stream: input.stream === true,
@@ -3200,18 +3802,18 @@ function isSummarizationCallbacks(value) {
3200
3802
  function isGraphSseSink(value) {
3201
3803
  return typeof value === "function";
3202
3804
  }
3203
- function readNonEmptyString2(value) {
3805
+ function readNonEmptyString3(value) {
3204
3806
  if (typeof value !== "string") return void 0;
3205
3807
  const trimmed = value.trim();
3206
3808
  return trimmed.length > 0 ? trimmed : void 0;
3207
3809
  }
3208
3810
  function readGraphAgentLocal(local) {
3209
3811
  const source = local ?? {};
3210
- const answerId = readNonEmptyString2(source.answerId);
3812
+ const answerId = readNonEmptyString3(source.answerId);
3211
3813
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
3212
3814
  return {
3213
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
3214
- turnId: readNonEmptyString2(source.turnId),
3815
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3816
+ turnId: readNonEmptyString3(source.turnId),
3215
3817
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
3216
3818
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
3217
3819
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3976,7 +4578,7 @@ var LlmNode = class {
3976
4578
  function isRecord8(value) {
3977
4579
  return typeof value === "object" && value !== null && !Array.isArray(value);
3978
4580
  }
3979
- function readNonEmptyString3(value) {
4581
+ function readNonEmptyString4(value) {
3980
4582
  if (typeof value !== "string") {
3981
4583
  return void 0;
3982
4584
  }
@@ -3998,7 +4600,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3998
4600
  return void 0;
3999
4601
  }
4000
4602
  if (toolName === "write_report") {
4001
- const report = readNonEmptyString3(data.report);
4603
+ const report = readNonEmptyString4(data.report);
4002
4604
  if (!report) {
4003
4605
  throw new Error("[write_report] \u5DE5\u5177\u8F93\u51FA\u7F3A\u5C11 data.report\uFF08\u5FC5\u987B\u63D0\u4F9B\u5B8C\u6574\u62A5\u544A\u6B63\u6587\uFF09");
4004
4606
  }
@@ -4008,7 +4610,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
4008
4610
  if (data.success !== true) {
4009
4611
  return void 0;
4010
4612
  }
4011
- const finalAnswer = readNonEmptyString3(data.final_answer);
4613
+ const finalAnswer = readNonEmptyString4(data.final_answer);
4012
4614
  if (!finalAnswer) {
4013
4615
  throw new Error("[research_run_writer] \u5DE5\u5177\u8F93\u51FA\u7F3A\u5C11 data.final_answer\uFF08success=true \u65F6\u5FC5\u987B\u63D0\u4F9B\u6700\u7EC8\u62A5\u544A\u6B63\u6587\uFF09");
4014
4616
  }
@@ -4117,11 +4719,11 @@ function buildToolOutputUiMeta(params) {
4117
4719
  }
4118
4720
  async function applyObservationGovernance(params) {
4119
4721
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
4120
- return;
4722
+ return {};
4121
4723
  }
4122
4724
  const policy = resolveToolObservationGovernancePolicy(params.policy);
4123
4725
  if (!policy.enabled) {
4124
- return;
4726
+ return {};
4125
4727
  }
4126
4728
  const truncated = await params.observationPreview.truncateObservation({
4127
4729
  context: params.toolContext,
@@ -4135,13 +4737,37 @@ async function applyObservationGovernance(params) {
4135
4737
  })
4136
4738
  });
4137
4739
  if (!truncated.truncated) {
4138
- return;
4740
+ return {};
4139
4741
  }
4140
4742
  params.parsed["observation"] = truncated.preview;
4141
4743
  const data = params.parsed["data"];
4142
4744
  if (isRecord9(data) && !("tool_output_store" in data)) {
4143
4745
  data["tool_output_store"] = { blob_id: truncated.blob_id };
4144
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;
4145
4771
  }
4146
4772
 
4147
4773
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4558,6 +5184,31 @@ function ensureToolContextRuntimeCapability(params) {
4558
5184
  function getToolContextRuntimeBinding(context) {
4559
5185
  return readBinding(context);
4560
5186
  }
5187
+ function copyToolContextRuntimeCapability(source, target) {
5188
+ const sourceBinding = readBinding(source);
5189
+ if (!sourceBinding) {
5190
+ return void 0;
5191
+ }
5192
+ const existingTargetBinding = readBinding(target);
5193
+ if (existingTargetBinding) {
5194
+ exposeCompatibilitySurface(target, existingTargetBinding);
5195
+ return existingTargetBinding;
5196
+ }
5197
+ const targetBinding = createRuntimeBinding({
5198
+ context: target,
5199
+ persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
5200
+ workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
5201
+ executionMeta: sourceBinding.readExecutionMeta()
5202
+ });
5203
+ Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
5204
+ value: targetBinding,
5205
+ enumerable: false,
5206
+ configurable: true,
5207
+ writable: false
5208
+ });
5209
+ exposeCompatibilitySurface(target, targetBinding);
5210
+ return targetBinding;
5211
+ }
4561
5212
  function readToolContextWorkingHistory(context) {
4562
5213
  if (context.conversationView) {
4563
5214
  return context.conversationView.getWorkingHistoryEvents();
@@ -5084,7 +5735,7 @@ var ToolNode = class {
5084
5735
  parentRunId: context.toolContext.parentRunId
5085
5736
  });
5086
5737
  applyProtocolFuseState(context.local);
5087
- await applyObservationGovernance({
5738
+ const observationGovernance = await applyObservationGovernance({
5088
5739
  parsed: context.parsed,
5089
5740
  toolName: context.toolName,
5090
5741
  toolContext: context.toolContext,
@@ -5111,6 +5762,12 @@ var ToolNode = class {
5111
5762
  runtimeToolOutput,
5112
5763
  execIdempotency: context.exec.idempotency
5113
5764
  });
5765
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5766
+ runtimeToolOutput.metadata = {
5767
+ ...runtimeToolOutput.metadata ?? {},
5768
+ observationTruncation: observationGovernance.observationTruncation
5769
+ };
5770
+ }
5114
5771
  const remainingCalls = context.calls.slice(1);
5115
5772
  context.state.local = buildSuccessLocalState({
5116
5773
  local: context.local,
@@ -5409,12 +6066,12 @@ function asRecord(value) {
5409
6066
  }
5410
6067
  return value;
5411
6068
  }
5412
- function summarizeCheckpoint(conversationId, state, savedAt) {
6069
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
5413
6070
  const local = asRecord(state.local);
5414
6071
  const executorLocal = asRecord(local?.executorLocal);
5415
6072
  const pendingToolCalls = local?.pendingToolCalls;
5416
6073
  return {
5417
- conversationId,
6074
+ checkpointKey,
5418
6075
  schemaVersion: state.schemaVersion ?? 1,
5419
6076
  savedAt,
5420
6077
  currentNode: state.nodeId,
@@ -5433,25 +6090,25 @@ var MemoryCheckpointer = class {
5433
6090
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
5434
6091
  };
5435
6092
  }
5436
- async load(conversationId) {
5437
- const entry = this.store.get(conversationId);
6093
+ async load(checkpointKey) {
6094
+ const entry = this.store.get(checkpointKey);
5438
6095
  return entry ? this.cloneState(entry.state) : null;
5439
6096
  }
5440
- async save(conversationId, state) {
5441
- this.store.set(conversationId, {
6097
+ async save(checkpointKey, state) {
6098
+ this.store.set(checkpointKey, {
5442
6099
  state: this.cloneState(state),
5443
6100
  savedAt: Date.now()
5444
6101
  });
5445
6102
  }
5446
- async clear(conversationId) {
5447
- this.store.delete(conversationId);
6103
+ async clear(checkpointKey) {
6104
+ this.store.delete(checkpointKey);
5448
6105
  }
5449
- async peekMeta(conversationId) {
5450
- const entry = this.store.get(conversationId);
5451
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
6106
+ async peekMeta(checkpointKey) {
6107
+ const entry = this.store.get(checkpointKey);
6108
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
5452
6109
  }
5453
6110
  async list(filter = {}) {
5454
- const summaries = Array.from(this.store.entries()).map(([conversationId, entry]) => summarizeCheckpoint(conversationId, entry.state, entry.savedAt)).filter((summary) => filter.savedAfter === void 0 ? true : summary.savedAt > filter.savedAfter).sort((left, right) => right.savedAt - left.savedAt);
6111
+ const summaries = Array.from(this.store.entries()).map(([checkpointKey, entry]) => summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt)).filter((summary) => filter.savedAfter === void 0 ? true : summary.savedAt > filter.savedAfter).sort((left, right) => right.savedAt - left.savedAt);
5455
6112
  if (filter.limit === void 0) {
5456
6113
  return summaries;
5457
6114
  }
@@ -5523,6 +6180,7 @@ __export(tools_exports, {
5523
6180
  CommonParameterTypes: () => CommonParameterTypes,
5524
6181
  ContextCheckpointTool: () => ContextCheckpointTool,
5525
6182
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
6183
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
5526
6184
  createContextCheckpointTool: () => createContextCheckpointTool,
5527
6185
  ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
5528
6186
  findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
@@ -5716,7 +6374,7 @@ function createContextCheckpointTool(options) {
5716
6374
  function isRecord15(value) {
5717
6375
  return !!value && typeof value === "object" && !Array.isArray(value);
5718
6376
  }
5719
- function readNonEmptyString4(value) {
6377
+ function readNonEmptyString5(value) {
5720
6378
  if (typeof value !== "string") {
5721
6379
  return void 0;
5722
6380
  }
@@ -5736,13 +6394,13 @@ function readToolContextUserQuery(context) {
5736
6394
  if (!context) {
5737
6395
  return void 0;
5738
6396
  }
5739
- return readNonEmptyString4(context["user_query"]);
6397
+ return readNonEmptyString5(context["user_query"]);
5740
6398
  }
5741
6399
  function readToolContextModelId(context) {
5742
6400
  if (!context) {
5743
6401
  return void 0;
5744
6402
  }
5745
- return readNonEmptyString4(context["modelId"]);
6403
+ return readNonEmptyString5(context["modelId"]);
5746
6404
  }
5747
6405
  function readToolContextRunContext(context) {
5748
6406
  if (!context) {
@@ -6944,6 +7602,7 @@ async function callLlmStream(params) {
6944
7602
  const streamAnswerId = generateMessageId();
6945
7603
  let streamChunkSeq = 0;
6946
7604
  let capturedUsage = void 0;
7605
+ let capturedCanonicalUsage = void 0;
6947
7606
  const toolAccumulator = new ToolCallStreamAccumulator([
6948
7607
  "markdown_edit",
6949
7608
  "text_to_image",
@@ -7002,6 +7661,10 @@ async function callLlmStream(params) {
7002
7661
  if (typeof chunk !== "object" || chunk === null) {
7003
7662
  return;
7004
7663
  }
7664
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7665
+ if (parsedCanonicalUsage.success) {
7666
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7667
+ }
7005
7668
  if (chunk.content) {
7006
7669
  emitThoughtComplete(thoughtSegmenter.onBoundary());
7007
7670
  fullResponse += chunk.content;
@@ -7086,6 +7749,12 @@ async function callLlmStream(params) {
7086
7749
  const onUsage = (usage) => {
7087
7750
  capturedUsage = usage;
7088
7751
  };
7752
+ const onCanonicalUsage = (usage) => {
7753
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7754
+ if (parsed.success) {
7755
+ capturedCanonicalUsage = parsed.data;
7756
+ }
7757
+ };
7089
7758
  await aiEngine.chatCompletionStream(
7090
7759
  modelId,
7091
7760
  messages,
@@ -7098,7 +7767,8 @@ async function callLlmStream(params) {
7098
7767
  onError,
7099
7768
  onFinish,
7100
7769
  onThought,
7101
- onUsage
7770
+ onUsage,
7771
+ onCanonicalUsage
7102
7772
  );
7103
7773
  if (streamError) {
7104
7774
  throw streamError;
@@ -7106,12 +7776,13 @@ async function callLlmStream(params) {
7106
7776
  emitThoughtComplete(thoughtSegmenter.finalize());
7107
7777
  const mergedToolCalls = toolAccumulator.getToolCalls();
7108
7778
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
7109
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7779
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
7110
7780
  return {
7111
7781
  content: fullResponse,
7112
7782
  tool_calls: mergedToolCalls,
7113
7783
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
7114
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7784
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7785
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
7115
7786
  };
7116
7787
  }
7117
7788
  return fullResponse;
@@ -7161,6 +7832,10 @@ function tryCloudQuotaFallback({
7161
7832
  }
7162
7833
 
7163
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
+ }
7164
7839
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
7165
7840
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
7166
7841
  return normalizeCompletionResponse(response);
@@ -7171,6 +7846,7 @@ function normalizeCompletionResponse(response) {
7171
7846
  }
7172
7847
  if (isRecord19(response)) {
7173
7848
  const usage = response["usage"];
7849
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7174
7850
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
7175
7851
  if (parsedToolCalls) {
7176
7852
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -7178,7 +7854,8 @@ function normalizeCompletionResponse(response) {
7178
7854
  content: typeof response["content"] === "string" ? response["content"] : "",
7179
7855
  tool_calls: parsedToolCalls,
7180
7856
  reasoning_details: reasoningDetails,
7181
- ...usage !== void 0 ? { usage } : {}
7857
+ ...usage !== void 0 ? { usage } : {},
7858
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7182
7859
  };
7183
7860
  }
7184
7861
  }
@@ -7188,10 +7865,12 @@ function normalizeCompletionResponse(response) {
7188
7865
  if (typeof response === "object") {
7189
7866
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
7190
7867
  const usage = response["usage"];
7868
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7191
7869
  return {
7192
7870
  content: typeof response["content"] === "string" ? response["content"] : "",
7193
7871
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
7194
- ...usage !== void 0 ? { usage } : {}
7872
+ ...usage !== void 0 ? { usage } : {},
7873
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7195
7874
  };
7196
7875
  }
7197
7876
  if (isRecord19(response)) {
@@ -7445,29 +8124,6 @@ var LlmCaller = class {
7445
8124
  }
7446
8125
  };
7447
8126
 
7448
- // src/shared/defaultTokenizerPort.ts
7449
- var DefaultTokenizerPort = class {
7450
- constructor(config = {}) {
7451
- this.config = config;
7452
- }
7453
- estimateText(text, _modelId) {
7454
- return TokenCalculator.estimateTokens(text, {
7455
- encoding: this.config.encoding,
7456
- avgCharsPerToken: this.config.avgCharsPerToken
7457
- });
7458
- }
7459
- estimateMessage(message, _modelId) {
7460
- return TokenCalculator.estimateMessageTokens(message, {
7461
- encoding: this.config.encoding,
7462
- avgCharsPerToken: this.config.avgCharsPerToken,
7463
- toolCallOverhead: this.config.toolCallOverhead
7464
- });
7465
- }
7466
- };
7467
- function createDefaultTokenizerPort(config = {}) {
7468
- return new DefaultTokenizerPort(config);
7469
- }
7470
-
7471
8127
  // src/runtime-kernel/child-runs/index.ts
7472
8128
  var child_runs_exports = {};
7473
8129
  __export(child_runs_exports, {
@@ -7477,7 +8133,6 @@ __export(child_runs_exports, {
7477
8133
 
7478
8134
  // src/runtime-kernel/child-runs/childToolContext.ts
7479
8135
  function createChildRunToolContext(params) {
7480
- const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
7481
8136
  const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
7482
8137
  const childToolContext = {
7483
8138
  ...inheritedContext,
@@ -7489,7 +8144,7 @@ function createChildRunToolContext(params) {
7489
8144
  persistedHistory: params.seedHistory,
7490
8145
  workingHistory: params.seedHistory,
7491
8146
  executionMeta: {
7492
- conversationId: inheritedConversationId ?? params.internalConversationId,
8147
+ conversationId: params.conversationId,
7493
8148
  turnId: params.turnId,
7494
8149
  runId: params.runId,
7495
8150
  parentRunId: params.parentRunId
@@ -7591,6 +8246,8 @@ var FinalAnswerCollector = class {
7591
8246
  this.conversationId = conversationId;
7592
8247
  this.turnId = turnId;
7593
8248
  }
8249
+ conversationId;
8250
+ turnId;
7594
8251
  answerId;
7595
8252
  chunks = [];
7596
8253
  chunkCount = 0;
@@ -7807,7 +8464,7 @@ function readCheckpointHistory(checkpoint) {
7807
8464
  });
7808
8465
  }
7809
8466
  async function recoverChildRunEventsFromCheckpoint(params) {
7810
- const checkpoint = await params.checkpointer.load(params.conversationId);
8467
+ const checkpoint = await params.checkpointer.load(params.checkpointKey);
7811
8468
  const history = readCheckpointHistory(checkpoint);
7812
8469
  if (history.length === 0) {
7813
8470
  return [];
@@ -7815,7 +8472,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
7815
8472
  if (hasSeedHistoryPrefix(history, params.seedHistory)) {
7816
8473
  return history.slice(params.seedHistory.length);
7817
8474
  }
7818
- return history.filter((event) => event.conversation_id === params.internalConversationId);
8475
+ return history.filter((event) => event.conversation_id === params.childConversationId);
7819
8476
  }
7820
8477
 
7821
8478
  // src/runtime-kernel/child-runs/childRunInvoker.ts
@@ -7844,6 +8501,7 @@ var ChildRunInvoker = class {
7844
8501
  agentConfig,
7845
8502
  userMessage,
7846
8503
  parentToolContext,
8504
+ conversationId,
7847
8505
  runId,
7848
8506
  parentRunId,
7849
8507
  subrunTracePublisher,
@@ -7852,12 +8510,18 @@ var ChildRunInvoker = class {
7852
8510
  modelId,
7853
8511
  abortSignal
7854
8512
  } = config;
7855
- const internalConversationId = `internal_${generateMessageId()}`;
8513
+ const internalCheckpointKey = `internal_${generateMessageId()}`;
8514
+ const runtimeConversationId = resolveChildRunConversationId({
8515
+ explicitConversationId: conversationId,
8516
+ parentToolContext,
8517
+ fallbackConversationId: internalCheckpointKey
8518
+ });
7856
8519
  const turnId = `turn_${Date.now()}`;
7857
- const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalConversationId;
8520
+ const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
7858
8521
  const resolvedParentRunId = typeof parentRunId === "string" && parentRunId.trim().length > 0 ? parentRunId.trim() : typeof parentToolContext.runId === "string" && parentToolContext.runId.trim().length > 0 ? parentToolContext.runId.trim() : void 0;
7859
8522
  logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
7860
- conversationId: internalConversationId,
8523
+ conversationId: runtimeConversationId,
8524
+ checkpointKey: internalCheckpointKey,
7861
8525
  maxSteps,
7862
8526
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
7863
8527
  });
@@ -7918,7 +8582,7 @@ var ChildRunInvoker = class {
7918
8582
  const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
7919
8583
  const childToolContext = createChildRunToolContext({
7920
8584
  parentToolContext,
7921
- internalConversationId,
8585
+ conversationId: runtimeConversationId,
7922
8586
  turnId,
7923
8587
  runId: childRunId,
7924
8588
  parentRunId: resolvedParentRunId,
@@ -7927,13 +8591,13 @@ var ChildRunInvoker = class {
7927
8591
  });
7928
8592
  const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
7929
8593
  publisher: subrunTracePublisher,
7930
- conversationId: internalConversationId,
8594
+ conversationId: runtimeConversationId,
7931
8595
  turnId
7932
8596
  }) : void 0;
7933
8597
  const initialLocal = {
7934
8598
  request,
7935
8599
  history: seedHistory,
7936
- conversationId: internalConversationId,
8600
+ conversationId: runtimeConversationId,
7937
8601
  turnId,
7938
8602
  toolContext: childToolContext,
7939
8603
  ...abortSignal ? { signal: abortSignal } : {},
@@ -7941,7 +8605,7 @@ var ChildRunInvoker = class {
7941
8605
  ...subrunSseSink ? { sseSink: subrunSseSink } : {},
7942
8606
  systemPrompt
7943
8607
  };
7944
- await graphExecutor.prime(internalConversationId, initialLocal, "llm");
8608
+ await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
7945
8609
  const allEvents = [];
7946
8610
  let stepCount = 0;
7947
8611
  let finalAnswer;
@@ -7953,7 +8617,7 @@ var ChildRunInvoker = class {
7953
8617
  err.name = "AbortError";
7954
8618
  throw err;
7955
8619
  }
7956
- const result = await graphExecutor.runUntilYield(internalConversationId);
8620
+ const result = await graphExecutor.runUntilYield(internalCheckpointKey);
7957
8621
  appendUniqueEvents(allEvents, result.events);
7958
8622
  stepCount = result.stepCount;
7959
8623
  if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
@@ -7987,8 +8651,8 @@ var ChildRunInvoker = class {
7987
8651
  }
7988
8652
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
7989
8653
  checkpointer,
7990
- conversationId: internalConversationId,
7991
- internalConversationId,
8654
+ checkpointKey: internalCheckpointKey,
8655
+ childConversationId: runtimeConversationId,
7992
8656
  seedHistory
7993
8657
  });
7994
8658
  appendUniqueEvents(allEvents, recoveredEvents);
@@ -8005,7 +8669,7 @@ var ChildRunInvoker = class {
8005
8669
  stack: err.stack
8006
8670
  } : { error: String(err) });
8007
8671
  }
8008
- await checkpointer.clear(internalConversationId);
8672
+ await checkpointer.clear(internalCheckpointKey);
8009
8673
  return {
8010
8674
  success: !error,
8011
8675
  runId: childRunId,
@@ -8018,6 +8682,16 @@ var ChildRunInvoker = class {
8018
8682
  };
8019
8683
  }
8020
8684
  };
8685
+ function readNonEmptyString6(value) {
8686
+ if (typeof value !== "string") {
8687
+ return void 0;
8688
+ }
8689
+ const trimmed = value.trim();
8690
+ return trimmed.length > 0 ? trimmed : void 0;
8691
+ }
8692
+ function resolveChildRunConversationId(params) {
8693
+ return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
8694
+ }
8021
8695
  function resolveChildRunSystemReminderPolicy(agentConfig) {
8022
8696
  const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
8023
8697
  const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
@@ -8208,7 +8882,7 @@ function cloneRunRecord(record) {
8208
8882
  ...record,
8209
8883
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
8210
8884
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
8211
- metadata: record.metadata ? { ...record.metadata } : void 0
8885
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
8212
8886
  };
8213
8887
  }
8214
8888
  function matchesStatus(candidate, filter) {
@@ -8620,7 +9294,7 @@ function isTerminalStatus(status) {
8620
9294
  return status === "completed" || status === "failed" || status === "cancelled";
8621
9295
  }
8622
9296
  function cloneMetadata(metadata) {
8623
- return metadata ? { ...metadata } : void 0;
9297
+ return metadata ? structuredClone(metadata) : void 0;
8624
9298
  }
8625
9299
  function recordToSnapshot(record) {
8626
9300
  return {
@@ -8707,7 +9381,7 @@ var DefaultRunSupervisor = class {
8707
9381
  startedAt,
8708
9382
  updatedAt: startedAt,
8709
9383
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
8710
- metadata: spec.metadata ? { ...spec.metadata } : void 0
9384
+ metadata: cloneMetadata(spec.metadata)
8711
9385
  };
8712
9386
  await this.registryStore.save(record);
8713
9387
  const handle = new DefaultRunHandle({
@@ -8881,12 +9555,13 @@ var DefaultRunSupervisor = class {
8881
9555
  }
8882
9556
  try {
8883
9557
  await handle.markRunning({ currentNode: "detached" });
9558
+ const registeredRecord = await this.registryStore.load(handle.runId);
8884
9559
  const executorOutcome = await this.executor.execute({
8885
9560
  runId: handle.runId,
8886
- parentRunId: spec.parentRunId,
8887
- conversationId: spec.conversationId,
8888
- agentSpec: spec.agentSpec,
8889
- request: spec.request,
9561
+ parentRunId: handle.parentRunId,
9562
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
9563
+ agentSpec: await handle.spec(),
9564
+ request: await handle.request(),
8890
9565
  signal: handle.signal,
8891
9566
  eventBus: spec.eventBus,
8892
9567
  eventStore: spec.eventStore,
@@ -8895,7 +9570,7 @@ var DefaultRunSupervisor = class {
8895
9570
  contextFences: spec.contextFences,
8896
9571
  wakeSource: spec.wakeSource,
8897
9572
  ephemeral: spec.ephemeral,
8898
- metadata: spec.metadata
9573
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
8899
9574
  });
8900
9575
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
8901
9576
  this.notifyTerminalWaiters(outcome);
@@ -8959,10 +9634,14 @@ var DefaultRunSupervisor = class {
8959
9634
  await this.registryStore.save(record);
8960
9635
  }
8961
9636
  const completedAt = executorOutcome?.completedAt ?? this.now();
9637
+ const fallbackMeta = record ? void 0 : await handle.meta();
8962
9638
  const outcome = recordToTerminalOutcome(record ?? {
8963
9639
  runId: handle.runId,
8964
9640
  parentRunId: handle.parentRunId,
8965
- status: executorOutcome?.status ?? "completed"}, completedAt);
9641
+ conversationId: fallbackMeta?.conversationId ?? "",
9642
+ agentSpecId: fallbackMeta?.agentSpecId,
9643
+ status: executorOutcome?.status ?? "completed",
9644
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
8966
9645
  const nextOutcome = {
8967
9646
  ...outcome,
8968
9647
  metadata: {
@@ -9054,6 +9733,7 @@ __export(telemetry_exports, {
9054
9733
  var TELEMETRY_EVENT_KINDS = [
9055
9734
  "llm_call",
9056
9735
  "tool_call",
9736
+ "context_build",
9057
9737
  "graph_node",
9058
9738
  "run_lifecycle"
9059
9739
  ];
@@ -9190,6 +9870,7 @@ function createGraphLoopHarness(options) {
9190
9870
  };
9191
9871
  return {
9192
9872
  async run() {
9873
+ const checkpointKey = options.conversationId;
9193
9874
  const executor = createDefaultGraphExecutor({
9194
9875
  llmNode: options.createLlmNode({
9195
9876
  llmCaller: options.llmCaller,
@@ -9218,8 +9899,8 @@ function createGraphLoopHarness(options) {
9218
9899
  signal: options.signal ?? options.toolContext.abortSignal,
9219
9900
  executorLocal
9220
9901
  };
9221
- await executor.prime(options.conversationId, local, "user");
9222
- const result = await executor.runUntilYield(options.conversationId);
9902
+ await executor.prime(checkpointKey, local, "user");
9903
+ const result = await executor.runUntilYield(checkpointKey);
9223
9904
  return {
9224
9905
  checkpointNodeId: result.checkpoint.nodeId,
9225
9906
  stepCount: result.stepCount
@@ -9562,6 +10243,7 @@ async function emitRunEvent(event, sink) {
9562
10243
  async function runAgent(agent, options) {
9563
10244
  const modelId = resolveModelId(agent, options);
9564
10245
  const conversationId = options.conversationId ?? `conv_${Date.now()}`;
10246
+ const checkpointKey = conversationId;
9565
10247
  const runId = options.runId ?? generateRunId();
9566
10248
  const turnId = runId;
9567
10249
  const costCollector = new QuickstartRunCostCollector();
@@ -9616,7 +10298,7 @@ async function runAgent(agent, options) {
9616
10298
  };
9617
10299
  await handle.markRunning({ currentNode: "user" });
9618
10300
  try {
9619
- await executor.prime(conversationId, {
10301
+ await executor.prime(checkpointKey, {
9620
10302
  conversationId,
9621
10303
  turnId,
9622
10304
  request: {
@@ -9641,7 +10323,7 @@ async function runAgent(agent, options) {
9641
10323
  return void 0;
9642
10324
  }
9643
10325
  });
9644
- const result = await executor.runUntilYield(conversationId);
10326
+ const result = await executor.runUntilYield(checkpointKey);
9645
10327
  runtimeEvents.push(...result.events);
9646
10328
  for (const event of result.events) {
9647
10329
  if (event.type === "final_answer_chunk") continue;