@linnlabs/linnkit 0.9.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/bin/linnkit.cjs +7 -0
  3. package/dist/{agent-invocation-BHcNfrBV.d.cts → agent-invocation-CAlm9qOw.d.cts} +1 -1
  4. package/dist/{agent-invocation-BznDaXDs.d.ts → agent-invocation-DKoEDLkl.d.ts} +1 -1
  5. package/dist/{ai-engine.types-vZRnQcJa.d.ts → ai-engine.types-CeLoM624.d.cts} +9 -1
  6. package/dist/{ai-engine.types-BpeU_XQG.d.cts → ai-engine.types-LqmnfR2W.d.ts} +9 -1
  7. package/dist/{audit-CtcfART1.d.ts → audit-BuWHoMEr.d.ts} +4 -2
  8. package/dist/{audit-LeOrm2hX.d.cts → audit-DnzNQzwq.d.cts} +4 -2
  9. package/dist/cli.cjs +682 -258
  10. package/dist/cli.cjs.map +1 -1
  11. package/dist/cli.js +682 -258
  12. package/dist/cli.js.map +1 -1
  13. package/dist/context-manager.cjs +823 -57
  14. package/dist/context-manager.cjs.map +1 -1
  15. package/dist/context-manager.d.cts +132 -18
  16. package/dist/context-manager.d.ts +132 -18
  17. package/dist/context-manager.js +823 -58
  18. package/dist/context-manager.js.map +1 -1
  19. package/dist/{context-trace-HE2qY5Q-.d.cts → context-trace-DrtvKac4.d.cts} +37 -4
  20. package/dist/{context-trace-DRi5M4lX.d.ts → context-trace-WV1HAZeB.d.ts} +37 -4
  21. package/dist/contracts.cjs +225 -2
  22. package/dist/contracts.cjs.map +1 -1
  23. package/dist/contracts.d.cts +6 -4
  24. package/dist/contracts.d.ts +6 -4
  25. package/dist/contracts.js +205 -3
  26. package/dist/contracts.js.map +1 -1
  27. package/dist/{defaultGraphExecutor-BIjJj7WF.d.cts → defaultGraphExecutor-L1ri3oij.d.cts} +48 -19
  28. package/dist/{defaultGraphExecutor-BBswR8wn.d.ts → defaultGraphExecutor-QzzdudLQ.d.ts} +48 -19
  29. package/dist/{index-BanRABEt.d.cts → index-BeQO0rx2.d.cts} +345 -268
  30. package/dist/{index-Cvr23YCl.d.cts → index-CDofGr_4.d.ts} +24 -6
  31. package/dist/{index-Dl5PLgAv.d.cts → index-Crl5E4eF.d.cts} +27 -4
  32. package/dist/{index-CJeWHopy.d.ts → index-DWGKvssS.d.ts} +3 -3
  33. package/dist/{index-CHqwkvGp.d.ts → index-X5lYU1Lj.d.ts} +27 -4
  34. package/dist/{index-DDzuSb0n.d.ts → index-uCNCpJBg.d.cts} +24 -6
  35. package/dist/{index-Z8NXKNwI.d.ts → index-wOZD-p2-.d.ts} +345 -268
  36. package/dist/{index-DO4dQgf2.d.cts → index-wXVAHZ0D.d.cts} +3 -3
  37. package/dist/index.cjs +1011 -329
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.d.cts +19 -16
  40. package/dist/index.d.ts +19 -16
  41. package/dist/index.js +1011 -329
  42. package/dist/index.js.map +1 -1
  43. package/dist/{messages-XthmnHZ3.d.cts → messages-Br5SiLD3.d.cts} +706 -1
  44. package/dist/{messages-XthmnHZ3.d.ts → messages-Br5SiLD3.d.ts} +706 -1
  45. package/dist/{ports-DnLuKfpE.d.ts → ports-Dugizzje.d.cts} +6 -2
  46. package/dist/{ports-DaatKJXp.d.cts → ports-fhp84x_C.d.ts} +6 -2
  47. package/dist/ports.d.cts +8 -5
  48. package/dist/ports.d.ts +8 -5
  49. package/dist/quickstart.cjs +683 -258
  50. package/dist/quickstart.cjs.map +1 -1
  51. package/dist/quickstart.d.cts +11 -10
  52. package/dist/quickstart.d.ts +11 -10
  53. package/dist/quickstart.js +683 -258
  54. package/dist/quickstart.js.map +1 -1
  55. package/dist/{runAgent-CPj_9e58.d.ts → runAgent-BmMSju8I.d.ts} +6 -6
  56. package/dist/{runAgent-HYKlXbVr.d.cts → runAgent-CKgcRSRH.d.cts} +6 -6
  57. package/dist/{runHandle-D3gPsD7B.d.cts → runHandle-DH4VmQx6.d.cts} +6 -4
  58. package/dist/{runHandle-CyXvzgzk.d.ts → runHandle-o3p06Nva.d.ts} +6 -4
  59. package/dist/runtime-kernel/events.cjs +202 -1
  60. package/dist/runtime-kernel/events.cjs.map +1 -1
  61. package/dist/runtime-kernel/events.d.cts +5 -5
  62. package/dist/runtime-kernel/events.d.ts +5 -5
  63. package/dist/runtime-kernel/events.js +202 -1
  64. package/dist/runtime-kernel/events.js.map +1 -1
  65. package/dist/runtime-kernel.cjs +999 -340
  66. package/dist/runtime-kernel.cjs.map +1 -1
  67. package/dist/runtime-kernel.d.cts +16 -14
  68. package/dist/runtime-kernel.d.ts +16 -14
  69. package/dist/runtime-kernel.js +990 -341
  70. package/dist/runtime-kernel.js.map +1 -1
  71. package/dist/testkit.cjs +1003 -321
  72. package/dist/testkit.cjs.map +1 -1
  73. package/dist/testkit.d.cts +16 -14
  74. package/dist/testkit.d.ts +16 -14
  75. package/dist/testkit.js +1003 -321
  76. package/dist/testkit.js.map +1 -1
  77. package/dist/{todo-B1PmDlp3.d.cts → todo-Ca8llpRQ.d.cts} +1 -1
  78. package/dist/{todo-B1PmDlp3.d.ts → todo-Ca8llpRQ.d.ts} +1 -1
  79. package/dist/{agentSpec-EkmviZjy.d.cts → token-accounting-CwpSPg4y.d.cts} +1280 -1
  80. package/dist/{agentSpec-EkmviZjy.d.ts → token-accounting-CwpSPg4y.d.ts} +1280 -1
  81. package/dist/token-calibration-Cxv6dDYF.d.cts +327 -0
  82. package/dist/token-calibration-Cxv6dDYF.d.ts +327 -0
  83. package/dist/token-counter-CFfP8PQb.d.cts +26 -0
  84. package/dist/token-counter-SFyyTeaG.d.ts +26 -0
  85. package/dist/token-usage-CqwT7-5K.d.cts +133 -0
  86. package/dist/token-usage-CqwT7-5K.d.ts +133 -0
  87. package/dist/{tokenizer-DFL4I7-I.d.ts → tokenizer-BFJNCHFX.d.ts} +1 -1
  88. package/dist/{tokenizer-DH_JXv-H.d.cts → tokenizer-DoGsBE3A.d.cts} +1 -1
  89. package/dist/{toolContracts-CLkQmhTG.d.cts → toolContracts-Bm3EZ1UM.d.cts} +13 -2
  90. package/dist/{toolContracts-Blll0241.d.ts → toolContracts-f8lzZBNa.d.ts} +13 -2
  91. package/docs/README.md +1 -1
  92. package/docs/integration/README.md +3 -3
  93. package/docs/integration/agent-registration-guide.md +3 -1
  94. package/docs/integration/child-runs.md +4 -1
  95. package/docs/integration/context-engineering.md +83 -16
  96. package/docs/integration/context-fences.md +44 -3
  97. package/docs/integration/llm-provider.md +1 -1
  98. package/docs/integration/persistence.md +1 -0
  99. package/docs/integration/run-supervisor.md +3 -0
  100. package/docs/integration/tool-development-guide.md +7 -5
  101. package/docs/integration/tool-history.md +43 -17
  102. package/package.json +4 -3
package/dist/cli.cjs CHANGED
@@ -79,6 +79,12 @@ zod.z.object({
79
79
  args: zod.z.record(zod.z.unknown()).optional(),
80
80
  tool_call_id: zod.z.string()
81
81
  });
82
+ var ObservationTruncationMeta = zod.z.object({
83
+ originalChars: zod.z.number().int().nonnegative(),
84
+ previewChars: zod.z.number().int().nonnegative(),
85
+ originalLines: zod.z.number().int().nonnegative().optional(),
86
+ previewLines: zod.z.number().int().nonnegative().optional()
87
+ });
82
88
  var ImageInfoMeta = zod.z.object({
83
89
  url: zod.z.string().optional(),
84
90
  width: zod.z.number().int().positive().optional(),
@@ -110,6 +116,7 @@ var PersistentMetadata = zod.z.object({
110
116
  tool_name: zod.z.string().optional(),
111
117
  args: zod.z.record(zod.z.unknown()).optional(),
112
118
  tool_call_id: zod.z.string().optional(),
119
+ observationTruncation: ObservationTruncationMeta.optional(),
113
120
  raw_output: zod.z.string().optional(),
114
121
  image_info: ImageInfoMeta.optional(),
115
122
  taskType: zod.z.string().optional(),
@@ -203,6 +210,7 @@ var AgentSpecBudgetPolicy = zod.z.object({
203
210
  });
204
211
  var AgentSpecToolHistoryPolicy = zod.z.object({
205
212
  strategy: zod.z.enum(["per-pair", "per-run", "none"]).optional(),
213
+ retentionMode: zod.z.enum(["drop", "compress"]).optional(),
206
214
  keepLatestToolPairs: zod.z.number().int().nonnegative().optional(),
207
215
  keepLatestRuns: zod.z.number().int().nonnegative().optional(),
208
216
  maxInteractionGroups: zod.z.number().int().nonnegative().optional(),
@@ -255,7 +263,17 @@ var AgentSpecReasoningRetentionPolicy = zod.z.object({
255
263
  var AgentSpecTokenEstimationPolicy = zod.z.object({
256
264
  encoding: zod.z.string().min(1).optional(),
257
265
  avgCharsPerToken: zod.z.number().positive().optional(),
258
- toolCallOverhead: zod.z.number().int().nonnegative().optional()
266
+ toolCallOverhead: zod.z.number().int().nonnegative().optional(),
267
+ calibration: zod.z.object({
268
+ enabled: zod.z.boolean().optional(),
269
+ minSamples: zod.z.number().int().positive().optional(),
270
+ minCoefficient: zod.z.number().positive().optional(),
271
+ maxCoefficient: zod.z.number().positive().optional()
272
+ }).optional(),
273
+ remoteCount: zod.z.object({
274
+ enabled: zod.z.boolean().optional(),
275
+ failureBehavior: zod.z.enum(["use-local-estimate", "fail-fast"]).optional()
276
+ }).optional()
259
277
  });
260
278
  var AgentSpecSystemReminderTrigger = zod.z.object({
261
279
  kind: zod.z.string().min(1),
@@ -951,6 +969,189 @@ var createSSEErrorEvent = (id, conversationId, turnId, error, options = {}) => (
951
969
  error,
952
970
  ...options
953
971
  });
972
+ var TokenCountSource = zod.z.enum([
973
+ "local-estimate",
974
+ "provider-preflight-count",
975
+ "provider-response-usage",
976
+ "host-supplied",
977
+ "test-fixture"
978
+ ]);
979
+ var TokenCountConfidence = zod.z.enum([
980
+ "estimate",
981
+ "provider-estimate",
982
+ "actual"
983
+ ]);
984
+ var TokenRouteCapabilities = zod.z.object({
985
+ supportsRemoteTokenCount: zod.z.boolean().optional(),
986
+ supportsResponseUsage: zod.z.boolean().optional(),
987
+ supportsImageInput: zod.z.boolean().optional(),
988
+ supportsCachedInputBilling: zod.z.boolean().optional(),
989
+ supportsReasoningTokens: zod.z.boolean().optional()
990
+ });
991
+ var TokenRoute = zod.z.object({
992
+ providerId: zod.z.string().describe("host \u4FA7 provider \u6807\u8BC6\uFF1Aopenai / anthropic / openrouter / siliconflow / zai ..."),
993
+ 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"),
994
+ modelId: zod.z.string().describe("host \u4FA7\u6A21\u578B id"),
995
+ providerModelId: zod.z.string().optional().describe("provider \u5B9E\u9645\u6A21\u578B\u540D\uFF08\u4E0E host modelId \u53EF\u80FD\u4E0D\u540C\uFF09"),
996
+ capabilities: TokenRouteCapabilities.optional()
997
+ });
998
+ var tokenCount = zod.z.number().int().nonnegative();
999
+ var CanonicalLlmUsage = zod.z.object({
1000
+ inputTokens: tokenCount.describe("\u975E\u7F13\u5B58\u666E\u901A\u8F93\u5165 token"),
1001
+ outputTokens: tokenCount.describe("\u8F93\u51FA token"),
1002
+ reasoningTokens: tokenCount.optional().describe("\u63A8\u7406 token\uFF1Bundefined=\u672A\u5355\u5217\uFF0C0=\u62A5\u544A\u4E3A 0"),
1003
+ cacheReadTokens: tokenCount.optional().describe("\u7F13\u5B58\u547D\u4E2D\u8BFB\u53D6 token"),
1004
+ cacheWriteTokens: tokenCount.optional().describe("\u7F13\u5B58\u5199\u5165 token"),
1005
+ 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"),
1006
+ source: TokenCountSource,
1007
+ confidence: TokenCountConfidence,
1008
+ rawUsage: zod.z.unknown().optional().describe("\u539F\u59CB provider usage\uFF0C\u4EC5\u4F9B\u5BA1\u8BA1")
1009
+ });
1010
+ var tokenCount2 = zod.z.number().int().nonnegative();
1011
+ var tokenPrice = zod.z.number().finite().nonnegative();
1012
+ zod.z.enum([
1013
+ "llm-usage",
1014
+ "context-component"
1015
+ ]);
1016
+ var ContextTokenComponentKind = zod.z.enum([
1017
+ "system",
1018
+ "user",
1019
+ "assistant",
1020
+ "tool",
1021
+ "context-injection",
1022
+ "history-summary",
1023
+ "working-memory",
1024
+ "fence",
1025
+ "system-reminder",
1026
+ "other"
1027
+ ]);
1028
+ var TokenUsageTotals = zod.z.object({
1029
+ inputTokens: tokenCount2,
1030
+ outputTokens: tokenCount2,
1031
+ reasoningTokens: tokenCount2.optional(),
1032
+ cacheReadTokens: tokenCount2.optional(),
1033
+ cacheWriteTokens: tokenCount2.optional(),
1034
+ totalTokens: tokenCount2.optional(),
1035
+ usageCount: zod.z.number().int().nonnegative()
1036
+ });
1037
+ var ContextTokenComponent = zod.z.object({
1038
+ componentId: zod.z.string().min(1),
1039
+ kind: ContextTokenComponentKind,
1040
+ tokens: tokenCount2,
1041
+ source: TokenCountSource,
1042
+ confidence: TokenCountConfidence,
1043
+ label: zod.z.string().optional(),
1044
+ messageId: zod.z.string().optional(),
1045
+ role: zod.z.string().optional(),
1046
+ action: zod.z.string().optional(),
1047
+ kept: zod.z.boolean().optional(),
1048
+ truncatedAtExecution: zod.z.boolean().optional(),
1049
+ originalTokensEstimate: tokenCount2.optional(),
1050
+ droppedTokensEstimate: tokenCount2.optional()
1051
+ });
1052
+ var TokenLedgerEntryBase = zod.z.object({
1053
+ id: zod.z.string().min(1),
1054
+ runId: zod.z.string().optional(),
1055
+ parentRunId: zod.z.string().optional(),
1056
+ conversationId: zod.z.string().optional(),
1057
+ turnId: zod.z.string().optional(),
1058
+ stepId: zod.z.string().optional(),
1059
+ route: TokenRoute.optional(),
1060
+ createdAt: zod.z.number().int().nonnegative().optional()
1061
+ });
1062
+ var LlmUsageTokenLedgerEntry = TokenLedgerEntryBase.extend({
1063
+ kind: zod.z.literal("llm-usage"),
1064
+ modelId: zod.z.string().optional(),
1065
+ usage: CanonicalLlmUsage
1066
+ });
1067
+ var ContextComponentTokenLedgerEntry = TokenLedgerEntryBase.extend({
1068
+ kind: zod.z.literal("context-component"),
1069
+ components: zod.z.array(ContextTokenComponent),
1070
+ totalTokens: tokenCount2
1071
+ });
1072
+ zod.z.discriminatedUnion("kind", [
1073
+ LlmUsageTokenLedgerEntry,
1074
+ ContextComponentTokenLedgerEntry
1075
+ ]);
1076
+ var TokenLedgerAggregate = zod.z.object({
1077
+ llmUsage: TokenUsageTotals.optional(),
1078
+ contextTokens: tokenCount2,
1079
+ entryCount: zod.z.number().int().nonnegative(),
1080
+ llmCallCount: zod.z.number().int().nonnegative(),
1081
+ contextComponentCount: zod.z.number().int().nonnegative()
1082
+ });
1083
+ zod.z.object({
1084
+ /**
1085
+ * 父 run 自己产生的 usage;子 run 必须放到 children,避免展示或计费时重复相加。
1086
+ */
1087
+ own: TokenLedgerAggregate,
1088
+ children: TokenLedgerAggregate.optional()
1089
+ });
1090
+ var TokenCostComponent = zod.z.enum([
1091
+ "input",
1092
+ "output",
1093
+ "reasoning",
1094
+ "cacheRead",
1095
+ "cacheWrite"
1096
+ ]);
1097
+ zod.z.object({
1098
+ currency: zod.z.string().min(1),
1099
+ unit: zod.z.literal("per_1m_tokens"),
1100
+ input: tokenPrice.optional(),
1101
+ output: tokenPrice.optional(),
1102
+ reasoning: tokenPrice.optional(),
1103
+ cacheRead: tokenPrice.optional(),
1104
+ cacheWrite: tokenPrice.optional()
1105
+ });
1106
+ zod.z.object({
1107
+ status: zod.z.enum(["computed", "unknown"]),
1108
+ currency: zod.z.string().optional(),
1109
+ inputCost: tokenPrice.optional(),
1110
+ outputCost: tokenPrice.optional(),
1111
+ reasoningCost: tokenPrice.optional(),
1112
+ cacheReadCost: tokenPrice.optional(),
1113
+ cacheWriteCost: tokenPrice.optional(),
1114
+ totalCost: tokenPrice.optional(),
1115
+ missingPriceComponents: zod.z.array(TokenCostComponent).optional()
1116
+ });
1117
+ var tokenCount3 = zod.z.number().int().nonnegative();
1118
+ var actualCalibrationSource = zod.z.enum([
1119
+ "provider-response-usage",
1120
+ "host-supplied",
1121
+ "test-fixture"
1122
+ ]);
1123
+ zod.z.object({
1124
+ route: TokenRoute,
1125
+ localEstimateTokens: tokenCount3,
1126
+ actualInputTokens: tokenCount3,
1127
+ source: actualCalibrationSource,
1128
+ confidence: zod.z.literal("actual"),
1129
+ observedAt: zod.z.number().int().nonnegative().optional(),
1130
+ runId: zod.z.string().optional(),
1131
+ ledgerEntryId: zod.z.string().optional()
1132
+ });
1133
+ zod.z.object({
1134
+ enabled: zod.z.boolean(),
1135
+ applied: zod.z.boolean(),
1136
+ route: TokenRoute.optional(),
1137
+ sampleCount: zod.z.number().int().nonnegative(),
1138
+ coefficient: zod.z.number().positive().optional(),
1139
+ minSamples: zod.z.number().int().positive().optional(),
1140
+ minCoefficient: zod.z.number().positive().optional(),
1141
+ maxCoefficient: zod.z.number().positive().optional(),
1142
+ localEstimateTokens: tokenCount3.optional(),
1143
+ calibratedEstimateTokens: tokenCount3.optional(),
1144
+ deltaTokens: zod.z.number().int().optional(),
1145
+ sampleLedgerEntryIds: zod.z.array(zod.z.string()).optional()
1146
+ });
1147
+ zod.z.object({
1148
+ route: TokenRoute.optional(),
1149
+ localEstimateTokens: tokenCount3,
1150
+ calibratedEstimateTokens: tokenCount3,
1151
+ finalTokens: tokenCount3,
1152
+ source: zod.z.literal("local-estimate"),
1153
+ confidence: zod.z.literal("estimate")
1154
+ });
954
1155
 
955
1156
  // src/quickstart/toolSchema.ts
956
1157
  function serializeToolProperty(property) {
@@ -1084,6 +1285,7 @@ var Logger = class {
1084
1285
  constructor(moduleName) {
1085
1286
  this.moduleName = moduleName;
1086
1287
  }
1288
+ moduleName;
1087
1289
  debug(message, data) {
1088
1290
  this.log(0 /* DEBUG */, "debug", message, data);
1089
1291
  }
@@ -1156,6 +1358,17 @@ var logger = new Logger("GraphExecutor");
1156
1358
  function asLocalRecord(local) {
1157
1359
  return local && typeof local === "object" ? { ...local } : {};
1158
1360
  }
1361
+ function readNonEmptyString(value) {
1362
+ return typeof value === "string" && value.trim().length > 0 ? value : void 0;
1363
+ }
1364
+ function readRuntimeConversationId(state) {
1365
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1366
+ return readNonEmptyString(local?.conversationId);
1367
+ }
1368
+ function readRuntimeTurnId(state) {
1369
+ const local = state?.local && typeof state.local === "object" ? state.local : void 0;
1370
+ return readNonEmptyString(local?.turnId);
1371
+ }
1159
1372
  var GraphExecutor = class {
1160
1373
  constructor(checkpointer, config = {}) {
1161
1374
  this.checkpointer = checkpointer;
@@ -1165,6 +1378,7 @@ var GraphExecutor = class {
1165
1378
  };
1166
1379
  this.telemetryPort = config.telemetryPort ?? noopTelemetry;
1167
1380
  }
1381
+ checkpointer;
1168
1382
  nodes = /* @__PURE__ */ new Map();
1169
1383
  ephemeralLocals = /* @__PURE__ */ new Map();
1170
1384
  config;
@@ -1172,8 +1386,8 @@ var GraphExecutor = class {
1172
1386
  registerNode(node) {
1173
1387
  this.nodes.set(node.id, node);
1174
1388
  }
1175
- async peekCheckpoint(conversationId) {
1176
- return await this.checkpointer.load(conversationId);
1389
+ async peekCheckpoint(checkpointKey) {
1390
+ return await this.checkpointer.load(checkpointKey);
1177
1391
  }
1178
1392
  sanitize(state) {
1179
1393
  const local = asLocalRecord(state.local);
@@ -1185,8 +1399,8 @@ var GraphExecutor = class {
1185
1399
  local
1186
1400
  };
1187
1401
  }
1188
- async prime(conversationId, local, nodeId = "user") {
1189
- this.ephemeralLocals.set(conversationId, { ...local || {} });
1402
+ async prime(checkpointKey, local, nodeId = "user") {
1403
+ this.ephemeralLocals.set(checkpointKey, { ...local || {} });
1190
1404
  const localSansMemory = { ...local || {} };
1191
1405
  if ("memory" in localSansMemory) delete localSansMemory.memory;
1192
1406
  const state = {
@@ -1194,10 +1408,10 @@ var GraphExecutor = class {
1194
1408
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1195
1409
  local: localSansMemory
1196
1410
  };
1197
- await this.checkpointer.save(conversationId, state);
1411
+ await this.checkpointer.save(checkpointKey, state);
1198
1412
  }
1199
- async setNode(conversationId, nodeId, localPatch) {
1200
- const current = await this.checkpointer.load(conversationId) || {
1413
+ async setNode(checkpointKey, nodeId, localPatch) {
1414
+ const current = await this.checkpointer.load(checkpointKey) || {
1201
1415
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1202
1416
  local: {}
1203
1417
  };
@@ -1208,19 +1422,46 @@ var GraphExecutor = class {
1208
1422
  schemaVersion: current.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
1209
1423
  local: mergedLocal
1210
1424
  };
1211
- await this.checkpointer.save(conversationId, next);
1425
+ await this.checkpointer.save(checkpointKey, next);
1212
1426
  }
1213
- async runUntilYield(conversationId) {
1427
+ async runUntilYield(checkpointKey) {
1214
1428
  const runId = `run_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
1215
1429
  let lifecyclePhase = "completed";
1430
+ let initialState = null;
1431
+ try {
1432
+ initialState = await this.loadInitialState(checkpointKey);
1433
+ } catch (err) {
1434
+ lifecyclePhase = "failed";
1435
+ this.telemetryPort.emit({
1436
+ kind: "run_lifecycle",
1437
+ runId,
1438
+ phase: "spawned",
1439
+ scope: {}
1440
+ });
1441
+ this.telemetryPort.emit({
1442
+ kind: "run_lifecycle",
1443
+ runId,
1444
+ phase: lifecyclePhase,
1445
+ scope: {}
1446
+ });
1447
+ throw err;
1448
+ }
1449
+ let lifecycleConversationId = readRuntimeConversationId(initialState);
1450
+ let lifecycleTurnId = readRuntimeTurnId(initialState);
1216
1451
  this.telemetryPort.emit({
1217
1452
  kind: "run_lifecycle",
1218
1453
  runId,
1219
1454
  phase: "spawned",
1220
- scope: { conversationId: conversationId || void 0 }
1455
+ scope: {
1456
+ conversationId: lifecycleConversationId,
1457
+ turnId: lifecycleTurnId
1458
+ }
1221
1459
  });
1222
1460
  try {
1223
- return await this.runUntilYieldInternal(conversationId);
1461
+ const result = await this.runUntilYieldInternal(checkpointKey, initialState);
1462
+ lifecycleConversationId = readRuntimeConversationId(result.checkpoint);
1463
+ lifecycleTurnId = readRuntimeTurnId(result.checkpoint);
1464
+ return result;
1224
1465
  } catch (err) {
1225
1466
  lifecyclePhase = err?.name === "AbortError" ? "cancelled" : "failed";
1226
1467
  throw err;
@@ -1229,17 +1470,23 @@ var GraphExecutor = class {
1229
1470
  kind: "run_lifecycle",
1230
1471
  runId,
1231
1472
  phase: lifecyclePhase,
1232
- scope: { conversationId: conversationId || void 0 }
1473
+ scope: {
1474
+ conversationId: lifecycleConversationId,
1475
+ turnId: lifecycleTurnId
1476
+ }
1233
1477
  });
1234
1478
  }
1235
1479
  }
1236
- async runUntilYieldInternal(conversationId) {
1237
- let state = await this.checkpointer.load(conversationId) || {
1480
+ async loadInitialState(checkpointKey) {
1481
+ return await this.checkpointer.load(checkpointKey) || {
1238
1482
  nodeId: "user",
1239
1483
  schemaVersion: ENGINE_STATE_SCHEMA_VERSION,
1240
1484
  local: {}
1241
1485
  };
1242
- const ephemeral = this.ephemeralLocals.get(conversationId) || {};
1486
+ }
1487
+ async runUntilYieldInternal(checkpointKey, initialState) {
1488
+ let state = initialState;
1489
+ const ephemeral = this.ephemeralLocals.get(checkpointKey) || {};
1243
1490
  state = {
1244
1491
  ...state,
1245
1492
  schemaVersion: state.schemaVersion ?? ENGINE_STATE_SCHEMA_VERSION,
@@ -1268,7 +1515,7 @@ var GraphExecutor = class {
1268
1515
  const signalRaw = state.local?.signal;
1269
1516
  if (isAbortSignal2(signalRaw) && signalRaw.aborted) {
1270
1517
  logger.warn("[GraphExecutor] \u6536\u5230 AbortSignal\uFF0C\u7ACB\u5373\u505C\u6B62\u63A8\u7406\u5FAA\u73AF");
1271
- this.ephemeralLocals.delete(conversationId);
1518
+ this.ephemeralLocals.delete(checkpointKey);
1272
1519
  throwAbortError();
1273
1520
  }
1274
1521
  const isLastStep = cycleStepCount >= this.config.maxSteps;
@@ -1316,8 +1563,8 @@ var GraphExecutor = class {
1316
1563
  checkpointCount
1317
1564
  });
1318
1565
  const cp2 = this.sanitize(state);
1319
- await this.checkpointer.save(conversationId, cp2);
1320
- this.ephemeralLocals.delete(conversationId);
1566
+ await this.checkpointer.save(checkpointKey, cp2);
1567
+ this.ephemeralLocals.delete(checkpointKey);
1321
1568
  return { events: allEvents, checkpoint: cp2, stepCount };
1322
1569
  }
1323
1570
  logger.info("[GraphExecutor] \u8282\u70B9\u5207\u6362", {
@@ -1328,18 +1575,18 @@ var GraphExecutor = class {
1328
1575
  });
1329
1576
  const nodeRunStartedAt = Date.now();
1330
1577
  const nodeIdForTelemetry = state.nodeId;
1578
+ const conversationIdForTelemetry = readRuntimeConversationId(state);
1331
1579
  let result;
1332
1580
  try {
1333
1581
  result = await node.run(state);
1334
1582
  } finally {
1335
- const turnIdForTelemetry = typeof state.local?.turnId === "string" ? state.local.turnId : void 0;
1336
1583
  this.telemetryPort.emit({
1337
1584
  kind: "graph_node",
1338
1585
  nodeId: nodeIdForTelemetry,
1339
1586
  durationMs: Date.now() - nodeRunStartedAt,
1340
1587
  scope: {
1341
- conversationId: conversationId || void 0,
1342
- turnId: turnIdForTelemetry
1588
+ conversationId: conversationIdForTelemetry,
1589
+ turnId: readRuntimeTurnId(state)
1343
1590
  }
1344
1591
  });
1345
1592
  }
@@ -1378,7 +1625,7 @@ var GraphExecutor = class {
1378
1625
  });
1379
1626
  state = { ...state, nodeId: nextNodeId };
1380
1627
  const cp2 = this.sanitize(state);
1381
- await this.checkpointer.save(conversationId, cp2);
1628
+ await this.checkpointer.save(checkpointKey, cp2);
1382
1629
  continue;
1383
1630
  }
1384
1631
  if (result.kind === "yield") {
@@ -1389,7 +1636,7 @@ var GraphExecutor = class {
1389
1636
  checkpointCount
1390
1637
  });
1391
1638
  const cp2 = this.sanitize(state);
1392
- await this.checkpointer.save(conversationId, cp2);
1639
+ await this.checkpointer.save(checkpointKey, cp2);
1393
1640
  return { events: allEvents, checkpoint: cp2, stepCount };
1394
1641
  }
1395
1642
  if (result.kind === "pause") {
@@ -1400,7 +1647,7 @@ var GraphExecutor = class {
1400
1647
  checkpointCount
1401
1648
  });
1402
1649
  const cp2 = this.sanitize(state);
1403
- await this.checkpointer.save(conversationId, cp2);
1650
+ await this.checkpointer.save(checkpointKey, cp2);
1404
1651
  return { events: allEvents, checkpoint: cp2, stepCount };
1405
1652
  }
1406
1653
  }
@@ -1411,8 +1658,8 @@ var GraphExecutor = class {
1411
1658
  checkpointCount
1412
1659
  });
1413
1660
  const cp = this.sanitize(state);
1414
- await this.checkpointer.save(conversationId, cp);
1415
- this.ephemeralLocals.delete(conversationId);
1661
+ await this.checkpointer.save(checkpointKey, cp);
1662
+ this.ephemeralLocals.delete(checkpointKey);
1416
1663
  return { events: allEvents, checkpoint: cp, stepCount };
1417
1664
  }
1418
1665
  };
@@ -1508,6 +1755,190 @@ var noopAudit = {
1508
1755
  flush() {
1509
1756
  }
1510
1757
  };
1758
+ var TokenCalculator = class {
1759
+ static BYTES_PER_TOKEN_LATIN = 4;
1760
+ static BYTES_PER_TOKEN_CJK = 3;
1761
+ static OVERHEAD_PER_MESSAGE = 5;
1762
+ static OVERHEAD_PER_TOOL_CALL = 10;
1763
+ static encoderCache = /* @__PURE__ */ new Map();
1764
+ static DEFAULT_ENCODING = "cl100k_base";
1765
+ static SUPPORTED_ENCODINGS = [
1766
+ "gpt2",
1767
+ "r50k_base",
1768
+ "p50k_base",
1769
+ "p50k_edit",
1770
+ "cl100k_base",
1771
+ "o200k_base"
1772
+ ];
1773
+ static resolveEncodingFromModelIdentifier(modelIdentifier) {
1774
+ const normalized = (modelIdentifier || "").trim().toLowerCase();
1775
+ if (this.isSupportedEncodingName(normalized)) {
1776
+ return normalized;
1777
+ }
1778
+ if (normalized.includes("deepseek")) {
1779
+ return "cl100k_base";
1780
+ }
1781
+ if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1782
+ return "o200k_base";
1783
+ }
1784
+ if (normalized.includes("gemini") || normalized.includes("claude")) {
1785
+ return "cl100k_base";
1786
+ }
1787
+ return this.DEFAULT_ENCODING;
1788
+ }
1789
+ static isSupportedEncodingName(value) {
1790
+ return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1791
+ }
1792
+ static getEncoder(modelIdentifierOrEncoding) {
1793
+ const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1794
+ const cached = this.encoderCache.get(encodingName);
1795
+ if (cached) {
1796
+ return cached;
1797
+ }
1798
+ const encoder = tiktoken.get_encoding(encodingName);
1799
+ this.encoderCache.set(encodingName, encoder);
1800
+ return encoder;
1801
+ }
1802
+ static estimateTokensRough(text, _modelIdentifier) {
1803
+ if (!text) return 0;
1804
+ const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1805
+ const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1806
+ const byteLength = new TextEncoder().encode(text).length;
1807
+ return Math.ceil(byteLength / ratio);
1808
+ }
1809
+ static estimateTokens(text, options = {}) {
1810
+ if (!text) return 0;
1811
+ if (options.encoding) {
1812
+ try {
1813
+ return this.estimateTokensPrecise(text, options.encoding);
1814
+ } catch {
1815
+ }
1816
+ }
1817
+ const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1818
+ return Math.ceil(text.length / avgCharsPerToken);
1819
+ }
1820
+ static estimateTokensPrecise(text, modelIdentifier) {
1821
+ if (!text) return 0;
1822
+ const encoder = this.getEncoder(modelIdentifier);
1823
+ return encoder.encode(text).length;
1824
+ }
1825
+ static estimateMessageTokens(message, options = {}) {
1826
+ let totalTokens = this.OVERHEAD_PER_MESSAGE;
1827
+ if (message.content) {
1828
+ totalTokens += this.estimateTokens(String(message.content), options);
1829
+ }
1830
+ const toolCalls = this.extractToolCallsForTokenEstimate(message);
1831
+ const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1832
+ for (const toolCall of toolCalls) {
1833
+ totalTokens += toolCallOverhead;
1834
+ const fn = toolCall["function"];
1835
+ if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1836
+ const fnRecord = fn;
1837
+ totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1838
+ totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1839
+ }
1840
+ }
1841
+ const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1842
+ if (toolCallId) {
1843
+ totalTokens += this.estimateTokens(toolCallId, options);
1844
+ }
1845
+ return totalTokens;
1846
+ }
1847
+ static estimateMessageTokensPrecise(message, modelIdentifier) {
1848
+ return this.estimateMessageTokens(message, {
1849
+ encoding: modelIdentifier,
1850
+ toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1851
+ });
1852
+ }
1853
+ static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1854
+ return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1855
+ }
1856
+ static extractToolCallsForTokenEstimate(message) {
1857
+ const direct = "tool_calls" in message ? message.tool_calls : void 0;
1858
+ if (Array.isArray(direct)) return direct;
1859
+ const metadata = "metadata" in message ? message.metadata : void 0;
1860
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1861
+ const metadataRecord = metadata;
1862
+ const metadataToolCalls = metadataRecord["tool_calls"];
1863
+ return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1864
+ }
1865
+ static extractToolCallIdForTokenEstimate(message) {
1866
+ if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1867
+ return message.tool_call_id;
1868
+ }
1869
+ const metadata = "metadata" in message ? message.metadata : void 0;
1870
+ if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1871
+ const metadataRecord = metadata;
1872
+ const toolCallId = metadataRecord["tool_call_id"];
1873
+ return typeof toolCallId === "string" ? toolCallId : void 0;
1874
+ }
1875
+ static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1876
+ if (!text || maxTokens <= 0) return "";
1877
+ const encoder = this.getEncoder(modelIdentifier);
1878
+ const tokens = encoder.encode(text);
1879
+ if (tokens.length <= maxTokens) {
1880
+ return text;
1881
+ }
1882
+ let truncatedTokens;
1883
+ const ellipsis = "...";
1884
+ switch (strategy) {
1885
+ case "start":
1886
+ truncatedTokens = tokens.slice(0, maxTokens);
1887
+ return encoder.decode(truncatedTokens) + ellipsis;
1888
+ case "end":
1889
+ truncatedTokens = tokens.slice(tokens.length - maxTokens);
1890
+ return ellipsis + encoder.decode(truncatedTokens);
1891
+ case "middle": {
1892
+ const half = Math.floor(maxTokens / 2);
1893
+ const head = tokens.slice(0, half);
1894
+ const tail = tokens.slice(tokens.length - (maxTokens - half));
1895
+ return encoder.decode(head) + ellipsis + encoder.decode(tail);
1896
+ }
1897
+ default:
1898
+ truncatedTokens = tokens.slice(0, maxTokens);
1899
+ return encoder.decode(truncatedTokens) + ellipsis;
1900
+ }
1901
+ }
1902
+ static cleanup() {
1903
+ for (const encoder of this.encoderCache.values()) {
1904
+ encoder.free();
1905
+ }
1906
+ this.encoderCache.clear();
1907
+ }
1908
+ };
1909
+ function normalizePositiveNumber(value, fallback) {
1910
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
1911
+ }
1912
+ function normalizeNonNegativeInteger(value, fallback) {
1913
+ if (typeof value !== "number" || !Number.isFinite(value)) {
1914
+ return fallback;
1915
+ }
1916
+ return Math.max(0, Math.floor(value));
1917
+ }
1918
+
1919
+ // src/shared/defaultTokenizerPort.ts
1920
+ var DefaultTokenizerPort = class {
1921
+ constructor(config = {}) {
1922
+ this.config = config;
1923
+ }
1924
+ config;
1925
+ estimateText(text, _modelId) {
1926
+ return TokenCalculator.estimateTokens(text, {
1927
+ encoding: this.config.encoding,
1928
+ avgCharsPerToken: this.config.avgCharsPerToken
1929
+ });
1930
+ }
1931
+ estimateMessage(message, _modelId) {
1932
+ return TokenCalculator.estimateMessageTokens(message, {
1933
+ encoding: this.config.encoding,
1934
+ avgCharsPerToken: this.config.avgCharsPerToken,
1935
+ toolCallOverhead: this.config.toolCallOverhead
1936
+ });
1937
+ }
1938
+ };
1939
+ function createDefaultTokenizerPort(config = {}) {
1940
+ return new DefaultTokenizerPort(config);
1941
+ }
1511
1942
 
1512
1943
  // src/runtime-kernel/llm/toolCallUtils.ts
1513
1944
  function isRecord2(value) {
@@ -1575,15 +2006,15 @@ function splitConcatenatedJsonObjects(input) {
1575
2006
  }
1576
2007
 
1577
2008
  // src/runtime-kernel/graph-engine/tick-pipeline/helpers.ts
1578
- function readNonEmptyString(value) {
2009
+ function readNonEmptyString2(value) {
1579
2010
  if (typeof value !== "string") return void 0;
1580
2011
  const trimmed = value.trim();
1581
2012
  return trimmed.length > 0 ? trimmed : void 0;
1582
2013
  }
1583
2014
  function resolveConversationIdForRuntimeEvents(toolContext) {
1584
- const fromCamel = readNonEmptyString(toolContext?.conversationId);
2015
+ const fromCamel = readNonEmptyString2(toolContext?.conversationId);
1585
2016
  if (fromCamel) return fromCamel;
1586
- const fromSnake = toolContext ? readNonEmptyString(toolContext["conversation_id"]) : void 0;
2017
+ const fromSnake = toolContext ? readNonEmptyString2(toolContext["conversation_id"]) : void 0;
1587
2018
  if (fromSnake) return fromSnake;
1588
2019
  return generateMessageId();
1589
2020
  }
@@ -1654,6 +2085,13 @@ function resolveUsage(response) {
1654
2085
  }
1655
2086
  return response.usage;
1656
2087
  }
2088
+ function resolveCanonicalUsage(response) {
2089
+ if (!response || typeof response === "string") {
2090
+ return void 0;
2091
+ }
2092
+ const parsed = CanonicalLlmUsage.safeParse(response.canonicalUsage);
2093
+ return parsed.success ? parsed.data : void 0;
2094
+ }
1657
2095
  function resolveToolCalls(response) {
1658
2096
  if (!response || typeof response === "string") {
1659
2097
  return void 0;
@@ -1708,181 +2146,54 @@ var contextAuditMiddleware = async (ctx, stage, next) => {
1708
2146
  });
1709
2147
  }
1710
2148
  };
1711
- var TokenCalculator = class {
1712
- static BYTES_PER_TOKEN_LATIN = 4;
1713
- static BYTES_PER_TOKEN_CJK = 3;
1714
- static OVERHEAD_PER_MESSAGE = 5;
1715
- static OVERHEAD_PER_TOOL_CALL = 10;
1716
- static encoderCache = /* @__PURE__ */ new Map();
1717
- static DEFAULT_ENCODING = "cl100k_base";
1718
- static SUPPORTED_ENCODINGS = [
1719
- "gpt2",
1720
- "r50k_base",
1721
- "p50k_base",
1722
- "p50k_edit",
1723
- "cl100k_base",
1724
- "o200k_base"
1725
- ];
1726
- static resolveEncodingFromModelIdentifier(modelIdentifier) {
1727
- const normalized = (modelIdentifier || "").trim().toLowerCase();
1728
- if (this.isSupportedEncodingName(normalized)) {
1729
- return normalized;
1730
- }
1731
- if (normalized.includes("deepseek")) {
1732
- return "cl100k_base";
1733
- }
1734
- if (normalized.includes("gpt-4o") || normalized.startsWith("o1")) {
1735
- return "o200k_base";
1736
- }
1737
- if (normalized.includes("gemini") || normalized.includes("claude")) {
1738
- return "cl100k_base";
1739
- }
1740
- return this.DEFAULT_ENCODING;
1741
- }
1742
- static isSupportedEncodingName(value) {
1743
- return this.SUPPORTED_ENCODINGS.some((encoding) => encoding === value);
1744
- }
1745
- static getEncoder(modelIdentifierOrEncoding) {
1746
- const encodingName = this.resolveEncodingFromModelIdentifier(modelIdentifierOrEncoding);
1747
- const cached = this.encoderCache.get(encodingName);
1748
- if (cached) {
1749
- return cached;
1750
- }
1751
- const encoder = tiktoken.get_encoding(encodingName);
1752
- this.encoderCache.set(encodingName, encoder);
1753
- return encoder;
1754
- }
1755
- static estimateTokensRough(text, _modelIdentifier) {
1756
- if (!text) return 0;
1757
- const hasCJK = /[\u4e00-\u9fa5]|[\u3040-\u30ff]|[\uac00-\ud7af]/.test(text);
1758
- const ratio = hasCJK ? this.BYTES_PER_TOKEN_CJK : this.BYTES_PER_TOKEN_LATIN;
1759
- const byteLength = new TextEncoder().encode(text).length;
1760
- return Math.ceil(byteLength / ratio);
1761
- }
1762
- static estimateTokens(text, options = {}) {
1763
- if (!text) return 0;
1764
- if (options.encoding) {
1765
- try {
1766
- return this.estimateTokensPrecise(text, options.encoding);
1767
- } catch {
1768
- }
1769
- }
1770
- const avgCharsPerToken = normalizePositiveNumber(options.avgCharsPerToken, 2);
1771
- return Math.ceil(text.length / avgCharsPerToken);
1772
- }
1773
- static estimateTokensPrecise(text, modelIdentifier) {
1774
- if (!text) return 0;
1775
- const encoder = this.getEncoder(modelIdentifier);
1776
- return encoder.encode(text).length;
1777
- }
1778
- static estimateMessageTokens(message, options = {}) {
1779
- let totalTokens = this.OVERHEAD_PER_MESSAGE;
1780
- if (message.content) {
1781
- totalTokens += this.estimateTokens(String(message.content), options);
1782
- }
1783
- const toolCalls = this.extractToolCallsForTokenEstimate(message);
1784
- const toolCallOverhead = normalizeNonNegativeInteger(options.toolCallOverhead, this.OVERHEAD_PER_TOOL_CALL);
1785
- for (const toolCall of toolCalls) {
1786
- totalTokens += toolCallOverhead;
1787
- const fn = toolCall["function"];
1788
- if (fn && typeof fn === "object" && !Array.isArray(fn)) {
1789
- const fnRecord = fn;
1790
- totalTokens += this.estimateTokens(String(fnRecord["name"] ?? ""), options);
1791
- totalTokens += this.estimateTokens(String(fnRecord["arguments"] ?? ""), options);
1792
- }
1793
- }
1794
- const toolCallId = this.extractToolCallIdForTokenEstimate(message);
1795
- if (toolCallId) {
1796
- totalTokens += this.estimateTokens(toolCallId, options);
1797
- }
1798
- return totalTokens;
1799
- }
1800
- static estimateMessageTokensPrecise(message, modelIdentifier) {
1801
- return this.estimateMessageTokens(message, {
1802
- encoding: modelIdentifier,
1803
- toolCallOverhead: this.OVERHEAD_PER_TOOL_CALL
1804
- });
1805
- }
1806
- static estimateMessagesTokensPrecise(messages, modelIdentifier) {
1807
- return messages.reduce((total, msg) => total + this.estimateMessageTokensPrecise(msg, modelIdentifier), 0);
1808
- }
1809
- static extractToolCallsForTokenEstimate(message) {
1810
- const direct = "tool_calls" in message ? message.tool_calls : void 0;
1811
- if (Array.isArray(direct)) return direct;
1812
- const metadata = "metadata" in message ? message.metadata : void 0;
1813
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return [];
1814
- const metadataRecord = metadata;
1815
- const metadataToolCalls = metadataRecord["tool_calls"];
1816
- return Array.isArray(metadataToolCalls) ? metadataToolCalls : [];
1817
- }
1818
- static extractToolCallIdForTokenEstimate(message) {
1819
- if ("tool_call_id" in message && typeof message.tool_call_id === "string") {
1820
- return message.tool_call_id;
1821
- }
1822
- const metadata = "metadata" in message ? message.metadata : void 0;
1823
- if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return void 0;
1824
- const metadataRecord = metadata;
1825
- const toolCallId = metadataRecord["tool_call_id"];
1826
- return typeof toolCallId === "string" ? toolCallId : void 0;
1827
- }
1828
- static truncateTextByTokens(text, maxTokens, modelIdentifier, strategy = "end") {
1829
- if (!text || maxTokens <= 0) return "";
1830
- const encoder = this.getEncoder(modelIdentifier);
1831
- const tokens = encoder.encode(text);
1832
- if (tokens.length <= maxTokens) {
1833
- return text;
1834
- }
1835
- let truncatedTokens;
1836
- const ellipsis = "...";
1837
- switch (strategy) {
1838
- case "start":
1839
- truncatedTokens = tokens.slice(0, maxTokens);
1840
- return encoder.decode(truncatedTokens) + ellipsis;
1841
- case "end":
1842
- truncatedTokens = tokens.slice(tokens.length - maxTokens);
1843
- return ellipsis + encoder.decode(truncatedTokens);
1844
- case "middle": {
1845
- const half = Math.floor(maxTokens / 2);
1846
- const head = tokens.slice(0, half);
1847
- const tail = tokens.slice(tokens.length - (maxTokens - half));
1848
- return encoder.decode(head) + ellipsis + encoder.decode(tail);
1849
- }
1850
- default:
1851
- truncatedTokens = tokens.slice(0, maxTokens);
1852
- return encoder.decode(truncatedTokens) + ellipsis;
1853
- }
1854
- }
1855
- static cleanup() {
1856
- for (const encoder of this.encoderCache.values()) {
1857
- encoder.free();
1858
- }
1859
- this.encoderCache.clear();
1860
- }
1861
- };
1862
- function normalizePositiveNumber(value, fallback) {
1863
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback;
2149
+ var als = new async_hooks.AsyncLocalStorage();
2150
+ function readTokenCount(record, key) {
2151
+ const value = record[key];
2152
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : void 0;
1864
2153
  }
1865
- function normalizeNonNegativeInteger(value, fallback) {
1866
- if (typeof value !== "number" || !Number.isFinite(value)) {
1867
- return fallback;
1868
- }
1869
- return Math.max(0, Math.floor(value));
2154
+ function readRecord(record, key) {
2155
+ const value = record[key];
2156
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
2157
+ return Object.fromEntries(Object.entries(value));
1870
2158
  }
1871
- var als = new async_hooks.AsyncLocalStorage();
1872
- function normalizeLlmUsage(usage2) {
2159
+ function normalizedUsageFromCanonical(canonicalUsage) {
2160
+ return {
2161
+ promptTokens: canonicalUsage.inputTokens,
2162
+ completionTokens: canonicalUsage.outputTokens,
2163
+ totalTokens: canonicalUsage.totalTokens ?? canonicalUsage.inputTokens + canonicalUsage.outputTokens,
2164
+ canonicalUsage
2165
+ };
2166
+ }
2167
+ function normalizeCanonicalLlmUsage(usage2) {
1873
2168
  if (!usage2 || typeof usage2 !== "object" || Array.isArray(usage2)) return void 0;
1874
2169
  const rec = usage2;
1875
- const promptTokensRaw = rec["prompt_tokens"];
1876
- const completionTokensRaw = rec["completion_tokens"];
1877
- const totalTokensRaw = rec["total_tokens"];
1878
- const tokensRaw = rec["tokens"];
1879
- const promptTokens = typeof promptTokensRaw === "number" && Number.isFinite(promptTokensRaw) ? promptTokensRaw : 0;
1880
- const completionTokens = typeof completionTokensRaw === "number" && Number.isFinite(completionTokensRaw) ? completionTokensRaw : 0;
1881
- const totalFromExplicit = typeof totalTokensRaw === "number" && Number.isFinite(totalTokensRaw) ? totalTokensRaw : void 0;
1882
- const totalFromTokens = typeof tokensRaw === "number" && Number.isFinite(tokensRaw) ? tokensRaw : void 0;
1883
- const totalTokens = totalFromExplicit ?? totalFromTokens ?? promptTokens + completionTokens;
1884
- if (promptTokens === 0 && completionTokens === 0 && totalTokens === 0) return void 0;
1885
- return { promptTokens, completionTokens, totalTokens };
2170
+ const inputTokens = readTokenCount(rec, "prompt_tokens");
2171
+ const outputTokens = readTokenCount(rec, "completion_tokens");
2172
+ if (inputTokens === void 0 || outputTokens === void 0) {
2173
+ return void 0;
2174
+ }
2175
+ const promptDetails = readRecord(rec, "prompt_tokens_details");
2176
+ const completionDetails = readRecord(rec, "completion_tokens_details");
2177
+ const cacheReadTokens = promptDetails ? readTokenCount(promptDetails, "cached_tokens") : void 0;
2178
+ const reasoningTokens = completionDetails ? readTokenCount(completionDetails, "reasoning_tokens") : void 0;
2179
+ const totalTokens = readTokenCount(rec, "total_tokens");
2180
+ if (cacheReadTokens !== void 0 && cacheReadTokens > inputTokens) {
2181
+ return void 0;
2182
+ }
2183
+ return {
2184
+ inputTokens: cacheReadTokens !== void 0 ? inputTokens - cacheReadTokens : inputTokens,
2185
+ outputTokens,
2186
+ ...reasoningTokens !== void 0 ? { reasoningTokens } : {},
2187
+ ...cacheReadTokens !== void 0 ? { cacheReadTokens } : {},
2188
+ ...totalTokens !== void 0 ? { totalTokens } : {},
2189
+ source: "provider-response-usage",
2190
+ confidence: "actual",
2191
+ rawUsage: usage2
2192
+ };
2193
+ }
2194
+ function normalizeLlmUsage(usage2) {
2195
+ const canonicalUsage = normalizeCanonicalLlmUsage(usage2);
2196
+ return canonicalUsage ? normalizedUsageFromCanonical(canonicalUsage) : void 0;
1886
2197
  }
1887
2198
  function recordLlmCallTelemetry(entry) {
1888
2199
  const store = als.getStore();
@@ -1896,17 +2207,23 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1896
2207
  if (stage.id !== "execute_llm" || ctx.llmCallStartedAt === void 0 || ctx.llmCallDurationMs === void 0) {
1897
2208
  return;
1898
2209
  }
1899
- const normalizedUsageFromProvider = normalizeLlmUsage(resolveUsage(ctx.llmResp));
2210
+ const canonicalUsageFromHost = resolveCanonicalUsage(ctx.llmResp);
2211
+ const normalizedUsageFromProvider = canonicalUsageFromHost ? normalizedUsageFromCanonical(canonicalUsageFromHost) : normalizeLlmUsage(resolveUsage(ctx.llmResp));
1900
2212
  const respText = extractResponseText(ctx.llmResp);
1901
2213
  const normalizedUsage = normalizedUsageFromProvider ?? (() => {
1902
2214
  try {
1903
- const promptTokens = TokenCalculator.estimateMessagesTokensPrecise(ctx.llmMessages, ctx.modelId);
1904
- const completionTokens = TokenCalculator.estimateTokensPrecise(respText, ctx.modelId);
1905
- return {
1906
- promptTokens,
1907
- completionTokens,
1908
- totalTokens: promptTokens + completionTokens
1909
- };
2215
+ const promptTokens = ctx.llmMessages.reduce(
2216
+ (total, message) => total + ctx.tokenizer.estimateMessage(message, ctx.modelId),
2217
+ 0
2218
+ );
2219
+ const completionTokens = ctx.tokenizer.estimateText(respText, ctx.modelId);
2220
+ return normalizedUsageFromCanonical({
2221
+ inputTokens: promptTokens,
2222
+ outputTokens: completionTokens,
2223
+ totalTokens: promptTokens + completionTokens,
2224
+ source: "local-estimate",
2225
+ confidence: "estimate"
2226
+ });
1910
2227
  } catch {
1911
2228
  return void 0;
1912
2229
  }
@@ -1916,7 +2233,8 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1916
2233
  stream: ctx.input.stream === true,
1917
2234
  startedAt: ctx.llmCallStartedAt,
1918
2235
  durationMs: ctx.llmCallDurationMs,
1919
- usage: normalizedUsage
2236
+ usage: normalizedUsage,
2237
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {}
1920
2238
  });
1921
2239
  ctx.telemetry.emit({
1922
2240
  kind: "llm_call",
@@ -1924,6 +2242,7 @@ var llmTelemetryMiddleware = async (ctx, stage, next) => {
1924
2242
  stream: ctx.input.stream === true,
1925
2243
  durationMs: ctx.llmCallDurationMs,
1926
2244
  usage: normalizedUsage,
2245
+ ...normalizedUsage?.canonicalUsage ? { canonicalUsage: normalizedUsage.canonicalUsage } : {},
1927
2246
  scope: {
1928
2247
  conversationId: ctx.conversationId || void 0,
1929
2248
  turnId: ctx.turnId,
@@ -1940,7 +2259,7 @@ var runModelLockMiddleware = async (ctx, stage, next) => {
1940
2259
  if (stage.id !== "execute_llm") {
1941
2260
  return;
1942
2261
  }
1943
- const normalized = readNonEmptyString(ctx.cloudQuotaFallbackAppliedModelId);
2262
+ const normalized = readNonEmptyString2(ctx.cloudQuotaFallbackAppliedModelId);
1944
2263
  if (!normalized) {
1945
2264
  return;
1946
2265
  }
@@ -2067,10 +2386,10 @@ var contextBudgetWarningTemplate = (ctx) => {
2067
2386
  return [
2068
2387
  `\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`,
2069
2388
  "\u4F60\u5FC5\u987B\u7ACB\u5373\u6267\u884C\u4EE5\u4E0B\u64CD\u4F5C\u4EE5\u907F\u514D\u4E0A\u4E0B\u6587\u6EA2\u51FA\uFF1A",
2070
- "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",
2389
+ "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",
2071
2390
  `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`,
2072
2391
  ' \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',
2073
- "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"
2392
+ "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"
2074
2393
  ].join("\n");
2075
2394
  };
2076
2395
  var BUILTIN_SYSTEM_REMINDER_TEMPLATES = {
@@ -2378,6 +2697,16 @@ function createApplySystemReminderStage() {
2378
2697
  };
2379
2698
  }
2380
2699
 
2700
+ // src/runtime-kernel/token-accounting/functions.ts
2701
+ function createContextComponentLedgerEntry(input) {
2702
+ return {
2703
+ ...input,
2704
+ kind: "context-component",
2705
+ components: [...input.components],
2706
+ totalTokens: input.components.reduce((total, component) => total + component.tokens, 0)
2707
+ };
2708
+ }
2709
+
2381
2710
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildContextStage.ts
2382
2711
  var logger4 = new Logger("GraphAgentExecutor");
2383
2712
  function createBuildContextStage(dependencies) {
@@ -2394,6 +2723,23 @@ function createBuildContextStage(dependencies) {
2394
2723
  ctx.mode = contextBuildResult.mode;
2395
2724
  ctx.llmMessages = contextBuildResult.llmMessages;
2396
2725
  ctx.contextTrace = contextBuildResult.contextTrace;
2726
+ if (contextBuildResult.tokenEstimate) {
2727
+ const tokenLedgerEntry = contextBuildResult.tokenLedgerEntry ?? createContextLedgerEntry(ctx, contextBuildResult);
2728
+ ctx.telemetry.emit({
2729
+ kind: "context_build",
2730
+ modelId: ctx.modelId,
2731
+ mode: contextBuildResult.mode,
2732
+ tokenEstimate: contextBuildResult.tokenEstimate,
2733
+ ...contextBuildResult.tokenComponents ? { tokenComponents: contextBuildResult.tokenComponents } : {},
2734
+ ...tokenLedgerEntry ? { tokenLedgerEntry } : {},
2735
+ scope: {
2736
+ conversationId: ctx.conversationId,
2737
+ runId: ctx.input.toolContext?.runId,
2738
+ parentRunId: ctx.input.toolContext?.parentRunId,
2739
+ turnId: ctx.turnId
2740
+ }
2741
+ });
2742
+ }
2397
2743
  for (const event of contextBuildResult.summaryEvents) {
2398
2744
  if (!isHistorySummaryEvent(event)) {
2399
2745
  continue;
@@ -2408,6 +2754,24 @@ function createBuildContextStage(dependencies) {
2408
2754
  }
2409
2755
  };
2410
2756
  }
2757
+ function createContextLedgerEntry(ctx, contextBuildResult) {
2758
+ const keptComponents = contextBuildResult.tokenComponents?.filter((component) => component.kept !== false) ?? [];
2759
+ if (keptComponents.length === 0) {
2760
+ return void 0;
2761
+ }
2762
+ const runId = ctx.input.toolContext?.runId ?? ctx.turnId;
2763
+ const createdAt = Date.now();
2764
+ return createContextComponentLedgerEntry({
2765
+ id: `context_${runId}_${ctx.turnId}_${createdAt}`,
2766
+ conversationId: ctx.conversationId,
2767
+ runId,
2768
+ parentRunId: ctx.input.toolContext?.parentRunId,
2769
+ turnId: ctx.turnId,
2770
+ route: contextBuildResult.tokenEstimate?.route,
2771
+ createdAt,
2772
+ components: keptComponents
2773
+ });
2774
+ }
2411
2775
 
2412
2776
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/buildDecisionStage.ts
2413
2777
  function createBuildDecisionStage(dependencies) {
@@ -2528,7 +2892,7 @@ function createExecuteLlmStage(dependencies) {
2528
2892
  streamEventHandler,
2529
2893
  ctx.signal,
2530
2894
  (fallbackModelId) => {
2531
- ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString(fallbackModelId);
2895
+ ctx.cloudQuotaFallbackAppliedModelId = readNonEmptyString2(fallbackModelId);
2532
2896
  },
2533
2897
  (info) => {
2534
2898
  ctx.modelFallbackAudit = info;
@@ -2572,7 +2936,7 @@ function createPrepareCallStage(dependencies) {
2572
2936
  return {
2573
2937
  id: "prepare_call",
2574
2938
  async run(ctx) {
2575
- const lockedRunModelId = readNonEmptyString(ctx.executorLocal?.runLockedModelId);
2939
+ const lockedRunModelId = readNonEmptyString2(ctx.executorLocal?.runLockedModelId);
2576
2940
  const requestedModelId = lockedRunModelId ?? ctx.request.model_id;
2577
2941
  ctx.modelId = dependencies.modelResolver.resolveModelId(requestedModelId);
2578
2942
  await emitAuditEnvelope(ctx.audit, {
@@ -2638,19 +3002,21 @@ var GraphAgentExecutor = class {
2638
3002
  modelCatalog;
2639
3003
  telemetryPort;
2640
3004
  auditPort;
3005
+ tokenizer;
2641
3006
  stages;
2642
3007
  middlewares;
2643
3008
  constructor(dependencies) {
2644
3009
  this.llmCaller = dependencies.llmCaller;
2645
3010
  this.toolRuntime = dependencies.toolRuntime;
2646
3011
  this.contextBuilder = dependencies.contextBuilder;
2647
- this.cloudQuotaFallbackModelId = readNonEmptyString(dependencies.cloudQuotaFallbackModelId);
3012
+ this.cloudQuotaFallbackModelId = readNonEmptyString2(dependencies.cloudQuotaFallbackModelId);
2648
3013
  this.modelCatalog = dependencies.modelCatalog ?? createEmptyModelCatalog();
2649
3014
  this.modelResolver = dependencies.modelResolver ?? new ModelResolver({
2650
3015
  modelCatalog: this.modelCatalog
2651
3016
  });
2652
3017
  this.telemetryPort = dependencies.telemetryPort ?? noopTelemetry;
2653
3018
  this.auditPort = dependencies.auditPort ?? noopAudit;
3019
+ this.tokenizer = dependencies.tokenizer ?? createDefaultTokenizerPort();
2654
3020
  this.stages = [
2655
3021
  createPrepareCallStage({
2656
3022
  modelResolver: this.modelResolver,
@@ -2692,9 +3058,10 @@ var GraphAgentExecutor = class {
2692
3058
  llmMessages: [],
2693
3059
  mode: input.request.mode === "chat" ? "chat" : "agent",
2694
3060
  conversationId: resolveConversationIdForRuntimeEvents(input.toolContext),
2695
- turnId: readNonEmptyString(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
3061
+ turnId: readNonEmptyString2(input.toolContext?.turnId) ?? `turn_${Date.now()}`,
2696
3062
  telemetry: this.telemetryPort,
2697
- audit: this.auditPort
3063
+ audit: this.auditPort,
3064
+ tokenizer: this.tokenizer
2698
3065
  };
2699
3066
  logger5.info("[GraphAgentExecutor] tick \u8C03\u7528", {
2700
3067
  stream: input.stream === true,
@@ -2742,18 +3109,18 @@ function isSummarizationCallbacks(value) {
2742
3109
  function isGraphSseSink(value) {
2743
3110
  return typeof value === "function";
2744
3111
  }
2745
- function readNonEmptyString2(value) {
3112
+ function readNonEmptyString3(value) {
2746
3113
  if (typeof value !== "string") return void 0;
2747
3114
  const trimmed = value.trim();
2748
3115
  return trimmed.length > 0 ? trimmed : void 0;
2749
3116
  }
2750
3117
  function readGraphAgentLocal(local) {
2751
3118
  const source = local ?? {};
2752
- const answerId = readNonEmptyString2(source.answerId);
3119
+ const answerId = readNonEmptyString3(source.answerId);
2753
3120
  const chunkSeq = Number.isInteger(source.chunkSeq) ? Number(source.chunkSeq) : 0;
2754
3121
  return {
2755
- conversationId: readNonEmptyString2(source.conversationId) ?? "",
2756
- turnId: readNonEmptyString2(source.turnId),
3122
+ conversationId: readNonEmptyString3(source.conversationId) ?? "",
3123
+ turnId: readNonEmptyString3(source.turnId),
2757
3124
  request: isAgentInvocationRequest(source.request) ? source.request : void 0,
2758
3125
  toolContext: isToolExecutionContext(source.toolContext) ? source.toolContext : void 0,
2759
3126
  history: isRuntimeEventArray(source.history) ? source.history : [],
@@ -3518,7 +3885,7 @@ var LlmNode = class {
3518
3885
  function isRecord8(value) {
3519
3886
  return typeof value === "object" && value !== null && !Array.isArray(value);
3520
3887
  }
3521
- function readNonEmptyString3(value) {
3888
+ function readNonEmptyString4(value) {
3522
3889
  if (typeof value !== "string") {
3523
3890
  return void 0;
3524
3891
  }
@@ -3540,7 +3907,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3540
3907
  return void 0;
3541
3908
  }
3542
3909
  if (toolName === "write_report") {
3543
- const report = readNonEmptyString3(data.report);
3910
+ const report = readNonEmptyString4(data.report);
3544
3911
  if (!report) {
3545
3912
  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");
3546
3913
  }
@@ -3550,7 +3917,7 @@ function resolveFinalAnswerFromToolResult(toolName, parsedResult) {
3550
3917
  if (data.success !== true) {
3551
3918
  return void 0;
3552
3919
  }
3553
- const finalAnswer = readNonEmptyString3(data.final_answer);
3920
+ const finalAnswer = readNonEmptyString4(data.final_answer);
3554
3921
  if (!finalAnswer) {
3555
3922
  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");
3556
3923
  }
@@ -3659,11 +4026,11 @@ function buildToolOutputUiMeta(params) {
3659
4026
  }
3660
4027
  async function applyObservationGovernance(params) {
3661
4028
  if (!params.structuredObservation || !isRecord9(params.parsed)) {
3662
- return;
4029
+ return {};
3663
4030
  }
3664
4031
  const policy = resolveToolObservationGovernancePolicy(params.policy);
3665
4032
  if (!policy.enabled) {
3666
- return;
4033
+ return {};
3667
4034
  }
3668
4035
  const truncated = await params.observationPreview.truncateObservation({
3669
4036
  context: params.toolContext,
@@ -3677,13 +4044,37 @@ async function applyObservationGovernance(params) {
3677
4044
  })
3678
4045
  });
3679
4046
  if (!truncated.truncated) {
3680
- return;
4047
+ return {};
3681
4048
  }
3682
4049
  params.parsed["observation"] = truncated.preview;
3683
4050
  const data = params.parsed["data"];
3684
4051
  if (isRecord9(data) && !("tool_output_store" in data)) {
3685
4052
  data["tool_output_store"] = { blob_id: truncated.blob_id };
3686
4053
  }
4054
+ return {
4055
+ observationTruncation: buildObservationTruncationMeta({
4056
+ originalText: params.structuredObservation,
4057
+ previewText: truncated.preview,
4058
+ originalChars: truncated.originalChars,
4059
+ previewChars: truncated.previewChars,
4060
+ originalLines: truncated.originalLines,
4061
+ previewLines: truncated.previewLines
4062
+ })
4063
+ };
4064
+ }
4065
+ function buildObservationTruncationMeta(input) {
4066
+ return {
4067
+ originalChars: input.originalChars ?? input.originalText.length,
4068
+ previewChars: input.previewChars ?? input.previewText.length,
4069
+ originalLines: input.originalLines ?? countLines(input.originalText),
4070
+ previewLines: input.previewLines ?? countLines(input.previewText)
4071
+ };
4072
+ }
4073
+ function countLines(value) {
4074
+ if (value.length === 0) {
4075
+ return 0;
4076
+ }
4077
+ return value.split(/\r\n|\r|\n/).length;
3687
4078
  }
3688
4079
 
3689
4080
  // src/runtime-kernel/graph-engine/nodes/toolNode.protocolFuse.ts
@@ -4559,7 +4950,7 @@ var ToolNode = class {
4559
4950
  parentRunId: context.toolContext.parentRunId
4560
4951
  });
4561
4952
  applyProtocolFuseState(context.local);
4562
- await applyObservationGovernance({
4953
+ const observationGovernance = await applyObservationGovernance({
4563
4954
  parsed: context.parsed,
4564
4955
  toolName: context.toolName,
4565
4956
  toolContext: context.toolContext,
@@ -4586,6 +4977,12 @@ var ToolNode = class {
4586
4977
  runtimeToolOutput,
4587
4978
  execIdempotency: context.exec.idempotency
4588
4979
  });
4980
+ if (runtimeToolOutput && observationGovernance.observationTruncation) {
4981
+ runtimeToolOutput.metadata = {
4982
+ ...runtimeToolOutput.metadata ?? {},
4983
+ observationTruncation: observationGovernance.observationTruncation
4984
+ };
4985
+ }
4589
4986
  const remainingCalls = context.calls.slice(1);
4590
4987
  context.state.local = buildSuccessLocalState({
4591
4988
  local: context.local,
@@ -4884,12 +5281,12 @@ function asRecord(value) {
4884
5281
  }
4885
5282
  return value;
4886
5283
  }
4887
- function summarizeCheckpoint(conversationId, state, savedAt) {
5284
+ function summarizeCheckpoint(checkpointKey, state, savedAt) {
4888
5285
  const local = asRecord(state.local);
4889
5286
  const executorLocal = asRecord(local?.executorLocal);
4890
5287
  const pendingToolCalls = local?.pendingToolCalls;
4891
5288
  return {
4892
- conversationId,
5289
+ checkpointKey,
4893
5290
  schemaVersion: state.schemaVersion ?? 1,
4894
5291
  savedAt,
4895
5292
  currentNode: state.nodeId,
@@ -4908,25 +5305,25 @@ var MemoryCheckpointer = class {
4908
5305
  local: state.local && typeof state.local === "object" && !Array.isArray(state.local) ? { ...state.local } : state.local
4909
5306
  };
4910
5307
  }
4911
- async load(conversationId) {
4912
- const entry = this.store.get(conversationId);
5308
+ async load(checkpointKey) {
5309
+ const entry = this.store.get(checkpointKey);
4913
5310
  return entry ? this.cloneState(entry.state) : null;
4914
5311
  }
4915
- async save(conversationId, state) {
4916
- this.store.set(conversationId, {
5312
+ async save(checkpointKey, state) {
5313
+ this.store.set(checkpointKey, {
4917
5314
  state: this.cloneState(state),
4918
5315
  savedAt: Date.now()
4919
5316
  });
4920
5317
  }
4921
- async clear(conversationId) {
4922
- this.store.delete(conversationId);
5318
+ async clear(checkpointKey) {
5319
+ this.store.delete(checkpointKey);
4923
5320
  }
4924
- async peekMeta(conversationId) {
4925
- const entry = this.store.get(conversationId);
4926
- return entry ? summarizeCheckpoint(conversationId, entry.state, entry.savedAt) : null;
5321
+ async peekMeta(checkpointKey) {
5322
+ const entry = this.store.get(checkpointKey);
5323
+ return entry ? summarizeCheckpoint(checkpointKey, entry.state, entry.savedAt) : null;
4927
5324
  }
4928
5325
  async list(filter = {}) {
4929
- 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);
5326
+ 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);
4930
5327
  if (filter.limit === void 0) {
4931
5328
  return summaries;
4932
5329
  }
@@ -5947,6 +6344,7 @@ async function callLlmStream(params) {
5947
6344
  const streamAnswerId = generateMessageId();
5948
6345
  let streamChunkSeq = 0;
5949
6346
  let capturedUsage = void 0;
6347
+ let capturedCanonicalUsage = void 0;
5950
6348
  const toolAccumulator = new ToolCallStreamAccumulator([
5951
6349
  "markdown_edit",
5952
6350
  "text_to_image",
@@ -6005,6 +6403,10 @@ async function callLlmStream(params) {
6005
6403
  if (typeof chunk !== "object" || chunk === null) {
6006
6404
  return;
6007
6405
  }
6406
+ const parsedCanonicalUsage = CanonicalLlmUsage.safeParse(chunk.canonicalUsage);
6407
+ if (parsedCanonicalUsage.success) {
6408
+ capturedCanonicalUsage = parsedCanonicalUsage.data;
6409
+ }
6008
6410
  if (chunk.content) {
6009
6411
  emitThoughtComplete(thoughtSegmenter.onBoundary());
6010
6412
  fullResponse += chunk.content;
@@ -6089,6 +6491,12 @@ async function callLlmStream(params) {
6089
6491
  const onUsage = (usage2) => {
6090
6492
  capturedUsage = usage2;
6091
6493
  };
6494
+ const onCanonicalUsage = (usage2) => {
6495
+ const parsed = CanonicalLlmUsage.safeParse(usage2);
6496
+ if (parsed.success) {
6497
+ capturedCanonicalUsage = parsed.data;
6498
+ }
6499
+ };
6092
6500
  await aiEngine.chatCompletionStream(
6093
6501
  modelId,
6094
6502
  messages,
@@ -6101,7 +6509,8 @@ async function callLlmStream(params) {
6101
6509
  onError,
6102
6510
  onFinish,
6103
6511
  onThought,
6104
- onUsage
6512
+ onUsage,
6513
+ onCanonicalUsage
6105
6514
  );
6106
6515
  if (streamError) {
6107
6516
  throw streamError;
@@ -6109,12 +6518,13 @@ async function callLlmStream(params) {
6109
6518
  emitThoughtComplete(thoughtSegmenter.finalize());
6110
6519
  const mergedToolCalls = toolAccumulator.getToolCalls();
6111
6520
  assertToolCallsHaveValidJsonArguments(mergedToolCalls);
6112
- if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0) {
6521
+ if (mergedToolCalls.length > 0 || reasoningDetails.length > 0 || capturedUsage !== void 0 || capturedCanonicalUsage !== void 0) {
6113
6522
  return {
6114
6523
  content: fullResponse,
6115
6524
  tool_calls: mergedToolCalls,
6116
6525
  reasoning_details: reasoningDetails.length > 0 ? reasoningDetails : void 0,
6117
- ...capturedUsage !== void 0 ? { usage: capturedUsage } : {}
6526
+ ...capturedUsage !== void 0 ? { usage: capturedUsage } : {},
6527
+ ...capturedCanonicalUsage !== void 0 ? { canonicalUsage: capturedCanonicalUsage } : {}
6118
6528
  };
6119
6529
  }
6120
6530
  return fullResponse;
@@ -6164,6 +6574,10 @@ function tryCloudQuotaFallback({
6164
6574
  }
6165
6575
 
6166
6576
  // src/runtime-kernel/llm/usage-telemetry.ts
6577
+ function parseCanonicalUsage(value) {
6578
+ const parsed = CanonicalLlmUsage.safeParse(value);
6579
+ return parsed.success ? parsed.data : void 0;
6580
+ }
6167
6581
  async function callPlainCompletion(aiEngine, modelId, messages, options = {}, signal) {
6168
6582
  const response = await aiEngine.chatCompletion(modelId, messages, { ...options, signal });
6169
6583
  return normalizeCompletionResponse(response);
@@ -6174,6 +6588,7 @@ function normalizeCompletionResponse(response) {
6174
6588
  }
6175
6589
  if (isRecord17(response)) {
6176
6590
  const usage2 = response["usage"];
6591
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6177
6592
  const parsedToolCalls = toToolCalls(response["tool_calls"]);
6178
6593
  if (parsedToolCalls) {
6179
6594
  const reasoningDetails = Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0;
@@ -6181,7 +6596,8 @@ function normalizeCompletionResponse(response) {
6181
6596
  content: typeof response["content"] === "string" ? response["content"] : "",
6182
6597
  tool_calls: parsedToolCalls,
6183
6598
  reasoning_details: reasoningDetails,
6184
- ...usage2 !== void 0 ? { usage: usage2 } : {}
6599
+ ...usage2 !== void 0 ? { usage: usage2 } : {},
6600
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6185
6601
  };
6186
6602
  }
6187
6603
  }
@@ -6191,10 +6607,12 @@ function normalizeCompletionResponse(response) {
6191
6607
  if (typeof response === "object") {
6192
6608
  if (isRecord17(response) && (response["content"] !== void 0 || response["reasoning_details"] !== void 0)) {
6193
6609
  const usage2 = response["usage"];
6610
+ const canonicalUsage = parseCanonicalUsage(response["canonicalUsage"]);
6194
6611
  return {
6195
6612
  content: typeof response["content"] === "string" ? response["content"] : "",
6196
6613
  reasoning_details: Array.isArray(response["reasoning_details"]) ? response["reasoning_details"] : void 0,
6197
- ...usage2 !== void 0 ? { usage: usage2 } : {}
6614
+ ...usage2 !== void 0 ? { usage: usage2 } : {},
6615
+ ...canonicalUsage !== void 0 ? { canonicalUsage } : {}
6198
6616
  };
6199
6617
  }
6200
6618
  if (isRecord17(response)) {
@@ -6466,7 +6884,7 @@ function cloneRunRecord(record) {
6466
6884
  ...record,
6467
6885
  iterationBudget: record.iterationBudget ? { ...record.iterationBudget } : void 0,
6468
6886
  errorIfAny: record.errorIfAny ? { ...record.errorIfAny } : void 0,
6469
- metadata: record.metadata ? { ...record.metadata } : void 0
6887
+ metadata: record.metadata ? structuredClone(record.metadata) : void 0
6470
6888
  };
6471
6889
  }
6472
6890
  function matchesStatus(candidate, filter) {
@@ -6878,7 +7296,7 @@ function isTerminalStatus(status) {
6878
7296
  return status === "completed" || status === "failed" || status === "cancelled";
6879
7297
  }
6880
7298
  function cloneMetadata(metadata) {
6881
- return metadata ? { ...metadata } : void 0;
7299
+ return metadata ? structuredClone(metadata) : void 0;
6882
7300
  }
6883
7301
  function recordToSnapshot(record) {
6884
7302
  return {
@@ -6965,7 +7383,7 @@ var DefaultRunSupervisor = class {
6965
7383
  startedAt,
6966
7384
  updatedAt: startedAt,
6967
7385
  iterationBudget: spec.iterationBudget ? { ...spec.iterationBudget } : void 0,
6968
- metadata: spec.metadata ? { ...spec.metadata } : void 0
7386
+ metadata: cloneMetadata(spec.metadata)
6969
7387
  };
6970
7388
  await this.registryStore.save(record);
6971
7389
  const handle = new DefaultRunHandle({
@@ -7139,12 +7557,13 @@ var DefaultRunSupervisor = class {
7139
7557
  }
7140
7558
  try {
7141
7559
  await handle.markRunning({ currentNode: "detached" });
7560
+ const registeredRecord = await this.registryStore.load(handle.runId);
7142
7561
  const executorOutcome = await this.executor.execute({
7143
7562
  runId: handle.runId,
7144
- parentRunId: spec.parentRunId,
7145
- conversationId: spec.conversationId,
7146
- agentSpec: spec.agentSpec,
7147
- request: spec.request,
7563
+ parentRunId: handle.parentRunId,
7564
+ conversationId: registeredRecord?.conversationId ?? spec.conversationId,
7565
+ agentSpec: await handle.spec(),
7566
+ request: await handle.request(),
7148
7567
  signal: handle.signal,
7149
7568
  eventBus: spec.eventBus,
7150
7569
  eventStore: spec.eventStore,
@@ -7153,7 +7572,7 @@ var DefaultRunSupervisor = class {
7153
7572
  contextFences: spec.contextFences,
7154
7573
  wakeSource: spec.wakeSource,
7155
7574
  ephemeral: spec.ephemeral,
7156
- metadata: spec.metadata
7575
+ metadata: cloneMetadata(registeredRecord?.metadata ?? spec.metadata)
7157
7576
  });
7158
7577
  const outcome = await this.persistExecutorOutcome(handle, executorOutcome);
7159
7578
  this.notifyTerminalWaiters(outcome);
@@ -7217,10 +7636,14 @@ var DefaultRunSupervisor = class {
7217
7636
  await this.registryStore.save(record);
7218
7637
  }
7219
7638
  const completedAt = executorOutcome?.completedAt ?? this.now();
7639
+ const fallbackMeta = record ? void 0 : await handle.meta();
7220
7640
  const outcome = recordToTerminalOutcome(record ?? {
7221
7641
  runId: handle.runId,
7222
7642
  parentRunId: handle.parentRunId,
7223
- status: executorOutcome?.status ?? "completed"}, completedAt);
7643
+ conversationId: fallbackMeta?.conversationId ?? "",
7644
+ agentSpecId: fallbackMeta?.agentSpecId,
7645
+ status: executorOutcome?.status ?? "completed",
7646
+ startedAt: fallbackMeta?.startedAt ?? completedAt}, completedAt);
7224
7647
  const nextOutcome = {
7225
7648
  ...outcome,
7226
7649
  metadata: {
@@ -7548,6 +7971,7 @@ async function emitRunEvent(event, sink) {
7548
7971
  async function runAgent(agent, options) {
7549
7972
  const modelId = resolveModelId(agent, options);
7550
7973
  const conversationId = options.conversationId ?? `conv_${Date.now()}`;
7974
+ const checkpointKey = conversationId;
7551
7975
  const runId = options.runId ?? generateRunId();
7552
7976
  const turnId = runId;
7553
7977
  const costCollector = new QuickstartRunCostCollector();
@@ -7602,7 +8026,7 @@ async function runAgent(agent, options) {
7602
8026
  };
7603
8027
  await handle.markRunning({ currentNode: "user" });
7604
8028
  try {
7605
- await executor.prime(conversationId, {
8029
+ await executor.prime(checkpointKey, {
7606
8030
  conversationId,
7607
8031
  turnId,
7608
8032
  request: {
@@ -7627,7 +8051,7 @@ async function runAgent(agent, options) {
7627
8051
  return void 0;
7628
8052
  }
7629
8053
  });
7630
- const result = await executor.runUntilYield(conversationId);
8054
+ const result = await executor.runUntilYield(checkpointKey);
7631
8055
  runtimeEvents.push(...result.events);
7632
8056
  for (const event of result.events) {
7633
8057
  if (event.type === "final_answer_chunk") continue;
@@ -7790,7 +8214,7 @@ function createQuickstartTemplateFiles(projectName) {
7790
8214
  start: 'linnkit run hello --input "\u4F60\u597D\uFF0C\u4ECB\u7ECD\u4E00\u4E0B\u4F60\u81EA\u5DF1"'
7791
8215
  },
7792
8216
  dependencies: {
7793
- "@linnlabs/linnkit": "^0.8.0",
8217
+ "@linnlabs/linnkit": "^0.16.0",
7794
8218
  zod: "^3.22.0"
7795
8219
  },
7796
8220
  devDependencies: {}