@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/testkit.js CHANGED
@@ -5224,6 +5224,88 @@ function evaluatePrimaryPromptCapacity(snapshot) {
5224
5224
  };
5225
5225
  }
5226
5226
 
5227
+ // src/shared/prompt-budget.ts
5228
+ var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
5229
+ var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
5230
+ function resolveEffectivePromptBudget(input) {
5231
+ assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
5232
+ assertOptionalPositiveSafeInteger(
5233
+ input.policyReservedForResponse,
5234
+ "policyReservedForResponse"
5235
+ );
5236
+ assertOptionalPositiveSafeInteger(
5237
+ input.modelContextWindowTokens,
5238
+ "modelContextWindowTokens"
5239
+ );
5240
+ assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
5241
+ assertOptionalPositiveSafeInteger(
5242
+ input.fallbackContextWindowTokens,
5243
+ "fallbackContextWindowTokens"
5244
+ );
5245
+ assertOptionalPositiveSafeInteger(
5246
+ input.fallbackMaxOutputTokens,
5247
+ "fallbackMaxOutputTokens"
5248
+ );
5249
+ assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
5250
+ const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
5251
+ const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
5252
+ const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
5253
+ const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
5254
+ const responseReservationTokens = input.policyReservedForResponse !== void 0 || input.modelContextWindowTokens === void 0 ? outputLimitTokens : 1;
5255
+ const inputBudgetTokens = effectiveWindowTokens - responseReservationTokens;
5256
+ if (inputBudgetTokens < 1) {
5257
+ throw new Error(
5258
+ "\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"
5259
+ );
5260
+ }
5261
+ const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
5262
+ if (messageBudgetTokens < 1) {
5263
+ throw new Error(
5264
+ "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
5265
+ );
5266
+ }
5267
+ return {
5268
+ effectiveWindowTokens,
5269
+ outputLimitTokens,
5270
+ inputBudgetTokens,
5271
+ toolDefinitionTokens: input.toolDefinitionTokens,
5272
+ messageBudgetTokens
5273
+ };
5274
+ }
5275
+ function assertOptionalPositiveSafeInteger(value, field) {
5276
+ if (value !== void 0) {
5277
+ assertPositiveSafeInteger(value, field);
5278
+ }
5279
+ }
5280
+ function assertPositiveSafeInteger(value, field) {
5281
+ if (!Number.isSafeInteger(value) || value < 1) {
5282
+ throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
5283
+ }
5284
+ }
5285
+ function assertNonNegativeSafeInteger(value, field) {
5286
+ if (!Number.isSafeInteger(value) || value < 0) {
5287
+ throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
5288
+ }
5289
+ }
5290
+
5291
+ // src/runtime-kernel/graph-engine/functions/resolveFallbackPromptBudget.ts
5292
+ function resolveFallbackPromptBudget(primaryBudget, requiredOutputLimitTokens, route) {
5293
+ if (!route) throw new Error("Fallback \u6A21\u578B\u7F3A\u5C11\u6B63\u5F0F inference route\u3002");
5294
+ const budget = resolveEffectivePromptBudget({
5295
+ policyMaxTokens: primaryBudget.effectiveWindowTokens,
5296
+ policyReservedForResponse: requiredOutputLimitTokens,
5297
+ modelContextWindowTokens: route.context_window_tokens,
5298
+ modelMaxOutputTokens: route.max_output_tokens,
5299
+ toolDefinitionTokens: primaryBudget.toolDefinitionTokens
5300
+ });
5301
+ const inputBudgetTokens = Math.min(primaryBudget.inputBudgetTokens, budget.inputBudgetTokens);
5302
+ return {
5303
+ ...budget,
5304
+ inputBudgetTokens,
5305
+ messageBudgetTokens: inputBudgetTokens - budget.toolDefinitionTokens
5306
+ };
5307
+ }
5308
+
5227
5309
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/executeLlmStage.ts
5228
5310
  function createExecuteLlmStage(dependencies) {
5229
5311
  return defineTickStage({
@@ -5302,7 +5384,11 @@ function createExecuteLlmStage(dependencies) {
5302
5384
  servedModelId: activeModelId,
5303
5385
  messages,
5304
5386
  llmOptions: ctx.llmOptions,
5305
- promptBudget,
5387
+ promptBudget: activeModelId === ctx.modelId ? promptBudget : resolveFallbackPromptBudget(
5388
+ promptBudget,
5389
+ ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
5390
+ dependencies.modelCatalog.getModelById(activeModelId)?.inference_route
5391
+ ),
5306
5392
  measurementPolicy: promptUsageMeasurementPolicy,
5307
5393
  imageInputTokens: ctx.imageInputAdmissionEvidence?.attachments.reduce(
5308
5394
  (total, attachment) => total + attachment.estimatedTokens,
@@ -5332,7 +5418,7 @@ function createExecuteLlmStage(dependencies) {
5332
5418
  return evaluateFallbackPromptCapacity({
5333
5419
  contextWindowTokens: route?.context_window_tokens,
5334
5420
  maxOutputTokens: route?.max_output_tokens,
5335
- requiredOutputLimitTokens: promptBudget.outputLimitTokens,
5421
+ requiredOutputLimitTokens: ctx.promptUsageCandidate?.output_limit_tokens ?? promptBudget.outputLimitTokens,
5336
5422
  estimatedPromptTokens: weights.systemPromptTokens + weights.conversationTokens + weights.toolDefinitionTokens
5337
5423
  });
5338
5424
  }
@@ -5620,7 +5706,7 @@ async function executeContextCompaction(dependencies, input) {
5620
5706
  response = await dependencies.llmCaller.call(
5621
5707
  input.modelId,
5622
5708
  messages,
5623
- compactionOptions,
5709
+ { ...compactionOptions, max_tokens: compactionPromptUsage.output_limit_tokens },
5624
5710
  input.signal,
5625
5711
  { imageInputAdmissionEvidence: input.imageInputAdmissionEvidence }
5626
5712
  );
@@ -5683,7 +5769,7 @@ async function executeContextCompaction(dependencies, input) {
5683
5769
  conversationId: input.conversationId,
5684
5770
  turnId: input.turnId,
5685
5771
  timestamp: Date.now(),
5686
- maxOutputTokens
5772
+ maxOutputTokens: compactionPromptUsage.output_limit_tokens
5687
5773
  });
5688
5774
  } catch (error) {
5689
5775
  if (error instanceof Error && error.name === "AbortError") throw error;
@@ -5868,14 +5954,11 @@ function buildCompactionLlmOptions(input) {
5868
5954
  };
5869
5955
  }
5870
5956
  function buildCompactionPromptBudget(mainBudget, maxOutputTokens) {
5871
- const inputBudgetTokens = mainBudget.effectiveWindowTokens - maxOutputTokens;
5872
- return {
5873
- effectiveWindowTokens: mainBudget.effectiveWindowTokens,
5874
- outputLimitTokens: maxOutputTokens,
5875
- inputBudgetTokens,
5876
- toolDefinitionTokens: mainBudget.toolDefinitionTokens,
5877
- messageBudgetTokens: inputBudgetTokens - mainBudget.toolDefinitionTokens
5878
- };
5957
+ return resolveEffectivePromptBudget({
5958
+ modelContextWindowTokens: mainBudget.effectiveWindowTokens,
5959
+ modelMaxOutputTokens: maxOutputTokens,
5960
+ toolDefinitionTokens: mainBudget.toolDefinitionTokens
5961
+ });
5879
5962
  }
5880
5963
 
5881
5964
  // src/runtime-kernel/graph-engine/tick-pipeline/stages/compactContextStage.ts
@@ -6452,6 +6535,10 @@ function createPromptUsageMeasurer(dependencies) {
6452
6535
  });
6453
6536
  const usedTokens = remoteResult?.inputTokens ?? calibratedLocalTotal;
6454
6537
  const components = normalizePromptUsageComponents(usedTokens, weights);
6538
+ const outputLimitTokens = usedTokens <= input.promptBudget.inputBudgetTokens ? Math.min(
6539
+ input.promptBudget.outputLimitTokens,
6540
+ input.promptBudget.effectiveWindowTokens - usedTokens
6541
+ ) : input.promptBudget.outputLimitTokens;
6455
6542
  return ContextUsageSnapshot.parse({
6456
6543
  basis: "last_completed_llm_prompt",
6457
6544
  budget_model_id: input.budgetModelId,
@@ -6461,7 +6548,7 @@ function createPromptUsageMeasurer(dependencies) {
6461
6548
  component_attribution: "normalized_local_estimate",
6462
6549
  input_budget_tokens: input.promptBudget.inputBudgetTokens,
6463
6550
  remaining_tokens: input.promptBudget.inputBudgetTokens - usedTokens,
6464
- output_limit_tokens: input.promptBudget.outputLimitTokens,
6551
+ output_limit_tokens: outputLimitTokens,
6465
6552
  source: remoteResult?.source ?? "local-estimate",
6466
6553
  confidence: remoteResult?.confidence ?? "estimate",
6467
6554
  measured_at: now()
@@ -9950,69 +10037,6 @@ function createHostToolCallBootstrap(input) {
9950
10037
  }
9951
10038
  };
9952
10039
  }
9953
-
9954
- // src/shared/prompt-budget.ts
9955
- var DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS = 256e3;
9956
- var DEFAULT_PROMPT_MAX_OUTPUT_TOKENS = 16384;
9957
- function resolveEffectivePromptBudget(input) {
9958
- assertOptionalPositiveSafeInteger(input.policyMaxTokens, "policyMaxTokens");
9959
- assertOptionalPositiveSafeInteger(
9960
- input.policyReservedForResponse,
9961
- "policyReservedForResponse"
9962
- );
9963
- assertOptionalPositiveSafeInteger(
9964
- input.modelContextWindowTokens,
9965
- "modelContextWindowTokens"
9966
- );
9967
- assertOptionalPositiveSafeInteger(input.modelMaxOutputTokens, "modelMaxOutputTokens");
9968
- assertOptionalPositiveSafeInteger(
9969
- input.fallbackContextWindowTokens,
9970
- "fallbackContextWindowTokens"
9971
- );
9972
- assertOptionalPositiveSafeInteger(
9973
- input.fallbackMaxOutputTokens,
9974
- "fallbackMaxOutputTokens"
9975
- );
9976
- assertNonNegativeSafeInteger(input.toolDefinitionTokens, "toolDefinitionTokens");
9977
- const modelContextWindowTokens = input.modelContextWindowTokens ?? input.fallbackContextWindowTokens ?? DEFAULT_PROMPT_CONTEXT_WINDOW_TOKENS;
9978
- const modelMaxOutputTokens = input.modelMaxOutputTokens ?? input.fallbackMaxOutputTokens ?? DEFAULT_PROMPT_MAX_OUTPUT_TOKENS;
9979
- const effectiveWindowTokens = input.policyMaxTokens === void 0 ? modelContextWindowTokens : Math.min(input.policyMaxTokens, modelContextWindowTokens);
9980
- const outputLimitTokens = input.policyReservedForResponse === void 0 ? modelMaxOutputTokens : Math.min(input.policyReservedForResponse, modelMaxOutputTokens);
9981
- const inputBudgetTokens = effectiveWindowTokens - outputLimitTokens;
9982
- if (inputBudgetTokens < 1) {
9983
- throw new Error(
9984
- "\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"
9985
- );
9986
- }
9987
- const messageBudgetTokens = inputBudgetTokens - input.toolDefinitionTokens;
9988
- if (messageBudgetTokens < 1) {
9989
- throw new Error(
9990
- "Tool definitions \u5DF2\u5360\u6EE1 Prompt \u8F93\u5165\u9884\u7B97\uFF0C\u65E0\u6CD5\u4E3A messages \u4FDD\u7559 token\u3002"
9991
- );
9992
- }
9993
- return {
9994
- effectiveWindowTokens,
9995
- outputLimitTokens,
9996
- inputBudgetTokens,
9997
- toolDefinitionTokens: input.toolDefinitionTokens,
9998
- messageBudgetTokens
9999
- };
10000
- }
10001
- function assertOptionalPositiveSafeInteger(value, field) {
10002
- if (value !== void 0) {
10003
- assertPositiveSafeInteger(value, field);
10004
- }
10005
- }
10006
- function assertPositiveSafeInteger(value, field) {
10007
- if (!Number.isSafeInteger(value) || value < 1) {
10008
- throw new Error(`${field} \u5FC5\u987B\u662F\u6B63\u5B89\u5168\u6574\u6570\u3002`);
10009
- }
10010
- }
10011
- function assertNonNegativeSafeInteger(value, field) {
10012
- if (!Number.isSafeInteger(value) || value < 0) {
10013
- throw new Error(`${field} \u5FC5\u987B\u662F\u975E\u8D1F\u5B89\u5168\u6574\u6570\u3002`);
10014
- }
10015
- }
10016
10040
  var counter = z.number().int().nonnegative();
10017
10041
  var executor = z.object({
10018
10042
  stepCount: counter,
@@ -10105,6 +10129,51 @@ __export(tools_exports, {
10105
10129
  stripRuntimeReservedToolContextPatch: () => stripRuntimeReservedToolContextPatch
10106
10130
  });
10107
10131
 
10132
+ // src/runtime-kernel/tools/schema/functions/formatUnknownToolArguments.ts
10133
+ function spellingDistance(left, right) {
10134
+ let previous = Array.from({ length: right.length + 1 }, (_, index) => index);
10135
+ for (let row = 1; row <= left.length; row += 1) {
10136
+ const current = [row];
10137
+ for (let column = 1; column <= right.length; column += 1) {
10138
+ current[column] = Math.min(
10139
+ current[column - 1] + 1,
10140
+ previous[column] + 1,
10141
+ previous[column - 1] + (left[row - 1] === right[column - 1] ? 0 : 1)
10142
+ );
10143
+ }
10144
+ previous = current;
10145
+ }
10146
+ return previous[right.length];
10147
+ }
10148
+ function nearestField(field, allowedFields) {
10149
+ const threshold = field.length < 5 ? 1 : 2;
10150
+ let nearest;
10151
+ let bestDistance = threshold + 1;
10152
+ for (const candidate of allowedFields) {
10153
+ if (Math.abs(field.length - candidate.length) > threshold) continue;
10154
+ const distance = spellingDistance(field, candidate);
10155
+ if (distance < bestDistance) {
10156
+ bestDistance = distance;
10157
+ nearest = candidate;
10158
+ } else if (distance === bestDistance) {
10159
+ nearest = void 0;
10160
+ }
10161
+ }
10162
+ return bestDistance <= threshold ? nearest : void 0;
10163
+ }
10164
+ function formatUnknownToolArguments(fields, allowedFields) {
10165
+ const suggestions = fields.flatMap((field) => {
10166
+ const candidate = nearestField(field, allowedFields);
10167
+ return candidate ? [`${JSON.stringify(field)} \u2192 ${JSON.stringify(candidate)}`] : [];
10168
+ });
10169
+ return [
10170
+ `Additional properties not allowed: ${fields.map((field) => JSON.stringify(field)).join(", ")}.`,
10171
+ `Allowed parameters: ${allowedFields.map((field) => JSON.stringify(field)).join(", ") || "(none)"}.`,
10172
+ ...suggestions.length > 0 ? [`Possible spelling corrections: ${suggestions.join("; ")}.`] : [],
10173
+ "Remove unsupported parameters before retrying; no arguments were changed or executed."
10174
+ ].join(" ");
10175
+ }
10176
+
10108
10177
  // src/runtime-kernel/tools/toolContracts.ts
10109
10178
  var BaseTool = class {
10110
10179
  idempotency;
@@ -10140,7 +10209,7 @@ var BaseTool = class {
10140
10209
  if (unknownFields.length > 0) {
10141
10210
  return {
10142
10211
  success: false,
10143
- error: `Additional properties not allowed: ${unknownFields.join(", ")}`
10212
+ error: formatUnknownToolArguments(unknownFields, [...allowed])
10144
10213
  };
10145
10214
  }
10146
10215
  }
@@ -11860,7 +11929,15 @@ async function callWithRetryFallback(params) {
11860
11929
  eventHandler,
11861
11930
  requirement
11862
11931
  });
11863
- const attemptContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11932
+ const measuredContextUsage = invocationContext?.measurePromptUsage ? await invocationContext.measurePromptUsage(activeModelId, messages) : void 0;
11933
+ const attemptContextUsage = measuredContextUsage ? {
11934
+ ...measuredContextUsage,
11935
+ output_limit_tokens: Math.min(
11936
+ measuredContextUsage.output_limit_tokens,
11937
+ options.max_tokens ?? measuredContextUsage.output_limit_tokens
11938
+ )
11939
+ } : void 0;
11940
+ const attemptOptions = attemptContextUsage ? { ...options, max_tokens: attemptContextUsage.output_limit_tokens } : options;
11864
11941
  const isRetry = attempt > 0;
11865
11942
  let pendingErrorEvent = null;
11866
11943
  let streamedErrorClassification;
@@ -11877,7 +11954,7 @@ async function callWithRetryFallback(params) {
11877
11954
  inferencePort: deps.inferencePort,
11878
11955
  modelId: activeModelId,
11879
11956
  messages: resolvedMessages,
11880
- options,
11957
+ options: attemptOptions,
11881
11958
  eventHandler: attemptTracker.handle,
11882
11959
  onErrorClassification(classification) {
11883
11960
  streamedErrorClassification = classification;
@@ -11889,7 +11966,7 @@ async function callWithRetryFallback(params) {
11889
11966
  deps.inferencePort,
11890
11967
  activeModelId,
11891
11968
  resolvedMessages,
11892
- options,
11969
+ attemptOptions,
11893
11970
  signal,
11894
11971
  traceId
11895
11972
  );