@warmdrift/kgauto-compiler 2.0.0-alpha.3

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.
@@ -0,0 +1,99 @@
1
+ /**
2
+ * kgauto dialect-v1 — the cross-app vocabulary.
3
+ *
4
+ * For learnings to flow between apps, every app must speak the same vocabulary
5
+ * about (a) what kind of work it's asking for and (b) the rough shape of the
6
+ * call. This file is that vocabulary. It is versioned.
7
+ *
8
+ * Two primitives:
9
+ * - IntentArchetype: WHAT the call is doing (semantic category)
10
+ * - ShapeSignature: HOW the call is shaped (size, tools, history, output)
11
+ *
12
+ * The brain learns by `(archetype, model, shape)` tuples. Apps that declare
13
+ * the same tuple inherit each other's mutations.
14
+ *
15
+ * v1 is intentionally small (9 archetypes, 5 shape dimensions). New entries
16
+ * arrive in v2/v3 from real usage signals — never speculatively.
17
+ */
18
+ declare const DIALECT_VERSION: "v1";
19
+ declare const INTENT_ARCHETYPES: {
20
+ readonly ask: {
21
+ readonly name: "ask";
22
+ readonly description: "Filter, search, or interrogate existing data";
23
+ readonly examples: ["filter creators by criteria", "find docs matching query", "lookup a record"];
24
+ };
25
+ readonly hunt: {
26
+ readonly name: "hunt";
27
+ readonly description: "Discover new entities not in the current dataset";
28
+ readonly examples: ["find new prospects", "crawl for unindexed sources", "expand a seed list"];
29
+ };
30
+ readonly classify: {
31
+ readonly name: "classify";
32
+ readonly description: "Assign a category from a finite set";
33
+ readonly examples: ["intent detection", "sentiment", "route-to-team"];
34
+ };
35
+ readonly summarize: {
36
+ readonly name: "summarize";
37
+ readonly description: "Compress text or data while preserving meaning";
38
+ readonly examples: ["dashboard insight", "meeting notes", "briefing"];
39
+ };
40
+ readonly generate: {
41
+ readonly name: "generate";
42
+ readonly description: "Produce new content from a prompt or template";
43
+ readonly examples: ["draft email", "create marketing copy", "co-founder conversation"];
44
+ };
45
+ readonly extract: {
46
+ readonly name: "extract";
47
+ readonly description: "Pull structured data from unstructured input";
48
+ readonly examples: ["parse invoice", "extract entities", "transcript → action items"];
49
+ };
50
+ readonly plan: {
51
+ readonly name: "plan";
52
+ readonly description: "Multi-step decomposition of a goal";
53
+ readonly examples: ["build a roadmap", "sequence tasks", "break a feature into steps"];
54
+ };
55
+ readonly critique: {
56
+ readonly name: "critique";
57
+ readonly description: "Quality assessment, review, or scoring";
58
+ readonly examples: ["code review", "design feedback", "oracle judgment"];
59
+ };
60
+ readonly transform: {
61
+ readonly name: "transform";
62
+ readonly description: "Change format or style while preserving content";
63
+ readonly examples: ["markdown → html", "formal → casual", "translate"];
64
+ };
65
+ };
66
+ type IntentArchetypeName = keyof typeof INTENT_ARCHETYPES;
67
+ declare const ALL_ARCHETYPES: IntentArchetypeName[];
68
+ declare function isArchetype(name: string): name is IntentArchetypeName;
69
+ type ContextBucket = 'tiny' | 'small' | 'medium' | 'large' | 'huge';
70
+ type ToolCountBucket = 'none' | 'few' | 'many' | 'massive';
71
+ type HistoryDepth = 'single_turn' | 'short' | 'long';
72
+ type OutputMode = 'text' | 'json' | 'tool_call';
73
+ interface ShapeSignature {
74
+ /** Log-binned input token count. */
75
+ contextBucket: ContextBucket;
76
+ /** Tool count bucket. */
77
+ toolCountBucket: ToolCountBucket;
78
+ /** Conversation depth. */
79
+ historyDepth: HistoryDepth;
80
+ /** Expected output shape. */
81
+ outputMode: OutputMode;
82
+ /** Whether the prompt includes few-shot examples. */
83
+ hasExamples: boolean;
84
+ }
85
+ declare function bucketContext(tokens: number): ContextBucket;
86
+ declare function bucketToolCount(count: number): ToolCountBucket;
87
+ declare function bucketHistory(turnCount: number): HistoryDepth;
88
+ /**
89
+ * Hash a shape signature into a compact string key. Stable across runs.
90
+ * Format: `<context>-<tools>-<history>-<output>-<examples>`.
91
+ */
92
+ declare function hashShape(s: ShapeSignature): string;
93
+ /**
94
+ * Compose the full learning key. This is what the brain learns by — a tuple
95
+ * any app can produce and any app can benefit from.
96
+ */
97
+ declare function learningKey(archetype: IntentArchetypeName, model: string, shape: ShapeSignature): string;
98
+
99
+ export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey };
@@ -0,0 +1,99 @@
1
+ /**
2
+ * kgauto dialect-v1 — the cross-app vocabulary.
3
+ *
4
+ * For learnings to flow between apps, every app must speak the same vocabulary
5
+ * about (a) what kind of work it's asking for and (b) the rough shape of the
6
+ * call. This file is that vocabulary. It is versioned.
7
+ *
8
+ * Two primitives:
9
+ * - IntentArchetype: WHAT the call is doing (semantic category)
10
+ * - ShapeSignature: HOW the call is shaped (size, tools, history, output)
11
+ *
12
+ * The brain learns by `(archetype, model, shape)` tuples. Apps that declare
13
+ * the same tuple inherit each other's mutations.
14
+ *
15
+ * v1 is intentionally small (9 archetypes, 5 shape dimensions). New entries
16
+ * arrive in v2/v3 from real usage signals — never speculatively.
17
+ */
18
+ declare const DIALECT_VERSION: "v1";
19
+ declare const INTENT_ARCHETYPES: {
20
+ readonly ask: {
21
+ readonly name: "ask";
22
+ readonly description: "Filter, search, or interrogate existing data";
23
+ readonly examples: ["filter creators by criteria", "find docs matching query", "lookup a record"];
24
+ };
25
+ readonly hunt: {
26
+ readonly name: "hunt";
27
+ readonly description: "Discover new entities not in the current dataset";
28
+ readonly examples: ["find new prospects", "crawl for unindexed sources", "expand a seed list"];
29
+ };
30
+ readonly classify: {
31
+ readonly name: "classify";
32
+ readonly description: "Assign a category from a finite set";
33
+ readonly examples: ["intent detection", "sentiment", "route-to-team"];
34
+ };
35
+ readonly summarize: {
36
+ readonly name: "summarize";
37
+ readonly description: "Compress text or data while preserving meaning";
38
+ readonly examples: ["dashboard insight", "meeting notes", "briefing"];
39
+ };
40
+ readonly generate: {
41
+ readonly name: "generate";
42
+ readonly description: "Produce new content from a prompt or template";
43
+ readonly examples: ["draft email", "create marketing copy", "co-founder conversation"];
44
+ };
45
+ readonly extract: {
46
+ readonly name: "extract";
47
+ readonly description: "Pull structured data from unstructured input";
48
+ readonly examples: ["parse invoice", "extract entities", "transcript → action items"];
49
+ };
50
+ readonly plan: {
51
+ readonly name: "plan";
52
+ readonly description: "Multi-step decomposition of a goal";
53
+ readonly examples: ["build a roadmap", "sequence tasks", "break a feature into steps"];
54
+ };
55
+ readonly critique: {
56
+ readonly name: "critique";
57
+ readonly description: "Quality assessment, review, or scoring";
58
+ readonly examples: ["code review", "design feedback", "oracle judgment"];
59
+ };
60
+ readonly transform: {
61
+ readonly name: "transform";
62
+ readonly description: "Change format or style while preserving content";
63
+ readonly examples: ["markdown → html", "formal → casual", "translate"];
64
+ };
65
+ };
66
+ type IntentArchetypeName = keyof typeof INTENT_ARCHETYPES;
67
+ declare const ALL_ARCHETYPES: IntentArchetypeName[];
68
+ declare function isArchetype(name: string): name is IntentArchetypeName;
69
+ type ContextBucket = 'tiny' | 'small' | 'medium' | 'large' | 'huge';
70
+ type ToolCountBucket = 'none' | 'few' | 'many' | 'massive';
71
+ type HistoryDepth = 'single_turn' | 'short' | 'long';
72
+ type OutputMode = 'text' | 'json' | 'tool_call';
73
+ interface ShapeSignature {
74
+ /** Log-binned input token count. */
75
+ contextBucket: ContextBucket;
76
+ /** Tool count bucket. */
77
+ toolCountBucket: ToolCountBucket;
78
+ /** Conversation depth. */
79
+ historyDepth: HistoryDepth;
80
+ /** Expected output shape. */
81
+ outputMode: OutputMode;
82
+ /** Whether the prompt includes few-shot examples. */
83
+ hasExamples: boolean;
84
+ }
85
+ declare function bucketContext(tokens: number): ContextBucket;
86
+ declare function bucketToolCount(count: number): ToolCountBucket;
87
+ declare function bucketHistory(turnCount: number): HistoryDepth;
88
+ /**
89
+ * Hash a shape signature into a compact string key. Stable across runs.
90
+ * Format: `<context>-<tools>-<history>-<output>-<examples>`.
91
+ */
92
+ declare function hashShape(s: ShapeSignature): string;
93
+ /**
94
+ * Compose the full learning key. This is what the brain learns by — a tuple
95
+ * any app can produce and any app can benefit from.
96
+ */
97
+ declare function learningKey(archetype: IntentArchetypeName, model: string, shape: ShapeSignature): string;
98
+
99
+ export { ALL_ARCHETYPES, type ContextBucket, DIALECT_VERSION, type HistoryDepth, INTENT_ARCHETYPES, type IntentArchetypeName, type OutputMode, type ShapeSignature, type ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey };
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/dialect.ts
21
+ var dialect_exports = {};
22
+ __export(dialect_exports, {
23
+ ALL_ARCHETYPES: () => ALL_ARCHETYPES,
24
+ DIALECT_VERSION: () => DIALECT_VERSION,
25
+ INTENT_ARCHETYPES: () => INTENT_ARCHETYPES,
26
+ bucketContext: () => bucketContext,
27
+ bucketHistory: () => bucketHistory,
28
+ bucketToolCount: () => bucketToolCount,
29
+ hashShape: () => hashShape,
30
+ isArchetype: () => isArchetype,
31
+ learningKey: () => learningKey
32
+ });
33
+ module.exports = __toCommonJS(dialect_exports);
34
+ var DIALECT_VERSION = "v1";
35
+ var INTENT_ARCHETYPES = {
36
+ ask: {
37
+ name: "ask",
38
+ description: "Filter, search, or interrogate existing data",
39
+ examples: ["filter creators by criteria", "find docs matching query", "lookup a record"]
40
+ },
41
+ hunt: {
42
+ name: "hunt",
43
+ description: "Discover new entities not in the current dataset",
44
+ examples: ["find new prospects", "crawl for unindexed sources", "expand a seed list"]
45
+ },
46
+ classify: {
47
+ name: "classify",
48
+ description: "Assign a category from a finite set",
49
+ examples: ["intent detection", "sentiment", "route-to-team"]
50
+ },
51
+ summarize: {
52
+ name: "summarize",
53
+ description: "Compress text or data while preserving meaning",
54
+ examples: ["dashboard insight", "meeting notes", "briefing"]
55
+ },
56
+ generate: {
57
+ name: "generate",
58
+ description: "Produce new content from a prompt or template",
59
+ examples: ["draft email", "create marketing copy", "co-founder conversation"]
60
+ },
61
+ extract: {
62
+ name: "extract",
63
+ description: "Pull structured data from unstructured input",
64
+ examples: ["parse invoice", "extract entities", "transcript \u2192 action items"]
65
+ },
66
+ plan: {
67
+ name: "plan",
68
+ description: "Multi-step decomposition of a goal",
69
+ examples: ["build a roadmap", "sequence tasks", "break a feature into steps"]
70
+ },
71
+ critique: {
72
+ name: "critique",
73
+ description: "Quality assessment, review, or scoring",
74
+ examples: ["code review", "design feedback", "oracle judgment"]
75
+ },
76
+ transform: {
77
+ name: "transform",
78
+ description: "Change format or style while preserving content",
79
+ examples: ["markdown \u2192 html", "formal \u2192 casual", "translate"]
80
+ }
81
+ };
82
+ var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
83
+ function isArchetype(name) {
84
+ return name in INTENT_ARCHETYPES;
85
+ }
86
+ function bucketContext(tokens) {
87
+ if (tokens < 1e3) return "tiny";
88
+ if (tokens < 4e3) return "small";
89
+ if (tokens < 16e3) return "medium";
90
+ if (tokens < 64e3) return "large";
91
+ return "huge";
92
+ }
93
+ function bucketToolCount(count) {
94
+ if (count === 0) return "none";
95
+ if (count <= 5) return "few";
96
+ if (count <= 20) return "many";
97
+ return "massive";
98
+ }
99
+ function bucketHistory(turnCount) {
100
+ if (turnCount <= 1) return "single_turn";
101
+ if (turnCount <= 6) return "short";
102
+ return "long";
103
+ }
104
+ function hashShape(s) {
105
+ return [
106
+ s.contextBucket,
107
+ s.toolCountBucket,
108
+ s.historyDepth,
109
+ s.outputMode,
110
+ s.hasExamples ? "ex" : "no_ex"
111
+ ].join("-");
112
+ }
113
+ function learningKey(archetype, model, shape) {
114
+ return `${DIALECT_VERSION}::${archetype}::${model}::${hashShape(shape)}`;
115
+ }
116
+ // Annotate the CommonJS export names for ESM import in node:
117
+ 0 && (module.exports = {
118
+ ALL_ARCHETYPES,
119
+ DIALECT_VERSION,
120
+ INTENT_ARCHETYPES,
121
+ bucketContext,
122
+ bucketHistory,
123
+ bucketToolCount,
124
+ hashShape,
125
+ isArchetype,
126
+ learningKey
127
+ });
@@ -0,0 +1,22 @@
1
+ import {
2
+ ALL_ARCHETYPES,
3
+ DIALECT_VERSION,
4
+ INTENT_ARCHETYPES,
5
+ bucketContext,
6
+ bucketHistory,
7
+ bucketToolCount,
8
+ hashShape,
9
+ isArchetype,
10
+ learningKey
11
+ } from "./chunk-5TI6PNSK.mjs";
12
+ export {
13
+ ALL_ARCHETYPES,
14
+ DIALECT_VERSION,
15
+ INTENT_ARCHETYPES,
16
+ bucketContext,
17
+ bucketHistory,
18
+ bucketToolCount,
19
+ hashShape,
20
+ isArchetype,
21
+ learningKey
22
+ };
@@ -0,0 +1,238 @@
1
+ import { M as ModelProfile, C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult } from './profiles-BiyrF36f.mjs';
2
+ export { f as ALIASES, g as CacheStrategy, h as CallAttempt, i as CallError, j as CliffRule, k as Constraints, I as IntentDeclaration, L as LoweringSpec, l as Message, m as MutationApplied, n as NormalizedTokens, o as PromptSection, p as Provider, q as RecoveryRule, S as StructuredOutputCapability, r as SystemPromptMode, T as ToolCall, s as ToolDefinition, t as allProfiles, u as getProfile, v as profilesByProvider, w as tryGetProfile } from './profiles-BiyrF36f.mjs';
3
+ export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, IntentArchetypeName, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
4
+
5
+ /**
6
+ * compile() — the main orchestrator.
7
+ *
8
+ * Runs all passes in order, picks a target, lowers to wire format, returns
9
+ * a CompileResult the caller uses to make the actual provider call.
10
+ *
11
+ * Pure function in v2.0.0-alpha.1: no network, no I/O, no mutation cache yet.
12
+ * Mutation cache will be added in v2.1 when the brain has data to push.
13
+ */
14
+
15
+ interface CompileOptions {
16
+ /** Custom profile resolver — for tests or custom profile sets. */
17
+ profileResolver?: (id: string) => ModelProfile;
18
+ /** Tool relevance threshold (default 0.2). */
19
+ toolRelevanceThreshold?: number;
20
+ /** History compression — turns count threshold (default 8). */
21
+ compressHistoryAfter?: number;
22
+ /**
23
+ * Consumer-declared policy. Filters blocked models, enforces cost
24
+ * ceiling, boosts preferred. See CompilePolicy in ir.ts.
25
+ */
26
+ policy?: CompilePolicy;
27
+ }
28
+
29
+ /**
30
+ * execute() — fire a CompiledRequest at the right provider, normalize the
31
+ * response shape across providers.
32
+ *
33
+ * This is what call() composes with compile() to own the network round-trip.
34
+ * Pure-fetch consumers stop reinventing per-provider parsing.
35
+ *
36
+ * Error classification follows L-061: 429/5xx/timeout/model_not_found are
37
+ * retryable; auth/validation are terminal. The orchestrator (call.ts) walks
38
+ * fallbackChain on retryable; surfaces terminal immediately.
39
+ */
40
+
41
+ interface ExecuteOptions {
42
+ apiKeys?: ApiKeys;
43
+ fetchImpl?: typeof fetch;
44
+ providerOverrides?: ProviderOverrides;
45
+ }
46
+ interface ExecuteOk {
47
+ ok: true;
48
+ status: number;
49
+ response: NormalizedResponse;
50
+ }
51
+ interface ExecuteErr {
52
+ ok: false;
53
+ status: number;
54
+ errorType: 'retryable' | 'terminal';
55
+ errorCode: string;
56
+ message: string;
57
+ raw: unknown;
58
+ }
59
+ type ExecuteResult = ExecuteOk | ExecuteErr;
60
+ declare function execute(request: CompiledRequest, opts?: ExecuteOptions): Promise<ExecuteResult>;
61
+
62
+ /**
63
+ * call() — the high-level orchestrator that owns the network round-trip.
64
+ *
65
+ * call(ir) ≈ compile(ir) → execute(request) → normalize(response) → record(...)
66
+ *
67
+ * Plain-fetch consumers (playbacksam, future incantato/glass-box/ivypass) use
68
+ * call() instead of importing fetch and reinventing per-provider response
69
+ * parsing. AI-SDK consumers can keep using compile() unchanged — call() is a
70
+ * sibling, not a replacement.
71
+ *
72
+ * Retry/fallback: on a retryable error (429, 5xx, 404, network), walk
73
+ * CompileResult.fallbackChain by re-running compile() with forceModel set on
74
+ * each fallback target. Each fallback gets fresh cliffs + fresh lowering.
75
+ * Hard cap at fallbackChain.length + 1 attempts. Terminal errors short-circuit.
76
+ */
77
+
78
+ /**
79
+ * Compile, execute, normalize, record. Returns a CallResult once a provider
80
+ * actually serves the request. Throws CallError if the fallback chain is
81
+ * exhausted without success.
82
+ */
83
+ declare function call(ir: PromptIR, opts?: CallOptions): Promise<CallResult>;
84
+
85
+ /**
86
+ * Brain client — fire-and-forget telemetry to the central kgauto Supabase.
87
+ *
88
+ * The brain is the centralized learning store. Apps POST outcomes here;
89
+ * mutations flow back through a separate pull (in v2.1).
90
+ *
91
+ * Design: never blocks the caller. Failures are silent (logged via optional
92
+ * onError hook). Uses fetch() — works in Node 18+, Edge runtimes, and browsers.
93
+ */
94
+
95
+ interface BrainConfig {
96
+ /** Brain HTTP endpoint base URL (e.g., https://kgauto-brain.vercel.app/api). */
97
+ endpoint: string;
98
+ /** Bearer token for auth. */
99
+ apiKey?: string;
100
+ /** Optional error hook for debugging. Defaults to console.warn. */
101
+ onError?: (err: unknown) => void;
102
+ /** If true, records are sent synchronously and awaited (test mode). */
103
+ sync?: boolean;
104
+ /** Optional fetch override (for tests). */
105
+ fetchImpl?: typeof fetch;
106
+ }
107
+ declare function configureBrain(config: BrainConfig): void;
108
+ declare function clearBrain(): void;
109
+ /**
110
+ * Record the outcome of a compiled call. Fire-and-forget by default.
111
+ *
112
+ * Returns a Promise so callers in `sync` mode can await; in async mode the
113
+ * promise resolves immediately (after the request is queued) and any
114
+ * network error is swallowed/forwarded to onError.
115
+ */
116
+ declare function record(input: RecordInput): Promise<void>;
117
+
118
+ /**
119
+ * Oracle contract — how an app tells the brain whether a response was good.
120
+ *
121
+ * The brain learns from oracle scores. Apps provide an oracle function per
122
+ * intent (or one default). Without oracle scores the brain can still record
123
+ * structural metrics (tokens, latency, success) but mutations cannot fire —
124
+ * structural metrics aren't quality.
125
+ *
126
+ * Two oracle styles supported:
127
+ * 1. App-provided synchronous scorer: cheap, deterministic, app-specific.
128
+ * Examples: "did the SQL filter return non-empty?", "did the JSON parse?",
129
+ * "did the response cite a known source?".
130
+ * 2. LLM-as-judge async scorer: built into kgauto for cold-start use. Calls
131
+ * a frontier model with a comparison prompt and parses a score.
132
+ */
133
+
134
+ interface OracleContext {
135
+ /** App identifier. */
136
+ appId: string;
137
+ /** App-local intent name. */
138
+ intentName: string;
139
+ /** Canonical archetype. */
140
+ archetype: string;
141
+ /** The original user turn text. */
142
+ userTurn?: string;
143
+ /** The model's text response. */
144
+ response: string;
145
+ /** Whether tool calls were involved. */
146
+ hadTools: boolean;
147
+ /** Free-form metadata the caller can attach. */
148
+ meta?: Record<string, unknown>;
149
+ }
150
+ /** App-provided oracle: pure function (sync or async). */
151
+ type AppOracle = (ctx: OracleContext) => OracleScore | Promise<OracleScore>;
152
+ interface LLMJudgeOptions {
153
+ /** Function that calls the judge model. Caller wires their own SDK. */
154
+ judgeCall: (prompt: string) => Promise<string>;
155
+ /**
156
+ * The dimensions to score. Default: 4-dimension rubric (correctness,
157
+ * completeness, conciseness, format).
158
+ */
159
+ dimensions?: string[];
160
+ /** Hard cap on judge calls per minute (rate limiting). */
161
+ rateLimitPerMin?: number;
162
+ }
163
+ /**
164
+ * Build an LLM-as-judge oracle. Returns an AppOracle that asks the judge
165
+ * model to rate the response and parses a JSON score.
166
+ */
167
+ declare function buildLLMJudge(opts: LLMJudgeOptions): AppOracle;
168
+
169
+ /**
170
+ * Tokenizer abstraction.
171
+ *
172
+ * Default: char-based fallback (~4 chars/token, ±20% accuracy).
173
+ * Recommended: caller wires js-tiktoken or a provider-specific tokenizer
174
+ * via setTokenizer(). The compiler always calls countTokens(); the rest of
175
+ * the system never touches the implementation directly.
176
+ */
177
+ /**
178
+ * Wire a real tokenizer. Caller is responsible for picking one accurate
179
+ * enough for their dominant provider.
180
+ */
181
+ declare function setTokenizer(impl: (text: string) => number): void;
182
+ /**
183
+ * Reset to the char-based fallback. Useful in tests.
184
+ */
185
+ declare function resetTokenizer(): void;
186
+ /**
187
+ * Count tokens for a string. Wraps the configured implementation with
188
+ * safety (never throws, always returns ≥ 0 for non-empty input).
189
+ */
190
+ declare function countTokens(text: string): number;
191
+
192
+ /**
193
+ * @warmdrift/kgauto v2 — prompt compiler + central learning brain.
194
+ *
195
+ * Two functions you'll use most:
196
+ * compile(ir, opts?) → CompileResult
197
+ * record(input) → Promise<void>
198
+ *
199
+ * Plus:
200
+ * configureBrain({ endpoint, apiKey }) — point at the central brain
201
+ * buildLLMJudge({ judgeCall }) — cold-start oracle
202
+ *
203
+ * Quickstart:
204
+ *
205
+ * import { compile, record, configureBrain } from '@warmdrift/kgauto';
206
+ *
207
+ * configureBrain({ endpoint: 'https://kgauto-brain.vercel.app/api', apiKey: '...' });
208
+ *
209
+ * const r = compile({
210
+ * appId: 'my-app',
211
+ * intent: { name: 'search', archetype: 'ask' },
212
+ * sections: [
213
+ * { id: 'role', text: 'You are an assistant.', cacheable: true },
214
+ * { id: 'task', text: userQuestion },
215
+ * ],
216
+ * models: ['claude-sonnet-4-6', 'gemini-2.5-flash'],
217
+ * });
218
+ *
219
+ * const start = Date.now();
220
+ * const response = await callProvider(r.target, r.request);
221
+ *
222
+ * await record({
223
+ * handle: r.handle,
224
+ * tokensIn: response.usage.input,
225
+ * tokensOut: response.usage.output,
226
+ * latencyMs: Date.now() - start,
227
+ * success: true,
228
+ * oracleScore: { score: 0.85 },
229
+ * });
230
+ */
231
+
232
+ /**
233
+ * Compile a request. Wraps the pure compile() with brain registration so
234
+ * record() can find call metadata later.
235
+ */
236
+ declare function compile(ir: PromptIR, opts?: CompileOptions): CompileResult;
237
+
238
+ export { ApiKeys, type AppOracle, type BrainConfig, CallOptions, CallResult, type CompileOptions, CompilePolicy, CompileResult, CompiledRequest, type ExecuteErr, type ExecuteOk, type ExecuteOptions, type ExecuteResult, type LLMJudgeOptions, ModelProfile, NormalizedResponse, type OracleContext, OracleScore, PromptIR, ProviderOverrides, RecordInput, buildLLMJudge, call, clearBrain, compile, configureBrain, countTokens, execute, record, resetTokenizer, setTokenizer };