@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
package/dist/index.js CHANGED
@@ -6059,6 +6059,88 @@ function evaluatePrimaryPromptCapacity(snapshot) {
6059
6059
  };
6060
6060
  }
6061
6061
 
6062
+ // src/shared/prompt-budget.ts
6063
+ var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
6064
+ var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
6065
+ function resolveEffectivePromptBudget(input) {
6066
+ assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
6067
+ assertOptionalPositiveSafeInteger(
6068
+ input.policyReservedForResponse,
6069
+ "policyReservedForResponse"
6070
+ );
6071
+ assertOptionalPositiveSafeInteger(
6072
+ input.modelContextWindowTokens,
6073
+ "modelContextWindowTokens"
6074
+ );
6075
+ assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
6076
+ assertOptionalPositiveSafeInteger(
6077
+ input.fallbackContextWindowTokens,
6078
+ "fallbackContextWindowTokens"
6079
+ );
6080
+ assertOptionalPositiveSafeInteger(
6081
+ input.fallbackMaxOutputTokens,
6082
+ "fallbackMaxOutputTokens"
6083
+ );
6084
+ assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
6085
+ const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
6086
+ const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
6087
+ const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
6088
+ const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
6089
+ const responseReservationTokens = input.policyReservedForResponse !== void 0 || input.modelContextWindowTokens === void 0 ? outputLimitTokens : 1;
6090
+ const inputBudgetTokens = effectiveWindowTokens - responseReservationTokens;
6091
+ if (inputBudgetTokens < 1) {
6092
+ throw new Error(
6093
+ "\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"
6094
+ );
6095
+ }
6096
+ const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
6097
+ if (messageBudgetTokens < 1) {
6098
+ throw new Error(
6099
+ "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
6100
+ );
6101
+ }
6102
+ return {
6103
+ effectiveWindowTokens,
6104
+ outputLimitTokens,
6105
+ inputBudgetTokens,
6106
+ toolDefinitionTokens: input.toolDefinitionTokens,
6107
+ messageBudgetTokens
6108
+ };
6109
+ }
6110
+ function assertOptionalPositiveSafeInteger(value, field) {
6111
+ if (value !== void 0) {
6112
+ assertPositiveSafeInteger(value, field);
6113
+ }
6114
+ }
6115
+ function assertPositiveSafeInteger(value, field) {
6116
+ if (!Number.isSafeInteger(value) || value < 1) {
6117
+ throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
6118
+ }
6119
+ }
6120
+ function assertNonNegativeSafeInteger(value, field) {
6121
+ if (!Number.isSafeInteger(value) || value < 0) {
6122
+ throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
6123
+ }
6124
+ }
6125
+
6126
+ // src/runtime-kernel/graph-engine/functions/resolveFallbackPromptBudget.ts
6127
+ function resolveFallbackPromptBudget(primaryBudget, requiredOutputLimitTokens, route) {
6128
+ if (!route) throw new Error("Fallback \u6A21\u578B\u7F3A\u5C11\u6B63\u5F0F inference route\u3002");
6129
+ const budget = resolveEffectivePromptBudget({
6130
+ policyMaxTokens: primaryBudget.effectiveWindowTokens,
6131
+ policyReservedForResponse: requiredOutputLimitTokens,
6132
+ modelContextWindowTokens: route.context_window_tokens,
6133
+ modelMaxOutputTokens: route.max_output_tokens,
6134
+ toolDefinitionTokens: primaryBudget.toolDefinitionTokens
6135
+ });
6136
+ const inputBudgetTokens = Math.min(primaryBudget.inputBudgetTokens, budget.inputBudgetTokens);
6137
+ return {
6138
+ ...budget,
6139
+ inputBudgetTokens,
6140
+ messageBudgetTokens: inputBudgetTokens - budget.toolDefinitionTokens
6141
+ };
6142
+ }
6143
+
6062
6144
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/executeLlmStage.ts
6063
6145
  function createExecuteLlmStage(dependencies) {
6064
6146
  return defineTickStage({
@@ -6137,7 +6219,11 @@ function createExecuteLlmStage(dependencies) {
6137
6219
  servedModelId: activeModelId,
6138
6220
  messages,
6139
6221
  llmOptions: ctx.llmOptions,
6140
- promptBudget,
6222
+ promptBudget: activeModelId === ctx.modelId ? promptBudget : resolveFallbackPromptBudget(
6223
+ promptBudget,
6224
+ ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
6225
+ dependencies.modelCatalog.getModelById(activeModelId)?.inference_route
6226
+ ),
6141
6227
  measurementPolicy: promptUsageMeasurementPolicy,
6142
6228
  imageInputTokens: ctx.imageInputAdmissionEvidence?.attachments.reduce(
6143
6229
  (total, attachment) => total + attachment.estimatedTokens,
@@ -6167,7 +6253,7 @@ function createExecuteLlmStage(dependencies) {
6167
6253
  return evaluateFallbackPromptCapacity({
6168
6254
  contextWindowTokens: route?.context_window_tokens,
6169
6255
  maxOutputTokens: route?.max_output_tokens,
6170
- requiredOutputLimitTokens: promptBudget.outputLimitTokens,
6256
+ requiredOutputLimitTokens: ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
6171
6257
  estimatedPromptTokens: weights.systemPromptTokens + weights.conversationTokens + weights.toolDefinitionTokens
6172
6258
  });
6173
6259
  }
@@ -6455,7 +6541,7 @@ async function executeContextCompaction(dependencies, input) {
6455
6541
  response = await dependencies.llmCaller.call(
6456
6542
  input.modelId,
6457
6543
  messages,
6458
- compactionOptions,
6544
+ { ...compactionOptions, max_tokens: compactionPromptUsage.output_limit_tokens },
6459
6545
  input.signal,
6460
6546
  { imageInputAdmissionEvidence: input.imageInputAdmissionEvidence }
6461
6547
  );
@@ -6518,7 +6604,7 @@ async function executeContextCompaction(dependencies, input) {
6518
6604
  conversationId: input.conversationId,
6519
6605
  turnId: input.turnId,
6520
6606
  timestamp: Date.now(),
6521
- maxOutputTokens
6607
+ maxOutputTokens: compactionPromptUsage.output_limit_tokens
6522
6608
  });
6523
6609
  } catch (error) {
6524
6610
  if (error instanceof Error && error.name === "AbortError") throw error;
@@ -6703,14 +6789,11 @@ function buildCompactionLlmOptions(input) {
6703
6789
  };
6704
6790
  }
6705
6791
  function buildCompactionPromptBudget(mainBudget, maxOutputTokens) {
6706
- const inputBudgetTokens = mainBudget.effectiveWindowTokens - maxOutputTokens;
6707
- return {
6708
- effectiveWindowTokens: mainBudget.effectiveWindowTokens,
6709
- outputLimitTokens: maxOutputTokens,
6710
- inputBudgetTokens,
6711
- toolDefinitionTokens: mainBudget.toolDefinitionTokens,
6712
- messageBudgetTokens: inputBudgetTokens - mainBudget.toolDefinitionTokens
6713
- };
6792
+ return resolveEffectivePromptBudget({
6793
+ modelContextWindowTokens: mainBudget.effectiveWindowTokens,
6794
+ modelMaxOutputTokens: maxOutputTokens,
6795
+ toolDefinitionTokens: mainBudget.toolDefinitionTokens
6796
+ });
6714
6797
  }
6715
6798
 
6716
6799
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/compactContextStage.ts
@@ -7287,6 +7370,10 @@ function createPromptUsageMeasurer(dependencies) {
7287
7370
  });
7288
7371
  const usedTokens = remoteResult?.inputTokens ?? calibratedLocalTotal;
7289
7372
  const components = normalizePromptUsageComponents(usedTokens, weights);
7373
+ const outputLimitTokens = usedTokens <= input.promptBudget.inputBudgetTokens ? Math.min(
7374
+ input.promptBudget.outputLimitTokens,
7375
+ input.promptBudget.effectiveWindowTokens - usedTokens
7376
+ ) : input.promptBudget.outputLimitTokens;
7290
7377
  return ContextUsageSnapshot.parse({
7291
7378
  basis: "last_completed_llm_prompt",
7292
7379
  budget_model_id: input.budgetModelId,
@@ -7296,7 +7383,7 @@ function createPromptUsageMeasurer(dependencies) {
7296
7383
  component_attribution: "normalized_local_estimate",
7297
7384
  input_budget_tokens: input.promptBudget.inputBudgetTokens,
7298
7385
  remaining_tokens: input.promptBudget.inputBudgetTokens - usedTokens,
7299
- output_limit_tokens: input.promptBudget.outputLimitTokens,
7386
+ output_limit_tokens: outputLimitTokens,
7300
7387
  source: remoteResult?.source ?? "local-estimate",
7301
7388
  confidence: remoteResult?.confidence ?? "estimate",
7302
7389
  measured_at: now()
@@ -10792,69 +10879,6 @@ function createHostToolCallBootstrap(input) {
10792
10879
  }
10793
10880
  };
10794
10881
  }
10795
-
10796
- // src/shared/prompt-budget.ts
10797
- var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
10798
- var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
10799
- function resolveEffectivePromptBudget(input) {
10800
- assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
10801
- assertOptionalPositiveSafeInteger(
10802
- input.policyReservedForResponse,
10803
- "policyReservedForResponse"
10804
- );
10805
- assertOptionalPositiveSafeInteger(
10806
- input.modelContextWindowTokens,
10807
- "modelContextWindowTokens"
10808
- );
10809
- assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
10810
- assertOptionalPositiveSafeInteger(
10811
- input.fallbackContextWindowTokens,
10812
- "fallbackContextWindowTokens"
10813
- );
10814
- assertOptionalPositiveSafeInteger(
10815
- input.fallbackMaxOutputTokens,
10816
- "fallbackMaxOutputTokens"
10817
- );
10818
- assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
10819
- const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
10820
- const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
10821
- const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
10822
- const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
10823
- const inputBudgetTokens = effectiveWindowTokens - outputLimitTokens;
10824
- if (inputBudgetTokens < 1) {
10825
- throw new Error(
10826
- "\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"
10827
- );
10828
- }
10829
- const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
10830
- if (messageBudgetTokens < 1) {
10831
- throw new Error(
10832
- "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
10833
- );
10834
- }
10835
- return {
10836
- effectiveWindowTokens,
10837
- outputLimitTokens,
10838
- inputBudgetTokens,
10839
- toolDefinitionTokens: input.toolDefinitionTokens,
10840
- messageBudgetTokens
10841
- };
10842
- }
10843
- function assertOptionalPositiveSafeInteger(value, field) {
10844
- if (value !== void 0) {
10845
- assertPositiveSafeInteger(value, field);
10846
- }
10847
- }
10848
- function assertPositiveSafeInteger(value, field) {
10849
- if (!Number.isSafeInteger(value) || value < 1) {
10850
- throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
10851
- }
10852
- }
10853
- function assertNonNegativeSafeInteger(value, field) {
10854
- if (!Number.isSafeInteger(value) || value < 0) {
10855
- throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
10856
- }
10857
- }
10858
10882
  var counter = z.number().int().nonnegative();
10859
10883
  var executor = z.object({
10860
10884
  stepCount: counter,
@@ -10947,6 +10971,51 @@ __export(tools_exports, {
10947
10971
  stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
10948
10972
  });
10949
10973
 
10974
+ // src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
10975
+ function spellingDistance(left, right) {
10976
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
10977
+ for (let row = 1; row <= left.length; row += 1) {
10978
+ const current = [row];
10979
+ for (let column = 1; column <= right.length; column += 1) {
10980
+ current[column] = Math.min(
10981
+ current[column - 1] + 1,
10982
+ previous[column] + 1,
10983
+ previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
10984
+ );
10985
+ }
10986
+ previous = current;
10987
+ }
10988
+ return previous[right.length];
10989
+ }
10990
+ function nearestField(field, allowedFields) {
10991
+ const threshold = field.length < 5 ? 1 : 2;
10992
+ let nearest;
10993
+ let bestDistance = threshold + 1;
10994
+ for (const candidate of allowedFields) {
10995
+ if (Math.abs(field.length - candidate.length) > threshold) continue;
10996
+ const distance = spellingDistance(field, candidate);
10997
+ if (distance < bestDistance) {
10998
+ bestDistance = distance;
10999
+ nearest = candidate;
11000
+ } else if (distance === bestDistance) {
11001
+ nearest = void 0;
11002
+ }
11003
+ }
11004
+ return bestDistance <= threshold ? nearest : void 0;
11005
+ }
11006
+ function formatUnknownToolArguments(fields, allowedFields) {
11007
+ const suggestions = fields.flatMap((field) => {
11008
+ const candidate = nearestField(field, allowedFields);
11009
+ return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
11010
+ });
11011
+ return [
11012
+ `Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
11013
+ `Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
11014
+ ...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
11015
+ "Remove unsupported parameters before retrying; no arguments were changed or executed."
11016
+ ].join(" ");
11017
+ }
11018
+
10950
11019
  // src/runtime-kernel/tools/toolContracts.ts
10951
11020
  var BaseTool = class {
10952
11021
  idempotency;
@@ -10982,7 +11051,7 @@ var BaseTool = class {
10982
11051
  if (unknownFields.length > 0) {
10983
11052
  return {
10984
11053
  success: false,
10985
- error: `Additional properties not allowed: ${unknownFields.join(", ")}`
11054
+ error: formatUnknownToolArguments(unknownFields, [...allowed])
10986
11055
  };
10987
11056
  }
10988
11057
  }
@@ -12702,7 +12771,15 @@ async function callWithRetryFallback(params) {
12702
12771
  eventHandler,
12703
12772
  requirement
12704
12773
  });
12705
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
12774
+ const measuredContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
12775
+ const attemptContextUsage = measuredContextUsage ? {
12776
+ ...measuredContextUsage,
12777
+ output_limit_tokens: Math.min(
12778
+ measuredContextUsage.output_limit_tokens,
12779
+ options.max_tokens ?? measuredContextUsage.output_limit_tokens
12780
+ )
12781
+ } : void 0;
12782
+ const attemptOptions = attemptContextUsage ? { ...options, max_tokens: attemptContextUsage.output_limit_tokens } : options;
12706
12783
  const isRetry = attempt > 0;
12707
12784
  let pendingErrorEvent = null;
12708
12785
  let streamedErrorClassification;
@@ -12719,7 +12796,7 @@ async function callWithRetryFallback(params) {
12719
12796
  inferencePort: deps.inferencePort,
12720
12797
  modelId: activeModelId,
12721
12798
  messages: resolvedMessages,
12722
- options,
12799
+ options: attemptOptions,
12723
12800
  eventHandler: attemptTracker.handle,
12724
12801
  onErrorClassification(classification) {
12725
12802
  streamedErrorClassification = classification;
@@ -12731,7 +12808,7 @@ async function callWithRetryFallback(params) {
12731
12808
  deps.inferencePort,
12732
12809
  activeModelId,
12733
12810
  resolvedMessages,
12734
- options,
12811
+ attemptOptions,
12735
12812
  signal,
12736
12813
  traceId
12737
12814
  );