@equationalapplications/core-llm-wiki 9.6.0 → 9.7.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.
@@ -329,6 +329,24 @@ interface LibrarianConfig {
329
329
  guidanceForEntity?: (entityId: string) => string | undefined;
330
330
  }
331
331
  interface WikiConfig {
332
+ /**
333
+ * Context-budget section (specs/context-budget). Absent, or
334
+ * `budget: 'legacy'`, keeps today's caps byte-identical.
335
+ * `budget: 'declared'` requires `contextWindowTokens` and derives the
336
+ * per-op prompt caps from the host's declared window; invalid values throw
337
+ * at construction (fail-fast, never fall back to legacy).
338
+ */
339
+ context?: {
340
+ budget: 'legacy' | 'declared';
341
+ /** Required under `budget: 'declared'`. */
342
+ contextWindowTokens?: number;
343
+ /** Chars per token for the host's tokenizer. Default 4. */
344
+ charsPerToken?: number;
345
+ /** Fraction of the derived window usable for prompts. Default 0.9. */
346
+ safetyFraction?: number;
347
+ /** Tokens held back for the model's reply. Default 4000. */
348
+ outputReserveTokens?: number;
349
+ };
332
350
  /** Source-store limits (spec source-store section 9). Defaults live in SourceStoreService. */
333
351
  sourceStore?: {
334
352
  maxCharsPerSource?: number;
@@ -329,6 +329,24 @@ interface LibrarianConfig {
329
329
  guidanceForEntity?: (entityId: string) => string | undefined;
330
330
  }
331
331
  interface WikiConfig {
332
+ /**
333
+ * Context-budget section (specs/context-budget). Absent, or
334
+ * `budget: 'legacy'`, keeps today's caps byte-identical.
335
+ * `budget: 'declared'` requires `contextWindowTokens` and derives the
336
+ * per-op prompt caps from the host's declared window; invalid values throw
337
+ * at construction (fail-fast, never fall back to legacy).
338
+ */
339
+ context?: {
340
+ budget: 'legacy' | 'declared';
341
+ /** Required under `budget: 'declared'`. */
342
+ contextWindowTokens?: number;
343
+ /** Chars per token for the host's tokenizer. Default 4. */
344
+ charsPerToken?: number;
345
+ /** Fraction of the derived window usable for prompts. Default 0.9. */
346
+ safetyFraction?: number;
347
+ /** Tokens held back for the model's reply. Default 4000. */
348
+ outputReserveTokens?: number;
349
+ };
332
350
  /** Source-store limits (spec source-store section 9). Defaults live in SourceStoreService. */
333
351
  sourceStore?: {
334
352
  maxCharsPerSource?: number;
@@ -1,2 +1,2 @@
1
- export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-BBeQQIYp.mjs';
1
+ export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-T0GgG1L6.mjs';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-BBeQQIYp.js';
1
+ export { a$ as EmbeddingService, b0 as ImportExportService, b1 as IngestionService, b2 as JobManager, b2 as JobManagerType, b3 as MaintenanceService, b4 as RetrievalService, b5 as SearchService, b5 as SearchServiceType, aM as WikiMemoryTestAccess, b6 as WriteService } from './testing-T0GgG1L6.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -2898,6 +2898,74 @@ function toGroundingAnchor(anchor) {
2898
2898
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
2899
2899
  var DEFAULT_CHUNK_OVERLAP = 400;
2900
2900
 
2901
+ // src/utils/contextCaps.ts
2902
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
2903
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
2904
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
2905
+
2906
+ // src/config/context.ts
2907
+ var DEFAULT_CHARS_PER_TOKEN = 4;
2908
+ var DEFAULT_SAFETY_FRACTION = 0.9;
2909
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
2910
+ var OP_FLOOR = {
2911
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
2912
+ heal: HEAL_MAX_PROMPT_CHARS,
2913
+ extract: OPS_MAX_EXTRACT_CHARS
2914
+ };
2915
+ function bad(key, value, why) {
2916
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
2917
+ }
2918
+ function resolveContextBudget(config) {
2919
+ const context = config?.context;
2920
+ if (!context || context.budget === void 0) {
2921
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2922
+ }
2923
+ if (context.budget !== "legacy" && context.budget !== "declared") {
2924
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
2925
+ }
2926
+ if (context.budget === "legacy") {
2927
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
2928
+ }
2929
+ const window = context.contextWindowTokens;
2930
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
2931
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
2932
+ }
2933
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
2934
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
2935
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
2936
+ }
2937
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
2938
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
2939
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
2940
+ }
2941
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
2942
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
2943
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
2944
+ }
2945
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
2946
+ }
2947
+ function declaredPromptCap(budget, op) {
2948
+ const derived = Math.floor(
2949
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
2950
+ );
2951
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
2952
+ return Math.max(OP_FLOOR.heal, derived);
2953
+ }
2954
+ function resolveMaxPromptChars(budget, op) {
2955
+ if (budget.mode !== "declared") {
2956
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
2957
+ }
2958
+ if (op === "extract") {
2959
+ const resolveDerived = declaredPromptCap(budget, "resolve");
2960
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
2961
+ return Math.max(OP_FLOOR.extract, extractDerived);
2962
+ }
2963
+ return declaredPromptCap(budget, op);
2964
+ }
2965
+ function resolveDefaultChunkLength(budget) {
2966
+ return DEFAULT_MAX_CHUNK_LENGTH;
2967
+ }
2968
+
2901
2969
  // src/utils/usage.ts
2902
2970
  function estimateTokens(text) {
2903
2971
  return Math.ceil(text.length / 4);
@@ -3038,7 +3106,7 @@ var IngestionService = class {
3038
3106
  if (!sourceRef) throw new Error("Invalid sourceRef");
3039
3107
  const sourceHash = normalizeSourceHash(params.sourceHash);
3040
3108
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
3041
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
3109
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
3042
3110
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
3043
3111
  const chunkOverlap = Math.min(
3044
3112
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -4939,18 +5007,18 @@ function parseValidFrom(v) {
4939
5007
 
4940
5008
  // src/services/librarian/ops/extract.ts
4941
5009
  var OPS_MAX_EVENTS_PER_PASS = 50;
4942
- var OPS_MAX_EXTRACT_CHARS = 24e3;
4943
5010
  var RESOLVE_RESERVE_FACTOR = 2;
4944
5011
  var MIN_SEGMENT_CHARS = 500;
4945
5012
  var MAX_SEGMENT_CALLS = 8;
4946
5013
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
4947
- async function selectBatch(deps, entityId, wm, meter, guidance) {
5014
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
4948
5015
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
4949
5016
  if (events.length === 0) return { batch: [] };
5017
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
4950
5018
  let n = 0;
4951
5019
  let chars = 0;
4952
5020
  for (const e of events) {
4953
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
5021
+ if (n > 0 && chars + e.summary.length > extractCap) break;
4954
5022
  chars += e.summary.length;
4955
5023
  n++;
4956
5024
  }
@@ -5289,7 +5357,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
5289
5357
  }
5290
5358
 
5291
5359
  // src/services/librarian/ops/resolve.ts
5292
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
5293
5360
  function validateOp(raw, aliases) {
5294
5361
  if (!raw || typeof raw !== "object") return null;
5295
5362
  const r = raw;
@@ -5308,7 +5375,7 @@ function validateOp(raw, aliases) {
5308
5375
  return update;
5309
5376
  }
5310
5377
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
5311
- async function runResolve(deps, ctx, ambiguous) {
5378
+ async function runResolve(deps, ctx, ambiguous, budget) {
5312
5379
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
5313
5380
  if (ambiguous.length === 0) return out;
5314
5381
  const { entityId, trigger } = ctx;
@@ -5334,7 +5401,7 @@ async function runResolve(deps, ctx, ambiguous) {
5334
5401
  onSkip: (g, err) => {
5335
5402
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
5336
5403
  },
5337
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
5404
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
5338
5405
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
5339
5406
  });
5340
5407
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -5543,7 +5610,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5543
5610
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
5544
5611
  await deps.seedWatermark(entityId);
5545
5612
  const wm = await deps.getWatermark(entityId);
5546
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
5613
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
5547
5614
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
5548
5615
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
5549
5616
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -5571,7 +5638,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
5571
5638
  });
5572
5639
  }
5573
5640
  diagnostics.push(gateDiagnostic);
5574
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
5641
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
5575
5642
  for (const itemIndex of res.overflowSkipped) {
5576
5643
  diagnostics.push({
5577
5644
  entityId,
@@ -5640,7 +5707,6 @@ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
5640
5707
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
5641
5708
  var CLASSIFIER_MAX_CHOICES = 255;
5642
5709
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
5643
- var HEAL_MAX_PROMPT_CHARS = 4e4;
5644
5710
  var HEAL_BATCH_SIZE = 25;
5645
5711
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
5646
5712
  var MAX_EMBED_ATTEMPTS = 5;
@@ -6944,7 +7010,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
6944
7010
  };
6945
7011
  },
6946
7012
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
6947
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
7013
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
6948
7014
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
6949
7015
  supportsEscalation: true,
6950
7016
  onSkip: (fact, err) => {