@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
@@ -42,6 +42,7 @@ var Logger = class {
42
42
  constructor(moduleName) {
43
43
  this.moduleName = moduleName;
44
44
  }
45
+ moduleName;
45
46
  debug(message, data) {
46
47
  this.log(0 /* DEBUG */, "debug", message, data);
47
48
  }
@@ -140,6 +141,12 @@ zod.z.object({
140
141
  args: zod.z.record(zod.z.unknown()).optional(),
141
142
  tool_call_id: zod.z.string()
142
143
  });
144
+ var ObservationTruncationMeta = zod.z.object({
145
+ originalChars: zod.z.number().int().nonnegative(),
146
+ previewChars: zod.z.number().int().nonnegative(),
147
+ originalLines: zod.z.number().int().nonnegative().optional(),
148
+ previewLines: zod.z.number().int().nonnegative().optional()
149
+ });
143
150
  var ImageInfoMeta = zod.z.object({
144
151
  url: zod.z.string().optional(),
145
152
  width: zod.z.number().int().positive().optional(),
@@ -171,6 +178,7 @@ var PersistentMetadata = zod.z.object({
171
178
  tool_name: zod.z.string().optional(),
172
179
  args: zod.z.record(zod.z.unknown()).optional(),
173
180
  tool_call_id: zod.z.string().optional(),
181
+ observationTruncation: ObservationTruncationMeta.optional(),
174
182
  raw_output: zod.z.string().optional(),
175
183
  image_info: ImageInfoMeta.optional(),
176
184
  taskType: zod.z.string().optional(),
@@ -264,6 +272,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
264
272
  });
265
273
  var AgentSpecToolHistoryPolicy = zod.z.object({
266
274
  strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
275
+ retentionMode: zod.z.enum(["drop", "compress"]).optional(),
267
276
  keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
268
277
  keepLatestRuns: zod.z.number().int().nonnegative().optional(),
269
278
  maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
@@ -316,7 +325,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
316
325
  var AgentSpecTokenEstimationPolicy = zod.z.object({
317
326
  encoding: zod.z.string().min(1).optional(),
318
327
  avgCharsPerToken: zod.z.number().positive().optional(),
319
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
328
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
329
+ calibration: zod.z.object({
330
+ enabled: zod.z.boolean().optional(),
331
+ minSamples: zod.z.number().int().positive().optional(),
332
+ minCoefficient: zod.z.number().positive().optional(),
333
+ maxCoefficient: zod.z.number().positive().optional()
334
+ }).optional(),
335
+ remoteCount: zod.z.object({
336
+ enabled: zod.z.boolean().optional(),
337
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
338
+ }).optional()
320
339
  });
321
340
  var AgentSpecSystemReminderTrigger = zod.z.object({
322
341
  kind: zod.z.string().min(1),
@@ -1014,12 +1033,206 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1014
1033
  error,
1015
1034
  ...options
1016
1035
  });
1036
+ var TokenCountSource = zod.z.enum([
1037
+ "local-estimate",
1038
+ "provider-preflight-count",
1039
+ "provider-response-usage",
1040
+ "host-supplied",
1041
+ "test-fixture"
1042
+ ]);
1043
+ var TokenCountConfidence = zod.z.enum([
1044
+ "estimate",
1045
+ "provider-estimate",
1046
+ "actual"
1047
+ ]);
1048
+ var TokenRouteCapabilities = zod.z.object({
1049
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1050
+ supportsResponseUsage: zod.z.boolean().optional(),
1051
+ supportsImageInput: zod.z.boolean().optional(),
1052
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1053
+ supportsReasoningTokens: zod.z.boolean().optional()
1054
+ });
1055
+ var TokenRoute = zod.z.object({
1056
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1057
+ 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"),
1058
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1059
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1060
+ capabilities: TokenRouteCapabilities.optional()
1061
+ });
1062
+ var tokenCount = zod.z.number().int().nonnegative();
1063
+ var CanonicalLlmUsage = zod.z.object({
1064
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1065
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1066
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1067
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1068
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1069
+ 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"),
1070
+ source: TokenCountSource,
1071
+ confidence: TokenCountConfidence,
1072
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1073
+ });
1074
+ var tokenCount2 = zod.z.number().int().nonnegative();
1075
+ var tokenPrice = zod.z.number().finite().nonnegative();
1076
+ zod.z.enum([
1077
+ "llm-usage",
1078
+ "context-component"
1079
+ ]);
1080
+ var ContextTokenComponentKind = zod.z.enum([
1081
+ "system",
1082
+ "user",
1083
+ "assistant",
1084
+ "tool",
1085
+ "context-injection",
1086
+ "history-summary",
1087
+ "working-memory",
1088
+ "fence",
1089
+ "system-reminder",
1090
+ "other"
1091
+ ]);
1092
+ var TokenUsageTotals = zod.z.object({
1093
+ inputTokens: tokenCount2,
1094
+ outputTokens: tokenCount2,
1095
+ reasoningTokens: tokenCount2.optional(),
1096
+ cacheReadTokens: tokenCount2.optional(),
1097
+ cacheWriteTokens: tokenCount2.optional(),
1098
+ totalTokens: tokenCount2.optional(),
1099
+ usageCount: zod.z.number().int().nonnegative()
1100
+ });
1101
+ var ContextTokenComponent = zod.z.object({
1102
+ componentId: zod.z.string().min(1),
1103
+ kind: ContextTokenComponentKind,
1104
+ tokens: tokenCount2,
1105
+ source: TokenCountSource,
1106
+ confidence: TokenCountConfidence,
1107
+ label: zod.z.string().optional(),
1108
+ messageId: zod.z.string().optional(),
1109
+ role: zod.z.string().optional(),
1110
+ action: zod.z.string().optional(),
1111
+ kept: zod.z.boolean().optional(),
1112
+ truncatedAtExecution: zod.z.boolean().optional(),
1113
+ originalTokensEstimate: tokenCount2.optional(),
1114
+ droppedTokensEstimate: tokenCount2.optional()
1115
+ });
1116
+ var TokenLedgerEntryBase = zod.z.object({
1117
+ id: zod.z.string().min(1),
1118
+ runId: zod.z.string().optional(),
1119
+ parentRunId: zod.z.string().optional(),
1120
+ conversationId: zod.z.string().optional(),
1121
+ turnId: zod.z.string().optional(),
1122
+ stepId: zod.z.string().optional(),
1123
+ route: TokenRoute.optional(),
1124
+ createdAt: zod.z.number().int().nonnegative().optional()
1125
+ });
1126
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1127
+ kind: zod.z.literal("llm-usage"),
1128
+ modelId: zod.z.string().optional(),
1129
+ usage: CanonicalLlmUsage
1130
+ });
1131
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1132
+ kind: zod.z.literal("context-component"),
1133
+ components: zod.z.array(ContextTokenComponent),
1134
+ totalTokens: tokenCount2
1135
+ });
1136
+ zod.z.discriminatedUnion("kind", [
1137
+ LlmUsageTokenLedgerEntry,
1138
+ ContextComponentTokenLedgerEntry
1139
+ ]);
1140
+ var TokenLedgerAggregate = zod.z.object({
1141
+ llmUsage: TokenUsageTotals.optional(),
1142
+ contextTokens: tokenCount2,
1143
+ entryCount: zod.z.number().int().nonnegative(),
1144
+ llmCallCount: zod.z.number().int().nonnegative(),
1145
+ contextComponentCount: zod.z.number().int().nonnegative()
1146
+ });
1147
+ zod.z.object({
1148
+ /**
1149
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1150
+ */
1151
+ own: TokenLedgerAggregate,
1152
+ children: TokenLedgerAggregate.optional()
1153
+ });
1154
+ var TokenCostComponent = zod.z.enum([
1155
+ "input",
1156
+ "output",
1157
+ "reasoning",
1158
+ "cacheRead",
1159
+ "cacheWrite"
1160
+ ]);
1161
+ zod.z.object({
1162
+ currency: zod.z.string().min(1),
1163
+ unit: zod.z.literal("per_1m_tokens"),
1164
+ input: tokenPrice.optional(),
1165
+ output: tokenPrice.optional(),
1166
+ reasoning: tokenPrice.optional(),
1167
+ cacheRead: tokenPrice.optional(),
1168
+ cacheWrite: tokenPrice.optional()
1169
+ });
1170
+ zod.z.object({
1171
+ status: zod.z.enum(["computed", "unknown"]),
1172
+ currency: zod.z.string().optional(),
1173
+ inputCost: tokenPrice.optional(),
1174
+ outputCost: tokenPrice.optional(),
1175
+ reasoningCost: tokenPrice.optional(),
1176
+ cacheReadCost: tokenPrice.optional(),
1177
+ cacheWriteCost: tokenPrice.optional(),
1178
+ totalCost: tokenPrice.optional(),
1179
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1180
+ });
1181
+ var tokenCount3 = zod.z.number().int().nonnegative();
1182
+ var actualCalibrationSource = zod.z.enum([
1183
+ "provider-response-usage",
1184
+ "host-supplied",
1185
+ "test-fixture"
1186
+ ]);
1187
+ zod.z.object({
1188
+ route: TokenRoute,
1189
+ localEstimateTokens: tokenCount3,
1190
+ actualInputTokens: tokenCount3,
1191
+ source: actualCalibrationSource,
1192
+ confidence: zod.z.literal("actual"),
1193
+ observedAt: zod.z.number().int().nonnegative().optional(),
1194
+ runId: zod.z.string().optional(),
1195
+ ledgerEntryId: zod.z.string().optional()
1196
+ });
1197
+ zod.z.object({
1198
+ enabled: zod.z.boolean(),
1199
+ applied: zod.z.boolean(),
1200
+ route: TokenRoute.optional(),
1201
+ sampleCount: zod.z.number().int().nonnegative(),
1202
+ coefficient: zod.z.number().positive().optional(),
1203
+ minSamples: zod.z.number().int().positive().optional(),
1204
+ minCoefficient: zod.z.number().positive().optional(),
1205
+ maxCoefficient: zod.z.number().positive().optional(),
1206
+ localEstimateTokens: tokenCount3.optional(),
1207
+ calibratedEstimateTokens: tokenCount3.optional(),
1208
+ deltaTokens: zod.z.number().int().optional(),
1209
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1210
+ });
1211
+ zod.z.object({
1212
+ route: TokenRoute.optional(),
1213
+ localEstimateTokens: tokenCount3,
1214
+ calibratedEstimateTokens: tokenCount3,
1215
+ finalTokens: tokenCount3,
1216
+ source: zod.z.literal("local-estimate"),
1217
+ confidence: zod.z.literal("estimate")
1218
+ });
1017
1219
 
1018
1220
  // src/runtime-kernel/graph-engine/engine.ts
1019
1221
  var logger = new Logger("GraphExecutor");
1020
1222
  function asLocalRecord(local) {
1021
1223
  return local && typeof local === "object" ? { ...local } : {};
1022
1224
  }
1225
+ function readNonEmptyString(value) {
1226
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1227
+ }
1228
+ function readRuntimeConversationId(state) {
1229
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1230
+ return readNonEmptyString(local?.conversationId);
1231
+ }
1232
+ function readRuntimeTurnId(state) {
1233
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1234
+ return readNonEmptyString(local?.turnId);
1235
+ }
1023
1236
  var GraphExecutor = class {
1024
1237
  constructor(checkpointer, config = {}) {
1025
1238
  this.checkpointer = checkpointer;
@@ -1029,6 +1242,7 @@ var GraphExecutor = class {
1029
1242
  };
1030
1243
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1031
1244
  }
1245
+ checkpointer;
1032
1246
  nodes = /* @__PURE__ */ new Map();
1033
1247
  ephemeralLocals = /* @__PURE__ */ new Map();
1034
1248
  config;
@@ -1036,8 +1250,8 @@ var GraphExecutor = class {
1036
1250
  registerNode(node) {
1037
1251
  this.nodes.set(node.id, node);
1038
1252
  }
1039
- async peekCheckpoint(conversationId) {
1040
- return await this.checkpointer.load(conversationId);
1253
+ async peekCheckpoint(checkpointKey) {
1254
+ return await this.checkpointer.load(checkpointKey);
1041
1255
  }
1042
1256
  sanitize(state) {
1043
1257
  const local = asLocalRecord(state.local);
@@ -1049,8 +1263,8 @@ var GraphExecutor = class {
1049
1263
  local
1050
1264
  };
1051
1265
  }
1052
- async prime(conversationId, local, nodeId = "user") {
1053
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1266
+ async prime(checkpointKey, local, nodeId = "user") {
1267
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1054
1268
  const localSansMemory = { ...local || {} };
1055
1269
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1056
1270
  const state = {
@@ -1058,10 +1272,10 @@ var GraphExecutor = class {
1058
1272
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1059
1273
  local: localSansMemory
1060
1274
  };
1061
- await this.checkpointer.save(conversationId, state);
1275
+ await this.checkpointer.save(checkpointKey, state);
1062
1276
  }
1063
- async setNode(conversationId, nodeId, localPatch) {
1064
- const current = await this.checkpointer.load(conversationId) || {
1277
+ async setNode(checkpointKey, nodeId, localPatch) {
1278
+ const current = await this.checkpointer.load(checkpointKey) || {
1065
1279
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1066
1280
  local: {}
1067
1281
  };
@@ -1072,19 +1286,46 @@ var GraphExecutor = class {
1072
1286
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1073
1287
  local: mergedLocal
1074
1288
  };
1075
- await this.checkpointer.save(conversationId, next);
1289
+ await this.checkpointer.save(checkpointKey, next);
1076
1290
  }
1077
- async runUntilYield(conversationId) {
1291
+ async runUntilYield(checkpointKey) {
1078
1292
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1079
1293
  let lifecyclePhase = "completed";
1294
+ let initialState = null;
1295
+ try {
1296
+ initialState = await this.loadInitialState(checkpointKey);
1297
+ } catch (err) {
1298
+ lifecyclePhase = "failed";
1299
+ this.telemetryPort.emit({
1300
+ kind: "run_lifecycle",
1301
+ runId,
1302
+ phase: "spawned",
1303
+ scope: {}
1304
+ });
1305
+ this.telemetryPort.emit({
1306
+ kind: "run_lifecycle",
1307
+ runId,
1308
+ phase: lifecyclePhase,
1309
+ scope: {}
1310
+ });
1311
+ throw err;
1312
+ }
1313
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1314
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1080
1315
  this.telemetryPort.emit({
1081
1316
  kind: "run_lifecycle",
1082
1317
  runId,
1083
1318
  phase: "spawned",
1084
- scope: { conversationId: conversationId || void 0 }
1319
+ scope: {
1320
+ conversationId: lifecycleConversationId,
1321
+ turnId: lifecycleTurnId
1322
+ }
1085
1323
  });
1086
1324
  try {
1087
- return await this.runUntilYieldInternal(conversationId);
1325
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1326
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1327
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1328
+ return result;
1088
1329
  } catch (err) {
1089
1330
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1090
1331
  throw err;
@@ -1093,17 +1334,23 @@ var GraphExecutor = class {
1093
1334
  kind: "run_lifecycle",
1094
1335
  runId,
1095
1336
  phase: lifecyclePhase,
1096
- scope: { conversationId: conversationId || void 0 }
1337
+ scope: {
1338
+ conversationId: lifecycleConversationId,
1339
+ turnId: lifecycleTurnId
1340
+ }
1097
1341
  });
1098
1342
  }
1099
1343
  }
1100
- async runUntilYieldInternal(conversationId) {
1101
- let state = await this.checkpointer.load(conversationId) || {
1344
+ async loadInitialState(checkpointKey) {
1345
+ return await this.checkpointer.load(checkpointKey) || {
1102
1346
  nodeId: "user",
1103
1347
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1104
1348
  local: {}
1105
1349
  };
1106
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1350
+ }
1351
+ async runUntilYieldInternal(checkpointKey, initialState) {
1352
+ let state = initialState;
1353
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1107
1354
  state = {
1108
1355
  ...state,
1109
1356
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1132,7 +1379,7 @@ var GraphExecutor = class {
1132
1379
  const signalRaw = state.local?.signal;
1133
1380
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1134
1381
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1135
- this.ephemeralLocals.delete(conversationId);
1382
+ this.ephemeralLocals.delete(checkpointKey);
1136
1383
  throwAbortError();
1137
1384
  }
1138
1385
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1180,8 +1427,8 @@ var GraphExecutor = class {
1180
1427
  checkpointCount
1181
1428
  });
1182
1429
  const cp2 = this.sanitize(state);
1183
- await this.checkpointer.save(conversationId, cp2);
1184
- this.ephemeralLocals.delete(conversationId);
1430
+ await this.checkpointer.save(checkpointKey, cp2);
1431
+ this.ephemeralLocals.delete(checkpointKey);
1185
1432
  return { events: allEvents, checkpoint: cp2, stepCount };
1186
1433
  }
1187
1434
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1192,18 +1439,18 @@ var GraphExecutor = class {
1192
1439
  });
1193
1440
  const nodeRunStartedAt = Date.now();
1194
1441
  const nodeIdForTelemetry = state.nodeId;
1442
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1195
1443
  let result;
1196
1444
  try {
1197
1445
  result = await node.run(state);
1198
1446
  } finally {
1199
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1200
1447
  this.telemetryPort.emit({
1201
1448
  kind: "graph_node",
1202
1449
  nodeId: nodeIdForTelemetry,
1203
1450
  durationMs: Date.now() - nodeRunStartedAt,
1204
1451
  scope: {
1205
- conversationId: conversationId || void 0,
1206
- turnId: turnIdForTelemetry
1452
+ conversationId: conversationIdForTelemetry,
1453
+ turnId: readRuntimeTurnId(state)
1207
1454
  }
1208
1455
  });
1209
1456
  }
@@ -1242,7 +1489,7 @@ var GraphExecutor = class {
1242
1489
  });
1243
1490
  state = { ...state, nodeId: nextNodeId };
1244
1491
  const cp2 = this.sanitize(state);
1245
- await this.checkpointer.save(conversationId, cp2);
1492
+ await this.checkpointer.save(checkpointKey, cp2);
1246
1493
  continue;
1247
1494
  }
1248
1495
  if (result.kind === "yield") {
@@ -1253,7 +1500,7 @@ var GraphExecutor = class {
1253
1500
  checkpointCount
1254
1501
  });
1255
1502
  const cp2 = this.sanitize(state);
1256
- await this.checkpointer.save(conversationId, cp2);
1503
+ await this.checkpointer.save(checkpointKey, cp2);
1257
1504
  return { events: allEvents, checkpoint: cp2, stepCount };
1258
1505
  }
1259
1506
  if (result.kind === "pause") {
@@ -1264,7 +1511,7 @@ var GraphExecutor = class {
1264
1511
  checkpointCount
1265
1512
  });
1266
1513
  const cp2 = this.sanitize(state);
1267
- await this.checkpointer.save(conversationId, cp2);
1514
+ await this.checkpointer.save(checkpointKey, cp2);
1268
1515
  return { events: allEvents, checkpoint: cp2, stepCount };
1269
1516
  }
1270
1517
  }
@@ -1275,8 +1522,8 @@ var GraphExecutor = class {
1275
1522
  checkpointCount
1276
1523
  });
1277
1524
  const cp = this.sanitize(state);
1278
- await this.checkpointer.save(conversationId, cp);
1279
- this.ephemeralLocals.delete(conversationId);
1525
+ await this.checkpointer.save(checkpointKey, cp);
1526
+ this.ephemeralLocals.delete(checkpointKey);
1280
1527
  return { events: allEvents, checkpoint: cp, stepCount };
1281
1528
  }
1282
1529
  };
@@ -1372,6 +1619,190 @@ var noopAudit = {
1372
1619
  flush() {
1373
1620
  }
1374
1621
  };
1622
+ var TokenCalculator = class {
1623
+ static BYTES_PER_TOKEN_LATIN = 4;
1624
+ static BYTES_PER_TOKEN_CJK = 3;
1625
+ static OVERHEAD_PER_MESSAGE = 5;
1626
+ static OVERHEAD_PER_TOOL_CALL = 10;
1627
+ static encoderCache = /* @__PURE__ */ new Map();
1628
+ static DEFAULT_ENCODING = "cl100k_base";
1629
+ static SUPPORTED_ENCODINGS = [
1630
+ "gpt2",
1631
+ "r50k_base",
1632
+ "p50k_base",
1633
+ "p50k_edit",
1634
+ "cl100k_base",
1635
+ "o200k_base"
1636
+ ];
1637
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1638
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1639
+ if (this.isSupportedEncodingName(normalized)) {
1640
+ return normalized;
1641
+ }
1642
+ if (normalized.includes("deepseek")) {
1643
+ return "cl100k_base";
1644
+ }
1645
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1646
+ return "o200k_base";
1647
+ }
1648
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1649
+ return "cl100k_base";
1650
+ }
1651
+ return this.DEFAULT_ENCODING;
1652
+ }
1653
+ static isSupportedEncodingName(value) {
1654
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1655
+ }
1656
+ static getEncoder(modelIdentifierOrEncoding) {
1657
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1658
+ const cached = this.encoderCache.get(encodingName);
1659
+ if (cached) {
1660
+ return cached;
1661
+ }
1662
+ const encoder = tiktoken.get_encoding(encodingName);
1663
+ this.encoderCache.set(encodingName, encoder);
1664
+ return encoder;
1665
+ }
1666
+ static estimateTokensRough(text, _modelIdentifier) {
1667
+ if (!text) return 0;
1668
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1669
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1670
+ const byteLength = new TextEncoder().encode(text).length;
1671
+ return Math.ceil(byteLength / ratio);
1672
+ }
1673
+ static estimateTokens(text, options = {}) {
1674
+ if (!text) return 0;
1675
+ if (options.encoding) {
1676
+ try {
1677
+ return this.estimateTokensPrecise(text, options.encoding);
1678
+ } catch {
1679
+ }
1680
+ }
1681
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1682
+ return Math.ceil(text.length / avgCharsPerToken);
1683
+ }
1684
+ static estimateTokensPrecise(text, modelIdentifier) {
1685
+ if (!text) return 0;
1686
+ const encoder = this.getEncoder(modelIdentifier);
1687
+ return encoder.encode(text).length;
1688
+ }
1689
+ static estimateMessageTokens(message, options = {}) {
1690
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1691
+ if (message.content) {
1692
+ totalTokens += this.estimateTokens(String(message.content), options);
1693
+ }
1694
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1695
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1696
+ for (const toolCall of toolCalls) {
1697
+ totalTokens += toolCallOverhead;
1698
+ const fn = toolCall["function"];
1699
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1700
+ const fnRecord = fn;
1701
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1702
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1703
+ }
1704
+ }
1705
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1706
+ if (toolCallId) {
1707
+ totalTokens += this.estimateTokens(toolCallId, options);
1708
+ }
1709
+ return totalTokens;
1710
+ }
1711
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1712
+ return this.estimateMessageTokens(message, {
1713
+ encoding: modelIdentifier,
1714
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1715
+ });
1716
+ }
1717
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1718
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1719
+ }
1720
+ static extractToolCallsForTokenEstimate(message) {
1721
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1722
+ if (Array.isArray(direct)) return direct;
1723
+ const metadata = "metadata" in message ? message.metadata : void 0;
1724
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1725
+ const metadataRecord = metadata;
1726
+ const metadataToolCalls = metadataRecord["tool_calls"];
1727
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1728
+ }
1729
+ static extractToolCallIdForTokenEstimate(message) {
1730
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1731
+ return message.tool_call_id;
1732
+ }
1733
+ const metadata = "metadata" in message ? message.metadata : void 0;
1734
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1735
+ const metadataRecord = metadata;
1736
+ const toolCallId = metadataRecord["tool_call_id"];
1737
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1738
+ }
1739
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1740
+ if (!text || maxTokens <= 0) return "";
1741
+ const encoder = this.getEncoder(modelIdentifier);
1742
+ const tokens = encoder.encode(text);
1743
+ if (tokens.length <= maxTokens) {
1744
+ return text;
1745
+ }
1746
+ let truncatedTokens;
1747
+ const ellipsis = "...";
1748
+ switch (strategy) {
1749
+ case "start":
1750
+ truncatedTokens = tokens.slice(0, maxTokens);
1751
+ return encoder.decode(truncatedTokens) + ellipsis;
1752
+ case "end":
1753
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1754
+ return ellipsis + encoder.decode(truncatedTokens);
1755
+ case "middle": {
1756
+ const half = Math.floor(maxTokens / 2);
1757
+ const head = tokens.slice(0, half);
1758
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1759
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1760
+ }
1761
+ default:
1762
+ truncatedTokens = tokens.slice(0, maxTokens);
1763
+ return encoder.decode(truncatedTokens) + ellipsis;
1764
+ }
1765
+ }
1766
+ static cleanup() {
1767
+ for (const encoder of this.encoderCache.values()) {
1768
+ encoder.free();
1769
+ }
1770
+ this.encoderCache.clear();
1771
+ }
1772
+ };
1773
+ function normalizePositiveNumber(value, fallback) {
1774
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1775
+ }
1776
+ function normalizeNonNegativeInteger(value, fallback) {
1777
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1778
+ return fallback;
1779
+ }
1780
+ return Math.max(0, Math.floor(value));
1781
+ }
1782
+
1783
+ // src/shared/defaultTokenizerPort.ts
1784
+ var DefaultTokenizerPort = class {
1785
+ constructor(config = {}) {
1786
+ this.config = config;
1787
+ }
1788
+ config;
1789
+ estimateText(text, _modelId) {
1790
+ return TokenCalculator.estimateTokens(text, {
1791
+ encoding: this.config.encoding,
1792
+ avgCharsPerToken: this.config.avgCharsPerToken
1793
+ });
1794
+ }
1795
+ estimateMessage(message, _modelId) {
1796
+ return TokenCalculator.estimateMessageTokens(message, {
1797
+ encoding: this.config.encoding,
1798
+ avgCharsPerToken: this.config.avgCharsPerToken,
1799
+ toolCallOverhead: this.config.toolCallOverhead
1800
+ });
1801
+ }
1802
+ };
1803
+ function createDefaultTokenizerPort(config = {}) {
1804
+ return new DefaultTokenizerPort(config);
1805
+ }
1375
1806
 
1376
1807
  // src/shared/ids.ts
1377
1808
  function isoRandomUUID() {
@@ -1473,15 +1904,15 @@ function splitConcatenatedJsonObjects(input) {
1473
1904
  }
1474
1905
 
1475
1906
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1476
- function readNonEmptyString(value) {
1907
+ function readNonEmptyString2(value) {
1477
1908
  if (typeof value !== "string") return void 0;
1478
1909
  const trimmed = value.trim();
1479
1910
  return trimmed.length > 0 ? trimmed : void 0;
1480
1911
  }
1481
1912
  function resolveConversationIdForRuntimeEvents(toolContext) {
1482
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
1913
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
1483
1914
  if (fromCamel) return fromCamel;
1484
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
1915
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
1485
1916
  if (fromSnake) return fromSnake;
1486
1917
  return generateMessageId();
1487
1918
  }
@@ -1552,6 +1983,13 @@ function resolveUsage(response) {
1552
1983
  }
1553
1984
  return response.usage;
1554
1985
  }
1986
+ function resolveCanonicalUsage(response) {
1987
+ if (!response || typeof response === "string") {
1988
+ return void 0;
1989
+ }
1990
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
1991
+ return parsed.success ? parsed.data : void 0;
1992
+ }
1555
1993
  function resolveToolCalls(response) {
1556
1994
  if (!response || typeof response === "string") {
1557
1995
  return void 0;
@@ -1562,227 +2000,100 @@ function resolveReasoningDetails(response) {
1562
2000
  if (!response || typeof response === "string") {
1563
2001
  return void 0;
1564
2002
  }
1565
- return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
1566
- }
1567
- function resolveToolNamesForAudit(ctx) {
1568
- if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
1569
- return [];
1570
- }
1571
- return ctx.toolSchemas.map((tool) => tool.function.name);
1572
- }
1573
- function recordBeforeContextManager(params) {
1574
- }
1575
- function recordAfterContextManager(params) {
1576
- }
1577
- function recordAfterContextManagerOnSystemReminderHit(params) {
1578
- }
1579
- function recordToolProtocolError(params) {
1580
- }
1581
- function recordRunTranscript(params) {
1582
- }
1583
-
1584
- // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
1585
- var contextAuditMiddleware = async (ctx, stage, next) => {
1586
- if (stage.id === "build_context") {
1587
- recordBeforeContextManager({
1588
- mode: ctx.request.mode === "chat" ? "chat" : "agent",
1589
- payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
1590
- });
1591
- }
1592
- await next();
1593
- if (stage.id !== "apply_system_reminder") {
1594
- return;
1595
- }
1596
- resolveToolNamesForAudit(ctx);
1597
- recordAfterContextManager({
1598
- mode: ctx.mode,
1599
- llmMessages: ctx.llmMessages,
1600
- contextTrace: ctx.contextTrace
1601
- });
1602
- if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
1603
- recordAfterContextManagerOnSystemReminderHit({
1604
- mode: ctx.mode,
1605
- llmMessages: ctx.llmMessages,
1606
- systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
1607
- contextTrace: ctx.contextTrace
1608
- });
1609
- }
1610
- };
1611
- var TokenCalculator = class {
1612
- static BYTES_PER_TOKEN_LATIN = 4;
1613
- static BYTES_PER_TOKEN_CJK = 3;
1614
- static OVERHEAD_PER_MESSAGE = 5;
1615
- static OVERHEAD_PER_TOOL_CALL = 10;
1616
- static encoderCache = /* @__PURE__ */ new Map();
1617
- static DEFAULT_ENCODING = "cl100k_base";
1618
- static SUPPORTED_ENCODINGS = [
1619
- "gpt2",
1620
- "r50k_base",
1621
- "p50k_base",
1622
- "p50k_edit",
1623
- "cl100k_base",
1624
- "o200k_base"
1625
- ];
1626
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1627
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1628
- if (this.isSupportedEncodingName(normalized)) {
1629
- return normalized;
1630
- }
1631
- if (normalized.includes("deepseek")) {
1632
- return "cl100k_base";
1633
- }
1634
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1635
- return "o200k_base";
1636
- }
1637
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1638
- return "cl100k_base";
1639
- }
1640
- return this.DEFAULT_ENCODING;
1641
- }
1642
- static isSupportedEncodingName(value) {
1643
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1644
- }
1645
- static getEncoder(modelIdentifierOrEncoding) {
1646
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1647
- const cached = this.encoderCache.get(encodingName);
1648
- if (cached) {
1649
- return cached;
1650
- }
1651
- const encoder = tiktoken.get_encoding(encodingName);
1652
- this.encoderCache.set(encodingName, encoder);
1653
- return encoder;
1654
- }
1655
- static estimateTokensRough(text, _modelIdentifier) {
1656
- if (!text) return 0;
1657
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1658
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1659
- const byteLength = new TextEncoder().encode(text).length;
1660
- return Math.ceil(byteLength / ratio);
1661
- }
1662
- static estimateTokens(text, options = {}) {
1663
- if (!text) return 0;
1664
- if (options.encoding) {
1665
- try {
1666
- return this.estimateTokensPrecise(text, options.encoding);
1667
- } catch {
1668
- }
1669
- }
1670
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1671
- return Math.ceil(text.length / avgCharsPerToken);
1672
- }
1673
- static estimateTokensPrecise(text, modelIdentifier) {
1674
- if (!text) return 0;
1675
- const encoder = this.getEncoder(modelIdentifier);
1676
- return encoder.encode(text).length;
1677
- }
1678
- static estimateMessageTokens(message, options = {}) {
1679
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1680
- if (message.content) {
1681
- totalTokens += this.estimateTokens(String(message.content), options);
1682
- }
1683
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1684
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1685
- for (const toolCall of toolCalls) {
1686
- totalTokens += toolCallOverhead;
1687
- const fn = toolCall["function"];
1688
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1689
- const fnRecord = fn;
1690
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1691
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1692
- }
1693
- }
1694
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1695
- if (toolCallId) {
1696
- totalTokens += this.estimateTokens(toolCallId, options);
1697
- }
1698
- return totalTokens;
1699
- }
1700
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1701
- return this.estimateMessageTokens(message, {
1702
- encoding: modelIdentifier,
1703
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1704
- });
1705
- }
1706
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1707
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1708
- }
1709
- static extractToolCallsForTokenEstimate(message) {
1710
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1711
- if (Array.isArray(direct)) return direct;
1712
- const metadata = "metadata" in message ? message.metadata : void 0;
1713
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1714
- const metadataRecord = metadata;
1715
- const metadataToolCalls = metadataRecord["tool_calls"];
1716
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1717
- }
1718
- static extractToolCallIdForTokenEstimate(message) {
1719
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1720
- return message.tool_call_id;
1721
- }
1722
- const metadata = "metadata" in message ? message.metadata : void 0;
1723
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1724
- const metadataRecord = metadata;
1725
- const toolCallId = metadataRecord["tool_call_id"];
1726
- return typeof toolCallId === "string" ? toolCallId : void 0;
2003
+ return Array.isArray(response.reasoning_details) ? response.reasoning_details : void 0;
2004
+ }
2005
+ function resolveToolNamesForAudit(ctx) {
2006
+ if (ctx.forceFinalAnswer || ctx.request.enableTools === false || ctx.toolSchemas.length === 0) {
2007
+ return [];
1727
2008
  }
1728
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1729
- if (!text || maxTokens <= 0) return "";
1730
- const encoder = this.getEncoder(modelIdentifier);
1731
- const tokens = encoder.encode(text);
1732
- if (tokens.length <= maxTokens) {
1733
- return text;
1734
- }
1735
- let truncatedTokens;
1736
- const ellipsis = "...";
1737
- switch (strategy) {
1738
- case "start":
1739
- truncatedTokens = tokens.slice(0, maxTokens);
1740
- return encoder.decode(truncatedTokens) + ellipsis;
1741
- case "end":
1742
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1743
- return ellipsis + encoder.decode(truncatedTokens);
1744
- case "middle": {
1745
- const half = Math.floor(maxTokens / 2);
1746
- const head = tokens.slice(0, half);
1747
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1748
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1749
- }
1750
- default:
1751
- truncatedTokens = tokens.slice(0, maxTokens);
1752
- return encoder.decode(truncatedTokens) + ellipsis;
1753
- }
2009
+ return ctx.toolSchemas.map((tool) => tool.function.name);
2010
+ }
2011
+ function recordBeforeContextManager(params) {
2012
+ }
2013
+ function recordAfterContextManager(params) {
2014
+ }
2015
+ function recordAfterContextManagerOnSystemReminderHit(params) {
2016
+ }
2017
+ function recordToolProtocolError(params) {
2018
+ }
2019
+ function recordRunTranscript(params) {
2020
+ }
2021
+
2022
+ // src/runtime-kernel/graph-engine/tick-pipeline/middlewares/contextAuditMiddleware.ts
2023
+ var contextAuditMiddleware = async (ctx, stage, next) => {
2024
+ if (stage.id === "build_context") {
2025
+ recordBeforeContextManager({
2026
+ mode: ctx.request.mode === "chat" ? "chat" : "agent",
2027
+ payload: ctx.request.mode === "chat" ? { request: ctx.request } : { request: ctx.request, history: ctx.history }
2028
+ });
1754
2029
  }
1755
- static cleanup() {
1756
- for (const encoder of this.encoderCache.values()) {
1757
- encoder.free();
1758
- }
1759
- this.encoderCache.clear();
2030
+ await next();
2031
+ if (stage.id !== "apply_system_reminder") {
2032
+ return;
2033
+ }
2034
+ resolveToolNamesForAudit(ctx);
2035
+ recordAfterContextManager({
2036
+ mode: ctx.mode,
2037
+ llmMessages: ctx.llmMessages,
2038
+ contextTrace: ctx.contextTrace
2039
+ });
2040
+ if (Array.isArray(ctx.systemReminderHitRuleIds) && ctx.systemReminderHitRuleIds.length > 0) {
2041
+ recordAfterContextManagerOnSystemReminderHit({
2042
+ mode: ctx.mode,
2043
+ llmMessages: ctx.llmMessages,
2044
+ systemReminder: { ruleIds: ctx.systemReminderHitRuleIds },
2045
+ contextTrace: ctx.contextTrace
2046
+ });
1760
2047
  }
1761
2048
  };
1762
- function normalizePositiveNumber(value, fallback) {
1763
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2049
+ var als = new async_hooks.AsyncLocalStorage();
2050
+ function readTokenCount(record, key) {
2051
+ const value = record[key];
2052
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1764
2053
  }
1765
- function normalizeNonNegativeInteger(value, fallback) {
1766
- if (typeof value !== "number" || !Number.isFinite(value)) {
1767
- return fallback;
1768
- }
1769
- return Math.max(0, Math.floor(value));
2054
+ function readRecord(record, key) {
2055
+ const value = record[key];
2056
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2057
+ return Object.fromEntries(Object.entries(value));
1770
2058
  }
1771
- var als = new async_hooks.AsyncLocalStorage();
1772
- function normalizeLlmUsage(usage) {
2059
+ function normalizedUsageFromCanonical(canonicalUsage) {
2060
+ return {
2061
+ promptTokens: canonicalUsage.inputTokens,
2062
+ completionTokens: canonicalUsage.outputTokens,
2063
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2064
+ canonicalUsage
2065
+ };
2066
+ }
2067
+ function normalizeCanonicalLlmUsage(usage) {
1773
2068
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1774
2069
  const rec = usage;
1775
- const promptTokensRaw = rec["prompt_tokens"];
1776
- const completionTokensRaw = rec["completion_tokens"];
1777
- const totalTokensRaw = rec["total_tokens"];
1778
- const tokensRaw = rec["tokens"];
1779
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1780
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1781
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1782
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1783
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1784
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1785
- return { promptTokens, completionTokens, totalTokens };
2070
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2071
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2072
+ if (inputTokens === void 0 || outputTokens === void 0) {
2073
+ return void 0;
2074
+ }
2075
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2076
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2077
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2078
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2079
+ const totalTokens = readTokenCount(rec, "total_tokens");
2080
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2081
+ return void 0;
2082
+ }
2083
+ return {
2084
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2085
+ outputTokens,
2086
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2087
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2088
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2089
+ source: "provider-response-usage",
2090
+ confidence: "actual",
2091
+ rawUsage: usage
2092
+ };
2093
+ }
2094
+ function normalizeLlmUsage(usage) {
2095
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2096
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1786
2097
  }
1787
2098
  function recordLlmCallTelemetry(entry) {
1788
2099
  const store = als.getStore();
@@ -1796,17 +2107,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1796
2107
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1797
2108
  return;
1798
2109
  }
1799
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2110
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2111
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1800
2112
  const respText = extractResponseText(ctx.llmResp);
1801
2113
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1802
2114
  try {
1803
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1804
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1805
- return {
1806
- promptTokens,
1807
- completionTokens,
1808
- totalTokens: promptTokens + completionTokens
1809
- };
2115
+ const promptTokens = ctx.llmMessages.reduce(
2116
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2117
+ 0
2118
+ );
2119
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2120
+ return normalizedUsageFromCanonical({
2121
+ inputTokens: promptTokens,
2122
+ outputTokens: completionTokens,
2123
+ totalTokens: promptTokens + completionTokens,
2124
+ source: "local-estimate",
2125
+ confidence: "estimate"
2126
+ });
1810
2127
  } catch {
1811
2128
  return void 0;
1812
2129
  }
@@ -1816,7 +2133,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1816
2133
  stream: ctx.input.stream === true,
1817
2134
  startedAt: ctx.llmCallStartedAt,
1818
2135
  durationMs: ctx.llmCallDurationMs,
1819
- usage: normalizedUsage
2136
+ usage: normalizedUsage,
2137
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1820
2138
  });
1821
2139
  ctx.telemetry.emit({
1822
2140
  kind: "llm_call",
@@ -1824,6 +2142,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1824
2142
  stream: ctx.input.stream === true,
1825
2143
  durationMs: ctx.llmCallDurationMs,
1826
2144
  usage: normalizedUsage,
2145
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1827
2146
  scope: {
1828
2147
  conversationId: ctx.conversationId || void 0,
1829
2148
  turnId: ctx.turnId,
@@ -1840,7 +2159,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
1840
2159
  if (stage.id !== "execute_llm") {
1841
2160
  return;
1842
2161
  }
1843
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2162
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
1844
2163
  if (!normalized) {
1845
2164
  return;
1846
2165
  }
@@ -1967,10 +2286,10 @@ var contextBudgetWarningTemplate = (ctx) => {
1967
2286
  return [
1968
2287
  `\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`,
1969
2288
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
1970
- "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",
2289
+ "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",
1971
2290
  `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`,
1972
2291
  ' \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',
1973
- "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"
2292
+ "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"
1974
2293
  ].join("\n");
1975
2294
  };
1976
2295
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2278,6 +2597,219 @@ function createApplySystemReminderStage() {
2278
2597
  };
2279
2598
  }
2280
2599
 
2600
+ // src/runtime-kernel/token-accounting/index.ts
2601
+ var token_accounting_exports = {};
2602
+ __export(token_accounting_exports, {
2603
+ addLedgerAggregate: () => addLedgerAggregate,
2604
+ addUsageTotals: () => addUsageTotals,
2605
+ aggregateCanonicalUsage: () => aggregateCanonicalUsage,
2606
+ aggregateTokenLedgerEntries: () => aggregateTokenLedgerEntries,
2607
+ computeCost: () => computeCost,
2608
+ createContextComponentLedgerEntry: () => createContextComponentLedgerEntry,
2609
+ createLlmUsageLedgerEntry: () => createLlmUsageLedgerEntry,
2610
+ createRunTokenUsageAggregate: () => createRunTokenUsageAggregate
2611
+ });
2612
+
2613
+ // src/runtime-kernel/token-accounting/functions.ts
2614
+ var EMPTY_LEDGER_AGGREGATE = {
2615
+ contextTokens: 0,
2616
+ entryCount: 0,
2617
+ llmCallCount: 0,
2618
+ contextComponentCount: 0
2619
+ };
2620
+ var TOKEN_PRICE_UNIT = 1e6;
2621
+ function sumReportedOptional(values) {
2622
+ const reported = values.filter((value) => value !== void 0);
2623
+ if (reported.length === 0) {
2624
+ return void 0;
2625
+ }
2626
+ return reported.reduce((total, value) => total + value, 0);
2627
+ }
2628
+ function sumTotalTokens(usages) {
2629
+ if (usages.length === 0 || usages.some((usage) => usage.totalTokens === void 0)) {
2630
+ return void 0;
2631
+ }
2632
+ return usages.reduce((total, usage) => total + (usage.totalTokens ?? 0), 0);
2633
+ }
2634
+ function aggregateCanonicalUsage(usages) {
2635
+ if (usages.length === 0) {
2636
+ return void 0;
2637
+ }
2638
+ return {
2639
+ inputTokens: usages.reduce((total, usage) => total + usage.inputTokens, 0),
2640
+ outputTokens: usages.reduce((total, usage) => total + usage.outputTokens, 0),
2641
+ reasoningTokens: sumReportedOptional(usages.map((usage) => usage.reasoningTokens)),
2642
+ cacheReadTokens: sumReportedOptional(usages.map((usage) => usage.cacheReadTokens)),
2643
+ cacheWriteTokens: sumReportedOptional(usages.map((usage) => usage.cacheWriteTokens)),
2644
+ totalTokens: sumTotalTokens(usages),
2645
+ usageCount: usages.length
2646
+ };
2647
+ }
2648
+ function createLlmUsageLedgerEntry(input) {
2649
+ return {
2650
+ ...input,
2651
+ kind: "llm-usage"
2652
+ };
2653
+ }
2654
+ function createContextComponentLedgerEntry(input) {
2655
+ return {
2656
+ ...input,
2657
+ kind: "context-component",
2658
+ components: [...input.components],
2659
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2660
+ };
2661
+ }
2662
+ function addUsageTotals(left, right) {
2663
+ if (!left) {
2664
+ return right;
2665
+ }
2666
+ if (!right) {
2667
+ return left;
2668
+ }
2669
+ return {
2670
+ inputTokens: left.inputTokens + right.inputTokens,
2671
+ outputTokens: left.outputTokens + right.outputTokens,
2672
+ reasoningTokens: sumReportedOptional([left.reasoningTokens, right.reasoningTokens]),
2673
+ cacheReadTokens: sumReportedOptional([left.cacheReadTokens, right.cacheReadTokens]),
2674
+ cacheWriteTokens: sumReportedOptional([left.cacheWriteTokens, right.cacheWriteTokens]),
2675
+ totalTokens: left.totalTokens === void 0 || right.totalTokens === void 0 ? void 0 : left.totalTokens + right.totalTokens,
2676
+ usageCount: left.usageCount + right.usageCount
2677
+ };
2678
+ }
2679
+ function addLedgerAggregate(left, right) {
2680
+ return {
2681
+ llmUsage: addUsageTotals(left.llmUsage, right.llmUsage),
2682
+ contextTokens: left.contextTokens + right.contextTokens,
2683
+ entryCount: left.entryCount + right.entryCount,
2684
+ llmCallCount: left.llmCallCount + right.llmCallCount,
2685
+ contextComponentCount: left.contextComponentCount + right.contextComponentCount
2686
+ };
2687
+ }
2688
+ function aggregateTokenLedgerEntries(entries) {
2689
+ const llmUsages = entries.filter((entry) => entry.kind === "llm-usage").map((entry) => entry.usage);
2690
+ return entries.reduce((aggregate, entry) => {
2691
+ if (entry.kind === "llm-usage") {
2692
+ return {
2693
+ ...aggregate,
2694
+ entryCount: aggregate.entryCount + 1,
2695
+ llmCallCount: aggregate.llmCallCount + 1
2696
+ };
2697
+ }
2698
+ return {
2699
+ ...aggregate,
2700
+ contextTokens: aggregate.contextTokens + entry.totalTokens,
2701
+ entryCount: aggregate.entryCount + 1,
2702
+ contextComponentCount: aggregate.contextComponentCount + entry.components.length
2703
+ };
2704
+ }, {
2705
+ ...EMPTY_LEDGER_AGGREGATE,
2706
+ llmUsage: aggregateCanonicalUsage(llmUsages)
2707
+ });
2708
+ }
2709
+ function createRunTokenUsageAggregate(input) {
2710
+ const children = input.childAggregates?.reduce(
2711
+ (aggregate, child) => addLedgerAggregate(aggregate, child),
2712
+ EMPTY_LEDGER_AGGREGATE
2713
+ );
2714
+ return children && children.entryCount > 0 ? { own: aggregateTokenLedgerEntries(input.ownEntries), children } : { own: aggregateTokenLedgerEntries(input.ownEntries) };
2715
+ }
2716
+ function componentCost(tokens, pricePerMillion) {
2717
+ return tokens / TOKEN_PRICE_UNIT * pricePerMillion;
2718
+ }
2719
+ function needsPrice(tokens) {
2720
+ return tokens !== void 0 && tokens > 0;
2721
+ }
2722
+ function missingPriceComponents(usage, pricing) {
2723
+ const missing = [];
2724
+ if (!pricing) {
2725
+ if (needsPrice(usage.inputTokens)) {
2726
+ missing.push("input");
2727
+ }
2728
+ if (needsPrice(usage.outputTokens)) {
2729
+ missing.push("output");
2730
+ }
2731
+ if (needsPrice(usage.reasoningTokens)) {
2732
+ missing.push("reasoning");
2733
+ }
2734
+ if (needsPrice(usage.cacheReadTokens)) {
2735
+ missing.push("cacheRead");
2736
+ }
2737
+ if (needsPrice(usage.cacheWriteTokens)) {
2738
+ missing.push("cacheWrite");
2739
+ }
2740
+ return missing;
2741
+ }
2742
+ if (needsPrice(usage.inputTokens) && pricing.input === void 0) {
2743
+ missing.push("input");
2744
+ }
2745
+ if (needsPrice(usage.outputTokens) && pricing.output === void 0) {
2746
+ missing.push("output");
2747
+ }
2748
+ if (needsPrice(usage.reasoningTokens) && pricing.reasoning === void 0) {
2749
+ missing.push("reasoning");
2750
+ }
2751
+ if (needsPrice(usage.cacheReadTokens) && pricing.cacheRead === void 0) {
2752
+ missing.push("cacheRead");
2753
+ }
2754
+ if (needsPrice(usage.cacheWriteTokens) && pricing.cacheWrite === void 0) {
2755
+ missing.push("cacheWrite");
2756
+ }
2757
+ return missing;
2758
+ }
2759
+ function reportedComponentCost(tokens, pricePerMillion) {
2760
+ if (tokens === void 0) {
2761
+ return void 0;
2762
+ }
2763
+ if (tokens === 0) {
2764
+ return 0;
2765
+ }
2766
+ return pricePerMillion === void 0 ? void 0 : componentCost(tokens, pricePerMillion);
2767
+ }
2768
+ function requiredComponentCost(tokens, pricePerMillion) {
2769
+ if (tokens === 0) {
2770
+ return 0;
2771
+ }
2772
+ return componentCost(tokens, pricePerMillion ?? 0);
2773
+ }
2774
+ function sumComputedCosts(costs) {
2775
+ let total = 0;
2776
+ for (const cost of costs) {
2777
+ total += cost ?? 0;
2778
+ }
2779
+ return total;
2780
+ }
2781
+ function computeCost(usage, pricing) {
2782
+ const missing = missingPriceComponents(usage, pricing);
2783
+ if (!pricing || missing.length > 0) {
2784
+ return {
2785
+ status: "unknown",
2786
+ ...pricing ? { currency: pricing.currency } : {},
2787
+ ...missing.length > 0 ? { missingPriceComponents: missing } : {}
2788
+ };
2789
+ }
2790
+ const inputCost = requiredComponentCost(usage.inputTokens, pricing.input);
2791
+ const outputCost = requiredComponentCost(usage.outputTokens, pricing.output);
2792
+ const reasoningCost = reportedComponentCost(usage.reasoningTokens, pricing.reasoning);
2793
+ const cacheReadCost = reportedComponentCost(usage.cacheReadTokens, pricing.cacheRead);
2794
+ const cacheWriteCost = reportedComponentCost(usage.cacheWriteTokens, pricing.cacheWrite);
2795
+ return {
2796
+ status: "computed",
2797
+ currency: pricing.currency,
2798
+ inputCost,
2799
+ outputCost,
2800
+ reasoningCost,
2801
+ cacheReadCost,
2802
+ cacheWriteCost,
2803
+ totalCost: sumComputedCosts([
2804
+ inputCost,
2805
+ outputCost,
2806
+ reasoningCost,
2807
+ cacheReadCost,
2808
+ cacheWriteCost
2809
+ ])
2810
+ };
2811
+ }
2812
+
2281
2813
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2282
2814
  var logger4 = new Logger("GraphAgentExecutor");
2283
2815
  function createBuildContextStage(dependencies) {
@@ -2294,6 +2826,23 @@ function createBuildContextStage(dependencies) {
2294
2826
  ctx.mode = contextBuildResult.mode;
2295
2827
  ctx.llmMessages = contextBuildResult.llmMessages;
2296
2828
  ctx.contextTrace = contextBuildResult.contextTrace;
2829
+ if (contextBuildResult.tokenEstimate) {
2830
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2831
+ ctx.telemetry.emit({
2832
+ kind: "context_build",
2833
+ modelId: ctx.modelId,
2834
+ mode: contextBuildResult.mode,
2835
+ tokenEstimate: contextBuildResult.tokenEstimate,
2836
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2837
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2838
+ scope: {
2839
+ conversationId: ctx.conversationId,
2840
+ runId: ctx.input.toolContext?.runId,
2841
+ parentRunId: ctx.input.toolContext?.parentRunId,
2842
+ turnId: ctx.turnId
2843
+ }
2844
+ });
2845
+ }
2297
2846
  for (const event of contextBuildResult.summaryEvents) {
2298
2847
  if (!isHistorySummaryEvent(event)) {
2299
2848
  continue;
@@ -2308,6 +2857,24 @@ function createBuildContextStage(dependencies) {
2308
2857
  }
2309
2858
  };
2310
2859
  }
2860
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2861
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2862
+ if (keptComponents.length === 0) {
2863
+ return void 0;
2864
+ }
2865
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2866
+ const createdAt = Date.now();
2867
+ return createContextComponentLedgerEntry({
2868
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2869
+ conversationId: ctx.conversationId,
2870
+ runId,
2871
+ parentRunId: ctx.input.toolContext?.parentRunId,
2872
+ turnId: ctx.turnId,
2873
+ route: contextBuildResult.tokenEstimate?.route,
2874
+ createdAt,
2875
+ components: keptComponents
2876
+ });
2877
+ }
2311
2878
 
2312
2879
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2313
2880
  function createBuildDecisionStage(dependencies) {
@@ -2441,7 +3008,7 @@ function createExecuteLlmStage(dependencies) {
2441
3008
  streamEventHandler,
2442
3009
  ctx.signal,
2443
3010
  (fallbackModelId) => {
2444
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
3011
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2445
3012
  },
2446
3013
  (info) => {
2447
3014
  ctx.modelFallbackAudit = info;
@@ -2485,7 +3052,7 @@ function createPrepareCallStage(dependencies) {
2485
3052
  return {
2486
3053
  id: "prepare_call",
2487
3054
  async run(ctx) {
2488
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
3055
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
2489
3056
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
2490
3057
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
2491
3058
  await emitAuditEnvelope(ctx.audit, {
@@ -2551,19 +3118,21 @@ var GraphAgentExecutor = class {
2551
3118
  modelCatalog;
2552
3119
  telemetryPort;
2553
3120
  auditPort;
3121
+ tokenizer;
2554
3122
  stages;
2555
3123
  middlewares;
2556
3124
  constructor(dependencies) {
2557
3125
  this.llmCaller = dependencies.llmCaller;
2558
3126
  this.toolRuntime = dependencies.toolRuntime;
2559
3127
  this.contextBuilder = dependencies.contextBuilder;
2560
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3128
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
2561
3129
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
2562
3130
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
2563
3131
  modelCatalog: this.modelCatalog
2564
3132
  });
2565
3133
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2566
3134
  this.auditPort = dependencies.auditPort ?? noopAudit;
3135
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2567
3136
  this.stages = [
2568
3137
  createPrepareCallStage({
2569
3138
  modelResolver: this.modelResolver,
@@ -2605,9 +3174,10 @@ var GraphAgentExecutor = class {
2605
3174
  llmMessages: [],
2606
3175
  mode: input.request.mode === "chat" ? "chat" : "agent",
2607
3176
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2608
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3177
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2609
3178
  telemetry: this.telemetryPort,
2610
- audit: this.auditPort
3179
+ audit: this.auditPort,
3180
+ tokenizer: this.tokenizer
2611
3181
  };
2612
3182
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2613
3183
  stream: input.stream === true,
@@ -2655,18 +3225,18 @@ function isSummarizationCallbacks(value) {
2655
3225
  function isGraphSseSink(value) {
2656
3226
  return typeof value === "function";
2657
3227
  }
2658
- function readNonEmptyString2(value) {
3228
+ function readNonEmptyString3(value) {
2659
3229
  if (typeof value !== "string") return void 0;
2660
3230
  const trimmed = value.trim();
2661
3231
  return trimmed.length > 0 ? trimmed : void 0;
2662
3232
  }
2663
3233
  function readGraphAgentLocal(local) {
2664
3234
  const source = local ?? {};
2665
- const answerId = readNonEmptyString2(source.answerId);
3235
+ const answerId = readNonEmptyString3(source.answerId);
2666
3236
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
2667
3237
  return {
2668
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
2669
- turnId: readNonEmptyString2(source.turnId),
3238
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3239
+ turnId: readNonEmptyString3(source.turnId),
2670
3240
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
2671
3241
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
2672
3242
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3431,7 +4001,7 @@ var LlmNode = class {
3431
4001
  function isRecord8(value) {
3432
4002
  return typeof value === "object" && value !== null && !Array.isArray(value);
3433
4003
  }
3434
- function readNonEmptyString3(value) {
4004
+ function readNonEmptyString4(value) {
3435
4005
  if (typeof value !== "string") {
3436
4006
  return void 0;
3437
4007
  }
@@ -3453,7 +4023,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3453
4023
  return void 0;
3454
4024
  }
3455
4025
  if (toolName === "write_report") {
3456
- const report = readNonEmptyString3(data.report);
4026
+ const report = readNonEmptyString4(data.report);
3457
4027
  if (!report) {
3458
4028
  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");
3459
4029
  }
@@ -3463,7 +4033,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3463
4033
  if (data.success !== true) {
3464
4034
  return void 0;
3465
4035
  }
3466
- const finalAnswer = readNonEmptyString3(data.final_answer);
4036
+ const finalAnswer = readNonEmptyString4(data.final_answer);
3467
4037
  if (!finalAnswer) {
3468
4038
  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");
3469
4039
  }
@@ -3572,11 +4142,11 @@ function buildToolOutputUiMeta(params) {
3572
4142
  }
3573
4143
  async function applyObservationGovernance(params) {
3574
4144
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3575
- return;
4145
+ return {};
3576
4146
  }
3577
4147
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3578
4148
  if (!policy.enabled) {
3579
- return;
4149
+ return {};
3580
4150
  }
3581
4151
  const truncated = await params.observationPreview.truncateObservation({
3582
4152
  context: params.toolContext,
@@ -3590,13 +4160,37 @@ async function applyObservationGovernance(params) {
3590
4160
  })
3591
4161
  });
3592
4162
  if (!truncated.truncated) {
3593
- return;
4163
+ return {};
3594
4164
  }
3595
4165
  params.parsed["observation"] = truncated.preview;
3596
4166
  const data = params.parsed["data"];
3597
4167
  if (isRecord9(data) && !("tool_output_store" in data)) {
3598
4168
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3599
4169
  }
4170
+ return {
4171
+ observationTruncation: buildObservationTruncationMeta({
4172
+ originalText: params.structuredObservation,
4173
+ previewText: truncated.preview,
4174
+ originalChars: truncated.originalChars,
4175
+ previewChars: truncated.previewChars,
4176
+ originalLines: truncated.originalLines,
4177
+ previewLines: truncated.previewLines
4178
+ })
4179
+ };
4180
+ }
4181
+ function buildObservationTruncationMeta(input) {
4182
+ return {
4183
+ originalChars: input.originalChars ?? input.originalText.length,
4184
+ previewChars: input.previewChars ?? input.previewText.length,
4185
+ originalLines: input.originalLines ?? countLines(input.originalText),
4186
+ previewLines: input.previewLines ?? countLines(input.previewText)
4187
+ };
4188
+ }
4189
+ function countLines(value) {
4190
+ if (value.length === 0) {
4191
+ return 0;
4192
+ }
4193
+ return value.split(/\r\n|\r|\n/).length;
3600
4194
  }
3601
4195
 
3602
4196
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4008,6 +4602,31 @@ function ensureToolContextRuntimeCapability(params) {
4008
4602
  function getToolContextRuntimeBinding(context) {
4009
4603
  return readBinding(context);
4010
4604
  }
4605
+ function copyToolContextRuntimeCapability(source, target) {
4606
+ const sourceBinding = readBinding(source);
4607
+ if (!sourceBinding) {
4608
+ return void 0;
4609
+ }
4610
+ const existingTargetBinding = readBinding(target);
4611
+ if (existingTargetBinding) {
4612
+ exposeCompatibilitySurface(target, existingTargetBinding);
4613
+ return existingTargetBinding;
4614
+ }
4615
+ const targetBinding = createRuntimeBinding({
4616
+ context: target,
4617
+ persistedHistory: () => sourceBinding.getPersistedHistoryEvents(),
4618
+ workingHistory: () => sourceBinding.getWorkingHistoryEvents(),
4619
+ executionMeta: sourceBinding.readExecutionMeta()
4620
+ });
4621
+ Object.defineProperty(target, TOOL_CONTEXT_RUNTIME_BINDING_KEY, {
4622
+ value: targetBinding,
4623
+ enumerable: false,
4624
+ configurable: true,
4625
+ writable: false
4626
+ });
4627
+ exposeCompatibilitySurface(target, targetBinding);
4628
+ return targetBinding;
4629
+ }
4011
4630
  function readToolContextWorkingHistory(context) {
4012
4631
  if (context.conversationView) {
4013
4632
  return context.conversationView.getWorkingHistoryEvents();
@@ -4534,7 +5153,7 @@ var ToolNode = class {
4534
5153
  parentRunId: context.toolContext.parentRunId
4535
5154
  });
4536
5155
  applyProtocolFuseState(context.local);
4537
- await applyObservationGovernance({
5156
+ const observationGovernance = await applyObservationGovernance({
4538
5157
  parsed: context.parsed,
4539
5158
  toolName: context.toolName,
4540
5159
  toolContext: context.toolContext,
@@ -4561,6 +5180,12 @@ var ToolNode = class {
4561
5180
  runtimeToolOutput,
4562
5181
  execIdempotency: context.exec.idempotency
4563
5182
  });
5183
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5184
+ runtimeToolOutput.metadata = {
5185
+ ...runtimeToolOutput.metadata ?? {},
5186
+ observationTruncation: observationGovernance.observationTruncation
5187
+ };
5188
+ }
4564
5189
  const remainingCalls = context.calls.slice(1);
4565
5190
  context.state.local = buildSuccessLocalState({
4566
5191
  local: context.local,
@@ -4859,12 +5484,12 @@ function asRecord(value) {
4859
5484
  }
4860
5485
  return value;
4861
5486
  }
4862
- function summarizeCheckpoint(conversationId, state, savedAt) {
5487
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
4863
5488
  const local = asRecord(state.local);
4864
5489
  const executorLocal = asRecord(local?.executorLocal);
4865
5490
  const pendingToolCalls = local?.pendingToolCalls;
4866
5491
  return {
4867
- conversationId,
5492
+ checkpointKey,
4868
5493
  schemaVersion: state.schemaVersion ?? 1,
4869
5494
  savedAt,
4870
5495
  currentNode: state.nodeId,
@@ -4883,25 +5508,25 @@ var MemoryCheckpointer = class {
4883
5508
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
4884
5509
  };
4885
5510
  }
4886
- async load(conversationId) {
4887
- const entry = this.store.get(conversationId);
5511
+ async load(checkpointKey) {
5512
+ const entry = this.store.get(checkpointKey);
4888
5513
  return entry ? this.cloneState(entry.state) : null;
4889
5514
  }
4890
- async save(conversationId, state) {
4891
- this.store.set(conversationId, {
5515
+ async save(checkpointKey, state) {
5516
+ this.store.set(checkpointKey, {
4892
5517
  state: this.cloneState(state),
4893
5518
  savedAt: Date.now()
4894
5519
  });
4895
5520
  }
4896
- async clear(conversationId) {
4897
- this.store.delete(conversationId);
5521
+ async clear(checkpointKey) {
5522
+ this.store.delete(checkpointKey);
4898
5523
  }
4899
- async peekMeta(conversationId) {
4900
- const entry = this.store.get(conversationId);
4901
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
5524
+ async peekMeta(checkpointKey) {
5525
+ const entry = this.store.get(checkpointKey);
5526
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
4902
5527
  }
4903
5528
  async list(filter = {}) {
4904
- 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);
5529
+ 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);
4905
5530
  if (filter.limit === void 0) {
4906
5531
  return summaries;
4907
5532
  }
@@ -4973,6 +5598,7 @@ __export(tools_exports, {
4973
5598
  CommonParameterTypes: () => CommonParameterTypes,
4974
5599
  ContextCheckpointTool: () => ContextCheckpointTool,
4975
5600
  computeToolIdempotencyKey: () => computeToolIdempotencyKey,
5601
+ copyToolContextRuntimeCapability: () => copyToolContextRuntimeCapability,
4976
5602
  createContextCheckpointTool: () => createContextCheckpointTool,
4977
5603
  ensureToolContextRuntimeCapability: () => ensureToolContextRuntimeCapability,
4978
5604
  findCachedToolOutputByIdempotencyKey: () => findCachedToolOutputByIdempotencyKey,
@@ -5166,7 +5792,7 @@ function createContextCheckpointTool(options) {
5166
5792
  function isRecord15(value) {
5167
5793
  return !!value && typeof value === "object" && !Array.isArray(value);
5168
5794
  }
5169
- function readNonEmptyString4(value) {
5795
+ function readNonEmptyString5(value) {
5170
5796
  if (typeof value !== "string") {
5171
5797
  return void 0;
5172
5798
  }
@@ -5186,13 +5812,13 @@ function readToolContextUserQuery(context) {
5186
5812
  if (!context) {
5187
5813
  return void 0;
5188
5814
  }
5189
- return readNonEmptyString4(context["user_query"]);
5815
+ return readNonEmptyString5(context["user_query"]);
5190
5816
  }
5191
5817
  function readToolContextModelId(context) {
5192
5818
  if (!context) {
5193
5819
  return void 0;
5194
5820
  }
5195
- return readNonEmptyString4(context["modelId"]);
5821
+ return readNonEmptyString5(context["modelId"]);
5196
5822
  }
5197
5823
  function readToolContextRunContext(context) {
5198
5824
  if (!context) {
@@ -6394,6 +7020,7 @@ async function callLlmStream(params) {
6394
7020
  const streamAnswerId = generateMessageId();
6395
7021
  let streamChunkSeq = 0;
6396
7022
  let capturedUsage = void 0;
7023
+ let capturedCanonicalUsage = void 0;
6397
7024
  const toolAccumulator = new ToolCallStreamAccumulator([
6398
7025
  "markdown_edit",
6399
7026
  "text_to_image",
@@ -6452,6 +7079,10 @@ async function callLlmStream(params) {
6452
7079
  if (typeof chunk !== "object" || chunk === null) {
6453
7080
  return;
6454
7081
  }
7082
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
7083
+ if (parsedCanonicalUsage.success) {
7084
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
7085
+ }
6455
7086
  if (chunk.content) {
6456
7087
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6457
7088
  fullResponse += chunk.content;
@@ -6536,6 +7167,12 @@ async function callLlmStream(params) {
6536
7167
  const onUsage = (usage) => {
6537
7168
  capturedUsage = usage;
6538
7169
  };
7170
+ const onCanonicalUsage = (usage) => {
7171
+ const parsed = CanonicalLlmUsage.safeParse(usage);
7172
+ if (parsed.success) {
7173
+ capturedCanonicalUsage = parsed.data;
7174
+ }
7175
+ };
6539
7176
  await aiEngine.chatCompletionStream(
6540
7177
  modelId,
6541
7178
  messages,
@@ -6548,7 +7185,8 @@ async function callLlmStream(params) {
6548
7185
  onError,
6549
7186
  onFinish,
6550
7187
  onThought,
6551
- onUsage
7188
+ onUsage,
7189
+ onCanonicalUsage
6552
7190
  );
6553
7191
  if (streamError) {
6554
7192
  throw streamError;
@@ -6556,12 +7194,13 @@ async function callLlmStream(params) {
6556
7194
  emitThoughtComplete(thoughtSegmenter.finalize());
6557
7195
  const mergedToolCalls = toolAccumulator.getToolCalls();
6558
7196
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6559
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
7197
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6560
7198
  return {
6561
7199
  content: fullResponse,
6562
7200
  tool_calls: mergedToolCalls,
6563
7201
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6564
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
7202
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
7203
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6565
7204
  };
6566
7205
  }
6567
7206
  return fullResponse;
@@ -6611,6 +7250,10 @@ function tryCloudQuotaFallback({
6611
7250
  }
6612
7251
 
6613
7252
  // src/runtime-kernel/llm/usage-telemetry.ts
7253
+ function parseCanonicalUsage(value) {
7254
+ const parsed = CanonicalLlmUsage.safeParse(value);
7255
+ return parsed.success ? parsed.data : void 0;
7256
+ }
6614
7257
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6615
7258
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6616
7259
  return normalizeCompletionResponse(response);
@@ -6621,6 +7264,7 @@ function normalizeCompletionResponse(response) {
6621
7264
  }
6622
7265
  if (isRecord19(response)) {
6623
7266
  const usage = response["usage"];
7267
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6624
7268
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6625
7269
  if (parsedToolCalls) {
6626
7270
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6628,7 +7272,8 @@ function normalizeCompletionResponse(response) {
6628
7272
  content: typeof response["content"] === "string" ? response["content"] : "",
6629
7273
  tool_calls: parsedToolCalls,
6630
7274
  reasoning_details: reasoningDetails,
6631
- ...usage !== void 0 ? { usage } : {}
7275
+ ...usage !== void 0 ? { usage } : {},
7276
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6632
7277
  };
6633
7278
  }
6634
7279
  }
@@ -6638,10 +7283,12 @@ function normalizeCompletionResponse(response) {
6638
7283
  if (typeof response === "object") {
6639
7284
  if (isRecord19(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6640
7285
  const usage = response["usage"];
7286
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6641
7287
  return {
6642
7288
  content: typeof response["content"] === "string" ? response["content"] : "",
6643
7289
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6644
- ...usage !== void 0 ? { usage } : {}
7290
+ ...usage !== void 0 ? { usage } : {},
7291
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6645
7292
  };
6646
7293
  }
6647
7294
  if (isRecord19(response)) {
@@ -6895,29 +7542,6 @@ var LlmCaller = class {
6895
7542
  }
6896
7543
  };
6897
7544
 
6898
- // src/shared/defaultTokenizerPort.ts
6899
- var DefaultTokenizerPort = class {
6900
- constructor(config = {}) {
6901
- this.config = config;
6902
- }
6903
- estimateText(text, _modelId) {
6904
- return TokenCalculator.estimateTokens(text, {
6905
- encoding: this.config.encoding,
6906
- avgCharsPerToken: this.config.avgCharsPerToken
6907
- });
6908
- }
6909
- estimateMessage(message, _modelId) {
6910
- return TokenCalculator.estimateMessageTokens(message, {
6911
- encoding: this.config.encoding,
6912
- avgCharsPerToken: this.config.avgCharsPerToken,
6913
- toolCallOverhead: this.config.toolCallOverhead
6914
- });
6915
- }
6916
- };
6917
- function createDefaultTokenizerPort(config = {}) {
6918
- return new DefaultTokenizerPort(config);
6919
- }
6920
-
6921
7545
  // src/runtime-kernel/child-runs/index.ts
6922
7546
  var child_runs_exports = {};
6923
7547
  __export(child_runs_exports, {
@@ -6927,7 +7551,6 @@ __export(child_runs_exports, {
6927
7551
 
6928
7552
  // src/runtime-kernel/child-runs/childToolContext.ts
6929
7553
  function createChildRunToolContext(params) {
6930
- const inheritedConversationId = typeof params.parentToolContext.conversationId === "string" && params.parentToolContext.conversationId.trim().length > 0 ? params.parentToolContext.conversationId.trim() : void 0;
6931
7554
  const inheritedContext = stripRuntimeReservedToolContextPatch(params.parentToolContext);
6932
7555
  const childToolContext = {
6933
7556
  ...inheritedContext,
@@ -6939,7 +7562,7 @@ function createChildRunToolContext(params) {
6939
7562
  persistedHistory: params.seedHistory,
6940
7563
  workingHistory: params.seedHistory,
6941
7564
  executionMeta: {
6942
- conversationId: inheritedConversationId ?? params.internalConversationId,
7565
+ conversationId: params.conversationId,
6943
7566
  turnId: params.turnId,
6944
7567
  runId: params.runId,
6945
7568
  parentRunId: params.parentRunId
@@ -7041,6 +7664,8 @@ var FinalAnswerCollector = class {
7041
7664
  this.conversationId = conversationId;
7042
7665
  this.turnId = turnId;
7043
7666
  }
7667
+ conversationId;
7668
+ turnId;
7044
7669
  answerId;
7045
7670
  chunks = [];
7046
7671
  chunkCount = 0;
@@ -7257,7 +7882,7 @@ function readCheckpointHistory(checkpoint) {
7257
7882
  });
7258
7883
  }
7259
7884
  async function recoverChildRunEventsFromCheckpoint(params) {
7260
- const checkpoint = await params.checkpointer.load(params.conversationId);
7885
+ const checkpoint = await params.checkpointer.load(params.checkpointKey);
7261
7886
  const history = readCheckpointHistory(checkpoint);
7262
7887
  if (history.length === 0) {
7263
7888
  return [];
@@ -7265,7 +7890,7 @@ async function recoverChildRunEventsFromCheckpoint(params) {
7265
7890
  if (hasSeedHistoryPrefix(history, params.seedHistory)) {
7266
7891
  return history.slice(params.seedHistory.length);
7267
7892
  }
7268
- return history.filter((event) => event.conversation_id === params.internalConversationId);
7893
+ return history.filter((event) => event.conversation_id === params.childConversationId);
7269
7894
  }
7270
7895
 
7271
7896
  // src/runtime-kernel/child-runs/childRunInvoker.ts
@@ -7294,6 +7919,7 @@ var ChildRunInvoker = class {
7294
7919
  agentConfig,
7295
7920
  userMessage,
7296
7921
  parentToolContext,
7922
+ conversationId,
7297
7923
  runId,
7298
7924
  parentRunId,
7299
7925
  subrunTracePublisher,
@@ -7302,12 +7928,18 @@ var ChildRunInvoker = class {
7302
7928
  modelId,
7303
7929
  abortSignal
7304
7930
  } = config;
7305
- const internalConversationId = `internal_${generateMessageId()}`;
7931
+ const internalCheckpointKey = `internal_${generateMessageId()}`;
7932
+ const runtimeConversationId = resolveChildRunConversationId({
7933
+ explicitConversationId: conversationId,
7934
+ parentToolContext,
7935
+ fallbackConversationId: internalCheckpointKey
7936
+ });
7306
7937
  const turnId = `turn_${Date.now()}`;
7307
- const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalConversationId;
7938
+ const childRunId = typeof runId === "string" && runId.trim().length > 0 ? runId.trim() : internalCheckpointKey;
7308
7939
  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;
7309
7940
  logger13.info(`\u542F\u52A8 child-run: ${agentConfig.id}`, {
7310
- conversationId: internalConversationId,
7941
+ conversationId: runtimeConversationId,
7942
+ checkpointKey: internalCheckpointKey,
7311
7943
  maxSteps,
7312
7944
  userMessage: userMessage.slice(0, 100) + (userMessage.length > 100 ? "..." : "")
7313
7945
  });
@@ -7368,7 +8000,7 @@ var ChildRunInvoker = class {
7368
8000
  const seedHistory = Array.isArray(seedHistoryEvents) ? seedHistoryEvents : [];
7369
8001
  const childToolContext = createChildRunToolContext({
7370
8002
  parentToolContext,
7371
- internalConversationId,
8003
+ conversationId: runtimeConversationId,
7372
8004
  turnId,
7373
8005
  runId: childRunId,
7374
8006
  parentRunId: resolvedParentRunId,
@@ -7377,13 +8009,13 @@ var ChildRunInvoker = class {
7377
8009
  });
7378
8010
  const subrunSseSink = subrunTracePublisher ? createChildRunTraceSink({
7379
8011
  publisher: subrunTracePublisher,
7380
- conversationId: internalConversationId,
8012
+ conversationId: runtimeConversationId,
7381
8013
  turnId
7382
8014
  }) : void 0;
7383
8015
  const initialLocal = {
7384
8016
  request,
7385
8017
  history: seedHistory,
7386
- conversationId: internalConversationId,
8018
+ conversationId: runtimeConversationId,
7387
8019
  turnId,
7388
8020
  toolContext: childToolContext,
7389
8021
  ...abortSignal ? { signal: abortSignal } : {},
@@ -7391,7 +8023,7 @@ var ChildRunInvoker = class {
7391
8023
  ...subrunSseSink ? { sseSink: subrunSseSink } : {},
7392
8024
  systemPrompt
7393
8025
  };
7394
- await graphExecutor.prime(internalConversationId, initialLocal, "llm");
8026
+ await graphExecutor.prime(internalCheckpointKey, initialLocal, "llm");
7395
8027
  const allEvents = [];
7396
8028
  let stepCount = 0;
7397
8029
  let finalAnswer;
@@ -7403,7 +8035,7 @@ var ChildRunInvoker = class {
7403
8035
  err.name = "AbortError";
7404
8036
  throw err;
7405
8037
  }
7406
- const result = await graphExecutor.runUntilYield(internalConversationId);
8038
+ const result = await graphExecutor.runUntilYield(internalCheckpointKey);
7407
8039
  appendUniqueEvents(allEvents, result.events);
7408
8040
  stepCount = result.stepCount;
7409
8041
  if (subrunSseSink && typeof subrunSseSink.finalize === "function") {
@@ -7437,8 +8069,8 @@ var ChildRunInvoker = class {
7437
8069
  }
7438
8070
  const recoveredEvents = await recoverChildRunEventsFromCheckpoint({
7439
8071
  checkpointer,
7440
- conversationId: internalConversationId,
7441
- internalConversationId,
8072
+ checkpointKey: internalCheckpointKey,
8073
+ childConversationId: runtimeConversationId,
7442
8074
  seedHistory
7443
8075
  });
7444
8076
  appendUniqueEvents(allEvents, recoveredEvents);
@@ -7455,7 +8087,7 @@ var ChildRunInvoker = class {
7455
8087
  stack: err.stack
7456
8088
  } : { error: String(err) });
7457
8089
  }
7458
- await checkpointer.clear(internalConversationId);
8090
+ await checkpointer.clear(internalCheckpointKey);
7459
8091
  return {
7460
8092
  success: !error,
7461
8093
  runId: childRunId,
@@ -7468,6 +8100,16 @@ var ChildRunInvoker = class {
7468
8100
  };
7469
8101
  }
7470
8102
  };
8103
+ function readNonEmptyString6(value) {
8104
+ if (typeof value !== "string") {
8105
+ return void 0;
8106
+ }
8107
+ const trimmed = value.trim();
8108
+ return trimmed.length > 0 ? trimmed : void 0;
8109
+ }
8110
+ function resolveChildRunConversationId(params) {
8111
+ return readNonEmptyString6(params.explicitConversationId) ?? readNonEmptyString6(params.parentToolContext.conversationId) ?? params.fallbackConversationId;
8112
+ }
7471
8113
  function resolveChildRunSystemReminderPolicy(agentConfig) {
7472
8114
  const configured = agentConfig.systemReminderPolicy ?? agentConfig.contextPolicy?.systemReminder;
7473
8115
  const threshold = agentConfig.stepPolicy?.lastStepsHintThreshold;
@@ -7658,7 +8300,7 @@ function cloneRunRecord(record) {
7658
8300
  ...record,
7659
8301
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
7660
8302
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
7661
- metadata: record.metadata ? { ...record.metadata } : void 0
8303
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
7662
8304
  };
7663
8305
  }
7664
8306
  function matchesStatus(candidate, filter) {
@@ -8070,7 +8712,7 @@ function isTerminalStatus(status) {
8070
8712
  return status === "completed" || status === "failed" || status === "cancelled";
8071
8713
  }
8072
8714
  function cloneMetadata(metadata) {
8073
- return metadata ? { ...metadata } : void 0;
8715
+ return metadata ? structuredClone(metadata) : void 0;
8074
8716
  }
8075
8717
  function recordToSnapshot(record) {
8076
8718
  return {
@@ -8157,7 +8799,7 @@ var DefaultRunSupervisor = class {
8157
8799
  startedAt,
8158
8800
  updatedAt: startedAt,
8159
8801
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
8160
- metadata: spec.metadata ? { ...spec.metadata } : void 0
8802
+ metadata: cloneMetadata(spec.metadata)
8161
8803
  };
8162
8804
  await this.registryStore.save(record);
8163
8805
  const handle = new DefaultRunHandle({
@@ -8331,12 +8973,13 @@ var DefaultRunSupervisor = class {
8331
8973
  }
8332
8974
  try {
8333
8975
  await handle.markRunning({ currentNode: "detached" });
8976
+ const registeredRecord = await this.registryStore.load(handle.runId);
8334
8977
  const executorOutcome = await this.executor.execute({
8335
8978
  runId: handle.runId,
8336
- parentRunId: spec.parentRunId,
8337
- conversationId: spec.conversationId,
8338
- agentSpec: spec.agentSpec,
8339
- request: spec.request,
8979
+ parentRunId: handle.parentRunId,
8980
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
8981
+ agentSpec: await handle.spec(),
8982
+ request: await handle.request(),
8340
8983
  signal: handle.signal,
8341
8984
  eventBus: spec.eventBus,
8342
8985
  eventStore: spec.eventStore,
@@ -8345,7 +8988,7 @@ var DefaultRunSupervisor = class {
8345
8988
  contextFences: spec.contextFences,
8346
8989
  wakeSource: spec.wakeSource,
8347
8990
  ephemeral: spec.ephemeral,
8348
- metadata: spec.metadata
8991
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
8349
8992
  });
8350
8993
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
8351
8994
  this.notifyTerminalWaiters(outcome);
@@ -8409,10 +9052,14 @@ var DefaultRunSupervisor = class {
8409
9052
  await this.registryStore.save(record);
8410
9053
  }
8411
9054
  const completedAt = executorOutcome?.completedAt ?? this.now();
9055
+ const fallbackMeta = record ? void 0 : await handle.meta();
8412
9056
  const outcome = recordToTerminalOutcome(record ?? {
8413
9057
  runId: handle.runId,
8414
9058
  parentRunId: handle.parentRunId,
8415
- status: executorOutcome?.status ?? "completed"}, completedAt);
9059
+ conversationId: fallbackMeta?.conversationId ?? "",
9060
+ agentSpecId: fallbackMeta?.agentSpecId,
9061
+ status: executorOutcome?.status ?? "completed",
9062
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
8416
9063
  const nextOutcome = {
8417
9064
  ...outcome,
8418
9065
  metadata: {
@@ -8504,6 +9151,7 @@ __export(telemetry_exports, {
8504
9151
  var TELEMETRY_EVENT_KINDS = [
8505
9152
  "llm_call",
8506
9153
  "tool_call",
9154
+ "context_build",
8507
9155
  "graph_node",
8508
9156
  "run_lifecycle"
8509
9157
  ];
@@ -8640,6 +9288,7 @@ function createGraphLoopHarness(options) {
8640
9288
  };
8641
9289
  return {
8642
9290
  async run() {
9291
+ const checkpointKey = options.conversationId;
8643
9292
  const executor = createDefaultGraphExecutor({
8644
9293
  llmNode: options.createLlmNode({
8645
9294
  llmCaller: options.llmCaller,
@@ -8668,8 +9317,8 @@ function createGraphLoopHarness(options) {
8668
9317
  signal: options.signal ?? options.toolContext.abortSignal,
8669
9318
  executorLocal
8670
9319
  };
8671
- await executor.prime(options.conversationId, local, "user");
8672
- const result = await executor.runUntilYield(options.conversationId);
9320
+ await executor.prime(checkpointKey, local, "user");
9321
+ const result = await executor.runUntilYield(checkpointKey);
8673
9322
  return {
8674
9323
  checkpointNodeId: result.checkpoint.nodeId,
8675
9324
  stepCount: result.stepCount
@@ -8706,7 +9355,11 @@ exports.SystemReminderRegistry = SystemReminderRegistry;
8706
9355
  exports.ToolNode = ToolNode;
8707
9356
  exports.UserNode = UserNode;
8708
9357
  exports.WaitUserNode = WaitUserNode;
9358
+ exports.addLedgerAggregate = addLedgerAggregate;
9359
+ exports.addUsageTotals = addUsageTotals;
8709
9360
  exports.agentHasToolTrigger = agentHasToolTrigger;
9361
+ exports.aggregateCanonicalUsage = aggregateCanonicalUsage;
9362
+ exports.aggregateTokenLedgerEntries = aggregateTokenLedgerEntries;
8710
9363
  exports.appendStreamingProviderReasoningDetails = appendStreamingProviderReasoningDetails;
8711
9364
  exports.applySystemReminders = applySystemReminders;
8712
9365
  exports.audit = audit_exports;
@@ -8715,20 +9368,25 @@ exports.childRunTrace = child_run_trace_exports;
8715
9368
  exports.childRuns = child_runs_exports;
8716
9369
  exports.compactProviderReasoningDetails = compactProviderReasoningDetails;
8717
9370
  exports.compactReasoningDetailsInValue = compactReasoningDetailsInValue;
9371
+ exports.computeCost = computeCost;
8718
9372
  exports.computeToolIdempotencyKey = computeToolIdempotencyKey;
8719
9373
  exports.consoleAudit = consoleAudit;
8720
9374
  exports.contextBudgetWarningTemplate = contextBudgetWarningTemplate;
9375
+ exports.copyToolContextRuntimeCapability = copyToolContextRuntimeCapability;
8721
9376
  exports.countToolCallsInCurrentRequest = countToolCallsInCurrentRequest;
8722
9377
  exports.createCompositeAudit = createCompositeAudit;
8723
9378
  exports.createConsoleAudit = createConsoleAudit;
8724
9379
  exports.createContextCheckpointTool = createContextCheckpointTool;
9380
+ exports.createContextComponentLedgerEntry = createContextComponentLedgerEntry;
8725
9381
  exports.createDefaultGraphExecutor = createDefaultGraphExecutor;
8726
9382
  exports.createDefaultSystemReminderRegistry = createDefaultSystemReminderRegistry;
8727
9383
  exports.createDefaultTokenizerPort = createDefaultTokenizerPort;
8728
9384
  exports.createEventStoreAudit = createEventStoreAudit;
8729
9385
  exports.createFileAudit = createFileAudit;
8730
9386
  exports.createGraphLoopHarness = createGraphLoopHarness;
9387
+ exports.createLlmUsageLedgerEntry = createLlmUsageLedgerEntry;
8731
9388
  exports.createMonotonicEventIdFactory = createMonotonicEventIdFactory;
9389
+ exports.createRunTokenUsageAggregate = createRunTokenUsageAggregate;
8732
9390
  exports.createSystemReminderRules = createSystemReminderRules;
8733
9391
  exports.defaultPolicyEngine = defaultPolicyEngine;
8734
9392
  exports.defaultSystemReminderRegistry = defaultSystemReminderRegistry;
@@ -8765,6 +9423,7 @@ exports.summarizeCheckpoint = summarizeCheckpoint;
8765
9423
  exports.systemReminder = system_reminder_exports;
8766
9424
  exports.telemetry = telemetry_exports;
8767
9425
  exports.toDisplayStep = toDisplayStep;
9426
+ exports.tokenAccounting = token_accounting_exports;
8768
9427
  exports.toolCallStreakTemplate = toolCallStreakTemplate;
8769
9428
  exports.toolCallStreakTrigger = toolCallStreakTrigger;
8770
9429
  exports.tools = tools_exports;