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