@warmdrift/kgauto-compiler 2.0.0-alpha.4 → 2.0.0-alpha.42

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 +87 -3
  2. package/dist/chunk-JQGRWJZO.mjs +1216 -0
  3. package/dist/chunk-KCNQUMHN.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 +2473 -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 +1796 -9
  24. package/dist/index.d.ts +1796 -9
  25. package/dist/index.js +4771 -312
  26. package/dist/index.mjs +2951 -275
  27. package/dist/ir-BG70lg9b.d.mts +1229 -0
  28. package/dist/ir-BmumS1Du.d.ts +1229 -0
  29. package/dist/profiles.d.mts +164 -2
  30. package/dist/profiles.d.ts +164 -2
  31. package/dist/profiles.js +820 -11
  32. package/dist/profiles.mjs +5 -1
  33. package/dist/types-Cs_hsBGm.d.ts +131 -0
  34. package/dist/types-DIl0tCDX.d.mts +149 -0
  35. package/dist/types-eKKDeADI.d.mts +131 -0
  36. package/dist/types-kFsIDC_5.d.ts +149 -0
  37. package/package.json +42 -6
  38. package/dist/chunk-MBEI5UOM.mjs +0 -409
  39. package/dist/profiles-CDttLtaD.d.ts +0 -521
  40. package/dist/profiles-CH_nKPjp.d.mts +0 -521
@@ -0,0 +1,1229 @@
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
+ /**
685
+ * alpha.33. Structured `system` for AI-SDK `streamText({ system })`
686
+ * consumers. When the consumer's lowered request has cacheable section
687
+ * markers, the flat `system: string` form loses the marker assignment
688
+ * (every `streamText({ system: '<string>' })` call silently strips
689
+ * providerOptions). Pass `systemMessages` instead to `streamText({
690
+ * system: result.systemMessages })` so the cacheable prefix is structurally
691
+ * preserved.
692
+ *
693
+ * Each entry is a `SystemModelMessage`-shaped object:
694
+ * { role: 'system', content: string, providerOptions?: { anthropic?:
695
+ * { cacheControl: { type: 'ephemeral' } } } }
696
+ *
697
+ * Provider-agnostic on emit: only Anthropic actually consumes the
698
+ * cacheControl block; Gemini / OpenAI / DeepSeek receive the same
699
+ * shape but ignore the marker (matching their implicit-caching semantics).
700
+ *
701
+ * Empty array when the IR carried zero sections (rare; usually means the
702
+ * compiler dropped everything for the chosen intent). Consumers can fall
703
+ * back to `result.systemMessages.length === 0 ? '' : result.systemMessages`
704
+ * or use the helper `attachCacheControlToStreamTextInput()` which handles
705
+ * both shapes.
706
+ */
707
+ systemMessages: SystemModelMessage[];
708
+ }
709
+ /**
710
+ * alpha.33. AI-SDK-compatible system-message shape carried on
711
+ * `CompileResult.systemMessages`. Matches the AI-SDK `streamText({ system })`
712
+ * structured form — consumers can pass these directly without conversion.
713
+ *
714
+ * The `providerOptions` field is set ONLY for entries that came from a
715
+ * section with `cacheable: true` AND the chosen provider is Anthropic AND
716
+ * the compiler computed a non-zero `cacheableTokens`. Other providers see
717
+ * `providerOptions: undefined` (or omitted entirely).
718
+ */
719
+ interface SystemModelMessage {
720
+ role: 'system';
721
+ content: string;
722
+ providerOptions?: {
723
+ anthropic?: {
724
+ cacheControl: {
725
+ type: 'ephemeral';
726
+ };
727
+ };
728
+ };
729
+ }
730
+ /**
731
+ * Token usage normalized across providers. `cached` and `cacheCreated` are
732
+ * Anthropic prompt-cache reads/writes (Gemini implicit caching populates
733
+ * `cached` from `usageMetadata.cachedContentTokenCount`; OpenAI populates
734
+ * from `prompt_tokens_details.cached_tokens`).
735
+ */
736
+ interface NormalizedTokens {
737
+ input: number;
738
+ output: number;
739
+ total: number;
740
+ cached?: number;
741
+ cacheCreated?: number;
742
+ }
743
+ /**
744
+ * Tool call in a provider-agnostic shape. Anthropic `tool_use` blocks,
745
+ * Google `functionCall` parts, and OpenAI/DeepSeek `tool_calls[]` all
746
+ * collapse to this.
747
+ */
748
+ interface ToolCall {
749
+ id: string;
750
+ name: string;
751
+ args: Record<string, unknown>;
752
+ }
753
+ interface NormalizedResponse {
754
+ /** Main text body. Empty string if response had no text content. */
755
+ text: string;
756
+ /**
757
+ * Parsed structured output. Populated when ir.constraints.structuredOutput
758
+ * is true and JSON.parse(text) succeeds. Null otherwise.
759
+ */
760
+ structuredOutput: unknown | null;
761
+ /** Tool calls in normalized shape. Empty array if none. */
762
+ toolCalls: ToolCall[];
763
+ tokens: NormalizedTokens;
764
+ /** Provider-specific finish reason, passed through unchanged. */
765
+ finishReason?: string;
766
+ /** Untouched provider response — escape hatch for consumers needing fields not yet normalized. */
767
+ raw: unknown;
768
+ /** Set when structuredOutput parsing was attempted and failed. */
769
+ parseError?: string;
770
+ }
771
+ interface ApiKeys {
772
+ anthropic?: string;
773
+ google?: string;
774
+ openai?: string;
775
+ deepseek?: string;
776
+ }
777
+ /**
778
+ * Per-provider override fields shallow-merged into the lowered request before
779
+ * execution. Lets consumers reach Gemini `safetySettings`, Anthropic
780
+ * `tool_choice`, OpenAI `seed` etc. without bypassing kgauto.
781
+ */
782
+ interface ProviderOverrides {
783
+ anthropic?: Record<string, unknown>;
784
+ google?: Record<string, unknown>;
785
+ openai?: Record<string, unknown>;
786
+ deepseek?: Record<string, unknown>;
787
+ }
788
+ interface CallOptions {
789
+ /** Forwarded to compile(). */
790
+ policy?: CompilePolicy;
791
+ toolRelevanceThreshold?: number;
792
+ compressHistoryAfter?: number;
793
+ /** Override API keys (defaults: process.env). */
794
+ apiKeys?: ApiKeys;
795
+ /** Provider-specific request fields shallow-merged into the lowered request. */
796
+ providerOverrides?: ProviderOverrides;
797
+ /** Override fetch (for tests). */
798
+ fetchImpl?: typeof fetch;
799
+ /** Disable retry/fallback walk on retryable errors. Default: enabled. */
800
+ noFallback?: boolean;
801
+ /**
802
+ * alpha.10. Disable the silent auto-filter of unreachable models from the
803
+ * fallback walk. Default: false (filter ON). Opt-out exists for tests +
804
+ * the rare consumer that wants the legacy "fail at execute() with auth
805
+ * error" behavior. When ON (default), models whose provider has no
806
+ * resolvable API key are dropped from `targetsToTry` before the first
807
+ * network call; if the chain empties entirely, throws CallError with
808
+ * `lastErrorCode = 'no_reachable_models'`.
809
+ *
810
+ * Reachability source: `apiKeys` (this CallOptions) + `process.env` (via
811
+ * `PROVIDER_ENV_KEYS`). Override env via env.ts's `ReachabilityOpts.envSource`
812
+ * is not exposed here — `call()` always uses process.env. Use
813
+ * `getDefaultFallbackChain({ reachability: { envSource } })` upstream
814
+ * for hermetic test runs.
815
+ */
816
+ noAutoFilter?: boolean;
817
+ /**
818
+ * alpha.34. When provided AND the chosen provider supports streaming
819
+ * (`profile.streaming === true`) AND `noStream` is not set, kgauto
820
+ * enables provider-native SSE streaming at the wire layer and invokes
821
+ * `onChunk(delta)` once per provider stream event. `delta` is the text
822
+ * since the previous `onChunk` call (NOT cumulative) — provider
823
+ * stream-shape headache normalized in kgauto's lowering layer.
824
+ *
825
+ * `CallResult.response.text` is still populated with the full assembled
826
+ * response — kgauto buffers internally regardless of the callback.
827
+ * Consumers can use either the streaming side-effect OR the final
828
+ * `response.text`, doesn't matter.
829
+ *
830
+ * Tool calls + finish reason + usage are collected from stream events
831
+ * and returned in the final `CallResult` exactly as the non-streaming
832
+ * path would shape them. Brain telemetry latency = time-to-stream-end.
833
+ *
834
+ * Chain-walk semantics: if the streaming target fails mid-stream
835
+ * (network error, retryable provider error), kgauto walks to the next
836
+ * fallback target and restarts streaming from its first chunk —
837
+ * `onChunk` fires fresh from the new target. Consumer detects via the
838
+ * post-call `CallResult.fellOverFrom`. To opt out of fallback for
839
+ * streaming, set `noFallback: true` alongside `onChunk`.
840
+ *
841
+ * Filed by playbacksam s42 (2026-05-22) as `streaming-output-callback-
842
+ * on-callresult` for ComposeDrawer SSE; perceived-latency UX win
843
+ * during 10-30s draft assembly.
844
+ */
845
+ onChunk?: (chunk: string) => void;
846
+ /**
847
+ * alpha.34. Explicit opt-out of streaming even when `onChunk` is
848
+ * provided. Default: false (streaming enabled when `onChunk` is set).
849
+ * Use when the consumer wants to pass `onChunk` conditionally without
850
+ * branching the call site (e.g., capture chunks for instrumentation
851
+ * without engaging streaming wire format).
852
+ */
853
+ noStream?: boolean;
854
+ }
855
+ interface CallAttempt {
856
+ model: string;
857
+ status: 'success' | 'retryable' | 'terminal';
858
+ errorCode?: string;
859
+ message?: string;
860
+ }
861
+ /**
862
+ * Why fallback fired. Normalized for `CallResult.fallbackReason` (alpha.9).
863
+ *
864
+ * - `rate_limit` provider returned 429
865
+ * - `provider_error` 5xx, network, or other retryable upstream issue
866
+ * - `cost_cap` preflight policy.maxCostPerCallUsd rejected target
867
+ * - `cliff` alpha.8 contract violation (MAX_TOKENS on
868
+ * structured output, parse-failed JSON)
869
+ * - `contract_violation` other compile-time-contract failures (reserved
870
+ * for alpha.10+ — e.g. mid-stream policy rejects)
871
+ * - `provider_auth_failed` alpha.14 — initial provider returned 401/403
872
+ * (upstream key revocation, malformed-but-truthy
873
+ * key, billing lapse). The chain walks to the
874
+ * next non-same-provider target instead of
875
+ * short-circuiting; same-provider remaining
876
+ * entries skip with errorCode='auth_inferred'.
877
+ */
878
+ type FallbackReason = 'rate_limit' | 'provider_error' | 'cost_cap' | 'cliff' | 'contract_violation' | 'provider_auth_failed';
879
+ interface CallResult {
880
+ /** Compile handle (still valid for record() if consumer wants to add oracle scores later). */
881
+ handle: string;
882
+ /** The model that ACTUALLY served the response (post-fallback). */
883
+ actualModel: string;
884
+ /** What compile() originally targeted. */
885
+ requestedModel: string;
886
+ provider: Provider;
887
+ response: NormalizedResponse;
888
+ latencyMs: number;
889
+ /** Mutations that fired during compile (informational, mirrors CompileResult.mutationsApplied). */
890
+ mutationsApplied: MutationApplied[];
891
+ /** One entry per provider attempt — observability for retry/fallback walks. */
892
+ attempts: CallAttempt[];
893
+ /**
894
+ * Alpha.9 normalization of fallback-walk telemetry. When the chain
895
+ * succeeded on the first attempt, these collapse to:
896
+ * - `servedBy === requestedModel`
897
+ * - `fellOverFrom` undefined
898
+ * - `fallbackReason` undefined
899
+ *
900
+ * When fallback fired:
901
+ * - `servedBy` = `actualModel` (the model that produced the response)
902
+ * - `fellOverFrom` = `requestedModel` (what the caller / compile() asked for)
903
+ * - `fallbackReason` = normalized cause derived from the first
904
+ * non-success attempt's `errorCode`
905
+ *
906
+ * Consumer UX use: show "Claude was busy; we used Pro for this answer"
907
+ * when `fellOverFrom` is set (master plan §3.6).
908
+ */
909
+ /** Model that actually answered. Equal to `actualModel`; kept distinct for clarity. */
910
+ servedBy: string;
911
+ /** Set only when fallback fired. Equal to `requestedModel` in that case. */
912
+ fellOverFrom?: string;
913
+ /** Set only when fallback fired. Normalized cause. */
914
+ fallbackReason?: FallbackReason;
915
+ /**
916
+ * alpha.10. Models that auto-filter dropped from the fallback walk because
917
+ * their provider had no reachable API key. Empty when nothing was filtered
918
+ * (the common case once consumers have all the keys they need). Surfaces
919
+ * silent self-heal so consumers can log/audit what happened without
920
+ * defeating the "kgauto just gets" UX.
921
+ *
922
+ * Empty array (not undefined) when filter ran but dropped nothing —
923
+ * distinguishes "filter ran cleanly" from "filter was disabled" (`undefined`
924
+ * when `noAutoFilter: true`).
925
+ */
926
+ unreachableFiltered?: string[];
927
+ /**
928
+ * alpha.16. Models that policy.blockedModels filtering dropped from the
929
+ * fallback walk. Defense-in-depth at the call() boundary — compile()'s
930
+ * passScoreTargets already excludes blocked entries from the initial
931
+ * target + fallbackChain, but if a consumer re-shapes the chain and
932
+ * threads policy through only partially, this filter catches the gap.
933
+ *
934
+ * Resolves TT-40 follow-on `policy-block-not-enforced-on-fallback-chain`
935
+ * (2026-05-15) where mutations_applied recorded the block intent but
936
+ * the call walker landed on the blocked model anyway.
937
+ *
938
+ * Undefined when no filter ran (no blockedModels set). Populated only
939
+ * when filter ran AND dropped at least one entry — empty drops are
940
+ * stored as `undefined` to keep brain telemetry quiet on the common
941
+ * case.
942
+ */
943
+ policyBlockedFiltered?: string[];
944
+ /**
945
+ * alpha.17. Unique identifier for this call() invocation, generated at
946
+ * call() entry via crypto.randomUUID(). Returned on success and emitted
947
+ * as the routing key for Glass-Box observability events
948
+ * (compile.start, compile.done, execute.attempt, execute.success,
949
+ * fallback.walked, advisory.fired). Pass the same id to
950
+ * `subscribe(traceId)` from `@warmdrift/kgauto-compiler/glassbox` to
951
+ * tap the in-flight event stream.
952
+ *
953
+ * Always present on success. Additive, non-breaking.
954
+ */
955
+ traceId: string;
956
+ }
957
+ /**
958
+ * Thrown when call() exhausts the fallback chain without success.
959
+ * `attempts` carries every model tried + classification.
960
+ */
961
+ declare class CallError extends Error {
962
+ readonly attempts: CallAttempt[];
963
+ readonly lastErrorCode?: string;
964
+ readonly lastStatus?: number;
965
+ constructor(message: string, attempts: CallAttempt[], lastStatus?: number, lastErrorCode?: string);
966
+ }
967
+ interface OracleScore {
968
+ /** 0..1 overall quality. */
969
+ score: number;
970
+ /** Optional per-dimension breakdown. */
971
+ dimensions?: Record<string, number>;
972
+ /** Free-form explanation for debugging. */
973
+ rationale?: string;
974
+ }
975
+ interface RecordInput {
976
+ /** Handle from CompileResult. */
977
+ handle: string;
978
+ /** Actual tokens consumed (post-call). */
979
+ tokensIn: number;
980
+ tokensOut: number;
981
+ /** Wall-clock latency in ms. */
982
+ latencyMs: number;
983
+ /** True iff the call returned a usable response. */
984
+ success: boolean;
985
+ /** True iff the call returned 0 output tokens despite success. */
986
+ emptyResponse?: boolean;
987
+ /** Provider error code if any. */
988
+ errorType?: string;
989
+ /** Tools actually invoked by the model. */
990
+ toolsCalled?: string[];
991
+ /** Oracle quality score — required for learning to fire. */
992
+ oracleScore?: OracleScore;
993
+ /** Optional: scrubbed prompt/response previews for debugging. */
994
+ promptPreview?: string;
995
+ responsePreview?: string;
996
+ /**
997
+ * The model that ACTUALLY RAN. Set this when consumer-side fallback ran
998
+ * a different model than v2 compile() targeted. Brain stores this as
999
+ * `model` (the truth) and the original target as `requested_model`.
1000
+ *
1001
+ * Omit when no fallback occurred — brain stores compile target as `model`
1002
+ * (still the truth in that case) and `requested_model` stays NULL.
1003
+ *
1004
+ * s11 fix: prevents the brain from misattributing fallback traffic to
1005
+ * the originally-requested model.
1006
+ */
1007
+ actualModel?: string;
1008
+ /**
1009
+ * Override `mutations_applied` for this outcome. Set by `call()` when
1010
+ * fallback fires — the served compile's mutations (which actually shaped
1011
+ * the request that went on the wire) replace the initial compile's
1012
+ * mutations (registered against the handle). Without this override, fallback
1013
+ * traffic is attributed to the initial compile's mutations and the brain's
1014
+ * mutation effectiveness stats become misleading.
1015
+ *
1016
+ * alpha.4: extends s11 truth-in-logging to mutations.
1017
+ */
1018
+ mutationsApplied?: string[];
1019
+ /**
1020
+ * Cache read input tokens, when supported by the provider.
1021
+ * - Anthropic: `usage.cache_read_input_tokens`
1022
+ * - Google (implicit caching): `usageMetadata.cachedContentTokenCount`
1023
+ * - OpenAI: `usage.prompt_tokens_details.cached_tokens`
1024
+ *
1025
+ * Powers the cost-and-efficiency-watcher (interfaces/kgauto.md, alpha.4):
1026
+ * `tokens_in - cache_read_input_tokens` is the un-cached new context per call.
1027
+ */
1028
+ cacheReadInputTokens?: number;
1029
+ /**
1030
+ * Cache creation input tokens (Anthropic-specific).
1031
+ * `usage.cache_creation_input_tokens`. The first call that pays the 25%
1032
+ * upcharge to write a cache marker; subsequent calls hit `cacheRead`.
1033
+ */
1034
+ cacheCreationInputTokens?: number;
1035
+ /**
1036
+ * Time to first token (ms). Optional; populated when the provider/SDK
1037
+ * surfaces it. Distinct from `latencyMs` (end-to-end wall clock).
1038
+ */
1039
+ ttftMs?: number;
1040
+ /**
1041
+ * alpha.20 — advisories fired at compile() time. Persisted to the brain's
1042
+ * `compile_outcome_advisories` sibling table via a second POST that fires
1043
+ * AFTER the primary outcome insert succeeds. Best-effort: a failed
1044
+ * advisory POST is logged via onError but does NOT throw or roll back the
1045
+ * primary outcome row.
1046
+ *
1047
+ * Pass `result.advisories` from the CompileResult directly. The brain
1048
+ * uses these to compute the `empty_rate_clean` comparator (rows with
1049
+ * zero advisories fired) so consumers can distinguish "model is bad"
1050
+ * from "client sent a bloated/uncached/malformed request."
1051
+ *
1052
+ * Empty array / undefined → no second POST fires.
1053
+ */
1054
+ advisories?: BestPracticeAdvisory[];
1055
+ /**
1056
+ * alpha.28 — Glass-Box renderer substrate fields (migration 018).
1057
+ *
1058
+ * All optional. When omitted, brain stores NULL and the renderer falls
1059
+ * back to "—" / hidden rows. Library callers (`call.ts`) populate what
1060
+ * they observe; adapter / SDK consumers can populate the rest from their
1061
+ * own provider response surface.
1062
+ */
1063
+ /**
1064
+ * Provider finish reason. Captured from NormalizedResponse.finishReason
1065
+ * (Anthropic `stop_reason`, Google `finishReason`, OpenAI `finish_reason`).
1066
+ * Lower-case canonicalization is the brain's job; consumers can pass
1067
+ * raw provider strings.
1068
+ */
1069
+ finishReason?: string;
1070
+ /**
1071
+ * End-to-end wall-clock latency in ms. Distinct from `latencyMs` only
1072
+ * insofar as `latencyMs` was the historical name for the same metric;
1073
+ * `totalMs` is the new column on `compile_outcomes` (migration 018).
1074
+ * When omitted, brain mirrors `latency_ms`.
1075
+ */
1076
+ totalMs?: number;
1077
+ /** Tools kept after the tool-relevance pass. */
1078
+ toolsCount?: number;
1079
+ /** Number of history messages at compile time. */
1080
+ historyDepth?: number;
1081
+ /** Rendered system prompt size in characters. */
1082
+ systemPromptChars?: number;
1083
+ /** Model originally targeted when a fallback fired. */
1084
+ fellOverFrom?: string;
1085
+ /**
1086
+ * Why the fallback fired. Closed set mirroring CallResult.fallbackReason —
1087
+ * keep in sync with the wire-contract enum (TraceDetail.fallbackReason).
1088
+ */
1089
+ fallbackReason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
1090
+ }
1091
+ /**
1092
+ * alpha.20 Entry 4: kinds of consumer-declared outcomes feeding the quality
1093
+ * loop. Surfaces in `recordOutcome()` as the verdict the consumer's UX is
1094
+ * forwarding to the brain.
1095
+ *
1096
+ * - `approved` user explicitly approved (thumbs up, "looks good", accepted)
1097
+ * - `rejected` user explicitly rejected (thumbs down, "redo", discarded)
1098
+ * - `partial` accepted with edits or partial use (mixed signal)
1099
+ * - `engaged` user engaged with the output (copy/scroll/dwell)
1100
+ * - `abandoned` user abandoned the response (closed, navigated away)
1101
+ * - `unknown` verdict could not be inferred — recorded for completeness
1102
+ */
1103
+ type OutcomeKind = 'approved' | 'rejected' | 'partial' | 'engaged' | 'abandoned' | 'unknown';
1104
+ /**
1105
+ * Input to `recordOutcome()` — consumer's verdict on a previously-compiled
1106
+ * call. Joins to the original `compile_outcomes` row via outcomeId,
1107
+ * enabling per-(model, archetype) approve-rate measurement once N ≥ 10
1108
+ * outcomes accumulate.
1109
+ */
1110
+ interface RecordOutcomeInput {
1111
+ /** Joins to compile_outcomes.id. Returned by compile() via CompileResult.outcomeId. */
1112
+ outcomeId: number | string;
1113
+ /** What did the user / system do with this output? */
1114
+ outcome: OutcomeKind;
1115
+ /** Optional 1-5 user rating (e.g., thumbs up/down with intensity, NPS-style). */
1116
+ rating?: 1 | 2 | 3 | 4 | 5;
1117
+ /** Optional free-text reason (e.g., user-typed feedback, system-inferred cause). */
1118
+ reason?: string;
1119
+ /**
1120
+ * Optional model-reported confidence at compile time (0..1). Used for
1121
+ * Brier-score calibration in later phases (alpha.21+) — pair this with
1122
+ * the actual `outcome` to compute calibration error.
1123
+ */
1124
+ observedConfidence?: number;
1125
+ }
1126
+ /**
1127
+ * Return shape of `recordOutcome()`. Never throws — persistence failures
1128
+ * surface as `ok: false` with a stable `reason` string.
1129
+ */
1130
+ interface OutcomeResult {
1131
+ /** True when the POST landed (2xx). False when brain not configured or POST failed. */
1132
+ ok: boolean;
1133
+ /** Stable reason code when ok=false. One of: 'brain_not_configured' | 'persistence_failed'. */
1134
+ reason?: string;
1135
+ }
1136
+ /**
1137
+ * alpha.21 (s78 Entry 1): provenance label on a chain entry. Surfaces WHY
1138
+ * an entry sits where it sits so consumers can distinguish:
1139
+ *
1140
+ * - 'measured' brain has N>=10 rows with a measurable quality
1141
+ * outcome backing this placement. The number lives on
1142
+ * `ChainEntry.n`.
1143
+ * - 'capability-fact' inclusion or exclusion driven by a published or
1144
+ * measured CAPABILITY (L-040 cliff, ctx window cap,
1145
+ * structured-output support). Not an opinion — a
1146
+ * fact about what the model can/can't do.
1147
+ * - 'judgment' engineer's pick, no measured backing yet. Cold-start
1148
+ * prior; entirely valid until evidence accumulates.
1149
+ *
1150
+ * "Judgment" is HONEST, not a downgrade. Most of `STARTER_CHAINS` lands here
1151
+ * in alpha.21 — that's the point: consumers can SEE the grounding gap and
1152
+ * prioritize the measurement work that would graduate them to 'measured'.
1153
+ */
1154
+ type Grounding = 'measured' | 'capability-fact' | 'judgment';
1155
+ /**
1156
+ * alpha.21 (s78 Entry 1): a single position in a fallback chain, carrying its
1157
+ * provenance label and an optional human-readable reason. The shape replaces
1158
+ * the old `string[]` representation everywhere chains are surfaced externally.
1159
+ *
1160
+ * `n` is REQUIRED when `grounding === 'measured'` — the runtime helper
1161
+ * `makeMeasuredEntry()` enforces this. For 'capability-fact' and 'judgment'
1162
+ * entries, `n` is undefined.
1163
+ */
1164
+ interface ChainEntry {
1165
+ /** Canonical model id (post-alias). */
1166
+ id: string;
1167
+ /** Why this entry sits in this position. */
1168
+ grounding: Grounding;
1169
+ /**
1170
+ * Optional one-liner explaining the grounding decision. The inline comments
1171
+ * that historically lived next to STARTER_CHAINS entries are now expressed
1172
+ * here as machine-readable text.
1173
+ */
1174
+ reason?: string;
1175
+ /**
1176
+ * When `grounding === 'measured'`, the brain row count that backs this
1177
+ * placement. Undefined for 'capability-fact' and 'judgment' entries.
1178
+ */
1179
+ n?: number;
1180
+ }
1181
+ /**
1182
+ * alpha.21 introspection shape — a per-archetype chain with grounding on
1183
+ * every position. Consumers reading this never see naked string ids;
1184
+ * everything carries provenance.
1185
+ */
1186
+ interface ChainWithGrounding {
1187
+ archetype: IntentArchetypeName;
1188
+ /** Ordered: position 0 = primary, rising index = fallback positions. */
1189
+ entries: ChainEntry[];
1190
+ }
1191
+ /** alpha.23 (s78 Phase 3): per-axis metrics returned by the brain RPC. */
1192
+ interface PerAxisMetrics {
1193
+ appId: string;
1194
+ archetype: string;
1195
+ model: string;
1196
+ windowDays: number;
1197
+ /** Total brain rows for this tuple in the window. */
1198
+ nRows: number;
1199
+ /** Subset of nRows with zero advisories fired — the "clean signal" comparator. */
1200
+ nRowsClean: number;
1201
+ /** Count of compile_outcome_quality entries joining to this tuple's outcomes. */
1202
+ nQualityOutcomes: number;
1203
+ /** Approve rate from quality outcomes. null when nQualityOutcomes === 0. */
1204
+ magicRate: number | null;
1205
+ /** Whether magicRate >= consumer-declared qualityFloor. null when no floor declared OR no outcomes. */
1206
+ qualityFloorMet: boolean | null;
1207
+ costEfficiency: {
1208
+ avgCostUsd: number | null;
1209
+ avgCostUsdClean: number | null;
1210
+ avgInputTokens: number | null;
1211
+ avgOutputTokens: number | null;
1212
+ inputTokenRatio: number | null;
1213
+ };
1214
+ timeEfficiency: {
1215
+ avgLatencyMs: number | null;
1216
+ avgTtftMs: number | null;
1217
+ };
1218
+ reliability: {
1219
+ successRate: number | null;
1220
+ successRateClean: number | null;
1221
+ emptyRate: number | null;
1222
+ emptyRateClean: number | null;
1223
+ };
1224
+ evidenceFreshnessDays: number | null;
1225
+ }
1226
+ /** Per-axis metrics keyed by model — used for chain-comparison views. */
1227
+ type PerAxisMetricsByModel = Record<string, PerAxisMetrics>;
1228
+
1229
+ 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 ToolDefinition as x };