@equationalapplications/core-llm-wiki 9.16.0 → 9.16.2

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.
@@ -505,13 +505,19 @@ var UsageMeter = class {
505
505
  constructor(budget) {
506
506
  this.used = 0;
507
507
  this.estimated = false;
508
+ this.heldTokens = 0;
508
509
  if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
509
510
  throw new TypeError("tokenBudget must be a finite number >= 0");
510
511
  }
511
512
  this.budget = budget;
512
513
  }
514
+ /** Tokens held by in-flight reservations. */
515
+ get reserved() {
516
+ return this.heldTokens;
517
+ }
518
+ /** budget - used - reserved, clamped at 0; Infinity when unbounded. */
513
519
  get remaining() {
514
- return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
520
+ return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used - this.heldTokens);
515
521
  }
516
522
  fits(estimate) {
517
523
  return estimate <= this.remaining;
@@ -520,6 +526,33 @@ var UsageMeter = class {
520
526
  this.used += r.inputTokens + r.outputTokens;
521
527
  if (r.estimated) this.estimated = true;
522
528
  }
529
+ /**
530
+ * Admit a call on `estimate` (throws WikiBudgetExhausted when it does not
531
+ * fit the unreserved remainder) and hold `max(estimate, hold)` tokens until
532
+ * settle/release.
533
+ */
534
+ reserve(estimate, hold) {
535
+ if (!this.fits(estimate)) throw new WikiBudgetExhausted(estimate, this.remaining);
536
+ const handle = { _brand: "UsageReservation", hold: Math.max(estimate, hold ?? estimate), open: true };
537
+ this.heldTokens += handle.hold;
538
+ return handle;
539
+ }
540
+ /** Free the hold, then charge the real usage. A closed handle is a no-op. */
541
+ settle(handle, actual) {
542
+ if (!this.close(handle)) return;
543
+ this.record(actual);
544
+ }
545
+ /** Free the hold and charge nothing. A closed handle is a no-op. */
546
+ release(handle) {
547
+ this.close(handle);
548
+ }
549
+ close(handle) {
550
+ const h = handle;
551
+ if (!h.open) return false;
552
+ h.open = false;
553
+ this.heldTokens -= h.hold;
554
+ return true;
555
+ }
523
556
  };
524
557
  var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
525
558
  constructor(requiredEstimate, remaining) {
@@ -532,6 +565,7 @@ var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
532
565
  };
533
566
 
534
567
  // src/utils/llmCall.ts
568
+ var CLASSIFY_HOLD_FACTOR = 2;
535
569
  function validUsage(u) {
536
570
  if (!u || typeof u !== "object") return false;
537
571
  const { inputTokens, outputTokens } = u;
@@ -539,25 +573,29 @@ function validUsage(u) {
539
573
  }
540
574
  async function callLlm(options, ctx, prompts) {
541
575
  const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
542
- if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
543
- throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
544
- }
545
576
  const provider = options.llmProvider;
546
577
  const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
547
578
  let text;
548
- let reported;
549
- if (typeof provider.generateTextWithUsage === "function") {
550
- const result = await provider.generateTextWithUsage(params);
551
- if (!result || typeof result.text !== "string") {
552
- throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
553
- }
554
- text = result.text;
555
- reported = validUsage(result.usage) ? result.usage : void 0;
556
- } else {
557
- text = await provider.generateText(params);
579
+ let record;
580
+ const reservation = ctx.meter?.reserve(promptEstimate);
581
+ try {
582
+ let reported;
583
+ if (typeof provider.generateTextWithUsage === "function") {
584
+ const result = await provider.generateTextWithUsage(params);
585
+ if (!result || typeof result.text !== "string") {
586
+ throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
587
+ }
588
+ text = result.text;
589
+ reported = validUsage(result.usage) ? result.usage : void 0;
590
+ } else {
591
+ text = await provider.generateText(params);
592
+ }
593
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
594
+ } catch (err) {
595
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
596
+ throw err;
558
597
  }
559
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
560
- ctx.meter?.record(record);
598
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
561
599
  if (options.config?.reportLlmUsage === true) {
562
600
  emitDiagnostic(options, {
563
601
  code: "llm_usage",
@@ -571,18 +609,23 @@ async function callLlm(options, ctx, prompts) {
571
609
  }
572
610
  async function callClassify(options, ctx, request) {
573
611
  const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
574
- if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
575
- throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
576
- }
577
612
  const provider = options.llmProvider;
578
- if (typeof provider.classify !== "function") {
579
- throw new TypeError("callClassify requires a provider with classify()");
580
- }
581
- const response = await provider.classify(request);
582
- const reported = validUsage(response?.usage) ? response.usage : void 0;
583
- const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
584
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
585
- ctx.meter?.record(record);
613
+ let response;
614
+ let record;
615
+ const reservation = ctx.meter?.reserve(inputEstimate, inputEstimate * CLASSIFY_HOLD_FACTOR);
616
+ try {
617
+ if (typeof provider.classify !== "function") {
618
+ throw new TypeError("callClassify requires a provider with classify()");
619
+ }
620
+ response = await provider.classify(request);
621
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
622
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
623
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
624
+ } catch (err) {
625
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
626
+ throw err;
627
+ }
628
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
586
629
  if (options.config?.reportLlmUsage === true) {
587
630
  emitDiagnostic(options, {
588
631
  code: "llm_usage",
@@ -10581,7 +10624,7 @@ var ImportExportService = class {
10581
10624
  const rawPointerValue = hasSourcePointerKey ? fact["source_pointer"] : void 0;
10582
10625
  const pointerValidated = hasSourcePointerKey ? validateSourcePointerValue(rawPointerValue) : null;
10583
10626
  if (pointerValidated === void 0) {
10584
- emitDiagnostic(this.options, {
10627
+ refusalDiagnostics.push({
10585
10628
  code: "source_pointer_invalid",
10586
10629
  operation: "importDump",
10587
10630
  trigger: "call",
@@ -12394,5 +12437,5 @@ var WriteService = class {
12394
12437
  };
12395
12438
 
12396
12439
  export { BaseRepository, CLASSIFIER_MAX_CHOICES, CURRENT_SCHEMA_VERSION, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, DiagnosticBuffer, EMBED_CHARS_CEILING, EdgeRepository, EmbeddingService, EraseStepError, FTS5_DRAIN_CHUNK, FTS5_REBUILD_SNAPSHOT_KEY, FTS5_REBUILD_WM_KEY, FTS5_RECLAIM_MERGE_PAGES, FTS5_RETIRED_COUNTER_KEY, FTS5_RETIRED_TABLES_KEY, FTS5_STATE_KEY, FTS5_SWEEP_CURSOR_KEY, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ImportExportService, IngestionService, JobManager, MAX_EMBED_ATTEMPTS, MIGRATIONS, MaintenanceService, MetadataRepository, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, RetrievalService, SearchService, SourceStoreService, TemporalService, UnavailableIndexStrategy, UsageMeter, VectorRemovalRepository, VectorRemovalService, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, WriteService, __privateAdd, __privateGet, __privateSet, assertEntityId, assertEpochMs, canEngageWriteTyping, chunkText, configureRandomSource, createEntriesDeletedIndex, createLegacySourceTypeIndex, createdAtValue, detectSchemaVersion, drainChunkSql, drainHiSql, edgeTripleAllowed, emitDiagnostic, emptyManifest, entityDrainChunkSql, entityDrainHiSql, entitySummaryMetaKey, extractSqliteCode, factTokenCost, fts5LedgerDropSql, fts5PendingIndexesDdl, fts5TablesDdl, fts5TriggerNames, fts5TriggersDdl, generateId, idDrainChunkSql, idReindexChunkSql, isLiveAt, isReservedAbstainSlug, isRetiredTableName, isUsableDate, isWikiSearchUnavailableError, liveAtSql, nodeTypeReceipts, normalizeSourceHash, normalizeSourceRef, normalizeTitleKey, packFactsByBudget, parseEmbedding, parseJsonArray, parseJsonObject, parseStoredDerivedEvents, parseStoredSourcePointer, passageFtsTablesDdl, passageFtsTriggerNames, passageFtsTriggersDdl, probePendingWork, readRebuildProgress, reanchorRebuildFingerprint, resolveContextBudget, resolveContextBudgetOrThrow, resolveDefaultChunkLength, resolveEdgeDefinitions, resolveEdgesMinConfidence, resolveGrounding, resolveHealScreenMinConfidence, resolveLibrarianStrategy, resolveMaxPromptChars, resolveNodeType, resolveNodeTypeMatch, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, retiredTableName, runSourceRefNormalize, safeSlice, serializeDerivedEvents, serializeSourcePointer, setupDatabase, shouldEmitOntologyReceipt, sweepChunkSql, sweepHiSql, typeSatisfies, validUsage, validateDerivedEventsValue, validateInlineEdges, validateManifest, validateSourcePointerValue, warnChangedDefaultsOnce, warnOnce, windowChunkSql, windowHiSql, writeNormalizeStamp, writeRebuildStart };
12397
- //# sourceMappingURL=chunk-DD5G4VRF.mjs.map
12398
- //# sourceMappingURL=chunk-DD5G4VRF.mjs.map
12440
+ //# sourceMappingURL=chunk-64ZKSSY6.mjs.map
12441
+ //# sourceMappingURL=chunk-64ZKSSY6.mjs.map