@warmdrift/kgauto-compiler 2.0.0-alpha.5 → 2.0.0-alpha.51

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.
Files changed (40) hide show
  1. package/README.md +140 -3
  2. package/dist/chunk-CXH7KC4D.mjs +1413 -0
  3. package/dist/chunk-HHWBB46W.mjs +694 -0
  4. package/dist/chunk-NBO4R5PC.mjs +313 -0
  5. package/dist/chunk-P3TOAEG4.mjs +56 -0
  6. package/dist/chunk-RO22VFIF.mjs +29 -0
  7. package/dist/glassbox/index.d.mts +59 -0
  8. package/dist/glassbox/index.d.ts +59 -0
  9. package/dist/glassbox/index.js +312 -0
  10. package/dist/glassbox/index.mjs +12 -0
  11. package/dist/glassbox-routes/format.d.mts +24 -0
  12. package/dist/glassbox-routes/format.d.ts +24 -0
  13. package/dist/glassbox-routes/format.js +86 -0
  14. package/dist/glassbox-routes/format.mjs +18 -0
  15. package/dist/glassbox-routes/index.d.mts +191 -0
  16. package/dist/glassbox-routes/index.d.ts +191 -0
  17. package/dist/glassbox-routes/index.js +2657 -0
  18. package/dist/glassbox-routes/index.mjs +663 -0
  19. package/dist/glassbox-routes/react/index.d.mts +74 -0
  20. package/dist/glassbox-routes/react/index.d.ts +74 -0
  21. package/dist/glassbox-routes/react/index.js +819 -0
  22. package/dist/glassbox-routes/react/index.mjs +754 -0
  23. package/dist/index.d.mts +2046 -9
  24. package/dist/index.d.ts +2046 -9
  25. package/dist/index.js +6266 -1079
  26. package/dist/index.mjs +3387 -186
  27. package/dist/ir-dDcG8Pvu.d.mts +1337 -0
  28. package/dist/ir-rUUojj0s.d.ts +1337 -0
  29. package/dist/profiles.d.mts +292 -2
  30. package/dist/profiles.d.ts +292 -2
  31. package/dist/profiles.js +1024 -16
  32. package/dist/profiles.mjs +9 -1
  33. package/dist/types-BTeRoSvM.d.mts +149 -0
  34. package/dist/types-B_pdPjxm.d.ts +149 -0
  35. package/dist/types-UXPxWabQ.d.ts +131 -0
  36. package/dist/types-vGo-h0tZ.d.mts +131 -0
  37. package/package.json +42 -6
  38. package/dist/chunk-MBEI5UOM.mjs +0 -409
  39. package/dist/profiles-DHdCRBVH.d.mts +0 -571
  40. package/dist/profiles-MGq5Tnjv.d.ts +0 -571
@@ -0,0 +1,1337 @@
1
+ import { IntentArchetypeName } from './dialect.js';
2
+
3
+ /**
4
+ * Intermediate Representation — the structured form of a prompt.
5
+ *
6
+ * Everything kgauto v2 does, it does on the IR. The IR is constructed by the
7
+ * caller (or by `parse()` from a string-style prompt for backwards-compat),
8
+ * transformed by the compiler passes, and lowered to a target-specific wire
9
+ * request only at the very end.
10
+ *
11
+ * The IR carries STRUCTURE, not just text. Sections are first-class. Tools
12
+ * carry per-intent relevance. History knows its turn-age. Constraints are
13
+ * explicit. This is what lets passes do real work.
14
+ */
15
+
16
+ /**
17
+ * A semantically-named section of the system prompt. Sections enable
18
+ * intent-aware slicing (drop sections not tagged for this intent), dedupe
19
+ * (collapse identical sections across files), and cache marking (identify
20
+ * the stable prefix).
21
+ */
22
+ interface PromptSection {
23
+ /** Stable identifier — used for slicing, dedupe, and cache markers. */
24
+ id: string;
25
+ /** Section text. */
26
+ text: string;
27
+ /**
28
+ * Which intents this section applies to. Empty = applies to all intents.
29
+ * Pass `compile()` will drop sections whose intents array doesn't include
30
+ * the current intent.
31
+ */
32
+ intents?: IntentArchetypeName[];
33
+ /**
34
+ * If true, this section is part of the stable cacheable prefix. The lower
35
+ * pass uses this to place cache markers correctly per target.
36
+ */
37
+ cacheable?: boolean;
38
+ /**
39
+ * Section weight when ordering — lower = earlier in the assembled prompt.
40
+ * Defaults to insertion order.
41
+ */
42
+ weight?: number;
43
+ /**
44
+ * alpha.29+ — declares the section's semantic kind so kgauto can apply
45
+ * model-aware rewrites at compile time. Default `'arbitrary'` (when
46
+ * unset) for full back-compat — pre-alpha.29 sections continue working
47
+ * unchanged.
48
+ *
49
+ * alpha.29 ships rewrites for `tool_call_contract` only. Other kinds are
50
+ * type-accepted but pass through. alpha.30+ will add rewrites for
51
+ * `narration_contract`, `role_intro`, etc.
52
+ *
53
+ * See `translator.ts` for the rewrite engine that consumes this field.
54
+ */
55
+ kind?: SectionKind;
56
+ }
57
+ /**
58
+ * alpha.29+ — semantic kind tag for a `PromptSection`. The translator
59
+ * (`v2/src/translator.ts`) consumes this to apply model-aware rewrites at
60
+ * compile time. CLOSED union; future kinds extend it explicitly in named
61
+ * alpha releases.
62
+ *
63
+ * alpha.29 ships rewrites for `tool_call_contract` only. Other kinds are
64
+ * type-accepted but pass through.
65
+ *
66
+ * - `role_intro` — "You are a helpful assistant", persona blocks
67
+ * - `tool_call_contract` — tool-use rules ("call X then Y"); the alpha.29
68
+ * translator rewrites this for models with a
69
+ * sequential-tool cliff on the active archetype
70
+ * - `narration_contract` — output-format rules ("don't narrate your steps");
71
+ * alpha.30+ candidate
72
+ * - `user_turn` — when sections carry user content rather than
73
+ * system context (rare)
74
+ * - `reference` — supporting reference data the model may consult
75
+ * - `arbitrary` — explicit pass-through (default when unset)
76
+ */
77
+ type SectionKind = 'role_intro' | 'tool_call_contract' | 'narration_contract' | 'user_turn' | 'reference' | 'arbitrary';
78
+ interface ToolDefinition {
79
+ name: string;
80
+ description?: string;
81
+ parameters?: Record<string, unknown>;
82
+ /**
83
+ * Per-intent relevance scores. Compile uses these to drop irrelevant tools.
84
+ * Missing intents default to 0.5 (neutral).
85
+ */
86
+ relevanceByIntent?: Partial<Record<IntentArchetypeName, number>>;
87
+ /** Pass-through for provider-specific fields (Anthropic input_schema, etc.). */
88
+ [key: string]: unknown;
89
+ }
90
+ interface Message {
91
+ role: 'system' | 'user' | 'assistant' | 'tool';
92
+ content: string;
93
+ /** Optional structured parts (tool calls, results) — passed through to lowering. */
94
+ parts?: unknown[];
95
+ /** For tool messages — which tool this corresponds to. */
96
+ toolName?: string;
97
+ /** For tool messages — the call id. */
98
+ toolCallId?: string;
99
+ }
100
+ /**
101
+ * The compile-time intent declaration. `name` is the app's local label;
102
+ * `archetype` is the canonical dialect-v1 archetype the app maps it to.
103
+ *
104
+ * Apps with their own intent vocabulary (tt-intelligence's "ask"/"hunt"/
105
+ * "dashboard") declare the mapping here. The brain learns by archetype, not
106
+ * by app-local name.
107
+ */
108
+ interface IntentDeclaration {
109
+ /** App-local intent name (free-form, for app's own debugging). */
110
+ name: string;
111
+ /** Canonical dialect-v1 archetype. Required for cross-app learning. */
112
+ archetype: IntentArchetypeName;
113
+ }
114
+ interface Constraints {
115
+ /** Hard latency ceiling — compiler will down-rank slow models. Advisory. */
116
+ maxLatencyMs?: number;
117
+ /** Hard cost ceiling per call (USD). Advisory. */
118
+ maxCostUsd?: number;
119
+ /** Caller wants structured (JSON) output. */
120
+ structuredOutput?: boolean;
121
+ /** Hint: caller expects a short response (used to disable thinking on Gemini). */
122
+ expectedShortOutput?: boolean;
123
+ /** Hint: max response words. */
124
+ maxResponseWords?: number;
125
+ /** Override target model selection — if set, compiler uses this instead of routing. */
126
+ forceModel?: string;
127
+ /**
128
+ * alpha.20: consumer-declared tool-orchestration shape for this call.
129
+ * - 'parallel': model may fire multiple tool calls per step (current
130
+ * default behavior; the L-040 cliff applies — DeepSeek's
131
+ * `tool_count >= 1` cliff trims tools because parallel-tool throughput
132
+ * collapses to sequential semantics).
133
+ * - 'sequential': consumer commits to one tool call per step (the agentic
134
+ * loop pattern). DeepSeek V4-Flash + V4-Pro can compete cleanly in
135
+ * this mode — the L-040 cliff is silenced and the hunt chain shifts
136
+ * to a DeepSeek-tier-1 ordering.
137
+ * - 'either': consumer doesn't care; library picks the parallel chain
138
+ * (status-quo default) and may upgrade to brain-driven per-mode perf
139
+ * selection in a future release.
140
+ *
141
+ * Affects:
142
+ * - Chain composition for `archetype: 'hunt'` (see
143
+ * `getDefaultFallbackChain` and `STARTER_CHAINS_BY_MODE`).
144
+ * - L-040 cliff in `passApplyCliffs` (silent when 'sequential').
145
+ *
146
+ * Default (when undefined): equivalent to 'parallel' for back-compat
147
+ * with every pre-alpha.20 caller.
148
+ */
149
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
150
+ }
151
+ /**
152
+ * Cache marker policy for the messages array (history + currentTurn).
153
+ *
154
+ * Anthropic positional caching: a `cache_control` marker on a content block
155
+ * tells the API "remember the prefix up through this block." On a subsequent
156
+ * request whose first N tokens match, those N billed at the cached rate
157
+ * (10% of the input price). Without a marker, every call re-pays for the
158
+ * entire history.
159
+ *
160
+ * - `'none'` (default when omitted): no history cache marker. System-level
161
+ * cache markers from `PromptSection.cacheable=true` still apply.
162
+ * - `'all-but-latest'`: marks the message immediately preceding `currentTurn`
163
+ * (the last history entry). On the next call, that entire history prefix
164
+ * is cacheable. Good fit for chat/agent loops where every prior turn is
165
+ * stable.
166
+ * - `'fixed-suffix'`: marks the message `suffix` positions from the end of
167
+ * `history`. Use when the last few turns are volatile (e.g., scratchpad,
168
+ * draft revisions) but the earlier prefix is stable.
169
+ *
170
+ * For non-Anthropic providers, no wire-format marker is emitted (Gemini /
171
+ * OpenAI / DeepSeek implicit caching takes effect automatically when a
172
+ * stable prefix is reused). The compiler still computes
173
+ * `diagnostics.historyCacheableTokens` for telemetry on every provider.
174
+ *
175
+ * alpha.5.
176
+ */
177
+ type HistoryCachePolicy = {
178
+ strategy: 'none';
179
+ } | {
180
+ strategy: 'all-but-latest';
181
+ } | {
182
+ strategy: 'fixed-suffix';
183
+ suffix: number;
184
+ };
185
+ /**
186
+ * Consumer-declared policy for model selection. Lives outside the IR
187
+ * (passed via CompileOptions) because it's a SESSION/APP-level constraint,
188
+ * not a per-call shape.
189
+ *
190
+ * The original tt-intelligence scenario (s11): user capped Anthropic
191
+ * spending on Sonnet for cost reasons. v2 compile() kept picking Sonnet
192
+ * as the best target, Hunter's preflight hit the cap and fell back to
193
+ * Flash — every single call. CompilePolicy.blockedModels lets the
194
+ * consumer tell kgauto "don't pick Sonnet right now" and the compiler
195
+ * routes to the next-best option directly. No wasted preflight tax.
196
+ *
197
+ * This is the "coach knows the constraints" feature — kgauto stops
198
+ * recommending things the consumer has already ruled out.
199
+ */
200
+ interface CompilePolicy {
201
+ /**
202
+ * Model IDs the consumer has gated. Compile() will never select these.
203
+ * Use for: cost caps, account-level rate limits, "this model is broken
204
+ * for our workload" decisions.
205
+ */
206
+ blockedModels?: string[];
207
+ /**
208
+ * Hard ceiling on estimated input cost per call (USD). Models whose
209
+ * estimated cost exceeds this are rejected. Use for: budget enforcement
210
+ * on high-volume routes.
211
+ */
212
+ maxCostPerCallUsd?: number;
213
+ /**
214
+ * Model IDs the consumer prefers. When multiple models fit, preferred
215
+ * models get a rank boost (large enough to overcome small quality
216
+ * differences but not large enough to override hard rejects).
217
+ */
218
+ preferredModels?: string[];
219
+ /**
220
+ * Customer-posture tag (master plan §1.2, alpha.9).
221
+ *
222
+ * - `'locked'` — compliance/contract/brand-promise. Caller passes
223
+ * exactly one model; no fallback is desired. kgauto
224
+ * never walks the chain.
225
+ * - `'preferred'` — user-selected primary, fallback chain as safety
226
+ * net. On 429/5xx, walk the chain and surface
227
+ * `fellOverFrom` so the consumer can show "Claude
228
+ * was busy; we used Pro for this answer."
229
+ * - `'open'` — library picks the chain. Model identity is
230
+ * irrelevant; output is the contract.
231
+ *
232
+ * The field is **informational** — kgauto's execution path is already
233
+ * determined by the shape of `ir.models`. Posture surfaces in
234
+ * telemetry so the cost-watcher can distinguish "locked failed, no
235
+ * fallback was tried" from "open chain exhausted." Default: when
236
+ * `ir.models.length === 1` posture is treated as `'locked'` by the
237
+ * advisor; otherwise unspecified.
238
+ */
239
+ posture?: 'locked' | 'preferred' | 'open';
240
+ }
241
+ /**
242
+ * alpha.41 — entry in `PromptIR.models[]`. Either a literal model id (the
243
+ * pre-alpha.41 shape, fully preserved) or a `{ family: string }` alias that
244
+ * resolves at compile() time to the latest-current model in that family.
245
+ *
246
+ * Family entries resolve via `resolveFamilyEntry` (internal twin of the
247
+ * public `getRecommendedPrimary`). Resolution fails CLOSED — a family that
248
+ * matches no current+active candidate throws `FamilyResolutionError` at
249
+ * compile time. Consumers who want a literal fallback should call
250
+ * `getRecommendedPrimary({ family, fallback, ... })` at IR-construction time
251
+ * and inline the resolved id, rather than passing `{ family }` into the IR.
252
+ *
253
+ * Family taxonomy is defined in `family-resolution.ts`; see also migration
254
+ * 024 (`kgauto_models.family` column + index).
255
+ */
256
+ type ChainModelEntry = string | {
257
+ family: string;
258
+ };
259
+ /**
260
+ * The IR — the input to compile().
261
+ */
262
+ interface PromptIR {
263
+ /** App identifier — required for multi-tenant brain. */
264
+ appId: string;
265
+ /** Intent declaration — what is this call doing? */
266
+ intent: IntentDeclaration;
267
+ /** Structured system prompt sections. */
268
+ sections: PromptSection[];
269
+ /** Available tools (compiler may drop based on intent relevance + budget). */
270
+ tools?: ToolDefinition[];
271
+ /** Conversation history (compiler may compress old turns). */
272
+ history?: Message[];
273
+ /** The user's current turn — never dropped. */
274
+ currentTurn?: Message;
275
+ /**
276
+ * Allowed model IDs (or family aliases — alpha.41+), in caller-preference
277
+ * order. Compiler resolves family entries to literal ids before scoring
278
+ * and picks among them. See {@link ChainModelEntry}.
279
+ *
280
+ * Internal passes downstream of compile()'s family-resolution step
281
+ * receive a narrowed `string[]` shape — `string` is a subtype of
282
+ * `ChainModelEntry`, so a `string[]` IS a `ChainModelEntry[]` at the
283
+ * type level. Code that needs to access string ids (passes.ts) reads
284
+ * via `getModelIds(ir)` from `models-runtime.ts` rather than narrowing
285
+ * inline.
286
+ */
287
+ models: ChainModelEntry[];
288
+ /** Compile constraints. */
289
+ constraints?: Constraints;
290
+ /**
291
+ * Cache marker placement policy for the messages array. Default = no
292
+ * history cache markers. See `HistoryCachePolicy` for semantics.
293
+ * alpha.5.
294
+ */
295
+ historyCachePolicy?: HistoryCachePolicy;
296
+ }
297
+ type Provider = 'anthropic' | 'google' | 'openai' | 'deepseek' | 'mistral' | 'xai';
298
+ /**
299
+ * Mutation IDs that fired during compile. Empty in v1 (no mutation engine
300
+ * yet). Populated when the brain is online and pushing mutations.
301
+ */
302
+ type MutationApplied = {
303
+ id: string;
304
+ source: string;
305
+ passName: string;
306
+ description: string;
307
+ };
308
+ /**
309
+ * Target-specific wire request. Shape varies by provider — caller passes the
310
+ * right field to the right SDK.
311
+ */
312
+ type CompiledRequest = {
313
+ provider: 'anthropic';
314
+ model: string;
315
+ system: Array<{
316
+ type: 'text';
317
+ text: string;
318
+ cache_control?: {
319
+ type: 'ephemeral';
320
+ };
321
+ }>;
322
+ messages: Array<{
323
+ role: string;
324
+ content: unknown;
325
+ }>;
326
+ tools?: unknown[];
327
+ max_tokens?: number;
328
+ /**
329
+ * alpha.29 — emitted only when the translator's wire-overrides set
330
+ * `parallelToolCalls = false`. Shape per Anthropic Messages API docs:
331
+ * `{ type: 'auto', disable_parallel_tool_use: true }`. kgauto defaults
332
+ * to omitting `tool_choice` entirely (Anthropic defaults to auto + parallel),
333
+ * so this field's presence signals an explicit override.
334
+ */
335
+ tool_choice?: {
336
+ type: 'auto' | 'any' | 'tool' | 'none';
337
+ disable_parallel_tool_use?: boolean;
338
+ name?: string;
339
+ };
340
+ } | {
341
+ provider: 'google';
342
+ model: string;
343
+ systemInstruction?: {
344
+ role: 'system';
345
+ parts: Array<{
346
+ text: string;
347
+ }>;
348
+ };
349
+ contents: Array<{
350
+ role: string;
351
+ parts: unknown[];
352
+ }>;
353
+ tools?: unknown[];
354
+ generationConfig?: Record<string, unknown>;
355
+ cachedContent?: string;
356
+ } | {
357
+ provider: 'openai';
358
+ model: string;
359
+ messages: Array<{
360
+ role: string;
361
+ content: unknown;
362
+ }>;
363
+ tools?: unknown[];
364
+ response_format?: unknown;
365
+ reasoning_effort?: string;
366
+ /**
367
+ * alpha.29 — emitted only when the translator's wire-overrides set
368
+ * `parallelToolCalls = false`. OpenAI defaults parallel_tool_calls=true
369
+ * server-side; we explicit-set to false only when overriding.
370
+ */
371
+ parallel_tool_calls?: boolean;
372
+ } | {
373
+ provider: 'deepseek';
374
+ model: string;
375
+ messages: Array<{
376
+ role: string;
377
+ content: unknown;
378
+ }>;
379
+ tools?: unknown[];
380
+ };
381
+ /**
382
+ * Best-practice advisory emitted by the compiler at compile time. Non-fatal —
383
+ * consumers log, surface in dev tools, gate on `level === 'critical'` in CI,
384
+ * or ignore. The advisor inspects the IR + selected profile + diagnostics
385
+ * and emits one entry per detected gap.
386
+ *
387
+ * Codes are stable across releases. `suggestion` and `docsUrl` are optional
388
+ * but encouraged: suggestion = the actionable diff; docsUrl = the
389
+ * interfaces/kgauto.md anchor for context.
390
+ *
391
+ * alpha.6 Phase 1 starter rules:
392
+ * - `caching-off-on-claude` (warn) system >2000 chars on Anthropic, no cacheable=true
393
+ * - `single-chunk-system` (info) Anthropic, only one PromptSection >1000 chars
394
+ * - `tool-bloat` (warn) >10 tools on a short-output archetype
395
+ * - `history-uncached-on-claude` (warn) Anthropic, ≥2 history messages, no historyCachePolicy
396
+ *
397
+ * Phase 2 (catalog as `bestPractices` block in profiles) and Phase 3 (brain
398
+ * telemetry on `advisories_fired`) are alpha.7+ territory.
399
+ */
400
+ interface BestPracticeAdvisory {
401
+ /**
402
+ * Severity. `info` = informational; `warn` = behavioral pattern that's
403
+ * usually expensive or wrong; `critical` = likely bug or production-grade
404
+ * misuse. Phase 1 ships info + warn only.
405
+ */
406
+ level: 'info' | 'warn' | 'critical';
407
+ /** Stable kebab-case code. Consumers filter / gate by this. */
408
+ code: string;
409
+ /** Human-readable explanation of what was detected. */
410
+ message: string;
411
+ /** Optional: how to fix — actionable diff or pattern. */
412
+ suggestion?: string;
413
+ /** Optional: link to docs anchor for more context. */
414
+ docsUrl?: string;
415
+ /**
416
+ * alpha.20 — actionable category for routing/dashboard surfacing. When set,
417
+ * the brain persists this as `recommendation_type` on
418
+ * `compile_outcome_advisories` so consumers can filter "show me all
419
+ * client-side issues that are caching-fix recommendations." Optional;
420
+ * absent on legacy or uncategorized rules.
421
+ *
422
+ * - `'model-swap'` — swap to a different model fixes this
423
+ * - `'prompt-fix'` — restructure prompt (sections, tools, format)
424
+ * - `'caching-fix'` — add cache markers (system or history)
425
+ * - `'no-ai-needed'` — the call shouldn't be using an AI model
426
+ * - `'tier-down'` — current model is overkill for this archetype
427
+ * - `'architecture-change'` — the issue isn't fixable at the kgauto layer
428
+ */
429
+ recommendationType?: 'model-swap' | 'prompt-fix' | 'caching-fix' | 'no-ai-needed' | 'tier-down' | 'architecture-change';
430
+ /**
431
+ * alpha.36 — architectural recommendation when the call shouldn't be an
432
+ * AI call at all, or should be a cheaper non-AI substitute. Optional and
433
+ * orthogonal to {@link recommendationType}: when set, narrows the
434
+ * `no-ai-needed` / `architecture-change` rec-type into an actionable
435
+ * pattern the consumer can implement.
436
+ *
437
+ * - `'lookup-table'` — deterministic input → output mapping (≥95% agreement at high N). Build a domain table; fall back to AI for novel inputs.
438
+ * - `'memoization-cache'` — same canonical input recurs across sessions with equivalent output. Add an edge/KV cache keyed on canonical input.
439
+ * - `'tier-down'` — cheaper model tier delivers equal-or-better oracle score on this shape. Move primary to the cheaper tier.
440
+ * - `'deterministic-parser'` — `constraints.structuredOutput: true` calls where the schema is regex/JSON-extractable from the input.
441
+ * - `'precompute'` — input is derivable at build / cron / batch time; eliminate the per-request call entirely.
442
+ *
443
+ * Operator-side detection lives in `v2/scripts/no-ai-needed-detector.mjs`
444
+ * (alpha.36); a compile-time advisor rule that consumes the brain-side
445
+ * findings cache follows in a later alpha. Today populated only by the
446
+ * operator-side detector + the brain RPC `get_no_ai_needed_candidates`
447
+ * (migration 021).
448
+ */
449
+ recommendedArchitecture?: 'lookup-table' | 'memoization-cache' | 'tier-down' | 'deterministic-parser' | 'precompute';
450
+ /**
451
+ * alpha.28 — when a rule wants to surface a specific structural adaptation
452
+ * (not just a swap or a prompt fix), it attaches the adapter shape here.
453
+ * Shape is the canonical {@link Adapter} discriminated union defined in
454
+ * this module; `compatibility.ts` re-exports it so
455
+ * `getModelCompatibility()` and `BestPracticeAdvisory.suggestedAdaptation`
456
+ * share one source of truth.
457
+ *
458
+ * Today fired by `archetype-perf-floor-breach` (alpha.28) when a
459
+ * documented adapter exists for the chosen model's archetype cliff.
460
+ * Absent on rules without a structural adapter (caching-off-on-claude,
461
+ * tool-bloat, etc.) and on the `reject` branch of
462
+ * `archetype-perf-floor-breach` where no adapter would help.
463
+ *
464
+ * CLOSED discriminated union (R3 from consultation doc) — future adapter
465
+ * parameters extend the union in `compatibility.ts` in named alpha
466
+ * releases. No `| string` escape hatch; consumer code can write
467
+ * exhaustive `switch (suggestedAdaptation.parameter)`.
468
+ *
469
+ * Phase 2 cross-builder coherence: Builder A's
470
+ * `AdvisoryRecord.suggestedAdaptation` (in `glassbox-routes/types.ts`)
471
+ * MUST type to the same union. Phase 2 integration verifies.
472
+ */
473
+ suggestedAdaptation?: Adapter;
474
+ /**
475
+ * alpha.42 — the kgauto request handle that produced this advisory. Stamped
476
+ * by `compile()` after `runAdvisor()` returns, sourced from
477
+ * `CompileResult.handle`. Lets a consumer's admin UI pivot from advisory
478
+ * row → original trace (Glass-Box card, brain `compile_outcomes` lookup).
479
+ *
480
+ * Absent when the advisory was constructed outside the full `compile()`
481
+ * pipeline (e.g., a direct `runAdvisor()` call in tests). Always present
482
+ * on advisories returned from `compile().advisories`.
483
+ */
484
+ kgautoRequestId?: string;
485
+ /**
486
+ * alpha.42 — who is positioned to act on this advisory.
487
+ *
488
+ * - `'consumer-actionable'` (Class A): the consumer can fix this by
489
+ * changing their wire-up — add `cacheable: true` markers, swap their
490
+ * model literal, declare a section, etc. The admin UI should surface
491
+ * a one-click apply or a "fix it" CTA.
492
+ * - `'producer-owned'` (Class B): kgauto needs to ship a code or data
493
+ * change — update a profile, promote a model in the chain, fix a
494
+ * wire contract. The admin UI should surface this as informational
495
+ * ("kgauto is on it") and not present a consumer-side action.
496
+ *
497
+ * Stamped by `compile()` after `runAdvisor()` returns. Rules can self-
498
+ * declare via the matching field on their return; otherwise the stamp
499
+ * consults the static `PRODUCER_OWNED_RULE_CODES` set in `advisor.ts`,
500
+ * defaulting to `'consumer-actionable'` when the code isn't listed.
501
+ *
502
+ * Closes the s47 dogfood gap where the tt-intel admin UI conflated the
503
+ * two classes — consumers couldn't tell whether they should act or wait.
504
+ */
505
+ ownership?: 'consumer-actionable' | 'producer-owned';
506
+ }
507
+ /**
508
+ * alpha.28 — adapter shape attached to advisories and returned by
509
+ * `getModelCompatibility()`. A CLOSED discriminated union: future adapter
510
+ * parameters extend it explicitly in named alpha releases. NO `| string`
511
+ * escape hatch — consumer policy code SHOULD write exhaustive
512
+ * `switch (adapter.parameter)` and rely on the compiler to flag
513
+ * "I added a new adapter parameter and forgot to update consumer policy."
514
+ *
515
+ * Defined here (in `ir.ts`, the foundational types module) and re-exported
516
+ * from `compatibility.ts` for ergonomic consumer imports. Anchoring it
517
+ * here avoids the import cycle that would form if both files tried to be
518
+ * the source of truth (ir.ts → compatibility.ts → profiles.ts → ir.ts).
519
+ *
520
+ * alpha.28 variants:
521
+ * - `{ parameter: 'toolOrchestration'; value: 'sequential'; consequence }`
522
+ * Lifts DeepSeek V4-family on `hunt` from the sequential-tool cliff
523
+ * (L-040). `consequence` is consumer-renderable plain English.
524
+ *
525
+ * Future alpha releases will add e.g. `parallelToolCalls`, `maxTools`,
526
+ * `thinkingBudget` (per tt-intel-Cairn priority list).
527
+ */
528
+ type Adapter = {
529
+ parameter: 'toolOrchestration';
530
+ value: 'sequential';
531
+ consequence: string;
532
+ };
533
+ /**
534
+ * alpha.29+ — record of a single section rewrite fired by the translator at
535
+ * compile time. Surfaces on `CompileResult.sectionRewritesApplied` and (in
536
+ * scrubbed wire form, without original/transformed text) on
537
+ * `TraceDetail.sectionRewritesApplied` for Glass-Box Coaching-card rendering.
538
+ *
539
+ * `originalText` / `transformedText` stay package-internal — they may carry
540
+ * consumer PII. The wire-shape variant (`TraceSectionRewrite` in
541
+ * `glassbox-routes/types.ts`) carries only `summary` for renderer use.
542
+ */
543
+ interface SectionRewrite {
544
+ /** Stable id of the `PromptSection` that was rewritten. */
545
+ sectionId: string;
546
+ /** The `kind` discriminator that matched the rewrite rule. */
547
+ kind: SectionKind;
548
+ /**
549
+ * Stable identifier of the rule that fired (e.g.
550
+ * `'sequential-tool-cliff-below-floor'`). Future rules add named ids; the
551
+ * brain aggregates by this value for cross-app learning.
552
+ */
553
+ rule: string;
554
+ /** The section's text BEFORE the rewrite fired. */
555
+ originalText: string;
556
+ /** The text the translator emitted into the IR for this section. */
557
+ transformedText: string;
558
+ /**
559
+ * Wire-level overrides emitted alongside the text rewrite. Merged into
560
+ * `CompileResult.wireOverrides` by `applySectionRewrites`. alpha.29 ships
561
+ * `parallelToolCalls`; the union extends as more wire-overrides surface.
562
+ */
563
+ wireOverrides?: {
564
+ parallelToolCalls?: boolean;
565
+ };
566
+ }
567
+ interface CompileResult {
568
+ /** Unique handle for this call — pass to record() to correlate the outcome. */
569
+ handle: string;
570
+ /** Selected target model id. */
571
+ target: string;
572
+ /** Selected provider. */
573
+ provider: Provider;
574
+ /** The wire request — pass the appropriate fields to your SDK. */
575
+ request: CompiledRequest;
576
+ /** Estimated tokens (input). */
577
+ tokensIn: number;
578
+ /** Estimated cost in USD (input portion). */
579
+ estimatedCostUsd: number;
580
+ /** Mutations that fired during compile (informational). */
581
+ mutationsApplied: MutationApplied[];
582
+ /** Fallback chain — try these in order if target fails. */
583
+ fallbackChain: string[];
584
+ /**
585
+ * Best-practice advisories emitted by the compiler. Non-fatal. Empty
586
+ * array when no rules fired. alpha.6 Phase 1.
587
+ */
588
+ advisories: BestPracticeAdvisory[];
589
+ /**
590
+ * alpha.29+ — per-section rewrites applied by the translator at compile
591
+ * time. Empty array means no rewrites fired (or pre-alpha.29 behavior —
592
+ * all sections default `kind: 'arbitrary'`, which is pass-through).
593
+ *
594
+ * Surfaces to:
595
+ * - Glass-Box Coaching card (via `TraceDetail.sectionRewritesApplied`,
596
+ * scrubbed of original/transformed text)
597
+ * - brain `compile_outcomes.section_rewrites_applied` (migration 019)
598
+ * for cross-app learning
599
+ */
600
+ sectionRewritesApplied: SectionRewrite[];
601
+ /**
602
+ * alpha.29+ — wire-level overrides emitted by translator rewrites. The
603
+ * provider lowering pass threads these through to the wire request before
604
+ * emit. Today only `parallelToolCalls: boolean`; the type extends as more
605
+ * wire-overrides surface.
606
+ *
607
+ * Undefined when no rewrite emitted overrides — the common case.
608
+ */
609
+ wireOverrides?: {
610
+ parallelToolCalls?: boolean;
611
+ };
612
+ /** Diagnostics for caller-side logging. */
613
+ diagnostics: {
614
+ sectionsKept: number;
615
+ sectionsDropped: number;
616
+ toolsKept: number;
617
+ toolsDropped: number;
618
+ historyKept: number;
619
+ historyDropped: number;
620
+ cacheableTokens: number;
621
+ estimatedCacheSavingsUsd: number;
622
+ /**
623
+ * Tokens in `history` (and `currentTurn` when before the marker) that
624
+ * fall within the cacheable prefix per `historyCachePolicy`. Always
625
+ * computed; only Anthropic actually emits a wire-format marker. For
626
+ * Gemini / OpenAI / DeepSeek, this represents the theoretical cacheable
627
+ * prefix that implicit caching may pick up — useful telemetry for the
628
+ * brain to learn which (app, model, archetype) tuples benefit most
629
+ * from history caching. alpha.5.
630
+ */
631
+ historyCacheableTokens: number;
632
+ /**
633
+ * Total tokens in input `history` (pre-compression). Computed regardless
634
+ * of whether `passCompressHistory` fired — surfaces how close a tuple is
635
+ * to its `compressHistoryAboveTokens` threshold so dashboards / cost-
636
+ * watchers can see the bloat axis the count-based threshold misses.
637
+ * 0 when history is empty. alpha.7.
638
+ */
639
+ historyTokensTotal: number;
640
+ /**
641
+ * alpha.20 E3. Consumer-declared tool-orchestration mode for this call,
642
+ * mirrored from `ir.constraints.toolOrchestration` for downstream
643
+ * observability (Glass-Box panel, brain telemetry, advisor logs).
644
+ * Undefined when the consumer hadn't adopted the constraint yet —
645
+ * treat as 'parallel' equivalent for back-compat.
646
+ */
647
+ toolOrchestration?: 'parallel' | 'sequential' | 'either';
648
+ /**
649
+ * alpha.33. Zero-based index into the resolved (post-compression) history
650
+ * array at which Anthropic prompt-cache marker should land — i.e., the
651
+ * last message that belongs to the stable cacheable prefix. Consumers
652
+ * using AI-SDK's `streamText({ messages: convertToModelMessages(...) })`
653
+ * lose the per-message `providerOptions.anthropic.cacheControl` markers
654
+ * the compiler emits on `result.request.messages`, because
655
+ * `convertToModelMessages` reads raw input not the lowered output.
656
+ * This index gives the consumer a single deterministic position to
657
+ * attach `cacheControl: { type: 'ephemeral' }` after their own conversion.
658
+ *
659
+ * Computation:
660
+ * - `historyCachePolicy.strategy === 'all-but-latest'`: history.length - 1
661
+ * (or undefined if history is empty)
662
+ * - `historyCachePolicy.strategy === 'fixed-suffix'` with `suffix: N`:
663
+ * history.length - 1 - N (undefined if N exceeds history length)
664
+ * - `historyCachePolicy.strategy === 'none'` or omitted: undefined
665
+ *
666
+ * The companion helper `attachCacheControlToStreamTextInput()` reads
667
+ * this field + the consumer's converted messages to perform the per-
668
+ * attempt mutation correctly. Filed by IC + tt-intel cross-consumer
669
+ * pattern 2026-05-20 (`streamText-cache-marker-propagation-gap`).
670
+ */
671
+ historyCacheMarkIndex?: number;
672
+ /**
673
+ * alpha.33. Zero-based index into the structured `systemMessages` array
674
+ * (see top-level `systemMessages` field) at which the cacheable system
675
+ * prefix ends. Useful when the consumer is building a multi-block
676
+ * system parameter for Anthropic streamText — they can attach
677
+ * `providerOptions.anthropic.cacheControl` to `systemMessages[index]`.
678
+ *
679
+ * Undefined when no section had `cacheable: true` OR `systemMessages` is
680
+ * empty. Matches `historyCacheMarkIndex` semantics on the history axis.
681
+ */
682
+ systemCacheMarkIndex?: number;
683
+ /**
684
+ * alpha.43. Cliff-style warnings surfaced by the convention pass
685
+ * (`passApplyConventions`) when the selected profile + archetype carry
686
+ * a `cliffWarning` whose preconditions are met. These are informational
687
+ * — they describe a structural mismatch between the call's shape and
688
+ * the chosen family (e.g. "reasoner family is wrong for parallel-tool
689
+ * hunt") so consumers can route differently next time.
690
+ *
691
+ * Empty array when no convention fired or no warnings surfaced.
692
+ * Separate from `cliff_guard` mutations in `mutationsApplied` — those
693
+ * are profile.cliffs[] runtime triggers; these are convention-level
694
+ * advisory text. Both can fire on the same call.
695
+ */
696
+ cliffWarnings: string[];
697
+ };
698
+ /**
699
+ * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
700
+ * consumers. When the consumer's lowered request has cacheable section
701
+ * markers, the flat `system: string` form loses the marker assignment
702
+ * (every `streamText({ system: '<string>' })` call silently strips
703
+ * providerOptions). Pass `systemMessages` instead to `streamText({
704
+ * system: result.systemMessages })` so the cacheable prefix is structurally
705
+ * preserved.
706
+ *
707
+ * Each entry is a `SystemModelMessage`-shaped object:
708
+ * { role: 'system', content: string, providerOptions?: { anthropic?:
709
+ * { cacheControl: { type: 'ephemeral' } } } }
710
+ *
711
+ * Provider-agnostic on emit: only Anthropic actually consumes the
712
+ * cacheControl block; Gemini / OpenAI / DeepSeek receive the same
713
+ * shape but ignore the marker (matching their implicit-caching semantics).
714
+ *
715
+ * Empty array when the IR carried zero sections (rare; usually means the
716
+ * compiler dropped everything for the chosen intent). Consumers can fall
717
+ * back to `result.systemMessages.length === 0 ? '' : result.systemMessages`
718
+ * or use the helper `attachCacheControlToStreamTextInput()` which handles
719
+ * both shapes.
720
+ */
721
+ systemMessages: SystemModelMessage[];
722
+ }
723
+ /**
724
+ * alpha.33. AI-SDK-compatible system-message shape carried on
725
+ * `CompileResult.systemMessages`. Matches the AI-SDK `streamText({ system })`
726
+ * structured form — consumers can pass these directly without conversion.
727
+ *
728
+ * The `providerOptions` field is set ONLY for entries that came from a
729
+ * section with `cacheable: true` AND the chosen provider is Anthropic AND
730
+ * the compiler computed a non-zero `cacheableTokens`. Other providers see
731
+ * `providerOptions: undefined` (or omitted entirely).
732
+ */
733
+ interface SystemModelMessage {
734
+ role: 'system';
735
+ content: string;
736
+ providerOptions?: {
737
+ anthropic?: {
738
+ cacheControl: {
739
+ type: 'ephemeral';
740
+ };
741
+ };
742
+ };
743
+ }
744
+ /**
745
+ * Token usage normalized across providers. `cached` and `cacheCreated` are
746
+ * Anthropic prompt-cache reads/writes (Gemini implicit caching populates
747
+ * `cached` from `usageMetadata.cachedContentTokenCount`; OpenAI populates
748
+ * from `prompt_tokens_details.cached_tokens`).
749
+ */
750
+ interface NormalizedTokens {
751
+ input: number;
752
+ output: number;
753
+ total: number;
754
+ cached?: number;
755
+ cacheCreated?: number;
756
+ }
757
+ /**
758
+ * Tool call in a provider-agnostic shape. Anthropic `tool_use` blocks,
759
+ * Google `functionCall` parts, and OpenAI/DeepSeek `tool_calls[]` all
760
+ * collapse to this.
761
+ */
762
+ interface ToolCall {
763
+ id: string;
764
+ name: string;
765
+ args: Record<string, unknown>;
766
+ }
767
+ interface NormalizedResponse {
768
+ /** Main text body. Empty string if response had no text content. */
769
+ text: string;
770
+ /**
771
+ * Parsed structured output. Populated when ir.constraints.structuredOutput
772
+ * is true and JSON.parse(text) succeeds. Null otherwise.
773
+ */
774
+ structuredOutput: unknown | null;
775
+ /** Tool calls in normalized shape. Empty array if none. */
776
+ toolCalls: ToolCall[];
777
+ tokens: NormalizedTokens;
778
+ /** Provider-specific finish reason, passed through unchanged. */
779
+ finishReason?: string;
780
+ /** Untouched provider response — escape hatch for consumers needing fields not yet normalized. */
781
+ raw: unknown;
782
+ /** Set when structuredOutput parsing was attempted and failed. */
783
+ parseError?: string;
784
+ }
785
+ interface ApiKeys {
786
+ anthropic?: string;
787
+ google?: string;
788
+ openai?: string;
789
+ deepseek?: string;
790
+ }
791
+ /**
792
+ * Per-provider override fields shallow-merged into the lowered request before
793
+ * execution. Lets consumers reach Gemini `safetySettings`, Anthropic
794
+ * `tool_choice`, OpenAI `seed` etc. without bypassing kgauto.
795
+ */
796
+ interface ProviderOverrides {
797
+ anthropic?: Record<string, unknown>;
798
+ google?: Record<string, unknown>;
799
+ openai?: Record<string, unknown>;
800
+ deepseek?: Record<string, unknown>;
801
+ }
802
+ /**
803
+ * Full-IR inline shadow-probe config (Shape B, Phase 1 — 2026-05-29 s51).
804
+ *
805
+ * When set on `call()`, after the primary response is served kgauto re-lowers
806
+ * the SAME in-memory PromptIR to each candidate and runs it, persisting a
807
+ * `probe_outcomes` row with `replay_source='inline-full-ir'` and
808
+ * `prompt_fidelity=1.0` — a fair, full-prompt measurement (vs the watchers'
809
+ * lossy `prompt_preview` replay). The probe NEVER blocks the user response and
810
+ * NEVER persists the raw prompt (system/context/payload) — only response
811
+ * previews + metadata, same policy the brain already holds.
812
+ *
813
+ * This is the trustworthy path that earns the right to a quality verdict;
814
+ * `prompt_preview` replay is retired for verdicts (see CLAUDE.md).
815
+ *
816
+ * Phase 1 enforces `sampleRate` and runs the candidate with `judge: 'off'`
817
+ * (responses stored for an offline batch judge). `judge: 'opus'` (inline
818
+ * verdict) and `maxPerDay` (per-tuple daily cap, needs a brain-count read)
819
+ * are accepted by the type but ENFORCED IN PHASE 2.
820
+ */
821
+ interface ShadowProbeConfig {
822
+ /** Model id(s) or family alias(es) to shadow-test against the served model, on the same IR. */
823
+ candidates: string | string[];
824
+ /** Probability [0,1] that any given call fires a probe. Default 0.05. */
825
+ sampleRate?: number;
826
+ /**
827
+ * 'off' (Phase 1 default): run candidate + store both responses for an
828
+ * offline batch judge. 'opus': judge candidate-vs-served inline (Phase 2).
829
+ */
830
+ judge?: 'opus' | 'off';
831
+ /** Per-(appId, archetype, candidate) daily cap. Phase 2 (needs brain-count read). Default 20. */
832
+ maxPerDay?: number;
833
+ /**
834
+ * alpha — latency budget (ms) for the probe leg. **Only enforced in sync mode**
835
+ * (`BrainConfig.sync === true`), where `call()` awaits the probe before returning
836
+ * the served response (PB-class Edge consumers, L-086) and the candidate's
837
+ * latency therefore lands on the user-facing critical path.
838
+ *
839
+ * The probe path races against this budget: if the candidate(s) don't finish
840
+ * within `maxLatencyMs`, the probe aborts, `call()` returns the already-served
841
+ * response immediately, and an `outcome='aborted_latency_budget'` row is
842
+ * recorded (no verdict, no false quality data). **The user is never delayed
843
+ * past the budget.** Default `15000`.
844
+ *
845
+ * No-op for fire-and-forget consumers (`sync` unset/false, and every
846
+ * `probeShadow()` caller fired from `after()`/`waitUntil()`) — they don't block
847
+ * the user, so there's no latency to bound. The probe runs to completion there.
848
+ *
849
+ * Root cause this closes (PB s57 dogfood incident, 2026-06-05): PB arms the
850
+ * probe inline with `sync:true` on a `maxDuration:120` analyze route; arming a
851
+ * `latency_tier='slow'` candidate (deepseek-v4-pro, ~78–84s) pushed total
852
+ * handler time past the frontend's patience and the served analysis came back
853
+ * empty. A sync probe had no latency budget — this field is the budget.
854
+ */
855
+ maxLatencyMs?: number;
856
+ /**
857
+ * alpha — when true (the default) **in sync mode**, skip a candidate whose
858
+ * registry `latency_tier === 'slow'` *before starting it*: a slow-tier model
859
+ * (e.g. deepseek-v4-pro / deepseek-v4-flash, both `slow` = ~24s+ p50) cannot
860
+ * fit a sane inline budget, so starting it just to abort it wastes a provider
861
+ * call. An `outcome='skipped_slow_tier_sync'` row is recorded so the offline
862
+ * rollup can see the skip (not a silent drop, not a false verdict). Fail-safe.
863
+ *
864
+ * **The deeper rule (slow-reasoner → offline-mode):** inline shadow-probing is
865
+ * for FAST candidates only. To evaluate a slow reasoner you need the offline /
866
+ * async probe path (the Phase-2 batch direction) which runs off the response
867
+ * entirely — never the inline sync probe. Set this `false` only if you've moved
868
+ * the budget high enough that a slow candidate genuinely fits (rare), or you're
869
+ * in a non-sync consumer where this flag is a no-op anyway.
870
+ *
871
+ * No-op for fire-and-forget consumers (`sync` unset/false; `probeShadow()`):
872
+ * there's no user latency to protect, so slow candidates run normally. Default
873
+ * `true`.
874
+ */
875
+ skipSlowTierInSync?: boolean;
876
+ }
877
+ interface CallOptions {
878
+ /** Forwarded to compile(). */
879
+ policy?: CompilePolicy;
880
+ /**
881
+ * alpha (s51 Phase 1) — full-IR inline shadow-probe. When set, kgauto
882
+ * measures the candidate(s) on the same IR after serving the primary,
883
+ * fire-and-forget. See {@link ShadowProbeConfig}.
884
+ */
885
+ shadowProbe?: ShadowProbeConfig;
886
+ toolRelevanceThreshold?: number;
887
+ compressHistoryAfter?: number;
888
+ /** Override API keys (defaults: process.env). */
889
+ apiKeys?: ApiKeys;
890
+ /** Provider-specific request fields shallow-merged into the lowered request. */
891
+ providerOverrides?: ProviderOverrides;
892
+ /** Override fetch (for tests). */
893
+ fetchImpl?: typeof fetch;
894
+ /** Disable retry/fallback walk on retryable errors. Default: enabled. */
895
+ noFallback?: boolean;
896
+ /**
897
+ * alpha.10. Disable the silent auto-filter of unreachable models from the
898
+ * fallback walk. Default: false (filter ON). Opt-out exists for tests +
899
+ * the rare consumer that wants the legacy "fail at execute() with auth
900
+ * error" behavior. When ON (default), models whose provider has no
901
+ * resolvable API key are dropped from `targetsToTry` before the first
902
+ * network call; if the chain empties entirely, throws CallError with
903
+ * `lastErrorCode = 'no_reachable_models'`.
904
+ *
905
+ * Reachability source: `apiKeys` (this CallOptions) + `process.env` (via
906
+ * `PROVIDER_ENV_KEYS`). Override env via env.ts's `ReachabilityOpts.envSource`
907
+ * is not exposed here — `call()` always uses process.env. Use
908
+ * `getDefaultFallbackChain({ reachability: { envSource } })` upstream
909
+ * for hermetic test runs.
910
+ */
911
+ noAutoFilter?: boolean;
912
+ /**
913
+ * alpha.34. When provided AND the chosen provider supports streaming
914
+ * (`profile.streaming === true`) AND `noStream` is not set, kgauto
915
+ * enables provider-native SSE streaming at the wire layer and invokes
916
+ * `onChunk(delta)` once per provider stream event. `delta` is the text
917
+ * since the previous `onChunk` call (NOT cumulative) — provider
918
+ * stream-shape headache normalized in kgauto's lowering layer.
919
+ *
920
+ * `CallResult.response.text` is still populated with the full assembled
921
+ * response — kgauto buffers internally regardless of the callback.
922
+ * Consumers can use either the streaming side-effect OR the final
923
+ * `response.text`, doesn't matter.
924
+ *
925
+ * Tool calls + finish reason + usage are collected from stream events
926
+ * and returned in the final `CallResult` exactly as the non-streaming
927
+ * path would shape them. Brain telemetry latency = time-to-stream-end.
928
+ *
929
+ * Chain-walk semantics: if the streaming target fails mid-stream
930
+ * (network error, retryable provider error), kgauto walks to the next
931
+ * fallback target and restarts streaming from its first chunk —
932
+ * `onChunk` fires fresh from the new target. Consumer detects via the
933
+ * post-call `CallResult.fellOverFrom`. To opt out of fallback for
934
+ * streaming, set `noFallback: true` alongside `onChunk`.
935
+ *
936
+ * Filed by playbacksam s42 (2026-05-22) as `streaming-output-callback-
937
+ * on-callresult` for ComposeDrawer SSE; perceived-latency UX win
938
+ * during 10-30s draft assembly.
939
+ */
940
+ onChunk?: (chunk: string) => void;
941
+ /**
942
+ * alpha.34. Explicit opt-out of streaming even when `onChunk` is
943
+ * provided. Default: false (streaming enabled when `onChunk` is set).
944
+ * Use when the consumer wants to pass `onChunk` conditionally without
945
+ * branching the call site (e.g., capture chunks for instrumentation
946
+ * without engaging streaming wire format).
947
+ */
948
+ noStream?: boolean;
949
+ }
950
+ interface CallAttempt {
951
+ model: string;
952
+ status: 'success' | 'retryable' | 'terminal';
953
+ errorCode?: string;
954
+ message?: string;
955
+ }
956
+ /**
957
+ * Why fallback fired. Normalized for `CallResult.fallbackReason` (alpha.9).
958
+ *
959
+ * - `rate_limit` provider returned 429
960
+ * - `provider_error` 5xx, network, or other retryable upstream issue
961
+ * - `cost_cap` preflight policy.maxCostPerCallUsd rejected target
962
+ * - `cliff` alpha.8 contract violation (MAX_TOKENS on
963
+ * structured output, parse-failed JSON)
964
+ * - `contract_violation` other compile-time-contract failures (reserved
965
+ * for alpha.10+ — e.g. mid-stream policy rejects)
966
+ * - `provider_auth_failed` alpha.14 — initial provider returned 401/403
967
+ * (upstream key revocation, malformed-but-truthy
968
+ * key, billing lapse). The chain walks to the
969
+ * next non-same-provider target instead of
970
+ * short-circuiting; same-provider remaining
971
+ * entries skip with errorCode='auth_inferred'.
972
+ */
973
+ type FallbackReason = 'rate_limit' | 'provider_error' | 'cost_cap' | 'cliff' | 'contract_violation' | 'provider_auth_failed';
974
+ interface CallResult {
975
+ /** Compile handle (still valid for record() if consumer wants to add oracle scores later). */
976
+ handle: string;
977
+ /** The model that ACTUALLY served the response (post-fallback). */
978
+ actualModel: string;
979
+ /** What compile() originally targeted. */
980
+ requestedModel: string;
981
+ provider: Provider;
982
+ response: NormalizedResponse;
983
+ latencyMs: number;
984
+ /** Mutations that fired during compile (informational, mirrors CompileResult.mutationsApplied). */
985
+ mutationsApplied: MutationApplied[];
986
+ /** One entry per provider attempt — observability for retry/fallback walks. */
987
+ attempts: CallAttempt[];
988
+ /**
989
+ * Alpha.9 normalization of fallback-walk telemetry. When the chain
990
+ * succeeded on the first attempt, these collapse to:
991
+ * - `servedBy === requestedModel`
992
+ * - `fellOverFrom` undefined
993
+ * - `fallbackReason` undefined
994
+ *
995
+ * When fallback fired:
996
+ * - `servedBy` = `actualModel` (the model that produced the response)
997
+ * - `fellOverFrom` = `requestedModel` (what the caller / compile() asked for)
998
+ * - `fallbackReason` = normalized cause derived from the first
999
+ * non-success attempt's `errorCode`
1000
+ *
1001
+ * Consumer UX use: show "Claude was busy; we used Pro for this answer"
1002
+ * when `fellOverFrom` is set (master plan §3.6).
1003
+ */
1004
+ /** Model that actually answered. Equal to `actualModel`; kept distinct for clarity. */
1005
+ servedBy: string;
1006
+ /** Set only when fallback fired. Equal to `requestedModel` in that case. */
1007
+ fellOverFrom?: string;
1008
+ /** Set only when fallback fired. Normalized cause. */
1009
+ fallbackReason?: FallbackReason;
1010
+ /**
1011
+ * alpha.10. Models that auto-filter dropped from the fallback walk because
1012
+ * their provider had no reachable API key. Empty when nothing was filtered
1013
+ * (the common case once consumers have all the keys they need). Surfaces
1014
+ * silent self-heal so consumers can log/audit what happened without
1015
+ * defeating the "kgauto just gets" UX.
1016
+ *
1017
+ * Empty array (not undefined) when filter ran but dropped nothing —
1018
+ * distinguishes "filter ran cleanly" from "filter was disabled" (`undefined`
1019
+ * when `noAutoFilter: true`).
1020
+ */
1021
+ unreachableFiltered?: string[];
1022
+ /**
1023
+ * alpha.16. Models that policy.blockedModels filtering dropped from the
1024
+ * fallback walk. Defense-in-depth at the call() boundary — compile()'s
1025
+ * passScoreTargets already excludes blocked entries from the initial
1026
+ * target + fallbackChain, but if a consumer re-shapes the chain and
1027
+ * threads policy through only partially, this filter catches the gap.
1028
+ *
1029
+ * Resolves TT-40 follow-on `policy-block-not-enforced-on-fallback-chain`
1030
+ * (2026-05-15) where mutations_applied recorded the block intent but
1031
+ * the call walker landed on the blocked model anyway.
1032
+ *
1033
+ * Undefined when no filter ran (no blockedModels set). Populated only
1034
+ * when filter ran AND dropped at least one entry — empty drops are
1035
+ * stored as `undefined` to keep brain telemetry quiet on the common
1036
+ * case.
1037
+ */
1038
+ policyBlockedFiltered?: string[];
1039
+ /**
1040
+ * alpha.17. Unique identifier for this call() invocation, generated at
1041
+ * call() entry via crypto.randomUUID(). Returned on success and emitted
1042
+ * as the routing key for Glass-Box observability events
1043
+ * (compile.start, compile.done, execute.attempt, execute.success,
1044
+ * fallback.walked, advisory.fired). Pass the same id to
1045
+ * `subscribe(traceId)` from `@warmdrift/kgauto-compiler/glassbox` to
1046
+ * tap the in-flight event stream.
1047
+ *
1048
+ * Always present on success. Additive, non-breaking.
1049
+ */
1050
+ traceId: string;
1051
+ /**
1052
+ * alpha.44. Best-practice advisories emitted by the compile that actually
1053
+ * served the response (mirrors `CompileResult.advisories`; uses the SERVED
1054
+ * compile on fallback, same as `mutationsApplied`). Empty array when no
1055
+ * rules fired.
1056
+ *
1057
+ * Closes IC's `callForAgent` side-finding (2026-05-26): call() consumers
1058
+ * (agent paths — sweep / dyad / session-title) previously had no way to
1059
+ * `logAdvisories('[kgauto-v2 ...]', advisories)` like compile() consumers
1060
+ * (chat / intake) do, because the advisories were consumed internally
1061
+ * (trace events, brain record) but never returned. Additive, non-breaking.
1062
+ */
1063
+ advisories: BestPracticeAdvisory[];
1064
+ }
1065
+ /**
1066
+ * Thrown when call() exhausts the fallback chain without success.
1067
+ * `attempts` carries every model tried + classification.
1068
+ */
1069
+ declare class CallError extends Error {
1070
+ readonly attempts: CallAttempt[];
1071
+ readonly lastErrorCode?: string;
1072
+ readonly lastStatus?: number;
1073
+ constructor(message: string, attempts: CallAttempt[], lastStatus?: number, lastErrorCode?: string);
1074
+ }
1075
+ interface OracleScore {
1076
+ /** 0..1 overall quality. */
1077
+ score: number;
1078
+ /** Optional per-dimension breakdown. */
1079
+ dimensions?: Record<string, number>;
1080
+ /** Free-form explanation for debugging. */
1081
+ rationale?: string;
1082
+ }
1083
+ interface RecordInput {
1084
+ /** Handle from CompileResult. */
1085
+ handle: string;
1086
+ /** Actual tokens consumed (post-call). */
1087
+ tokensIn: number;
1088
+ tokensOut: number;
1089
+ /** Wall-clock latency in ms. */
1090
+ latencyMs: number;
1091
+ /** True iff the call returned a usable response. */
1092
+ success: boolean;
1093
+ /** True iff the call returned 0 output tokens despite success. */
1094
+ emptyResponse?: boolean;
1095
+ /** Provider error code if any. */
1096
+ errorType?: string;
1097
+ /** Tools actually invoked by the model. */
1098
+ toolsCalled?: string[];
1099
+ /** Oracle quality score — required for learning to fire. */
1100
+ oracleScore?: OracleScore;
1101
+ /** Optional: scrubbed prompt/response previews for debugging. */
1102
+ promptPreview?: string;
1103
+ responsePreview?: string;
1104
+ /**
1105
+ * The model that ACTUALLY RAN. Set this when consumer-side fallback ran
1106
+ * a different model than v2 compile() targeted. Brain stores this as
1107
+ * `model` (the truth) and the original target as `requested_model`.
1108
+ *
1109
+ * Omit when no fallback occurred — brain stores compile target as `model`
1110
+ * (still the truth in that case) and `requested_model` stays NULL.
1111
+ *
1112
+ * s11 fix: prevents the brain from misattributing fallback traffic to
1113
+ * the originally-requested model.
1114
+ */
1115
+ actualModel?: string;
1116
+ /**
1117
+ * Override `mutations_applied` for this outcome. Set by `call()` when
1118
+ * fallback fires — the served compile's mutations (which actually shaped
1119
+ * the request that went on the wire) replace the initial compile's
1120
+ * mutations (registered against the handle). Without this override, fallback
1121
+ * traffic is attributed to the initial compile's mutations and the brain's
1122
+ * mutation effectiveness stats become misleading.
1123
+ *
1124
+ * alpha.4: extends s11 truth-in-logging to mutations.
1125
+ */
1126
+ mutationsApplied?: string[];
1127
+ /**
1128
+ * Cache read input tokens, when supported by the provider.
1129
+ * - Anthropic: `usage.cache_read_input_tokens`
1130
+ * - Google (implicit caching): `usageMetadata.cachedContentTokenCount`
1131
+ * - OpenAI: `usage.prompt_tokens_details.cached_tokens`
1132
+ *
1133
+ * Powers the cost-and-efficiency-watcher (interfaces/kgauto.md, alpha.4):
1134
+ * `tokens_in - cache_read_input_tokens` is the un-cached new context per call.
1135
+ */
1136
+ cacheReadInputTokens?: number;
1137
+ /**
1138
+ * Cache creation input tokens (Anthropic-specific).
1139
+ * `usage.cache_creation_input_tokens`. The first call that pays the 25%
1140
+ * upcharge to write a cache marker; subsequent calls hit `cacheRead`.
1141
+ */
1142
+ cacheCreationInputTokens?: number;
1143
+ /**
1144
+ * Time to first token (ms). Optional; populated when the provider/SDK
1145
+ * surfaces it. Distinct from `latencyMs` (end-to-end wall clock).
1146
+ */
1147
+ ttftMs?: number;
1148
+ /**
1149
+ * alpha.20 — advisories fired at compile() time. Persisted to the brain's
1150
+ * `compile_outcome_advisories` sibling table via a second POST that fires
1151
+ * AFTER the primary outcome insert succeeds. Best-effort: a failed
1152
+ * advisory POST is logged via onError but does NOT throw or roll back the
1153
+ * primary outcome row.
1154
+ *
1155
+ * Pass `result.advisories` from the CompileResult directly. The brain
1156
+ * uses these to compute the `empty_rate_clean` comparator (rows with
1157
+ * zero advisories fired) so consumers can distinguish "model is bad"
1158
+ * from "client sent a bloated/uncached/malformed request."
1159
+ *
1160
+ * Empty array / undefined → no second POST fires.
1161
+ */
1162
+ advisories?: BestPracticeAdvisory[];
1163
+ /**
1164
+ * alpha.28 — Glass-Box renderer substrate fields (migration 018).
1165
+ *
1166
+ * All optional. When omitted, brain stores NULL and the renderer falls
1167
+ * back to "—" / hidden rows. Library callers (`call.ts`) populate what
1168
+ * they observe; adapter / SDK consumers can populate the rest from their
1169
+ * own provider response surface.
1170
+ */
1171
+ /**
1172
+ * Provider finish reason. Captured from NormalizedResponse.finishReason
1173
+ * (Anthropic `stop_reason`, Google `finishReason`, OpenAI `finish_reason`).
1174
+ * Lower-case canonicalization is the brain's job; consumers can pass
1175
+ * raw provider strings.
1176
+ */
1177
+ finishReason?: string;
1178
+ /**
1179
+ * End-to-end wall-clock latency in ms. Distinct from `latencyMs` only
1180
+ * insofar as `latencyMs` was the historical name for the same metric;
1181
+ * `totalMs` is the new column on `compile_outcomes` (migration 018).
1182
+ * When omitted, brain mirrors `latency_ms`.
1183
+ */
1184
+ totalMs?: number;
1185
+ /** Tools kept after the tool-relevance pass. */
1186
+ toolsCount?: number;
1187
+ /** Number of history messages at compile time. */
1188
+ historyDepth?: number;
1189
+ /** Rendered system prompt size in characters. */
1190
+ systemPromptChars?: number;
1191
+ /** Model originally targeted when a fallback fired. */
1192
+ fellOverFrom?: string;
1193
+ /**
1194
+ * Why the fallback fired. Closed set mirroring CallResult.fallbackReason —
1195
+ * keep in sync with the wire-contract enum (TraceDetail.fallbackReason).
1196
+ */
1197
+ fallbackReason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
1198
+ }
1199
+ /**
1200
+ * alpha.20 Entry 4: kinds of consumer-declared outcomes feeding the quality
1201
+ * loop. Surfaces in `recordOutcome()` as the verdict the consumer's UX is
1202
+ * forwarding to the brain.
1203
+ *
1204
+ * - `approved` user explicitly approved (thumbs up, "looks good", accepted)
1205
+ * - `rejected` user explicitly rejected (thumbs down, "redo", discarded)
1206
+ * - `partial` accepted with edits or partial use (mixed signal)
1207
+ * - `engaged` user engaged with the output (copy/scroll/dwell)
1208
+ * - `abandoned` user abandoned the response (closed, navigated away)
1209
+ * - `unknown` verdict could not be inferred — recorded for completeness
1210
+ */
1211
+ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned' | 'unknown';
1212
+ /**
1213
+ * Input to `recordOutcome()` — consumer's verdict on a previously-compiled
1214
+ * call. Joins to the original `compile_outcomes` row via outcomeId,
1215
+ * enabling per-(model, archetype) approve-rate measurement once N ≥ 10
1216
+ * outcomes accumulate.
1217
+ */
1218
+ interface RecordOutcomeInput {
1219
+ /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1220
+ outcomeId: number | string;
1221
+ /** What did the user / system do with this output? */
1222
+ outcome: OutcomeKind;
1223
+ /** Optional 1-5 user rating (e.g., thumbs up/down with intensity, NPS-style). */
1224
+ rating?: 1 | 2 | 3 | 4 | 5;
1225
+ /** Optional free-text reason (e.g., user-typed feedback, system-inferred cause). */
1226
+ reason?: string;
1227
+ /**
1228
+ * Optional model-reported confidence at compile time (0..1). Used for
1229
+ * Brier-score calibration in later phases (alpha.21+) — pair this with
1230
+ * the actual `outcome` to compute calibration error.
1231
+ */
1232
+ observedConfidence?: number;
1233
+ }
1234
+ /**
1235
+ * Return shape of `recordOutcome()`. Never throws — persistence failures
1236
+ * surface as `ok: false` with a stable `reason` string.
1237
+ */
1238
+ interface OutcomeResult {
1239
+ /** True when the POST landed (2xx). False when brain not configured or POST failed. */
1240
+ ok: boolean;
1241
+ /** Stable reason code when ok=false. One of: 'brain_not_configured' | 'persistence_failed'. */
1242
+ reason?: string;
1243
+ }
1244
+ /**
1245
+ * alpha.21 (s78 Entry 1): provenance label on a chain entry. Surfaces WHY
1246
+ * an entry sits where it sits so consumers can distinguish:
1247
+ *
1248
+ * - 'measured' brain has N>=10 rows with a measurable quality
1249
+ * outcome backing this placement. The number lives on
1250
+ * `ChainEntry.n`.
1251
+ * - 'capability-fact' inclusion or exclusion driven by a published or
1252
+ * measured CAPABILITY (L-040 cliff, ctx window cap,
1253
+ * structured-output support). Not an opinion — a
1254
+ * fact about what the model can/can't do.
1255
+ * - 'judgment' engineer's pick, no measured backing yet. Cold-start
1256
+ * prior; entirely valid until evidence accumulates.
1257
+ *
1258
+ * "Judgment" is HONEST, not a downgrade. Most of `STARTER_CHAINS` lands here
1259
+ * in alpha.21 — that's the point: consumers can SEE the grounding gap and
1260
+ * prioritize the measurement work that would graduate them to 'measured'.
1261
+ */
1262
+ type Grounding = 'measured' | 'capability-fact' | 'judgment';
1263
+ /**
1264
+ * alpha.21 (s78 Entry 1): a single position in a fallback chain, carrying its
1265
+ * provenance label and an optional human-readable reason. The shape replaces
1266
+ * the old `string[]` representation everywhere chains are surfaced externally.
1267
+ *
1268
+ * `n` is REQUIRED when `grounding === 'measured'` — the runtime helper
1269
+ * `makeMeasuredEntry()` enforces this. For 'capability-fact' and 'judgment'
1270
+ * entries, `n` is undefined.
1271
+ */
1272
+ interface ChainEntry {
1273
+ /** Canonical model id (post-alias). */
1274
+ id: string;
1275
+ /** Why this entry sits in this position. */
1276
+ grounding: Grounding;
1277
+ /**
1278
+ * Optional one-liner explaining the grounding decision. The inline comments
1279
+ * that historically lived next to STARTER_CHAINS entries are now expressed
1280
+ * here as machine-readable text.
1281
+ */
1282
+ reason?: string;
1283
+ /**
1284
+ * When `grounding === 'measured'`, the brain row count that backs this
1285
+ * placement. Undefined for 'capability-fact' and 'judgment' entries.
1286
+ */
1287
+ n?: number;
1288
+ }
1289
+ /**
1290
+ * alpha.21 introspection shape — a per-archetype chain with grounding on
1291
+ * every position. Consumers reading this never see naked string ids;
1292
+ * everything carries provenance.
1293
+ */
1294
+ interface ChainWithGrounding {
1295
+ archetype: IntentArchetypeName;
1296
+ /** Ordered: position 0 = primary, rising index = fallback positions. */
1297
+ entries: ChainEntry[];
1298
+ }
1299
+ /** alpha.23 (s78 Phase 3): per-axis metrics returned by the brain RPC. */
1300
+ interface PerAxisMetrics {
1301
+ appId: string;
1302
+ archetype: string;
1303
+ model: string;
1304
+ windowDays: number;
1305
+ /** Total brain rows for this tuple in the window. */
1306
+ nRows: number;
1307
+ /** Subset of nRows with zero advisories fired — the "clean signal" comparator. */
1308
+ nRowsClean: number;
1309
+ /** Count of compile_outcome_quality entries joining to this tuple's outcomes. */
1310
+ nQualityOutcomes: number;
1311
+ /** Approve rate from quality outcomes. null when nQualityOutcomes === 0. */
1312
+ magicRate: number | null;
1313
+ /** Whether magicRate >= consumer-declared qualityFloor. null when no floor declared OR no outcomes. */
1314
+ qualityFloorMet: boolean | null;
1315
+ costEfficiency: {
1316
+ avgCostUsd: number | null;
1317
+ avgCostUsdClean: number | null;
1318
+ avgInputTokens: number | null;
1319
+ avgOutputTokens: number | null;
1320
+ inputTokenRatio: number | null;
1321
+ };
1322
+ timeEfficiency: {
1323
+ avgLatencyMs: number | null;
1324
+ avgTtftMs: number | null;
1325
+ };
1326
+ reliability: {
1327
+ successRate: number | null;
1328
+ successRateClean: number | null;
1329
+ emptyRate: number | null;
1330
+ emptyRateClean: number | null;
1331
+ };
1332
+ evidenceFreshnessDays: number | null;
1333
+ }
1334
+ /** Per-axis metrics keyed by model — used for chain-comparison views. */
1335
+ type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1336
+
1337
+ export { type ApiKeys as A, type BestPracticeAdvisory as B, type CompilePolicy as C, type FallbackReason as F, type Grounding as G, type HistoryCachePolicy as H, type IntentDeclaration as I, type Message as M, type NormalizedResponse as N, type OutcomeResult as O, type ProviderOverrides as P, type RecordInput as R, type SystemModelMessage as S, type ToolCall as T, type CompiledRequest as a, type PromptIR as b, type CallOptions as c, type CallResult as d, type CompileResult as e, type SectionRewrite as f, type RecordOutcomeInput as g, type OracleScore as h, type Adapter as i, type PerAxisMetrics as j, type Provider as k, type ChainEntry as l, type CallAttempt as m, CallError as n, type ChainModelEntry as o, type ChainWithGrounding as p, type Constraints as q, type MutationApplied as r, type NormalizedTokens as s, type OutcomeKind as t, type PerAxisMetricsByModel as u, type PromptSection as v, type SectionKind as w, type ShadowProbeConfig as x, type ToolDefinition as y };