@equationalapplications/core-llm-wiki 9.16.1 → 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.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, serializeDerivedEvents, parseStoredDerivedEvents, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, resolveContextBudgetOrThrow, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, createEntriesDeletedIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL, WikiDraftNotFound, generateId, emptyManifest, resolveNodeTypeMatch, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, resolveNodeType, shouldEmitOntologyReceipt, nodeTypeReceipts, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateDerivedEventsValue, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-7DBDJBN3.mjs';
2
- export { CLASSIFIER_MAX_CHOICES, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isReservedAbstainSlug, isWikiSearchUnavailableError, parseEmbedding, resolveContextBudget, resolveDefaultChunkLength, resolveEdgesMinConfidence, resolveHealScreenMinConfidence, resolveMaxPromptChars, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-7DBDJBN3.mjs';
1
+ import { BaseRepository, WikiGraphNodeOwnershipConflict, serializeSourcePointer, serializeDerivedEvents, parseStoredDerivedEvents, parseStoredSourcePointer, parseJsonObject, parseJsonArray, liveAtSql, reanchorRebuildFingerprint, __privateAdd, warnChangedDefaultsOnce, resolveContextBudgetOrThrow, EdgeRepository, MetadataRepository, EmbeddingService, VectorRemovalRepository, VectorRemovalService, SearchService, TemporalService, JobManager, PromptService, resolveGrounding, IngestionService, MaintenanceService, ImportExportService, RetrievalService, SourceStoreService, WriteService, __privateGet, __privateSet, createLegacySourceTypeIndex, createEntriesDeletedIndex, writeNormalizeStamp, CURRENT_SCHEMA_VERSION, detectSchemaVersion, MIGRATIONS, runSourceRefNormalize, emitDiagnostic, normalizeSourceRef, normalizeSourceHash, canEngageWriteTyping, resolveLibrarianStrategy, entitySummaryMetaKey, WikiSourceRefHashCollision, DiagnosticBuffer, validateManifest, isReservedAbstainSlug, ONTOLOGY_ABSTAIN_SENTINEL, WikiDraftNotFound, generateId, emptyManifest, resolveNodeTypeMatch, WikiStrictOntologyViolation, validateInlineEdges, resolveEdgeDefinitions, typeSatisfies, normalizeTitleKey, edgeTripleAllowed, resolveNodeType, shouldEmitOntologyReceipt, nodeTypeReceipts, MAX_EMBED_ATTEMPTS, UsageMeter, isWikiSearchUnavailableError, WikiBusyError, WikiInvalidReadOptions, isLiveAt, packFactsByBudget, factTokenCost, probePendingWork, WikiMigrationRequiredError, setupDatabase, UnavailableIndexStrategy, createdAtValue, isUsableDate, validateDerivedEventsValue, validateSourcePointerValue, assertEntityId, assertEpochMs, passageFtsTriggerNames, FTS5_STATE_KEY, fts5LedgerDropSql, passageFtsTablesDdl, passageFtsTriggersDdl, fts5TablesDdl, fts5PendingIndexesDdl, fts5TriggersDdl, writeRebuildStart, FTS5_RETIRED_COUNTER_KEY, retiredTableName, FTS5_RETIRED_TABLES_KEY, isRetiredTableName, idReindexChunkSql, readRebuildProgress, FTS5_DRAIN_CHUNK, FTS5_RECLAIM_MERGE_PAGES, windowHiSql, windowChunkSql, FTS5_REBUILD_WM_KEY, sweepHiSql, sweepChunkSql, FTS5_SWEEP_CURSOR_KEY, drainHiSql, drainChunkSql, FTS5_REBUILD_SNAPSHOT_KEY, idDrainChunkSql, entityDrainHiSql, entityDrainChunkSql, fts5TriggerNames, extractSqliteCode, WikiTransactionError } from './chunk-64ZKSSY6.mjs';
2
+ export { CLASSIFIER_MAX_CHOICES, CheckpointIncompleteError, DEFAULT_CHUNK_OVERLAP, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, EraseStepError, HEAL_ANCHORS_PER_CANDIDATE, HEAL_BATCH_SIZE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, HEAL_RECHECK_MS, HOOK_TIMEOUT_MARKER, ONTOLOGY_ABSTAIN_SENTINEL, ONTOLOGY_BACKFILL_BATCH_SIZE, ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, ONTOLOGY_BACKFILL_RECHECK_MS, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, PromptService, PrunePartialFailureError, WikiBusyError, WikiDraftNotFound, WikiDuplicateHashError, WikiExternalDeletionError, WikiGraphNodeOwnershipConflict, WikiIngestEmptyError, WikiInvalidReadOptions, WikiMigrationRequiredError, WikiParseError, WikiSearchUnavailableError, WikiSourceRefHashCollision, WikiStrictOntologyViolation, WikiSupersedeError, WikiTransactionError, chunkText, configureRandomSource, isReservedAbstainSlug, isWikiSearchUnavailableError, parseEmbedding, resolveContextBudget, resolveDefaultChunkLength, resolveEdgesMinConfidence, resolveHealScreenMinConfidence, resolveMaxPromptChars, resolveResolveMinConfidence, resolveSystemOneEdges, resolveSystemOneHealScreen, resolveSystemOneResolve, resolveSystemOneTypeOnWrite, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateManifest, warnOnce } from './chunk-64ZKSSY6.mjs';
3
3
  import { deriveTrustTier, isStaleAfter, appendRelatedSection, buildConceptDocument, buildLogMd, buildEntityIndexMd, buildRootIndexMd, isAllowedOkfPath, parseRootIndexMd, parseEntityIndexMd, parseConcept, splitRelatedSection, extractMarkdownLinks, parseLogMd, parseEventIdComment, createEventIdDeriver, latestVerified, formatSourcesJson, appendEventIdComment, parseVerifiedFlexible, parseCitationsList } from '@equationalapplications/core-okf';
4
4
  import MiniSearch from 'minisearch';
5
5
 
@@ -1782,7 +1782,11 @@ interface PendingMaintenance {
1782
1782
  interface RunPendingMaintenanceOptions {
1783
1783
  /** Default: every entity with pending work. */
1784
1784
  entityIds?: string[];
1785
- /** generateText tokens (provider-reported or chars/4). Omitted = unbounded. */
1785
+ /**
1786
+ * generateText and classify tokens (provider-reported or chars/4). Omitted = unbounded.
1787
+ * Calls in flight hold budget before they start; admission tests the input
1788
+ * estimate, so a call's own output can pass the budget.
1789
+ */
1786
1790
  tokenBudget?: number;
1787
1791
  /** Wall-clock milliseconds from the call. Checked between units; a unit in flight is never interrupted. */
1788
1792
  deadlineMs?: number;
@@ -4078,15 +4082,41 @@ interface UsageRecord {
4078
4082
  /** True when either figure came from estimateTokens rather than the provider. */
4079
4083
  estimated: boolean;
4080
4084
  }
4081
- /** One budget shared by every LLM call in a maintenance run. */
4085
+ /** Opaque handle for tokens held by one in-flight metered call. */
4086
+ interface UsageReservation {
4087
+ readonly _brand: 'UsageReservation';
4088
+ }
4089
+ /**
4090
+ * One budget shared by every LLM call in a maintenance run (generateText and
4091
+ * classify). A call is admitted on its input estimate (`reserve`), holds
4092
+ * tokens against the budget while in flight so parallel calls cannot all
4093
+ * claim the same headroom, then `settle`s the real usage or `release`s on
4094
+ * failure (specs/meter-reservation). The budget stays an admission check on
4095
+ * the input estimate, not a hard ceiling on provider output.
4096
+ */
4082
4097
  declare class UsageMeter {
4083
4098
  readonly budget: number | undefined;
4084
4099
  used: number;
4085
4100
  estimated: boolean;
4101
+ private heldTokens;
4086
4102
  constructor(budget?: number);
4103
+ /** Tokens held by in-flight reservations. */
4104
+ get reserved(): number;
4105
+ /** budget - used - reserved, clamped at 0; Infinity when unbounded. */
4087
4106
  get remaining(): number;
4088
4107
  fits(estimate: number): boolean;
4089
4108
  record(r: UsageRecord): void;
4109
+ /**
4110
+ * Admit a call on `estimate` (throws WikiBudgetExhausted when it does not
4111
+ * fit the unreserved remainder) and hold `max(estimate, hold)` tokens until
4112
+ * settle/release.
4113
+ */
4114
+ reserve(estimate: number, hold?: number): UsageReservation;
4115
+ /** Free the hold, then charge the real usage. A closed handle is a no-op. */
4116
+ settle(handle: UsageReservation, actual: UsageRecord): void;
4117
+ /** Free the hold and charge nothing. A closed handle is a no-op. */
4118
+ release(handle: UsageReservation): void;
4119
+ private close;
4090
4120
  }
4091
4121
 
4092
4122
  /**
@@ -1782,7 +1782,11 @@ interface PendingMaintenance {
1782
1782
  interface RunPendingMaintenanceOptions {
1783
1783
  /** Default: every entity with pending work. */
1784
1784
  entityIds?: string[];
1785
- /** generateText tokens (provider-reported or chars/4). Omitted = unbounded. */
1785
+ /**
1786
+ * generateText and classify tokens (provider-reported or chars/4). Omitted = unbounded.
1787
+ * Calls in flight hold budget before they start; admission tests the input
1788
+ * estimate, so a call's own output can pass the budget.
1789
+ */
1786
1790
  tokenBudget?: number;
1787
1791
  /** Wall-clock milliseconds from the call. Checked between units; a unit in flight is never interrupted. */
1788
1792
  deadlineMs?: number;
@@ -4078,15 +4082,41 @@ interface UsageRecord {
4078
4082
  /** True when either figure came from estimateTokens rather than the provider. */
4079
4083
  estimated: boolean;
4080
4084
  }
4081
- /** One budget shared by every LLM call in a maintenance run. */
4085
+ /** Opaque handle for tokens held by one in-flight metered call. */
4086
+ interface UsageReservation {
4087
+ readonly _brand: 'UsageReservation';
4088
+ }
4089
+ /**
4090
+ * One budget shared by every LLM call in a maintenance run (generateText and
4091
+ * classify). A call is admitted on its input estimate (`reserve`), holds
4092
+ * tokens against the budget while in flight so parallel calls cannot all
4093
+ * claim the same headroom, then `settle`s the real usage or `release`s on
4094
+ * failure (specs/meter-reservation). The budget stays an admission check on
4095
+ * the input estimate, not a hard ceiling on provider output.
4096
+ */
4082
4097
  declare class UsageMeter {
4083
4098
  readonly budget: number | undefined;
4084
4099
  used: number;
4085
4100
  estimated: boolean;
4101
+ private heldTokens;
4086
4102
  constructor(budget?: number);
4103
+ /** Tokens held by in-flight reservations. */
4104
+ get reserved(): number;
4105
+ /** budget - used - reserved, clamped at 0; Infinity when unbounded. */
4087
4106
  get remaining(): number;
4088
4107
  fits(estimate: number): boolean;
4089
4108
  record(r: UsageRecord): void;
4109
+ /**
4110
+ * Admit a call on `estimate` (throws WikiBudgetExhausted when it does not
4111
+ * fit the unreserved remainder) and hold `max(estimate, hold)` tokens until
4112
+ * settle/release.
4113
+ */
4114
+ reserve(estimate: number, hold?: number): UsageReservation;
4115
+ /** Free the hold, then charge the real usage. A closed handle is a no-op. */
4116
+ settle(handle: UsageReservation, actual: UsageRecord): void;
4117
+ /** Free the hold and charge nothing. A closed handle is a no-op. */
4118
+ release(handle: UsageReservation): void;
4119
+ private close;
4090
4120
  }
4091
4121
 
4092
4122
  /**
@@ -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, aL as WikiMemoryTestAccess, b6 as WriteService } from './testing-C8sYdo2S.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, aL as WikiMemoryTestAccess, b6 as WriteService } from './testing-DNSqIkkv.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, aL as WikiMemoryTestAccess, b6 as WriteService } from './testing-C8sYdo2S.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, aL as WikiMemoryTestAccess, b6 as WriteService } from './testing-DNSqIkkv.js';
2
2
  import '@equationalapplications/core-okf';
package/dist/testing.js CHANGED
@@ -3105,13 +3105,19 @@ var UsageMeter = class {
3105
3105
  constructor(budget) {
3106
3106
  this.used = 0;
3107
3107
  this.estimated = false;
3108
+ this.heldTokens = 0;
3108
3109
  if (budget !== void 0 && (typeof budget !== "number" || !Number.isFinite(budget) || budget < 0)) {
3109
3110
  throw new TypeError("tokenBudget must be a finite number >= 0");
3110
3111
  }
3111
3112
  this.budget = budget;
3112
3113
  }
3114
+ /** Tokens held by in-flight reservations. */
3115
+ get reserved() {
3116
+ return this.heldTokens;
3117
+ }
3118
+ /** budget - used - reserved, clamped at 0; Infinity when unbounded. */
3113
3119
  get remaining() {
3114
- return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used);
3120
+ return this.budget === void 0 ? Infinity : Math.max(0, this.budget - this.used - this.heldTokens);
3115
3121
  }
3116
3122
  fits(estimate) {
3117
3123
  return estimate <= this.remaining;
@@ -3120,6 +3126,33 @@ var UsageMeter = class {
3120
3126
  this.used += r.inputTokens + r.outputTokens;
3121
3127
  if (r.estimated) this.estimated = true;
3122
3128
  }
3129
+ /**
3130
+ * Admit a call on `estimate` (throws WikiBudgetExhausted when it does not
3131
+ * fit the unreserved remainder) and hold `max(estimate, hold)` tokens until
3132
+ * settle/release.
3133
+ */
3134
+ reserve(estimate, hold) {
3135
+ if (!this.fits(estimate)) throw new WikiBudgetExhausted(estimate, this.remaining);
3136
+ const handle = { _brand: "UsageReservation", hold: Math.max(estimate, hold ?? estimate), open: true };
3137
+ this.heldTokens += handle.hold;
3138
+ return handle;
3139
+ }
3140
+ /** Free the hold, then charge the real usage. A closed handle is a no-op. */
3141
+ settle(handle, actual) {
3142
+ if (!this.close(handle)) return;
3143
+ this.record(actual);
3144
+ }
3145
+ /** Free the hold and charge nothing. A closed handle is a no-op. */
3146
+ release(handle) {
3147
+ this.close(handle);
3148
+ }
3149
+ close(handle) {
3150
+ const h = handle;
3151
+ if (!h.open) return false;
3152
+ h.open = false;
3153
+ this.heldTokens -= h.hold;
3154
+ return true;
3155
+ }
3123
3156
  };
3124
3157
  var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
3125
3158
  constructor(requiredEstimate, remaining) {
@@ -3132,6 +3165,7 @@ var WikiBudgetExhausted = class _WikiBudgetExhausted extends Error {
3132
3165
  };
3133
3166
 
3134
3167
  // src/utils/llmCall.ts
3168
+ var CLASSIFY_HOLD_FACTOR = 2;
3135
3169
  function validUsage(u) {
3136
3170
  if (!u || typeof u !== "object") return false;
3137
3171
  const { inputTokens, outputTokens } = u;
@@ -3139,25 +3173,29 @@ function validUsage(u) {
3139
3173
  }
3140
3174
  async function callLlm(options, ctx, prompts) {
3141
3175
  const promptEstimate = estimateTokens(prompts.systemPrompt) + estimateTokens(prompts.userPrompt);
3142
- if (ctx.meter && !ctx.meter.fits(promptEstimate)) {
3143
- throw new WikiBudgetExhausted(promptEstimate, ctx.meter.remaining);
3144
- }
3145
3176
  const provider = options.llmProvider;
3146
3177
  const params = { systemPrompt: prompts.systemPrompt, userPrompt: prompts.userPrompt };
3147
3178
  let text;
3148
- let reported;
3149
- if (typeof provider.generateTextWithUsage === "function") {
3150
- const result = await provider.generateTextWithUsage(params);
3151
- if (!result || typeof result.text !== "string") {
3152
- throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
3153
- }
3154
- text = result.text;
3155
- reported = validUsage(result.usage) ? result.usage : void 0;
3156
- } else {
3157
- text = await provider.generateText(params);
3179
+ let record;
3180
+ const reservation = ctx.meter?.reserve(promptEstimate);
3181
+ try {
3182
+ let reported;
3183
+ if (typeof provider.generateTextWithUsage === "function") {
3184
+ const result = await provider.generateTextWithUsage(params);
3185
+ if (!result || typeof result.text !== "string") {
3186
+ throw new TypeError("generateTextWithUsage() must resolve to { text: string, usage? }");
3187
+ }
3188
+ text = result.text;
3189
+ reported = validUsage(result.usage) ? result.usage : void 0;
3190
+ } else {
3191
+ text = await provider.generateText(params);
3192
+ }
3193
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
3194
+ } catch (err) {
3195
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
3196
+ throw err;
3158
3197
  }
3159
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: promptEstimate, outputTokens: estimateTokens(text), estimated: true };
3160
- ctx.meter?.record(record);
3198
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
3161
3199
  if (options.config?.reportLlmUsage === true) {
3162
3200
  emitDiagnostic(options, {
3163
3201
  code: "llm_usage",
@@ -3171,18 +3209,23 @@ async function callLlm(options, ctx, prompts) {
3171
3209
  }
3172
3210
  async function callClassify(options, ctx, request) {
3173
3211
  const inputEstimate = estimateTokens(request.state) + estimateTokens(JSON.stringify(request.questions));
3174
- if (ctx.meter && !ctx.meter.fits(inputEstimate)) {
3175
- throw new WikiBudgetExhausted(inputEstimate, ctx.meter.remaining);
3176
- }
3177
3212
  const provider = options.llmProvider;
3178
- if (typeof provider.classify !== "function") {
3179
- throw new TypeError("callClassify requires a provider with classify()");
3180
- }
3181
- const response = await provider.classify(request);
3182
- const reported = validUsage(response?.usage) ? response.usage : void 0;
3183
- const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
3184
- const record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
3185
- ctx.meter?.record(record);
3213
+ let response;
3214
+ let record;
3215
+ const reservation = ctx.meter?.reserve(inputEstimate, inputEstimate * CLASSIFY_HOLD_FACTOR);
3216
+ try {
3217
+ if (typeof provider.classify !== "function") {
3218
+ throw new TypeError("callClassify requires a provider with classify()");
3219
+ }
3220
+ response = await provider.classify(request);
3221
+ const reported = validUsage(response?.usage) ? response.usage : void 0;
3222
+ const outputEstimate = estimateTokens(JSON.stringify(response?.answers ?? {}));
3223
+ record = reported ? { inputTokens: reported.inputTokens, outputTokens: reported.outputTokens, estimated: false } : { inputTokens: inputEstimate, outputTokens: outputEstimate, estimated: true };
3224
+ } catch (err) {
3225
+ if (ctx.meter && reservation) ctx.meter.release(reservation);
3226
+ throw err;
3227
+ }
3228
+ if (ctx.meter && reservation) ctx.meter.settle(reservation, record);
3186
3229
  if (options.config?.reportLlmUsage === true) {
3187
3230
  emitDiagnostic(options, {
3188
3231
  code: "llm_usage",