@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.
package/dist/index.js ADDED
@@ -0,0 +1,1804 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ALIASES: () => ALIASES,
24
+ ALL_ARCHETYPES: () => ALL_ARCHETYPES,
25
+ CallError: () => CallError,
26
+ DIALECT_VERSION: () => DIALECT_VERSION,
27
+ INTENT_ARCHETYPES: () => INTENT_ARCHETYPES,
28
+ allProfiles: () => allProfiles,
29
+ bucketContext: () => bucketContext,
30
+ bucketHistory: () => bucketHistory,
31
+ bucketToolCount: () => bucketToolCount,
32
+ buildLLMJudge: () => buildLLMJudge,
33
+ call: () => call,
34
+ clearBrain: () => clearBrain,
35
+ compile: () => compile2,
36
+ configureBrain: () => configureBrain,
37
+ countTokens: () => countTokens,
38
+ execute: () => execute,
39
+ getProfile: () => getProfile,
40
+ hashShape: () => hashShape,
41
+ isArchetype: () => isArchetype,
42
+ learningKey: () => learningKey,
43
+ profilesByProvider: () => profilesByProvider,
44
+ record: () => record,
45
+ resetTokenizer: () => resetTokenizer,
46
+ setTokenizer: () => setTokenizer,
47
+ tryGetProfile: () => tryGetProfile
48
+ });
49
+ module.exports = __toCommonJS(index_exports);
50
+
51
+ // src/tokenizer.ts
52
+ var tokenizerImpl = defaultCharBasedCounter;
53
+ function defaultCharBasedCounter(text) {
54
+ if (!text) return 0;
55
+ return Math.max(1, Math.ceil(text.length / 4));
56
+ }
57
+ function setTokenizer(impl) {
58
+ tokenizerImpl = impl;
59
+ }
60
+ function resetTokenizer() {
61
+ tokenizerImpl = defaultCharBasedCounter;
62
+ }
63
+ function countTokens(text) {
64
+ if (!text) return 0;
65
+ try {
66
+ const n = tokenizerImpl(text);
67
+ return Number.isFinite(n) && n >= 0 ? n : defaultCharBasedCounter(text);
68
+ } catch {
69
+ return defaultCharBasedCounter(text);
70
+ }
71
+ }
72
+ function countToolTokens(tool) {
73
+ const namePart = countTokens(tool.name);
74
+ const descPart = tool.description ? countTokens(tool.description) : 0;
75
+ const paramPart = tool.parameters ? countTokens(JSON.stringify(tool.parameters)) : 0;
76
+ return namePart + descPart + paramPart + 8;
77
+ }
78
+ function countMessagesTokens(messages) {
79
+ let total = 0;
80
+ for (const m of messages) {
81
+ total += countTokens(m.content) + 4;
82
+ }
83
+ return total;
84
+ }
85
+
86
+ // src/dialect.ts
87
+ var DIALECT_VERSION = "v1";
88
+ var INTENT_ARCHETYPES = {
89
+ ask: {
90
+ name: "ask",
91
+ description: "Filter, search, or interrogate existing data",
92
+ examples: ["filter creators by criteria", "find docs matching query", "lookup a record"]
93
+ },
94
+ hunt: {
95
+ name: "hunt",
96
+ description: "Discover new entities not in the current dataset",
97
+ examples: ["find new prospects", "crawl for unindexed sources", "expand a seed list"]
98
+ },
99
+ classify: {
100
+ name: "classify",
101
+ description: "Assign a category from a finite set",
102
+ examples: ["intent detection", "sentiment", "route-to-team"]
103
+ },
104
+ summarize: {
105
+ name: "summarize",
106
+ description: "Compress text or data while preserving meaning",
107
+ examples: ["dashboard insight", "meeting notes", "briefing"]
108
+ },
109
+ generate: {
110
+ name: "generate",
111
+ description: "Produce new content from a prompt or template",
112
+ examples: ["draft email", "create marketing copy", "co-founder conversation"]
113
+ },
114
+ extract: {
115
+ name: "extract",
116
+ description: "Pull structured data from unstructured input",
117
+ examples: ["parse invoice", "extract entities", "transcript \u2192 action items"]
118
+ },
119
+ plan: {
120
+ name: "plan",
121
+ description: "Multi-step decomposition of a goal",
122
+ examples: ["build a roadmap", "sequence tasks", "break a feature into steps"]
123
+ },
124
+ critique: {
125
+ name: "critique",
126
+ description: "Quality assessment, review, or scoring",
127
+ examples: ["code review", "design feedback", "oracle judgment"]
128
+ },
129
+ transform: {
130
+ name: "transform",
131
+ description: "Change format or style while preserving content",
132
+ examples: ["markdown \u2192 html", "formal \u2192 casual", "translate"]
133
+ }
134
+ };
135
+ var ALL_ARCHETYPES = Object.keys(INTENT_ARCHETYPES);
136
+ function isArchetype(name) {
137
+ return name in INTENT_ARCHETYPES;
138
+ }
139
+ function bucketContext(tokens) {
140
+ if (tokens < 1e3) return "tiny";
141
+ if (tokens < 4e3) return "small";
142
+ if (tokens < 16e3) return "medium";
143
+ if (tokens < 64e3) return "large";
144
+ return "huge";
145
+ }
146
+ function bucketToolCount(count) {
147
+ if (count === 0) return "none";
148
+ if (count <= 5) return "few";
149
+ if (count <= 20) return "many";
150
+ return "massive";
151
+ }
152
+ function bucketHistory(turnCount) {
153
+ if (turnCount <= 1) return "single_turn";
154
+ if (turnCount <= 6) return "short";
155
+ return "long";
156
+ }
157
+ function hashShape(s) {
158
+ return [
159
+ s.contextBucket,
160
+ s.toolCountBucket,
161
+ s.historyDepth,
162
+ s.outputMode,
163
+ s.hasExamples ? "ex" : "no_ex"
164
+ ].join("-");
165
+ }
166
+ function learningKey(archetype, model, shape) {
167
+ return `${DIALECT_VERSION}::${archetype}::${model}::${hashShape(shape)}`;
168
+ }
169
+
170
+ // src/passes.ts
171
+ function passSlice(ir) {
172
+ const intent = ir.intent.archetype;
173
+ const before = ir.sections.length;
174
+ const kept = ir.sections.filter((s) => !s.intents || s.intents.length === 0 || s.intents.includes(intent));
175
+ const dropped = before - kept.length;
176
+ if (dropped === 0) return { value: ir, mutations: [] };
177
+ return {
178
+ value: { ...ir, sections: kept },
179
+ mutations: [
180
+ {
181
+ id: `slice-${dropped}`,
182
+ source: "static_pass",
183
+ passName: "slice",
184
+ description: `Dropped ${dropped} of ${before} sections not tagged for intent=${intent}`
185
+ }
186
+ ]
187
+ };
188
+ }
189
+ function passDedupe(ir) {
190
+ const seen = /* @__PURE__ */ new Map();
191
+ const order = [];
192
+ for (const s of ir.sections) {
193
+ const key = simpleHash(s.text.trim());
194
+ if (!seen.has(key)) {
195
+ seen.set(key, s);
196
+ order.push(key);
197
+ }
198
+ }
199
+ const deduped = order.map((k) => seen.get(k));
200
+ const dropped = ir.sections.length - deduped.length;
201
+ if (dropped === 0) return { value: ir, mutations: [] };
202
+ return {
203
+ value: { ...ir, sections: deduped },
204
+ mutations: [
205
+ {
206
+ id: `dedupe-${dropped}`,
207
+ source: "static_pass",
208
+ passName: "dedupe",
209
+ description: `Removed ${dropped} duplicate section(s) (by text hash)`
210
+ }
211
+ ]
212
+ };
213
+ }
214
+ function passToolRelevance(ir, opts = {}) {
215
+ if (!ir.tools || ir.tools.length === 0) return { value: ir, mutations: [] };
216
+ const threshold = opts.threshold ?? 0.2;
217
+ const intent = ir.intent.archetype;
218
+ const scored = ir.tools.map((t) => {
219
+ const score = t.relevanceByIntent?.[intent] ?? 0.5;
220
+ return { tool: t, score };
221
+ });
222
+ const kept = scored.filter((s) => s.score >= threshold).sort((a, b) => b.score - a.score).map((s) => s.tool);
223
+ const limited = opts.maxKeep ? kept.slice(0, opts.maxKeep) : kept;
224
+ const dropped = ir.tools.length - limited.length;
225
+ if (dropped === 0) return { value: ir, mutations: [] };
226
+ return {
227
+ value: { ...ir, tools: limited },
228
+ mutations: [
229
+ {
230
+ id: `tool-relevance-${dropped}`,
231
+ source: "static_pass",
232
+ passName: "tool_relevance",
233
+ description: `Dropped ${dropped} of ${ir.tools.length} tools below relevance ${threshold} for intent=${intent}`
234
+ }
235
+ ]
236
+ };
237
+ }
238
+ function passCompressHistory(ir, opts = {}) {
239
+ const history = ir.history;
240
+ if (!history || history.length === 0) return { value: ir, mutations: [] };
241
+ const keepRecent = opts.keepRecent ?? 4;
242
+ const summarizeOlderThan = opts.summarizeOlderThan ?? 8;
243
+ if (history.length <= summarizeOlderThan) return { value: ir, mutations: [] };
244
+ const cutIndex = history.length - keepRecent;
245
+ const old = history.slice(0, cutIndex);
246
+ const recent = history.slice(cutIndex);
247
+ const userTurns = old.filter((m) => m.role === "user");
248
+ const firstUserLine = userTurns[0]?.content.split("\n")[0]?.slice(0, 200) ?? "";
249
+ const summary = {
250
+ role: "system",
251
+ content: `[Earlier conversation: ${old.length} turns omitted. First user message: "${firstUserLine}"]`
252
+ };
253
+ return {
254
+ value: { ...ir, history: [summary, ...recent] },
255
+ mutations: [
256
+ {
257
+ id: `compress-history-${old.length}`,
258
+ source: "static_pass",
259
+ passName: "compress_history",
260
+ description: `Compressed ${old.length} old turns into 1 summary line (kept ${keepRecent} recent)`
261
+ }
262
+ ]
263
+ };
264
+ }
265
+ function passApplyCliffs(ir, profile, estimatedInputTokens) {
266
+ const mutations = [];
267
+ const hints = { qualityWarning: [] };
268
+ let nextIR = ir;
269
+ for (const cliff of profile.cliffs) {
270
+ let triggered = false;
271
+ switch (cliff.metric) {
272
+ case "input_tokens":
273
+ triggered = estimatedInputTokens >= cliff.threshold;
274
+ break;
275
+ case "tool_count":
276
+ triggered = (nextIR.tools?.length ?? 0) >= cliff.threshold;
277
+ break;
278
+ case "history_turns":
279
+ triggered = (nextIR.history?.length ?? 0) >= cliff.threshold;
280
+ break;
281
+ case "thinking_with_short_output":
282
+ triggered = !!nextIR.constraints?.expectedShortOutput;
283
+ break;
284
+ }
285
+ if (triggered && cliff.whenIntent && nextIR.intent.archetype !== cliff.whenIntent) {
286
+ triggered = false;
287
+ }
288
+ if (!triggered) continue;
289
+ switch (cliff.action) {
290
+ case "drop_to_top_relevant": {
291
+ const targetCount = Math.min(
292
+ Math.floor(cliff.threshold * 0.75),
293
+ Math.max(1, Math.floor((nextIR.tools?.length ?? 0) / 2))
294
+ );
295
+ if (nextIR.tools && nextIR.tools.length > targetCount) {
296
+ const intent = nextIR.intent.archetype;
297
+ const scored = nextIR.tools.map((t) => ({ tool: t, score: t.relevanceByIntent?.[intent] ?? 0.5 })).sort((a, b) => b.score - a.score).slice(0, targetCount).map((s) => s.tool);
298
+ nextIR = { ...nextIR, tools: scored };
299
+ mutations.push({
300
+ id: `cliff-${cliff.metric}`,
301
+ source: "cliff_guard",
302
+ passName: "apply_cliffs",
303
+ description: `${profile.id}: ${cliff.reason}; trimmed tools to ${targetCount}`
304
+ });
305
+ }
306
+ break;
307
+ }
308
+ case "force_thinking_budget_zero":
309
+ hints.forceThinkingZero = true;
310
+ mutations.push({
311
+ id: `cliff-thinking-zero`,
312
+ source: "cliff_guard",
313
+ passName: "apply_cliffs",
314
+ description: `${profile.id}: ${cliff.reason}`
315
+ });
316
+ break;
317
+ case "force_terse_output":
318
+ hints.forceTerseOutput = true;
319
+ mutations.push({
320
+ id: `cliff-terse`,
321
+ source: "cliff_guard",
322
+ passName: "apply_cliffs",
323
+ description: `${profile.id}: ${cliff.reason}`
324
+ });
325
+ break;
326
+ case "downgrade_quality_warning":
327
+ hints.qualityWarning.push(cliff.reason);
328
+ mutations.push({
329
+ id: `cliff-quality-warning`,
330
+ source: "cliff_guard",
331
+ passName: "apply_cliffs",
332
+ description: `${profile.id}: ${cliff.reason}`
333
+ });
334
+ break;
335
+ case "escalate_target":
336
+ hints.escalateRequested = true;
337
+ mutations.push({
338
+ id: `cliff-escalate`,
339
+ source: "cliff_guard",
340
+ passName: "apply_cliffs",
341
+ description: `${profile.id}: ${cliff.reason}`
342
+ });
343
+ break;
344
+ case "strip_tools": {
345
+ const droppedCount = nextIR.tools?.length ?? 0;
346
+ if (droppedCount > 0) {
347
+ nextIR = { ...nextIR, tools: [] };
348
+ mutations.push({
349
+ id: `cliff-strip-tools${cliff.whenIntent ? `-${cliff.whenIntent}` : ""}`,
350
+ source: "cliff_guard",
351
+ passName: "apply_cliffs",
352
+ description: `${profile.id}: ${cliff.reason} \u2014 stripped ${droppedCount} tools`
353
+ });
354
+ }
355
+ break;
356
+ }
357
+ }
358
+ }
359
+ return { value: { ir: nextIR, loweringHints: hints }, mutations };
360
+ }
361
+ function passScoreTargets(ir, opts) {
362
+ const constraints = ir.constraints ?? {};
363
+ const policy = opts.policy ?? {};
364
+ const blockedSet = new Set(policy.blockedModels ?? []);
365
+ const preferredSet = new Set(policy.preferredModels ?? []);
366
+ const scores = [];
367
+ const policyMutations = [];
368
+ for (const modelId of ir.models) {
369
+ let profile;
370
+ try {
371
+ profile = opts.profilesById(modelId);
372
+ } catch {
373
+ scores.push({
374
+ modelId,
375
+ estimatedCostUsd: 0,
376
+ fits: false,
377
+ rejectReasons: ["unknown_model_id"],
378
+ qualityScore: 0,
379
+ rank: -Infinity
380
+ });
381
+ continue;
382
+ }
383
+ const reasons = [];
384
+ if (blockedSet.has(modelId)) {
385
+ reasons.push(`blocked_by_policy (consumer gated this model \u2014 see CompilePolicy.blockedModels)`);
386
+ }
387
+ if (opts.estimatedInputTokens > profile.maxContextTokens * 0.9) {
388
+ reasons.push(`exceeds context budget (${opts.estimatedInputTokens} > 0.9*${profile.maxContextTokens})`);
389
+ }
390
+ if ((ir.tools?.length ?? 0) > profile.maxTools) {
391
+ reasons.push(`exceeds maxTools (${ir.tools?.length} > ${profile.maxTools})`);
392
+ }
393
+ if (constraints.structuredOutput && profile.structuredOutput === "none") {
394
+ reasons.push(`structuredOutput requested but model has none`);
395
+ }
396
+ let qualityPenalty = 0;
397
+ for (const cliff of profile.cliffs) {
398
+ if (cliff.action !== "downgrade_quality_warning") continue;
399
+ let triggered = false;
400
+ if (cliff.metric === "input_tokens") triggered = opts.estimatedInputTokens >= cliff.threshold;
401
+ if (cliff.metric === "tool_count") triggered = (ir.tools?.length ?? 0) >= cliff.threshold;
402
+ if (triggered) qualityPenalty += 0.3;
403
+ }
404
+ const estimatedCostUsd = opts.estimatedInputTokens / 1e6 * profile.costInputPer1m;
405
+ if (policy.maxCostPerCallUsd !== void 0 && estimatedCostUsd > policy.maxCostPerCallUsd) {
406
+ reasons.push(
407
+ `exceeds_max_cost_per_call (estimated $${estimatedCostUsd.toFixed(4)} > policy ceiling $${policy.maxCostPerCallUsd.toFixed(4)})`
408
+ );
409
+ }
410
+ const baseQuality = profile.strengths.includes("reasoning") ? 0.85 : profile.strengths.includes("quality") ? 0.8 : 0.6;
411
+ const qualityScore = Math.max(0, baseQuality - qualityPenalty);
412
+ const callerOrderBoost = (ir.models.length - ir.models.indexOf(modelId)) * 0.1;
413
+ const costPenalty = estimatedCostUsd * 5;
414
+ const preferredBoost = preferredSet.has(modelId) ? 0.5 : 0;
415
+ const rank = qualityScore + callerOrderBoost - costPenalty - reasons.length * 10 + preferredBoost;
416
+ scores.push({
417
+ modelId,
418
+ estimatedCostUsd,
419
+ fits: reasons.length === 0,
420
+ rejectReasons: reasons,
421
+ qualityScore,
422
+ rank
423
+ });
424
+ if (blockedSet.has(modelId)) {
425
+ policyMutations.push({
426
+ id: `policy-blocked-${modelId}`,
427
+ source: "compile_policy",
428
+ passName: "score_targets",
429
+ description: `Model ${modelId} excluded by CompilePolicy.blockedModels`
430
+ });
431
+ }
432
+ if (policy.maxCostPerCallUsd !== void 0 && estimatedCostUsd > policy.maxCostPerCallUsd && !blockedSet.has(modelId)) {
433
+ policyMutations.push({
434
+ id: `policy-over-cost-${modelId}`,
435
+ source: "compile_policy",
436
+ passName: "score_targets",
437
+ description: `Model ${modelId} excluded \u2014 estimated cost $${estimatedCostUsd.toFixed(4)} exceeds policy ceiling $${policy.maxCostPerCallUsd.toFixed(4)}`
438
+ });
439
+ }
440
+ if (preferredSet.has(modelId) && reasons.length === 0) {
441
+ policyMutations.push({
442
+ id: `policy-preferred-${modelId}`,
443
+ source: "compile_policy",
444
+ passName: "score_targets",
445
+ description: `Model ${modelId} rank boosted by CompilePolicy.preferredModels`
446
+ });
447
+ }
448
+ }
449
+ return { value: scores, mutations: policyMutations };
450
+ }
451
+ function computeShape(ir, estimatedInputTokens) {
452
+ return {
453
+ contextBucket: bucketContext(estimatedInputTokens),
454
+ toolCountBucket: bucketToolCount(ir.tools?.length ?? 0),
455
+ historyDepth: bucketHistory(ir.history?.length ?? 0),
456
+ outputMode: ir.constraints?.structuredOutput ? "json" : ir.tools?.length ? "tool_call" : "text",
457
+ hasExamples: ir.sections.some((s) => /\bexample\b/i.test(s.id))
458
+ };
459
+ }
460
+ function estimateInputTokens(ir) {
461
+ const sectionTokens = ir.sections.reduce((sum, s) => sum + countTokens(s.text), 0);
462
+ const toolTokens = (ir.tools ?? []).reduce((sum, t) => sum + countToolTokens(t), 0);
463
+ const historyTokens = countMessagesTokens(ir.history ?? []);
464
+ const turnTokens = ir.currentTurn ? countTokens(ir.currentTurn.content) + 4 : 0;
465
+ return sectionTokens + toolTokens + historyTokens + turnTokens + 6;
466
+ }
467
+ function simpleHash(s) {
468
+ let h = 5381;
469
+ for (let i = 0; i < s.length; i++) {
470
+ h = (h << 5) + h + s.charCodeAt(i) | 0;
471
+ }
472
+ return (h >>> 0).toString(36);
473
+ }
474
+
475
+ // src/lower.ts
476
+ function lower(ir, profile, hints = {}) {
477
+ switch (profile.provider) {
478
+ case "anthropic":
479
+ return lowerAnthropic(ir, profile, hints);
480
+ case "google":
481
+ return lowerGoogle(ir, profile, hints);
482
+ case "openai":
483
+ return lowerOpenAI(ir, profile, hints);
484
+ case "deepseek":
485
+ return lowerDeepSeek(ir, profile);
486
+ default:
487
+ throw new Error(`No lowering implementation for provider: ${profile.provider}`);
488
+ }
489
+ }
490
+ function lowerAnthropic(ir, profile, hints) {
491
+ const systemBlocks = buildAnthropicSystemBlocks(ir.sections, profile);
492
+ const messages = buildAnthropicMessages(ir.history ?? [], ir.currentTurn);
493
+ const tools = ir.tools ? toAnthropicTools(ir.tools) : void 0;
494
+ const cacheableTokens = computeCacheableTokens(systemBlocks);
495
+ const cacheSavings = cacheableTokens / 1e6 * profile.costInputPer1m * (1 - (profile.lowering.cache.discount ?? 0.1));
496
+ return {
497
+ request: {
498
+ provider: "anthropic",
499
+ model: profile.id,
500
+ system: systemBlocks,
501
+ messages,
502
+ tools,
503
+ max_tokens: hints.forceTerseOutput ? 200 : Math.min(profile.maxOutputTokens, 4096)
504
+ },
505
+ diagnostics: {
506
+ cacheableTokens,
507
+ estimatedCacheSavingsUsd: cacheSavings
508
+ }
509
+ };
510
+ }
511
+ function buildAnthropicSystemBlocks(sections, profile) {
512
+ if (sections.length === 0) return [];
513
+ const ordered = sortSections(sections);
514
+ const minTokens = profile.lowering.cache.minTokens ?? 1024;
515
+ const cacheable = [];
516
+ const dynamic = [];
517
+ for (const s of ordered) {
518
+ if (s.cacheable) cacheable.push(s);
519
+ else dynamic.push(s);
520
+ }
521
+ const blocks = [];
522
+ if (cacheable.length > 0) {
523
+ const cacheText = cacheable.map((s) => s.text).join("\n\n");
524
+ const cacheTextTokens = countTokens(cacheText);
525
+ const block = {
526
+ type: "text",
527
+ text: cacheText
528
+ };
529
+ if (cacheTextTokens >= minTokens) {
530
+ block.cache_control = { type: "ephemeral" };
531
+ }
532
+ blocks.push(block);
533
+ }
534
+ for (const s of dynamic) {
535
+ blocks.push({ type: "text", text: s.text });
536
+ }
537
+ return blocks;
538
+ }
539
+ function buildAnthropicMessages(history, currentTurn) {
540
+ const out = [];
541
+ for (const m of history) {
542
+ if (m.role === "system") continue;
543
+ out.push({ role: m.role, content: m.parts ?? m.content });
544
+ }
545
+ if (currentTurn && currentTurn.role !== "system") {
546
+ out.push({ role: currentTurn.role, content: currentTurn.parts ?? currentTurn.content });
547
+ }
548
+ return out;
549
+ }
550
+ function toAnthropicTools(tools) {
551
+ return tools.map((t) => ({
552
+ name: t.name,
553
+ description: t.description ?? "",
554
+ input_schema: t.parameters ?? { type: "object", properties: {} }
555
+ }));
556
+ }
557
+ function computeCacheableTokens(blocks) {
558
+ let total = 0;
559
+ for (const b of blocks) {
560
+ if (b.cache_control) total += countTokens(b.text);
561
+ }
562
+ return total;
563
+ }
564
+ function lowerGoogle(ir, profile, hints) {
565
+ const ordered = sortSections(ir.sections);
566
+ const systemText = ordered.map((s) => s.text).join("\n\n");
567
+ const generationConfig = {};
568
+ if (hints.forceThinkingZero && profile.lowering.thinking) {
569
+ setNestedField(generationConfig, profile.lowering.thinking.field.replace(/^generationConfig\./, ""), 0);
570
+ }
571
+ if (hints.forceTerseOutput) {
572
+ generationConfig.maxOutputTokens = 200;
573
+ }
574
+ if (ir.constraints?.structuredOutput && profile.structuredOutput === "native") {
575
+ generationConfig.responseMimeType = "application/json";
576
+ }
577
+ const contents = buildGoogleContents(ir.history ?? [], ir.currentTurn);
578
+ const tools = ir.tools && ir.tools.length > 0 ? toGoogleTools(ir.tools) : void 0;
579
+ const cacheable = ordered.filter((s) => s.cacheable);
580
+ const cacheableTokens = cacheable.reduce((sum, s) => sum + countTokens(s.text), 0);
581
+ const minTokens = profile.lowering.cache.minTokens ?? 4096;
582
+ const meetsMin = cacheableTokens >= minTokens;
583
+ const cacheSavings = meetsMin ? cacheableTokens / 1e6 * profile.costInputPer1m * (1 - (profile.lowering.cache.discount ?? 0.25)) : 0;
584
+ return {
585
+ request: {
586
+ provider: "google",
587
+ model: profile.id,
588
+ systemInstruction: systemText ? { role: "system", parts: [{ text: systemText }] } : void 0,
589
+ contents,
590
+ tools,
591
+ generationConfig: Object.keys(generationConfig).length > 0 ? generationConfig : void 0
592
+ },
593
+ diagnostics: {
594
+ cacheableTokens: meetsMin ? cacheableTokens : 0,
595
+ estimatedCacheSavingsUsd: cacheSavings
596
+ }
597
+ };
598
+ }
599
+ function buildGoogleContents(history, currentTurn) {
600
+ const out = [];
601
+ for (const m of history) {
602
+ if (m.role === "system") continue;
603
+ out.push({
604
+ role: m.role === "assistant" ? "model" : m.role,
605
+ parts: m.parts ?? [{ text: m.content }]
606
+ });
607
+ }
608
+ if (currentTurn && currentTurn.role !== "system") {
609
+ out.push({
610
+ role: currentTurn.role === "assistant" ? "model" : currentTurn.role,
611
+ parts: currentTurn.parts ?? [{ text: currentTurn.content }]
612
+ });
613
+ }
614
+ return out;
615
+ }
616
+ function toGoogleTools(tools) {
617
+ return [
618
+ {
619
+ functionDeclarations: tools.map((t) => ({
620
+ name: t.name,
621
+ description: t.description ?? "",
622
+ parameters: t.parameters ?? { type: "object", properties: {} }
623
+ }))
624
+ }
625
+ ];
626
+ }
627
+ function lowerOpenAI(ir, profile, hints) {
628
+ const ordered = sortSections(ir.sections);
629
+ const systemText = ordered.map((s) => s.text).join("\n\n");
630
+ const systemRole = profile.systemPromptMode === "as_developer" ? "developer" : "system";
631
+ const messages = systemText ? [{ role: systemRole, content: systemText }] : [];
632
+ for (const m of ir.history ?? []) {
633
+ if (m.role === "system") continue;
634
+ messages.push({ role: m.role, content: m.parts ?? m.content });
635
+ }
636
+ if (ir.currentTurn && ir.currentTurn.role !== "system") {
637
+ messages.push({
638
+ role: ir.currentTurn.role,
639
+ content: ir.currentTurn.parts ?? ir.currentTurn.content
640
+ });
641
+ }
642
+ return {
643
+ request: {
644
+ provider: "openai",
645
+ model: profile.id,
646
+ messages,
647
+ tools: ir.tools && ir.tools.length > 0 ? toOpenAITools(ir.tools) : void 0,
648
+ response_format: ir.constraints?.structuredOutput ? { type: "json_object" } : void 0,
649
+ reasoning_effort: hints.forceTerseOutput ? "low" : void 0
650
+ },
651
+ diagnostics: { cacheableTokens: 0, estimatedCacheSavingsUsd: 0 }
652
+ };
653
+ }
654
+ function toOpenAITools(tools) {
655
+ return tools.map((t) => ({
656
+ type: "function",
657
+ function: {
658
+ name: t.name,
659
+ description: t.description ?? "",
660
+ parameters: t.parameters ?? { type: "object", properties: {} }
661
+ }
662
+ }));
663
+ }
664
+ function lowerDeepSeek(ir, profile) {
665
+ const ordered = sortSections(ir.sections);
666
+ const systemText = ordered.map((s) => s.text).join("\n\n");
667
+ const messages = systemText ? [{ role: "system", content: systemText }] : [];
668
+ for (const m of ir.history ?? []) {
669
+ if (m.role === "system") continue;
670
+ messages.push({ role: m.role, content: m.parts ?? m.content });
671
+ }
672
+ if (ir.currentTurn && ir.currentTurn.role !== "system") {
673
+ messages.push({
674
+ role: ir.currentTurn.role,
675
+ content: ir.currentTurn.parts ?? ir.currentTurn.content
676
+ });
677
+ }
678
+ return {
679
+ request: {
680
+ provider: "deepseek",
681
+ model: profile.id,
682
+ messages,
683
+ tools: ir.tools && ir.tools.length > 0 ? ir.tools.slice(0, 1).map((t) => ({
684
+ type: "function",
685
+ function: {
686
+ name: t.name,
687
+ description: t.description ?? "",
688
+ parameters: t.parameters ?? { type: "object", properties: {} }
689
+ }
690
+ })) : void 0
691
+ },
692
+ diagnostics: { cacheableTokens: 0, estimatedCacheSavingsUsd: 0 }
693
+ };
694
+ }
695
+ function sortSections(sections) {
696
+ return [...sections].sort((a, b) => {
697
+ const wa = a.weight ?? 100;
698
+ const wb = b.weight ?? 100;
699
+ return wa - wb;
700
+ });
701
+ }
702
+ function setNestedField(obj, path, value) {
703
+ const parts = path.split(".");
704
+ let cursor = obj;
705
+ for (let i = 0; i < parts.length - 1; i++) {
706
+ const key = parts[i];
707
+ if (!(key in cursor) || typeof cursor[key] !== "object" || cursor[key] === null) {
708
+ cursor[key] = {};
709
+ }
710
+ cursor = cursor[key];
711
+ }
712
+ cursor[parts[parts.length - 1]] = value;
713
+ }
714
+
715
+ // src/profiles.ts
716
+ var ANTHROPIC_LOWERING_BASE = {
717
+ system: { mode: "inline" },
718
+ cache: {
719
+ strategy: "cache_control",
720
+ minTokens: 1024,
721
+ discount: 0.1,
722
+ ttlSeconds: 300
723
+ },
724
+ tools: { format: "anthropic" }
725
+ };
726
+ var GOOGLE_LOWERING_BASE = {
727
+ system: { mode: "separate", field: "systemInstruction" },
728
+ cache: {
729
+ strategy: "cachedContent",
730
+ minTokens: 4096,
731
+ discount: 0.25,
732
+ ttlSeconds: 3600
733
+ },
734
+ tools: { format: "google" }
735
+ };
736
+ var PROFILES_RAW = [
737
+ // ── Anthropic ──
738
+ {
739
+ id: "claude-opus-4-7",
740
+ verifiedAgainstDocs: "2026-05-08",
741
+ provider: "anthropic",
742
+ status: "current",
743
+ maxContextTokens: 1e6,
744
+ maxOutputTokens: 128e3,
745
+ maxTools: 64,
746
+ parallelToolCalls: true,
747
+ structuredOutput: "grammar",
748
+ systemPromptMode: "inline",
749
+ streaming: true,
750
+ cliffs: [],
751
+ costInputPer1m: 5,
752
+ costOutputPer1m: 25,
753
+ lowering: ANTHROPIC_LOWERING_BASE,
754
+ recovery: [
755
+ {
756
+ signal: "rate_limit",
757
+ action: "escalate",
758
+ reason: "429 from Anthropic \u2014 escalate to fallback chain"
759
+ },
760
+ {
761
+ signal: "model_not_found",
762
+ action: "escalate",
763
+ reason: "Model deprecated/renamed \u2014 escalate (L-061)"
764
+ }
765
+ ],
766
+ strengths: ["reasoning", "agentic_coding", "long_context", "reliable_tool_use", "structured_output"],
767
+ weaknesses: ["cost", "latency"],
768
+ notes: "Frontier (2026-05). Step-change improvement over 4.6 in agentic coding. Adaptive thinking only \u2014 no extended-thinking toggle. 1M context, 128k max output."
769
+ },
770
+ {
771
+ id: "claude-opus-4-6",
772
+ verifiedAgainstDocs: "2026-05-08",
773
+ provider: "anthropic",
774
+ status: "legacy",
775
+ maxContextTokens: 1e6,
776
+ maxOutputTokens: 128e3,
777
+ maxTools: 64,
778
+ parallelToolCalls: true,
779
+ structuredOutput: "grammar",
780
+ systemPromptMode: "inline",
781
+ streaming: true,
782
+ cliffs: [],
783
+ costInputPer1m: 5,
784
+ costOutputPer1m: 25,
785
+ lowering: ANTHROPIC_LOWERING_BASE,
786
+ recovery: [
787
+ {
788
+ signal: "rate_limit",
789
+ action: "escalate",
790
+ reason: "429 from Anthropic \u2014 escalate to fallback chain"
791
+ },
792
+ {
793
+ signal: "model_not_found",
794
+ action: "escalate",
795
+ reason: "Model deprecated/renamed \u2014 escalate (L-061)"
796
+ }
797
+ ],
798
+ strengths: ["reasoning", "long_context", "reliable_tool_use", "structured_output", "extended_thinking"],
799
+ weaknesses: ["cost", "latency"],
800
+ notes: "Predecessor to 4.7. Still current in Anthropic legacy table. Same pricing as 4.7 \u2014 choose 4.7 unless you need extended-thinking budget control (4.7 is adaptive-only)."
801
+ },
802
+ {
803
+ id: "claude-sonnet-4-6",
804
+ verifiedAgainstDocs: "2026-05-08",
805
+ provider: "anthropic",
806
+ status: "current",
807
+ maxContextTokens: 1e6,
808
+ maxOutputTokens: 64e3,
809
+ maxTools: 64,
810
+ parallelToolCalls: true,
811
+ structuredOutput: "grammar",
812
+ systemPromptMode: "inline",
813
+ streaming: true,
814
+ cliffs: [],
815
+ costInputPer1m: 3,
816
+ costOutputPer1m: 15,
817
+ lowering: ANTHROPIC_LOWERING_BASE,
818
+ recovery: [
819
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" },
820
+ { signal: "model_not_found", action: "escalate", reason: "Deprecated \u2014 escalate (L-061)" }
821
+ ],
822
+ strengths: ["quality", "tool_use", "long_context", "cache_friendly", "extended_thinking"],
823
+ weaknesses: [],
824
+ notes: "Workhorse. Best price/quality for most multi-turn agentic work. 1M context, 64k max output."
825
+ },
826
+ {
827
+ id: "claude-haiku-4-5",
828
+ verifiedAgainstDocs: "2026-05-08",
829
+ provider: "anthropic",
830
+ status: "current",
831
+ maxContextTokens: 2e5,
832
+ maxOutputTokens: 64e3,
833
+ maxTools: 32,
834
+ parallelToolCalls: true,
835
+ structuredOutput: "grammar",
836
+ systemPromptMode: "inline",
837
+ streaming: true,
838
+ cliffs: [
839
+ {
840
+ metric: "tool_count",
841
+ threshold: 16,
842
+ action: "drop_to_top_relevant",
843
+ reason: "Haiku reliability degrades above ~16 tools"
844
+ }
845
+ ],
846
+ costInputPer1m: 1,
847
+ costOutputPer1m: 5,
848
+ lowering: ANTHROPIC_LOWERING_BASE,
849
+ recovery: [
850
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate to Sonnet" }
851
+ ],
852
+ strengths: ["speed", "cost", "classification", "cache_friendly", "extended_thinking"],
853
+ weaknesses: ["complex_reasoning", "large_tool_sets"],
854
+ notes: "Cheapest Anthropic. Great for classify, summarize, ask shapes. 200k context, 64k max output. API alias `claude-haiku-4-5` resolves to dated snapshot `claude-haiku-4-5-20251001`."
855
+ },
856
+ // ── Google ──
857
+ {
858
+ id: "gemini-2.5-flash",
859
+ verifiedAgainstDocs: "2026-05-08",
860
+ provider: "google",
861
+ status: "current",
862
+ maxContextTokens: 1048576,
863
+ maxOutputTokens: 65535,
864
+ maxTools: 128,
865
+ parallelToolCalls: true,
866
+ structuredOutput: "native",
867
+ systemPromptMode: "separate",
868
+ streaming: true,
869
+ cliffs: [
870
+ {
871
+ metric: "input_tokens",
872
+ threshold: 8e3,
873
+ action: "downgrade_quality_warning",
874
+ reason: "Quality degrades significantly above ~8K context tokens"
875
+ },
876
+ {
877
+ metric: "tool_count",
878
+ threshold: 20,
879
+ action: "drop_to_top_relevant",
880
+ reason: "Tool reliability drops above ~20 tools (despite 128 hard limit)"
881
+ },
882
+ {
883
+ metric: "thinking_with_short_output",
884
+ threshold: 1,
885
+ action: "force_thinking_budget_zero",
886
+ reason: "Thinking tokens consume maxOutputTokens \u2014 empty response if drained"
887
+ },
888
+ {
889
+ // s11 trust artifact (2026-05-02): brain showed 5/5 empty rate on
890
+ // tt-intelligence/summarize/gemini-2.5-flash with tools offered.
891
+ // v1's disable_thinking_for_short_output already fired and didn't
892
+ // help — disabling thinking is necessary but not sufficient. Tools
893
+ // present + summarize intent confuses Flash into a no-output state
894
+ // (likely tool-decision purgatory). Strip tools entirely for this
895
+ // archetype on this model.
896
+ metric: "tool_count",
897
+ threshold: 1,
898
+ whenIntent: "summarize",
899
+ action: "strip_tools",
900
+ reason: "Gemini Flash returns empty when summarize intent has tools offered (5/5 empty rate observed in v1 prod 2026-04-19, replayed into v2 brain 2026-04-29)"
901
+ }
902
+ ],
903
+ costInputPer1m: 0.3,
904
+ costOutputPer1m: 2.5,
905
+ lowering: {
906
+ ...GOOGLE_LOWERING_BASE,
907
+ thinking: { field: "generationConfig.thinkingConfig.thinkingBudget", default: "auto" }
908
+ },
909
+ recovery: [
910
+ {
911
+ signal: "empty_response_after_tool",
912
+ action: "retry_with_params",
913
+ retryParams: { "generationConfig.thinkingConfig.thinkingBudget": 0 },
914
+ maxRetries: 1,
915
+ reason: "Known: empty after tool result \u2014 retry with thinking off"
916
+ },
917
+ {
918
+ signal: "empty_response",
919
+ action: "retry_with_params",
920
+ retryParams: { "generationConfig.thinkingConfig.thinkingBudget": 0 },
921
+ maxRetries: 1,
922
+ reason: "Empty response \u2014 try with thinking off"
923
+ },
924
+ {
925
+ signal: "malformed_function_call",
926
+ action: "escalate",
927
+ reason: "MALFORMED_FUNCTION_CALL maps to stop \u2014 escalate to next target"
928
+ }
929
+ ],
930
+ strengths: ["speed", "volume", "classification", "1m_context", "cost"],
931
+ weaknesses: ["complex_schemas", "large_tool_sets", "high_context_quality"],
932
+ notes: "Fast and cheap with 1M context. Quality cliffs at 8K context and 20 tools \u2014 guard with cliffs."
933
+ },
934
+ {
935
+ id: "gemini-2.5-pro",
936
+ verifiedAgainstDocs: "2026-05-08",
937
+ provider: "google",
938
+ status: "current",
939
+ maxContextTokens: 1048576,
940
+ maxOutputTokens: 65535,
941
+ maxTools: 128,
942
+ parallelToolCalls: true,
943
+ structuredOutput: "native",
944
+ systemPromptMode: "separate",
945
+ streaming: true,
946
+ cliffs: [
947
+ {
948
+ metric: "input_tokens",
949
+ threshold: 2e5,
950
+ action: "downgrade_quality_warning",
951
+ reason: "Pricing doubles above 200K: input $1.25\u2192$2.50/M, output $10\u2192$15/M"
952
+ }
953
+ ],
954
+ costInputPer1m: 1.25,
955
+ costOutputPer1m: 10,
956
+ lowering: {
957
+ ...GOOGLE_LOWERING_BASE,
958
+ thinking: { field: "generationConfig.thinkingConfig.thinkingBudget", default: "auto" }
959
+ },
960
+ recovery: [
961
+ {
962
+ signal: "malformed_function_call",
963
+ action: "escalate",
964
+ reason: "MALFORMED_FUNCTION_CALL \u2014 escalate"
965
+ }
966
+ ],
967
+ strengths: ["reasoning", "1m_context", "structured_output", "tool_use"],
968
+ weaknesses: ["pricing_above_200k"]
969
+ },
970
+ {
971
+ id: "gemini-3.1-pro-preview",
972
+ verifiedAgainstDocs: "2026-05-08",
973
+ provider: "google",
974
+ status: "preview",
975
+ maxContextTokens: 1048576,
976
+ maxOutputTokens: 65535,
977
+ maxTools: 128,
978
+ parallelToolCalls: true,
979
+ structuredOutput: "native",
980
+ systemPromptMode: "separate",
981
+ streaming: true,
982
+ cliffs: [
983
+ {
984
+ metric: "input_tokens",
985
+ threshold: 2e5,
986
+ action: "downgrade_quality_warning",
987
+ reason: "Pricing doubles above 200K: input $2\u2192$4/M, output $12\u2192$18/M"
988
+ }
989
+ ],
990
+ costInputPer1m: 2,
991
+ costOutputPer1m: 12,
992
+ lowering: {
993
+ ...GOOGLE_LOWERING_BASE,
994
+ cache: { ...GOOGLE_LOWERING_BASE.cache, discount: 0.1 },
995
+ thinking: { field: "generationConfig.thinkingConfig.thinkingBudget", default: "auto" }
996
+ },
997
+ recovery: [
998
+ {
999
+ signal: "malformed_function_call",
1000
+ action: "escalate",
1001
+ reason: "MALFORMED_FUNCTION_CALL \u2014 escalate"
1002
+ }
1003
+ ],
1004
+ strengths: ["reasoning", "1m_context", "agentic_coding", "structured_output", "tool_use"],
1005
+ weaknesses: ["cost", "preview_status", "pricing_above_200k"],
1006
+ notes: "Frontier Gemini (preview, 2026-Q2). Step-change agentic coding per Google. Cache discount 10\xD7 (vs 4\xD7 for 2.5 Pro). Use status=preview to flag rollback path until GA."
1007
+ },
1008
+ // ── DeepSeek ──
1009
+ // 2026-05-08 audit (L-073): DeepSeek's `deepseek-chat` was silently aliased
1010
+ // to `deepseek-v4-flash` non-thinking mode. Old kgauto profile claimed 64k
1011
+ // context + $0.27/$1.10 — actual is 1M context + $0.14/$0.28. Now modeled
1012
+ // as: V4-Flash + V4-Pro as canonical profiles; deepseek-chat and
1013
+ // deepseek-reasoner registered as aliases (see ALIASES below).
1014
+ {
1015
+ id: "deepseek-v4-flash",
1016
+ verifiedAgainstDocs: "2026-05-08",
1017
+ provider: "deepseek",
1018
+ status: "current",
1019
+ maxContextTokens: 1e6,
1020
+ maxOutputTokens: 384e3,
1021
+ maxTools: 16,
1022
+ parallelToolCalls: false,
1023
+ structuredOutput: "native",
1024
+ systemPromptMode: "inline",
1025
+ streaming: true,
1026
+ cliffs: [
1027
+ {
1028
+ metric: "tool_count",
1029
+ threshold: 1,
1030
+ action: "drop_to_top_relevant",
1031
+ reason: "Sequential tool calls only \u2014 L-040"
1032
+ }
1033
+ ],
1034
+ costInputPer1m: 0.14,
1035
+ costOutputPer1m: 0.28,
1036
+ lowering: {
1037
+ system: { mode: "inline" },
1038
+ cache: { strategy: "unsupported" },
1039
+ tools: { format: "deepseek" }
1040
+ },
1041
+ recovery: [
1042
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" }
1043
+ ],
1044
+ strengths: ["cost", "1m_context", "json_output", "code", "reasoning"],
1045
+ weaknesses: ["parallel_tools", "large_tool_sets"],
1046
+ notes: "Cheap workhorse. 1M context, 384k max output. Cache-hit input $0.0028/M (1/50\xD7 of miss). Aliased as `deepseek-chat` (non-thinking) and `deepseek-reasoner` (thinking) \u2014 see ALIASES."
1047
+ },
1048
+ {
1049
+ id: "deepseek-v4-pro",
1050
+ verifiedAgainstDocs: "2026-05-08",
1051
+ provider: "deepseek",
1052
+ status: "current",
1053
+ maxContextTokens: 1e6,
1054
+ maxOutputTokens: 384e3,
1055
+ maxTools: 16,
1056
+ parallelToolCalls: false,
1057
+ structuredOutput: "native",
1058
+ systemPromptMode: "inline",
1059
+ streaming: true,
1060
+ cliffs: [
1061
+ {
1062
+ metric: "tool_count",
1063
+ threshold: 1,
1064
+ action: "drop_to_top_relevant",
1065
+ reason: "Sequential tool calls only \u2014 L-040"
1066
+ }
1067
+ ],
1068
+ // Profile carries REGULAR pricing, not the 75%-off promo (ends 2026-05-31).
1069
+ // Under-estimating cost is worse than over-estimating for budget caps.
1070
+ costInputPer1m: 1.74,
1071
+ costOutputPer1m: 3.48,
1072
+ lowering: {
1073
+ system: { mode: "inline" },
1074
+ cache: { strategy: "unsupported" },
1075
+ tools: { format: "deepseek" }
1076
+ },
1077
+ recovery: [
1078
+ { signal: "rate_limit", action: "escalate", reason: "429 \u2014 escalate" }
1079
+ ],
1080
+ strengths: ["quality", "reasoning", "1m_context", "json_output", "code", "extended_thinking"],
1081
+ weaknesses: ["parallel_tools", "large_tool_sets"],
1082
+ notes: "Pro tier. 1M context, 384k max output. Regular pricing $1.74/$3.48; 75% promo through 2026-05-31 ($0.435/$0.87). Default mode = thinking."
1083
+ }
1084
+ ];
1085
+ var ALIASES = {
1086
+ // DeepSeek's own model routing — both names served by V4-Flash.
1087
+ "deepseek-chat": "deepseek-v4-flash",
1088
+ "deepseek-reasoner": "deepseek-v4-flash",
1089
+ // Legacy kgauto typo — actual API alias is dash-form (alpha.1 had dot).
1090
+ "claude-haiku-4.5": "claude-haiku-4-5"
1091
+ };
1092
+ function canonicalId(id) {
1093
+ return ALIASES[id] ?? id;
1094
+ }
1095
+ var PROFILE_INDEX = new Map(
1096
+ PROFILES_RAW.map((p) => [p.id, p])
1097
+ );
1098
+ function getProfile(id) {
1099
+ const canonical = canonicalId(id);
1100
+ const p = PROFILE_INDEX.get(canonical);
1101
+ if (!p) {
1102
+ const known = [...PROFILE_INDEX.keys(), ...Object.keys(ALIASES)].join(", ");
1103
+ throw new Error(`Unknown model id: "${id}". Known: ${known}`);
1104
+ }
1105
+ return p;
1106
+ }
1107
+ function tryGetProfile(id) {
1108
+ return PROFILE_INDEX.get(canonicalId(id));
1109
+ }
1110
+ function allProfiles() {
1111
+ return PROFILES_RAW;
1112
+ }
1113
+ function profilesByProvider(provider) {
1114
+ return PROFILES_RAW.filter((p) => p.provider === provider);
1115
+ }
1116
+
1117
+ // src/compile.ts
1118
+ var counter = 0;
1119
+ function makeHandle() {
1120
+ counter = (counter + 1) % 1e6;
1121
+ return `c${Date.now().toString(36)}-${counter.toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
1122
+ }
1123
+ function compile(ir, opts = {}) {
1124
+ const resolver = opts.profileResolver ?? getProfile;
1125
+ validateIR(ir);
1126
+ const sliced = passSlice(ir);
1127
+ const deduped = passDedupe(sliced.value);
1128
+ const toolFiltered = passToolRelevance(deduped.value, {
1129
+ threshold: opts.toolRelevanceThreshold
1130
+ });
1131
+ const compressed = passCompressHistory(toolFiltered.value, {
1132
+ summarizeOlderThan: opts.compressHistoryAfter
1133
+ });
1134
+ let workingIR = compressed.value;
1135
+ const accumulatedMutations = [
1136
+ ...sliced.mutations,
1137
+ ...deduped.mutations,
1138
+ ...toolFiltered.mutations,
1139
+ ...compressed.mutations
1140
+ ];
1141
+ const inputTokens = estimateInputTokens(workingIR);
1142
+ const scores = passScoreTargets(workingIR, {
1143
+ estimatedInputTokens: inputTokens,
1144
+ profilesById: resolver,
1145
+ policy: opts.policy
1146
+ });
1147
+ accumulatedMutations.push(...scores.mutations);
1148
+ const target = pickTarget(workingIR, scores.value);
1149
+ if (!target) {
1150
+ throw new Error(
1151
+ `compile(): no allowed model fits the request. Scores: ${JSON.stringify(scores.value, null, 2)}`
1152
+ );
1153
+ }
1154
+ const profile = resolver(target.modelId);
1155
+ const fallbackChain = scores.value.filter((s) => s.modelId !== target.modelId && s.fits).sort((a, b) => b.rank - a.rank).map((s) => s.modelId);
1156
+ const cliffs = passApplyCliffs(workingIR, profile, inputTokens);
1157
+ workingIR = cliffs.value.ir;
1158
+ accumulatedMutations.push(...cliffs.mutations);
1159
+ const lowered = lower(workingIR, profile, {
1160
+ forceThinkingZero: cliffs.value.loweringHints.forceThinkingZero,
1161
+ forceTerseOutput: cliffs.value.loweringHints.forceTerseOutput
1162
+ });
1163
+ validateFinalFit(workingIR, profile, inputTokens);
1164
+ const handle = makeHandle();
1165
+ const finalShape = computeShape(workingIR, inputTokens);
1166
+ const _learningKey = learningKey(ir.intent.archetype, profile.id, finalShape);
1167
+ return {
1168
+ handle,
1169
+ target: profile.id,
1170
+ provider: profile.provider,
1171
+ request: lowered.request,
1172
+ tokensIn: inputTokens,
1173
+ estimatedCostUsd: target.estimatedCostUsd,
1174
+ mutationsApplied: accumulatedMutations,
1175
+ fallbackChain,
1176
+ diagnostics: {
1177
+ sectionsKept: workingIR.sections.length,
1178
+ sectionsDropped: ir.sections.length - workingIR.sections.length,
1179
+ toolsKept: workingIR.tools?.length ?? 0,
1180
+ toolsDropped: (ir.tools?.length ?? 0) - (workingIR.tools?.length ?? 0),
1181
+ historyKept: workingIR.history?.length ?? 0,
1182
+ historyDropped: (ir.history?.length ?? 0) - (workingIR.history?.length ?? 0),
1183
+ cacheableTokens: lowered.diagnostics.cacheableTokens,
1184
+ estimatedCacheSavingsUsd: lowered.diagnostics.estimatedCacheSavingsUsd
1185
+ }
1186
+ };
1187
+ }
1188
+ function validateIR(ir) {
1189
+ if (!ir.appId) throw new Error("compile(): ir.appId is required");
1190
+ if (!ir.intent || !ir.intent.archetype) {
1191
+ throw new Error("compile(): ir.intent.archetype is required (use a dialect-v1 archetype)");
1192
+ }
1193
+ if (!Array.isArray(ir.models) || ir.models.length === 0) {
1194
+ throw new Error("compile(): ir.models must be a non-empty array");
1195
+ }
1196
+ if (!Array.isArray(ir.sections)) {
1197
+ throw new Error("compile(): ir.sections must be an array");
1198
+ }
1199
+ }
1200
+ function pickTarget(ir, scores) {
1201
+ if (ir.constraints?.forceModel) {
1202
+ const forced = scores.find((s) => s.modelId === ir.constraints.forceModel);
1203
+ if (forced && forced.fits) return forced;
1204
+ if (forced) {
1205
+ throw new Error(
1206
+ `compile(): forceModel="${ir.constraints.forceModel}" does not fit: ${forced.rejectReasons.join("; ")}`
1207
+ );
1208
+ }
1209
+ }
1210
+ const fitting = scores.filter((s) => s.fits).sort((a, b) => b.rank - a.rank);
1211
+ return fitting[0];
1212
+ }
1213
+ function validateFinalFit(ir, profile, tokens) {
1214
+ if (tokens > profile.maxContextTokens) {
1215
+ throw new Error(
1216
+ `compile(): final IR is ${tokens} tokens, exceeds ${profile.id} context (${profile.maxContextTokens})`
1217
+ );
1218
+ }
1219
+ if ((ir.tools?.length ?? 0) > profile.maxTools) {
1220
+ throw new Error(
1221
+ `compile(): final IR has ${ir.tools?.length} tools, exceeds ${profile.id} maxTools (${profile.maxTools})`
1222
+ );
1223
+ }
1224
+ }
1225
+
1226
+ // src/brain.ts
1227
+ var activeConfig;
1228
+ function configureBrain(config) {
1229
+ const endpoint = config.endpoint.replace(/\/outcomes\/?$/, "");
1230
+ activeConfig = { ...config, endpoint };
1231
+ }
1232
+ function clearBrain() {
1233
+ activeConfig = void 0;
1234
+ }
1235
+ var compileRegistry = /* @__PURE__ */ new Map();
1236
+ var REGISTRY_MAX_ENTRIES = 1e4;
1237
+ function registerCompile(appId, archetype, ir, result) {
1238
+ if (compileRegistry.size >= REGISTRY_MAX_ENTRIES) {
1239
+ const cutoff = Math.floor(REGISTRY_MAX_ENTRIES * 0.25);
1240
+ let evicted = 0;
1241
+ for (const k of compileRegistry.keys()) {
1242
+ compileRegistry.delete(k);
1243
+ if (++evicted >= cutoff) break;
1244
+ }
1245
+ }
1246
+ const tokens = result.tokensIn;
1247
+ const shape = computeShape(
1248
+ {
1249
+ appId,
1250
+ intent: { name: archetype, archetype },
1251
+ sections: ir.sections,
1252
+ tools: ir.tools,
1253
+ history: ir.history,
1254
+ models: ir.models,
1255
+ constraints: ir.constraints
1256
+ },
1257
+ tokens
1258
+ );
1259
+ const shapeKey = `${shape.contextBucket}-${shape.toolCountBucket}-${shape.historyDepth}-${shape.outputMode}`;
1260
+ compileRegistry.set(result.handle, {
1261
+ appId,
1262
+ archetype,
1263
+ model: result.target,
1264
+ provider: result.provider,
1265
+ shapeKey,
1266
+ learningKey: learningKey(archetype, result.target, shape),
1267
+ estimatedTokensIn: tokens,
1268
+ mutationsApplied: result.mutationsApplied.map((m) => m.id),
1269
+ startedAt: Date.now()
1270
+ });
1271
+ }
1272
+ async function record(input) {
1273
+ const reg = compileRegistry.get(input.handle);
1274
+ if (reg) compileRegistry.delete(input.handle);
1275
+ if (!activeConfig) {
1276
+ return;
1277
+ }
1278
+ const payload = buildPayload(input, reg);
1279
+ const config = activeConfig;
1280
+ const fetchFn = config.fetchImpl ?? fetch;
1281
+ const send = async () => {
1282
+ try {
1283
+ const res = await fetchFn(`${config.endpoint}/outcomes`, {
1284
+ method: "POST",
1285
+ headers: {
1286
+ "Content-Type": "application/json",
1287
+ ...config.apiKey ? { Authorization: `Bearer ${config.apiKey}` } : {}
1288
+ },
1289
+ body: JSON.stringify(payload)
1290
+ });
1291
+ if (!res.ok) {
1292
+ const text = await res.text().catch(() => "<no body>");
1293
+ throw new Error(`brain ${res.status}: ${text}`);
1294
+ }
1295
+ } catch (err) {
1296
+ (config.onError ?? defaultOnError)(err);
1297
+ }
1298
+ };
1299
+ if (config.sync) {
1300
+ await send();
1301
+ } else {
1302
+ void send();
1303
+ }
1304
+ }
1305
+ function defaultOnError(err) {
1306
+ console.warn("[kgauto] brain record failed:", err);
1307
+ }
1308
+ function buildPayload(input, reg) {
1309
+ const compileTarget = reg?.model;
1310
+ const actual = input.actualModel ?? compileTarget;
1311
+ const requested = input.actualModel && compileTarget && input.actualModel !== compileTarget ? compileTarget : void 0;
1312
+ return {
1313
+ handle: input.handle,
1314
+ app_id: reg?.appId,
1315
+ intent_archetype: reg?.archetype,
1316
+ model: actual,
1317
+ requested_model: requested,
1318
+ provider: reg?.provider,
1319
+ shape_key: reg?.shapeKey,
1320
+ learning_key: reg?.learningKey,
1321
+ mutations_applied: reg?.mutationsApplied ?? [],
1322
+ tokens_in: input.tokensIn,
1323
+ tokens_out: input.tokensOut,
1324
+ estimated_tokens_in: reg?.estimatedTokensIn,
1325
+ latency_ms: input.latencyMs,
1326
+ success: input.success,
1327
+ empty_response: input.emptyResponse ?? input.tokensOut === 0,
1328
+ error_type: input.errorType,
1329
+ tools_called: input.toolsCalled,
1330
+ oracle_score: input.oracleScore?.score,
1331
+ oracle_dimensions: input.oracleScore?.dimensions,
1332
+ oracle_rationale: input.oracleScore?.rationale,
1333
+ prompt_preview: input.promptPreview,
1334
+ response_preview: input.responsePreview,
1335
+ dialect_version: "v1"
1336
+ };
1337
+ }
1338
+
1339
+ // src/ir.ts
1340
+ var CallError = class extends Error {
1341
+ attempts;
1342
+ lastErrorCode;
1343
+ lastStatus;
1344
+ constructor(message, attempts, lastStatus, lastErrorCode) {
1345
+ super(message);
1346
+ this.name = "CallError";
1347
+ this.attempts = attempts;
1348
+ this.lastStatus = lastStatus;
1349
+ this.lastErrorCode = lastErrorCode;
1350
+ }
1351
+ };
1352
+
1353
+ // src/execute.ts
1354
+ var ANTHROPIC_URL = "https://api.anthropic.com/v1/messages";
1355
+ var OPENAI_URL = "https://api.openai.com/v1/chat/completions";
1356
+ var DEEPSEEK_URL = "https://api.deepseek.com/chat/completions";
1357
+ async function execute(request, opts = {}) {
1358
+ const merged = applyOverrides(request, opts.providerOverrides);
1359
+ switch (merged.provider) {
1360
+ case "anthropic":
1361
+ return executeAnthropic(merged, opts);
1362
+ case "google":
1363
+ return executeGoogle(merged, opts);
1364
+ case "openai":
1365
+ return executeOpenAI(merged, opts);
1366
+ case "deepseek":
1367
+ return executeDeepSeek(merged, opts);
1368
+ default: {
1369
+ const _exhaustive = merged;
1370
+ throw new Error(`execute(): no executor for provider: ${JSON.stringify(_exhaustive)}`);
1371
+ }
1372
+ }
1373
+ }
1374
+ async function executeAnthropic(request, opts) {
1375
+ const apiKey = opts.apiKeys?.anthropic ?? process.env.ANTHROPIC_API_KEY;
1376
+ if (!apiKey) {
1377
+ return terminalError(401, "auth", "ANTHROPIC_API_KEY missing");
1378
+ }
1379
+ const { provider: _provider, ...body } = request;
1380
+ const fetchFn = opts.fetchImpl ?? fetch;
1381
+ let res;
1382
+ let json;
1383
+ try {
1384
+ res = await fetchFn(ANTHROPIC_URL, {
1385
+ method: "POST",
1386
+ headers: {
1387
+ "x-api-key": apiKey,
1388
+ "anthropic-version": "2023-06-01",
1389
+ "content-type": "application/json"
1390
+ },
1391
+ body: JSON.stringify(body)
1392
+ });
1393
+ json = await res.json().catch(() => ({}));
1394
+ } catch (err) {
1395
+ return retryableError(0, "network_error", String(err), null);
1396
+ }
1397
+ if (!res.ok) return classifyHttpError(res.status, json);
1398
+ return { ok: true, status: res.status, response: normalizeAnthropic(json) };
1399
+ }
1400
+ function normalizeAnthropic(raw) {
1401
+ const r = raw;
1402
+ const text = (r.content ?? []).filter((b) => b.type === "text" && typeof b.text === "string").map((b) => b.text).join("");
1403
+ const toolCalls = (r.content ?? []).filter((b) => b.type === "tool_use" && b.name && b.id).map((b) => ({ id: b.id, name: b.name, args: b.input ?? {} }));
1404
+ const tokens = {
1405
+ input: r.usage?.input_tokens ?? 0,
1406
+ output: r.usage?.output_tokens ?? 0,
1407
+ total: (r.usage?.input_tokens ?? 0) + (r.usage?.output_tokens ?? 0),
1408
+ cached: r.usage?.cache_read_input_tokens,
1409
+ cacheCreated: r.usage?.cache_creation_input_tokens
1410
+ };
1411
+ return { text, structuredOutput: null, toolCalls, tokens, finishReason: r.stop_reason, raw };
1412
+ }
1413
+ async function executeGoogle(request, opts) {
1414
+ const apiKey = opts.apiKeys?.google ?? process.env.GOOGLE_API_KEY ?? process.env.GEMINI_API_KEY;
1415
+ if (!apiKey) {
1416
+ return terminalError(401, "auth", "GOOGLE_API_KEY/GEMINI_API_KEY missing");
1417
+ }
1418
+ const { provider: _provider, model, ...body } = request;
1419
+ const url = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`;
1420
+ const fetchFn = opts.fetchImpl ?? fetch;
1421
+ let res;
1422
+ let json;
1423
+ try {
1424
+ res = await fetchFn(url, {
1425
+ method: "POST",
1426
+ headers: { "content-type": "application/json" },
1427
+ body: JSON.stringify(body)
1428
+ });
1429
+ json = await res.json().catch(() => ({}));
1430
+ } catch (err) {
1431
+ return retryableError(0, "network_error", String(err), null);
1432
+ }
1433
+ if (!res.ok) return classifyHttpError(res.status, json);
1434
+ return { ok: true, status: res.status, response: normalizeGoogle(json) };
1435
+ }
1436
+ function normalizeGoogle(raw) {
1437
+ const r = raw;
1438
+ const candidate = r.candidates?.[0];
1439
+ const parts = candidate?.content?.parts ?? [];
1440
+ const text = parts.filter((p) => typeof p.text === "string").map((p) => p.text).join("");
1441
+ const toolCalls = parts.filter((p) => p.functionCall?.name).map((p, i) => ({
1442
+ id: `gemini-call-${i}`,
1443
+ name: p.functionCall.name,
1444
+ args: p.functionCall.args ?? {}
1445
+ }));
1446
+ const u = r.usageMetadata ?? {};
1447
+ const tokens = {
1448
+ input: u.promptTokenCount ?? 0,
1449
+ output: u.candidatesTokenCount ?? 0,
1450
+ total: u.totalTokenCount ?? (u.promptTokenCount ?? 0) + (u.candidatesTokenCount ?? 0),
1451
+ cached: u.cachedContentTokenCount
1452
+ };
1453
+ return { text, structuredOutput: null, toolCalls, tokens, finishReason: candidate?.finishReason, raw };
1454
+ }
1455
+ async function executeOpenAI(request, opts) {
1456
+ const apiKey = opts.apiKeys?.openai ?? process.env.OPENAI_API_KEY;
1457
+ if (!apiKey) {
1458
+ return terminalError(401, "auth", "OPENAI_API_KEY missing");
1459
+ }
1460
+ const { provider: _provider, ...body } = request;
1461
+ const fetchFn = opts.fetchImpl ?? fetch;
1462
+ let res;
1463
+ let json;
1464
+ try {
1465
+ res = await fetchFn(OPENAI_URL, {
1466
+ method: "POST",
1467
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
1468
+ body: JSON.stringify(body)
1469
+ });
1470
+ json = await res.json().catch(() => ({}));
1471
+ } catch (err) {
1472
+ return retryableError(0, "network_error", String(err), null);
1473
+ }
1474
+ if (!res.ok) return classifyHttpError(res.status, json);
1475
+ return { ok: true, status: res.status, response: normalizeOpenAILike(json) };
1476
+ }
1477
+ async function executeDeepSeek(request, opts) {
1478
+ const apiKey = opts.apiKeys?.deepseek ?? process.env.DEEPSEEK_API_KEY;
1479
+ if (!apiKey) {
1480
+ return terminalError(401, "auth", "DEEPSEEK_API_KEY missing");
1481
+ }
1482
+ const { provider: _provider, ...body } = request;
1483
+ const fetchFn = opts.fetchImpl ?? fetch;
1484
+ let res;
1485
+ let json;
1486
+ try {
1487
+ res = await fetchFn(DEEPSEEK_URL, {
1488
+ method: "POST",
1489
+ headers: { authorization: `Bearer ${apiKey}`, "content-type": "application/json" },
1490
+ body: JSON.stringify(body)
1491
+ });
1492
+ json = await res.json().catch(() => ({}));
1493
+ } catch (err) {
1494
+ return retryableError(0, "network_error", String(err), null);
1495
+ }
1496
+ if (!res.ok) return classifyHttpError(res.status, json);
1497
+ return { ok: true, status: res.status, response: normalizeOpenAILike(json) };
1498
+ }
1499
+ function normalizeOpenAILike(raw) {
1500
+ const r = raw;
1501
+ const choice = r.choices?.[0];
1502
+ const text = choice?.message?.content ?? "";
1503
+ const toolCalls = (choice?.message?.tool_calls ?? []).filter((tc) => tc.function?.name).map((tc, i) => ({
1504
+ id: tc.id ?? `tc-${i}`,
1505
+ name: tc.function.name,
1506
+ args: tryParseJson(tc.function?.arguments) ?? {}
1507
+ }));
1508
+ const u = r.usage ?? {};
1509
+ const tokens = {
1510
+ input: u.prompt_tokens ?? 0,
1511
+ output: u.completion_tokens ?? 0,
1512
+ total: u.total_tokens ?? (u.prompt_tokens ?? 0) + (u.completion_tokens ?? 0),
1513
+ cached: u.prompt_tokens_details?.cached_tokens
1514
+ };
1515
+ return { text, structuredOutput: null, toolCalls, tokens, finishReason: choice?.finish_reason, raw };
1516
+ }
1517
+ function applyOverrides(request, overrides) {
1518
+ if (!overrides) return request;
1519
+ const layer = overrides[request.provider];
1520
+ if (!layer) return request;
1521
+ return { ...request, ...layer };
1522
+ }
1523
+ function classifyHttpError(status, body) {
1524
+ const message = extractErrorMessage(body) ?? `HTTP ${status}`;
1525
+ if (status === 429) {
1526
+ return { ok: false, status, errorType: "retryable", errorCode: "rate_limit", message, raw: body };
1527
+ }
1528
+ if (status === 408) {
1529
+ return { ok: false, status, errorType: "retryable", errorCode: "timeout", message, raw: body };
1530
+ }
1531
+ if (status >= 500) {
1532
+ return { ok: false, status, errorType: "retryable", errorCode: "server_error", message, raw: body };
1533
+ }
1534
+ if (status === 404) {
1535
+ return { ok: false, status, errorType: "retryable", errorCode: "model_not_found", message, raw: body };
1536
+ }
1537
+ if (status === 401 || status === 403) {
1538
+ return { ok: false, status, errorType: "terminal", errorCode: "auth", message, raw: body };
1539
+ }
1540
+ if (status === 400) {
1541
+ return { ok: false, status, errorType: "terminal", errorCode: "invalid_request", message, raw: body };
1542
+ }
1543
+ return { ok: false, status, errorType: "terminal", errorCode: "unknown", message, raw: body };
1544
+ }
1545
+ function extractErrorMessage(body) {
1546
+ if (!body || typeof body !== "object") return void 0;
1547
+ const b = body;
1548
+ if (b.error && typeof b.error === "object") {
1549
+ const e = b.error;
1550
+ if (typeof e.message === "string") return e.message;
1551
+ }
1552
+ if (typeof b.message === "string") return b.message;
1553
+ return void 0;
1554
+ }
1555
+ function terminalError(status, code, message) {
1556
+ return { ok: false, status, errorType: "terminal", errorCode: code, message, raw: null };
1557
+ }
1558
+ function retryableError(status, code, message, raw) {
1559
+ return { ok: false, status, errorType: "retryable", errorCode: code, message, raw };
1560
+ }
1561
+ function tryParseJson(s) {
1562
+ if (typeof s !== "string" || s.length === 0) return void 0;
1563
+ try {
1564
+ const parsed = JSON.parse(s);
1565
+ return typeof parsed === "object" && parsed !== null ? parsed : void 0;
1566
+ } catch {
1567
+ return void 0;
1568
+ }
1569
+ }
1570
+
1571
+ // src/call.ts
1572
+ async function call(ir, opts = {}) {
1573
+ const initial = compileAndRegister(ir, opts);
1574
+ const start = Date.now();
1575
+ const attempts = [];
1576
+ const targetsToTry = [initial.target, ...initial.fallbackChain];
1577
+ let activeCompile = initial;
1578
+ let lastErr;
1579
+ for (let i = 0; i < targetsToTry.length; i++) {
1580
+ const targetModel = targetsToTry[i];
1581
+ if (i > 0) {
1582
+ try {
1583
+ activeCompile = compileAndRegister(
1584
+ {
1585
+ ...ir,
1586
+ models: ir.models.includes(targetModel) ? ir.models : [targetModel, ...ir.models],
1587
+ constraints: { ...ir.constraints ?? {}, forceModel: targetModel }
1588
+ },
1589
+ opts
1590
+ );
1591
+ } catch (err) {
1592
+ attempts.push({
1593
+ model: targetModel,
1594
+ status: "terminal",
1595
+ errorCode: "compile_error",
1596
+ message: err instanceof Error ? err.message : String(err)
1597
+ });
1598
+ continue;
1599
+ }
1600
+ }
1601
+ const exec = await execute(activeCompile.request, {
1602
+ apiKeys: opts.apiKeys,
1603
+ fetchImpl: opts.fetchImpl,
1604
+ providerOverrides: opts.providerOverrides
1605
+ });
1606
+ if (exec.ok) {
1607
+ attempts.push({ model: targetModel, status: "success" });
1608
+ const latencyMs2 = Date.now() - start;
1609
+ const responseWithStructured = withStructuredOutput(exec.response, ir);
1610
+ void record({
1611
+ handle: initial.handle,
1612
+ tokensIn: responseWithStructured.tokens.input,
1613
+ tokensOut: responseWithStructured.tokens.output,
1614
+ latencyMs: latencyMs2,
1615
+ success: true,
1616
+ emptyResponse: responseWithStructured.tokens.output === 0,
1617
+ toolsCalled: responseWithStructured.toolCalls.map((tc) => tc.name),
1618
+ actualModel: targetModel !== initial.target ? targetModel : void 0,
1619
+ responsePreview: responseWithStructured.text.slice(0, 200)
1620
+ });
1621
+ return {
1622
+ handle: initial.handle,
1623
+ actualModel: targetModel,
1624
+ requestedModel: initial.target,
1625
+ provider: activeCompile.provider,
1626
+ response: responseWithStructured,
1627
+ latencyMs: latencyMs2,
1628
+ mutationsApplied: activeCompile.mutationsApplied,
1629
+ attempts
1630
+ };
1631
+ }
1632
+ attempts.push({
1633
+ model: targetModel,
1634
+ status: exec.errorType,
1635
+ errorCode: exec.errorCode,
1636
+ message: exec.message
1637
+ });
1638
+ lastErr = exec;
1639
+ if (exec.errorType === "terminal" || opts.noFallback) {
1640
+ break;
1641
+ }
1642
+ }
1643
+ const latencyMs = Date.now() - start;
1644
+ void record({
1645
+ handle: initial.handle,
1646
+ tokensIn: 0,
1647
+ tokensOut: 0,
1648
+ latencyMs,
1649
+ success: false,
1650
+ errorType: lastErr?.errorCode
1651
+ });
1652
+ throw new CallError(
1653
+ `call(): all attempts failed${lastErr ? ` \u2014 ${lastErr.errorCode}: ${lastErr.message}` : ""}`,
1654
+ attempts,
1655
+ lastErr?.status,
1656
+ lastErr?.errorCode
1657
+ );
1658
+ }
1659
+ function compileAndRegister(ir, opts) {
1660
+ const result = compile(ir, {
1661
+ policy: opts.policy,
1662
+ toolRelevanceThreshold: opts.toolRelevanceThreshold,
1663
+ compressHistoryAfter: opts.compressHistoryAfter
1664
+ });
1665
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
1666
+ return result;
1667
+ }
1668
+ function withStructuredOutput(response, ir) {
1669
+ if (!ir.constraints?.structuredOutput) return response;
1670
+ if (!response.text) return response;
1671
+ try {
1672
+ const parsed = JSON.parse(response.text);
1673
+ return { ...response, structuredOutput: parsed };
1674
+ } catch (err) {
1675
+ return {
1676
+ ...response,
1677
+ structuredOutput: null,
1678
+ parseError: err instanceof Error ? err.message : String(err)
1679
+ };
1680
+ }
1681
+ }
1682
+
1683
+ // src/oracle.ts
1684
+ var DEFAULT_DIMENSIONS = ["correctness", "completeness", "conciseness", "format"];
1685
+ var judgeCallTimes = [];
1686
+ function buildLLMJudge(opts) {
1687
+ const dimensions = opts.dimensions ?? DEFAULT_DIMENSIONS;
1688
+ const rateLimit = opts.rateLimitPerMin;
1689
+ return async (ctx) => {
1690
+ if (rateLimit) {
1691
+ const now = Date.now();
1692
+ judgeCallTimes = judgeCallTimes.filter((t) => now - t < 6e4);
1693
+ if (judgeCallTimes.length >= rateLimit) {
1694
+ return { score: 0.5, rationale: "judge rate-limited; default neutral" };
1695
+ }
1696
+ judgeCallTimes.push(now);
1697
+ }
1698
+ const prompt = buildJudgePrompt(ctx, dimensions);
1699
+ let raw;
1700
+ try {
1701
+ raw = await opts.judgeCall(prompt);
1702
+ } catch (err) {
1703
+ return {
1704
+ score: 0.5,
1705
+ rationale: `judge error: ${err instanceof Error ? err.message : String(err)}`
1706
+ };
1707
+ }
1708
+ return parseJudgeOutput(raw, dimensions);
1709
+ };
1710
+ }
1711
+ function buildJudgePrompt(ctx, dimensions) {
1712
+ return `You are an oracle scoring an AI response. Output ONLY a JSON object, no other text.
1713
+
1714
+ Intent archetype: ${ctx.archetype}
1715
+ App: ${ctx.appId} / ${ctx.intentName}
1716
+ Tools were involved: ${ctx.hadTools}
1717
+
1718
+ User asked:
1719
+ ${ctx.userTurn ?? "<not provided>"}
1720
+
1721
+ Response:
1722
+ ${ctx.response.slice(0, 4e3)}
1723
+
1724
+ Score from 0.0 to 1.0 on each dimension. 1.0 = perfect, 0.5 = mediocre, 0.0 = wrong.
1725
+ Be honest \u2014 most responses are 0.5-0.8. Reserve 0.9+ for genuinely excellent.
1726
+
1727
+ Respond with this JSON shape:
1728
+ {
1729
+ "score": <overall 0..1>,
1730
+ "dimensions": { ${dimensions.map((d) => `"${d}": <0..1>`).join(", ")} },
1731
+ "rationale": "<one sentence>"
1732
+ }`;
1733
+ }
1734
+ function parseJudgeOutput(raw, dimensions) {
1735
+ const cleaned = raw.replace(/^```(?:json)?\s*/i, "").replace(/\s*```\s*$/, "").trim();
1736
+ let parsed;
1737
+ try {
1738
+ parsed = JSON.parse(cleaned);
1739
+ } catch {
1740
+ const match = cleaned.match(/\{[\s\S]*\}/);
1741
+ if (match) {
1742
+ try {
1743
+ parsed = JSON.parse(match[0]);
1744
+ } catch {
1745
+ return { score: 0.5, rationale: "judge output unparseable" };
1746
+ }
1747
+ } else {
1748
+ return { score: 0.5, rationale: "judge output unparseable" };
1749
+ }
1750
+ }
1751
+ if (!parsed || typeof parsed !== "object") {
1752
+ return { score: 0.5, rationale: "judge output not an object" };
1753
+ }
1754
+ const obj = parsed;
1755
+ const score = clamp(typeof obj.score === "number" ? obj.score : 0.5);
1756
+ const dims = {};
1757
+ if (obj.dimensions && typeof obj.dimensions === "object") {
1758
+ for (const d of dimensions) {
1759
+ const v = obj.dimensions[d];
1760
+ dims[d] = clamp(typeof v === "number" ? v : 0.5);
1761
+ }
1762
+ }
1763
+ const rationale = typeof obj.rationale === "string" ? obj.rationale : void 0;
1764
+ return { score, dimensions: Object.keys(dims).length > 0 ? dims : void 0, rationale };
1765
+ }
1766
+ function clamp(n) {
1767
+ if (!Number.isFinite(n)) return 0.5;
1768
+ return Math.max(0, Math.min(1, n));
1769
+ }
1770
+
1771
+ // src/index.ts
1772
+ function compile2(ir, opts) {
1773
+ const result = compile(ir, opts);
1774
+ registerCompile(ir.appId, ir.intent.archetype, ir, result);
1775
+ return result;
1776
+ }
1777
+ // Annotate the CommonJS export names for ESM import in node:
1778
+ 0 && (module.exports = {
1779
+ ALIASES,
1780
+ ALL_ARCHETYPES,
1781
+ CallError,
1782
+ DIALECT_VERSION,
1783
+ INTENT_ARCHETYPES,
1784
+ allProfiles,
1785
+ bucketContext,
1786
+ bucketHistory,
1787
+ bucketToolCount,
1788
+ buildLLMJudge,
1789
+ call,
1790
+ clearBrain,
1791
+ compile,
1792
+ configureBrain,
1793
+ countTokens,
1794
+ execute,
1795
+ getProfile,
1796
+ hashShape,
1797
+ isArchetype,
1798
+ learningKey,
1799
+ profilesByProvider,
1800
+ record,
1801
+ resetTokenizer,
1802
+ setTokenizer,
1803
+ tryGetProfile
1804
+ });