@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.js CHANGED
@@ -45,7 +45,11 @@ __export(runtime_kernel_exports, {
45
45
  ToolNode: () => ToolNode,
46
46
  UserNode: () => UserNode,
47
47
  WaitUserNode: () => WaitUserNode,
48
+ addLedgerAggregate: () => addLedgerAggregate,
49
+ addUsageTotals: () => addUsageTotals,
48
50
  agentHasToolTrigger: () => agentHasToolTrigger,
51
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
52
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
49
53
  appendStreamingProviderReasoningDetails: () => appendStreamingProviderReasoningDetails,
50
54
  applySystemReminders: () => applySystemReminders,
51
55
  audit: () => audit_exports,
@@ -54,20 +58,25 @@ __export(runtime_kernel_exports, {
54
58
  childRuns: () => child_runs_exports,
55
59
  compactProviderReasoningDetails: () => compactProviderReasoningDetails,
56
60
  compactReasoningDetailsInValue: () => compactReasoningDetailsInValue,
61
+ computeCost: () => computeCost,
57
62
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
58
63
  consoleAudit: () => consoleAudit,
59
64
  contextBudgetWarningTemplate: () => contextBudgetWarningTemplate,
65
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
60
66
  countToolCallsInCurrentRequest: () => countToolCallsInCurrentRequest,
61
67
  createCompositeAudit: () => createCompositeAudit,
62
68
  createConsoleAudit: () => createConsoleAudit,
63
69
  createContextCheckpointTool: () => createContextCheckpointTool,
70
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
64
71
  createDefaultGraphExecutor: () => createDefaultGraphExecutor,
65
72
  createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
66
73
  createDefaultTokenizerPort: () => createDefaultTokenizerPort,
67
74
  createEventStoreAudit: () => createEventStoreAudit,
68
75
  createFileAudit: () => createFileAudit,
69
76
  createGraphLoopHarness: () => createGraphLoopHarness,
77
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
70
78
  createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
79
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
71
80
  createSystemReminderRules: () => createSystemReminderRules,
72
81
  defaultPolicyEngine: () => defaultPolicyEngine,
73
82
  defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
@@ -104,6 +113,7 @@ __export(runtime_kernel_exports, {
104
113
  systemReminder: () => system_reminder_exports,
105
114
  telemetry: () => telemetry_exports,
106
115
  toDisplayStep: () => toDisplayStep,
116
+ tokenAccounting: () => token_accounting_exports,
107
117
  toolCallStreakTemplate: () => toolCallStreakTemplate,
108
118
  toolCallStreakTrigger: () => toolCallStreakTrigger,
109
119
  tools: () => tools_exports
@@ -138,6 +148,7 @@ var Logger = class {
138
148
  constructor(moduleName) {
139
149
  this.moduleName = moduleName;
140
150
  }
151
+ moduleName;
141
152
  debug(message, data) {
142
153
  this.log(0 /* DEBUG */, "debug", message, data);
143
154
  }
@@ -244,14 +255,23 @@ __export(contracts_exports, {
244
255
  AuditScope: () => AuditScope,
245
256
  BaseEvent: () => BaseEvent,
246
257
  BaseSSEEvent: () => BaseSSEEvent,
258
+ CanonicalLlmUsage: () => CanonicalLlmUsage,
259
+ ContextBuildTokenEstimate: () => ContextBuildTokenEstimate,
260
+ ContextComponentTokenLedgerEntry: () => ContextComponentTokenLedgerEntry,
261
+ ContextTokenComponent: () => ContextTokenComponent,
262
+ ContextTokenComponentKind: () => ContextTokenComponentKind,
263
+ CostBreakdown: () => CostBreakdown,
247
264
  DEFAULT_MAX_STEPS: () => DEFAULT_MAX_STEPS,
248
265
  EventEnvelope: () => EventEnvelope,
249
266
  ExecutionTraceContext: () => ExecutionTraceContext,
250
267
  HistorySummaryMeta: () => HistorySummaryMeta,
251
268
  ImageInfoMeta: () => ImageInfoMeta,
269
+ LlmUsageTokenLedgerEntry: () => LlmUsageTokenLedgerEntry,
270
+ ObservationTruncationMeta: () => ObservationTruncationMeta,
252
271
  PersistentMetadata: () => PersistentMetadata,
253
272
  ProviderReasoningDetails: () => ProviderReasoningDetails,
254
273
  ProviderReasoningDetailsPayload: () => ProviderReasoningDetailsPayload,
274
+ RunTokenUsageAggregate: () => RunTokenUsageAggregate,
255
275
  RuntimeEvent: () => RuntimeEvent,
256
276
  SSEErrorEvent: () => SSEErrorEvent,
257
277
  SSEEvent: () => SSEEvent,
@@ -274,6 +294,18 @@ __export(contracts_exports, {
274
294
  Status: () => Status,
275
295
  SystemMessage: () => SystemMessage,
276
296
  TaskTrackingMeta: () => TaskTrackingMeta,
297
+ TokenCostComponent: () => TokenCostComponent,
298
+ TokenCountConfidence: () => TokenCountConfidence,
299
+ TokenCountSource: () => TokenCountSource,
300
+ TokenLedgerAggregate: () => TokenLedgerAggregate,
301
+ TokenLedgerEntry: () => TokenLedgerEntry,
302
+ TokenLedgerEntryKind: () => TokenLedgerEntryKind,
303
+ TokenPricing: () => TokenPricing,
304
+ TokenRoute: () => TokenRoute,
305
+ TokenRouteCapabilities: () => TokenRouteCapabilities,
306
+ TokenUsageCalibrationSample: () => TokenUsageCalibrationSample,
307
+ TokenUsageCalibrationTrace: () => TokenUsageCalibrationTrace,
308
+ TokenUsageTotals: () => TokenUsageTotals,
277
309
  ToolBindingSpec: () => ToolBindingSpec,
278
310
  ToolCallDecisionPayload: () => ToolCallDecisionPayload,
279
311
  ToolCallExtraContent: () => ToolCallExtraContent,
@@ -359,6 +391,12 @@ var ToolOutputMeta = z.object({
359
391
  args: z.record(z.unknown()).optional(),
360
392
  tool_call_id: z.string()
361
393
  });
394
+ var ObservationTruncationMeta = z.object({
395
+ originalChars: z.number().int().nonnegative(),
396
+ previewChars: z.number().int().nonnegative(),
397
+ originalLines: z.number().int().nonnegative().optional(),
398
+ previewLines: z.number().int().nonnegative().optional()
399
+ });
362
400
  var ImageInfoMeta = z.object({
363
401
  url: z.string().optional(),
364
402
  width: z.number().int().positive().optional(),
@@ -390,6 +428,7 @@ var PersistentMetadata = z.object({
390
428
  tool_name: z.string().optional(),
391
429
  args: z.record(z.unknown()).optional(),
392
430
  tool_call_id: z.string().optional(),
431
+ observationTruncation: ObservationTruncationMeta.optional(),
393
432
  raw_output: z.string().optional(),
394
433
  image_info: ImageInfoMeta.optional(),
395
434
  taskType: z.string().optional(),
@@ -561,6 +600,7 @@ var AgentSpecBudgetPolicy = z.object({
561
600
  });
562
601
  var AgentSpecToolHistoryPolicy = z.object({
563
602
  strategy: z.enum(["per-pair", "per-run", "none"]).optional(),
603
+ retentionMode: z.enum(["drop", "compress"]).optional(),
564
604
  keepLatestToolPairs: z.number().int().nonnegative().optional(),
565
605
  keepLatestRuns: z.number().int().nonnegative().optional(),
566
606
  maxInteractionGroups: z.number().int().nonnegative().optional(),
@@ -613,7 +653,17 @@ var AgentSpecReasoningRetentionPolicy = z.object({
613
653
  var AgentSpecTokenEstimationPolicy = z.object({
614
654
  encoding: z.string().min(1).optional(),
615
655
  avgCharsPerToken: z.number().positive().optional(),
616
- toolCallOverhead: z.number().int().nonnegative().optional()
656
+ toolCallOverhead: z.number().int().nonnegative().optional(),
657
+ calibration: z.object({
658
+ enabled: z.boolean().optional(),
659
+ minSamples: z.number().int().positive().optional(),
660
+ minCoefficient: z.number().positive().optional(),
661
+ maxCoefficient: z.number().positive().optional()
662
+ }).optional(),
663
+ remoteCount: z.object({
664
+ enabled: z.boolean().optional(),
665
+ failureBehavior: z.enum(["use-local-estimate", "fail-fast"]).optional()
666
+ }).optional()
617
667
  });
618
668
  var SYSTEM_REMINDER_BUILTIN_TRIGGER_KINDS = [
619
669
  "phase-equals",
@@ -683,12 +733,13 @@ var AgentSpecContextPolicy = z.object({
683
733
  var DEFAULT_CONTEXT_POLICY = {
684
734
  profileId: "agent",
685
735
  budget: {
686
- maxTokens: 12e4,
736
+ maxTokens: 232e3,
687
737
  reservedForResponse: 2400,
688
738
  workingMemoryBudgetPercentage: 0.7
689
739
  },
690
740
  toolHistory: {
691
741
  strategy: "per-run",
742
+ retentionMode: "drop",
692
743
  keepLatestToolPairs: 2,
693
744
  keepLatestRuns: 1,
694
745
  maxInteractionGroups: 12,
@@ -1534,12 +1585,206 @@ var createSSEHistorySummaryEvent = (id, conversationId, turnId, summaryId, conte
1534
1585
  summary_seq: summarySeq,
1535
1586
  ...options
1536
1587
  });
1588
+ var TokenCountSource = z.enum([
1589
+ "local-estimate",
1590
+ "provider-preflight-count",
1591
+ "provider-response-usage",
1592
+ "host-supplied",
1593
+ "test-fixture"
1594
+ ]);
1595
+ var TokenCountConfidence = z.enum([
1596
+ "estimate",
1597
+ "provider-estimate",
1598
+ "actual"
1599
+ ]);
1600
+ var TokenRouteCapabilities = z.object({
1601
+ supportsRemoteTokenCount: z.boolean().optional(),
1602
+ supportsResponseUsage: z.boolean().optional(),
1603
+ supportsImageInput: z.boolean().optional(),
1604
+ supportsCachedInputBilling: z.boolean().optional(),
1605
+ supportsReasoningTokens: z.boolean().optional()
1606
+ });
1607
+ var TokenRoute = z.object({
1608
+ providerId: z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1609
+ baseURL: z.string().optional().describe("\u4E2D\u8F6C\u5E73\u53F0\u6216\u79C1\u6709 endpoint\uFF1B\u7528\u4E8E\u533A\u5206\u540C\u540D\u6A21\u578B\u7684\u4E0D\u540C route"),
1610
+ modelId: z.string().describe("host \u4FA7\u6A21\u578B id"),
1611
+ providerModelId: z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1612
+ capabilities: TokenRouteCapabilities.optional()
1613
+ });
1614
+ var tokenCount = z.number().int().nonnegative();
1615
+ var CanonicalLlmUsage = z.object({
1616
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1617
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1618
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1619
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1620
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1621
+ totalTokens: tokenCount.optional().describe("provider \u62A5\u544A\u7684\u603B\u91CF\uFF1B\u53EF\u7F3A\u5931\uFF0C\u4E14\u4E0D\u4FDD\u8BC1\u7B49\u4E8E\u5404\u9879\u4E4B\u548C"),
1622
+ source: TokenCountSource,
1623
+ confidence: TokenCountConfidence,
1624
+ rawUsage: z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1625
+ });
1626
+ var tokenCount2 = z.number().int().nonnegative();
1627
+ var tokenPrice = z.number().finite().nonnegative();
1628
+ var TokenLedgerEntryKind = z.enum([
1629
+ "llm-usage",
1630
+ "context-component"
1631
+ ]);
1632
+ var ContextTokenComponentKind = z.enum([
1633
+ "system",
1634
+ "user",
1635
+ "assistant",
1636
+ "tool",
1637
+ "context-injection",
1638
+ "history-summary",
1639
+ "working-memory",
1640
+ "fence",
1641
+ "system-reminder",
1642
+ "other"
1643
+ ]);
1644
+ var TokenUsageTotals = z.object({
1645
+ inputTokens: tokenCount2,
1646
+ outputTokens: tokenCount2,
1647
+ reasoningTokens: tokenCount2.optional(),
1648
+ cacheReadTokens: tokenCount2.optional(),
1649
+ cacheWriteTokens: tokenCount2.optional(),
1650
+ totalTokens: tokenCount2.optional(),
1651
+ usageCount: z.number().int().nonnegative()
1652
+ });
1653
+ var ContextTokenComponent = z.object({
1654
+ componentId: z.string().min(1),
1655
+ kind: ContextTokenComponentKind,
1656
+ tokens: tokenCount2,
1657
+ source: TokenCountSource,
1658
+ confidence: TokenCountConfidence,
1659
+ label: z.string().optional(),
1660
+ messageId: z.string().optional(),
1661
+ role: z.string().optional(),
1662
+ action: z.string().optional(),
1663
+ kept: z.boolean().optional(),
1664
+ truncatedAtExecution: z.boolean().optional(),
1665
+ originalTokensEstimate: tokenCount2.optional(),
1666
+ droppedTokensEstimate: tokenCount2.optional()
1667
+ });
1668
+ var TokenLedgerEntryBase = z.object({
1669
+ id: z.string().min(1),
1670
+ runId: z.string().optional(),
1671
+ parentRunId: z.string().optional(),
1672
+ conversationId: z.string().optional(),
1673
+ turnId: z.string().optional(),
1674
+ stepId: z.string().optional(),
1675
+ route: TokenRoute.optional(),
1676
+ createdAt: z.number().int().nonnegative().optional()
1677
+ });
1678
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1679
+ kind: z.literal("llm-usage"),
1680
+ modelId: z.string().optional(),
1681
+ usage: CanonicalLlmUsage
1682
+ });
1683
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1684
+ kind: z.literal("context-component"),
1685
+ components: z.array(ContextTokenComponent),
1686
+ totalTokens: tokenCount2
1687
+ });
1688
+ var TokenLedgerEntry = z.discriminatedUnion("kind", [
1689
+ LlmUsageTokenLedgerEntry,
1690
+ ContextComponentTokenLedgerEntry
1691
+ ]);
1692
+ var TokenLedgerAggregate = z.object({
1693
+ llmUsage: TokenUsageTotals.optional(),
1694
+ contextTokens: tokenCount2,
1695
+ entryCount: z.number().int().nonnegative(),
1696
+ llmCallCount: z.number().int().nonnegative(),
1697
+ contextComponentCount: z.number().int().nonnegative()
1698
+ });
1699
+ var RunTokenUsageAggregate = z.object({
1700
+ /**
1701
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1702
+ */
1703
+ own: TokenLedgerAggregate,
1704
+ children: TokenLedgerAggregate.optional()
1705
+ });
1706
+ var TokenCostComponent = z.enum([
1707
+ "input",
1708
+ "output",
1709
+ "reasoning",
1710
+ "cacheRead",
1711
+ "cacheWrite"
1712
+ ]);
1713
+ var TokenPricing = z.object({
1714
+ currency: z.string().min(1),
1715
+ unit: z.literal("per_1m_tokens"),
1716
+ input: tokenPrice.optional(),
1717
+ output: tokenPrice.optional(),
1718
+ reasoning: tokenPrice.optional(),
1719
+ cacheRead: tokenPrice.optional(),
1720
+ cacheWrite: tokenPrice.optional()
1721
+ });
1722
+ var CostBreakdown = z.object({
1723
+ status: z.enum(["computed", "unknown"]),
1724
+ currency: z.string().optional(),
1725
+ inputCost: tokenPrice.optional(),
1726
+ outputCost: tokenPrice.optional(),
1727
+ reasoningCost: tokenPrice.optional(),
1728
+ cacheReadCost: tokenPrice.optional(),
1729
+ cacheWriteCost: tokenPrice.optional(),
1730
+ totalCost: tokenPrice.optional(),
1731
+ missingPriceComponents: z.array(TokenCostComponent).optional()
1732
+ });
1733
+ var tokenCount3 = z.number().int().nonnegative();
1734
+ var actualCalibrationSource = z.enum([
1735
+ "provider-response-usage",
1736
+ "host-supplied",
1737
+ "test-fixture"
1738
+ ]);
1739
+ var TokenUsageCalibrationSample = z.object({
1740
+ route: TokenRoute,
1741
+ localEstimateTokens: tokenCount3,
1742
+ actualInputTokens: tokenCount3,
1743
+ source: actualCalibrationSource,
1744
+ confidence: z.literal("actual"),
1745
+ observedAt: z.number().int().nonnegative().optional(),
1746
+ runId: z.string().optional(),
1747
+ ledgerEntryId: z.string().optional()
1748
+ });
1749
+ var TokenUsageCalibrationTrace = z.object({
1750
+ enabled: z.boolean(),
1751
+ applied: z.boolean(),
1752
+ route: TokenRoute.optional(),
1753
+ sampleCount: z.number().int().nonnegative(),
1754
+ coefficient: z.number().positive().optional(),
1755
+ minSamples: z.number().int().positive().optional(),
1756
+ minCoefficient: z.number().positive().optional(),
1757
+ maxCoefficient: z.number().positive().optional(),
1758
+ localEstimateTokens: tokenCount3.optional(),
1759
+ calibratedEstimateTokens: tokenCount3.optional(),
1760
+ deltaTokens: z.number().int().optional(),
1761
+ sampleLedgerEntryIds: z.array(z.string()).optional()
1762
+ });
1763
+ var ContextBuildTokenEstimate = z.object({
1764
+ route: TokenRoute.optional(),
1765
+ localEstimateTokens: tokenCount3,
1766
+ calibratedEstimateTokens: tokenCount3,
1767
+ finalTokens: tokenCount3,
1768
+ source: z.literal("local-estimate"),
1769
+ confidence: z.literal("estimate")
1770
+ });
1537
1771
 
1538
1772
  // src/runtime-kernel/graph-engine/engine.ts
1539
1773
  var logger = new Logger("GraphExecutor");
1540
1774
  function asLocalRecord(local) {
1541
1775
  return local && typeof local === "object" ? { ...local } : {};
1542
1776
  }
1777
+ function readNonEmptyString(value) {
1778
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1779
+ }
1780
+ function readRuntimeConversationId(state) {
1781
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1782
+ return readNonEmptyString(local?.conversationId);
1783
+ }
1784
+ function readRuntimeTurnId(state) {
1785
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1786
+ return readNonEmptyString(local?.turnId);
1787
+ }
1543
1788
  var GraphExecutor = class {
1544
1789
  constructor(checkpointer, config = {}) {
1545
1790
  this.checkpointer = checkpointer;
@@ -1549,6 +1794,7 @@ var GraphExecutor = class {
1549
1794
  };
1550
1795
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1551
1796
  }
1797
+ checkpointer;
1552
1798
  nodes = /* @__PURE__ */ new Map();
1553
1799
  ephemeralLocals = /* @__PURE__ */ new Map();
1554
1800
  config;
@@ -1556,8 +1802,8 @@ var GraphExecutor = class {
1556
1802
  registerNode(node) {
1557
1803
  this.nodes.set(node.id, node);
1558
1804
  }
1559
- async peekCheckpoint(conversationId) {
1560
- return await this.checkpointer.load(conversationId);
1805
+ async peekCheckpoint(checkpointKey) {
1806
+ return await this.checkpointer.load(checkpointKey);
1561
1807
  }
1562
1808
  sanitize(state) {
1563
1809
  const local = asLocalRecord(state.local);
@@ -1569,8 +1815,8 @@ var GraphExecutor = class {
1569
1815
  local
1570
1816
  };
1571
1817
  }
1572
- async prime(conversationId, local, nodeId = "user") {
1573
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1818
+ async prime(checkpointKey, local, nodeId = "user") {
1819
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1574
1820
  const localSansMemory = { ...local || {} };
1575
1821
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1576
1822
  const state = {
@@ -1578,10 +1824,10 @@ var GraphExecutor = class {
1578
1824
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1579
1825
  local: localSansMemory
1580
1826
  };
1581
- await this.checkpointer.save(conversationId, state);
1827
+ await this.checkpointer.save(checkpointKey, state);
1582
1828
  }
1583
- async setNode(conversationId, nodeId, localPatch) {
1584
- const current = await this.checkpointer.load(conversationId) || {
1829
+ async setNode(checkpointKey, nodeId, localPatch) {
1830
+ const current = await this.checkpointer.load(checkpointKey) || {
1585
1831
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1586
1832
  local: {}
1587
1833
  };
@@ -1592,19 +1838,46 @@ var GraphExecutor = class {
1592
1838
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1593
1839
  local: mergedLocal
1594
1840
  };
1595
- await this.checkpointer.save(conversationId, next);
1841
+ await this.checkpointer.save(checkpointKey, next);
1596
1842
  }
1597
- async runUntilYield(conversationId) {
1843
+ async runUntilYield(checkpointKey) {
1598
1844
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1599
1845
  let lifecyclePhase = "completed";
1846
+ let initialState = null;
1847
+ try {
1848
+ initialState = await this.loadInitialState(checkpointKey);
1849
+ } catch (err) {
1850
+ lifecyclePhase = "failed";
1851
+ this.telemetryPort.emit({
1852
+ kind: "run_lifecycle",
1853
+ runId,
1854
+ phase: "spawned",
1855
+ scope: {}
1856
+ });
1857
+ this.telemetryPort.emit({
1858
+ kind: "run_lifecycle",
1859
+ runId,
1860
+ phase: lifecyclePhase,
1861
+ scope: {}
1862
+ });
1863
+ throw err;
1864
+ }
1865
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1866
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1600
1867
  this.telemetryPort.emit({
1601
1868
  kind: "run_lifecycle",
1602
1869
  runId,
1603
1870
  phase: "spawned",
1604
- scope: { conversationId: conversationId || void 0 }
1871
+ scope: {
1872
+ conversationId: lifecycleConversationId,
1873
+ turnId: lifecycleTurnId
1874
+ }
1605
1875
  });
1606
1876
  try {
1607
- return await this.runUntilYieldInternal(conversationId);
1877
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1878
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1879
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1880
+ return result;
1608
1881
  } catch (err) {
1609
1882
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1610
1883
  throw err;
@@ -1613,17 +1886,23 @@ var GraphExecutor = class {
1613
1886
  kind: "run_lifecycle",
1614
1887
  runId,
1615
1888
  phase: lifecyclePhase,
1616
- scope: { conversationId: conversationId || void 0 }
1889
+ scope: {
1890
+ conversationId: lifecycleConversationId,
1891
+ turnId: lifecycleTurnId
1892
+ }
1617
1893
  });
1618
1894
  }
1619
1895
  }
1620
- async runUntilYieldInternal(conversationId) {
1621
- let state = await this.checkpointer.load(conversationId) || {
1896
+ async loadInitialState(checkpointKey) {
1897
+ return await this.checkpointer.load(checkpointKey) || {
1622
1898
  nodeId: "user",
1623
1899
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1624
1900
  local: {}
1625
1901
  };
1626
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1902
+ }
1903
+ async runUntilYieldInternal(checkpointKey, initialState) {
1904
+ let state = initialState;
1905
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1627
1906
  state = {
1628
1907
  ...state,
1629
1908
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1652,7 +1931,7 @@ var GraphExecutor = class {
1652
1931
  const signalRaw = state.local?.signal;
1653
1932
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1654
1933
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1655
- this.ephemeralLocals.delete(conversationId);
1934
+ this.ephemeralLocals.delete(checkpointKey);
1656
1935
  throwAbortError();
1657
1936
  }
1658
1937
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1700,8 +1979,8 @@ var GraphExecutor = class {
1700
1979
  checkpointCount
1701
1980
  });
1702
1981
  const cp2 = this.sanitize(state);
1703
- await this.checkpointer.save(conversationId, cp2);
1704
- this.ephemeralLocals.delete(conversationId);
1982
+ await this.checkpointer.save(checkpointKey, cp2);
1983
+ this.ephemeralLocals.delete(checkpointKey);
1705
1984
  return { events: allEvents, checkpoint: cp2, stepCount };
1706
1985
  }
1707
1986
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1712,18 +1991,18 @@ var GraphExecutor = class {
1712
1991
  });
1713
1992
  const nodeRunStartedAt = Date.now();
1714
1993
  const nodeIdForTelemetry = state.nodeId;
1994
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1715
1995
  let result;
1716
1996
  try {
1717
1997
  result = await node.run(state);
1718
1998
  } finally {
1719
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1720
1999
  this.telemetryPort.emit({
1721
2000
  kind: "graph_node",
1722
2001
  nodeId: nodeIdForTelemetry,
1723
2002
  durationMs: Date.now() - nodeRunStartedAt,
1724
2003
  scope: {
1725
- conversationId: conversationId || void 0,
1726
- turnId: turnIdForTelemetry
2004
+ conversationId: conversationIdForTelemetry,
2005
+ turnId: readRuntimeTurnId(state)
1727
2006
  }
1728
2007
  });
1729
2008
  }
@@ -1762,7 +2041,7 @@ var GraphExecutor = class {
1762
2041
  });
1763
2042
  state = { ...state, nodeId: nextNodeId };
1764
2043
  const cp2 = this.sanitize(state);
1765
- await this.checkpointer.save(conversationId, cp2);
2044
+ await this.checkpointer.save(checkpointKey, cp2);
1766
2045
  continue;
1767
2046
  }
1768
2047
  if (result.kind === "yield") {
@@ -1773,7 +2052,7 @@ var GraphExecutor = class {
1773
2052
  checkpointCount
1774
2053
  });
1775
2054
  const cp2 = this.sanitize(state);
1776
- await this.checkpointer.save(conversationId, cp2);
2055
+ await this.checkpointer.save(checkpointKey, cp2);
1777
2056
  return { events: allEvents, checkpoint: cp2, stepCount };
1778
2057
  }
1779
2058
  if (result.kind === "pause") {
@@ -1784,7 +2063,7 @@ var GraphExecutor = class {
1784
2063
  checkpointCount
1785
2064
  });
1786
2065
  const cp2 = this.sanitize(state);
1787
- await this.checkpointer.save(conversationId, cp2);
2066
+ await this.checkpointer.save(checkpointKey, cp2);
1788
2067
  return { events: allEvents, checkpoint: cp2, stepCount };
1789
2068
  }
1790
2069
  }
@@ -1795,8 +2074,8 @@ var GraphExecutor = class {
1795
2074
  checkpointCount
1796
2075
  });
1797
2076
  const cp = this.sanitize(state);
1798
- await this.checkpointer.save(conversationId, cp);
1799
- this.ephemeralLocals.delete(conversationId);
2077
+ await this.checkpointer.save(checkpointKey, cp);
2078
+ this.ephemeralLocals.delete(checkpointKey);
1800
2079
  return { events: allEvents, checkpoint: cp, stepCount };
1801
2080
  }
1802
2081
  };
@@ -1892,6 +2171,190 @@ var noopAudit = {
1892
2171
  flush() {
1893
2172
  }
1894
2173
  };
2174
+ var TokenCalculator = class {
2175
+ static BYTES_PER_TOKEN_LATIN = 4;
2176
+ static BYTES_PER_TOKEN_CJK = 3;
2177
+ static OVERHEAD_PER_MESSAGE = 5;
2178
+ static OVERHEAD_PER_TOOL_CALL = 10;
2179
+ static encoderCache = /* @__PURE__ */ new Map();
2180
+ static DEFAULT_ENCODING = "cl100k_base";
2181
+ static SUPPORTED_ENCODINGS = [
2182
+ "gpt2",
2183
+ "r50k_base",
2184
+ "p50k_base",
2185
+ "p50k_edit",
2186
+ "cl100k_base",
2187
+ "o200k_base"
2188
+ ];
2189
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
2190
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
2191
+ if (this.isSupportedEncodingName(normalized)) {
2192
+ return normalized;
2193
+ }
2194
+ if (normalized.includes("deepseek")) {
2195
+ return "cl100k_base";
2196
+ }
2197
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
2198
+ return "o200k_base";
2199
+ }
2200
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
2201
+ return "cl100k_base";
2202
+ }
2203
+ return this.DEFAULT_ENCODING;
2204
+ }
2205
+ static isSupportedEncodingName(value) {
2206
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
2207
+ }
2208
+ static getEncoder(modelIdentifierOrEncoding) {
2209
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
2210
+ const cached = this.encoderCache.get(encodingName);
2211
+ if (cached) {
2212
+ return cached;
2213
+ }
2214
+ const encoder = get_encoding(encodingName);
2215
+ this.encoderCache.set(encodingName, encoder);
2216
+ return encoder;
2217
+ }
2218
+ static estimateTokensRough(text, _modelIdentifier) {
2219
+ if (!text) return 0;
2220
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
2221
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
2222
+ const byteLength = new TextEncoder().encode(text).length;
2223
+ return Math.ceil(byteLength / ratio);
2224
+ }
2225
+ static estimateTokens(text, options = {}) {
2226
+ if (!text) return 0;
2227
+ if (options.encoding) {
2228
+ try {
2229
+ return this.estimateTokensPrecise(text, options.encoding);
2230
+ } catch {
2231
+ }
2232
+ }
2233
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
2234
+ return Math.ceil(text.length / avgCharsPerToken);
2235
+ }
2236
+ static estimateTokensPrecise(text, modelIdentifier) {
2237
+ if (!text) return 0;
2238
+ const encoder = this.getEncoder(modelIdentifier);
2239
+ return encoder.encode(text).length;
2240
+ }
2241
+ static estimateMessageTokens(message, options = {}) {
2242
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
2243
+ if (message.content) {
2244
+ totalTokens += this.estimateTokens(String(message.content), options);
2245
+ }
2246
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
2247
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
2248
+ for (const toolCall of toolCalls) {
2249
+ totalTokens += toolCallOverhead;
2250
+ const fn = toolCall["function"];
2251
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
2252
+ const fnRecord = fn;
2253
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
2254
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
2255
+ }
2256
+ }
2257
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
2258
+ if (toolCallId) {
2259
+ totalTokens += this.estimateTokens(toolCallId, options);
2260
+ }
2261
+ return totalTokens;
2262
+ }
2263
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
2264
+ return this.estimateMessageTokens(message, {
2265
+ encoding: modelIdentifier,
2266
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
2267
+ });
2268
+ }
2269
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
2270
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2271
+ }
2272
+ static extractToolCallsForTokenEstimate(message) {
2273
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
2274
+ if (Array.isArray(direct)) return direct;
2275
+ const metadata = "metadata" in message ? message.metadata : void 0;
2276
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
2277
+ const metadataRecord = metadata;
2278
+ const metadataToolCalls = metadataRecord["tool_calls"];
2279
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2280
+ }
2281
+ static extractToolCallIdForTokenEstimate(message) {
2282
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
2283
+ return message.tool_call_id;
2284
+ }
2285
+ const metadata = "metadata" in message ? message.metadata : void 0;
2286
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
2287
+ const metadataRecord = metadata;
2288
+ const toolCallId = metadataRecord["tool_call_id"];
2289
+ return typeof toolCallId === "string" ? toolCallId : void 0;
2290
+ }
2291
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
2292
+ if (!text || maxTokens <= 0) return "";
2293
+ const encoder = this.getEncoder(modelIdentifier);
2294
+ const tokens = encoder.encode(text);
2295
+ if (tokens.length <= maxTokens) {
2296
+ return text;
2297
+ }
2298
+ let truncatedTokens;
2299
+ const ellipsis = "...";
2300
+ switch (strategy) {
2301
+ case "start":
2302
+ truncatedTokens = tokens.slice(0, maxTokens);
2303
+ return encoder.decode(truncatedTokens) + ellipsis;
2304
+ case "end":
2305
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
2306
+ return ellipsis + encoder.decode(truncatedTokens);
2307
+ case "middle": {
2308
+ const half = Math.floor(maxTokens / 2);
2309
+ const head = tokens.slice(0, half);
2310
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
2311
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
2312
+ }
2313
+ default:
2314
+ truncatedTokens = tokens.slice(0, maxTokens);
2315
+ return encoder.decode(truncatedTokens) + ellipsis;
2316
+ }
2317
+ }
2318
+ static cleanup() {
2319
+ for (const encoder of this.encoderCache.values()) {
2320
+ encoder.free();
2321
+ }
2322
+ this.encoderCache.clear();
2323
+ }
2324
+ };
2325
+ function normalizePositiveNumber(value, fallback) {
2326
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2327
+ }
2328
+ function normalizeNonNegativeInteger(value, fallback) {
2329
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2330
+ return fallback;
2331
+ }
2332
+ return Math.max(0, Math.floor(value));
2333
+ }
2334
+
2335
+ // src/shared/defaultTokenizerPort.ts
2336
+ var DefaultTokenizerPort = class {
2337
+ constructor(config = {}) {
2338
+ this.config = config;
2339
+ }
2340
+ config;
2341
+ estimateText(text, _modelId) {
2342
+ return TokenCalculator.estimateTokens(text, {
2343
+ encoding: this.config.encoding,
2344
+ avgCharsPerToken: this.config.avgCharsPerToken
2345
+ });
2346
+ }
2347
+ estimateMessage(message, _modelId) {
2348
+ return TokenCalculator.estimateMessageTokens(message, {
2349
+ encoding: this.config.encoding,
2350
+ avgCharsPerToken: this.config.avgCharsPerToken,
2351
+ toolCallOverhead: this.config.toolCallOverhead
2352
+ });
2353
+ }
2354
+ };
2355
+ function createDefaultTokenizerPort(config = {}) {
2356
+ return new DefaultTokenizerPort(config);
2357
+ }
1895
2358
 
1896
2359
  // src/shared/ids.ts
1897
2360
  function isoRandomUUID() {
@@ -1993,15 +2456,15 @@ function splitConcatenatedJsonObjects(input) {
1993
2456
  }
1994
2457
 
1995
2458
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1996
- function readNonEmptyString(value) {
2459
+ function readNonEmptyString2(value) {
1997
2460
  if (typeof value !== "string") return void 0;
1998
2461
  const trimmed = value.trim();
1999
2462
  return trimmed.length > 0 ? trimmed : void 0;
2000
2463
  }
2001
2464
  function resolveConversationIdForRuntimeEvents(toolContext) {
2002
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
2465
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
2003
2466
  if (fromCamel) return fromCamel;
2004
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
2467
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
2005
2468
  if (fromSnake) return fromSnake;
2006
2469
  return generateMessageId();
2007
2470
  }
@@ -2072,6 +2535,13 @@ function resolveUsage(response) {
2072
2535
  }
2073
2536
  return response.usage;
2074
2537
  }
2538
+ function resolveCanonicalUsage(response) {
2539
+ if (!response || typeof response === "string") {
2540
+ return void 0;
2541
+ }
2542
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2543
+ return parsed.success ? parsed.data : void 0;
2544
+ }
2075
2545
  function resolveToolCalls(response) {
2076
2546
  if (!response || typeof response === "string") {
2077
2547
  return void 0;
@@ -2108,214 +2578,87 @@ function recordAfterContextManagerOnSystemReminderHit(params) {
2108
2578
  function recordToolProtocolError(params) {
2109
2579
  recorder?.recordToolProtocolError?.(params);
2110
2580
  }
2111
- function recordRunTranscript(params) {
2112
- recorder?.recordRunTranscript?.(params);
2113
- }
2114
-
2115
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2116
- var contextAuditMiddleware = async (ctx, stage, next) => {
2117
- if (stage.id === "build_context") {
2118
- recordBeforeContextManager({
2119
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
2120
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2121
- });
2122
- }
2123
- await next();
2124
- if (stage.id !== "apply_system_reminder") {
2125
- return;
2126
- }
2127
- const toolNamesForAudit = resolveToolNamesForAudit(ctx);
2128
- recordAfterContextManager({
2129
- mode: ctx.mode,
2130
- llmMessages: ctx.llmMessages,
2131
- toolNames: toolNamesForAudit,
2132
- contextTrace: ctx.contextTrace
2133
- });
2134
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2135
- recordAfterContextManagerOnSystemReminderHit({
2136
- mode: ctx.mode,
2137
- llmMessages: ctx.llmMessages,
2138
- toolNames: toolNamesForAudit,
2139
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2140
- contextTrace: ctx.contextTrace
2141
- });
2142
- }
2143
- };
2144
- var TokenCalculator = class {
2145
- static BYTES_PER_TOKEN_LATIN = 4;
2146
- static BYTES_PER_TOKEN_CJK = 3;
2147
- static OVERHEAD_PER_MESSAGE = 5;
2148
- static OVERHEAD_PER_TOOL_CALL = 10;
2149
- static encoderCache = /* @__PURE__ */ new Map();
2150
- static DEFAULT_ENCODING = "cl100k_base";
2151
- static SUPPORTED_ENCODINGS = [
2152
- "gpt2",
2153
- "r50k_base",
2154
- "p50k_base",
2155
- "p50k_edit",
2156
- "cl100k_base",
2157
- "o200k_base"
2158
- ];
2159
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
2160
- const normalized = (modelIdentifier || "").trim().toLowerCase();
2161
- if (this.isSupportedEncodingName(normalized)) {
2162
- return normalized;
2163
- }
2164
- if (normalized.includes("deepseek")) {
2165
- return "cl100k_base";
2166
- }
2167
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
2168
- return "o200k_base";
2169
- }
2170
- if (normalized.includes("gemini") || normalized.includes("claude")) {
2171
- return "cl100k_base";
2172
- }
2173
- return this.DEFAULT_ENCODING;
2174
- }
2175
- static isSupportedEncodingName(value) {
2176
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
2177
- }
2178
- static getEncoder(modelIdentifierOrEncoding) {
2179
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
2180
- const cached = this.encoderCache.get(encodingName);
2181
- if (cached) {
2182
- return cached;
2183
- }
2184
- const encoder = get_encoding(encodingName);
2185
- this.encoderCache.set(encodingName, encoder);
2186
- return encoder;
2187
- }
2188
- static estimateTokensRough(text, _modelIdentifier) {
2189
- if (!text) return 0;
2190
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
2191
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
2192
- const byteLength = new TextEncoder().encode(text).length;
2193
- return Math.ceil(byteLength / ratio);
2194
- }
2195
- static estimateTokens(text, options = {}) {
2196
- if (!text) return 0;
2197
- if (options.encoding) {
2198
- try {
2199
- return this.estimateTokensPrecise(text, options.encoding);
2200
- } catch {
2201
- }
2202
- }
2203
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
2204
- return Math.ceil(text.length / avgCharsPerToken);
2205
- }
2206
- static estimateTokensPrecise(text, modelIdentifier) {
2207
- if (!text) return 0;
2208
- const encoder = this.getEncoder(modelIdentifier);
2209
- return encoder.encode(text).length;
2210
- }
2211
- static estimateMessageTokens(message, options = {}) {
2212
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
2213
- if (message.content) {
2214
- totalTokens += this.estimateTokens(String(message.content), options);
2215
- }
2216
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
2217
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
2218
- for (const toolCall of toolCalls) {
2219
- totalTokens += toolCallOverhead;
2220
- const fn = toolCall["function"];
2221
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
2222
- const fnRecord = fn;
2223
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
2224
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
2225
- }
2226
- }
2227
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
2228
- if (toolCallId) {
2229
- totalTokens += this.estimateTokens(toolCallId, options);
2230
- }
2231
- return totalTokens;
2232
- }
2233
- static estimateMessageTokensPrecise(message, modelIdentifier) {
2234
- return this.estimateMessageTokens(message, {
2235
- encoding: modelIdentifier,
2236
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
2581
+ function recordRunTranscript(params) {
2582
+ recorder?.recordRunTranscript?.(params);
2583
+ }
2584
+
2585
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2586
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2587
+ if (stage.id === "build_context") {
2588
+ recordBeforeContextManager({
2589
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2590
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2237
2591
  });
2238
2592
  }
2239
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
2240
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
2241
- }
2242
- static extractToolCallsForTokenEstimate(message) {
2243
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
2244
- if (Array.isArray(direct)) return direct;
2245
- const metadata = "metadata" in message ? message.metadata : void 0;
2246
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
2247
- const metadataRecord = metadata;
2248
- const metadataToolCalls = metadataRecord["tool_calls"];
2249
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
2250
- }
2251
- static extractToolCallIdForTokenEstimate(message) {
2252
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
2253
- return message.tool_call_id;
2254
- }
2255
- const metadata = "metadata" in message ? message.metadata : void 0;
2256
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
2257
- const metadataRecord = metadata;
2258
- const toolCallId = metadataRecord["tool_call_id"];
2259
- return typeof toolCallId === "string" ? toolCallId : void 0;
2260
- }
2261
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
2262
- if (!text || maxTokens <= 0) return "";
2263
- const encoder = this.getEncoder(modelIdentifier);
2264
- const tokens = encoder.encode(text);
2265
- if (tokens.length <= maxTokens) {
2266
- return text;
2267
- }
2268
- let truncatedTokens;
2269
- const ellipsis = "...";
2270
- switch (strategy) {
2271
- case "start":
2272
- truncatedTokens = tokens.slice(0, maxTokens);
2273
- return encoder.decode(truncatedTokens) + ellipsis;
2274
- case "end":
2275
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
2276
- return ellipsis + encoder.decode(truncatedTokens);
2277
- case "middle": {
2278
- const half = Math.floor(maxTokens / 2);
2279
- const head = tokens.slice(0, half);
2280
- const tail = tokens.slice(tokens.length - (maxTokens - half));
2281
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
2282
- }
2283
- default:
2284
- truncatedTokens = tokens.slice(0, maxTokens);
2285
- return encoder.decode(truncatedTokens) + ellipsis;
2286
- }
2593
+ await next();
2594
+ if (stage.id !== "apply_system_reminder") {
2595
+ return;
2287
2596
  }
2288
- static cleanup() {
2289
- for (const encoder of this.encoderCache.values()) {
2290
- encoder.free();
2291
- }
2292
- this.encoderCache.clear();
2597
+ const toolNamesForAudit = resolveToolNamesForAudit(ctx);
2598
+ recordAfterContextManager({
2599
+ mode: ctx.mode,
2600
+ llmMessages: ctx.llmMessages,
2601
+ toolNames: toolNamesForAudit,
2602
+ contextTrace: ctx.contextTrace
2603
+ });
2604
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2605
+ recordAfterContextManagerOnSystemReminderHit({
2606
+ mode: ctx.mode,
2607
+ llmMessages: ctx.llmMessages,
2608
+ toolNames: toolNamesForAudit,
2609
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2610
+ contextTrace: ctx.contextTrace
2611
+ });
2293
2612
  }
2294
2613
  };
2295
- function normalizePositiveNumber(value, fallback) {
2296
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2614
+ var als = new AsyncLocalStorage();
2615
+ function readTokenCount(record, key) {
2616
+ const value = record[key];
2617
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
2297
2618
  }
2298
- function normalizeNonNegativeInteger(value, fallback) {
2299
- if (typeof value !== "number" || !Number.isFinite(value)) {
2300
- return fallback;
2301
- }
2302
- return Math.max(0, Math.floor(value));
2619
+ function readRecord(record, key) {
2620
+ const value = record[key];
2621
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2622
+ return Object.fromEntries(Object.entries(value));
2303
2623
  }
2304
- var als = new AsyncLocalStorage();
2305
- function normalizeLlmUsage(usage) {
2624
+ function normalizedUsageFromCanonical(canonicalUsage) {
2625
+ return {
2626
+ promptTokens: canonicalUsage.inputTokens,
2627
+ completionTokens: canonicalUsage.outputTokens,
2628
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2629
+ canonicalUsage
2630
+ };
2631
+ }
2632
+ function normalizeCanonicalLlmUsage(usage) {
2306
2633
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
2307
2634
  const rec = usage;
2308
- const promptTokensRaw = rec["prompt_tokens"];
2309
- const completionTokensRaw = rec["completion_tokens"];
2310
- const totalTokensRaw = rec["total_tokens"];
2311
- const tokensRaw = rec["tokens"];
2312
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
2313
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
2314
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
2315
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
2316
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
2317
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
2318
- return { promptTokens, completionTokens, totalTokens };
2635
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2636
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2637
+ if (inputTokens === void 0 || outputTokens === void 0) {
2638
+ return void 0;
2639
+ }
2640
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2641
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2642
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2643
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2644
+ const totalTokens = readTokenCount(rec, "total_tokens");
2645
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2646
+ return void 0;
2647
+ }
2648
+ return {
2649
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2650
+ outputTokens,
2651
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2652
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2653
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2654
+ source: "provider-response-usage",
2655
+ confidence: "actual",
2656
+ rawUsage: usage
2657
+ };
2658
+ }
2659
+ function normalizeLlmUsage(usage) {
2660
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2661
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
2319
2662
  }
2320
2663
  function recordLlmCallTelemetry(entry) {
2321
2664
  const store = als.getStore();
@@ -2339,17 +2682,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2339
2682
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2340
2683
  return;
2341
2684
  }
2342
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2685
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2686
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2343
2687
  const respText = extractResponseText(ctx.llmResp);
2344
2688
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2345
2689
  try {
2346
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2347
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2348
- return {
2349
- promptTokens,
2350
- completionTokens,
2351
- totalTokens: promptTokens + completionTokens
2352
- };
2690
+ const promptTokens = ctx.llmMessages.reduce(
2691
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2692
+ 0
2693
+ );
2694
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2695
+ return normalizedUsageFromCanonical({
2696
+ inputTokens: promptTokens,
2697
+ outputTokens: completionTokens,
2698
+ totalTokens: promptTokens + completionTokens,
2699
+ source: "local-estimate",
2700
+ confidence: "estimate"
2701
+ });
2353
2702
  } catch {
2354
2703
  return void 0;
2355
2704
  }
@@ -2359,7 +2708,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2359
2708
  stream: ctx.input.stream === true,
2360
2709
  startedAt: ctx.llmCallStartedAt,
2361
2710
  durationMs: ctx.llmCallDurationMs,
2362
- usage: normalizedUsage
2711
+ usage: normalizedUsage,
2712
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2363
2713
  });
2364
2714
  ctx.telemetry.emit({
2365
2715
  kind: "llm_call",
@@ -2367,6 +2717,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2367
2717
  stream: ctx.input.stream === true,
2368
2718
  durationMs: ctx.llmCallDurationMs,
2369
2719
  usage: normalizedUsage,
2720
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2370
2721
  scope: {
2371
2722
  conversationId: ctx.conversationId || void 0,
2372
2723
  turnId: ctx.turnId,
@@ -2383,7 +2734,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
2383
2734
  if (stage.id !== "execute_llm") {
2384
2735
  return;
2385
2736
  }
2386
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2737
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
2387
2738
  if (!normalized) {
2388
2739
  return;
2389
2740
  }
@@ -2510,10 +2861,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2510
2861
  return [
2511
2862
  `\u26A0\uFE0F \u4E0A\u4E0B\u6587\u9884\u7B97\u544A\u8B66\uFF1A\u4F60\u5DF2\u6267\u884C\u4E86 ${displayStep}/${displayMax} \u6B65\uFF0C\u4E0A\u4E0B\u6587\u7A7A\u95F4\u5373\u5C06\u8017\u5C3D\u3002`,
2512
2863
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2513
- "1. \u8C03\u7528sharedmemory_write\u5DE5\u5177\uFF0C\u5C06\u5F53\u524D\u53D1\u73B0\u3001\u603B\u7ED3\u3001\u601D\u8003\u6216\u8005\u4EFB\u4F55\u91CD\u8981\u4FE1\u606F\u8BE6\u7EC6\u5199\u5165sharedmemory\u3002",
2864
+ "1. \u5148\u786E\u8BA4\u5173\u952E\u8FDB\u5C55\u3001\u7EA6\u675F\u3001\u4E0B\u4E00\u6B65\u5DF2\u7ECF\u8FDB\u5165 TaskState\uFF1B\u5982\u679C\u6CA1\u6709\uFF0C\u8BF7\u8C03\u7528 taskstate_write \u66F4\u65B0\u3002",
2514
2865
  `2. \u8C03\u7528 ${checkpointToolName} \u5DE5\u5177\uFF0C\u4F20\u5165 summary\uFF08\u9636\u6BB5\u8FC7\u6E21\u6458\u8981\uFF09\u548C taskstate\uFF08\u6700\u65B0\u4EFB\u52A1\u72B6\u6001\uFF09\u3002`,
2515
2866
  ' \u8FD9\u4F1A\u4E00\u6B21\u6027\u5B8C\u6210"\u4FDD\u5B58\u72B6\u6001 + \u6E05\u7406\u5386\u53F2"\uFF0Ccheckpoint tool_output \u4E2D\u4F1A\u4FDD\u7559\u4F60\u7684 TaskState \u5FEB\u7167\u3002',
2516
- "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u91CD\u8981\u4FE1\u606F\u4F1A\u901A\u8FC7sharedmemory\u4FDD\u5B58\u3002"
2867
+ "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u9700\u8981\u957F\u671F\u4EA4\u4ED8\u7ED9\u7528\u6237\u7684\u5185\u5BB9\u8BF7\u5199\u5165 Workspace \u6587\u4EF6\u3002"
2517
2868
  ].join("\n");
2518
2869
  };
2519
2870
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2821,6 +3172,219 @@ function createApplySystemReminderStage() {
2821
3172
  };
2822
3173
  }
2823
3174
 
3175
+ // src/runtime-kernel/token-accounting/index.ts
3176
+ var token_accounting_exports = {};
3177
+ __export(token_accounting_exports, {
3178
+ addLedgerAggregate: () => addLedgerAggregate,
3179
+ addUsageTotals: () => addUsageTotals,
3180
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
3181
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
3182
+ computeCost: () => computeCost,
3183
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
3184
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
3185
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
3186
+ });
3187
+
3188
+ // src/runtime-kernel/token-accounting/functions.ts
3189
+ var EMPTY_LEDGER_AGGREGATE = {
3190
+ contextTokens: 0,
3191
+ entryCount: 0,
3192
+ llmCallCount: 0,
3193
+ contextComponentCount: 0
3194
+ };
3195
+ var TOKEN_PRICE_UNIT = 1e6;
3196
+ function sumReportedOptional(values) {
3197
+ const reported = values.filter((value) => value !== void 0);
3198
+ if (reported.length === 0) {
3199
+ return void 0;
3200
+ }
3201
+ return reported.reduce((total, value) => total + value, 0);
3202
+ }
3203
+ function sumTotalTokens(usages) {
3204
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
3205
+ return void 0;
3206
+ }
3207
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
3208
+ }
3209
+ function aggregateCanonicalUsage(usages) {
3210
+ if (usages.length === 0) {
3211
+ return void 0;
3212
+ }
3213
+ return {
3214
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
3215
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
3216
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
3217
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
3218
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
3219
+ totalTokens: sumTotalTokens(usages),
3220
+ usageCount: usages.length
3221
+ };
3222
+ }
3223
+ function createLlmUsageLedgerEntry(input) {
3224
+ return {
3225
+ ...input,
3226
+ kind: "llm-usage"
3227
+ };
3228
+ }
3229
+ function createContextComponentLedgerEntry(input) {
3230
+ return {
3231
+ ...input,
3232
+ kind: "context-component",
3233
+ components: [...input.components],
3234
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
3235
+ };
3236
+ }
3237
+ function addUsageTotals(left, right) {
3238
+ if (!left) {
3239
+ return right;
3240
+ }
3241
+ if (!right) {
3242
+ return left;
3243
+ }
3244
+ return {
3245
+ inputTokens: left.inputTokens + right.inputTokens,
3246
+ outputTokens: left.outputTokens + right.outputTokens,
3247
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
3248
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
3249
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
3250
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
3251
+ usageCount: left.usageCount + right.usageCount
3252
+ };
3253
+ }
3254
+ function addLedgerAggregate(left, right) {
3255
+ return {
3256
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
3257
+ contextTokens: left.contextTokens + right.contextTokens,
3258
+ entryCount: left.entryCount + right.entryCount,
3259
+ llmCallCount: left.llmCallCount + right.llmCallCount,
3260
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
3261
+ };
3262
+ }
3263
+ function aggregateTokenLedgerEntries(entries) {
3264
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
3265
+ return entries.reduce((aggregate, entry) => {
3266
+ if (entry.kind === "llm-usage") {
3267
+ return {
3268
+ ...aggregate,
3269
+ entryCount: aggregate.entryCount + 1,
3270
+ llmCallCount: aggregate.llmCallCount + 1
3271
+ };
3272
+ }
3273
+ return {
3274
+ ...aggregate,
3275
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
3276
+ entryCount: aggregate.entryCount + 1,
3277
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
3278
+ };
3279
+ }, {
3280
+ ...EMPTY_LEDGER_AGGREGATE,
3281
+ llmUsage: aggregateCanonicalUsage(llmUsages)
3282
+ });
3283
+ }
3284
+ function createRunTokenUsageAggregate(input) {
3285
+ const children = input.childAggregates?.reduce(
3286
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
3287
+ EMPTY_LEDGER_AGGREGATE
3288
+ );
3289
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
3290
+ }
3291
+ function componentCost(tokens, pricePerMillion) {
3292
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
3293
+ }
3294
+ function needsPrice(tokens) {
3295
+ return tokens !== void 0 && tokens > 0;
3296
+ }
3297
+ function missingPriceComponents(usage, pricing) {
3298
+ const missing = [];
3299
+ if (!pricing) {
3300
+ if (needsPrice(usage.inputTokens)) {
3301
+ missing.push("input");
3302
+ }
3303
+ if (needsPrice(usage.outputTokens)) {
3304
+ missing.push("output");
3305
+ }
3306
+ if (needsPrice(usage.reasoningTokens)) {
3307
+ missing.push("reasoning");
3308
+ }
3309
+ if (needsPrice(usage.cacheReadTokens)) {
3310
+ missing.push("cacheRead");
3311
+ }
3312
+ if (needsPrice(usage.cacheWriteTokens)) {
3313
+ missing.push("cacheWrite");
3314
+ }
3315
+ return missing;
3316
+ }
3317
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
3318
+ missing.push("input");
3319
+ }
3320
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
3321
+ missing.push("output");
3322
+ }
3323
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
3324
+ missing.push("reasoning");
3325
+ }
3326
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
3327
+ missing.push("cacheRead");
3328
+ }
3329
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
3330
+ missing.push("cacheWrite");
3331
+ }
3332
+ return missing;
3333
+ }
3334
+ function reportedComponentCost(tokens, pricePerMillion) {
3335
+ if (tokens === void 0) {
3336
+ return void 0;
3337
+ }
3338
+ if (tokens === 0) {
3339
+ return 0;
3340
+ }
3341
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
3342
+ }
3343
+ function requiredComponentCost(tokens, pricePerMillion) {
3344
+ if (tokens === 0) {
3345
+ return 0;
3346
+ }
3347
+ return componentCost(tokens, pricePerMillion ?? 0);
3348
+ }
3349
+ function sumComputedCosts(costs) {
3350
+ let total = 0;
3351
+ for (const cost of costs) {
3352
+ total += cost ?? 0;
3353
+ }
3354
+ return total;
3355
+ }
3356
+ function computeCost(usage, pricing) {
3357
+ const missing = missingPriceComponents(usage, pricing);
3358
+ if (!pricing || missing.length > 0) {
3359
+ return {
3360
+ status: "unknown",
3361
+ ...pricing ? { currency: pricing.currency } : {},
3362
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
3363
+ };
3364
+ }
3365
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
3366
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
3367
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
3368
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
3369
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
3370
+ return {
3371
+ status: "computed",
3372
+ currency: pricing.currency,
3373
+ inputCost,
3374
+ outputCost,
3375
+ reasoningCost,
3376
+ cacheReadCost,
3377
+ cacheWriteCost,
3378
+ totalCost: sumComputedCosts([
3379
+ inputCost,
3380
+ outputCost,
3381
+ reasoningCost,
3382
+ cacheReadCost,
3383
+ cacheWriteCost
3384
+ ])
3385
+ };
3386
+ }
3387
+
2824
3388
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2825
3389
  var logger4 = new Logger("GraphAgentExecutor");
2826
3390
  function createBuildContextStage(dependencies) {
@@ -2837,6 +3401,23 @@ function createBuildContextStage(dependencies) {
2837
3401
  ctx.mode = contextBuildResult.mode;
2838
3402
  ctx.llmMessages = contextBuildResult.llmMessages;
2839
3403
  ctx.contextTrace = contextBuildResult.contextTrace;
3404
+ if (contextBuildResult.tokenEstimate) {
3405
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
3406
+ ctx.telemetry.emit({
3407
+ kind: "context_build",
3408
+ modelId: ctx.modelId,
3409
+ mode: contextBuildResult.mode,
3410
+ tokenEstimate: contextBuildResult.tokenEstimate,
3411
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
3412
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
3413
+ scope: {
3414
+ conversationId: ctx.conversationId,
3415
+ runId: ctx.input.toolContext?.runId,
3416
+ parentRunId: ctx.input.toolContext?.parentRunId,
3417
+ turnId: ctx.turnId
3418
+ }
3419
+ });
3420
+ }
2840
3421
  for (const event of contextBuildResult.summaryEvents) {
2841
3422
  if (!isHistorySummaryEvent(event)) {
2842
3423
  continue;
@@ -2851,6 +3432,24 @@ function createBuildContextStage(dependencies) {
2851
3432
  }
2852
3433
  };
2853
3434
  }
3435
+ function createContextLedgerEntry(ctx, contextBuildResult) {
3436
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
3437
+ if (keptComponents.length === 0) {
3438
+ return void 0;
3439
+ }
3440
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
3441
+ const createdAt = Date.now();
3442
+ return createContextComponentLedgerEntry({
3443
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
3444
+ conversationId: ctx.conversationId,
3445
+ runId,
3446
+ parentRunId: ctx.input.toolContext?.parentRunId,
3447
+ turnId: ctx.turnId,
3448
+ route: contextBuildResult.tokenEstimate?.route,
3449
+ createdAt,
3450
+ components: keptComponents
3451
+ });
3452
+ }
2854
3453
 
2855
3454
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2856
3455
  function createBuildDecisionStage(dependencies) {
@@ -2984,7 +3583,7 @@ function createExecuteLlmStage(dependencies) {
2984
3583
  streamEventHandler,
2985
3584
  ctx.signal,
2986
3585
  (fallbackModelId) => {
2987
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
3586
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2988
3587
  },
2989
3588
  (info) => {
2990
3589
  ctx.modelFallbackAudit = info;
@@ -3028,7 +3627,7 @@ function createPrepareCallStage(dependencies) {
3028
3627
  return {
3029
3628
  id: "prepare_call",
3030
3629
  async run(ctx) {
3031
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
3630
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
3032
3631
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
3033
3632
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
3034
3633
  await emitAuditEnvelope(ctx.audit, {
@@ -3094,19 +3693,21 @@ var GraphAgentExecutor = class {
3094
3693
  modelCatalog;
3095
3694
  telemetryPort;
3096
3695
  auditPort;
3696
+ tokenizer;
3097
3697
  stages;
3098
3698
  middlewares;
3099
3699
  constructor(dependencies) {
3100
3700
  this.llmCaller = dependencies.llmCaller;
3101
3701
  this.toolRuntime = dependencies.toolRuntime;
3102
3702
  this.contextBuilder = dependencies.contextBuilder;
3103
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3703
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
3104
3704
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
3105
3705
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
3106
3706
  modelCatalog: this.modelCatalog
3107
3707
  });
3108
3708
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
3109
3709
  this.auditPort = dependencies.auditPort ?? noopAudit;
3710
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
3110
3711
  this.stages = [
3111
3712
  createPrepareCallStage({
3112
3713
  modelResolver: this.modelResolver,
@@ -3148,9 +3749,10 @@ var GraphAgentExecutor = class {
3148
3749
  llmMessages: [],
3149
3750
  mode: input.request.mode === "chat" ? "chat" : "agent",
3150
3751
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
3151
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3752
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3152
3753
  telemetry: this.telemetryPort,
3153
- audit: this.auditPort
3754
+ audit: this.auditPort,
3755
+ tokenizer: this.tokenizer
3154
3756
  };
3155
3757
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
3156
3758
  stream: input.stream === true,
@@ -3198,18 +3800,18 @@ function isSummarizationCallbacks(value) {
3198
3800
  function isGraphSseSink(value) {
3199
3801
  return typeof value === "function";
3200
3802
  }
3201
- function readNonEmptyString2(value) {
3803
+ function readNonEmptyString3(value) {
3202
3804
  if (typeof value !== "string") return void 0;
3203
3805
  const trimmed = value.trim();
3204
3806
  return trimmed.length > 0 ? trimmed : void 0;
3205
3807
  }
3206
3808
  function readGraphAgentLocal(local) {
3207
3809
  const source = local ?? {};
3208
- const answerId = readNonEmptyString2(source.answerId);
3810
+ const answerId = readNonEmptyString3(source.answerId);
3209
3811
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
3210
3812
  return {
3211
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
3212
- turnId: readNonEmptyString2(source.turnId),
3813
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3814
+ turnId: readNonEmptyString3(source.turnId),
3213
3815
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
3214
3816
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
3215
3817
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3974,7 +4576,7 @@ var LlmNode = class {
3974
4576
  function isRecord8(value) {
3975
4577
  return typeof value === "object" && value !== null && !Array.isArray(value);
3976
4578
  }
3977
- function readNonEmptyString3(value) {
4579
+ function readNonEmptyString4(value) {
3978
4580
  if (typeof value !== "string") {
3979
4581
  return void 0;
3980
4582
  }
@@ -3996,7 +4598,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3996
4598
  return void 0;
3997
4599
  }
3998
4600
  if (toolName === "write_report") {
3999
- const report = readNonEmptyString3(data.report);
4601
+ const report = readNonEmptyString4(data.report);
4000
4602
  if (!report) {
4001
4603
  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");
4002
4604
  }
@@ -4006,7 +4608,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
4006
4608
  if (data.success !== true) {
4007
4609
  return void 0;
4008
4610
  }
4009
- const finalAnswer = readNonEmptyString3(data.final_answer);
4611
+ const finalAnswer = readNonEmptyString4(data.final_answer);
4010
4612
  if (!finalAnswer) {
4011
4613
  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");
4012
4614
  }
@@ -4115,11 +4717,11 @@ function buildToolOutputUiMeta(params) {
4115
4717
  }
4116
4718
  async function applyObservationGovernance(params) {
4117
4719
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
4118
- return;
4720
+ return {};
4119
4721
  }
4120
4722
  const policy = resolveToolObservationGovernancePolicy(params.policy);
4121
4723
  if (!policy.enabled) {
4122
- return;
4724
+ return {};
4123
4725
  }
4124
4726
  const truncated = await params.observationPreview.truncateObservation({
4125
4727
  context: params.toolContext,
@@ -4133,13 +4735,37 @@ async function applyObservationGovernance(params) {
4133
4735
  })
4134
4736
  });
4135
4737
  if (!truncated.truncated) {
4136
- return;
4738
+ return {};
4137
4739
  }
4138
4740
  params.parsed["observation"] = truncated.preview;
4139
4741
  const data = params.parsed["data"];
4140
4742
  if (isRecord9(data) && !("tool_output_store" in data)) {
4141
4743
  data["tool_output_store"] = { blob_id: truncated.blob_id };
4142
4744
  }
4745
+ return {
4746
+ observationTruncation: buildObservationTruncationMeta({
4747
+ originalText: params.structuredObservation,
4748
+ previewText: truncated.preview,
4749
+ originalChars: truncated.originalChars,
4750
+ previewChars: truncated.previewChars,
4751
+ originalLines: truncated.originalLines,
4752
+ previewLines: truncated.previewLines
4753
+ })
4754
+ };
4755
+ }
4756
+ function buildObservationTruncationMeta(input) {
4757
+ return {
4758
+ originalChars: input.originalChars ?? input.originalText.length,
4759
+ previewChars: input.previewChars ?? input.previewText.length,
4760
+ originalLines: input.originalLines ?? countLines(input.originalText),
4761
+ previewLines: input.previewLines ?? countLines(input.previewText)
4762
+ };
4763
+ }
4764
+ function countLines(value) {
4765
+ if (value.length === 0) {
4766
+ return 0;
4767
+ }
4768
+ return value.split(/\r\n|\r|\n/).length;
4143
4769
  }
4144
4770
 
4145
4771
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4556,6 +5182,31 @@ function ensureToolContextRuntimeCapability(params) {
4556
5182
  function getToolContextRuntimeBinding(context) {
4557
5183
  return readBinding(context);
4558
5184
  }
5185
+ function copyToolContextRuntimeCapability(source, target) {
5186
+ const sourceBinding = readBinding(source);
5187
+ if (!sourceBinding) {
5188
+ return void 0;
5189
+ }
5190
+ const existingTargetBinding = readBinding(target);
5191
+ if (existingTargetBinding) {
5192
+ exposeCompatibilitySurface(target, existingTargetBinding);
5193
+ return existingTargetBinding;
5194
+ }
5195
+ const targetBinding = createRuntimeBinding({
5196
+ context: target,
5197
+ persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
5198
+ workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
5199
+ executionMeta: sourceBinding.readExecutionMeta()
5200
+ });
5201
+ Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
5202
+ value: targetBinding,
5203
+ enumerable: false,
5204
+ configurable: true,
5205
+ writable: false
5206
+ });
5207
+ exposeCompatibilitySurface(target, targetBinding);
5208
+ return targetBinding;
5209
+ }
4559
5210
  function readToolContextWorkingHistory(context) {
4560
5211
  if (context.conversationView) {
4561
5212
  return context.conversationView.getWorkingHistoryEvents();
@@ -5082,7 +5733,7 @@ var ToolNode = class {
5082
5733
  parentRunId: context.toolContext.parentRunId
5083
5734
  });
5084
5735
  applyProtocolFuseState(context.local);
5085
- await applyObservationGovernance({
5736
+ const observationGovernance = await applyObservationGovernance({
5086
5737
  parsed: context.parsed,
5087
5738
  toolName: context.toolName,
5088
5739
  toolContext: context.toolContext,
@@ -5109,6 +5760,12 @@ var ToolNode = class {
5109
5760
  runtimeToolOutput,
5110
5761
  execIdempotency: context.exec.idempotency
5111
5762
  });
5763
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5764
+ runtimeToolOutput.metadata = {
5765
+ ...runtimeToolOutput.metadata ?? {},
5766
+ observationTruncation: observationGovernance.observationTruncation
5767
+ };
5768
+ }
5112
5769
  const remainingCalls = context.calls.slice(1);
5113
5770
  context.state.local = buildSuccessLocalState({
5114
5771
  local: context.local,
@@ -5407,12 +6064,12 @@ function asRecord(value) {
5407
6064
  }
5408
6065
  return value;
5409
6066
  }
5410
- function summarizeCheckpoint(conversationId, state, savedAt) {
6067
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
5411
6068
  const local = asRecord(state.local);
5412
6069
  const executorLocal = asRecord(local?.executorLocal);
5413
6070
  const pendingToolCalls = local?.pendingToolCalls;
5414
6071
  return {
5415
- conversationId,
6072
+ checkpointKey,
5416
6073
  schemaVersion: state.schemaVersion ?? 1,
5417
6074
  savedAt,
5418
6075
  currentNode: state.nodeId,
@@ -5431,25 +6088,25 @@ var MemoryCheckpointer = class {
5431
6088
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
5432
6089
  };
5433
6090
  }
5434
- async load(conversationId) {
5435
- const entry = this.store.get(conversationId);
6091
+ async load(checkpointKey) {
6092
+ const entry = this.store.get(checkpointKey);
5436
6093
  return entry ? this.cloneState(entry.state) : null;
5437
6094
  }
5438
- async save(conversationId, state) {
5439
- this.store.set(conversationId, {
6095
+ async save(checkpointKey, state) {
6096
+ this.store.set(checkpointKey, {
5440
6097
  state: this.cloneState(state),
5441
6098
  savedAt: Date.now()
5442
6099
  });
5443
6100
  }
5444
- async clear(conversationId) {
5445
- this.store.delete(conversationId);
6101
+ async clear(checkpointKey) {
6102
+ this.store.delete(checkpointKey);
5446
6103
  }
5447
- async peekMeta(conversationId) {
5448
- const entry = this.store.get(conversationId);
5449
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
6104
+ async peekMeta(checkpointKey) {
6105
+ const entry = this.store.get(checkpointKey);
6106
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
5450
6107
  }
5451
6108
  async list(filter = {}) {
5452
- 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);
6109
+ 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);
5453
6110
  if (filter.limit === void 0) {
5454
6111
  return summaries;
5455
6112
  }
@@ -5521,6 +6178,7 @@ __export(tools_exports, {
5521
6178
  CommonParameterTypes: () => CommonParameterTypes,
5522
6179
  ContextCheckpointTool: () => ContextCheckpointTool,
5523
6180
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
6181
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
5524
6182
  createContextCheckpointTool: () => createContextCheckpointTool,
5525
6183
  ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
5526
6184
  findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
@@ -5714,7 +6372,7 @@ function createContextCheckpointTool(options) {
5714
6372
  function isRecord15(value) {
5715
6373
  return !!value && typeof value === "object" && !Array.isArray(value);
5716
6374
  }
5717
- function readNonEmptyString4(value) {
6375
+ function readNonEmptyString5(value) {
5718
6376
  if (typeof value !== "string") {
5719
6377
  return void 0;
5720
6378
  }
@@ -5734,13 +6392,13 @@ function readToolContextUserQuery(context) {
5734
6392
  if (!context) {
5735
6393
  return void 0;
5736
6394
  }
5737
- return readNonEmptyString4(context["user_query"]);
6395
+ return readNonEmptyString5(context["user_query"]);
5738
6396
  }
5739
6397
  function readToolContextModelId(context) {
5740
6398
  if (!context) {
5741
6399
  return void 0;
5742
6400
  }
5743
- return readNonEmptyString4(context["modelId"]);
6401
+ return readNonEmptyString5(context["modelId"]);
5744
6402
  }
5745
6403
  function readToolContextRunContext(context) {
5746
6404
  if (!context) {
@@ -6942,6 +7600,7 @@ async function callLlmStream(params) {
6942
7600
  const streamAnswerId = generateMessageId();
6943
7601
  let streamChunkSeq = 0;
6944
7602
  let capturedUsage = void 0;
7603
+ let capturedCanonicalUsage = void 0;
6945
7604
  const toolAccumulator = new ToolCallStreamAccumulator([
6946
7605
  "markdown_edit",
6947
7606
  "text_to_image",
@@ -7000,6 +7659,10 @@ async function callLlmStream(params) {
7000
7659
  if (typeof chunk !== "object" || chunk === null) {
7001
7660
  return;
7002
7661
  }
7662
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7663
+ if (parsedCanonicalUsage.success) {
7664
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7665
+ }
7003
7666
  if (chunk.content) {
7004
7667
  emitThoughtComplete(thoughtSegmenter.onBoundary());
7005
7668
  fullResponse += chunk.content;
@@ -7084,6 +7747,12 @@ async function callLlmStream(params) {
7084
7747
  const onUsage = (usage) => {
7085
7748
  capturedUsage = usage;
7086
7749
  };
7750
+ const onCanonicalUsage = (usage) => {
7751
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7752
+ if (parsed.success) {
7753
+ capturedCanonicalUsage = parsed.data;
7754
+ }
7755
+ };
7087
7756
  await aiEngine.chatCompletionStream(
7088
7757
  modelId,
7089
7758
  messages,
@@ -7096,7 +7765,8 @@ async function callLlmStream(params) {
7096
7765
  onError,
7097
7766
  onFinish,
7098
7767
  onThought,
7099
- onUsage
7768
+ onUsage,
7769
+ onCanonicalUsage
7100
7770
  );
7101
7771
  if (streamError) {
7102
7772
  throw streamError;
@@ -7104,12 +7774,13 @@ async function callLlmStream(params) {
7104
7774
  emitThoughtComplete(thoughtSegmenter.finalize());
7105
7775
  const mergedToolCalls = toolAccumulator.getToolCalls();
7106
7776
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
7107
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7777
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
7108
7778
  return {
7109
7779
  content: fullResponse,
7110
7780
  tool_calls: mergedToolCalls,
7111
7781
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
7112
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7782
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7783
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
7113
7784
  };
7114
7785
  }
7115
7786
  return fullResponse;
@@ -7159,6 +7830,10 @@ function tryCloudQuotaFallback({
7159
7830
  }
7160
7831
 
7161
7832
  // src/runtime-kernel/llm/usage-telemetry.ts
7833
+ function parseCanonicalUsage(value) {
7834
+ const parsed = CanonicalLlmUsage.safeParse(value);
7835
+ return parsed.success ? parsed.data : void 0;
7836
+ }
7162
7837
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
7163
7838
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
7164
7839
  return normalizeCompletionResponse(response);
@@ -7169,6 +7844,7 @@ function normalizeCompletionResponse(response) {
7169
7844
  }
7170
7845
  if (isRecord19(response)) {
7171
7846
  const usage = response["usage"];
7847
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7172
7848
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
7173
7849
  if (parsedToolCalls) {
7174
7850
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -7176,7 +7852,8 @@ function normalizeCompletionResponse(response) {
7176
7852
  content: typeof response["content"] === "string" ? response["content"] : "",
7177
7853
  tool_calls: parsedToolCalls,
7178
7854
  reasoning_details: reasoningDetails,
7179
- ...usage !== void 0 ? { usage } : {}
7855
+ ...usage !== void 0 ? { usage } : {},
7856
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7180
7857
  };
7181
7858
  }
7182
7859
  }
@@ -7186,10 +7863,12 @@ function normalizeCompletionResponse(response) {
7186
7863
  if (typeof response === "object") {
7187
7864
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
7188
7865
  const usage = response["usage"];
7866
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
7189
7867
  return {
7190
7868
  content: typeof response["content"] === "string" ? response["content"] : "",
7191
7869
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
7192
- ...usage !== void 0 ? { usage } : {}
7870
+ ...usage !== void 0 ? { usage } : {},
7871
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
7193
7872
  };
7194
7873
  }
7195
7874
  if (isRecord19(response)) {
@@ -7443,29 +8122,6 @@ var LlmCaller = class {
7443
8122
  }
7444
8123
  };
7445
8124
 
7446
- // src/shared/defaultTokenizerPort.ts
7447
- var DefaultTokenizerPort = class {
7448
- constructor(config = {}) {
7449
- this.config = config;
7450
- }
7451
- estimateText(text, _modelId) {
7452
- return TokenCalculator.estimateTokens(text, {
7453
- encoding: this.config.encoding,
7454
- avgCharsPerToken: this.config.avgCharsPerToken
7455
- });
7456
- }
7457
- estimateMessage(message, _modelId) {
7458
- return TokenCalculator.estimateMessageTokens(message, {
7459
- encoding: this.config.encoding,
7460
- avgCharsPerToken: this.config.avgCharsPerToken,
7461
- toolCallOverhead: this.config.toolCallOverhead
7462
- });
7463
- }
7464
- };
7465
- function createDefaultTokenizerPort(config = {}) {
7466
- return new DefaultTokenizerPort(config);
7467
- }
7468
-
7469
8125
  // src/runtime-kernel/child-runs/index.ts
7470
8126
  var child_runs_exports = {};
7471
8127
  __export(child_runs_exports, {
@@ -7475,7 +8131,6 @@ __export(child_runs_exports, {
7475
8131
 
7476
8132
  // src/runtime-kernel/child-runs/childToolContext.ts
7477
8133
  function createChildRunToolContext(params) {
7478
- const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
7479
8134
  const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
7480
8135
  const childToolContext = {
7481
8136
  ...inheritedContext,
@@ -7487,7 +8142,7 @@ function createChildRunToolContext(params) {
7487
8142
  persistedHistory: params.seedHistory,
7488
8143
  workingHistory: params.seedHistory,
7489
8144
  executionMeta: {
7490
- conversationId: inheritedConversationId ?? params.internalConversationId,
8145
+ conversationId: params.conversationId,
7491
8146
  turnId: params.turnId,
7492
8147
  runId: params.runId,
7493
8148
  parentRunId: params.parentRunId
@@ -7589,6 +8244,8 @@ var FinalAnswerCollector = class {
7589
8244
  this.conversationId = conversationId;
7590
8245
  this.turnId = turnId;
7591
8246
  }
8247
+ conversationId;
8248
+ turnId;
7592
8249
  answerId;
7593
8250
  chunks = [];
7594
8251
  chunkCount = 0;
@@ -7805,7 +8462,7 @@ function readCheckpointHistory(checkpoint) {
7805
8462
  });
7806
8463
  }
7807
8464
  async function recoverChildRunEventsFromCheckpoint(params) {
7808
- const checkpoint = await params.checkpointer.load(params.conversationId);
8465
+ const checkpoint = await params.checkpointer.load(params.checkpointKey);
7809
8466
  const history = readCheckpointHistory(checkpoint);
7810
8467
  if (history.length === 0) {
7811
8468
  return [];
@@ -7813,7 +8470,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
7813
8470
  if (hasSeedHistoryPrefix(history, params.seedHistory)) {
7814
8471
  return history.slice(params.seedHistory.length);
7815
8472
  }
7816
- return history.filter((event) => event.conversation_id === params.internalConversationId);
8473
+ return history.filter((event) => event.conversation_id === params.childConversationId);
7817
8474
  }
7818
8475
 
7819
8476
  // src/runtime-kernel/child-runs/childRunInvoker.ts
@@ -7842,6 +8499,7 @@ var ChildRunInvoker = class {
7842
8499
  agentConfig,
7843
8500
  userMessage,
7844
8501
  parentToolContext,
8502
+ conversationId,
7845
8503
  runId,
7846
8504
  parentRunId,
7847
8505
  subrunTracePublisher,
@@ -7850,12 +8508,18 @@ var ChildRunInvoker = class {
7850
8508
  modelId,
7851
8509
  abortSignal
7852
8510
  } = config;
7853
- const internalConversationId = `internal_${generateMessageId()}`;
8511
+ const internalCheckpointKey = `internal_${generateMessageId()}`;
8512
+ const runtimeConversationId = resolveChildRunConversationId({
8513
+ explicitConversationId: conversationId,
8514
+ parentToolContext,
8515
+ fallbackConversationId: internalCheckpointKey
8516
+ });
7854
8517
  const turnId = `turn_${Date.now()}`;
7855
- const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalConversationId;
8518
+ const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
7856
8519
  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;
7857
8520
  logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
7858
- conversationId: internalConversationId,
8521
+ conversationId: runtimeConversationId,
8522
+ checkpointKey: internalCheckpointKey,
7859
8523
  maxSteps,
7860
8524
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
7861
8525
  });
@@ -7916,7 +8580,7 @@ var ChildRunInvoker = class {
7916
8580
  const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
7917
8581
  const childToolContext = createChildRunToolContext({
7918
8582
  parentToolContext,
7919
- internalConversationId,
8583
+ conversationId: runtimeConversationId,
7920
8584
  turnId,
7921
8585
  runId: childRunId,
7922
8586
  parentRunId: resolvedParentRunId,
@@ -7925,13 +8589,13 @@ var ChildRunInvoker = class {
7925
8589
  });
7926
8590
  const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
7927
8591
  publisher: subrunTracePublisher,
7928
- conversationId: internalConversationId,
8592
+ conversationId: runtimeConversationId,
7929
8593
  turnId
7930
8594
  }) : void 0;
7931
8595
  const initialLocal = {
7932
8596
  request,
7933
8597
  history: seedHistory,
7934
- conversationId: internalConversationId,
8598
+ conversationId: runtimeConversationId,
7935
8599
  turnId,
7936
8600
  toolContext: childToolContext,
7937
8601
  ...abortSignal ? { signal: abortSignal } : {},
@@ -7939,7 +8603,7 @@ var ChildRunInvoker = class {
7939
8603
  ...subrunSseSink ? { sseSink: subrunSseSink } : {},
7940
8604
  systemPrompt
7941
8605
  };
7942
- await graphExecutor.prime(internalConversationId, initialLocal, "llm");
8606
+ await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
7943
8607
  const allEvents = [];
7944
8608
  let stepCount = 0;
7945
8609
  let finalAnswer;
@@ -7951,7 +8615,7 @@ var ChildRunInvoker = class {
7951
8615
  err.name = "AbortError";
7952
8616
  throw err;
7953
8617
  }
7954
- const result = await graphExecutor.runUntilYield(internalConversationId);
8618
+ const result = await graphExecutor.runUntilYield(internalCheckpointKey);
7955
8619
  appendUniqueEvents(allEvents, result.events);
7956
8620
  stepCount = result.stepCount;
7957
8621
  if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
@@ -7985,8 +8649,8 @@ var ChildRunInvoker = class {
7985
8649
  }
7986
8650
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
7987
8651
  checkpointer,
7988
- conversationId: internalConversationId,
7989
- internalConversationId,
8652
+ checkpointKey: internalCheckpointKey,
8653
+ childConversationId: runtimeConversationId,
7990
8654
  seedHistory
7991
8655
  });
7992
8656
  appendUniqueEvents(allEvents, recoveredEvents);
@@ -8003,7 +8667,7 @@ var ChildRunInvoker = class {
8003
8667
  stack: err.stack
8004
8668
  } : { error: String(err) });
8005
8669
  }
8006
- await checkpointer.clear(internalConversationId);
8670
+ await checkpointer.clear(internalCheckpointKey);
8007
8671
  return {
8008
8672
  success: !error,
8009
8673
  runId: childRunId,
@@ -8016,6 +8680,16 @@ var ChildRunInvoker = class {
8016
8680
  };
8017
8681
  }
8018
8682
  };
8683
+ function readNonEmptyString6(value) {
8684
+ if (typeof value !== "string") {
8685
+ return void 0;
8686
+ }
8687
+ const trimmed = value.trim();
8688
+ return trimmed.length > 0 ? trimmed : void 0;
8689
+ }
8690
+ function resolveChildRunConversationId(params) {
8691
+ return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
8692
+ }
8019
8693
  function resolveChildRunSystemReminderPolicy(agentConfig) {
8020
8694
  const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
8021
8695
  const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
@@ -8206,7 +8880,7 @@ function cloneRunRecord(record) {
8206
8880
  ...record,
8207
8881
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
8208
8882
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
8209
- metadata: record.metadata ? { ...record.metadata } : void 0
8883
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
8210
8884
  };
8211
8885
  }
8212
8886
  function matchesStatus(candidate, filter) {
@@ -8618,7 +9292,7 @@ function isTerminalStatus(status) {
8618
9292
  return status === "completed" || status === "failed" || status === "cancelled";
8619
9293
  }
8620
9294
  function cloneMetadata(metadata) {
8621
- return metadata ? { ...metadata } : void 0;
9295
+ return metadata ? structuredClone(metadata) : void 0;
8622
9296
  }
8623
9297
  function recordToSnapshot(record) {
8624
9298
  return {
@@ -8705,7 +9379,7 @@ var DefaultRunSupervisor = class {
8705
9379
  startedAt,
8706
9380
  updatedAt: startedAt,
8707
9381
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
8708
- metadata: spec.metadata ? { ...spec.metadata } : void 0
9382
+ metadata: cloneMetadata(spec.metadata)
8709
9383
  };
8710
9384
  await this.registryStore.save(record);
8711
9385
  const handle = new DefaultRunHandle({
@@ -8879,12 +9553,13 @@ var DefaultRunSupervisor = class {
8879
9553
  }
8880
9554
  try {
8881
9555
  await handle.markRunning({ currentNode: "detached" });
9556
+ const registeredRecord = await this.registryStore.load(handle.runId);
8882
9557
  const executorOutcome = await this.executor.execute({
8883
9558
  runId: handle.runId,
8884
- parentRunId: spec.parentRunId,
8885
- conversationId: spec.conversationId,
8886
- agentSpec: spec.agentSpec,
8887
- request: spec.request,
9559
+ parentRunId: handle.parentRunId,
9560
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
9561
+ agentSpec: await handle.spec(),
9562
+ request: await handle.request(),
8888
9563
  signal: handle.signal,
8889
9564
  eventBus: spec.eventBus,
8890
9565
  eventStore: spec.eventStore,
@@ -8893,7 +9568,7 @@ var DefaultRunSupervisor = class {
8893
9568
  contextFences: spec.contextFences,
8894
9569
  wakeSource: spec.wakeSource,
8895
9570
  ephemeral: spec.ephemeral,
8896
- metadata: spec.metadata
9571
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
8897
9572
  });
8898
9573
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
8899
9574
  this.notifyTerminalWaiters(outcome);
@@ -8957,10 +9632,14 @@ var DefaultRunSupervisor = class {
8957
9632
  await this.registryStore.save(record);
8958
9633
  }
8959
9634
  const completedAt = executorOutcome?.completedAt ?? this.now();
9635
+ const fallbackMeta = record ? void 0 : await handle.meta();
8960
9636
  const outcome = recordToTerminalOutcome(record ?? {
8961
9637
  runId: handle.runId,
8962
9638
  parentRunId: handle.parentRunId,
8963
- status: executorOutcome?.status ?? "completed"}, completedAt);
9639
+ conversationId: fallbackMeta?.conversationId ?? "",
9640
+ agentSpecId: fallbackMeta?.agentSpecId,
9641
+ status: executorOutcome?.status ?? "completed",
9642
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
8964
9643
  const nextOutcome = {
8965
9644
  ...outcome,
8966
9645
  metadata: {
@@ -9052,6 +9731,7 @@ __export(telemetry_exports, {
9052
9731
  var TELEMETRY_EVENT_KINDS = [
9053
9732
  "llm_call",
9054
9733
  "tool_call",
9734
+ "context_build",
9055
9735
  "graph_node",
9056
9736
  "run_lifecycle"
9057
9737
  ];
@@ -9188,6 +9868,7 @@ function createGraphLoopHarness(options) {
9188
9868
  };
9189
9869
  return {
9190
9870
  async run() {
9871
+ const checkpointKey = options.conversationId;
9191
9872
  const executor = createDefaultGraphExecutor({
9192
9873
  llmNode: options.createLlmNode({
9193
9874
  llmCaller: options.llmCaller,
@@ -9216,8 +9897,8 @@ function createGraphLoopHarness(options) {
9216
9897
  signal: options.signal ?? options.toolContext.abortSignal,
9217
9898
  executorLocal
9218
9899
  };
9219
- await executor.prime(options.conversationId, local, "user");
9220
- const result = await executor.runUntilYield(options.conversationId);
9900
+ await executor.prime(checkpointKey, local, "user");
9901
+ const result = await executor.runUntilYield(checkpointKey);
9221
9902
  return {
9222
9903
  checkpointNodeId: result.checkpoint.nodeId,
9223
9904
  stepCount: result.stepCount
@@ -9560,6 +10241,7 @@ async function emitRunEvent(event, sink) {
9560
10241
  async function runAgent(agent, options) {
9561
10242
  const modelId = resolveModelId(agent, options);
9562
10243
  const conversationId = options.conversationId ?? `conv_${Date.now()}`;
10244
+ const checkpointKey = conversationId;
9563
10245
  const runId = options.runId ?? generateRunId();
9564
10246
  const turnId = runId;
9565
10247
  const costCollector = new QuickstartRunCostCollector();
@@ -9614,7 +10296,7 @@ async function runAgent(agent, options) {
9614
10296
  };
9615
10297
  await handle.markRunning({ currentNode: "user" });
9616
10298
  try {
9617
- await executor.prime(conversationId, {
10299
+ await executor.prime(checkpointKey, {
9618
10300
  conversationId,
9619
10301
  turnId,
9620
10302
  request: {
@@ -9639,7 +10321,7 @@ async function runAgent(agent, options) {
9639
10321
  return void 0;
9640
10322
  }
9641
10323
  });
9642
- const result = await executor.runUntilYield(conversationId);
10324
+ const result = await executor.runUntilYield(checkpointKey);
9643
10325
  runtimeEvents.push(...result.events);
9644
10326
  for (const event of result.events) {
9645
10327
  if (event.type === "final_answer_chunk") continue;