@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/testkit.cjs CHANGED
@@ -106,7 +106,11 @@ __export(runtime_kernel_exports, {
106
106
  ToolNode: () => ToolNode,
107
107
  UserNode: () => UserNode,
108
108
  WaitUserNode: () => WaitUserNode,
109
+ addLedgerAggregate: () => addLedgerAggregate,
110
+ addUsageTotals: () => addUsageTotals,
109
111
  agentHasToolTrigger: () => agentHasToolTrigger,
112
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
113
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
110
114
  appendStreamingProviderReasoningDetails: () => appendStreamingProviderReasoningDetails,
111
115
  applySystemReminders: () => applySystemReminders,
112
116
  audit: () => audit_exports,
@@ -115,20 +119,25 @@ __export(runtime_kernel_exports, {
115
119
  childRuns: () => child_runs_exports,
116
120
  compactProviderReasoningDetails: () => compactProviderReasoningDetails,
117
121
  compactReasoningDetailsInValue: () => compactReasoningDetailsInValue,
122
+ computeCost: () => computeCost,
118
123
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
119
124
  consoleAudit: () => consoleAudit,
120
125
  contextBudgetWarningTemplate: () => contextBudgetWarningTemplate,
126
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
121
127
  countToolCallsInCurrentRequest: () => countToolCallsInCurrentRequest,
122
128
  createCompositeAudit: () => createCompositeAudit,
123
129
  createConsoleAudit: () => createConsoleAudit,
124
130
  createContextCheckpointTool: () => createContextCheckpointTool,
131
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
125
132
  createDefaultGraphExecutor: () => createDefaultGraphExecutor,
126
133
  createDefaultSystemReminderRegistry: () => createDefaultSystemReminderRegistry,
127
134
  createDefaultTokenizerPort: () => createDefaultTokenizerPort,
128
135
  createEventStoreAudit: () => createEventStoreAudit,
129
136
  createFileAudit: () => createFileAudit,
130
137
  createGraphLoopHarness: () => createGraphLoopHarness,
138
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
131
139
  createMonotonicEventIdFactory: () => createMonotonicEventIdFactory,
140
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate,
132
141
  createSystemReminderRules: () => createSystemReminderRules,
133
142
  defaultPolicyEngine: () => defaultPolicyEngine,
134
143
  defaultSystemReminderRegistry: () => defaultSystemReminderRegistry,
@@ -165,6 +174,7 @@ __export(runtime_kernel_exports, {
165
174
  systemReminder: () => system_reminder_exports,
166
175
  telemetry: () => telemetry_exports,
167
176
  toDisplayStep: () => toDisplayStep,
177
+ tokenAccounting: () => token_accounting_exports,
168
178
  toolCallStreakTemplate: () => toolCallStreakTemplate,
169
179
  toolCallStreakTrigger: () => toolCallStreakTrigger,
170
180
  tools: () => tools_exports
@@ -199,6 +209,7 @@ var Logger = class {
199
209
  constructor(moduleName) {
200
210
  this.moduleName = moduleName;
201
211
  }
212
+ moduleName;
202
213
  debug(message, data) {
203
214
  this.log(0 /* DEBUG */, "debug", message, data);
204
215
  }
@@ -297,6 +308,12 @@ zod.z.object({
297
308
  args: zod.z.record(zod.z.unknown()).optional(),
298
309
  tool_call_id: zod.z.string()
299
310
  });
311
+ var ObservationTruncationMeta = zod.z.object({
312
+ originalChars: zod.z.number().int().nonnegative(),
313
+ previewChars: zod.z.number().int().nonnegative(),
314
+ originalLines: zod.z.number().int().nonnegative().optional(),
315
+ previewLines: zod.z.number().int().nonnegative().optional()
316
+ });
300
317
  var ImageInfoMeta = zod.z.object({
301
318
  url: zod.z.string().optional(),
302
319
  width: zod.z.number().int().positive().optional(),
@@ -328,6 +345,7 @@ var PersistentMetadata = zod.z.object({
328
345
  tool_name: zod.z.string().optional(),
329
346
  args: zod.z.record(zod.z.unknown()).optional(),
330
347
  tool_call_id: zod.z.string().optional(),
348
+ observationTruncation: ObservationTruncationMeta.optional(),
331
349
  raw_output: zod.z.string().optional(),
332
350
  image_info: ImageInfoMeta.optional(),
333
351
  taskType: zod.z.string().optional(),
@@ -421,6 +439,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
421
439
  });
422
440
  var AgentSpecToolHistoryPolicy = zod.z.object({
423
441
  strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
442
+ retentionMode: zod.z.enum(["drop", "compress"]).optional(),
424
443
  keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
425
444
  keepLatestRuns: zod.z.number().int().nonnegative().optional(),
426
445
  maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
@@ -473,7 +492,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
473
492
  var AgentSpecTokenEstimationPolicy = zod.z.object({
474
493
  encoding: zod.z.string().min(1).optional(),
475
494
  avgCharsPerToken: zod.z.number().positive().optional(),
476
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
495
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
496
+ calibration: zod.z.object({
497
+ enabled: zod.z.boolean().optional(),
498
+ minSamples: zod.z.number().int().positive().optional(),
499
+ minCoefficient: zod.z.number().positive().optional(),
500
+ maxCoefficient: zod.z.number().positive().optional()
501
+ }).optional(),
502
+ remoteCount: zod.z.object({
503
+ enabled: zod.z.boolean().optional(),
504
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
505
+ }).optional()
477
506
  });
478
507
  var AgentSpecSystemReminderTrigger = zod.z.object({
479
508
  kind: zod.z.string().min(1),
@@ -1171,12 +1200,206 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1171
1200
  error,
1172
1201
  ...options
1173
1202
  });
1203
+ var TokenCountSource = zod.z.enum([
1204
+ "local-estimate",
1205
+ "provider-preflight-count",
1206
+ "provider-response-usage",
1207
+ "host-supplied",
1208
+ "test-fixture"
1209
+ ]);
1210
+ var TokenCountConfidence = zod.z.enum([
1211
+ "estimate",
1212
+ "provider-estimate",
1213
+ "actual"
1214
+ ]);
1215
+ var TokenRouteCapabilities = zod.z.object({
1216
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1217
+ supportsResponseUsage: zod.z.boolean().optional(),
1218
+ supportsImageInput: zod.z.boolean().optional(),
1219
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1220
+ supportsReasoningTokens: zod.z.boolean().optional()
1221
+ });
1222
+ var TokenRoute = zod.z.object({
1223
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1224
+ baseURL: zod.z.string().optional().describe("\u4E2D\u8F6C\u5E73\u53F0\u6216\u79C1\u6709 endpoint\uFF1B\u7528\u4E8E\u533A\u5206\u540C\u540D\u6A21\u578B\u7684\u4E0D\u540C route"),
1225
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1226
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1227
+ capabilities: TokenRouteCapabilities.optional()
1228
+ });
1229
+ var tokenCount = zod.z.number().int().nonnegative();
1230
+ var CanonicalLlmUsage = zod.z.object({
1231
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1232
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1233
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1234
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1235
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1236
+ totalTokens: tokenCount.optional().describe("provider \u62A5\u544A\u7684\u603B\u91CF\uFF1B\u53EF\u7F3A\u5931\uFF0C\u4E14\u4E0D\u4FDD\u8BC1\u7B49\u4E8E\u5404\u9879\u4E4B\u548C"),
1237
+ source: TokenCountSource,
1238
+ confidence: TokenCountConfidence,
1239
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1240
+ });
1241
+ var tokenCount2 = zod.z.number().int().nonnegative();
1242
+ var tokenPrice = zod.z.number().finite().nonnegative();
1243
+ zod.z.enum([
1244
+ "llm-usage",
1245
+ "context-component"
1246
+ ]);
1247
+ var ContextTokenComponentKind = zod.z.enum([
1248
+ "system",
1249
+ "user",
1250
+ "assistant",
1251
+ "tool",
1252
+ "context-injection",
1253
+ "history-summary",
1254
+ "working-memory",
1255
+ "fence",
1256
+ "system-reminder",
1257
+ "other"
1258
+ ]);
1259
+ var TokenUsageTotals = zod.z.object({
1260
+ inputTokens: tokenCount2,
1261
+ outputTokens: tokenCount2,
1262
+ reasoningTokens: tokenCount2.optional(),
1263
+ cacheReadTokens: tokenCount2.optional(),
1264
+ cacheWriteTokens: tokenCount2.optional(),
1265
+ totalTokens: tokenCount2.optional(),
1266
+ usageCount: zod.z.number().int().nonnegative()
1267
+ });
1268
+ var ContextTokenComponent = zod.z.object({
1269
+ componentId: zod.z.string().min(1),
1270
+ kind: ContextTokenComponentKind,
1271
+ tokens: tokenCount2,
1272
+ source: TokenCountSource,
1273
+ confidence: TokenCountConfidence,
1274
+ label: zod.z.string().optional(),
1275
+ messageId: zod.z.string().optional(),
1276
+ role: zod.z.string().optional(),
1277
+ action: zod.z.string().optional(),
1278
+ kept: zod.z.boolean().optional(),
1279
+ truncatedAtExecution: zod.z.boolean().optional(),
1280
+ originalTokensEstimate: tokenCount2.optional(),
1281
+ droppedTokensEstimate: tokenCount2.optional()
1282
+ });
1283
+ var TokenLedgerEntryBase = zod.z.object({
1284
+ id: zod.z.string().min(1),
1285
+ runId: zod.z.string().optional(),
1286
+ parentRunId: zod.z.string().optional(),
1287
+ conversationId: zod.z.string().optional(),
1288
+ turnId: zod.z.string().optional(),
1289
+ stepId: zod.z.string().optional(),
1290
+ route: TokenRoute.optional(),
1291
+ createdAt: zod.z.number().int().nonnegative().optional()
1292
+ });
1293
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1294
+ kind: zod.z.literal("llm-usage"),
1295
+ modelId: zod.z.string().optional(),
1296
+ usage: CanonicalLlmUsage
1297
+ });
1298
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1299
+ kind: zod.z.literal("context-component"),
1300
+ components: zod.z.array(ContextTokenComponent),
1301
+ totalTokens: tokenCount2
1302
+ });
1303
+ zod.z.discriminatedUnion("kind", [
1304
+ LlmUsageTokenLedgerEntry,
1305
+ ContextComponentTokenLedgerEntry
1306
+ ]);
1307
+ var TokenLedgerAggregate = zod.z.object({
1308
+ llmUsage: TokenUsageTotals.optional(),
1309
+ contextTokens: tokenCount2,
1310
+ entryCount: zod.z.number().int().nonnegative(),
1311
+ llmCallCount: zod.z.number().int().nonnegative(),
1312
+ contextComponentCount: zod.z.number().int().nonnegative()
1313
+ });
1314
+ zod.z.object({
1315
+ /**
1316
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1317
+ */
1318
+ own: TokenLedgerAggregate,
1319
+ children: TokenLedgerAggregate.optional()
1320
+ });
1321
+ var TokenCostComponent = zod.z.enum([
1322
+ "input",
1323
+ "output",
1324
+ "reasoning",
1325
+ "cacheRead",
1326
+ "cacheWrite"
1327
+ ]);
1328
+ zod.z.object({
1329
+ currency: zod.z.string().min(1),
1330
+ unit: zod.z.literal("per_1m_tokens"),
1331
+ input: tokenPrice.optional(),
1332
+ output: tokenPrice.optional(),
1333
+ reasoning: tokenPrice.optional(),
1334
+ cacheRead: tokenPrice.optional(),
1335
+ cacheWrite: tokenPrice.optional()
1336
+ });
1337
+ zod.z.object({
1338
+ status: zod.z.enum(["computed", "unknown"]),
1339
+ currency: zod.z.string().optional(),
1340
+ inputCost: tokenPrice.optional(),
1341
+ outputCost: tokenPrice.optional(),
1342
+ reasoningCost: tokenPrice.optional(),
1343
+ cacheReadCost: tokenPrice.optional(),
1344
+ cacheWriteCost: tokenPrice.optional(),
1345
+ totalCost: tokenPrice.optional(),
1346
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1347
+ });
1348
+ var tokenCount3 = zod.z.number().int().nonnegative();
1349
+ var actualCalibrationSource = zod.z.enum([
1350
+ "provider-response-usage",
1351
+ "host-supplied",
1352
+ "test-fixture"
1353
+ ]);
1354
+ zod.z.object({
1355
+ route: TokenRoute,
1356
+ localEstimateTokens: tokenCount3,
1357
+ actualInputTokens: tokenCount3,
1358
+ source: actualCalibrationSource,
1359
+ confidence: zod.z.literal("actual"),
1360
+ observedAt: zod.z.number().int().nonnegative().optional(),
1361
+ runId: zod.z.string().optional(),
1362
+ ledgerEntryId: zod.z.string().optional()
1363
+ });
1364
+ zod.z.object({
1365
+ enabled: zod.z.boolean(),
1366
+ applied: zod.z.boolean(),
1367
+ route: TokenRoute.optional(),
1368
+ sampleCount: zod.z.number().int().nonnegative(),
1369
+ coefficient: zod.z.number().positive().optional(),
1370
+ minSamples: zod.z.number().int().positive().optional(),
1371
+ minCoefficient: zod.z.number().positive().optional(),
1372
+ maxCoefficient: zod.z.number().positive().optional(),
1373
+ localEstimateTokens: tokenCount3.optional(),
1374
+ calibratedEstimateTokens: tokenCount3.optional(),
1375
+ deltaTokens: zod.z.number().int().optional(),
1376
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1377
+ });
1378
+ zod.z.object({
1379
+ route: TokenRoute.optional(),
1380
+ localEstimateTokens: tokenCount3,
1381
+ calibratedEstimateTokens: tokenCount3,
1382
+ finalTokens: tokenCount3,
1383
+ source: zod.z.literal("local-estimate"),
1384
+ confidence: zod.z.literal("estimate")
1385
+ });
1174
1386
 
1175
1387
  // src/runtime-kernel/graph-engine/engine.ts
1176
1388
  var logger = new Logger("GraphExecutor");
1177
1389
  function asLocalRecord(local) {
1178
1390
  return local && typeof local === "object" ? { ...local } : {};
1179
1391
  }
1392
+ function readNonEmptyString(value) {
1393
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1394
+ }
1395
+ function readRuntimeConversationId(state) {
1396
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1397
+ return readNonEmptyString(local?.conversationId);
1398
+ }
1399
+ function readRuntimeTurnId(state) {
1400
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1401
+ return readNonEmptyString(local?.turnId);
1402
+ }
1180
1403
  var GraphExecutor = class {
1181
1404
  constructor(checkpointer, config = {}) {
1182
1405
  this.checkpointer = checkpointer;
@@ -1186,6 +1409,7 @@ var GraphExecutor = class {
1186
1409
  };
1187
1410
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1188
1411
  }
1412
+ checkpointer;
1189
1413
  nodes = /* @__PURE__ */ new Map();
1190
1414
  ephemeralLocals = /* @__PURE__ */ new Map();
1191
1415
  config;
@@ -1193,8 +1417,8 @@ var GraphExecutor = class {
1193
1417
  registerNode(node) {
1194
1418
  this.nodes.set(node.id, node);
1195
1419
  }
1196
- async peekCheckpoint(conversationId) {
1197
- return await this.checkpointer.load(conversationId);
1420
+ async peekCheckpoint(checkpointKey) {
1421
+ return await this.checkpointer.load(checkpointKey);
1198
1422
  }
1199
1423
  sanitize(state) {
1200
1424
  const local = asLocalRecord(state.local);
@@ -1206,8 +1430,8 @@ var GraphExecutor = class {
1206
1430
  local
1207
1431
  };
1208
1432
  }
1209
- async prime(conversationId, local, nodeId = "user") {
1210
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1433
+ async prime(checkpointKey, local, nodeId = "user") {
1434
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1211
1435
  const localSansMemory = { ...local || {} };
1212
1436
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1213
1437
  const state = {
@@ -1215,10 +1439,10 @@ var GraphExecutor = class {
1215
1439
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1216
1440
  local: localSansMemory
1217
1441
  };
1218
- await this.checkpointer.save(conversationId, state);
1442
+ await this.checkpointer.save(checkpointKey, state);
1219
1443
  }
1220
- async setNode(conversationId, nodeId, localPatch) {
1221
- const current = await this.checkpointer.load(conversationId) || {
1444
+ async setNode(checkpointKey, nodeId, localPatch) {
1445
+ const current = await this.checkpointer.load(checkpointKey) || {
1222
1446
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1223
1447
  local: {}
1224
1448
  };
@@ -1229,19 +1453,46 @@ var GraphExecutor = class {
1229
1453
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1230
1454
  local: mergedLocal
1231
1455
  };
1232
- await this.checkpointer.save(conversationId, next);
1456
+ await this.checkpointer.save(checkpointKey, next);
1233
1457
  }
1234
- async runUntilYield(conversationId) {
1458
+ async runUntilYield(checkpointKey) {
1235
1459
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1236
1460
  let lifecyclePhase = "completed";
1461
+ let initialState = null;
1462
+ try {
1463
+ initialState = await this.loadInitialState(checkpointKey);
1464
+ } catch (err) {
1465
+ lifecyclePhase = "failed";
1466
+ this.telemetryPort.emit({
1467
+ kind: "run_lifecycle",
1468
+ runId,
1469
+ phase: "spawned",
1470
+ scope: {}
1471
+ });
1472
+ this.telemetryPort.emit({
1473
+ kind: "run_lifecycle",
1474
+ runId,
1475
+ phase: lifecyclePhase,
1476
+ scope: {}
1477
+ });
1478
+ throw err;
1479
+ }
1480
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1481
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1237
1482
  this.telemetryPort.emit({
1238
1483
  kind: "run_lifecycle",
1239
1484
  runId,
1240
1485
  phase: "spawned",
1241
- scope: { conversationId: conversationId || void 0 }
1486
+ scope: {
1487
+ conversationId: lifecycleConversationId,
1488
+ turnId: lifecycleTurnId
1489
+ }
1242
1490
  });
1243
1491
  try {
1244
- return await this.runUntilYieldInternal(conversationId);
1492
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1493
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1494
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1495
+ return result;
1245
1496
  } catch (err) {
1246
1497
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1247
1498
  throw err;
@@ -1250,17 +1501,23 @@ var GraphExecutor = class {
1250
1501
  kind: "run_lifecycle",
1251
1502
  runId,
1252
1503
  phase: lifecyclePhase,
1253
- scope: { conversationId: conversationId || void 0 }
1504
+ scope: {
1505
+ conversationId: lifecycleConversationId,
1506
+ turnId: lifecycleTurnId
1507
+ }
1254
1508
  });
1255
1509
  }
1256
1510
  }
1257
- async runUntilYieldInternal(conversationId) {
1258
- let state = await this.checkpointer.load(conversationId) || {
1511
+ async loadInitialState(checkpointKey) {
1512
+ return await this.checkpointer.load(checkpointKey) || {
1259
1513
  nodeId: "user",
1260
1514
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1261
1515
  local: {}
1262
1516
  };
1263
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1517
+ }
1518
+ async runUntilYieldInternal(checkpointKey, initialState) {
1519
+ let state = initialState;
1520
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1264
1521
  state = {
1265
1522
  ...state,
1266
1523
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1289,7 +1546,7 @@ var GraphExecutor = class {
1289
1546
  const signalRaw = state.local?.signal;
1290
1547
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1291
1548
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1292
- this.ephemeralLocals.delete(conversationId);
1549
+ this.ephemeralLocals.delete(checkpointKey);
1293
1550
  throwAbortError();
1294
1551
  }
1295
1552
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1337,8 +1594,8 @@ var GraphExecutor = class {
1337
1594
  checkpointCount
1338
1595
  });
1339
1596
  const cp2 = this.sanitize(state);
1340
- await this.checkpointer.save(conversationId, cp2);
1341
- this.ephemeralLocals.delete(conversationId);
1597
+ await this.checkpointer.save(checkpointKey, cp2);
1598
+ this.ephemeralLocals.delete(checkpointKey);
1342
1599
  return { events: allEvents, checkpoint: cp2, stepCount };
1343
1600
  }
1344
1601
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1349,18 +1606,18 @@ var GraphExecutor = class {
1349
1606
  });
1350
1607
  const nodeRunStartedAt = Date.now();
1351
1608
  const nodeIdForTelemetry = state.nodeId;
1609
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1352
1610
  let result;
1353
1611
  try {
1354
1612
  result = await node.run(state);
1355
1613
  } finally {
1356
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1357
1614
  this.telemetryPort.emit({
1358
1615
  kind: "graph_node",
1359
1616
  nodeId: nodeIdForTelemetry,
1360
1617
  durationMs: Date.now() - nodeRunStartedAt,
1361
1618
  scope: {
1362
- conversationId: conversationId || void 0,
1363
- turnId: turnIdForTelemetry
1619
+ conversationId: conversationIdForTelemetry,
1620
+ turnId: readRuntimeTurnId(state)
1364
1621
  }
1365
1622
  });
1366
1623
  }
@@ -1399,7 +1656,7 @@ var GraphExecutor = class {
1399
1656
  });
1400
1657
  state = { ...state, nodeId: nextNodeId };
1401
1658
  const cp2 = this.sanitize(state);
1402
- await this.checkpointer.save(conversationId, cp2);
1659
+ await this.checkpointer.save(checkpointKey, cp2);
1403
1660
  continue;
1404
1661
  }
1405
1662
  if (result.kind === "yield") {
@@ -1410,7 +1667,7 @@ var GraphExecutor = class {
1410
1667
  checkpointCount
1411
1668
  });
1412
1669
  const cp2 = this.sanitize(state);
1413
- await this.checkpointer.save(conversationId, cp2);
1670
+ await this.checkpointer.save(checkpointKey, cp2);
1414
1671
  return { events: allEvents, checkpoint: cp2, stepCount };
1415
1672
  }
1416
1673
  if (result.kind === "pause") {
@@ -1421,7 +1678,7 @@ var GraphExecutor = class {
1421
1678
  checkpointCount
1422
1679
  });
1423
1680
  const cp2 = this.sanitize(state);
1424
- await this.checkpointer.save(conversationId, cp2);
1681
+ await this.checkpointer.save(checkpointKey, cp2);
1425
1682
  return { events: allEvents, checkpoint: cp2, stepCount };
1426
1683
  }
1427
1684
  }
@@ -1432,8 +1689,8 @@ var GraphExecutor = class {
1432
1689
  checkpointCount
1433
1690
  });
1434
1691
  const cp = this.sanitize(state);
1435
- await this.checkpointer.save(conversationId, cp);
1436
- this.ephemeralLocals.delete(conversationId);
1692
+ await this.checkpointer.save(checkpointKey, cp);
1693
+ this.ephemeralLocals.delete(checkpointKey);
1437
1694
  return { events: allEvents, checkpoint: cp, stepCount };
1438
1695
  }
1439
1696
  };
@@ -1529,6 +1786,190 @@ var noopAudit = {
1529
1786
  flush() {
1530
1787
  }
1531
1788
  };
1789
+ var TokenCalculator = class {
1790
+ static BYTES_PER_TOKEN_LATIN = 4;
1791
+ static BYTES_PER_TOKEN_CJK = 3;
1792
+ static OVERHEAD_PER_MESSAGE = 5;
1793
+ static OVERHEAD_PER_TOOL_CALL = 10;
1794
+ static encoderCache = /* @__PURE__ */ new Map();
1795
+ static DEFAULT_ENCODING = "cl100k_base";
1796
+ static SUPPORTED_ENCODINGS = [
1797
+ "gpt2",
1798
+ "r50k_base",
1799
+ "p50k_base",
1800
+ "p50k_edit",
1801
+ "cl100k_base",
1802
+ "o200k_base"
1803
+ ];
1804
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1805
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1806
+ if (this.isSupportedEncodingName(normalized)) {
1807
+ return normalized;
1808
+ }
1809
+ if (normalized.includes("deepseek")) {
1810
+ return "cl100k_base";
1811
+ }
1812
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1813
+ return "o200k_base";
1814
+ }
1815
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1816
+ return "cl100k_base";
1817
+ }
1818
+ return this.DEFAULT_ENCODING;
1819
+ }
1820
+ static isSupportedEncodingName(value) {
1821
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1822
+ }
1823
+ static getEncoder(modelIdentifierOrEncoding) {
1824
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1825
+ const cached = this.encoderCache.get(encodingName);
1826
+ if (cached) {
1827
+ return cached;
1828
+ }
1829
+ const encoder = tiktoken.get_encoding(encodingName);
1830
+ this.encoderCache.set(encodingName, encoder);
1831
+ return encoder;
1832
+ }
1833
+ static estimateTokensRough(text, _modelIdentifier) {
1834
+ if (!text) return 0;
1835
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1836
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1837
+ const byteLength = new TextEncoder().encode(text).length;
1838
+ return Math.ceil(byteLength / ratio);
1839
+ }
1840
+ static estimateTokens(text, options = {}) {
1841
+ if (!text) return 0;
1842
+ if (options.encoding) {
1843
+ try {
1844
+ return this.estimateTokensPrecise(text, options.encoding);
1845
+ } catch {
1846
+ }
1847
+ }
1848
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1849
+ return Math.ceil(text.length / avgCharsPerToken);
1850
+ }
1851
+ static estimateTokensPrecise(text, modelIdentifier) {
1852
+ if (!text) return 0;
1853
+ const encoder = this.getEncoder(modelIdentifier);
1854
+ return encoder.encode(text).length;
1855
+ }
1856
+ static estimateMessageTokens(message, options = {}) {
1857
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1858
+ if (message.content) {
1859
+ totalTokens += this.estimateTokens(String(message.content), options);
1860
+ }
1861
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1862
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1863
+ for (const toolCall of toolCalls) {
1864
+ totalTokens += toolCallOverhead;
1865
+ const fn = toolCall["function"];
1866
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1867
+ const fnRecord = fn;
1868
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1869
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1870
+ }
1871
+ }
1872
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1873
+ if (toolCallId) {
1874
+ totalTokens += this.estimateTokens(toolCallId, options);
1875
+ }
1876
+ return totalTokens;
1877
+ }
1878
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1879
+ return this.estimateMessageTokens(message, {
1880
+ encoding: modelIdentifier,
1881
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1882
+ });
1883
+ }
1884
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1885
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1886
+ }
1887
+ static extractToolCallsForTokenEstimate(message) {
1888
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1889
+ if (Array.isArray(direct)) return direct;
1890
+ const metadata = "metadata" in message ? message.metadata : void 0;
1891
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1892
+ const metadataRecord = metadata;
1893
+ const metadataToolCalls = metadataRecord["tool_calls"];
1894
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1895
+ }
1896
+ static extractToolCallIdForTokenEstimate(message) {
1897
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1898
+ return message.tool_call_id;
1899
+ }
1900
+ const metadata = "metadata" in message ? message.metadata : void 0;
1901
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1902
+ const metadataRecord = metadata;
1903
+ const toolCallId = metadataRecord["tool_call_id"];
1904
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1905
+ }
1906
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1907
+ if (!text || maxTokens <= 0) return "";
1908
+ const encoder = this.getEncoder(modelIdentifier);
1909
+ const tokens = encoder.encode(text);
1910
+ if (tokens.length <= maxTokens) {
1911
+ return text;
1912
+ }
1913
+ let truncatedTokens;
1914
+ const ellipsis = "...";
1915
+ switch (strategy) {
1916
+ case "start":
1917
+ truncatedTokens = tokens.slice(0, maxTokens);
1918
+ return encoder.decode(truncatedTokens) + ellipsis;
1919
+ case "end":
1920
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1921
+ return ellipsis + encoder.decode(truncatedTokens);
1922
+ case "middle": {
1923
+ const half = Math.floor(maxTokens / 2);
1924
+ const head = tokens.slice(0, half);
1925
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1926
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1927
+ }
1928
+ default:
1929
+ truncatedTokens = tokens.slice(0, maxTokens);
1930
+ return encoder.decode(truncatedTokens) + ellipsis;
1931
+ }
1932
+ }
1933
+ static cleanup() {
1934
+ for (const encoder of this.encoderCache.values()) {
1935
+ encoder.free();
1936
+ }
1937
+ this.encoderCache.clear();
1938
+ }
1939
+ };
1940
+ function normalizePositiveNumber(value, fallback) {
1941
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1942
+ }
1943
+ function normalizeNonNegativeInteger(value, fallback) {
1944
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1945
+ return fallback;
1946
+ }
1947
+ return Math.max(0, Math.floor(value));
1948
+ }
1949
+
1950
+ // src/shared/defaultTokenizerPort.ts
1951
+ var DefaultTokenizerPort = class {
1952
+ constructor(config = {}) {
1953
+ this.config = config;
1954
+ }
1955
+ config;
1956
+ estimateText(text, _modelId) {
1957
+ return TokenCalculator.estimateTokens(text, {
1958
+ encoding: this.config.encoding,
1959
+ avgCharsPerToken: this.config.avgCharsPerToken
1960
+ });
1961
+ }
1962
+ estimateMessage(message, _modelId) {
1963
+ return TokenCalculator.estimateMessageTokens(message, {
1964
+ encoding: this.config.encoding,
1965
+ avgCharsPerToken: this.config.avgCharsPerToken,
1966
+ toolCallOverhead: this.config.toolCallOverhead
1967
+ });
1968
+ }
1969
+ };
1970
+ function createDefaultTokenizerPort(config = {}) {
1971
+ return new DefaultTokenizerPort(config);
1972
+ }
1532
1973
 
1533
1974
  // src/shared/ids.ts
1534
1975
  function isoRandomUUID() {
@@ -1630,15 +2071,15 @@ function splitConcatenatedJsonObjects(input) {
1630
2071
  }
1631
2072
 
1632
2073
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1633
- function readNonEmptyString(value) {
2074
+ function readNonEmptyString2(value) {
1634
2075
  if (typeof value !== "string") return void 0;
1635
2076
  const trimmed = value.trim();
1636
2077
  return trimmed.length > 0 ? trimmed : void 0;
1637
2078
  }
1638
2079
  function resolveConversationIdForRuntimeEvents(toolContext) {
1639
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
2080
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
1640
2081
  if (fromCamel) return fromCamel;
1641
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
2082
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
1642
2083
  if (fromSnake) return fromSnake;
1643
2084
  return generateMessageId();
1644
2085
  }
@@ -1709,6 +2150,13 @@ function resolveUsage(response) {
1709
2150
  }
1710
2151
  return response.usage;
1711
2152
  }
2153
+ function resolveCanonicalUsage(response) {
2154
+ if (!response || typeof response === "string") {
2155
+ return void 0;
2156
+ }
2157
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2158
+ return parsed.success ? parsed.data : void 0;
2159
+ }
1712
2160
  function resolveToolCalls(response) {
1713
2161
  if (!response || typeof response === "string") {
1714
2162
  return void 0;
@@ -1740,206 +2188,79 @@ function recordRunTranscript(params) {
1740
2188
 
1741
2189
  // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
1742
2190
  var contextAuditMiddleware = async (ctx, stage, next) => {
1743
- if (stage.id === "build_context") {
1744
- recordBeforeContextManager({
1745
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
1746
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1747
- });
1748
- }
1749
- await next();
1750
- if (stage.id !== "apply_system_reminder") {
1751
- return;
1752
- }
1753
- resolveToolNamesForAudit(ctx);
1754
- recordAfterContextManager({
1755
- mode: ctx.mode,
1756
- llmMessages: ctx.llmMessages,
1757
- contextTrace: ctx.contextTrace
1758
- });
1759
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
1760
- recordAfterContextManagerOnSystemReminderHit({
1761
- mode: ctx.mode,
1762
- llmMessages: ctx.llmMessages,
1763
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
1764
- contextTrace: ctx.contextTrace
1765
- });
1766
- }
1767
- };
1768
- var TokenCalculator = class {
1769
- static BYTES_PER_TOKEN_LATIN = 4;
1770
- static BYTES_PER_TOKEN_CJK = 3;
1771
- static OVERHEAD_PER_MESSAGE = 5;
1772
- static OVERHEAD_PER_TOOL_CALL = 10;
1773
- static encoderCache = /* @__PURE__ */ new Map();
1774
- static DEFAULT_ENCODING = "cl100k_base";
1775
- static SUPPORTED_ENCODINGS = [
1776
- "gpt2",
1777
- "r50k_base",
1778
- "p50k_base",
1779
- "p50k_edit",
1780
- "cl100k_base",
1781
- "o200k_base"
1782
- ];
1783
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1784
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1785
- if (this.isSupportedEncodingName(normalized)) {
1786
- return normalized;
1787
- }
1788
- if (normalized.includes("deepseek")) {
1789
- return "cl100k_base";
1790
- }
1791
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1792
- return "o200k_base";
1793
- }
1794
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1795
- return "cl100k_base";
1796
- }
1797
- return this.DEFAULT_ENCODING;
1798
- }
1799
- static isSupportedEncodingName(value) {
1800
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1801
- }
1802
- static getEncoder(modelIdentifierOrEncoding) {
1803
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1804
- const cached = this.encoderCache.get(encodingName);
1805
- if (cached) {
1806
- return cached;
1807
- }
1808
- const encoder = tiktoken.get_encoding(encodingName);
1809
- this.encoderCache.set(encodingName, encoder);
1810
- return encoder;
1811
- }
1812
- static estimateTokensRough(text, _modelIdentifier) {
1813
- if (!text) return 0;
1814
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1815
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1816
- const byteLength = new TextEncoder().encode(text).length;
1817
- return Math.ceil(byteLength / ratio);
1818
- }
1819
- static estimateTokens(text, options = {}) {
1820
- if (!text) return 0;
1821
- if (options.encoding) {
1822
- try {
1823
- return this.estimateTokensPrecise(text, options.encoding);
1824
- } catch {
1825
- }
1826
- }
1827
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1828
- return Math.ceil(text.length / avgCharsPerToken);
1829
- }
1830
- static estimateTokensPrecise(text, modelIdentifier) {
1831
- if (!text) return 0;
1832
- const encoder = this.getEncoder(modelIdentifier);
1833
- return encoder.encode(text).length;
1834
- }
1835
- static estimateMessageTokens(message, options = {}) {
1836
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1837
- if (message.content) {
1838
- totalTokens += this.estimateTokens(String(message.content), options);
1839
- }
1840
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1841
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1842
- for (const toolCall of toolCalls) {
1843
- totalTokens += toolCallOverhead;
1844
- const fn = toolCall["function"];
1845
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1846
- const fnRecord = fn;
1847
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1848
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1849
- }
1850
- }
1851
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1852
- if (toolCallId) {
1853
- totalTokens += this.estimateTokens(toolCallId, options);
1854
- }
1855
- return totalTokens;
1856
- }
1857
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1858
- return this.estimateMessageTokens(message, {
1859
- encoding: modelIdentifier,
1860
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
2191
+ if (stage.id === "build_context") {
2192
+ recordBeforeContextManager({
2193
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2194
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1861
2195
  });
1862
2196
  }
1863
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1864
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1865
- }
1866
- static extractToolCallsForTokenEstimate(message) {
1867
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1868
- if (Array.isArray(direct)) return direct;
1869
- const metadata = "metadata" in message ? message.metadata : void 0;
1870
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1871
- const metadataRecord = metadata;
1872
- const metadataToolCalls = metadataRecord["tool_calls"];
1873
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1874
- }
1875
- static extractToolCallIdForTokenEstimate(message) {
1876
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1877
- return message.tool_call_id;
1878
- }
1879
- const metadata = "metadata" in message ? message.metadata : void 0;
1880
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1881
- const metadataRecord = metadata;
1882
- const toolCallId = metadataRecord["tool_call_id"];
1883
- return typeof toolCallId === "string" ? toolCallId : void 0;
1884
- }
1885
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1886
- if (!text || maxTokens <= 0) return "";
1887
- const encoder = this.getEncoder(modelIdentifier);
1888
- const tokens = encoder.encode(text);
1889
- if (tokens.length <= maxTokens) {
1890
- return text;
1891
- }
1892
- let truncatedTokens;
1893
- const ellipsis = "...";
1894
- switch (strategy) {
1895
- case "start":
1896
- truncatedTokens = tokens.slice(0, maxTokens);
1897
- return encoder.decode(truncatedTokens) + ellipsis;
1898
- case "end":
1899
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1900
- return ellipsis + encoder.decode(truncatedTokens);
1901
- case "middle": {
1902
- const half = Math.floor(maxTokens / 2);
1903
- const head = tokens.slice(0, half);
1904
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1905
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1906
- }
1907
- default:
1908
- truncatedTokens = tokens.slice(0, maxTokens);
1909
- return encoder.decode(truncatedTokens) + ellipsis;
1910
- }
2197
+ await next();
2198
+ if (stage.id !== "apply_system_reminder") {
2199
+ return;
1911
2200
  }
1912
- static cleanup() {
1913
- for (const encoder of this.encoderCache.values()) {
1914
- encoder.free();
1915
- }
1916
- this.encoderCache.clear();
2201
+ resolveToolNamesForAudit(ctx);
2202
+ recordAfterContextManager({
2203
+ mode: ctx.mode,
2204
+ llmMessages: ctx.llmMessages,
2205
+ contextTrace: ctx.contextTrace
2206
+ });
2207
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2208
+ recordAfterContextManagerOnSystemReminderHit({
2209
+ mode: ctx.mode,
2210
+ llmMessages: ctx.llmMessages,
2211
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2212
+ contextTrace: ctx.contextTrace
2213
+ });
1917
2214
  }
1918
2215
  };
1919
- function normalizePositiveNumber(value, fallback) {
1920
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2216
+ var als = new async_hooks.AsyncLocalStorage();
2217
+ function readTokenCount(record, key) {
2218
+ const value = record[key];
2219
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1921
2220
  }
1922
- function normalizeNonNegativeInteger(value, fallback) {
1923
- if (typeof value !== "number" || !Number.isFinite(value)) {
1924
- return fallback;
1925
- }
1926
- return Math.max(0, Math.floor(value));
2221
+ function readRecord(record, key) {
2222
+ const value = record[key];
2223
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2224
+ return Object.fromEntries(Object.entries(value));
1927
2225
  }
1928
- var als = new async_hooks.AsyncLocalStorage();
1929
- function normalizeLlmUsage(usage) {
2226
+ function normalizedUsageFromCanonical(canonicalUsage) {
2227
+ return {
2228
+ promptTokens: canonicalUsage.inputTokens,
2229
+ completionTokens: canonicalUsage.outputTokens,
2230
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2231
+ canonicalUsage
2232
+ };
2233
+ }
2234
+ function normalizeCanonicalLlmUsage(usage) {
1930
2235
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1931
2236
  const rec = usage;
1932
- const promptTokensRaw = rec["prompt_tokens"];
1933
- const completionTokensRaw = rec["completion_tokens"];
1934
- const totalTokensRaw = rec["total_tokens"];
1935
- const tokensRaw = rec["tokens"];
1936
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1937
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1938
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1939
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1940
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1941
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1942
- return { promptTokens, completionTokens, totalTokens };
2237
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2238
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2239
+ if (inputTokens === void 0 || outputTokens === void 0) {
2240
+ return void 0;
2241
+ }
2242
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2243
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2244
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2245
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2246
+ const totalTokens = readTokenCount(rec, "total_tokens");
2247
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2248
+ return void 0;
2249
+ }
2250
+ return {
2251
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2252
+ outputTokens,
2253
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2254
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2255
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2256
+ source: "provider-response-usage",
2257
+ confidence: "actual",
2258
+ rawUsage: usage
2259
+ };
2260
+ }
2261
+ function normalizeLlmUsage(usage) {
2262
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2263
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1943
2264
  }
1944
2265
  function recordLlmCallTelemetry(entry) {
1945
2266
  const store = als.getStore();
@@ -1953,17 +2274,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1953
2274
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1954
2275
  return;
1955
2276
  }
1956
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2277
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2278
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1957
2279
  const respText = extractResponseText(ctx.llmResp);
1958
2280
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1959
2281
  try {
1960
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1961
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1962
- return {
1963
- promptTokens,
1964
- completionTokens,
1965
- totalTokens: promptTokens + completionTokens
1966
- };
2282
+ const promptTokens = ctx.llmMessages.reduce(
2283
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2284
+ 0
2285
+ );
2286
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2287
+ return normalizedUsageFromCanonical({
2288
+ inputTokens: promptTokens,
2289
+ outputTokens: completionTokens,
2290
+ totalTokens: promptTokens + completionTokens,
2291
+ source: "local-estimate",
2292
+ confidence: "estimate"
2293
+ });
1967
2294
  } catch {
1968
2295
  return void 0;
1969
2296
  }
@@ -1973,7 +2300,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1973
2300
  stream: ctx.input.stream === true,
1974
2301
  startedAt: ctx.llmCallStartedAt,
1975
2302
  durationMs: ctx.llmCallDurationMs,
1976
- usage: normalizedUsage
2303
+ usage: normalizedUsage,
2304
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1977
2305
  });
1978
2306
  ctx.telemetry.emit({
1979
2307
  kind: "llm_call",
@@ -1981,6 +2309,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1981
2309
  stream: ctx.input.stream === true,
1982
2310
  durationMs: ctx.llmCallDurationMs,
1983
2311
  usage: normalizedUsage,
2312
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1984
2313
  scope: {
1985
2314
  conversationId: ctx.conversationId || void 0,
1986
2315
  turnId: ctx.turnId,
@@ -1997,7 +2326,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
1997
2326
  if (stage.id !== "execute_llm") {
1998
2327
  return;
1999
2328
  }
2000
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2329
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
2001
2330
  if (!normalized) {
2002
2331
  return;
2003
2332
  }
@@ -2124,10 +2453,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2124
2453
  return [
2125
2454
  `\u26A0\uFE0F \u4E0A\u4E0B\u6587\u9884\u7B97\u544A\u8B66\uFF1A\u4F60\u5DF2\u6267\u884C\u4E86 ${displayStep}/${displayMax} \u6B65\uFF0C\u4E0A\u4E0B\u6587\u7A7A\u95F4\u5373\u5C06\u8017\u5C3D\u3002`,
2126
2455
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2127
- "1. \u8C03\u7528sharedmemory_write\u5DE5\u5177\uFF0C\u5C06\u5F53\u524D\u53D1\u73B0\u3001\u603B\u7ED3\u3001\u601D\u8003\u6216\u8005\u4EFB\u4F55\u91CD\u8981\u4FE1\u606F\u8BE6\u7EC6\u5199\u5165sharedmemory\u3002",
2456
+ "1. \u5148\u786E\u8BA4\u5173\u952E\u8FDB\u5C55\u3001\u7EA6\u675F\u3001\u4E0B\u4E00\u6B65\u5DF2\u7ECF\u8FDB\u5165 TaskState\uFF1B\u5982\u679C\u6CA1\u6709\uFF0C\u8BF7\u8C03\u7528 taskstate_write \u66F4\u65B0\u3002",
2128
2457
  `2. \u8C03\u7528 ${checkpointToolName} \u5DE5\u5177\uFF0C\u4F20\u5165 summary\uFF08\u9636\u6BB5\u8FC7\u6E21\u6458\u8981\uFF09\u548C taskstate\uFF08\u6700\u65B0\u4EFB\u52A1\u72B6\u6001\uFF09\u3002`,
2129
2458
  ' \u8FD9\u4F1A\u4E00\u6B21\u6027\u5B8C\u6210"\u4FDD\u5B58\u72B6\u6001 + \u6E05\u7406\u5386\u53F2"\uFF0Ccheckpoint tool_output \u4E2D\u4F1A\u4FDD\u7559\u4F60\u7684 TaskState \u5FEB\u7167\u3002',
2130
- "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u91CD\u8981\u4FE1\u606F\u4F1A\u901A\u8FC7sharedmemory\u4FDD\u5B58\u3002"
2459
+ "3. \u6E05\u7406\u540E\u4F60\u7684\u4E0A\u4E0B\u6587\u5C06\u53EA\u4FDD\u7559\uFF1Acheckpoint \u5DE5\u5177\u5BF9\uFF08\u542B\u6458\u8981 + TaskState\uFF09+ \u6700\u8FD1 2 \u5BF9\u5DE5\u5177\u4EA4\u4E92\u3002\u9700\u8981\u957F\u671F\u4EA4\u4ED8\u7ED9\u7528\u6237\u7684\u5185\u5BB9\u8BF7\u5199\u5165 Workspace \u6587\u4EF6\u3002"
2131
2460
  ].join("\n");
2132
2461
  };
2133
2462
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2435,6 +2764,219 @@ function createApplySystemReminderStage() {
2435
2764
  };
2436
2765
  }
2437
2766
 
2767
+ // src/runtime-kernel/token-accounting/index.ts
2768
+ var token_accounting_exports = {};
2769
+ __export(token_accounting_exports, {
2770
+ addLedgerAggregate: () => addLedgerAggregate,
2771
+ addUsageTotals: () => addUsageTotals,
2772
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
2773
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
2774
+ computeCost: () => computeCost,
2775
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
2776
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
2777
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
2778
+ });
2779
+
2780
+ // src/runtime-kernel/token-accounting/functions.ts
2781
+ var EMPTY_LEDGER_AGGREGATE = {
2782
+ contextTokens: 0,
2783
+ entryCount: 0,
2784
+ llmCallCount: 0,
2785
+ contextComponentCount: 0
2786
+ };
2787
+ var TOKEN_PRICE_UNIT = 1e6;
2788
+ function sumReportedOptional(values) {
2789
+ const reported = values.filter((value) => value !== void 0);
2790
+ if (reported.length === 0) {
2791
+ return void 0;
2792
+ }
2793
+ return reported.reduce((total, value) => total + value, 0);
2794
+ }
2795
+ function sumTotalTokens(usages) {
2796
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
2797
+ return void 0;
2798
+ }
2799
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
2800
+ }
2801
+ function aggregateCanonicalUsage(usages) {
2802
+ if (usages.length === 0) {
2803
+ return void 0;
2804
+ }
2805
+ return {
2806
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
2807
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
2808
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
2809
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
2810
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
2811
+ totalTokens: sumTotalTokens(usages),
2812
+ usageCount: usages.length
2813
+ };
2814
+ }
2815
+ function createLlmUsageLedgerEntry(input) {
2816
+ return {
2817
+ ...input,
2818
+ kind: "llm-usage"
2819
+ };
2820
+ }
2821
+ function createContextComponentLedgerEntry(input) {
2822
+ return {
2823
+ ...input,
2824
+ kind: "context-component",
2825
+ components: [...input.components],
2826
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2827
+ };
2828
+ }
2829
+ function addUsageTotals(left, right) {
2830
+ if (!left) {
2831
+ return right;
2832
+ }
2833
+ if (!right) {
2834
+ return left;
2835
+ }
2836
+ return {
2837
+ inputTokens: left.inputTokens + right.inputTokens,
2838
+ outputTokens: left.outputTokens + right.outputTokens,
2839
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
2840
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
2841
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
2842
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
2843
+ usageCount: left.usageCount + right.usageCount
2844
+ };
2845
+ }
2846
+ function addLedgerAggregate(left, right) {
2847
+ return {
2848
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
2849
+ contextTokens: left.contextTokens + right.contextTokens,
2850
+ entryCount: left.entryCount + right.entryCount,
2851
+ llmCallCount: left.llmCallCount + right.llmCallCount,
2852
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
2853
+ };
2854
+ }
2855
+ function aggregateTokenLedgerEntries(entries) {
2856
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
2857
+ return entries.reduce((aggregate, entry) => {
2858
+ if (entry.kind === "llm-usage") {
2859
+ return {
2860
+ ...aggregate,
2861
+ entryCount: aggregate.entryCount + 1,
2862
+ llmCallCount: aggregate.llmCallCount + 1
2863
+ };
2864
+ }
2865
+ return {
2866
+ ...aggregate,
2867
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
2868
+ entryCount: aggregate.entryCount + 1,
2869
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
2870
+ };
2871
+ }, {
2872
+ ...EMPTY_LEDGER_AGGREGATE,
2873
+ llmUsage: aggregateCanonicalUsage(llmUsages)
2874
+ });
2875
+ }
2876
+ function createRunTokenUsageAggregate(input) {
2877
+ const children = input.childAggregates?.reduce(
2878
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
2879
+ EMPTY_LEDGER_AGGREGATE
2880
+ );
2881
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
2882
+ }
2883
+ function componentCost(tokens, pricePerMillion) {
2884
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
2885
+ }
2886
+ function needsPrice(tokens) {
2887
+ return tokens !== void 0 && tokens > 0;
2888
+ }
2889
+ function missingPriceComponents(usage, pricing) {
2890
+ const missing = [];
2891
+ if (!pricing) {
2892
+ if (needsPrice(usage.inputTokens)) {
2893
+ missing.push("input");
2894
+ }
2895
+ if (needsPrice(usage.outputTokens)) {
2896
+ missing.push("output");
2897
+ }
2898
+ if (needsPrice(usage.reasoningTokens)) {
2899
+ missing.push("reasoning");
2900
+ }
2901
+ if (needsPrice(usage.cacheReadTokens)) {
2902
+ missing.push("cacheRead");
2903
+ }
2904
+ if (needsPrice(usage.cacheWriteTokens)) {
2905
+ missing.push("cacheWrite");
2906
+ }
2907
+ return missing;
2908
+ }
2909
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
2910
+ missing.push("input");
2911
+ }
2912
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
2913
+ missing.push("output");
2914
+ }
2915
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
2916
+ missing.push("reasoning");
2917
+ }
2918
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
2919
+ missing.push("cacheRead");
2920
+ }
2921
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
2922
+ missing.push("cacheWrite");
2923
+ }
2924
+ return missing;
2925
+ }
2926
+ function reportedComponentCost(tokens, pricePerMillion) {
2927
+ if (tokens === void 0) {
2928
+ return void 0;
2929
+ }
2930
+ if (tokens === 0) {
2931
+ return 0;
2932
+ }
2933
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
2934
+ }
2935
+ function requiredComponentCost(tokens, pricePerMillion) {
2936
+ if (tokens === 0) {
2937
+ return 0;
2938
+ }
2939
+ return componentCost(tokens, pricePerMillion ?? 0);
2940
+ }
2941
+ function sumComputedCosts(costs) {
2942
+ let total = 0;
2943
+ for (const cost of costs) {
2944
+ total += cost ?? 0;
2945
+ }
2946
+ return total;
2947
+ }
2948
+ function computeCost(usage, pricing) {
2949
+ const missing = missingPriceComponents(usage, pricing);
2950
+ if (!pricing || missing.length > 0) {
2951
+ return {
2952
+ status: "unknown",
2953
+ ...pricing ? { currency: pricing.currency } : {},
2954
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
2955
+ };
2956
+ }
2957
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
2958
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
2959
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
2960
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
2961
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
2962
+ return {
2963
+ status: "computed",
2964
+ currency: pricing.currency,
2965
+ inputCost,
2966
+ outputCost,
2967
+ reasoningCost,
2968
+ cacheReadCost,
2969
+ cacheWriteCost,
2970
+ totalCost: sumComputedCosts([
2971
+ inputCost,
2972
+ outputCost,
2973
+ reasoningCost,
2974
+ cacheReadCost,
2975
+ cacheWriteCost
2976
+ ])
2977
+ };
2978
+ }
2979
+
2438
2980
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2439
2981
  var logger4 = new Logger("GraphAgentExecutor");
2440
2982
  function createBuildContextStage(dependencies) {
@@ -2451,6 +2993,23 @@ function createBuildContextStage(dependencies) {
2451
2993
  ctx.mode = contextBuildResult.mode;
2452
2994
  ctx.llmMessages = contextBuildResult.llmMessages;
2453
2995
  ctx.contextTrace = contextBuildResult.contextTrace;
2996
+ if (contextBuildResult.tokenEstimate) {
2997
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2998
+ ctx.telemetry.emit({
2999
+ kind: "context_build",
3000
+ modelId: ctx.modelId,
3001
+ mode: contextBuildResult.mode,
3002
+ tokenEstimate: contextBuildResult.tokenEstimate,
3003
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
3004
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
3005
+ scope: {
3006
+ conversationId: ctx.conversationId,
3007
+ runId: ctx.input.toolContext?.runId,
3008
+ parentRunId: ctx.input.toolContext?.parentRunId,
3009
+ turnId: ctx.turnId
3010
+ }
3011
+ });
3012
+ }
2454
3013
  for (const event of contextBuildResult.summaryEvents) {
2455
3014
  if (!isHistorySummaryEvent(event)) {
2456
3015
  continue;
@@ -2465,6 +3024,24 @@ function createBuildContextStage(dependencies) {
2465
3024
  }
2466
3025
  };
2467
3026
  }
3027
+ function createContextLedgerEntry(ctx, contextBuildResult) {
3028
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
3029
+ if (keptComponents.length === 0) {
3030
+ return void 0;
3031
+ }
3032
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
3033
+ const createdAt = Date.now();
3034
+ return createContextComponentLedgerEntry({
3035
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
3036
+ conversationId: ctx.conversationId,
3037
+ runId,
3038
+ parentRunId: ctx.input.toolContext?.parentRunId,
3039
+ turnId: ctx.turnId,
3040
+ route: contextBuildResult.tokenEstimate?.route,
3041
+ createdAt,
3042
+ components: keptComponents
3043
+ });
3044
+ }
2468
3045
 
2469
3046
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2470
3047
  function createBuildDecisionStage(dependencies) {
@@ -2598,7 +3175,7 @@ function createExecuteLlmStage(dependencies) {
2598
3175
  streamEventHandler,
2599
3176
  ctx.signal,
2600
3177
  (fallbackModelId) => {
2601
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
3178
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2602
3179
  },
2603
3180
  (info) => {
2604
3181
  ctx.modelFallbackAudit = info;
@@ -2642,7 +3219,7 @@ function createPrepareCallStage(dependencies) {
2642
3219
  return {
2643
3220
  id: "prepare_call",
2644
3221
  async run(ctx) {
2645
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
3222
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
2646
3223
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
2647
3224
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
2648
3225
  await emitAuditEnvelope(ctx.audit, {
@@ -2708,19 +3285,21 @@ var GraphAgentExecutor = class {
2708
3285
  modelCatalog;
2709
3286
  telemetryPort;
2710
3287
  auditPort;
3288
+ tokenizer;
2711
3289
  stages;
2712
3290
  middlewares;
2713
3291
  constructor(dependencies) {
2714
3292
  this.llmCaller = dependencies.llmCaller;
2715
3293
  this.toolRuntime = dependencies.toolRuntime;
2716
3294
  this.contextBuilder = dependencies.contextBuilder;
2717
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3295
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
2718
3296
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
2719
3297
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
2720
3298
  modelCatalog: this.modelCatalog
2721
3299
  });
2722
3300
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2723
3301
  this.auditPort = dependencies.auditPort ?? noopAudit;
3302
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2724
3303
  this.stages = [
2725
3304
  createPrepareCallStage({
2726
3305
  modelResolver: this.modelResolver,
@@ -2762,9 +3341,10 @@ var GraphAgentExecutor = class {
2762
3341
  llmMessages: [],
2763
3342
  mode: input.request.mode === "chat" ? "chat" : "agent",
2764
3343
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2765
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3344
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2766
3345
  telemetry: this.telemetryPort,
2767
- audit: this.auditPort
3346
+ audit: this.auditPort,
3347
+ tokenizer: this.tokenizer
2768
3348
  };
2769
3349
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2770
3350
  stream: input.stream === true,
@@ -2812,18 +3392,18 @@ function isSummarizationCallbacks(value) {
2812
3392
  function isGraphSseSink(value) {
2813
3393
  return typeof value === "function";
2814
3394
  }
2815
- function readNonEmptyString2(value) {
3395
+ function readNonEmptyString3(value) {
2816
3396
  if (typeof value !== "string") return void 0;
2817
3397
  const trimmed = value.trim();
2818
3398
  return trimmed.length > 0 ? trimmed : void 0;
2819
3399
  }
2820
3400
  function readGraphAgentLocal(local) {
2821
3401
  const source = local ?? {};
2822
- const answerId = readNonEmptyString2(source.answerId);
3402
+ const answerId = readNonEmptyString3(source.answerId);
2823
3403
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
2824
3404
  return {
2825
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
2826
- turnId: readNonEmptyString2(source.turnId),
3405
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3406
+ turnId: readNonEmptyString3(source.turnId),
2827
3407
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
2828
3408
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
2829
3409
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3588,7 +4168,7 @@ var LlmNode = class {
3588
4168
  function isRecord8(value) {
3589
4169
  return typeof value === "object" && value !== null && !Array.isArray(value);
3590
4170
  }
3591
- function readNonEmptyString3(value) {
4171
+ function readNonEmptyString4(value) {
3592
4172
  if (typeof value !== "string") {
3593
4173
  return void 0;
3594
4174
  }
@@ -3610,7 +4190,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3610
4190
  return void 0;
3611
4191
  }
3612
4192
  if (toolName === "write_report") {
3613
- const report = readNonEmptyString3(data.report);
4193
+ const report = readNonEmptyString4(data.report);
3614
4194
  if (!report) {
3615
4195
  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");
3616
4196
  }
@@ -3620,7 +4200,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3620
4200
  if (data.success !== true) {
3621
4201
  return void 0;
3622
4202
  }
3623
- const finalAnswer = readNonEmptyString3(data.final_answer);
4203
+ const finalAnswer = readNonEmptyString4(data.final_answer);
3624
4204
  if (!finalAnswer) {
3625
4205
  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");
3626
4206
  }
@@ -3729,11 +4309,11 @@ function buildToolOutputUiMeta(params) {
3729
4309
  }
3730
4310
  async function applyObservationGovernance(params) {
3731
4311
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3732
- return;
4312
+ return {};
3733
4313
  }
3734
4314
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3735
4315
  if (!policy.enabled) {
3736
- return;
4316
+ return {};
3737
4317
  }
3738
4318
  const truncated = await params.observationPreview.truncateObservation({
3739
4319
  context: params.toolContext,
@@ -3747,13 +4327,37 @@ async function applyObservationGovernance(params) {
3747
4327
  })
3748
4328
  });
3749
4329
  if (!truncated.truncated) {
3750
- return;
4330
+ return {};
3751
4331
  }
3752
4332
  params.parsed["observation"] = truncated.preview;
3753
4333
  const data = params.parsed["data"];
3754
4334
  if (isRecord9(data) && !("tool_output_store" in data)) {
3755
4335
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3756
4336
  }
4337
+ return {
4338
+ observationTruncation: buildObservationTruncationMeta({
4339
+ originalText: params.structuredObservation,
4340
+ previewText: truncated.preview,
4341
+ originalChars: truncated.originalChars,
4342
+ previewChars: truncated.previewChars,
4343
+ originalLines: truncated.originalLines,
4344
+ previewLines: truncated.previewLines
4345
+ })
4346
+ };
4347
+ }
4348
+ function buildObservationTruncationMeta(input) {
4349
+ return {
4350
+ originalChars: input.originalChars ?? input.originalText.length,
4351
+ previewChars: input.previewChars ?? input.previewText.length,
4352
+ originalLines: input.originalLines ?? countLines(input.originalText),
4353
+ previewLines: input.previewLines ?? countLines(input.previewText)
4354
+ };
4355
+ }
4356
+ function countLines(value) {
4357
+ if (value.length === 0) {
4358
+ return 0;
4359
+ }
4360
+ return value.split(/\r\n|\r|\n/).length;
3757
4361
  }
3758
4362
 
3759
4363
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4165,6 +4769,31 @@ function ensureToolContextRuntimeCapability(params) {
4165
4769
  function getToolContextRuntimeBinding(context) {
4166
4770
  return readBinding(context);
4167
4771
  }
4772
+ function copyToolContextRuntimeCapability(source, target) {
4773
+ const sourceBinding = readBinding(source);
4774
+ if (!sourceBinding) {
4775
+ return void 0;
4776
+ }
4777
+ const existingTargetBinding = readBinding(target);
4778
+ if (existingTargetBinding) {
4779
+ exposeCompatibilitySurface(target, existingTargetBinding);
4780
+ return existingTargetBinding;
4781
+ }
4782
+ const targetBinding = createRuntimeBinding({
4783
+ context: target,
4784
+ persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
4785
+ workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
4786
+ executionMeta: sourceBinding.readExecutionMeta()
4787
+ });
4788
+ Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
4789
+ value: targetBinding,
4790
+ enumerable: false,
4791
+ configurable: true,
4792
+ writable: false
4793
+ });
4794
+ exposeCompatibilitySurface(target, targetBinding);
4795
+ return targetBinding;
4796
+ }
4168
4797
  function readToolContextWorkingHistory(context) {
4169
4798
  if (context.conversationView) {
4170
4799
  return context.conversationView.getWorkingHistoryEvents();
@@ -4691,7 +5320,7 @@ var ToolNode = class {
4691
5320
  parentRunId: context.toolContext.parentRunId
4692
5321
  });
4693
5322
  applyProtocolFuseState(context.local);
4694
- await applyObservationGovernance({
5323
+ const observationGovernance = await applyObservationGovernance({
4695
5324
  parsed: context.parsed,
4696
5325
  toolName: context.toolName,
4697
5326
  toolContext: context.toolContext,
@@ -4718,6 +5347,12 @@ var ToolNode = class {
4718
5347
  runtimeToolOutput,
4719
5348
  execIdempotency: context.exec.idempotency
4720
5349
  });
5350
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5351
+ runtimeToolOutput.metadata = {
5352
+ ...runtimeToolOutput.metadata ?? {},
5353
+ observationTruncation: observationGovernance.observationTruncation
5354
+ };
5355
+ }
4721
5356
  const remainingCalls = context.calls.slice(1);
4722
5357
  context.state.local = buildSuccessLocalState({
4723
5358
  local: context.local,
@@ -5016,12 +5651,12 @@ function asRecord(value) {
5016
5651
  }
5017
5652
  return value;
5018
5653
  }
5019
- function summarizeCheckpoint(conversationId, state, savedAt) {
5654
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
5020
5655
  const local = asRecord(state.local);
5021
5656
  const executorLocal = asRecord(local?.executorLocal);
5022
5657
  const pendingToolCalls = local?.pendingToolCalls;
5023
5658
  return {
5024
- conversationId,
5659
+ checkpointKey,
5025
5660
  schemaVersion: state.schemaVersion ?? 1,
5026
5661
  savedAt,
5027
5662
  currentNode: state.nodeId,
@@ -5040,25 +5675,25 @@ var MemoryCheckpointer = class {
5040
5675
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
5041
5676
  };
5042
5677
  }
5043
- async load(conversationId) {
5044
- const entry = this.store.get(conversationId);
5678
+ async load(checkpointKey) {
5679
+ const entry = this.store.get(checkpointKey);
5045
5680
  return entry ? this.cloneState(entry.state) : null;
5046
5681
  }
5047
- async save(conversationId, state) {
5048
- this.store.set(conversationId, {
5682
+ async save(checkpointKey, state) {
5683
+ this.store.set(checkpointKey, {
5049
5684
  state: this.cloneState(state),
5050
5685
  savedAt: Date.now()
5051
5686
  });
5052
5687
  }
5053
- async clear(conversationId) {
5054
- this.store.delete(conversationId);
5688
+ async clear(checkpointKey) {
5689
+ this.store.delete(checkpointKey);
5055
5690
  }
5056
- async peekMeta(conversationId) {
5057
- const entry = this.store.get(conversationId);
5058
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
5691
+ async peekMeta(checkpointKey) {
5692
+ const entry = this.store.get(checkpointKey);
5693
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
5059
5694
  }
5060
5695
  async list(filter = {}) {
5061
- 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);
5696
+ 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);
5062
5697
  if (filter.limit === void 0) {
5063
5698
  return summaries;
5064
5699
  }
@@ -5130,6 +5765,7 @@ __export(tools_exports, {
5130
5765
  CommonParameterTypes: () => CommonParameterTypes,
5131
5766
  ContextCheckpointTool: () => ContextCheckpointTool,
5132
5767
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
5768
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
5133
5769
  createContextCheckpointTool: () => createContextCheckpointTool,
5134
5770
  ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
5135
5771
  findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
@@ -5323,7 +5959,7 @@ function createContextCheckpointTool(options) {
5323
5959
  function isRecord15(value) {
5324
5960
  return !!value && typeof value === "object" && !Array.isArray(value);
5325
5961
  }
5326
- function readNonEmptyString4(value) {
5962
+ function readNonEmptyString5(value) {
5327
5963
  if (typeof value !== "string") {
5328
5964
  return void 0;
5329
5965
  }
@@ -5343,13 +5979,13 @@ function readToolContextUserQuery(context) {
5343
5979
  if (!context) {
5344
5980
  return void 0;
5345
5981
  }
5346
- return readNonEmptyString4(context["user_query"]);
5982
+ return readNonEmptyString5(context["user_query"]);
5347
5983
  }
5348
5984
  function readToolContextModelId(context) {
5349
5985
  if (!context) {
5350
5986
  return void 0;
5351
5987
  }
5352
- return readNonEmptyString4(context["modelId"]);
5988
+ return readNonEmptyString5(context["modelId"]);
5353
5989
  }
5354
5990
  function readToolContextRunContext(context) {
5355
5991
  if (!context) {
@@ -6551,6 +7187,7 @@ async function callLlmStream(params) {
6551
7187
  const streamAnswerId = generateMessageId();
6552
7188
  let streamChunkSeq = 0;
6553
7189
  let capturedUsage = void 0;
7190
+ let capturedCanonicalUsage = void 0;
6554
7191
  const toolAccumulator = new ToolCallStreamAccumulator([
6555
7192
  "markdown_edit",
6556
7193
  "text_to_image",
@@ -6609,6 +7246,10 @@ async function callLlmStream(params) {
6609
7246
  if (typeof chunk !== "object" || chunk === null) {
6610
7247
  return;
6611
7248
  }
7249
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7250
+ if (parsedCanonicalUsage.success) {
7251
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7252
+ }
6612
7253
  if (chunk.content) {
6613
7254
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6614
7255
  fullResponse += chunk.content;
@@ -6693,6 +7334,12 @@ async function callLlmStream(params) {
6693
7334
  const onUsage = (usage) => {
6694
7335
  capturedUsage = usage;
6695
7336
  };
7337
+ const onCanonicalUsage = (usage) => {
7338
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7339
+ if (parsed.success) {
7340
+ capturedCanonicalUsage = parsed.data;
7341
+ }
7342
+ };
6696
7343
  await aiEngine.chatCompletionStream(
6697
7344
  modelId,
6698
7345
  messages,
@@ -6705,7 +7352,8 @@ async function callLlmStream(params) {
6705
7352
  onError,
6706
7353
  onFinish,
6707
7354
  onThought,
6708
- onUsage
7355
+ onUsage,
7356
+ onCanonicalUsage
6709
7357
  );
6710
7358
  if (streamError) {
6711
7359
  throw streamError;
@@ -6713,12 +7361,13 @@ async function callLlmStream(params) {
6713
7361
  emitThoughtComplete(thoughtSegmenter.finalize());
6714
7362
  const mergedToolCalls = toolAccumulator.getToolCalls();
6715
7363
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6716
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7364
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6717
7365
  return {
6718
7366
  content: fullResponse,
6719
7367
  tool_calls: mergedToolCalls,
6720
7368
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6721
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7369
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7370
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6722
7371
  };
6723
7372
  }
6724
7373
  return fullResponse;
@@ -6768,6 +7417,10 @@ function tryCloudQuotaFallback({
6768
7417
  }
6769
7418
 
6770
7419
  // src/runtime-kernel/llm/usage-telemetry.ts
7420
+ function parseCanonicalUsage(value) {
7421
+ const parsed = CanonicalLlmUsage.safeParse(value);
7422
+ return parsed.success ? parsed.data : void 0;
7423
+ }
6771
7424
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6772
7425
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6773
7426
  return normalizeCompletionResponse(response);
@@ -6778,6 +7431,7 @@ function normalizeCompletionResponse(response) {
6778
7431
  }
6779
7432
  if (isRecord19(response)) {
6780
7433
  const usage = response["usage"];
7434
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6781
7435
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6782
7436
  if (parsedToolCalls) {
6783
7437
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6785,7 +7439,8 @@ function normalizeCompletionResponse(response) {
6785
7439
  content: typeof response["content"] === "string" ? response["content"] : "",
6786
7440
  tool_calls: parsedToolCalls,
6787
7441
  reasoning_details: reasoningDetails,
6788
- ...usage !== void 0 ? { usage } : {}
7442
+ ...usage !== void 0 ? { usage } : {},
7443
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6789
7444
  };
6790
7445
  }
6791
7446
  }
@@ -6795,10 +7450,12 @@ function normalizeCompletionResponse(response) {
6795
7450
  if (typeof response === "object") {
6796
7451
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6797
7452
  const usage = response["usage"];
7453
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6798
7454
  return {
6799
7455
  content: typeof response["content"] === "string" ? response["content"] : "",
6800
7456
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6801
- ...usage !== void 0 ? { usage } : {}
7457
+ ...usage !== void 0 ? { usage } : {},
7458
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6802
7459
  };
6803
7460
  }
6804
7461
  if (isRecord19(response)) {
@@ -7052,29 +7709,6 @@ var LlmCaller = class {
7052
7709
  }
7053
7710
  };
7054
7711
 
7055
- // src/shared/defaultTokenizerPort.ts
7056
- var DefaultTokenizerPort = class {
7057
- constructor(config = {}) {
7058
- this.config = config;
7059
- }
7060
- estimateText(text, _modelId) {
7061
- return TokenCalculator.estimateTokens(text, {
7062
- encoding: this.config.encoding,
7063
- avgCharsPerToken: this.config.avgCharsPerToken
7064
- });
7065
- }
7066
- estimateMessage(message, _modelId) {
7067
- return TokenCalculator.estimateMessageTokens(message, {
7068
- encoding: this.config.encoding,
7069
- avgCharsPerToken: this.config.avgCharsPerToken,
7070
- toolCallOverhead: this.config.toolCallOverhead
7071
- });
7072
- }
7073
- };
7074
- function createDefaultTokenizerPort(config = {}) {
7075
- return new DefaultTokenizerPort(config);
7076
- }
7077
-
7078
7712
  // src/runtime-kernel/child-runs/index.ts
7079
7713
  var child_runs_exports = {};
7080
7714
  __export(child_runs_exports, {
@@ -7084,7 +7718,6 @@ __export(child_runs_exports, {
7084
7718
 
7085
7719
  // src/runtime-kernel/child-runs/childToolContext.ts
7086
7720
  function createChildRunToolContext(params) {
7087
- const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
7088
7721
  const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
7089
7722
  const childToolContext = {
7090
7723
  ...inheritedContext,
@@ -7096,7 +7729,7 @@ function createChildRunToolContext(params) {
7096
7729
  persistedHistory: params.seedHistory,
7097
7730
  workingHistory: params.seedHistory,
7098
7731
  executionMeta: {
7099
- conversationId: inheritedConversationId ?? params.internalConversationId,
7732
+ conversationId: params.conversationId,
7100
7733
  turnId: params.turnId,
7101
7734
  runId: params.runId,
7102
7735
  parentRunId: params.parentRunId
@@ -7198,6 +7831,8 @@ var FinalAnswerCollector = class {
7198
7831
  this.conversationId = conversationId;
7199
7832
  this.turnId = turnId;
7200
7833
  }
7834
+ conversationId;
7835
+ turnId;
7201
7836
  answerId;
7202
7837
  chunks = [];
7203
7838
  chunkCount = 0;
@@ -7414,7 +8049,7 @@ function readCheckpointHistory(checkpoint) {
7414
8049
  });
7415
8050
  }
7416
8051
  async function recoverChildRunEventsFromCheckpoint(params) {
7417
- const checkpoint = await params.checkpointer.load(params.conversationId);
8052
+ const checkpoint = await params.checkpointer.load(params.checkpointKey);
7418
8053
  const history = readCheckpointHistory(checkpoint);
7419
8054
  if (history.length === 0) {
7420
8055
  return [];
@@ -7422,7 +8057,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
7422
8057
  if (hasSeedHistoryPrefix(history, params.seedHistory)) {
7423
8058
  return history.slice(params.seedHistory.length);
7424
8059
  }
7425
- return history.filter((event) => event.conversation_id === params.internalConversationId);
8060
+ return history.filter((event) => event.conversation_id === params.childConversationId);
7426
8061
  }
7427
8062
 
7428
8063
  // src/runtime-kernel/child-runs/childRunInvoker.ts
@@ -7451,6 +8086,7 @@ var ChildRunInvoker = class {
7451
8086
  agentConfig,
7452
8087
  userMessage,
7453
8088
  parentToolContext,
8089
+ conversationId,
7454
8090
  runId,
7455
8091
  parentRunId,
7456
8092
  subrunTracePublisher,
@@ -7459,12 +8095,18 @@ var ChildRunInvoker = class {
7459
8095
  modelId,
7460
8096
  abortSignal
7461
8097
  } = config;
7462
- const internalConversationId = `internal_${generateMessageId()}`;
8098
+ const internalCheckpointKey = `internal_${generateMessageId()}`;
8099
+ const runtimeConversationId = resolveChildRunConversationId({
8100
+ explicitConversationId: conversationId,
8101
+ parentToolContext,
8102
+ fallbackConversationId: internalCheckpointKey
8103
+ });
7463
8104
  const turnId = `turn_${Date.now()}`;
7464
- const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalConversationId;
8105
+ const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
7465
8106
  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;
7466
8107
  logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
7467
- conversationId: internalConversationId,
8108
+ conversationId: runtimeConversationId,
8109
+ checkpointKey: internalCheckpointKey,
7468
8110
  maxSteps,
7469
8111
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
7470
8112
  });
@@ -7525,7 +8167,7 @@ var ChildRunInvoker = class {
7525
8167
  const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
7526
8168
  const childToolContext = createChildRunToolContext({
7527
8169
  parentToolContext,
7528
- internalConversationId,
8170
+ conversationId: runtimeConversationId,
7529
8171
  turnId,
7530
8172
  runId: childRunId,
7531
8173
  parentRunId: resolvedParentRunId,
@@ -7534,13 +8176,13 @@ var ChildRunInvoker = class {
7534
8176
  });
7535
8177
  const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
7536
8178
  publisher: subrunTracePublisher,
7537
- conversationId: internalConversationId,
8179
+ conversationId: runtimeConversationId,
7538
8180
  turnId
7539
8181
  }) : void 0;
7540
8182
  const initialLocal = {
7541
8183
  request,
7542
8184
  history: seedHistory,
7543
- conversationId: internalConversationId,
8185
+ conversationId: runtimeConversationId,
7544
8186
  turnId,
7545
8187
  toolContext: childToolContext,
7546
8188
  ...abortSignal ? { signal: abortSignal } : {},
@@ -7548,7 +8190,7 @@ var ChildRunInvoker = class {
7548
8190
  ...subrunSseSink ? { sseSink: subrunSseSink } : {},
7549
8191
  systemPrompt
7550
8192
  };
7551
- await graphExecutor.prime(internalConversationId, initialLocal, "llm");
8193
+ await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
7552
8194
  const allEvents = [];
7553
8195
  let stepCount = 0;
7554
8196
  let finalAnswer;
@@ -7560,7 +8202,7 @@ var ChildRunInvoker = class {
7560
8202
  err.name = "AbortError";
7561
8203
  throw err;
7562
8204
  }
7563
- const result = await graphExecutor.runUntilYield(internalConversationId);
8205
+ const result = await graphExecutor.runUntilYield(internalCheckpointKey);
7564
8206
  appendUniqueEvents(allEvents, result.events);
7565
8207
  stepCount = result.stepCount;
7566
8208
  if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
@@ -7594,8 +8236,8 @@ var ChildRunInvoker = class {
7594
8236
  }
7595
8237
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
7596
8238
  checkpointer,
7597
- conversationId: internalConversationId,
7598
- internalConversationId,
8239
+ checkpointKey: internalCheckpointKey,
8240
+ childConversationId: runtimeConversationId,
7599
8241
  seedHistory
7600
8242
  });
7601
8243
  appendUniqueEvents(allEvents, recoveredEvents);
@@ -7612,7 +8254,7 @@ var ChildRunInvoker = class {
7612
8254
  stack: err.stack
7613
8255
  } : { error: String(err) });
7614
8256
  }
7615
- await checkpointer.clear(internalConversationId);
8257
+ await checkpointer.clear(internalCheckpointKey);
7616
8258
  return {
7617
8259
  success: !error,
7618
8260
  runId: childRunId,
@@ -7625,6 +8267,16 @@ var ChildRunInvoker = class {
7625
8267
  };
7626
8268
  }
7627
8269
  };
8270
+ function readNonEmptyString6(value) {
8271
+ if (typeof value !== "string") {
8272
+ return void 0;
8273
+ }
8274
+ const trimmed = value.trim();
8275
+ return trimmed.length > 0 ? trimmed : void 0;
8276
+ }
8277
+ function resolveChildRunConversationId(params) {
8278
+ return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
8279
+ }
7628
8280
  function resolveChildRunSystemReminderPolicy(agentConfig) {
7629
8281
  const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
7630
8282
  const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
@@ -7815,7 +8467,7 @@ function cloneRunRecord(record) {
7815
8467
  ...record,
7816
8468
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
7817
8469
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
7818
- metadata: record.metadata ? { ...record.metadata } : void 0
8470
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
7819
8471
  };
7820
8472
  }
7821
8473
  function matchesStatus(candidate, filter) {
@@ -8227,7 +8879,7 @@ function isTerminalStatus(status) {
8227
8879
  return status === "completed" || status === "failed" || status === "cancelled";
8228
8880
  }
8229
8881
  function cloneMetadata(metadata) {
8230
- return metadata ? { ...metadata } : void 0;
8882
+ return metadata ? structuredClone(metadata) : void 0;
8231
8883
  }
8232
8884
  function recordToSnapshot(record) {
8233
8885
  return {
@@ -8314,7 +8966,7 @@ var DefaultRunSupervisor = class {
8314
8966
  startedAt,
8315
8967
  updatedAt: startedAt,
8316
8968
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
8317
- metadata: spec.metadata ? { ...spec.metadata } : void 0
8969
+ metadata: cloneMetadata(spec.metadata)
8318
8970
  };
8319
8971
  await this.registryStore.save(record);
8320
8972
  const handle = new DefaultRunHandle({
@@ -8488,12 +9140,13 @@ var DefaultRunSupervisor = class {
8488
9140
  }
8489
9141
  try {
8490
9142
  await handle.markRunning({ currentNode: "detached" });
9143
+ const registeredRecord = await this.registryStore.load(handle.runId);
8491
9144
  const executorOutcome = await this.executor.execute({
8492
9145
  runId: handle.runId,
8493
- parentRunId: spec.parentRunId,
8494
- conversationId: spec.conversationId,
8495
- agentSpec: spec.agentSpec,
8496
- request: spec.request,
9146
+ parentRunId: handle.parentRunId,
9147
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
9148
+ agentSpec: await handle.spec(),
9149
+ request: await handle.request(),
8497
9150
  signal: handle.signal,
8498
9151
  eventBus: spec.eventBus,
8499
9152
  eventStore: spec.eventStore,
@@ -8502,7 +9155,7 @@ var DefaultRunSupervisor = class {
8502
9155
  contextFences: spec.contextFences,
8503
9156
  wakeSource: spec.wakeSource,
8504
9157
  ephemeral: spec.ephemeral,
8505
- metadata: spec.metadata
9158
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
8506
9159
  });
8507
9160
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
8508
9161
  this.notifyTerminalWaiters(outcome);
@@ -8566,10 +9219,14 @@ var DefaultRunSupervisor = class {
8566
9219
  await this.registryStore.save(record);
8567
9220
  }
8568
9221
  const completedAt = executorOutcome?.completedAt ?? this.now();
9222
+ const fallbackMeta = record ? void 0 : await handle.meta();
8569
9223
  const outcome = recordToTerminalOutcome(record ?? {
8570
9224
  runId: handle.runId,
8571
9225
  parentRunId: handle.parentRunId,
8572
- status: executorOutcome?.status ?? "completed"}, completedAt);
9226
+ conversationId: fallbackMeta?.conversationId ?? "",
9227
+ agentSpecId: fallbackMeta?.agentSpecId,
9228
+ status: executorOutcome?.status ?? "completed",
9229
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
8573
9230
  const nextOutcome = {
8574
9231
  ...outcome,
8575
9232
  metadata: {
@@ -8661,6 +9318,7 @@ __export(telemetry_exports, {
8661
9318
  var TELEMETRY_EVENT_KINDS = [
8662
9319
  "llm_call",
8663
9320
  "tool_call",
9321
+ "context_build",
8664
9322
  "graph_node",
8665
9323
  "run_lifecycle"
8666
9324
  ];
@@ -8797,6 +9455,7 @@ function createGraphLoopHarness(options) {
8797
9455
  };
8798
9456
  return {
8799
9457
  async run() {
9458
+ const checkpointKey = options.conversationId;
8800
9459
  const executor = createDefaultGraphExecutor({
8801
9460
  llmNode: options.createLlmNode({
8802
9461
  llmCaller: options.llmCaller,
@@ -8825,8 +9484,8 @@ function createGraphLoopHarness(options) {
8825
9484
  signal: options.signal ?? options.toolContext.abortSignal,
8826
9485
  executorLocal
8827
9486
  };
8828
- await executor.prime(options.conversationId, local, "user");
8829
- const result = await executor.runUntilYield(options.conversationId);
9487
+ await executor.prime(checkpointKey, local, "user");
9488
+ const result = await executor.runUntilYield(checkpointKey);
8830
9489
  return {
8831
9490
  checkpointNodeId: result.checkpoint.nodeId,
8832
9491
  stepCount: result.stepCount
@@ -9420,6 +10079,27 @@ var summarizeToolOutput = (toolName, output, toolSummaryProvider, toolArgs, conf
9420
10079
  function isRecord25(value) {
9421
10080
  return !!value && typeof value === "object" && !Array.isArray(value);
9422
10081
  }
10082
+ function readObservationTruncationMeta(value) {
10083
+ if (!isRecord25(value)) {
10084
+ return void 0;
10085
+ }
10086
+ const originalChars = value["originalChars"];
10087
+ const previewChars = value["previewChars"];
10088
+ if (typeof originalChars !== "number" || !Number.isInteger(originalChars) || originalChars < 0) {
10089
+ return void 0;
10090
+ }
10091
+ if (typeof previewChars !== "number" || !Number.isInteger(previewChars) || previewChars < 0) {
10092
+ return void 0;
10093
+ }
10094
+ const originalLines = value["originalLines"];
10095
+ const previewLines = value["previewLines"];
10096
+ return {
10097
+ originalChars,
10098
+ previewChars,
10099
+ ...typeof originalLines === "number" && Number.isInteger(originalLines) && originalLines >= 0 ? { originalLines } : {},
10100
+ ...typeof previewLines === "number" && Number.isInteger(previewLines) && previewLines >= 0 ? { previewLines } : {}
10101
+ };
10102
+ }
9423
10103
  function isHistorySummaryEvent2(event) {
9424
10104
  return "type" in event && event.type === "history_summary";
9425
10105
  }
@@ -9532,6 +10212,7 @@ function convertEventToAiMessage(event) {
9532
10212
  }
9533
10213
  })();
9534
10214
  const outputContent = observationFromPayload ?? rawOutput;
10215
+ const observationTruncation = readObservationTruncationMeta(event.metadata?.observationTruncation);
9535
10216
  return {
9536
10217
  id: event.id,
9537
10218
  role: "tool",
@@ -9542,6 +10223,7 @@ function convertEventToAiMessage(event) {
9542
10223
  tool_call_id: event.tool_call_id,
9543
10224
  tool_name: event.tool_name,
9544
10225
  raw_output: rawOutput,
10226
+ ...observationTruncation ? { observationTruncation } : {},
9545
10227
  ...observationFromPayload ? { observation: observationFromPayload } : {}
9546
10228
  }
9547
10229
  };
@@ -10340,14 +11022,14 @@ function createRunSupervisorHarness(options = {}) {
10340
11022
  function failure2(id, title, message, details) {
10341
11023
  return details === void 0 ? { id, title, message } : { id, title, message, details };
10342
11024
  }
10343
- function readRecord(value) {
11025
+ function readRecord2(value) {
10344
11026
  return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
10345
11027
  }
10346
11028
  function readString4(value) {
10347
11029
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
10348
11030
  }
10349
11031
  function readEventRunId(event) {
10350
- const metadata = readRecord(event.metadata);
11032
+ const metadata = readRecord2(event.metadata);
10351
11033
  if (!metadata) {
10352
11034
  return void 0;
10353
11035
  }
@@ -10355,7 +11037,7 @@ function readEventRunId(event) {
10355
11037
  if (direct) {
10356
11038
  return direct;
10357
11039
  }
10358
- const runContext = readRecord(metadata.run_context);
11040
+ const runContext = readRecord2(metadata.run_context);
10359
11041
  return runContext ? readString4(runContext.runId) ?? readString4(runContext.run_id) : void 0;
10360
11042
  }
10361
11043
  function runIds(records) {