@warmdrift/kgauto-compiler 2.0.0-alpha.3 → 2.0.0-alpha.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,242 @@
1
+ import { G as GlassboxEvent } from '../types-D_JAhCv4.js';
2
+ import { h as Adapter, u as SectionKind } from '../ir-BIAT9gJk.js';
3
+ import '../dialect.js';
4
+
5
+ /**
6
+ * Internal config + hook types for createGlassboxRoutes().
7
+ *
8
+ * The public contract lives on `GlassboxRoutesConfig` in ./index.ts; these
9
+ * are the narrower per-handler shapes consumed by proxy.ts and stream.ts.
10
+ */
11
+
12
+ /**
13
+ * Wire contract for the Glass-Box Chrome extension's brain-poll endpoint.
14
+ *
15
+ * The list mode of `proxy(req)` returns `{ traces: TraceSummary[] }`. The
16
+ * detail mode (`?traceId=<id>`) returns a single `TraceDetail`. These are
17
+ * the camelCase shapes the extension renderer expects — distinct from the
18
+ * snake_case `compile_outcomes` row shape that PostgREST returns. The
19
+ * factory's typed `rowToSummary` / `rowToDetail` transformer is the single
20
+ * canonical boundary between the DB shape and the wire shape (see
21
+ * `feedback_typed_boundary_transformers.md` in kgauto memory for the rule).
22
+ */
23
+ interface TraceSummary {
24
+ traceId: string;
25
+ appId: string;
26
+ archetype: string;
27
+ target: string;
28
+ createdAt: string;
29
+ tokensIn: number;
30
+ tokensOut: number;
31
+ estimatedCostUsd: number;
32
+ }
33
+
34
+ interface AdvisoryRecord {
35
+ level: 'info' | 'warn' | 'critical';
36
+ /** Stable advisory identifier, e.g. "caching-off-on-claude". */
37
+ code: string;
38
+ /** Consumer-renderable message — no internal jargon ("L-040", "R3" etc.). */
39
+ message: string;
40
+ /** Optional secondary one-liner. Renders below `message` in italics. */
41
+ suggestion?: string;
42
+ /** Deep link to the relevant section of `interfaces/kgauto.md` or docs. */
43
+ docsUrl?: string;
44
+ /**
45
+ * alpha.28+ — closed-union adaptation hint surfaced by the advisor when
46
+ * the advisory can be auto-mitigated by a config knob. Renderer surfaces
47
+ * as `→ try toolOrchestration: 'sequential'` on the advisory row.
48
+ *
49
+ * MUST stay byte-identical to Builder C's
50
+ * `BestPracticeAdvisory.suggestedAdaptation` shape (verified at Phase 2
51
+ * integration; the Adapter type itself is the contract).
52
+ */
53
+ suggestedAdaptation?: Adapter;
54
+ }
55
+ /**
56
+ * Cost-equivalent alternative the chain could have served. Computed at
57
+ * detail-view time by `computeCounterfactuals()` against the served row's
58
+ * observed token counts + archetype + cache state. Up to 2 entries, sorted
59
+ * cheapest first.
60
+ */
61
+ interface TraceCounterfactual {
62
+ modelId: string;
63
+ estimatedCostUsd: number;
64
+ /** servedCostUsd - estimatedCostUsd (always > 0; only ≥10% savings kept). */
65
+ savingsUsd: number;
66
+ /** 0-100. */
67
+ savingsPercent: number;
68
+ /** Plain-English rationale tying archetype + perf score. */
69
+ reason: string;
70
+ }
71
+ /**
72
+ * Derived axis-health tri-state for the three Glass-Box dots
73
+ * (input-ratio · cache · fallback). Renderer reads; transformer computes.
74
+ *
75
+ * Thresholds (locked in design contract Phase 0):
76
+ * - inputRatio: green ≤ 0.65 · yellow 0.65–0.85 · red > 0.85
77
+ * - cache (only when historyCacheableTokens > 1000):
78
+ * green if inputCacheHitRatio ≥ 0.5
79
+ * yellow if 0.1 ≤ inputCacheHitRatio < 0.5
80
+ * red if inputCacheHitRatio < 0.1
81
+ * na if historyCacheableTokens ≤ 1000
82
+ * - fallback: red iff fellOverFrom !== undefined && fellOverFrom !== target
83
+ */
84
+ interface TraceHealth {
85
+ inputRatioStatus: 'green' | 'yellow' | 'red';
86
+ cacheStatus: 'green' | 'yellow' | 'red' | 'na';
87
+ fallbackStatus: 'green' | 'red';
88
+ }
89
+ /**
90
+ * alpha.29+ — wire-boundary representation of a translator section-rewrite.
91
+ *
92
+ * Distinct from the package-internal `SectionRewrite` type in `ir.ts`: this
93
+ * shape drops `originalText` + `transformedText` because those may carry
94
+ * consumer PII. The renderer shows the `rule` + `summary` only. Full text
95
+ * stays on `compile_outcomes.section_rewrites_applied` (Supabase row), gated
96
+ * by RLS for brain-side cross-app learning.
97
+ */
98
+ interface TraceSectionRewrite {
99
+ /** Stable id of the rewritten section. */
100
+ sectionId: string;
101
+ /** Section-kind discriminator that triggered the rewrite. */
102
+ kind: SectionKind;
103
+ /** Stable rule identifier (e.g. `'sequential-tool-cliff-below-floor'`). */
104
+ rule: string;
105
+ /**
106
+ * Plain-English one-liner describing what fired and why. Renderer surfaces
107
+ * this on the Coaching card; no internal jargon ("L-040", "below floor").
108
+ */
109
+ summary: string;
110
+ }
111
+ interface TraceDetail extends TraceSummary {
112
+ mutationsApplied: string[];
113
+ advisories: AdvisoryRecord[];
114
+ rawRequest?: string;
115
+ rawResponse?: string;
116
+ /** Set when consumer passed a forceModel / fallback fired. */
117
+ requestedModel?: string;
118
+ /** Provider finish reason — 'stop' / 'max_tokens' / 'tool_use' / etc. */
119
+ finishReason?: string;
120
+ /** Time to first token (ms); populated when provider surfaces it. */
121
+ ttftMs?: number;
122
+ /** End-to-end wall-clock (ms); from migration 018. */
123
+ totalMs?: number;
124
+ /** Tools kept after relevance pass. */
125
+ toolsCount?: number;
126
+ /** Number of history messages at compile time. */
127
+ historyDepth?: number;
128
+ /** Rendered system prompt size in characters. */
129
+ systemPromptChars?: number;
130
+ cacheReadInputTokens: number;
131
+ cacheCreationInputTokens: number;
132
+ historyCacheableTokens: number;
133
+ /** Derived: cacheReadInputTokens / max(tokensIn, 1). 0-1. */
134
+ inputCacheHitRatio: number;
135
+ fellOverFrom?: string;
136
+ fallbackReason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
137
+ /** Up to 2 alternatives. Empty array (not undefined) when none qualify. */
138
+ counterfactuals?: TraceCounterfactual[];
139
+ /** Undefined when 7d volume < 5/day (insufficient data). */
140
+ projectedDailyCostUsd?: number;
141
+ /**
142
+ * alpha.29+ — translator activity for this trace. Empty array (not
143
+ * undefined) when no rewrites fired or pre-019 row. Surfaced in the
144
+ * Glass-Box Coaching card as synthetic info-level rows. PII-safe by
145
+ * construction: only sectionId + kind + rule + summary cross the wire.
146
+ */
147
+ sectionRewritesApplied: TraceSectionRewrite[];
148
+ health: TraceHealth;
149
+ }
150
+
151
+ /**
152
+ * Public entry point for `@warmdrift/kgauto-compiler/glassbox-routes`.
153
+ *
154
+ * One factory call from a Vercel Edge consumer route handler gets you both
155
+ * the replay-query (`proxy`) and live-SSE (`stream`) endpoints that the
156
+ * Glass-Box Chrome panel reads. Wiring is ~6 lines per app:
157
+ *
158
+ * // app/api/glassbox/proxy/route.ts
159
+ * import { createGlassboxRoutes } from '@warmdrift/kgauto-compiler/glassbox-routes';
160
+ * const { proxy } = createGlassboxRoutes({
161
+ * installToken: process.env.GLASSBOX_INSTALL_TOKEN!,
162
+ * extensionId: process.env.GLASSBOX_EXTENSION_ID!,
163
+ * brainEndpoint: process.env.GLASSBOX_BRAIN_ENDPOINT!,
164
+ * brainJwt: process.env.GLASSBOX_BRAIN_JWT!, // scoped JWT (RLS via app_id claim)
165
+ * brainAnonKey: process.env.GLASSBOX_BRAIN_ANON_KEY!, // project anon/publishable key (Supabase apikey header)
166
+ * appId: 'playbacksam',
167
+ * });
168
+ * export { proxy as GET };
169
+ *
170
+ * Auth model (defense in depth):
171
+ * - Bearer install token → primary, constant-time compared
172
+ * - chrome-extension Origin → secondary CSRF gate
173
+ *
174
+ * Scrub: optional sanitization runs at the proxy boundary before events or
175
+ * rows leave the consumer's infrastructure. Per pii-scrubber-call-site-not-
176
+ * package: kgauto stays naive to PII policy; consumers pass scrub hooks
177
+ * that encode their own data-handling rules.
178
+ *
179
+ * Brain reads use the scoped JWT minted via migration 013. RLS enforces
180
+ * `app_id = jwt.claim.app_id`; the proxy filter is belt-and-suspenders for
181
+ * payload size + log legibility.
182
+ */
183
+
184
+ interface GlassboxRoutesConfig {
185
+ /** Bearer token validated on every request via constant-time compare. Required. */
186
+ installToken: string;
187
+ /** chrome-extension://<id> — exact match required on Origin header. Required. */
188
+ extensionId: string;
189
+ /** Brain endpoint base (e.g. https://kgauto-brain.supabase.co). Used by `proxy` for replay queries. */
190
+ brainEndpoint: string;
191
+ /** Scoped JWT for brain reads. Use the per-consumer JWT minted via migration 013 (claim: app_id). Drives RLS via the `app_id` claim; sent as `Authorization: Bearer <jwt>` only. */
192
+ brainJwt: string;
193
+ /**
194
+ * Anon/publishable key for the Supabase `apikey` header. Supabase requires
195
+ * `apikey` to be one of the project's known keys (anon or service_role) —
196
+ * the scoped JWT in `brainJwt` doesn't qualify there. Pass the project's
197
+ * legacy `anon` key (JWT format, role=anon) or the modern `sb_publishable_...`
198
+ * key. Safe to expose at the wire (that's what "publishable" means).
199
+ *
200
+ * Pre-alpha.24 this was missing and `brainJwt` was used as apikey too — first
201
+ * real call always 401'd against real Supabase. Catching this required a
202
+ * pre-publish smoke against the real brain; unit tests with mocked fetch
203
+ * couldn't surface it. See L-117 in command-center/learnings.md.
204
+ */
205
+ brainAnonKey: string;
206
+ /** App scope filter — must match the JWT's app_id claim. */
207
+ appId: string;
208
+ /**
209
+ * Optional sanitization hook. Called with each event/trace BEFORE it leaves the consumer.
210
+ * Default: identity (no scrub). PII policy lives at the call-site, not in the package.
211
+ */
212
+ scrub?: (event: GlassboxEvent | Record<string, unknown>) => GlassboxEvent | Record<string, unknown>;
213
+ /**
214
+ * Test-only seam: override the brain fetch implementation. Production
215
+ * code never sets this; tests use it to mock PostgREST responses.
216
+ */
217
+ fetch?: typeof fetch;
218
+ /**
219
+ * Test-only seam: override the per-trace live-stream subscriber. Production
220
+ * code resolves to the alpha.17 `subscribe()` export; tests inject a fake
221
+ * source ReadableStream<GlassboxEvent>.
222
+ */
223
+ subscribe?: (traceId: string) => ReadableStream<GlassboxEvent>;
224
+ /**
225
+ * Test-only seam: override the per-app "tail-all" subscriber (alpha.26).
226
+ * Production code resolves to the `subscribeApp()` export; tests inject
227
+ * a fake source. Backs the extension's default Live tab mode when no
228
+ * traceId is supplied in the URL.
229
+ */
230
+ subscribeApp?: (args: {
231
+ appId: string;
232
+ }) => ReadableStream<GlassboxEvent>;
233
+ }
234
+ interface GlassboxRoutes {
235
+ /** GET /api/glassbox/proxy?traceId=<id> OR ?limit=20 (recent traces) */
236
+ proxy: (req: Request) => Promise<Response>;
237
+ /** GET /api/glassbox/stream?traceId=<id> (SSE) */
238
+ stream: (req: Request) => Promise<Response>;
239
+ }
240
+ declare function createGlassboxRoutes(config: GlassboxRoutesConfig): GlassboxRoutes;
241
+
242
+ export { type GlassboxRoutes, type GlassboxRoutesConfig, type TraceDetail, type TraceSummary, createGlassboxRoutes };