@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.
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, c as OntologyConfig, W as WikiConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-BBeQQIYp.mjs';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-BBeQQIYp.mjs';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-T0GgG1L6.mjs';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-T0GgG1L6.mjs';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -62,6 +62,22 @@ declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
62
62
  */
63
63
  declare const HEAL_MAX_TASKS = 50;
64
64
 
65
+ /**
66
+ * Default maximum characters per chunk that `ingestDocument` uses when a
67
+ * caller doesn't override `maxChunkLength` (directly or via
68
+ * `WikiOptions.config.maxChunkLength`).
69
+ */
70
+ declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
71
+ /**
72
+ * Default/fallback character overlap between consecutive chunks.
73
+ * `ingestDocument` uses this when a caller doesn't override `chunkOverlap`
74
+ * (directly or via `WikiOptions.config.chunkOverlap`), and clamps the
75
+ * effective overlap (including this default) to `maxChunkLength - 1` when
76
+ * needed. The clamp is a no-op for the shipped defaults; it can also apply
77
+ * when a custom `maxChunkLength` makes the resolved overlap too large.
78
+ */
79
+ declare const DEFAULT_CHUNK_OVERLAP = 400;
80
+
65
81
  declare function formatContext(bundle: MemoryBundle, options?: FormatContextOptions): string;
66
82
 
67
83
  /**
@@ -111,20 +127,32 @@ declare function validUsage(u: unknown): u is {
111
127
  };
112
128
 
113
129
  /**
114
- * Default maximum characters per chunk that `ingestDocument` uses when a
115
- * caller doesn't override `maxChunkLength` (directly or via
116
- * `WikiOptions.config.maxChunkLength`).
117
- */
118
- declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
119
- /**
120
- * Default/fallback character overlap between consecutive chunks.
121
- * `ingestDocument` uses this when a caller doesn't override `chunkOverlap`
122
- * (directly or via `WikiOptions.config.chunkOverlap`), and clamps the
123
- * effective overlap (including this default) to `maxChunkLength - 1` when
124
- * needed. The clamp is a no-op for the shipped defaults; it can also apply
125
- * when a custom `maxChunkLength` makes the resolved overlap too large.
126
- */
127
- declare const DEFAULT_CHUNK_OVERLAP = 400;
130
+ * Context-budget wrapper (specs/context-budget Proposed change 2).
131
+ *
132
+ * Core ships no tokenizer: every estimate is chars/`charsPerToken`. The
133
+ * meter keeps plain `estimateTokens` (chars/4) this PR — metering is out of
134
+ * scope — so `estimateTokensWith` under a legacy budget (`charsPerToken: 4`)
135
+ * is byte-equal to `estimateTokens` for every input, and the wrapper ships
136
+ * unused by metering.
137
+ */
138
+ interface ContextBudget {
139
+ mode: 'legacy' | 'declared';
140
+ /** Set iff mode === 'declared'. */
141
+ contextWindowTokens?: number;
142
+ /** 4 under legacy. */
143
+ charsPerToken: number;
144
+ /** 0.9 under legacy (unused in legacy math). */
145
+ safetyFraction: number;
146
+ /** 4000 under legacy (unused in legacy math). */
147
+ outputReserveTokens: number;
148
+ }
149
+ declare function estimateTokensWith(budget: ContextBudget, text: string): number;
150
+
151
+ type ContextBudgetOp = 'resolve' | 'heal' | 'extract';
152
+ declare function resolveContextBudget(config: WikiConfig | undefined): ContextBudget;
153
+ declare function resolveMaxPromptChars(budget: ContextBudget, op: ContextBudgetOp): number;
154
+ /** The ingest chunk default stays 12000 in both modes (ruling R2). */
155
+ declare function resolveDefaultChunkLength(budget: ContextBudget): number;
128
156
 
129
157
  /**
130
158
  * Default clamp on embed input length, in characters (~1,500 tokens).
@@ -217,5 +245,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
217
245
 
218
246
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
219
247
 
220
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
221
- export type { FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
248
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
+ export type { ContextBudget, FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, R as ReadOptions, c as OntologyConfig, W as WikiConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-BBeQQIYp.js';
2
- export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-BBeQQIYp.js';
1
+ import { M as MemoryBundle, F as FormatContextOptions, G as GraphNeighborhood, a as MemoryDump, b as FormattedMemoryDump, O as OntologyMode, W as WikiConfig, R as ReadOptions, c as OntologyConfig, S as SQLiteAdapter, d as WikiOptions, e as WikiMemory } from './testing-T0GgG1L6.js';
2
+ export { C as CLASSIFIER_MAX_CHOICES, f as CheckpointIncompleteError, g as ChunkFailure, h as ClassifierAnswer, i as ClassifierQuestion, j as ClassifyRequest, k as ClassifyResponse, D as DegradedRecord, l as DraftPage, E as EmbedFactResult, m as EmbedFailureKind, n as EmbeddingMarkerKind, o as EntityMaintenanceReport, p as EntityStatus, q as EraseReport, r as EraseStepError, s as ExtractedFact, t as ExtractedFactEdge, u as ExtractedFactWithOntology, v as ExtractedTask, w as ForgetParams, x as ForgetResult, y as GraphTraversalOptions, z as GroundingConfig, H as HEAL_BATCH_SIZE, A as HEAL_RECHECK_MS, B as HOOK_TIMEOUT_MARKER, I as HealResult, J as ImportDumpResult, K as IngestDocumentResult, L as LLMProvider, N as LibrarianConfig, P as LibrarianGateConfig, Q as LockedMaintenanceJob, T as MaintenanceJob, U as MaintenanceStopReason, V as MemoryDumpEntity, X as MigrationPolicy, Y as ONTOLOGY_ABSTAIN_SENTINEL, Z as ONTOLOGY_BACKFILL_BATCH_SIZE, _ as ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS, $ as ONTOLOGY_BACKFILL_RECHECK_MS, a0 as OntologyBackfillResult, a1 as OntologyEdgeType, a2 as OntologyManifest, a3 as OntologyNodeType, a4 as OntologyPromptContext, a5 as OntologyUpdates, a6 as PendingMaintenance, a7 as PendingMigrationWork, a8 as PendingSourceStatus, a9 as PromptOverrides, aa as PromptService, ab as PrunePartialFailureError, ac as ReembedResult, ad as RememberInput, ae as RunPendingMaintenanceOptions, af as RunPendingMaintenanceResult, ag as SourcePassage, ah as StoreSourceResult, ai as StoredSource, aj as StoredSourceDump, ak as StoredSourceSummary, al as SupersedeReplacement, am as SystemOneConfig, an as SystemOneThresholdSite, ao as VectorRanker, ap as VectorRankerFallback, aq as VectorRankerRankArgs, ar as VectorRankerSemanticResult, as as WikiBusyError, at as WikiBusyOperation, au as WikiCheckpoint, av as WikiDiagnostic, aw as WikiDiagnosticCode, ax as WikiDiagnosticDetail, ay as WikiDiagnosticOperation, az as WikiDiagnosticSeverity, aA as WikiDiagnosticTrigger, aB as WikiDraftNotFound, aC as WikiDuplicateHashError, aD as WikiEdge, aE as WikiEvent, aF as WikiExternalDeletionError, aG as WikiFact, aH as WikiGraphNodeOwnershipConflict, aI as WikiIngestEmptyError, aJ as WikiInstructions, aK as WikiInvalidReadOptions, aL as WikiLintReport, aM as WikiMemoryTestAccess, aN as WikiMigrationRequiredError, aO as WikiOutboxEvent, aP as WikiParseError, aQ as WikiSearchUnavailableError, aR as WikiSourcePointer, aS as WikiSourceRefHashCollision, aT as WikiStrictOntologyViolation, aU as WikiSupersedeError, aV as WikiSupersedeReason, aW as WikiTask, aX as WikiTransactionError, aY as isReservedAbstainSlug, aZ as isWikiSearchUnavailableError, a_ as validateManifest } from './testing-T0GgG1L6.js';
3
3
  import { OkfFile } from '@equationalapplications/core-okf';
4
4
 
5
5
  /**
@@ -62,6 +62,22 @@ declare const HEAL_MAX_FACT_BODY_CHARS_L3 = 4000;
62
62
  */
63
63
  declare const HEAL_MAX_TASKS = 50;
64
64
 
65
+ /**
66
+ * Default maximum characters per chunk that `ingestDocument` uses when a
67
+ * caller doesn't override `maxChunkLength` (directly or via
68
+ * `WikiOptions.config.maxChunkLength`).
69
+ */
70
+ declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
71
+ /**
72
+ * Default/fallback character overlap between consecutive chunks.
73
+ * `ingestDocument` uses this when a caller doesn't override `chunkOverlap`
74
+ * (directly or via `WikiOptions.config.chunkOverlap`), and clamps the
75
+ * effective overlap (including this default) to `maxChunkLength - 1` when
76
+ * needed. The clamp is a no-op for the shipped defaults; it can also apply
77
+ * when a custom `maxChunkLength` makes the resolved overlap too large.
78
+ */
79
+ declare const DEFAULT_CHUNK_OVERLAP = 400;
80
+
65
81
  declare function formatContext(bundle: MemoryBundle, options?: FormatContextOptions): string;
66
82
 
67
83
  /**
@@ -111,20 +127,32 @@ declare function validUsage(u: unknown): u is {
111
127
  };
112
128
 
113
129
  /**
114
- * Default maximum characters per chunk that `ingestDocument` uses when a
115
- * caller doesn't override `maxChunkLength` (directly or via
116
- * `WikiOptions.config.maxChunkLength`).
117
- */
118
- declare const DEFAULT_MAX_CHUNK_LENGTH = 12000;
119
- /**
120
- * Default/fallback character overlap between consecutive chunks.
121
- * `ingestDocument` uses this when a caller doesn't override `chunkOverlap`
122
- * (directly or via `WikiOptions.config.chunkOverlap`), and clamps the
123
- * effective overlap (including this default) to `maxChunkLength - 1` when
124
- * needed. The clamp is a no-op for the shipped defaults; it can also apply
125
- * when a custom `maxChunkLength` makes the resolved overlap too large.
126
- */
127
- declare const DEFAULT_CHUNK_OVERLAP = 400;
130
+ * Context-budget wrapper (specs/context-budget Proposed change 2).
131
+ *
132
+ * Core ships no tokenizer: every estimate is chars/`charsPerToken`. The
133
+ * meter keeps plain `estimateTokens` (chars/4) this PR — metering is out of
134
+ * scope — so `estimateTokensWith` under a legacy budget (`charsPerToken: 4`)
135
+ * is byte-equal to `estimateTokens` for every input, and the wrapper ships
136
+ * unused by metering.
137
+ */
138
+ interface ContextBudget {
139
+ mode: 'legacy' | 'declared';
140
+ /** Set iff mode === 'declared'. */
141
+ contextWindowTokens?: number;
142
+ /** 4 under legacy. */
143
+ charsPerToken: number;
144
+ /** 0.9 under legacy (unused in legacy math). */
145
+ safetyFraction: number;
146
+ /** 4000 under legacy (unused in legacy math). */
147
+ outputReserveTokens: number;
148
+ }
149
+ declare function estimateTokensWith(budget: ContextBudget, text: string): number;
150
+
151
+ type ContextBudgetOp = 'resolve' | 'heal' | 'extract';
152
+ declare function resolveContextBudget(config: WikiConfig | undefined): ContextBudget;
153
+ declare function resolveMaxPromptChars(budget: ContextBudget, op: ContextBudgetOp): number;
154
+ /** The ingest chunk default stays 12000 in both modes (ruling R2). */
155
+ declare function resolveDefaultChunkLength(budget: ContextBudget): number;
128
156
 
129
157
  /**
130
158
  * Default clamp on embed input length, in characters (~1,500 tokens).
@@ -217,5 +245,5 @@ declare const ONTOLOGY_BACKFILL_SYSTEM_PROMPT = "You are a knowledge classificat
217
245
 
218
246
  declare function createWiki(db: SQLiteAdapter, options: WikiOptions): WikiMemory;
219
247
 
220
- export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
221
- export type { FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
248
+ export { DEFAULT_CHUNK_OVERLAP, DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT, DEFAULT_MAX_CHUNK_LENGTH, DEFAULT_MAX_EMBED_CHARS, DEFAULT_ONTOLOGY_JOB_BATCH_SIZE, DEFAULT_SETUP_BUDGET_MS, DEFAULT_TYPING_MIN_CONFIDENCE, EMBED_CHARS_CEILING, FormatContextOptions, FormattedMemoryDump, GraphNeighborhood, HEAL_ANCHORS_PER_CANDIDATE, HEAL_MAX_FACT_BODY_CHARS_L3, HEAL_MAX_TASKS, MemoryBundle, MemoryDump, ONTOLOGY_BACKFILL_SYSTEM_PROMPT, OntologyConfig, OntologyMode, ReadOptions, SQLiteAdapter, WikiConfig, WikiMemory, WikiOptions, buildOntologyPromptAppendix, chunkText, configureRandomSource, createWiki, estimateTokensWith, formatContext, formatGraphContext, formatMemoryDump, formatOkfBundle, hydrateLibrarianPrompt, mapLibrarianOptionsToReadOptions, parseEmbedding, parseOkfBundle, resolveContextBudget, resolveDefaultChunkLength, resolveMaxPromptChars, resolveOntologyJobDefaults, resolveSystemOneTyping, resolveTypingMinConfidence, safeSlice, validUsage, validateLibrarianPromptTemplate, warnOnce };
249
+ export type { ContextBudget, FormatOkfBundleOptions, LibrarianOptions, LibrarianPromptVariables, OkfFormatProfile, OkfImportOptions };
package/dist/index.js CHANGED
@@ -7889,6 +7889,74 @@ function toGroundingAnchor(anchor) {
7889
7889
  var DEFAULT_MAX_CHUNK_LENGTH = 12e3;
7890
7890
  var DEFAULT_CHUNK_OVERLAP = 400;
7891
7891
 
7892
+ // src/utils/contextCaps.ts
7893
+ var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
7894
+ var HEAL_MAX_PROMPT_CHARS = 4e4;
7895
+ var OPS_MAX_EXTRACT_CHARS = 24e3;
7896
+
7897
+ // src/config/context.ts
7898
+ var DEFAULT_CHARS_PER_TOKEN = 4;
7899
+ var DEFAULT_SAFETY_FRACTION = 0.9;
7900
+ var DEFAULT_OUTPUT_RESERVE_TOKENS = 4e3;
7901
+ var OP_FLOOR = {
7902
+ resolve: OPS_RESOLVE_MAX_PROMPT_CHARS,
7903
+ heal: HEAL_MAX_PROMPT_CHARS,
7904
+ extract: OPS_MAX_EXTRACT_CHARS
7905
+ };
7906
+ function bad(key, value, why) {
7907
+ return new Error(`[core-llm-wiki] config.context.${key} must be ${why}; received ${JSON.stringify(value)}`);
7908
+ }
7909
+ function resolveContextBudget(config) {
7910
+ const context = config?.context;
7911
+ if (!context || context.budget === void 0) {
7912
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
7913
+ }
7914
+ if (context.budget !== "legacy" && context.budget !== "declared") {
7915
+ throw bad("budget", context.budget, "'legacy' or 'declared'");
7916
+ }
7917
+ if (context.budget === "legacy") {
7918
+ return { mode: "legacy", charsPerToken: DEFAULT_CHARS_PER_TOKEN, safetyFraction: DEFAULT_SAFETY_FRACTION, outputReserveTokens: DEFAULT_OUTPUT_RESERVE_TOKENS };
7919
+ }
7920
+ const window = context.contextWindowTokens;
7921
+ if (window === void 0 || typeof window !== "number" || !Number.isFinite(window) || window <= 0) {
7922
+ throw bad("contextWindowTokens", window, "a finite number > 0 under budget: declared");
7923
+ }
7924
+ const charsPerToken = context.charsPerToken ?? DEFAULT_CHARS_PER_TOKEN;
7925
+ if (typeof charsPerToken !== "number" || !Number.isFinite(charsPerToken) || charsPerToken <= 0) {
7926
+ throw bad("charsPerToken", context.charsPerToken, "a finite number > 0");
7927
+ }
7928
+ const safetyFraction = context.safetyFraction ?? DEFAULT_SAFETY_FRACTION;
7929
+ if (typeof safetyFraction !== "number" || !Number.isFinite(safetyFraction) || safetyFraction <= 0 || safetyFraction > 1) {
7930
+ throw bad("safetyFraction", context.safetyFraction, "a finite number in (0, 1]");
7931
+ }
7932
+ const outputReserveTokens = context.outputReserveTokens ?? DEFAULT_OUTPUT_RESERVE_TOKENS;
7933
+ if (typeof outputReserveTokens !== "number" || !Number.isFinite(outputReserveTokens) || outputReserveTokens < 0 || outputReserveTokens >= window) {
7934
+ throw bad("outputReserveTokens", context.outputReserveTokens, `a finite number >= 0 and < contextWindowTokens (${window})`);
7935
+ }
7936
+ return { mode: "declared", contextWindowTokens: window, charsPerToken, safetyFraction, outputReserveTokens };
7937
+ }
7938
+ function declaredPromptCap(budget, op) {
7939
+ const derived = Math.floor(
7940
+ (budget.contextWindowTokens - budget.outputReserveTokens) * budget.safetyFraction * budget.charsPerToken
7941
+ );
7942
+ if (op === "resolve") return Math.max(OP_FLOOR.resolve, derived);
7943
+ return Math.max(OP_FLOOR.heal, derived);
7944
+ }
7945
+ function resolveMaxPromptChars(budget, op) {
7946
+ if (budget.mode !== "declared") {
7947
+ return op === "resolve" ? OP_FLOOR.resolve : op === "heal" ? OP_FLOOR.heal : OP_FLOOR.extract;
7948
+ }
7949
+ if (op === "extract") {
7950
+ const resolveDerived = declaredPromptCap(budget, "resolve");
7951
+ const extractDerived = Math.floor(resolveDerived * OPS_MAX_EXTRACT_CHARS / OPS_RESOLVE_MAX_PROMPT_CHARS);
7952
+ return Math.max(OP_FLOOR.extract, extractDerived);
7953
+ }
7954
+ return declaredPromptCap(budget, op);
7955
+ }
7956
+ function resolveDefaultChunkLength(budget) {
7957
+ return DEFAULT_MAX_CHUNK_LENGTH;
7958
+ }
7959
+
7892
7960
  // src/utils/usage.ts
7893
7961
  function estimateTokens(text) {
7894
7962
  return Math.ceil(text.length / 4);
@@ -8029,7 +8097,7 @@ var IngestionService = class {
8029
8097
  if (!sourceRef) throw new Error("Invalid sourceRef");
8030
8098
  const sourceHash = normalizeSourceHash(params.sourceHash);
8031
8099
  if (!sourceHash) throw new Error("Invalid sourceHash (must be 64-char hex string)");
8032
- const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? DEFAULT_MAX_CHUNK_LENGTH;
8100
+ const maxChunkLength = params.maxChunkLength ?? this.options.config?.maxChunkLength ?? resolveDefaultChunkLength(resolveContextBudget(this.options.config));
8033
8101
  const rawOverlap = params.chunkOverlap ?? this.options.config?.chunkOverlap ?? DEFAULT_CHUNK_OVERLAP;
8034
8102
  const chunkOverlap = Math.min(
8035
8103
  Number.isFinite(rawOverlap) && rawOverlap >= 0 ? Math.floor(rawOverlap) : DEFAULT_CHUNK_OVERLAP,
@@ -8815,6 +8883,9 @@ function resolveLibrarianStrategy(config) {
8815
8883
  function resolveMaintenanceMode(config) {
8816
8884
  return config?.maintenance ?? DEFAULT_MAINTENANCE_MODE;
8817
8885
  }
8886
+ function resolveContextBudgetOrThrow(config) {
8887
+ return resolveContextBudget(config);
8888
+ }
8818
8889
  function changedDefaultWarnings(config) {
8819
8890
  const warnings = [];
8820
8891
  const hasThreshold = config?.autoLibrarianThreshold !== void 0 || config?.autoHealThreshold !== void 0 || config?.autoLibrarianTokenThreshold !== void 0;
@@ -9821,18 +9892,18 @@ function parseValidFrom(v) {
9821
9892
 
9822
9893
  // src/services/librarian/ops/extract.ts
9823
9894
  var OPS_MAX_EVENTS_PER_PASS = 50;
9824
- var OPS_MAX_EXTRACT_CHARS = 24e3;
9825
9895
  var RESOLVE_RESERVE_FACTOR = 2;
9826
9896
  var MIN_SEGMENT_CHARS = 500;
9827
9897
  var MAX_SEGMENT_CALLS = 8;
9828
9898
  var estimatePrompt = (p) => estimateTokens(p.systemPrompt) + estimateTokens(p.userPrompt);
9829
- async function selectBatch(deps, entityId, wm, meter, guidance) {
9899
+ async function selectBatch(deps, entityId, wm, meter, guidance, budget) {
9830
9900
  const events = await deps.eventRepo.getAfter(entityId, wm, OPS_MAX_EVENTS_PER_PASS);
9831
9901
  if (events.length === 0) return { batch: [] };
9902
+ const extractCap = resolveMaxPromptChars(budget ?? { mode: "legacy", charsPerToken: 4, safetyFraction: 0.9, outputReserveTokens: 4e3 }, "extract");
9832
9903
  let n = 0;
9833
9904
  let chars = 0;
9834
9905
  for (const e of events) {
9835
- if (n > 0 && chars + e.summary.length > OPS_MAX_EXTRACT_CHARS) break;
9906
+ if (n > 0 && chars + e.summary.length > extractCap) break;
9836
9907
  chars += e.summary.length;
9837
9908
  n++;
9838
9909
  }
@@ -10158,7 +10229,6 @@ async function gateCandidates(deps, ctx, candidates, cfg) {
10158
10229
  }
10159
10230
 
10160
10231
  // src/services/librarian/ops/resolve.ts
10161
- var OPS_RESOLVE_MAX_PROMPT_CHARS = 4e4;
10162
10232
  function validateOp(raw, aliases) {
10163
10233
  if (!raw || typeof raw !== "object") return null;
10164
10234
  const r = raw;
@@ -10177,7 +10247,7 @@ function validateOp(raw, aliases) {
10177
10247
  return update;
10178
10248
  }
10179
10249
  var aliasMapOf = (g) => new Map(g.neighbours.map((n) => [n.ref, n.id]));
10180
- async function runResolve(deps, ctx, ambiguous) {
10250
+ async function runResolve(deps, ctx, ambiguous, budget) {
10181
10251
  const out = { ops: /* @__PURE__ */ new Map(), rejected: [], failed: [], overflowSkipped: [] };
10182
10252
  if (ambiguous.length === 0) return out;
10183
10253
  const { entityId, trigger } = ctx;
@@ -10203,7 +10273,7 @@ async function runResolve(deps, ctx, ambiguous) {
10203
10273
  onSkip: (g, err) => {
10204
10274
  if (isContextOverflowError(err)) out.overflowSkipped.push(g.candidate.index);
10205
10275
  },
10206
- maxPromptChars: OPS_RESOLVE_MAX_PROMPT_CHARS,
10276
+ maxPromptChars: budget ? resolveMaxPromptChars(budget, "resolve") : OPS_RESOLVE_MAX_PROMPT_CHARS,
10207
10277
  maxOutputTokens: deps.options.llmProvider.maxOutputTokens
10208
10278
  });
10209
10279
  if (outcome.budgetStop) return { ...out, budgetStop: outcome.budgetStop };
@@ -10412,7 +10482,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10412
10482
  const cfg = resolveGateConfig(deps.options.config?.librarian?.gate);
10413
10483
  await deps.seedWatermark(entityId);
10414
10484
  const wm = await deps.getWatermark(entityId);
10415
- const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance);
10485
+ const sel = await selectBatch(deps, entityId, wm, ctx.meter, ctx.guidance, resolveContextBudget(deps.options.config));
10416
10486
  if ("budgetStop" in sel) return { processedThrough: null, factsWritten: 0, budgetStop: sel.budgetStop };
10417
10487
  if (sel.batch.length === 0) return { processedThrough: null, factsWritten: 0 };
10418
10488
  if (!deps.searchService.isKeywordAvailable() && await gateNeedsKeyword(deps, entityId)) {
@@ -10440,7 +10510,7 @@ var runOpsLibrarianPass = async (deps, ctx) => {
10440
10510
  });
10441
10511
  }
10442
10512
  diagnostics.push(gateDiagnostic);
10443
- const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"));
10513
+ const res = await runResolve(deps, ctx, gated.filter((g) => g.decision.kind === "ambiguous"), resolveContextBudget(deps.options.config));
10444
10514
  for (const itemIndex of res.overflowSkipped) {
10445
10515
  diagnostics.push({
10446
10516
  entityId,
@@ -10509,7 +10579,6 @@ var ONTOLOGY_BACKFILL_MAX_PROMPT_CHARS = 4e4;
10509
10579
  var ONTOLOGY_BACKFILL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10510
10580
  var CLASSIFIER_MAX_CHOICES = 255;
10511
10581
  var HEAL_ANCHOR_SEARCH_OVERFETCH = 4;
10512
- var HEAL_MAX_PROMPT_CHARS = 4e4;
10513
10582
  var HEAL_BATCH_SIZE = 25;
10514
10583
  var HEAL_RECHECK_MS = 7 * 24 * 60 * 60 * 1e3;
10515
10584
  var MAX_EMBED_ATTEMPTS = 5;
@@ -11813,7 +11882,7 @@ DROP TRIGGER IF EXISTS ${ad};`);
11813
11882
  };
11814
11883
  },
11815
11884
  maxOutputTokens: this.options.llmProvider.maxOutputTokens,
11816
- maxPromptChars: HEAL_MAX_PROMPT_CHARS,
11885
+ maxPromptChars: resolveMaxPromptChars(resolveContextBudget(this.options.config), "heal"),
11817
11886
  // heal's buildPrompt sheds anchors per attemptLevel — escalation is real (errata E2)
11818
11887
  supportsEscalation: true,
11819
11888
  onSkip: (fact, err) => {
@@ -15570,6 +15639,7 @@ var WikiMemory = class {
15570
15639
  this.db = withSerializedTransactions(db);
15571
15640
  this.options = options;
15572
15641
  warnChangedDefaultsOnce(options.config);
15642
+ resolveContextBudgetOrThrow(options.config);
15573
15643
  this.prefix = options.config?.tablePrefix ?? "llm_wiki_";
15574
15644
  if (!TABLE_PREFIX_PATTERN.test(this.prefix)) {
15575
15645
  throw new Error(
@@ -17686,6 +17756,11 @@ function parseOkfBundle(entityId, files, options) {
17686
17756
  };
17687
17757
  }
17688
17758
 
17759
+ // src/utils/contextBudget.ts
17760
+ function estimateTokensWith(budget, text) {
17761
+ return Math.ceil(text.length / budget.charsPerToken);
17762
+ }
17763
+
17689
17764
  // src/librarianPrompt.ts
17690
17765
  var DEFAULT_LIBRARIAN_SYNTHESIS_PROMPT = `You are a careful memory synthesis assistant.
17691
17766
  Use only the retrieved context when answering the request.
@@ -17773,6 +17848,7 @@ exports.buildOntologyPromptAppendix = buildOntologyPromptAppendix;
17773
17848
  exports.chunkText = chunkText;
17774
17849
  exports.configureRandomSource = configureRandomSource;
17775
17850
  exports.createWiki = createWiki;
17851
+ exports.estimateTokensWith = estimateTokensWith;
17776
17852
  exports.formatContext = formatContext;
17777
17853
  exports.formatGraphContext = formatGraphContext;
17778
17854
  exports.formatMemoryDump = formatMemoryDump;
@@ -17783,6 +17859,9 @@ exports.isWikiSearchUnavailableError = isWikiSearchUnavailableError;
17783
17859
  exports.mapLibrarianOptionsToReadOptions = mapLibrarianOptionsToReadOptions;
17784
17860
  exports.parseEmbedding = parseEmbedding;
17785
17861
  exports.parseOkfBundle = parseOkfBundle;
17862
+ exports.resolveContextBudget = resolveContextBudget;
17863
+ exports.resolveDefaultChunkLength = resolveDefaultChunkLength;
17864
+ exports.resolveMaxPromptChars = resolveMaxPromptChars;
17786
17865
  exports.resolveOntologyJobDefaults = resolveOntologyJobDefaults;
17787
17866
  exports.resolveSystemOneTyping = resolveSystemOneTyping;
17788
17867
  exports.resolveTypingMinConfidence = resolveTypingMinConfidence;