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