@warmdrift/kgauto-compiler 2.0.0-alpha.7 → 2.0.0-alpha.70

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 (55) hide show
  1. package/README.md +176 -46
  2. package/dist/brain-proxy.d.mts +113 -0
  3. package/dist/brain-proxy.d.ts +113 -0
  4. package/dist/brain-proxy.js +193 -0
  5. package/dist/brain-proxy.mjs +6 -0
  6. package/dist/chunk-4UO4CCSP.mjs +1620 -0
  7. package/dist/chunk-65ZMX5OT.mjs +169 -0
  8. package/dist/{chunk-5TI6PNSK.mjs → chunk-BVEXV5KC.mjs} +11 -0
  9. package/dist/chunk-FR4DNGLW.mjs +203 -0
  10. package/dist/chunk-NBO4R5PC.mjs +313 -0
  11. package/dist/chunk-P3TOAEG4.mjs +56 -0
  12. package/dist/chunk-RO22VFIF.mjs +29 -0
  13. package/dist/chunk-SBFSYCQG.mjs +719 -0
  14. package/dist/dialect.d.mts +41 -3
  15. package/dist/dialect.d.ts +41 -3
  16. package/dist/dialect.js +14 -2
  17. package/dist/dialect.mjs +5 -3
  18. package/dist/glassbox/index.d.mts +59 -0
  19. package/dist/glassbox/index.d.ts +59 -0
  20. package/dist/glassbox/index.js +312 -0
  21. package/dist/glassbox/index.mjs +12 -0
  22. package/dist/glassbox-routes/format.d.mts +24 -0
  23. package/dist/glassbox-routes/format.d.ts +24 -0
  24. package/dist/glassbox-routes/format.js +86 -0
  25. package/dist/glassbox-routes/format.mjs +18 -0
  26. package/dist/glassbox-routes/index.d.mts +191 -0
  27. package/dist/glassbox-routes/index.d.ts +191 -0
  28. package/dist/glassbox-routes/index.js +2888 -0
  29. package/dist/glassbox-routes/index.mjs +667 -0
  30. package/dist/glassbox-routes/react/index.d.mts +74 -0
  31. package/dist/glassbox-routes/react/index.d.ts +74 -0
  32. package/dist/glassbox-routes/react/index.js +819 -0
  33. package/dist/glassbox-routes/react/index.mjs +754 -0
  34. package/dist/index.d.mts +2739 -17
  35. package/dist/index.d.ts +2739 -17
  36. package/dist/index.js +8989 -1659
  37. package/dist/index.mjs +5078 -367
  38. package/dist/ir-Bqn1RVdV.d.mts +1583 -0
  39. package/dist/ir-Bvlkw5ja.d.ts +1583 -0
  40. package/dist/key-health.d.mts +131 -0
  41. package/dist/key-health.d.ts +131 -0
  42. package/dist/key-health.js +228 -0
  43. package/dist/key-health.mjs +6 -0
  44. package/dist/profiles.d.mts +292 -2
  45. package/dist/profiles.d.ts +292 -2
  46. package/dist/profiles.js +1231 -16
  47. package/dist/profiles.mjs +9 -1
  48. package/dist/types-Bon96eyc.d.ts +131 -0
  49. package/dist/types-CwGhacGT.d.mts +149 -0
  50. package/dist/types-DIxRZ3Dj.d.ts +149 -0
  51. package/dist/types-DsEq35WY.d.mts +131 -0
  52. package/package.json +54 -8
  53. package/dist/chunk-MBEI5UOM.mjs +0 -409
  54. package/dist/profiles-B3eNQ2py.d.ts +0 -619
  55. package/dist/profiles-Py8c7zjJ.d.mts +0 -619
package/dist/profiles.mjs CHANGED
@@ -1,14 +1,22 @@
1
1
  import {
2
2
  ALIASES,
3
+ LATENCY_TIER_MS,
4
+ _setProfileBrainHook,
3
5
  allProfiles,
6
+ allProfilesRaw,
4
7
  getProfile,
8
+ latencyTierOf,
5
9
  profilesByProvider,
6
10
  tryGetProfile
7
- } from "./chunk-MBEI5UOM.mjs";
11
+ } from "./chunk-4UO4CCSP.mjs";
8
12
  export {
9
13
  ALIASES,
14
+ LATENCY_TIER_MS,
15
+ _setProfileBrainHook,
10
16
  allProfiles,
17
+ allProfilesRaw,
11
18
  getProfile,
19
+ latencyTierOf,
12
20
  profilesByProvider,
13
21
  tryGetProfile
14
22
  };
@@ -0,0 +1,131 @@
1
+ import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-Bvlkw5ja.js';
2
+
3
+ /**
4
+ * Glass-Box observability types (alpha.17).
5
+ *
6
+ * The substrate for kgauto's in-flight observability surface — a Chrome MV3
7
+ * side panel that renders compile + execute + advisor outputs in real-time.
8
+ * See design doc:
9
+ * ~/.gstack/projects/stue-kgauto/stgreen-claude-serene-williamson-51a105-design-20260518-175356.md
10
+ *
11
+ * Wire shape is intentionally minimal:
12
+ * { kind, at, data } — discriminated union by `kind`.
13
+ *
14
+ * Critical-path safety (L-086 derived): emit MUST NEVER fail the user's
15
+ * `call()` invocation. emit.ts wraps every adapter write in try/catch +
16
+ * silently drops on error. Consumers in Vercel Edge runtimes can lose one
17
+ * event without losing the response.
18
+ */
19
+
20
+ /**
21
+ * Discriminator. Six event kinds cover the v1 substrate. New kinds added
22
+ * additively; the side-panel renderer treats unknown kinds as "ignore".
23
+ */
24
+ type GlassboxEventKind = 'compile.start' | 'compile.done' | 'execute.attempt' | 'execute.success' | 'advisory.fired' | 'fallback.walked';
25
+ /**
26
+ * Wire envelope. Every emit lands as one of these.
27
+ *
28
+ * - kind: discriminator
29
+ * - at: unix milliseconds (Date.now())
30
+ * - data: kind-specific payload
31
+ *
32
+ * `data` typed loosely as Record<string, unknown> for serialization-friendliness;
33
+ * the per-kind builders below populate it with the structured shape expected
34
+ * by the renderer. We deliberately do NOT typescript-narrow `data` by kind on
35
+ * the wire type — the side panel reads JSON from SSE and only the renderer
36
+ * needs the narrowed shape. Internal callers (emit.ts) get type assistance via
37
+ * the typed factory helpers in emit.ts.
38
+ */
39
+ interface GlassboxEvent {
40
+ kind: GlassboxEventKind;
41
+ at: number;
42
+ data: Record<string, unknown>;
43
+ }
44
+ /**
45
+ * Per-kind data shapes. Surfaced as type aids; not enforced at the
46
+ * GlassboxEvent boundary (intentionally — see comment above).
47
+ */
48
+ interface CompileStartData {
49
+ appId: string;
50
+ archetype: string;
51
+ models: string[];
52
+ }
53
+ interface CompileDoneData {
54
+ target: string;
55
+ provider: string;
56
+ fallbackChain: string[];
57
+ tokensIn: number;
58
+ estimatedCostUsd: number;
59
+ mutationsApplied: MutationApplied[];
60
+ advisories: BestPracticeAdvisory[];
61
+ }
62
+ interface ExecuteAttemptData {
63
+ model: string;
64
+ attemptIndex: number;
65
+ }
66
+ interface ExecuteSuccessData {
67
+ model: string;
68
+ tokensIn: number;
69
+ tokensOut: number;
70
+ latencyMs: number;
71
+ }
72
+ interface AdvisoryFiredData {
73
+ code: string;
74
+ message: string;
75
+ }
76
+ interface FallbackWalkedData {
77
+ from: string;
78
+ to: string;
79
+ reason: FallbackReason | 'unknown';
80
+ attempt: CallAttempt;
81
+ }
82
+ /**
83
+ * Pub/sub backend interface. Two adapters implement it: in-memory (dev /
84
+ * single-process) and Upstash Redis Streams (Vercel Edge multi-instance).
85
+ *
86
+ * The choice is made at module load (NOT per-call) based on env-var presence:
87
+ * if (UPSTASH_REDIS_URL && UPSTASH_REDIS_TOKEN) → Upstash
88
+ * else → in-memory
89
+ *
90
+ * Stream TTL: 60s after last event. After that, subscriber stream closes
91
+ * cleanly. The adapter owns its own TTL clock; subscribe() is agnostic.
92
+ */
93
+ interface GlassboxPubSub {
94
+ /**
95
+ * Publish a single event to a channel key. The channel is an opaque
96
+ * namespaced string — callers build it via `traceChannel(traceId)` or
97
+ * `appChannel(appId)` (see pubsub-upstash.ts). Returns a promise that
98
+ * resolves after the event is durably appended (or rejects on adapter
99
+ * failure — callers in emit.ts always swallow rejections).
100
+ *
101
+ * Pre-alpha.26 the parameter was named `traceId` because there was only
102
+ * one channel namespace; alpha.26 added per-app channels for the
103
+ * "tail-all" Live tab subscription. Behavior identical to the adapters —
104
+ * they treat the value as an opaque key — but the rename surfaces the
105
+ * generalization at the type level.
106
+ */
107
+ publish(channelKey: string, event: GlassboxEvent): Promise<void>;
108
+ /**
109
+ * Subscribe to events on a channel key. Returns a ReadableStream that
110
+ * emits GlassboxEvent objects as they're published. The stream closes
111
+ * cleanly after the channel-level TTL elapses since the LAST event
112
+ * (rolling 60s).
113
+ *
114
+ * If no publisher writes to the channel within 60s of subscription, the
115
+ * stream closes empty.
116
+ */
117
+ subscribe(channelKey: string): ReadableStream<GlassboxEvent>;
118
+ /**
119
+ * Test-only escape hatch. Clears any in-memory state. Upstash adapter
120
+ * no-ops (server-side state isn't accessible from here). Tests reach for
121
+ * this between cases to keep adapters hermetic.
122
+ */
123
+ _reset?(): void;
124
+ }
125
+ /**
126
+ * TTL applied to a stream after each event. The design doc names 60s; this
127
+ * constant centralizes it so both adapters + tests agree.
128
+ */
129
+ declare const GLASSBOX_STREAM_TTL_MS = 60000;
130
+
131
+ export { type AdvisoryFiredData as A, type CompileDoneData as C, type ExecuteAttemptData as E, type FallbackWalkedData as F, type GlassboxEvent as G, type CompileStartData as a, type ExecuteSuccessData as b, GLASSBOX_STREAM_TTL_MS as c, type GlassboxEventKind as d, type GlassboxPubSub as e };
@@ -0,0 +1,149 @@
1
+ import { i as Adapter, x as SectionKind } from './ir-Bqn1RVdV.mjs';
2
+
3
+ /**
4
+ * Internal config + hook types for createGlassboxRoutes().
5
+ *
6
+ * The public contract lives on `GlassboxRoutesConfig` in ./index.ts; these
7
+ * are the narrower per-handler shapes consumed by proxy.ts and stream.ts.
8
+ */
9
+
10
+ /**
11
+ * Wire contract for the Glass-Box Chrome extension's brain-poll endpoint.
12
+ *
13
+ * The list mode of `proxy(req)` returns `{ traces: TraceSummary[] }`. The
14
+ * detail mode (`?traceId=<id>`) returns a single `TraceDetail`. These are
15
+ * the camelCase shapes the extension renderer expects — distinct from the
16
+ * snake_case `compile_outcomes` row shape that PostgREST returns. The
17
+ * factory's typed `rowToSummary` / `rowToDetail` transformer is the single
18
+ * canonical boundary between the DB shape and the wire shape (see
19
+ * `feedback_typed_boundary_transformers.md` in kgauto memory for the rule).
20
+ */
21
+ interface TraceSummary {
22
+ traceId: string;
23
+ appId: string;
24
+ archetype: string;
25
+ target: string;
26
+ createdAt: string;
27
+ tokensIn: number;
28
+ tokensOut: number;
29
+ estimatedCostUsd: number;
30
+ }
31
+
32
+ interface AdvisoryRecord {
33
+ level: 'info' | 'warn' | 'critical';
34
+ /** Stable advisory identifier, e.g. "caching-off-on-claude". */
35
+ code: string;
36
+ /** Consumer-renderable message — no internal jargon ("L-040", "R3" etc.). */
37
+ message: string;
38
+ /** Optional secondary one-liner. Renders below `message` in italics. */
39
+ suggestion?: string;
40
+ /** Deep link to the relevant section of `interfaces/kgauto.md` or docs. */
41
+ docsUrl?: string;
42
+ /**
43
+ * alpha.28+ — closed-union adaptation hint surfaced by the advisor when
44
+ * the advisory can be auto-mitigated by a config knob. Renderer surfaces
45
+ * as `→ try toolOrchestration: 'sequential'` on the advisory row.
46
+ *
47
+ * MUST stay byte-identical to Builder C's
48
+ * `BestPracticeAdvisory.suggestedAdaptation` shape (verified at Phase 2
49
+ * integration; the Adapter type itself is the contract).
50
+ */
51
+ suggestedAdaptation?: Adapter;
52
+ }
53
+ /**
54
+ * Cost-equivalent alternative the chain could have served. Computed at
55
+ * detail-view time by `computeCounterfactuals()` against the served row's
56
+ * observed token counts + archetype + cache state. Up to 2 entries, sorted
57
+ * cheapest first.
58
+ */
59
+ interface TraceCounterfactual {
60
+ modelId: string;
61
+ estimatedCostUsd: number;
62
+ /** servedCostUsd - estimatedCostUsd (always > 0; only ≥10% savings kept). */
63
+ savingsUsd: number;
64
+ /** 0-100. */
65
+ savingsPercent: number;
66
+ /** Plain-English rationale tying archetype + perf score. */
67
+ reason: string;
68
+ }
69
+ /**
70
+ * Derived axis-health tri-state for the three Glass-Box dots
71
+ * (input-ratio · cache · fallback). Renderer reads; transformer computes.
72
+ *
73
+ * Thresholds (locked in design contract Phase 0):
74
+ * - inputRatio: green ≤ 0.65 · yellow 0.65–0.85 · red > 0.85
75
+ * - cache (only when historyCacheableTokens > 1000):
76
+ * green if inputCacheHitRatio ≥ 0.5
77
+ * yellow if 0.1 ≤ inputCacheHitRatio < 0.5
78
+ * red if inputCacheHitRatio < 0.1
79
+ * na if historyCacheableTokens ≤ 1000
80
+ * - fallback: red iff fellOverFrom !== undefined && fellOverFrom !== target
81
+ */
82
+ interface TraceHealth {
83
+ inputRatioStatus: 'green' | 'yellow' | 'red';
84
+ cacheStatus: 'green' | 'yellow' | 'red' | 'na';
85
+ fallbackStatus: 'green' | 'red';
86
+ }
87
+ /**
88
+ * alpha.29+ — wire-boundary representation of a translator section-rewrite.
89
+ *
90
+ * Distinct from the package-internal `SectionRewrite` type in `ir.ts`: this
91
+ * shape drops `originalText` + `transformedText` because those may carry
92
+ * consumer PII. The renderer shows the `rule` + `summary` only. Full text
93
+ * stays on `compile_outcomes.section_rewrites_applied` (Supabase row), gated
94
+ * by RLS for brain-side cross-app learning.
95
+ */
96
+ interface TraceSectionRewrite {
97
+ /** Stable id of the rewritten section. */
98
+ sectionId: string;
99
+ /** Section-kind discriminator that triggered the rewrite. */
100
+ kind: SectionKind;
101
+ /** Stable rule identifier (e.g. `'sequential-tool-cliff-below-floor'`). */
102
+ rule: string;
103
+ /**
104
+ * Plain-English one-liner describing what fired and why. Renderer surfaces
105
+ * this on the Coaching card; no internal jargon ("L-040", "below floor").
106
+ */
107
+ summary: string;
108
+ }
109
+ interface TraceDetail extends TraceSummary {
110
+ mutationsApplied: string[];
111
+ advisories: AdvisoryRecord[];
112
+ rawRequest?: string;
113
+ rawResponse?: string;
114
+ /** Set when consumer passed a forceModel / fallback fired. */
115
+ requestedModel?: string;
116
+ /** Provider finish reason — 'stop' / 'max_tokens' / 'tool_use' / etc. */
117
+ finishReason?: string;
118
+ /** Time to first token (ms); populated when provider surfaces it. */
119
+ ttftMs?: number;
120
+ /** End-to-end wall-clock (ms); from migration 018. */
121
+ totalMs?: number;
122
+ /** Tools kept after relevance pass. */
123
+ toolsCount?: number;
124
+ /** Number of history messages at compile time. */
125
+ historyDepth?: number;
126
+ /** Rendered system prompt size in characters. */
127
+ systemPromptChars?: number;
128
+ cacheReadInputTokens: number;
129
+ cacheCreationInputTokens: number;
130
+ historyCacheableTokens: number;
131
+ /** Derived: cacheReadInputTokens / max(tokensIn, 1). 0-1. */
132
+ inputCacheHitRatio: number;
133
+ fellOverFrom?: string;
134
+ fallbackReason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
135
+ /** Up to 2 alternatives. Empty array (not undefined) when none qualify. */
136
+ counterfactuals?: TraceCounterfactual[];
137
+ /** Undefined when 7d volume < 5/day (insufficient data). */
138
+ projectedDailyCostUsd?: number;
139
+ /**
140
+ * alpha.29+ — translator activity for this trace. Empty array (not
141
+ * undefined) when no rewrites fired or pre-019 row. Surfaced in the
142
+ * Glass-Box Coaching card as synthetic info-level rows. PII-safe by
143
+ * construction: only sectionId + kind + rule + summary cross the wire.
144
+ */
145
+ sectionRewritesApplied: TraceSectionRewrite[];
146
+ health: TraceHealth;
147
+ }
148
+
149
+ export type { AdvisoryRecord as A, TraceHealth as T, TraceDetail as a, TraceSummary as b, TraceCounterfactual as c, TraceSectionRewrite as d };
@@ -0,0 +1,149 @@
1
+ import { i as Adapter, x as SectionKind } from './ir-Bvlkw5ja.js';
2
+
3
+ /**
4
+ * Internal config + hook types for createGlassboxRoutes().
5
+ *
6
+ * The public contract lives on `GlassboxRoutesConfig` in ./index.ts; these
7
+ * are the narrower per-handler shapes consumed by proxy.ts and stream.ts.
8
+ */
9
+
10
+ /**
11
+ * Wire contract for the Glass-Box Chrome extension's brain-poll endpoint.
12
+ *
13
+ * The list mode of `proxy(req)` returns `{ traces: TraceSummary[] }`. The
14
+ * detail mode (`?traceId=<id>`) returns a single `TraceDetail`. These are
15
+ * the camelCase shapes the extension renderer expects — distinct from the
16
+ * snake_case `compile_outcomes` row shape that PostgREST returns. The
17
+ * factory's typed `rowToSummary` / `rowToDetail` transformer is the single
18
+ * canonical boundary between the DB shape and the wire shape (see
19
+ * `feedback_typed_boundary_transformers.md` in kgauto memory for the rule).
20
+ */
21
+ interface TraceSummary {
22
+ traceId: string;
23
+ appId: string;
24
+ archetype: string;
25
+ target: string;
26
+ createdAt: string;
27
+ tokensIn: number;
28
+ tokensOut: number;
29
+ estimatedCostUsd: number;
30
+ }
31
+
32
+ interface AdvisoryRecord {
33
+ level: 'info' | 'warn' | 'critical';
34
+ /** Stable advisory identifier, e.g. "caching-off-on-claude". */
35
+ code: string;
36
+ /** Consumer-renderable message — no internal jargon ("L-040", "R3" etc.). */
37
+ message: string;
38
+ /** Optional secondary one-liner. Renders below `message` in italics. */
39
+ suggestion?: string;
40
+ /** Deep link to the relevant section of `interfaces/kgauto.md` or docs. */
41
+ docsUrl?: string;
42
+ /**
43
+ * alpha.28+ — closed-union adaptation hint surfaced by the advisor when
44
+ * the advisory can be auto-mitigated by a config knob. Renderer surfaces
45
+ * as `→ try toolOrchestration: 'sequential'` on the advisory row.
46
+ *
47
+ * MUST stay byte-identical to Builder C's
48
+ * `BestPracticeAdvisory.suggestedAdaptation` shape (verified at Phase 2
49
+ * integration; the Adapter type itself is the contract).
50
+ */
51
+ suggestedAdaptation?: Adapter;
52
+ }
53
+ /**
54
+ * Cost-equivalent alternative the chain could have served. Computed at
55
+ * detail-view time by `computeCounterfactuals()` against the served row's
56
+ * observed token counts + archetype + cache state. Up to 2 entries, sorted
57
+ * cheapest first.
58
+ */
59
+ interface TraceCounterfactual {
60
+ modelId: string;
61
+ estimatedCostUsd: number;
62
+ /** servedCostUsd - estimatedCostUsd (always > 0; only ≥10% savings kept). */
63
+ savingsUsd: number;
64
+ /** 0-100. */
65
+ savingsPercent: number;
66
+ /** Plain-English rationale tying archetype + perf score. */
67
+ reason: string;
68
+ }
69
+ /**
70
+ * Derived axis-health tri-state for the three Glass-Box dots
71
+ * (input-ratio · cache · fallback). Renderer reads; transformer computes.
72
+ *
73
+ * Thresholds (locked in design contract Phase 0):
74
+ * - inputRatio: green ≤ 0.65 · yellow 0.65–0.85 · red > 0.85
75
+ * - cache (only when historyCacheableTokens > 1000):
76
+ * green if inputCacheHitRatio ≥ 0.5
77
+ * yellow if 0.1 ≤ inputCacheHitRatio < 0.5
78
+ * red if inputCacheHitRatio < 0.1
79
+ * na if historyCacheableTokens ≤ 1000
80
+ * - fallback: red iff fellOverFrom !== undefined && fellOverFrom !== target
81
+ */
82
+ interface TraceHealth {
83
+ inputRatioStatus: 'green' | 'yellow' | 'red';
84
+ cacheStatus: 'green' | 'yellow' | 'red' | 'na';
85
+ fallbackStatus: 'green' | 'red';
86
+ }
87
+ /**
88
+ * alpha.29+ — wire-boundary representation of a translator section-rewrite.
89
+ *
90
+ * Distinct from the package-internal `SectionRewrite` type in `ir.ts`: this
91
+ * shape drops `originalText` + `transformedText` because those may carry
92
+ * consumer PII. The renderer shows the `rule` + `summary` only. Full text
93
+ * stays on `compile_outcomes.section_rewrites_applied` (Supabase row), gated
94
+ * by RLS for brain-side cross-app learning.
95
+ */
96
+ interface TraceSectionRewrite {
97
+ /** Stable id of the rewritten section. */
98
+ sectionId: string;
99
+ /** Section-kind discriminator that triggered the rewrite. */
100
+ kind: SectionKind;
101
+ /** Stable rule identifier (e.g. `'sequential-tool-cliff-below-floor'`). */
102
+ rule: string;
103
+ /**
104
+ * Plain-English one-liner describing what fired and why. Renderer surfaces
105
+ * this on the Coaching card; no internal jargon ("L-040", "below floor").
106
+ */
107
+ summary: string;
108
+ }
109
+ interface TraceDetail extends TraceSummary {
110
+ mutationsApplied: string[];
111
+ advisories: AdvisoryRecord[];
112
+ rawRequest?: string;
113
+ rawResponse?: string;
114
+ /** Set when consumer passed a forceModel / fallback fired. */
115
+ requestedModel?: string;
116
+ /** Provider finish reason — 'stop' / 'max_tokens' / 'tool_use' / etc. */
117
+ finishReason?: string;
118
+ /** Time to first token (ms); populated when provider surfaces it. */
119
+ ttftMs?: number;
120
+ /** End-to-end wall-clock (ms); from migration 018. */
121
+ totalMs?: number;
122
+ /** Tools kept after relevance pass. */
123
+ toolsCount?: number;
124
+ /** Number of history messages at compile time. */
125
+ historyDepth?: number;
126
+ /** Rendered system prompt size in characters. */
127
+ systemPromptChars?: number;
128
+ cacheReadInputTokens: number;
129
+ cacheCreationInputTokens: number;
130
+ historyCacheableTokens: number;
131
+ /** Derived: cacheReadInputTokens / max(tokensIn, 1). 0-1. */
132
+ inputCacheHitRatio: number;
133
+ fellOverFrom?: string;
134
+ fallbackReason?: 'rate_limit' | 'provider_auth_failed' | 'provider_error' | 'cliff' | 'cost_cap' | 'contract_violation';
135
+ /** Up to 2 alternatives. Empty array (not undefined) when none qualify. */
136
+ counterfactuals?: TraceCounterfactual[];
137
+ /** Undefined when 7d volume < 5/day (insufficient data). */
138
+ projectedDailyCostUsd?: number;
139
+ /**
140
+ * alpha.29+ — translator activity for this trace. Empty array (not
141
+ * undefined) when no rewrites fired or pre-019 row. Surfaced in the
142
+ * Glass-Box Coaching card as synthetic info-level rows. PII-safe by
143
+ * construction: only sectionId + kind + rule + summary cross the wire.
144
+ */
145
+ sectionRewritesApplied: TraceSectionRewrite[];
146
+ health: TraceHealth;
147
+ }
148
+
149
+ export type { AdvisoryRecord as A, TraceHealth as T, TraceDetail as a, TraceSummary as b, TraceCounterfactual as c, TraceSectionRewrite as d };
@@ -0,0 +1,131 @@
1
+ import { s as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, m as CallAttempt } from './ir-Bqn1RVdV.mjs';
2
+
3
+ /**
4
+ * Glass-Box observability types (alpha.17).
5
+ *
6
+ * The substrate for kgauto's in-flight observability surface — a Chrome MV3
7
+ * side panel that renders compile + execute + advisor outputs in real-time.
8
+ * See design doc:
9
+ * ~/.gstack/projects/stue-kgauto/stgreen-claude-serene-williamson-51a105-design-20260518-175356.md
10
+ *
11
+ * Wire shape is intentionally minimal:
12
+ * { kind, at, data } — discriminated union by `kind`.
13
+ *
14
+ * Critical-path safety (L-086 derived): emit MUST NEVER fail the user's
15
+ * `call()` invocation. emit.ts wraps every adapter write in try/catch +
16
+ * silently drops on error. Consumers in Vercel Edge runtimes can lose one
17
+ * event without losing the response.
18
+ */
19
+
20
+ /**
21
+ * Discriminator. Six event kinds cover the v1 substrate. New kinds added
22
+ * additively; the side-panel renderer treats unknown kinds as "ignore".
23
+ */
24
+ type GlassboxEventKind = 'compile.start' | 'compile.done' | 'execute.attempt' | 'execute.success' | 'advisory.fired' | 'fallback.walked';
25
+ /**
26
+ * Wire envelope. Every emit lands as one of these.
27
+ *
28
+ * - kind: discriminator
29
+ * - at: unix milliseconds (Date.now())
30
+ * - data: kind-specific payload
31
+ *
32
+ * `data` typed loosely as Record<string, unknown> for serialization-friendliness;
33
+ * the per-kind builders below populate it with the structured shape expected
34
+ * by the renderer. We deliberately do NOT typescript-narrow `data` by kind on
35
+ * the wire type — the side panel reads JSON from SSE and only the renderer
36
+ * needs the narrowed shape. Internal callers (emit.ts) get type assistance via
37
+ * the typed factory helpers in emit.ts.
38
+ */
39
+ interface GlassboxEvent {
40
+ kind: GlassboxEventKind;
41
+ at: number;
42
+ data: Record<string, unknown>;
43
+ }
44
+ /**
45
+ * Per-kind data shapes. Surfaced as type aids; not enforced at the
46
+ * GlassboxEvent boundary (intentionally — see comment above).
47
+ */
48
+ interface CompileStartData {
49
+ appId: string;
50
+ archetype: string;
51
+ models: string[];
52
+ }
53
+ interface CompileDoneData {
54
+ target: string;
55
+ provider: string;
56
+ fallbackChain: string[];
57
+ tokensIn: number;
58
+ estimatedCostUsd: number;
59
+ mutationsApplied: MutationApplied[];
60
+ advisories: BestPracticeAdvisory[];
61
+ }
62
+ interface ExecuteAttemptData {
63
+ model: string;
64
+ attemptIndex: number;
65
+ }
66
+ interface ExecuteSuccessData {
67
+ model: string;
68
+ tokensIn: number;
69
+ tokensOut: number;
70
+ latencyMs: number;
71
+ }
72
+ interface AdvisoryFiredData {
73
+ code: string;
74
+ message: string;
75
+ }
76
+ interface FallbackWalkedData {
77
+ from: string;
78
+ to: string;
79
+ reason: FallbackReason | 'unknown';
80
+ attempt: CallAttempt;
81
+ }
82
+ /**
83
+ * Pub/sub backend interface. Two adapters implement it: in-memory (dev /
84
+ * single-process) and Upstash Redis Streams (Vercel Edge multi-instance).
85
+ *
86
+ * The choice is made at module load (NOT per-call) based on env-var presence:
87
+ * if (UPSTASH_REDIS_URL && UPSTASH_REDIS_TOKEN) → Upstash
88
+ * else → in-memory
89
+ *
90
+ * Stream TTL: 60s after last event. After that, subscriber stream closes
91
+ * cleanly. The adapter owns its own TTL clock; subscribe() is agnostic.
92
+ */
93
+ interface GlassboxPubSub {
94
+ /**
95
+ * Publish a single event to a channel key. The channel is an opaque
96
+ * namespaced string — callers build it via `traceChannel(traceId)` or
97
+ * `appChannel(appId)` (see pubsub-upstash.ts). Returns a promise that
98
+ * resolves after the event is durably appended (or rejects on adapter
99
+ * failure — callers in emit.ts always swallow rejections).
100
+ *
101
+ * Pre-alpha.26 the parameter was named `traceId` because there was only
102
+ * one channel namespace; alpha.26 added per-app channels for the
103
+ * "tail-all" Live tab subscription. Behavior identical to the adapters —
104
+ * they treat the value as an opaque key — but the rename surfaces the
105
+ * generalization at the type level.
106
+ */
107
+ publish(channelKey: string, event: GlassboxEvent): Promise<void>;
108
+ /**
109
+ * Subscribe to events on a channel key. Returns a ReadableStream that
110
+ * emits GlassboxEvent objects as they're published. The stream closes
111
+ * cleanly after the channel-level TTL elapses since the LAST event
112
+ * (rolling 60s).
113
+ *
114
+ * If no publisher writes to the channel within 60s of subscription, the
115
+ * stream closes empty.
116
+ */
117
+ subscribe(channelKey: string): ReadableStream<GlassboxEvent>;
118
+ /**
119
+ * Test-only escape hatch. Clears any in-memory state. Upstash adapter
120
+ * no-ops (server-side state isn't accessible from here). Tests reach for
121
+ * this between cases to keep adapters hermetic.
122
+ */
123
+ _reset?(): void;
124
+ }
125
+ /**
126
+ * TTL applied to a stream after each event. The design doc names 60s; this
127
+ * constant centralizes it so both adapters + tests agree.
128
+ */
129
+ declare const GLASSBOX_STREAM_TTL_MS = 60000;
130
+
131
+ export { type AdvisoryFiredData as A, type CompileDoneData as C, type ExecuteAttemptData as E, type FallbackWalkedData as F, type GlassboxEvent as G, type CompileStartData as a, type ExecuteSuccessData as b, GLASSBOX_STREAM_TTL_MS as c, type GlassboxEventKind as d, type GlassboxPubSub as e };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@warmdrift/kgauto-compiler",
3
- "version": "2.0.0-alpha.7",
4
- "description": "Prompt compiler + central learning brain for multi-model AI apps. Swap models without rewriting prompts.",
3
+ "version": "2.0.0-alpha.70",
4
+ "description": "Prompt compiler with executable provider knowledge for multi-model AI apps: normalized multi-provider transport with fallback chains, compile-time cliff guards, a curated model registry, and a telemetry flight recorder. Swap models without rewriting prompts.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
7
7
  "types": "./dist/index.d.ts",
@@ -20,11 +20,44 @@
20
20
  "types": "./dist/profiles.d.ts",
21
21
  "import": "./dist/profiles.mjs",
22
22
  "require": "./dist/profiles.js"
23
+ },
24
+ "./brain-proxy": {
25
+ "types": "./dist/brain-proxy.d.ts",
26
+ "import": "./dist/brain-proxy.mjs",
27
+ "require": "./dist/brain-proxy.js"
28
+ },
29
+ "./key-health": {
30
+ "types": "./dist/key-health.d.ts",
31
+ "import": "./dist/key-health.mjs",
32
+ "require": "./dist/key-health.js"
33
+ },
34
+ "./glassbox": {
35
+ "types": "./dist/glassbox/index.d.ts",
36
+ "import": "./dist/glassbox/index.mjs",
37
+ "require": "./dist/glassbox/index.js"
38
+ },
39
+ "./glassbox-routes": {
40
+ "types": "./dist/glassbox-routes/index.d.ts",
41
+ "import": "./dist/glassbox-routes/index.mjs",
42
+ "require": "./dist/glassbox-routes/index.js"
43
+ },
44
+ "./glassbox-routes/format": {
45
+ "types": "./dist/glassbox-routes/format.d.ts",
46
+ "import": "./dist/glassbox-routes/format.mjs",
47
+ "require": "./dist/glassbox-routes/format.js"
48
+ },
49
+ "./glassbox-routes/react": {
50
+ "types": "./dist/glassbox-routes/react/index.d.ts",
51
+ "import": "./dist/glassbox-routes/react/index.mjs",
52
+ "require": "./dist/glassbox-routes/react/index.js"
23
53
  }
24
54
  },
25
- "files": ["dist", "README.md"],
55
+ "files": [
56
+ "dist",
57
+ "README.md"
58
+ ],
26
59
  "scripts": {
27
- "build": "tsup src/index.ts src/dialect.ts src/profiles.ts --format cjs,esm --dts --clean",
60
+ "build": "tsup src/index.ts src/dialect.ts src/profiles.ts src/brain-proxy.ts src/key-health.ts src/glassbox/index.ts src/glassbox-routes/index.ts src/glassbox-routes/format.ts src/glassbox-routes/react/index.ts --format cjs,esm --dts --clean --external react --external react-dom",
28
61
  "test": "vitest run",
29
62
  "test:watch": "vitest",
30
63
  "typecheck": "tsc --noEmit",
@@ -40,18 +73,31 @@
40
73
  "gemini",
41
74
  "deepseek",
42
75
  "prompt-cache",
43
- "self-improving"
76
+ "model-fallback"
44
77
  ],
45
78
  "license": "MIT",
46
- "dependencies": {},
47
79
  "peerDependencies": {
48
- "js-tiktoken": ">=1.0.0"
80
+ "js-tiktoken": ">=1.0.0",
81
+ "react": ">=18.0.0",
82
+ "react-dom": ">=18.0.0"
49
83
  },
50
84
  "peerDependenciesMeta": {
51
- "js-tiktoken": { "optional": true }
85
+ "js-tiktoken": {
86
+ "optional": true
87
+ },
88
+ "react": {
89
+ "optional": true
90
+ },
91
+ "react-dom": {
92
+ "optional": true
93
+ }
52
94
  },
53
95
  "devDependencies": {
54
96
  "@types/node": "^22.10.0",
97
+ "@types/react": "^19.2.15",
98
+ "@types/react-dom": "^19.2.3",
99
+ "react": "^19.2.6",
100
+ "react-dom": "^19.2.6",
55
101
  "tsup": "^8.4.0",
56
102
  "typescript": "^5.7.0",
57
103
  "vitest": "^3.1.0"