@linnlabs/linnkit 0.38.0 → 0.39.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 (42) hide show
  1. package/CHANGELOG.md +33 -1
  2. package/dist/cli.cjs +111 -79
  3. package/dist/cli.cjs.map +1 -1
  4. package/dist/cli.js +111 -79
  5. package/dist/cli.js.map +1 -1
  6. package/dist/context-manager.cjs +23 -17
  7. package/dist/context-manager.cjs.map +1 -1
  8. package/dist/context-manager.js +23 -17
  9. package/dist/context-manager.js.map +1 -1
  10. package/dist/contracts/contextPolicy.d.cts +2 -1
  11. package/dist/contracts/contextPolicy.d.ts +2 -1
  12. package/dist/contracts/token-accounting.d.cts +8 -8
  13. package/dist/contracts/token-accounting.d.ts +8 -8
  14. package/dist/contracts.cjs.map +1 -1
  15. package/dist/contracts.js.map +1 -1
  16. package/dist/index.cjs +157 -80
  17. package/dist/index.cjs.map +1 -1
  18. package/dist/index.js +157 -80
  19. package/dist/index.js.map +1 -1
  20. package/dist/quickstart.cjs +111 -79
  21. package/dist/quickstart.cjs.map +1 -1
  22. package/dist/quickstart.js +111 -79
  23. package/dist/quickstart.js.map +1 -1
  24. package/dist/runtime-kernel/events.cjs.map +1 -1
  25. package/dist/runtime-kernel/events.js.map +1 -1
  26. package/dist/runtime-kernel/llm/definitions/llmCallInvocationContext.d.cts +4 -1
  27. package/dist/runtime-kernel/llm/definitions/llmCallInvocationContext.d.ts +4 -1
  28. package/dist/runtime-kernel.cjs +157 -80
  29. package/dist/runtime-kernel.cjs.map +1 -1
  30. package/dist/runtime-kernel.js +157 -80
  31. package/dist/runtime-kernel.js.map +1 -1
  32. package/dist/shared/prompt-budget.d.cts +4 -2
  33. package/dist/shared/prompt-budget.d.ts +4 -2
  34. package/dist/testkit.cjs +157 -80
  35. package/dist/testkit.cjs.map +1 -1
  36. package/dist/testkit.js +157 -80
  37. package/dist/testkit.js.map +1 -1
  38. package/docs/integration/agent-registration-guide.md +1 -1
  39. package/docs/integration/context-engineering.md +12 -8
  40. package/docs/integration/token-management.md +6 -1
  41. package/docs/integration/tools.md +4 -0
  42. package/package.json +2 -2
@@ -5036,6 +5036,88 @@ function evaluatePrimaryPromptCapacity(snapshot) {
5036
5036
  };
5037
5037
  }
5038
5038
 
5039
+ // src/shared/prompt-budget.ts
5040
+ var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
5041
+ var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
5042
+ function resolveEffectivePromptBudget(input) {
5043
+ assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
5044
+ assertOptionalPositiveSafeInteger(
5045
+ input.policyReservedForResponse,
5046
+ "policyReservedForResponse"
5047
+ );
5048
+ assertOptionalPositiveSafeInteger(
5049
+ input.modelContextWindowTokens,
5050
+ "modelContextWindowTokens"
5051
+ );
5052
+ assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
5053
+ assertOptionalPositiveSafeInteger(
5054
+ input.fallbackContextWindowTokens,
5055
+ "fallbackContextWindowTokens"
5056
+ );
5057
+ assertOptionalPositiveSafeInteger(
5058
+ input.fallbackMaxOutputTokens,
5059
+ "fallbackMaxOutputTokens"
5060
+ );
5061
+ assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
5062
+ const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
5063
+ const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
5064
+ const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
5065
+ const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
5066
+ const responseReservationTokens = input.policyReservedForResponse !== void 0 || input.modelContextWindowTokens === void 0 ? outputLimitTokens : 1;
5067
+ const inputBudgetTokens = effectiveWindowTokens - responseReservationTokens;
5068
+ if (inputBudgetTokens < 1) {
5069
+ throw new Error(
5070
+ "\u6709\u6548\u6A21\u578B\u7A97\u53E3\u5FC5\u987B\u5927\u4E8E\u8F93\u51FA\u9884\u7559\uFF0C\u624D\u80FD\u5F62\u6210\u6B63\u6570 Prompt \u8F93\u5165\u9884\u7B97\u3002"
5071
+ );
5072
+ }
5073
+ const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
5074
+ if (messageBudgetTokens < 1) {
5075
+ throw new Error(
5076
+ "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
5077
+ );
5078
+ }
5079
+ return {
5080
+ effectiveWindowTokens,
5081
+ outputLimitTokens,
5082
+ inputBudgetTokens,
5083
+ toolDefinitionTokens: input.toolDefinitionTokens,
5084
+ messageBudgetTokens
5085
+ };
5086
+ }
5087
+ function assertOptionalPositiveSafeInteger(value, field) {
5088
+ if (value !== void 0) {
5089
+ assertPositiveSafeInteger(value, field);
5090
+ }
5091
+ }
5092
+ function assertPositiveSafeInteger(value, field) {
5093
+ if (!Number.isSafeInteger(value) || value < 1) {
5094
+ throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
5095
+ }
5096
+ }
5097
+ function assertNonNegativeSafeInteger(value, field) {
5098
+ if (!Number.isSafeInteger(value) || value < 0) {
5099
+ throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
5100
+ }
5101
+ }
5102
+
5103
+ // src/runtime-kernel/graph-engine/functions/resolveFallbackPromptBudget.ts
5104
+ function resolveFallbackPromptBudget(primaryBudget, requiredOutputLimitTokens, route) {
5105
+ if (!route) throw new Error("Fallback \u6A21\u578B\u7F3A\u5C11\u6B63\u5F0F inference route\u3002");
5106
+ const budget = resolveEffectivePromptBudget({
5107
+ policyMaxTokens: primaryBudget.effectiveWindowTokens,
5108
+ policyReservedForResponse: requiredOutputLimitTokens,
5109
+ modelContextWindowTokens: route.context_window_tokens,
5110
+ modelMaxOutputTokens: route.max_output_tokens,
5111
+ toolDefinitionTokens: primaryBudget.toolDefinitionTokens
5112
+ });
5113
+ const inputBudgetTokens = Math.min(primaryBudget.inputBudgetTokens, budget.inputBudgetTokens);
5114
+ return {
5115
+ ...budget,
5116
+ inputBudgetTokens,
5117
+ messageBudgetTokens: inputBudgetTokens - budget.toolDefinitionTokens
5118
+ };
5119
+ }
5120
+
5039
5121
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/executeLlmStage.ts
5040
5122
  function createExecuteLlmStage(dependencies) {
5041
5123
  return defineTickStage({
@@ -5114,7 +5196,11 @@ function createExecuteLlmStage(dependencies) {
5114
5196
  servedModelId: activeModelId,
5115
5197
  messages,
5116
5198
  llmOptions: ctx.llmOptions,
5117
- promptBudget,
5199
+ promptBudget: activeModelId === ctx.modelId ? promptBudget : resolveFallbackPromptBudget(
5200
+ promptBudget,
5201
+ ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
5202
+ dependencies.modelCatalog.getModelById(activeModelId)?.inference_route
5203
+ ),
5118
5204
  measurementPolicy: promptUsageMeasurementPolicy,
5119
5205
  imageInputTokens: ctx.imageInputAdmissionEvidence?.attachments.reduce(
5120
5206
  (total, attachment) => total + attachment.estimatedTokens,
@@ -5144,7 +5230,7 @@ function createExecuteLlmStage(dependencies) {
5144
5230
  return evaluateFallbackPromptCapacity({
5145
5231
  contextWindowTokens: route?.context_window_tokens,
5146
5232
  maxOutputTokens: route?.max_output_tokens,
5147
- requiredOutputLimitTokens: promptBudget.outputLimitTokens,
5233
+ requiredOutputLimitTokens: ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
5148
5234
  estimatedPromptTokens: weights.systemPromptTokens + weights.conversationTokens + weights.toolDefinitionTokens
5149
5235
  });
5150
5236
  }
@@ -5432,7 +5518,7 @@ async function executeContextCompaction(dependencies, input) {
5432
5518
  response = await dependencies.llmCaller.call(
5433
5519
  input.modelId,
5434
5520
  messages,
5435
- compactionOptions,
5521
+ { ...compactionOptions, max_tokens: compactionPromptUsage.output_limit_tokens },
5436
5522
  input.signal,
5437
5523
  { imageInputAdmissionEvidence: input.imageInputAdmissionEvidence }
5438
5524
  );
@@ -5495,7 +5581,7 @@ async function executeContextCompaction(dependencies, input) {
5495
5581
  conversationId: input.conversationId,
5496
5582
  turnId: input.turnId,
5497
5583
  timestamp: Date.now(),
5498
- maxOutputTokens
5584
+ maxOutputTokens: compactionPromptUsage.output_limit_tokens
5499
5585
  });
5500
5586
  } catch (error) {
5501
5587
  if (error instanceof Error && error.name === "AbortError") throw error;
@@ -5680,14 +5766,11 @@ function buildCompactionLlmOptions(input) {
5680
5766
  };
5681
5767
  }
5682
5768
  function buildCompactionPromptBudget(mainBudget, maxOutputTokens) {
5683
- const inputBudgetTokens = mainBudget.effectiveWindowTokens - maxOutputTokens;
5684
- return {
5685
- effectiveWindowTokens: mainBudget.effectiveWindowTokens,
5686
- outputLimitTokens: maxOutputTokens,
5687
- inputBudgetTokens,
5688
- toolDefinitionTokens: mainBudget.toolDefinitionTokens,
5689
- messageBudgetTokens: inputBudgetTokens - mainBudget.toolDefinitionTokens
5690
- };
5769
+ return resolveEffectivePromptBudget({
5770
+ modelContextWindowTokens: mainBudget.effectiveWindowTokens,
5771
+ modelMaxOutputTokens: maxOutputTokens,
5772
+ toolDefinitionTokens: mainBudget.toolDefinitionTokens
5773
+ });
5691
5774
  }
5692
5775
 
5693
5776
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/compactContextStage.ts
@@ -6264,6 +6347,10 @@ function createPromptUsageMeasurer(dependencies) {
6264
6347
  });
6265
6348
  const usedTokens = remoteResult?.inputTokens ?? calibratedLocalTotal;
6266
6349
  const components = normalizePromptUsageComponents(usedTokens, weights);
6350
+ const outputLimitTokens = usedTokens <= input.promptBudget.inputBudgetTokens ? Math.min(
6351
+ input.promptBudget.outputLimitTokens,
6352
+ input.promptBudget.effectiveWindowTokens - usedTokens
6353
+ ) : input.promptBudget.outputLimitTokens;
6267
6354
  return ContextUsageSnapshot.parse({
6268
6355
  basis: "last_completed_llm_prompt",
6269
6356
  budget_model_id: input.budgetModelId,
@@ -6273,7 +6360,7 @@ function createPromptUsageMeasurer(dependencies) {
6273
6360
  component_attribution: "normalized_local_estimate",
6274
6361
  input_budget_tokens: input.promptBudget.inputBudgetTokens,
6275
6362
  remaining_tokens: input.promptBudget.inputBudgetTokens - usedTokens,
6276
- output_limit_tokens: input.promptBudget.outputLimitTokens,
6363
+ output_limit_tokens: outputLimitTokens,
6277
6364
  source: remoteResult?.source ?? "local-estimate",
6278
6365
  confidence: remoteResult?.confidence ?? "estimate",
6279
6366
  measured_at: now()
@@ -9762,69 +9849,6 @@ function createHostToolCallBootstrap(input) {
9762
9849
  }
9763
9850
  };
9764
9851
  }
9765
-
9766
- // src/shared/prompt-budget.ts
9767
- var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
9768
- var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
9769
- function resolveEffectivePromptBudget(input) {
9770
- assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
9771
- assertOptionalPositiveSafeInteger(
9772
- input.policyReservedForResponse,
9773
- "policyReservedForResponse"
9774
- );
9775
- assertOptionalPositiveSafeInteger(
9776
- input.modelContextWindowTokens,
9777
- "modelContextWindowTokens"
9778
- );
9779
- assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
9780
- assertOptionalPositiveSafeInteger(
9781
- input.fallbackContextWindowTokens,
9782
- "fallbackContextWindowTokens"
9783
- );
9784
- assertOptionalPositiveSafeInteger(
9785
- input.fallbackMaxOutputTokens,
9786
- "fallbackMaxOutputTokens"
9787
- );
9788
- assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
9789
- const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
9790
- const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
9791
- const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
9792
- const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
9793
- const inputBudgetTokens = effectiveWindowTokens - outputLimitTokens;
9794
- if (inputBudgetTokens < 1) {
9795
- throw new Error(
9796
- "\u6709\u6548\u6A21\u578B\u7A97\u53E3\u5FC5\u987B\u5927\u4E8E\u8F93\u51FA\u9884\u7559\uFF0C\u624D\u80FD\u5F62\u6210\u6B63\u6570 Prompt \u8F93\u5165\u9884\u7B97\u3002"
9797
- );
9798
- }
9799
- const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
9800
- if (messageBudgetTokens < 1) {
9801
- throw new Error(
9802
- "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
9803
- );
9804
- }
9805
- return {
9806
- effectiveWindowTokens,
9807
- outputLimitTokens,
9808
- inputBudgetTokens,
9809
- toolDefinitionTokens: input.toolDefinitionTokens,
9810
- messageBudgetTokens
9811
- };
9812
- }
9813
- function assertOptionalPositiveSafeInteger(value, field) {
9814
- if (value !== void 0) {
9815
- assertPositiveSafeInteger(value, field);
9816
- }
9817
- }
9818
- function assertPositiveSafeInteger(value, field) {
9819
- if (!Number.isSafeInteger(value) || value < 1) {
9820
- throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
9821
- }
9822
- }
9823
- function assertNonNegativeSafeInteger(value, field) {
9824
- if (!Number.isSafeInteger(value) || value < 0) {
9825
- throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
9826
- }
9827
- }
9828
9852
  var counter = z.number().int().nonnegative();
9829
9853
  var executor = z.object({
9830
9854
  stepCount: counter,
@@ -9917,6 +9941,51 @@ __export(tools_exports, {
9917
9941
  stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
9918
9942
  });
9919
9943
 
9944
+ // src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
9945
+ function spellingDistance(left, right) {
9946
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
9947
+ for (let row = 1; row <= left.length; row += 1) {
9948
+ const current = [row];
9949
+ for (let column = 1; column <= right.length; column += 1) {
9950
+ current[column] = Math.min(
9951
+ current[column - 1] + 1,
9952
+ previous[column] + 1,
9953
+ previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
9954
+ );
9955
+ }
9956
+ previous = current;
9957
+ }
9958
+ return previous[right.length];
9959
+ }
9960
+ function nearestField(field, allowedFields) {
9961
+ const threshold = field.length < 5 ? 1 : 2;
9962
+ let nearest;
9963
+ let bestDistance = threshold + 1;
9964
+ for (const candidate of allowedFields) {
9965
+ if (Math.abs(field.length - candidate.length) > threshold) continue;
9966
+ const distance = spellingDistance(field, candidate);
9967
+ if (distance < bestDistance) {
9968
+ bestDistance = distance;
9969
+ nearest = candidate;
9970
+ } else if (distance === bestDistance) {
9971
+ nearest = void 0;
9972
+ }
9973
+ }
9974
+ return bestDistance <= threshold ? nearest : void 0;
9975
+ }
9976
+ function formatUnknownToolArguments(fields, allowedFields) {
9977
+ const suggestions = fields.flatMap((field) => {
9978
+ const candidate = nearestField(field, allowedFields);
9979
+ return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
9980
+ });
9981
+ return [
9982
+ `Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
9983
+ `Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
9984
+ ...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
9985
+ "Remove unsupported parameters before retrying; no arguments were changed or executed."
9986
+ ].join(" ");
9987
+ }
9988
+
9920
9989
  // src/runtime-kernel/tools/toolContracts.ts
9921
9990
  var BaseTool = class {
9922
9991
  idempotency;
@@ -9952,7 +10021,7 @@ var BaseTool = class {
9952
10021
  if (unknownFields.length > 0) {
9953
10022
  return {
9954
10023
  success: false,
9955
- error: `Additional properties not allowed: ${unknownFields.join(", ")}`
10024
+ error: formatUnknownToolArguments(unknownFields, [...allowed])
9956
10025
  };
9957
10026
  }
9958
10027
  }
@@ -11672,7 +11741,15 @@ async function callWithRetryFallback(params) {
11672
11741
  eventHandler,
11673
11742
  requirement
11674
11743
  });
11675
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11744
+ const measuredContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11745
+ const attemptContextUsage = measuredContextUsage ? {
11746
+ ...measuredContextUsage,
11747
+ output_limit_tokens: Math.min(
11748
+ measuredContextUsage.output_limit_tokens,
11749
+ options.max_tokens ?? measuredContextUsage.output_limit_tokens
11750
+ )
11751
+ } : void 0;
11752
+ const attemptOptions = attemptContextUsage ? { ...options, max_tokens: attemptContextUsage.output_limit_tokens } : options;
11676
11753
  const isRetry = attempt > 0;
11677
11754
  let pendingErrorEvent = null;
11678
11755
  let streamedErrorClassification;
@@ -11689,7 +11766,7 @@ async function callWithRetryFallback(params) {
11689
11766
  inferencePort: deps.inferencePort,
11690
11767
  modelId: activeModelId,
11691
11768
  messages: resolvedMessages,
11692
- options,
11769
+ options: attemptOptions,
11693
11770
  eventHandler: attemptTracker.handle,
11694
11771
  onErrorClassification(classification) {
11695
11772
  streamedErrorClassification = classification;
@@ -11701,7 +11778,7 @@ async function callWithRetryFallback(params) {
11701
11778
  deps.inferencePort,
11702
11779
  activeModelId,
11703
11780
  resolvedMessages,
11704
- options,
11781
+ attemptOptions,
11705
11782
  signal,
11706
11783
  traceId
11707
11784
  );