@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
@@ -44,6 +44,12 @@ zod.z.object({
44
44
  args: zod.z.record(zod.z.unknown()).optional(),
45
45
  tool_call_id: zod.z.string()
46
46
  });
47
+ var ObservationTruncationMeta = zod.z.object({
48
+ originalChars: zod.z.number().int().nonnegative(),
49
+ previewChars: zod.z.number().int().nonnegative(),
50
+ originalLines: zod.z.number().int().nonnegative().optional(),
51
+ previewLines: zod.z.number().int().nonnegative().optional()
52
+ });
47
53
  var ImageInfoMeta = zod.z.object({
48
54
  url: zod.z.string().optional(),
49
55
  width: zod.z.number().int().positive().optional(),
@@ -75,6 +81,7 @@ var PersistentMetadata = zod.z.object({
75
81
  tool_name: zod.z.string().optional(),
76
82
  args: zod.z.record(zod.z.unknown()).optional(),
77
83
  tool_call_id: zod.z.string().optional(),
84
+ observationTruncation: ObservationTruncationMeta.optional(),
78
85
  raw_output: zod.z.string().optional(),
79
86
  image_info: ImageInfoMeta.optional(),
80
87
  taskType: zod.z.string().optional(),
@@ -168,6 +175,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
168
175
  });
169
176
  var AgentSpecToolHistoryPolicy = zod.z.object({
170
177
  strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
178
+ retentionMode: zod.z.enum(["drop", "compress"]).optional(),
171
179
  keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
172
180
  keepLatestRuns: zod.z.number().int().nonnegative().optional(),
173
181
  maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
@@ -220,7 +228,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
220
228
  var AgentSpecTokenEstimationPolicy = zod.z.object({
221
229
  encoding: zod.z.string().min(1).optional(),
222
230
  avgCharsPerToken: zod.z.number().positive().optional(),
223
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
231
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
232
+ calibration: zod.z.object({
233
+ enabled: zod.z.boolean().optional(),
234
+ minSamples: zod.z.number().int().positive().optional(),
235
+ minCoefficient: zod.z.number().positive().optional(),
236
+ maxCoefficient: zod.z.number().positive().optional()
237
+ }).optional(),
238
+ remoteCount: zod.z.object({
239
+ enabled: zod.z.boolean().optional(),
240
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
241
+ }).optional()
224
242
  });
225
243
  var AgentSpecSystemReminderTrigger = zod.z.object({
226
244
  kind: zod.z.string().min(1),
@@ -282,12 +300,13 @@ var AgentSpecContextPolicy = zod.z.object({
282
300
  var DEFAULT_CONTEXT_POLICY = {
283
301
  profileId: "agent",
284
302
  budget: {
285
- maxTokens: 12e4,
303
+ maxTokens: 232e3,
286
304
  reservedForResponse: 2400,
287
305
  workingMemoryBudgetPercentage: 0.7
288
306
  },
289
307
  toolHistory: {
290
308
  strategy: "per-run",
309
+ retentionMode: "drop",
291
310
  keepLatestToolPairs: 2,
292
311
  keepLatestRuns: 1,
293
312
  maxInteractionGroups: 12,
@@ -1019,6 +1038,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
1019
1038
  error,
1020
1039
  ...options
1021
1040
  });
1041
+ var TokenCountSource = zod.z.enum([
1042
+ "local-estimate",
1043
+ "provider-preflight-count",
1044
+ "provider-response-usage",
1045
+ "host-supplied",
1046
+ "test-fixture"
1047
+ ]);
1048
+ var TokenCountConfidence = zod.z.enum([
1049
+ "estimate",
1050
+ "provider-estimate",
1051
+ "actual"
1052
+ ]);
1053
+ var TokenRouteCapabilities = zod.z.object({
1054
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
1055
+ supportsResponseUsage: zod.z.boolean().optional(),
1056
+ supportsImageInput: zod.z.boolean().optional(),
1057
+ supportsCachedInputBilling: zod.z.boolean().optional(),
1058
+ supportsReasoningTokens: zod.z.boolean().optional()
1059
+ });
1060
+ var TokenRoute = zod.z.object({
1061
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
1062
+ 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"),
1063
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
1064
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
1065
+ capabilities: TokenRouteCapabilities.optional()
1066
+ });
1067
+ var tokenCount = zod.z.number().int().nonnegative();
1068
+ var CanonicalLlmUsage = zod.z.object({
1069
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1070
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1071
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1072
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1073
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1074
+ 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"),
1075
+ source: TokenCountSource,
1076
+ confidence: TokenCountConfidence,
1077
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1078
+ });
1079
+ var tokenCount2 = zod.z.number().int().nonnegative();
1080
+ var tokenPrice = zod.z.number().finite().nonnegative();
1081
+ zod.z.enum([
1082
+ "llm-usage",
1083
+ "context-component"
1084
+ ]);
1085
+ var ContextTokenComponentKind = zod.z.enum([
1086
+ "system",
1087
+ "user",
1088
+ "assistant",
1089
+ "tool",
1090
+ "context-injection",
1091
+ "history-summary",
1092
+ "working-memory",
1093
+ "fence",
1094
+ "system-reminder",
1095
+ "other"
1096
+ ]);
1097
+ var TokenUsageTotals = zod.z.object({
1098
+ inputTokens: tokenCount2,
1099
+ outputTokens: tokenCount2,
1100
+ reasoningTokens: tokenCount2.optional(),
1101
+ cacheReadTokens: tokenCount2.optional(),
1102
+ cacheWriteTokens: tokenCount2.optional(),
1103
+ totalTokens: tokenCount2.optional(),
1104
+ usageCount: zod.z.number().int().nonnegative()
1105
+ });
1106
+ var ContextTokenComponent = zod.z.object({
1107
+ componentId: zod.z.string().min(1),
1108
+ kind: ContextTokenComponentKind,
1109
+ tokens: tokenCount2,
1110
+ source: TokenCountSource,
1111
+ confidence: TokenCountConfidence,
1112
+ label: zod.z.string().optional(),
1113
+ messageId: zod.z.string().optional(),
1114
+ role: zod.z.string().optional(),
1115
+ action: zod.z.string().optional(),
1116
+ kept: zod.z.boolean().optional(),
1117
+ truncatedAtExecution: zod.z.boolean().optional(),
1118
+ originalTokensEstimate: tokenCount2.optional(),
1119
+ droppedTokensEstimate: tokenCount2.optional()
1120
+ });
1121
+ var TokenLedgerEntryBase = zod.z.object({
1122
+ id: zod.z.string().min(1),
1123
+ runId: zod.z.string().optional(),
1124
+ parentRunId: zod.z.string().optional(),
1125
+ conversationId: zod.z.string().optional(),
1126
+ turnId: zod.z.string().optional(),
1127
+ stepId: zod.z.string().optional(),
1128
+ route: TokenRoute.optional(),
1129
+ createdAt: zod.z.number().int().nonnegative().optional()
1130
+ });
1131
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1132
+ kind: zod.z.literal("llm-usage"),
1133
+ modelId: zod.z.string().optional(),
1134
+ usage: CanonicalLlmUsage
1135
+ });
1136
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1137
+ kind: zod.z.literal("context-component"),
1138
+ components: zod.z.array(ContextTokenComponent),
1139
+ totalTokens: tokenCount2
1140
+ });
1141
+ zod.z.discriminatedUnion("kind", [
1142
+ LlmUsageTokenLedgerEntry,
1143
+ ContextComponentTokenLedgerEntry
1144
+ ]);
1145
+ var TokenLedgerAggregate = zod.z.object({
1146
+ llmUsage: TokenUsageTotals.optional(),
1147
+ contextTokens: tokenCount2,
1148
+ entryCount: zod.z.number().int().nonnegative(),
1149
+ llmCallCount: zod.z.number().int().nonnegative(),
1150
+ contextComponentCount: zod.z.number().int().nonnegative()
1151
+ });
1152
+ zod.z.object({
1153
+ /**
1154
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1155
+ */
1156
+ own: TokenLedgerAggregate,
1157
+ children: TokenLedgerAggregate.optional()
1158
+ });
1159
+ var TokenCostComponent = zod.z.enum([
1160
+ "input",
1161
+ "output",
1162
+ "reasoning",
1163
+ "cacheRead",
1164
+ "cacheWrite"
1165
+ ]);
1166
+ zod.z.object({
1167
+ currency: zod.z.string().min(1),
1168
+ unit: zod.z.literal("per_1m_tokens"),
1169
+ input: tokenPrice.optional(),
1170
+ output: tokenPrice.optional(),
1171
+ reasoning: tokenPrice.optional(),
1172
+ cacheRead: tokenPrice.optional(),
1173
+ cacheWrite: tokenPrice.optional()
1174
+ });
1175
+ zod.z.object({
1176
+ status: zod.z.enum(["computed", "unknown"]),
1177
+ currency: zod.z.string().optional(),
1178
+ inputCost: tokenPrice.optional(),
1179
+ outputCost: tokenPrice.optional(),
1180
+ reasoningCost: tokenPrice.optional(),
1181
+ cacheReadCost: tokenPrice.optional(),
1182
+ cacheWriteCost: tokenPrice.optional(),
1183
+ totalCost: tokenPrice.optional(),
1184
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1185
+ });
1186
+ var tokenCount3 = zod.z.number().int().nonnegative();
1187
+ var actualCalibrationSource = zod.z.enum([
1188
+ "provider-response-usage",
1189
+ "host-supplied",
1190
+ "test-fixture"
1191
+ ]);
1192
+ zod.z.object({
1193
+ route: TokenRoute,
1194
+ localEstimateTokens: tokenCount3,
1195
+ actualInputTokens: tokenCount3,
1196
+ source: actualCalibrationSource,
1197
+ confidence: zod.z.literal("actual"),
1198
+ observedAt: zod.z.number().int().nonnegative().optional(),
1199
+ runId: zod.z.string().optional(),
1200
+ ledgerEntryId: zod.z.string().optional()
1201
+ });
1202
+ zod.z.object({
1203
+ enabled: zod.z.boolean(),
1204
+ applied: zod.z.boolean(),
1205
+ route: TokenRoute.optional(),
1206
+ sampleCount: zod.z.number().int().nonnegative(),
1207
+ coefficient: zod.z.number().positive().optional(),
1208
+ minSamples: zod.z.number().int().positive().optional(),
1209
+ minCoefficient: zod.z.number().positive().optional(),
1210
+ maxCoefficient: zod.z.number().positive().optional(),
1211
+ localEstimateTokens: tokenCount3.optional(),
1212
+ calibratedEstimateTokens: tokenCount3.optional(),
1213
+ deltaTokens: zod.z.number().int().optional(),
1214
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1215
+ });
1216
+ zod.z.object({
1217
+ route: TokenRoute.optional(),
1218
+ localEstimateTokens: tokenCount3,
1219
+ calibratedEstimateTokens: tokenCount3,
1220
+ finalTokens: tokenCount3,
1221
+ source: zod.z.literal("local-estimate"),
1222
+ confidence: zod.z.literal("estimate")
1223
+ });
1022
1224
 
1023
1225
  // src/quickstart/toolSchema.ts
1024
1226
  function serializeToolProperty(property) {
@@ -1200,6 +1402,7 @@ var Logger = class {
1200
1402
  constructor(moduleName) {
1201
1403
  this.moduleName = moduleName;
1202
1404
  }
1405
+ moduleName;
1203
1406
  debug(message, data) {
1204
1407
  this.log(0 /* DEBUG */, "debug", message, data);
1205
1408
  }
@@ -1272,6 +1475,17 @@ var logger = new Logger("GraphExecutor");
1272
1475
  function asLocalRecord(local) {
1273
1476
  return local && typeof local === "object" ? { ...local } : {};
1274
1477
  }
1478
+ function readNonEmptyString(value) {
1479
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1480
+ }
1481
+ function readRuntimeConversationId(state) {
1482
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1483
+ return readNonEmptyString(local?.conversationId);
1484
+ }
1485
+ function readRuntimeTurnId(state) {
1486
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1487
+ return readNonEmptyString(local?.turnId);
1488
+ }
1275
1489
  var GraphExecutor = class {
1276
1490
  constructor(checkpointer, config = {}) {
1277
1491
  this.checkpointer = checkpointer;
@@ -1281,6 +1495,7 @@ var GraphExecutor = class {
1281
1495
  };
1282
1496
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1283
1497
  }
1498
+ checkpointer;
1284
1499
  nodes = /* @__PURE__ */ new Map();
1285
1500
  ephemeralLocals = /* @__PURE__ */ new Map();
1286
1501
  config;
@@ -1288,8 +1503,8 @@ var GraphExecutor = class {
1288
1503
  registerNode(node) {
1289
1504
  this.nodes.set(node.id, node);
1290
1505
  }
1291
- async peekCheckpoint(conversationId) {
1292
- return await this.checkpointer.load(conversationId);
1506
+ async peekCheckpoint(checkpointKey) {
1507
+ return await this.checkpointer.load(checkpointKey);
1293
1508
  }
1294
1509
  sanitize(state) {
1295
1510
  const local = asLocalRecord(state.local);
@@ -1301,8 +1516,8 @@ var GraphExecutor = class {
1301
1516
  local
1302
1517
  };
1303
1518
  }
1304
- async prime(conversationId, local, nodeId = "user") {
1305
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1519
+ async prime(checkpointKey, local, nodeId = "user") {
1520
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1306
1521
  const localSansMemory = { ...local || {} };
1307
1522
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1308
1523
  const state = {
@@ -1310,10 +1525,10 @@ var GraphExecutor = class {
1310
1525
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1311
1526
  local: localSansMemory
1312
1527
  };
1313
- await this.checkpointer.save(conversationId, state);
1528
+ await this.checkpointer.save(checkpointKey, state);
1314
1529
  }
1315
- async setNode(conversationId, nodeId, localPatch) {
1316
- const current = await this.checkpointer.load(conversationId) || {
1530
+ async setNode(checkpointKey, nodeId, localPatch) {
1531
+ const current = await this.checkpointer.load(checkpointKey) || {
1317
1532
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1318
1533
  local: {}
1319
1534
  };
@@ -1324,19 +1539,46 @@ var GraphExecutor = class {
1324
1539
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1325
1540
  local: mergedLocal
1326
1541
  };
1327
- await this.checkpointer.save(conversationId, next);
1542
+ await this.checkpointer.save(checkpointKey, next);
1328
1543
  }
1329
- async runUntilYield(conversationId) {
1544
+ async runUntilYield(checkpointKey) {
1330
1545
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1331
1546
  let lifecyclePhase = "completed";
1547
+ let initialState = null;
1548
+ try {
1549
+ initialState = await this.loadInitialState(checkpointKey);
1550
+ } catch (err) {
1551
+ lifecyclePhase = "failed";
1552
+ this.telemetryPort.emit({
1553
+ kind: "run_lifecycle",
1554
+ runId,
1555
+ phase: "spawned",
1556
+ scope: {}
1557
+ });
1558
+ this.telemetryPort.emit({
1559
+ kind: "run_lifecycle",
1560
+ runId,
1561
+ phase: lifecyclePhase,
1562
+ scope: {}
1563
+ });
1564
+ throw err;
1565
+ }
1566
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1567
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1332
1568
  this.telemetryPort.emit({
1333
1569
  kind: "run_lifecycle",
1334
1570
  runId,
1335
1571
  phase: "spawned",
1336
- scope: { conversationId: conversationId || void 0 }
1572
+ scope: {
1573
+ conversationId: lifecycleConversationId,
1574
+ turnId: lifecycleTurnId
1575
+ }
1337
1576
  });
1338
1577
  try {
1339
- return await this.runUntilYieldInternal(conversationId);
1578
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1579
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1580
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1581
+ return result;
1340
1582
  } catch (err) {
1341
1583
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1342
1584
  throw err;
@@ -1345,17 +1587,23 @@ var GraphExecutor = class {
1345
1587
  kind: "run_lifecycle",
1346
1588
  runId,
1347
1589
  phase: lifecyclePhase,
1348
- scope: { conversationId: conversationId || void 0 }
1590
+ scope: {
1591
+ conversationId: lifecycleConversationId,
1592
+ turnId: lifecycleTurnId
1593
+ }
1349
1594
  });
1350
1595
  }
1351
1596
  }
1352
- async runUntilYieldInternal(conversationId) {
1353
- let state = await this.checkpointer.load(conversationId) || {
1597
+ async loadInitialState(checkpointKey) {
1598
+ return await this.checkpointer.load(checkpointKey) || {
1354
1599
  nodeId: "user",
1355
1600
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1356
1601
  local: {}
1357
1602
  };
1358
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1603
+ }
1604
+ async runUntilYieldInternal(checkpointKey, initialState) {
1605
+ let state = initialState;
1606
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1359
1607
  state = {
1360
1608
  ...state,
1361
1609
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1384,7 +1632,7 @@ var GraphExecutor = class {
1384
1632
  const signalRaw = state.local?.signal;
1385
1633
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1386
1634
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1387
- this.ephemeralLocals.delete(conversationId);
1635
+ this.ephemeralLocals.delete(checkpointKey);
1388
1636
  throwAbortError();
1389
1637
  }
1390
1638
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1432,8 +1680,8 @@ var GraphExecutor = class {
1432
1680
  checkpointCount
1433
1681
  });
1434
1682
  const cp2 = this.sanitize(state);
1435
- await this.checkpointer.save(conversationId, cp2);
1436
- this.ephemeralLocals.delete(conversationId);
1683
+ await this.checkpointer.save(checkpointKey, cp2);
1684
+ this.ephemeralLocals.delete(checkpointKey);
1437
1685
  return { events: allEvents, checkpoint: cp2, stepCount };
1438
1686
  }
1439
1687
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1444,18 +1692,18 @@ var GraphExecutor = class {
1444
1692
  });
1445
1693
  const nodeRunStartedAt = Date.now();
1446
1694
  const nodeIdForTelemetry = state.nodeId;
1695
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1447
1696
  let result;
1448
1697
  try {
1449
1698
  result = await node.run(state);
1450
1699
  } finally {
1451
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1452
1700
  this.telemetryPort.emit({
1453
1701
  kind: "graph_node",
1454
1702
  nodeId: nodeIdForTelemetry,
1455
1703
  durationMs: Date.now() - nodeRunStartedAt,
1456
1704
  scope: {
1457
- conversationId: conversationId || void 0,
1458
- turnId: turnIdForTelemetry
1705
+ conversationId: conversationIdForTelemetry,
1706
+ turnId: readRuntimeTurnId(state)
1459
1707
  }
1460
1708
  });
1461
1709
  }
@@ -1494,7 +1742,7 @@ var GraphExecutor = class {
1494
1742
  });
1495
1743
  state = { ...state, nodeId: nextNodeId };
1496
1744
  const cp2 = this.sanitize(state);
1497
- await this.checkpointer.save(conversationId, cp2);
1745
+ await this.checkpointer.save(checkpointKey, cp2);
1498
1746
  continue;
1499
1747
  }
1500
1748
  if (result.kind === "yield") {
@@ -1505,7 +1753,7 @@ var GraphExecutor = class {
1505
1753
  checkpointCount
1506
1754
  });
1507
1755
  const cp2 = this.sanitize(state);
1508
- await this.checkpointer.save(conversationId, cp2);
1756
+ await this.checkpointer.save(checkpointKey, cp2);
1509
1757
  return { events: allEvents, checkpoint: cp2, stepCount };
1510
1758
  }
1511
1759
  if (result.kind === "pause") {
@@ -1516,7 +1764,7 @@ var GraphExecutor = class {
1516
1764
  checkpointCount
1517
1765
  });
1518
1766
  const cp2 = this.sanitize(state);
1519
- await this.checkpointer.save(conversationId, cp2);
1767
+ await this.checkpointer.save(checkpointKey, cp2);
1520
1768
  return { events: allEvents, checkpoint: cp2, stepCount };
1521
1769
  }
1522
1770
  }
@@ -1527,8 +1775,8 @@ var GraphExecutor = class {
1527
1775
  checkpointCount
1528
1776
  });
1529
1777
  const cp = this.sanitize(state);
1530
- await this.checkpointer.save(conversationId, cp);
1531
- this.ephemeralLocals.delete(conversationId);
1778
+ await this.checkpointer.save(checkpointKey, cp);
1779
+ this.ephemeralLocals.delete(checkpointKey);
1532
1780
  return { events: allEvents, checkpoint: cp, stepCount };
1533
1781
  }
1534
1782
  };
@@ -1624,6 +1872,190 @@ var noopAudit = {
1624
1872
  flush() {
1625
1873
  }
1626
1874
  };
1875
+ var TokenCalculator = class {
1876
+ static BYTES_PER_TOKEN_LATIN = 4;
1877
+ static BYTES_PER_TOKEN_CJK = 3;
1878
+ static OVERHEAD_PER_MESSAGE = 5;
1879
+ static OVERHEAD_PER_TOOL_CALL = 10;
1880
+ static encoderCache = /* @__PURE__ */ new Map();
1881
+ static DEFAULT_ENCODING = "cl100k_base";
1882
+ static SUPPORTED_ENCODINGS = [
1883
+ "gpt2",
1884
+ "r50k_base",
1885
+ "p50k_base",
1886
+ "p50k_edit",
1887
+ "cl100k_base",
1888
+ "o200k_base"
1889
+ ];
1890
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1891
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1892
+ if (this.isSupportedEncodingName(normalized)) {
1893
+ return normalized;
1894
+ }
1895
+ if (normalized.includes("deepseek")) {
1896
+ return "cl100k_base";
1897
+ }
1898
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1899
+ return "o200k_base";
1900
+ }
1901
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1902
+ return "cl100k_base";
1903
+ }
1904
+ return this.DEFAULT_ENCODING;
1905
+ }
1906
+ static isSupportedEncodingName(value) {
1907
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1908
+ }
1909
+ static getEncoder(modelIdentifierOrEncoding) {
1910
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1911
+ const cached = this.encoderCache.get(encodingName);
1912
+ if (cached) {
1913
+ return cached;
1914
+ }
1915
+ const encoder = tiktoken.get_encoding(encodingName);
1916
+ this.encoderCache.set(encodingName, encoder);
1917
+ return encoder;
1918
+ }
1919
+ static estimateTokensRough(text, _modelIdentifier) {
1920
+ if (!text) return 0;
1921
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1922
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1923
+ const byteLength = new TextEncoder().encode(text).length;
1924
+ return Math.ceil(byteLength / ratio);
1925
+ }
1926
+ static estimateTokens(text, options = {}) {
1927
+ if (!text) return 0;
1928
+ if (options.encoding) {
1929
+ try {
1930
+ return this.estimateTokensPrecise(text, options.encoding);
1931
+ } catch {
1932
+ }
1933
+ }
1934
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1935
+ return Math.ceil(text.length / avgCharsPerToken);
1936
+ }
1937
+ static estimateTokensPrecise(text, modelIdentifier) {
1938
+ if (!text) return 0;
1939
+ const encoder = this.getEncoder(modelIdentifier);
1940
+ return encoder.encode(text).length;
1941
+ }
1942
+ static estimateMessageTokens(message, options = {}) {
1943
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1944
+ if (message.content) {
1945
+ totalTokens += this.estimateTokens(String(message.content), options);
1946
+ }
1947
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1948
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1949
+ for (const toolCall of toolCalls) {
1950
+ totalTokens += toolCallOverhead;
1951
+ const fn = toolCall["function"];
1952
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1953
+ const fnRecord = fn;
1954
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1955
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1956
+ }
1957
+ }
1958
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1959
+ if (toolCallId) {
1960
+ totalTokens += this.estimateTokens(toolCallId, options);
1961
+ }
1962
+ return totalTokens;
1963
+ }
1964
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1965
+ return this.estimateMessageTokens(message, {
1966
+ encoding: modelIdentifier,
1967
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1968
+ });
1969
+ }
1970
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1971
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1972
+ }
1973
+ static extractToolCallsForTokenEstimate(message) {
1974
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1975
+ if (Array.isArray(direct)) return direct;
1976
+ const metadata = "metadata" in message ? message.metadata : void 0;
1977
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1978
+ const metadataRecord = metadata;
1979
+ const metadataToolCalls = metadataRecord["tool_calls"];
1980
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1981
+ }
1982
+ static extractToolCallIdForTokenEstimate(message) {
1983
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1984
+ return message.tool_call_id;
1985
+ }
1986
+ const metadata = "metadata" in message ? message.metadata : void 0;
1987
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1988
+ const metadataRecord = metadata;
1989
+ const toolCallId = metadataRecord["tool_call_id"];
1990
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1991
+ }
1992
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1993
+ if (!text || maxTokens <= 0) return "";
1994
+ const encoder = this.getEncoder(modelIdentifier);
1995
+ const tokens = encoder.encode(text);
1996
+ if (tokens.length <= maxTokens) {
1997
+ return text;
1998
+ }
1999
+ let truncatedTokens;
2000
+ const ellipsis = "...";
2001
+ switch (strategy) {
2002
+ case "start":
2003
+ truncatedTokens = tokens.slice(0, maxTokens);
2004
+ return encoder.decode(truncatedTokens) + ellipsis;
2005
+ case "end":
2006
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
2007
+ return ellipsis + encoder.decode(truncatedTokens);
2008
+ case "middle": {
2009
+ const half = Math.floor(maxTokens / 2);
2010
+ const head = tokens.slice(0, half);
2011
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
2012
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
2013
+ }
2014
+ default:
2015
+ truncatedTokens = tokens.slice(0, maxTokens);
2016
+ return encoder.decode(truncatedTokens) + ellipsis;
2017
+ }
2018
+ }
2019
+ static cleanup() {
2020
+ for (const encoder of this.encoderCache.values()) {
2021
+ encoder.free();
2022
+ }
2023
+ this.encoderCache.clear();
2024
+ }
2025
+ };
2026
+ function normalizePositiveNumber(value, fallback) {
2027
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2028
+ }
2029
+ function normalizeNonNegativeInteger(value, fallback) {
2030
+ if (typeof value !== "number" || !Number.isFinite(value)) {
2031
+ return fallback;
2032
+ }
2033
+ return Math.max(0, Math.floor(value));
2034
+ }
2035
+
2036
+ // src/shared/defaultTokenizerPort.ts
2037
+ var DefaultTokenizerPort = class {
2038
+ constructor(config = {}) {
2039
+ this.config = config;
2040
+ }
2041
+ config;
2042
+ estimateText(text, _modelId) {
2043
+ return TokenCalculator.estimateTokens(text, {
2044
+ encoding: this.config.encoding,
2045
+ avgCharsPerToken: this.config.avgCharsPerToken
2046
+ });
2047
+ }
2048
+ estimateMessage(message, _modelId) {
2049
+ return TokenCalculator.estimateMessageTokens(message, {
2050
+ encoding: this.config.encoding,
2051
+ avgCharsPerToken: this.config.avgCharsPerToken,
2052
+ toolCallOverhead: this.config.toolCallOverhead
2053
+ });
2054
+ }
2055
+ };
2056
+ function createDefaultTokenizerPort(config = {}) {
2057
+ return new DefaultTokenizerPort(config);
2058
+ }
1627
2059
 
1628
2060
  // src/runtime-kernel/llm/toolCallUtils.ts
1629
2061
  function isRecord2(value) {
@@ -1691,15 +2123,15 @@ function splitConcatenatedJsonObjects(input) {
1691
2123
  }
1692
2124
 
1693
2125
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1694
- function readNonEmptyString(value) {
2126
+ function readNonEmptyString2(value) {
1695
2127
  if (typeof value !== "string") return void 0;
1696
2128
  const trimmed = value.trim();
1697
2129
  return trimmed.length > 0 ? trimmed : void 0;
1698
2130
  }
1699
2131
  function resolveConversationIdForRuntimeEvents(toolContext) {
1700
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
2132
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
1701
2133
  if (fromCamel) return fromCamel;
1702
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
2134
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
1703
2135
  if (fromSnake) return fromSnake;
1704
2136
  return generateMessageId();
1705
2137
  }
@@ -1770,6 +2202,13 @@ function resolveUsage(response) {
1770
2202
  }
1771
2203
  return response.usage;
1772
2204
  }
2205
+ function resolveCanonicalUsage(response) {
2206
+ if (!response || typeof response === "string") {
2207
+ return void 0;
2208
+ }
2209
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2210
+ return parsed.success ? parsed.data : void 0;
2211
+ }
1773
2212
  function resolveToolCalls(response) {
1774
2213
  if (!response || typeof response === "string") {
1775
2214
  return void 0;
@@ -1824,181 +2263,54 @@ var contextAuditMiddleware = async (ctx, stage, next) => {
1824
2263
  });
1825
2264
  }
1826
2265
  };
1827
- var TokenCalculator = class {
1828
- static BYTES_PER_TOKEN_LATIN = 4;
1829
- static BYTES_PER_TOKEN_CJK = 3;
1830
- static OVERHEAD_PER_MESSAGE = 5;
1831
- static OVERHEAD_PER_TOOL_CALL = 10;
1832
- static encoderCache = /* @__PURE__ */ new Map();
1833
- static DEFAULT_ENCODING = "cl100k_base";
1834
- static SUPPORTED_ENCODINGS = [
1835
- "gpt2",
1836
- "r50k_base",
1837
- "p50k_base",
1838
- "p50k_edit",
1839
- "cl100k_base",
1840
- "o200k_base"
1841
- ];
1842
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1843
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1844
- if (this.isSupportedEncodingName(normalized)) {
1845
- return normalized;
1846
- }
1847
- if (normalized.includes("deepseek")) {
1848
- return "cl100k_base";
1849
- }
1850
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1851
- return "o200k_base";
1852
- }
1853
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1854
- return "cl100k_base";
1855
- }
1856
- return this.DEFAULT_ENCODING;
1857
- }
1858
- static isSupportedEncodingName(value) {
1859
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1860
- }
1861
- static getEncoder(modelIdentifierOrEncoding) {
1862
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1863
- const cached = this.encoderCache.get(encodingName);
1864
- if (cached) {
1865
- return cached;
1866
- }
1867
- const encoder = tiktoken.get_encoding(encodingName);
1868
- this.encoderCache.set(encodingName, encoder);
1869
- return encoder;
1870
- }
1871
- static estimateTokensRough(text, _modelIdentifier) {
1872
- if (!text) return 0;
1873
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1874
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1875
- const byteLength = new TextEncoder().encode(text).length;
1876
- return Math.ceil(byteLength / ratio);
1877
- }
1878
- static estimateTokens(text, options = {}) {
1879
- if (!text) return 0;
1880
- if (options.encoding) {
1881
- try {
1882
- return this.estimateTokensPrecise(text, options.encoding);
1883
- } catch {
1884
- }
1885
- }
1886
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1887
- return Math.ceil(text.length / avgCharsPerToken);
1888
- }
1889
- static estimateTokensPrecise(text, modelIdentifier) {
1890
- if (!text) return 0;
1891
- const encoder = this.getEncoder(modelIdentifier);
1892
- return encoder.encode(text).length;
1893
- }
1894
- static estimateMessageTokens(message, options = {}) {
1895
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1896
- if (message.content) {
1897
- totalTokens += this.estimateTokens(String(message.content), options);
1898
- }
1899
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1900
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1901
- for (const toolCall of toolCalls) {
1902
- totalTokens += toolCallOverhead;
1903
- const fn = toolCall["function"];
1904
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1905
- const fnRecord = fn;
1906
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1907
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1908
- }
1909
- }
1910
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1911
- if (toolCallId) {
1912
- totalTokens += this.estimateTokens(toolCallId, options);
1913
- }
1914
- return totalTokens;
1915
- }
1916
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1917
- return this.estimateMessageTokens(message, {
1918
- encoding: modelIdentifier,
1919
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1920
- });
1921
- }
1922
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1923
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1924
- }
1925
- static extractToolCallsForTokenEstimate(message) {
1926
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1927
- if (Array.isArray(direct)) return direct;
1928
- const metadata = "metadata" in message ? message.metadata : void 0;
1929
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1930
- const metadataRecord = metadata;
1931
- const metadataToolCalls = metadataRecord["tool_calls"];
1932
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1933
- }
1934
- static extractToolCallIdForTokenEstimate(message) {
1935
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1936
- return message.tool_call_id;
1937
- }
1938
- const metadata = "metadata" in message ? message.metadata : void 0;
1939
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1940
- const metadataRecord = metadata;
1941
- const toolCallId = metadataRecord["tool_call_id"];
1942
- return typeof toolCallId === "string" ? toolCallId : void 0;
1943
- }
1944
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1945
- if (!text || maxTokens <= 0) return "";
1946
- const encoder = this.getEncoder(modelIdentifier);
1947
- const tokens = encoder.encode(text);
1948
- if (tokens.length <= maxTokens) {
1949
- return text;
1950
- }
1951
- let truncatedTokens;
1952
- const ellipsis = "...";
1953
- switch (strategy) {
1954
- case "start":
1955
- truncatedTokens = tokens.slice(0, maxTokens);
1956
- return encoder.decode(truncatedTokens) + ellipsis;
1957
- case "end":
1958
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1959
- return ellipsis + encoder.decode(truncatedTokens);
1960
- case "middle": {
1961
- const half = Math.floor(maxTokens / 2);
1962
- const head = tokens.slice(0, half);
1963
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1964
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1965
- }
1966
- default:
1967
- truncatedTokens = tokens.slice(0, maxTokens);
1968
- return encoder.decode(truncatedTokens) + ellipsis;
1969
- }
1970
- }
1971
- static cleanup() {
1972
- for (const encoder of this.encoderCache.values()) {
1973
- encoder.free();
1974
- }
1975
- this.encoderCache.clear();
1976
- }
1977
- };
1978
- function normalizePositiveNumber(value, fallback) {
1979
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2266
+ var als = new async_hooks.AsyncLocalStorage();
2267
+ function readTokenCount(record, key) {
2268
+ const value = record[key];
2269
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1980
2270
  }
1981
- function normalizeNonNegativeInteger(value, fallback) {
1982
- if (typeof value !== "number" || !Number.isFinite(value)) {
1983
- return fallback;
1984
- }
1985
- return Math.max(0, Math.floor(value));
2271
+ function readRecord(record, key) {
2272
+ const value = record[key];
2273
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2274
+ return Object.fromEntries(Object.entries(value));
1986
2275
  }
1987
- var als = new async_hooks.AsyncLocalStorage();
1988
- function normalizeLlmUsage(usage) {
2276
+ function normalizedUsageFromCanonical(canonicalUsage) {
2277
+ return {
2278
+ promptTokens: canonicalUsage.inputTokens,
2279
+ completionTokens: canonicalUsage.outputTokens,
2280
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2281
+ canonicalUsage
2282
+ };
2283
+ }
2284
+ function normalizeCanonicalLlmUsage(usage) {
1989
2285
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) return void 0;
1990
2286
  const rec = usage;
1991
- const promptTokensRaw = rec["prompt_tokens"];
1992
- const completionTokensRaw = rec["completion_tokens"];
1993
- const totalTokensRaw = rec["total_tokens"];
1994
- const tokensRaw = rec["tokens"];
1995
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1996
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1997
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1998
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1999
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
2000
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
2001
- return { promptTokens, completionTokens, totalTokens };
2287
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2288
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2289
+ if (inputTokens === void 0 || outputTokens === void 0) {
2290
+ return void 0;
2291
+ }
2292
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2293
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2294
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2295
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2296
+ const totalTokens = readTokenCount(rec, "total_tokens");
2297
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2298
+ return void 0;
2299
+ }
2300
+ return {
2301
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2302
+ outputTokens,
2303
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2304
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2305
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2306
+ source: "provider-response-usage",
2307
+ confidence: "actual",
2308
+ rawUsage: usage
2309
+ };
2310
+ }
2311
+ function normalizeLlmUsage(usage) {
2312
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage);
2313
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
2002
2314
  }
2003
2315
  function recordLlmCallTelemetry(entry) {
2004
2316
  const store = als.getStore();
@@ -2012,17 +2324,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2012
2324
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
2013
2325
  return;
2014
2326
  }
2015
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2327
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2328
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
2016
2329
  const respText = extractResponseText(ctx.llmResp);
2017
2330
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
2018
2331
  try {
2019
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
2020
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
2021
- return {
2022
- promptTokens,
2023
- completionTokens,
2024
- totalTokens: promptTokens + completionTokens
2025
- };
2332
+ const promptTokens = ctx.llmMessages.reduce(
2333
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2334
+ 0
2335
+ );
2336
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2337
+ return normalizedUsageFromCanonical({
2338
+ inputTokens: promptTokens,
2339
+ outputTokens: completionTokens,
2340
+ totalTokens: promptTokens + completionTokens,
2341
+ source: "local-estimate",
2342
+ confidence: "estimate"
2343
+ });
2026
2344
  } catch {
2027
2345
  return void 0;
2028
2346
  }
@@ -2032,7 +2350,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2032
2350
  stream: ctx.input.stream === true,
2033
2351
  startedAt: ctx.llmCallStartedAt,
2034
2352
  durationMs: ctx.llmCallDurationMs,
2035
- usage: normalizedUsage
2353
+ usage: normalizedUsage,
2354
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
2036
2355
  });
2037
2356
  ctx.telemetry.emit({
2038
2357
  kind: "llm_call",
@@ -2040,6 +2359,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
2040
2359
  stream: ctx.input.stream === true,
2041
2360
  durationMs: ctx.llmCallDurationMs,
2042
2361
  usage: normalizedUsage,
2362
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
2043
2363
  scope: {
2044
2364
  conversationId: ctx.conversationId || void 0,
2045
2365
  turnId: ctx.turnId,
@@ -2056,7 +2376,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
2056
2376
  if (stage.id !== "execute_llm") {
2057
2377
  return;
2058
2378
  }
2059
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2379
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
2060
2380
  if (!normalized) {
2061
2381
  return;
2062
2382
  }
@@ -2183,10 +2503,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2183
2503
  return [
2184
2504
  `\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`,
2185
2505
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2186
- "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",
2506
+ "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",
2187
2507
  `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`,
2188
2508
  ' \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',
2189
- "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"
2509
+ "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"
2190
2510
  ].join("\n");
2191
2511
  };
2192
2512
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2494,6 +2814,16 @@ function createApplySystemReminderStage() {
2494
2814
  };
2495
2815
  }
2496
2816
 
2817
+ // src/runtime-kernel/token-accounting/functions.ts
2818
+ function createContextComponentLedgerEntry(input) {
2819
+ return {
2820
+ ...input,
2821
+ kind: "context-component",
2822
+ components: [...input.components],
2823
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2824
+ };
2825
+ }
2826
+
2497
2827
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2498
2828
  var logger4 = new Logger("GraphAgentExecutor");
2499
2829
  function createBuildContextStage(dependencies) {
@@ -2510,6 +2840,23 @@ function createBuildContextStage(dependencies) {
2510
2840
  ctx.mode = contextBuildResult.mode;
2511
2841
  ctx.llmMessages = contextBuildResult.llmMessages;
2512
2842
  ctx.contextTrace = contextBuildResult.contextTrace;
2843
+ if (contextBuildResult.tokenEstimate) {
2844
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2845
+ ctx.telemetry.emit({
2846
+ kind: "context_build",
2847
+ modelId: ctx.modelId,
2848
+ mode: contextBuildResult.mode,
2849
+ tokenEstimate: contextBuildResult.tokenEstimate,
2850
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2851
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2852
+ scope: {
2853
+ conversationId: ctx.conversationId,
2854
+ runId: ctx.input.toolContext?.runId,
2855
+ parentRunId: ctx.input.toolContext?.parentRunId,
2856
+ turnId: ctx.turnId
2857
+ }
2858
+ });
2859
+ }
2513
2860
  for (const event of contextBuildResult.summaryEvents) {
2514
2861
  if (!isHistorySummaryEvent(event)) {
2515
2862
  continue;
@@ -2524,6 +2871,24 @@ function createBuildContextStage(dependencies) {
2524
2871
  }
2525
2872
  };
2526
2873
  }
2874
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2875
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2876
+ if (keptComponents.length === 0) {
2877
+ return void 0;
2878
+ }
2879
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2880
+ const createdAt = Date.now();
2881
+ return createContextComponentLedgerEntry({
2882
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2883
+ conversationId: ctx.conversationId,
2884
+ runId,
2885
+ parentRunId: ctx.input.toolContext?.parentRunId,
2886
+ turnId: ctx.turnId,
2887
+ route: contextBuildResult.tokenEstimate?.route,
2888
+ createdAt,
2889
+ components: keptComponents
2890
+ });
2891
+ }
2527
2892
 
2528
2893
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2529
2894
  function createBuildDecisionStage(dependencies) {
@@ -2644,7 +3009,7 @@ function createExecuteLlmStage(dependencies) {
2644
3009
  streamEventHandler,
2645
3010
  ctx.signal,
2646
3011
  (fallbackModelId) => {
2647
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
3012
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2648
3013
  },
2649
3014
  (info) => {
2650
3015
  ctx.modelFallbackAudit = info;
@@ -2688,7 +3053,7 @@ function createPrepareCallStage(dependencies) {
2688
3053
  return {
2689
3054
  id: "prepare_call",
2690
3055
  async run(ctx) {
2691
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
3056
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
2692
3057
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
2693
3058
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
2694
3059
  await emitAuditEnvelope(ctx.audit, {
@@ -2754,19 +3119,21 @@ var GraphAgentExecutor = class {
2754
3119
  modelCatalog;
2755
3120
  telemetryPort;
2756
3121
  auditPort;
3122
+ tokenizer;
2757
3123
  stages;
2758
3124
  middlewares;
2759
3125
  constructor(dependencies) {
2760
3126
  this.llmCaller = dependencies.llmCaller;
2761
3127
  this.toolRuntime = dependencies.toolRuntime;
2762
3128
  this.contextBuilder = dependencies.contextBuilder;
2763
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3129
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
2764
3130
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
2765
3131
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
2766
3132
  modelCatalog: this.modelCatalog
2767
3133
  });
2768
3134
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2769
3135
  this.auditPort = dependencies.auditPort ?? noopAudit;
3136
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2770
3137
  this.stages = [
2771
3138
  createPrepareCallStage({
2772
3139
  modelResolver: this.modelResolver,
@@ -2808,9 +3175,10 @@ var GraphAgentExecutor = class {
2808
3175
  llmMessages: [],
2809
3176
  mode: input.request.mode === "chat" ? "chat" : "agent",
2810
3177
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2811
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3178
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2812
3179
  telemetry: this.telemetryPort,
2813
- audit: this.auditPort
3180
+ audit: this.auditPort,
3181
+ tokenizer: this.tokenizer
2814
3182
  };
2815
3183
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2816
3184
  stream: input.stream === true,
@@ -2858,18 +3226,18 @@ function isSummarizationCallbacks(value) {
2858
3226
  function isGraphSseSink(value) {
2859
3227
  return typeof value === "function";
2860
3228
  }
2861
- function readNonEmptyString2(value) {
3229
+ function readNonEmptyString3(value) {
2862
3230
  if (typeof value !== "string") return void 0;
2863
3231
  const trimmed = value.trim();
2864
3232
  return trimmed.length > 0 ? trimmed : void 0;
2865
3233
  }
2866
3234
  function readGraphAgentLocal(local) {
2867
3235
  const source = local ?? {};
2868
- const answerId = readNonEmptyString2(source.answerId);
3236
+ const answerId = readNonEmptyString3(source.answerId);
2869
3237
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
2870
3238
  return {
2871
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
2872
- turnId: readNonEmptyString2(source.turnId),
3239
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3240
+ turnId: readNonEmptyString3(source.turnId),
2873
3241
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
2874
3242
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
2875
3243
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3634,7 +4002,7 @@ var LlmNode = class {
3634
4002
  function isRecord8(value) {
3635
4003
  return typeof value === "object" && value !== null && !Array.isArray(value);
3636
4004
  }
3637
- function readNonEmptyString3(value) {
4005
+ function readNonEmptyString4(value) {
3638
4006
  if (typeof value !== "string") {
3639
4007
  return void 0;
3640
4008
  }
@@ -3656,7 +4024,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3656
4024
  return void 0;
3657
4025
  }
3658
4026
  if (toolName === "write_report") {
3659
- const report = readNonEmptyString3(data.report);
4027
+ const report = readNonEmptyString4(data.report);
3660
4028
  if (!report) {
3661
4029
  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");
3662
4030
  }
@@ -3666,7 +4034,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3666
4034
  if (data.success !== true) {
3667
4035
  return void 0;
3668
4036
  }
3669
- const finalAnswer = readNonEmptyString3(data.final_answer);
4037
+ const finalAnswer = readNonEmptyString4(data.final_answer);
3670
4038
  if (!finalAnswer) {
3671
4039
  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");
3672
4040
  }
@@ -3775,11 +4143,11 @@ function buildToolOutputUiMeta(params) {
3775
4143
  }
3776
4144
  async function applyObservationGovernance(params) {
3777
4145
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3778
- return;
4146
+ return {};
3779
4147
  }
3780
4148
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3781
4149
  if (!policy.enabled) {
3782
- return;
4150
+ return {};
3783
4151
  }
3784
4152
  const truncated = await params.observationPreview.truncateObservation({
3785
4153
  context: params.toolContext,
@@ -3793,13 +4161,37 @@ async function applyObservationGovernance(params) {
3793
4161
  })
3794
4162
  });
3795
4163
  if (!truncated.truncated) {
3796
- return;
4164
+ return {};
3797
4165
  }
3798
4166
  params.parsed["observation"] = truncated.preview;
3799
4167
  const data = params.parsed["data"];
3800
4168
  if (isRecord9(data) && !("tool_output_store" in data)) {
3801
4169
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3802
4170
  }
4171
+ return {
4172
+ observationTruncation: buildObservationTruncationMeta({
4173
+ originalText: params.structuredObservation,
4174
+ previewText: truncated.preview,
4175
+ originalChars: truncated.originalChars,
4176
+ previewChars: truncated.previewChars,
4177
+ originalLines: truncated.originalLines,
4178
+ previewLines: truncated.previewLines
4179
+ })
4180
+ };
4181
+ }
4182
+ function buildObservationTruncationMeta(input) {
4183
+ return {
4184
+ originalChars: input.originalChars ?? input.originalText.length,
4185
+ previewChars: input.previewChars ?? input.previewText.length,
4186
+ originalLines: input.originalLines ?? countLines(input.originalText),
4187
+ previewLines: input.previewLines ?? countLines(input.previewText)
4188
+ };
4189
+ }
4190
+ function countLines(value) {
4191
+ if (value.length === 0) {
4192
+ return 0;
4193
+ }
4194
+ return value.split(/\r\n|\r|\n/).length;
3803
4195
  }
3804
4196
 
3805
4197
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4675,7 +5067,7 @@ var ToolNode = class {
4675
5067
  parentRunId: context.toolContext.parentRunId
4676
5068
  });
4677
5069
  applyProtocolFuseState(context.local);
4678
- await applyObservationGovernance({
5070
+ const observationGovernance = await applyObservationGovernance({
4679
5071
  parsed: context.parsed,
4680
5072
  toolName: context.toolName,
4681
5073
  toolContext: context.toolContext,
@@ -4702,6 +5094,12 @@ var ToolNode = class {
4702
5094
  runtimeToolOutput,
4703
5095
  execIdempotency: context.exec.idempotency
4704
5096
  });
5097
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
5098
+ runtimeToolOutput.metadata = {
5099
+ ...runtimeToolOutput.metadata ?? {},
5100
+ observationTruncation: observationGovernance.observationTruncation
5101
+ };
5102
+ }
4705
5103
  const remainingCalls = context.calls.slice(1);
4706
5104
  context.state.local = buildSuccessLocalState({
4707
5105
  local: context.local,
@@ -5000,12 +5398,12 @@ function asRecord(value) {
5000
5398
  }
5001
5399
  return value;
5002
5400
  }
5003
- function summarizeCheckpoint(conversationId, state, savedAt) {
5401
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
5004
5402
  const local = asRecord(state.local);
5005
5403
  const executorLocal = asRecord(local?.executorLocal);
5006
5404
  const pendingToolCalls = local?.pendingToolCalls;
5007
5405
  return {
5008
- conversationId,
5406
+ checkpointKey,
5009
5407
  schemaVersion: state.schemaVersion ?? 1,
5010
5408
  savedAt,
5011
5409
  currentNode: state.nodeId,
@@ -5024,25 +5422,25 @@ var MemoryCheckpointer = class {
5024
5422
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
5025
5423
  };
5026
5424
  }
5027
- async load(conversationId) {
5028
- const entry = this.store.get(conversationId);
5425
+ async load(checkpointKey) {
5426
+ const entry = this.store.get(checkpointKey);
5029
5427
  return entry ? this.cloneState(entry.state) : null;
5030
5428
  }
5031
- async save(conversationId, state) {
5032
- this.store.set(conversationId, {
5429
+ async save(checkpointKey, state) {
5430
+ this.store.set(checkpointKey, {
5033
5431
  state: this.cloneState(state),
5034
5432
  savedAt: Date.now()
5035
5433
  });
5036
5434
  }
5037
- async clear(conversationId) {
5038
- this.store.delete(conversationId);
5435
+ async clear(checkpointKey) {
5436
+ this.store.delete(checkpointKey);
5039
5437
  }
5040
- async peekMeta(conversationId) {
5041
- const entry = this.store.get(conversationId);
5042
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
5438
+ async peekMeta(checkpointKey) {
5439
+ const entry = this.store.get(checkpointKey);
5440
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
5043
5441
  }
5044
5442
  async list(filter = {}) {
5045
- 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);
5443
+ 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);
5046
5444
  if (filter.limit === void 0) {
5047
5445
  return summaries;
5048
5446
  }
@@ -6063,6 +6461,7 @@ async function callLlmStream(params) {
6063
6461
  const streamAnswerId = generateMessageId();
6064
6462
  let streamChunkSeq = 0;
6065
6463
  let capturedUsage = void 0;
6464
+ let capturedCanonicalUsage = void 0;
6066
6465
  const toolAccumulator = new ToolCallStreamAccumulator([
6067
6466
  "markdown_edit",
6068
6467
  "text_to_image",
@@ -6121,6 +6520,10 @@ async function callLlmStream(params) {
6121
6520
  if (typeof chunk !== "object" || chunk === null) {
6122
6521
  return;
6123
6522
  }
6523
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
6524
+ if (parsedCanonicalUsage.success) {
6525
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
6526
+ }
6124
6527
  if (chunk.content) {
6125
6528
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6126
6529
  fullResponse += chunk.content;
@@ -6205,6 +6608,12 @@ async function callLlmStream(params) {
6205
6608
  const onUsage = (usage) => {
6206
6609
  capturedUsage = usage;
6207
6610
  };
6611
+ const onCanonicalUsage = (usage) => {
6612
+ const parsed = CanonicalLlmUsage.safeParse(usage);
6613
+ if (parsed.success) {
6614
+ capturedCanonicalUsage = parsed.data;
6615
+ }
6616
+ };
6208
6617
  await aiEngine.chatCompletionStream(
6209
6618
  modelId,
6210
6619
  messages,
@@ -6217,7 +6626,8 @@ async function callLlmStream(params) {
6217
6626
  onError,
6218
6627
  onFinish,
6219
6628
  onThought,
6220
- onUsage
6629
+ onUsage,
6630
+ onCanonicalUsage
6221
6631
  );
6222
6632
  if (streamError) {
6223
6633
  throw streamError;
@@ -6225,12 +6635,13 @@ async function callLlmStream(params) {
6225
6635
  emitThoughtComplete(thoughtSegmenter.finalize());
6226
6636
  const mergedToolCalls = toolAccumulator.getToolCalls();
6227
6637
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6228
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
6638
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6229
6639
  return {
6230
6640
  content: fullResponse,
6231
6641
  tool_calls: mergedToolCalls,
6232
6642
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6233
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
6643
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
6644
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6234
6645
  };
6235
6646
  }
6236
6647
  return fullResponse;
@@ -6280,6 +6691,10 @@ function tryCloudQuotaFallback({
6280
6691
  }
6281
6692
 
6282
6693
  // src/runtime-kernel/llm/usage-telemetry.ts
6694
+ function parseCanonicalUsage(value) {
6695
+ const parsed = CanonicalLlmUsage.safeParse(value);
6696
+ return parsed.success ? parsed.data : void 0;
6697
+ }
6283
6698
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6284
6699
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6285
6700
  return normalizeCompletionResponse(response);
@@ -6290,6 +6705,7 @@ function normalizeCompletionResponse(response) {
6290
6705
  }
6291
6706
  if (isRecord17(response)) {
6292
6707
  const usage = response["usage"];
6708
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6293
6709
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6294
6710
  if (parsedToolCalls) {
6295
6711
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6297,7 +6713,8 @@ function normalizeCompletionResponse(response) {
6297
6713
  content: typeof response["content"] === "string" ? response["content"] : "",
6298
6714
  tool_calls: parsedToolCalls,
6299
6715
  reasoning_details: reasoningDetails,
6300
- ...usage !== void 0 ? { usage } : {}
6716
+ ...usage !== void 0 ? { usage } : {},
6717
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6301
6718
  };
6302
6719
  }
6303
6720
  }
@@ -6307,10 +6724,12 @@ function normalizeCompletionResponse(response) {
6307
6724
  if (typeof response === "object") {
6308
6725
  if (isRecord17(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6309
6726
  const usage = response["usage"];
6727
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6310
6728
  return {
6311
6729
  content: typeof response["content"] === "string" ? response["content"] : "",
6312
6730
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6313
- ...usage !== void 0 ? { usage } : {}
6731
+ ...usage !== void 0 ? { usage } : {},
6732
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6314
6733
  };
6315
6734
  }
6316
6735
  if (isRecord17(response)) {
@@ -6582,7 +7001,7 @@ function cloneRunRecord(record) {
6582
7001
  ...record,
6583
7002
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
6584
7003
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
6585
- metadata: record.metadata ? { ...record.metadata } : void 0
7004
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
6586
7005
  };
6587
7006
  }
6588
7007
  function matchesStatus(candidate, filter) {
@@ -6994,7 +7413,7 @@ function isTerminalStatus(status) {
6994
7413
  return status === "completed" || status === "failed" || status === "cancelled";
6995
7414
  }
6996
7415
  function cloneMetadata(metadata) {
6997
- return metadata ? { ...metadata } : void 0;
7416
+ return metadata ? structuredClone(metadata) : void 0;
6998
7417
  }
6999
7418
  function recordToSnapshot(record) {
7000
7419
  return {
@@ -7081,7 +7500,7 @@ var DefaultRunSupervisor = class {
7081
7500
  startedAt,
7082
7501
  updatedAt: startedAt,
7083
7502
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
7084
- metadata: spec.metadata ? { ...spec.metadata } : void 0
7503
+ metadata: cloneMetadata(spec.metadata)
7085
7504
  };
7086
7505
  await this.registryStore.save(record);
7087
7506
  const handle = new DefaultRunHandle({
@@ -7255,12 +7674,13 @@ var DefaultRunSupervisor = class {
7255
7674
  }
7256
7675
  try {
7257
7676
  await handle.markRunning({ currentNode: "detached" });
7677
+ const registeredRecord = await this.registryStore.load(handle.runId);
7258
7678
  const executorOutcome = await this.executor.execute({
7259
7679
  runId: handle.runId,
7260
- parentRunId: spec.parentRunId,
7261
- conversationId: spec.conversationId,
7262
- agentSpec: spec.agentSpec,
7263
- request: spec.request,
7680
+ parentRunId: handle.parentRunId,
7681
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
7682
+ agentSpec: await handle.spec(),
7683
+ request: await handle.request(),
7264
7684
  signal: handle.signal,
7265
7685
  eventBus: spec.eventBus,
7266
7686
  eventStore: spec.eventStore,
@@ -7269,7 +7689,7 @@ var DefaultRunSupervisor = class {
7269
7689
  contextFences: spec.contextFences,
7270
7690
  wakeSource: spec.wakeSource,
7271
7691
  ephemeral: spec.ephemeral,
7272
- metadata: spec.metadata
7692
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
7273
7693
  });
7274
7694
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
7275
7695
  this.notifyTerminalWaiters(outcome);
@@ -7333,10 +7753,14 @@ var DefaultRunSupervisor = class {
7333
7753
  await this.registryStore.save(record);
7334
7754
  }
7335
7755
  const completedAt = executorOutcome?.completedAt ?? this.now();
7756
+ const fallbackMeta = record ? void 0 : await handle.meta();
7336
7757
  const outcome = recordToTerminalOutcome(record ?? {
7337
7758
  runId: handle.runId,
7338
7759
  parentRunId: handle.parentRunId,
7339
- status: executorOutcome?.status ?? "completed"}, completedAt);
7760
+ conversationId: fallbackMeta?.conversationId ?? "",
7761
+ agentSpecId: fallbackMeta?.agentSpecId,
7762
+ status: executorOutcome?.status ?? "completed",
7763
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
7340
7764
  const nextOutcome = {
7341
7765
  ...outcome,
7342
7766
  metadata: {
@@ -7664,6 +8088,7 @@ async function emitRunEvent(event, sink) {
7664
8088
  async function runAgent(agent, options) {
7665
8089
  const modelId = resolveModelId(agent, options);
7666
8090
  const conversationId = options.conversationId ?? `conv_${Date.now()}`;
8091
+ const checkpointKey = conversationId;
7667
8092
  const runId = options.runId ?? generateRunId();
7668
8093
  const turnId = runId;
7669
8094
  const costCollector = new QuickstartRunCostCollector();
@@ -7718,7 +8143,7 @@ async function runAgent(agent, options) {
7718
8143
  };
7719
8144
  await handle.markRunning({ currentNode: "user" });
7720
8145
  try {
7721
- await executor.prime(conversationId, {
8146
+ await executor.prime(checkpointKey, {
7722
8147
  conversationId,
7723
8148
  turnId,
7724
8149
  request: {
@@ -7743,7 +8168,7 @@ async function runAgent(agent, options) {
7743
8168
  return void 0;
7744
8169
  }
7745
8170
  });
7746
- const result = await executor.runUntilYield(conversationId);
8171
+ const result = await executor.runUntilYield(checkpointKey);
7747
8172
  runtimeEvents.push(...result.events);
7748
8173
  for (const event of result.events) {
7749
8174
  if (event.type === "final_answer_chunk") continue;