@warmdrift/kgauto-compiler 2.0.0-alpha.10

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