@warmdrift/kgauto-compiler 2.0.0-alpha.9 → 2.0.0-alpha.90

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-4LYNDEHJ.mjs +219 -0
  7. package/dist/chunk-65ZMX5OT.mjs +169 -0
  8. package/dist/{chunk-5TI6PNSK.mjs → chunk-BVEXV5KC.mjs} +11 -0
  9. package/dist/chunk-ENELVMJI.mjs +858 -0
  10. package/dist/chunk-NBO4R5PC.mjs +313 -0
  11. package/dist/chunk-OK2TMFRR.mjs +1879 -0
  12. package/dist/chunk-P3TOAEG4.mjs +56 -0
  13. package/dist/chunk-RO22VFIF.mjs +29 -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 +3197 -0
  29. package/dist/glassbox-routes/index.mjs +668 -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 +3782 -99
  35. package/dist/index.d.ts +3782 -99
  36. package/dist/index.js +10835 -2046
  37. package/dist/index.mjs +6270 -276
  38. package/dist/ir-CTx026t0.d.ts +1887 -0
  39. package/dist/ir-DeYMLWge.d.mts +1887 -0
  40. package/dist/key-health.d.mts +166 -0
  41. package/dist/key-health.d.ts +166 -0
  42. package/dist/key-health.js +247 -0
  43. package/dist/key-health.mjs +12 -0
  44. package/dist/profiles.d.mts +352 -2
  45. package/dist/profiles.d.ts +352 -2
  46. package/dist/profiles.js +1282 -51
  47. package/dist/profiles.mjs +19 -1
  48. package/dist/types-BKbRtmUb.d.ts +131 -0
  49. package/dist/types-Cp9ot1HV.d.ts +142 -0
  50. package/dist/types-DD36cCbZ.d.mts +142 -0
  51. package/dist/types-cBzinzUR.d.mts +131 -0
  52. package/package.json +62 -9
  53. package/dist/chunk-3KVKELZN.mjs +0 -657
  54. package/dist/profiles-BYVOc1eW.d.ts +0 -700
  55. package/dist/profiles-NUZOIzGr.d.mts +0 -700
package/dist/profiles.mjs CHANGED
@@ -1,14 +1,32 @@
1
1
  import {
2
2
  ALIASES,
3
+ LATENCY_TIER_MS,
4
+ _setProfileBrainHook,
5
+ _testClearConsumerProfiles,
3
6
  allProfiles,
7
+ allProfilesRaw,
8
+ bestEffortProfile,
4
9
  getProfile,
10
+ inferProviderFromId,
11
+ latencyTierOf,
5
12
  profilesByProvider,
13
+ registerProfiles,
14
+ resolveModelAlias,
6
15
  tryGetProfile
7
- } from "./chunk-3KVKELZN.mjs";
16
+ } from "./chunk-OK2TMFRR.mjs";
8
17
  export {
9
18
  ALIASES,
19
+ LATENCY_TIER_MS,
20
+ _setProfileBrainHook,
21
+ _testClearConsumerProfiles,
10
22
  allProfiles,
23
+ allProfilesRaw,
24
+ bestEffortProfile,
11
25
  getProfile,
26
+ inferProviderFromId,
27
+ latencyTierOf,
12
28
  profilesByProvider,
29
+ registerProfiles,
30
+ resolveModelAlias,
13
31
  tryGetProfile
14
32
  };
@@ -0,0 +1,131 @@
1
+ import { t as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, n as CallAttempt } from './ir-CTx026t0.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,142 @@
1
+ import { j as Adapter, F as FallbackReason, y as SectionKind } from './ir-CTx026t0.js';
2
+
3
+ /**
4
+ * Wire contract for the Glass-Box Chrome extension's brain-poll endpoint.
5
+ *
6
+ * The list mode of `proxy(req)` returns `{ traces: TraceSummary[] }`. The
7
+ * detail mode (`?traceId=<id>`) returns a single `TraceDetail`. These are
8
+ * the camelCase shapes the extension renderer expects — distinct from the
9
+ * snake_case `compile_outcomes` row shape that PostgREST returns. The
10
+ * factory's typed `rowToSummary` / `rowToDetail` transformer is the single
11
+ * canonical boundary between the DB shape and the wire shape (see
12
+ * `feedback_typed_boundary_transformers.md` in kgauto memory for the rule).
13
+ */
14
+ interface TraceSummary {
15
+ traceId: string;
16
+ appId: string;
17
+ archetype: string;
18
+ target: string;
19
+ createdAt: string;
20
+ tokensIn: number;
21
+ tokensOut: number;
22
+ estimatedCostUsd: number;
23
+ }
24
+
25
+ interface AdvisoryRecord {
26
+ level: 'info' | 'warn' | 'critical';
27
+ /** Stable advisory identifier, e.g. "caching-off-on-claude". */
28
+ code: string;
29
+ /** Consumer-renderable message — no internal jargon ("L-040", "R3" etc.). */
30
+ message: string;
31
+ /** Optional secondary one-liner. Renders below `message` in italics. */
32
+ suggestion?: string;
33
+ /** Deep link to the relevant section of `interfaces/kgauto.md` or docs. */
34
+ docsUrl?: string;
35
+ /**
36
+ * alpha.28+ — closed-union adaptation hint surfaced by the advisor when
37
+ * the advisory can be auto-mitigated by a config knob. Renderer surfaces
38
+ * as `→ try toolOrchestration: 'sequential'` on the advisory row.
39
+ *
40
+ * MUST stay byte-identical to Builder C's
41
+ * `BestPracticeAdvisory.suggestedAdaptation` shape (verified at Phase 2
42
+ * integration; the Adapter type itself is the contract).
43
+ */
44
+ suggestedAdaptation?: Adapter;
45
+ }
46
+ /**
47
+ * Cost-equivalent alternative the chain could have served. Computed at
48
+ * detail-view time by `computeCounterfactuals()` against the served row's
49
+ * observed token counts + archetype + cache state. Up to 2 entries, sorted
50
+ * cheapest first.
51
+ */
52
+ interface TraceCounterfactual {
53
+ modelId: string;
54
+ estimatedCostUsd: number;
55
+ /** servedCostUsd - estimatedCostUsd (always > 0; only ≥10% savings kept). */
56
+ savingsUsd: number;
57
+ /** 0-100. */
58
+ savingsPercent: number;
59
+ /** Plain-English rationale tying archetype + perf score. */
60
+ reason: string;
61
+ }
62
+ /**
63
+ * Derived axis-health tri-state for the three Glass-Box dots
64
+ * (input-ratio · cache · fallback). Renderer reads; transformer computes.
65
+ *
66
+ * Thresholds (locked in design contract Phase 0):
67
+ * - inputRatio: green ≤ 0.65 · yellow 0.65–0.85 · red > 0.85
68
+ * - cache (only when historyCacheableTokens > 1000):
69
+ * green if inputCacheHitRatio ≥ 0.5
70
+ * yellow if 0.1 ≤ inputCacheHitRatio < 0.5
71
+ * red if inputCacheHitRatio < 0.1
72
+ * na if historyCacheableTokens ≤ 1000
73
+ * - fallback: red iff fellOverFrom !== undefined && fellOverFrom !== target
74
+ */
75
+ interface TraceHealth {
76
+ inputRatioStatus: 'green' | 'yellow' | 'red';
77
+ cacheStatus: 'green' | 'yellow' | 'red' | 'na';
78
+ fallbackStatus: 'green' | 'red';
79
+ }
80
+ /**
81
+ * alpha.29+ — wire-boundary representation of a translator section-rewrite.
82
+ *
83
+ * Distinct from the package-internal `SectionRewrite` type in `ir.ts`: this
84
+ * shape drops `originalText` + `transformedText` because those may carry
85
+ * consumer PII. The renderer shows the `rule` + `summary` only. Full text
86
+ * stays on `compile_outcomes.section_rewrites_applied` (Supabase row), gated
87
+ * by RLS for brain-side cross-app learning.
88
+ */
89
+ interface TraceSectionRewrite {
90
+ /** Stable id of the rewritten section. */
91
+ sectionId: string;
92
+ /** Section-kind discriminator that triggered the rewrite. */
93
+ kind: SectionKind;
94
+ /** Stable rule identifier (e.g. `'sequential-tool-cliff-below-floor'`). */
95
+ rule: string;
96
+ /**
97
+ * Plain-English one-liner describing what fired and why. Renderer surfaces
98
+ * this on the Coaching card; no internal jargon ("L-040", "below floor").
99
+ */
100
+ summary: string;
101
+ }
102
+ interface TraceDetail extends TraceSummary {
103
+ mutationsApplied: string[];
104
+ advisories: AdvisoryRecord[];
105
+ rawRequest?: string;
106
+ rawResponse?: string;
107
+ /** Set when consumer passed a forceModel / fallback fired. */
108
+ requestedModel?: string;
109
+ /** Provider finish reason — 'stop' / 'max_tokens' / 'tool_use' / etc. */
110
+ finishReason?: string;
111
+ /** Time to first token (ms); populated when provider surfaces it. */
112
+ ttftMs?: number;
113
+ /** End-to-end wall-clock (ms); from migration 018. */
114
+ totalMs?: number;
115
+ /** Tools kept after relevance pass. */
116
+ toolsCount?: number;
117
+ /** Number of history messages at compile time. */
118
+ historyDepth?: number;
119
+ /** Rendered system prompt size in characters. */
120
+ systemPromptChars?: number;
121
+ cacheReadInputTokens: number;
122
+ cacheCreationInputTokens: number;
123
+ historyCacheableTokens: number;
124
+ /** Derived: cacheReadInputTokens / max(tokensIn, 1). 0-1. */
125
+ inputCacheHitRatio: number;
126
+ fellOverFrom?: string;
127
+ fallbackReason?: FallbackReason;
128
+ /** Up to 2 alternatives. Empty array (not undefined) when none qualify. */
129
+ counterfactuals?: TraceCounterfactual[];
130
+ /** Undefined when 7d volume < 5/day (insufficient data). */
131
+ projectedDailyCostUsd?: number;
132
+ /**
133
+ * alpha.29+ — translator activity for this trace. Empty array (not
134
+ * undefined) when no rewrites fired or pre-019 row. Surfaced in the
135
+ * Glass-Box Coaching card as synthetic info-level rows. PII-safe by
136
+ * construction: only sectionId + kind + rule + summary cross the wire.
137
+ */
138
+ sectionRewritesApplied: TraceSectionRewrite[];
139
+ health: TraceHealth;
140
+ }
141
+
142
+ export type { AdvisoryRecord as A, TraceHealth as T, TraceDetail as a, TraceSummary as b, TraceCounterfactual as c, TraceSectionRewrite as d };
@@ -0,0 +1,142 @@
1
+ import { j as Adapter, F as FallbackReason, y as SectionKind } from './ir-DeYMLWge.mjs';
2
+
3
+ /**
4
+ * Wire contract for the Glass-Box Chrome extension's brain-poll endpoint.
5
+ *
6
+ * The list mode of `proxy(req)` returns `{ traces: TraceSummary[] }`. The
7
+ * detail mode (`?traceId=<id>`) returns a single `TraceDetail`. These are
8
+ * the camelCase shapes the extension renderer expects — distinct from the
9
+ * snake_case `compile_outcomes` row shape that PostgREST returns. The
10
+ * factory's typed `rowToSummary` / `rowToDetail` transformer is the single
11
+ * canonical boundary between the DB shape and the wire shape (see
12
+ * `feedback_typed_boundary_transformers.md` in kgauto memory for the rule).
13
+ */
14
+ interface TraceSummary {
15
+ traceId: string;
16
+ appId: string;
17
+ archetype: string;
18
+ target: string;
19
+ createdAt: string;
20
+ tokensIn: number;
21
+ tokensOut: number;
22
+ estimatedCostUsd: number;
23
+ }
24
+
25
+ interface AdvisoryRecord {
26
+ level: 'info' | 'warn' | 'critical';
27
+ /** Stable advisory identifier, e.g. "caching-off-on-claude". */
28
+ code: string;
29
+ /** Consumer-renderable message — no internal jargon ("L-040", "R3" etc.). */
30
+ message: string;
31
+ /** Optional secondary one-liner. Renders below `message` in italics. */
32
+ suggestion?: string;
33
+ /** Deep link to the relevant section of `interfaces/kgauto.md` or docs. */
34
+ docsUrl?: string;
35
+ /**
36
+ * alpha.28+ — closed-union adaptation hint surfaced by the advisor when
37
+ * the advisory can be auto-mitigated by a config knob. Renderer surfaces
38
+ * as `→ try toolOrchestration: 'sequential'` on the advisory row.
39
+ *
40
+ * MUST stay byte-identical to Builder C's
41
+ * `BestPracticeAdvisory.suggestedAdaptation` shape (verified at Phase 2
42
+ * integration; the Adapter type itself is the contract).
43
+ */
44
+ suggestedAdaptation?: Adapter;
45
+ }
46
+ /**
47
+ * Cost-equivalent alternative the chain could have served. Computed at
48
+ * detail-view time by `computeCounterfactuals()` against the served row's
49
+ * observed token counts + archetype + cache state. Up to 2 entries, sorted
50
+ * cheapest first.
51
+ */
52
+ interface TraceCounterfactual {
53
+ modelId: string;
54
+ estimatedCostUsd: number;
55
+ /** servedCostUsd - estimatedCostUsd (always > 0; only ≥10% savings kept). */
56
+ savingsUsd: number;
57
+ /** 0-100. */
58
+ savingsPercent: number;
59
+ /** Plain-English rationale tying archetype + perf score. */
60
+ reason: string;
61
+ }
62
+ /**
63
+ * Derived axis-health tri-state for the three Glass-Box dots
64
+ * (input-ratio · cache · fallback). Renderer reads; transformer computes.
65
+ *
66
+ * Thresholds (locked in design contract Phase 0):
67
+ * - inputRatio: green ≤ 0.65 · yellow 0.65–0.85 · red > 0.85
68
+ * - cache (only when historyCacheableTokens > 1000):
69
+ * green if inputCacheHitRatio ≥ 0.5
70
+ * yellow if 0.1 ≤ inputCacheHitRatio < 0.5
71
+ * red if inputCacheHitRatio < 0.1
72
+ * na if historyCacheableTokens ≤ 1000
73
+ * - fallback: red iff fellOverFrom !== undefined && fellOverFrom !== target
74
+ */
75
+ interface TraceHealth {
76
+ inputRatioStatus: 'green' | 'yellow' | 'red';
77
+ cacheStatus: 'green' | 'yellow' | 'red' | 'na';
78
+ fallbackStatus: 'green' | 'red';
79
+ }
80
+ /**
81
+ * alpha.29+ — wire-boundary representation of a translator section-rewrite.
82
+ *
83
+ * Distinct from the package-internal `SectionRewrite` type in `ir.ts`: this
84
+ * shape drops `originalText` + `transformedText` because those may carry
85
+ * consumer PII. The renderer shows the `rule` + `summary` only. Full text
86
+ * stays on `compile_outcomes.section_rewrites_applied` (Supabase row), gated
87
+ * by RLS for brain-side cross-app learning.
88
+ */
89
+ interface TraceSectionRewrite {
90
+ /** Stable id of the rewritten section. */
91
+ sectionId: string;
92
+ /** Section-kind discriminator that triggered the rewrite. */
93
+ kind: SectionKind;
94
+ /** Stable rule identifier (e.g. `'sequential-tool-cliff-below-floor'`). */
95
+ rule: string;
96
+ /**
97
+ * Plain-English one-liner describing what fired and why. Renderer surfaces
98
+ * this on the Coaching card; no internal jargon ("L-040", "below floor").
99
+ */
100
+ summary: string;
101
+ }
102
+ interface TraceDetail extends TraceSummary {
103
+ mutationsApplied: string[];
104
+ advisories: AdvisoryRecord[];
105
+ rawRequest?: string;
106
+ rawResponse?: string;
107
+ /** Set when consumer passed a forceModel / fallback fired. */
108
+ requestedModel?: string;
109
+ /** Provider finish reason — 'stop' / 'max_tokens' / 'tool_use' / etc. */
110
+ finishReason?: string;
111
+ /** Time to first token (ms); populated when provider surfaces it. */
112
+ ttftMs?: number;
113
+ /** End-to-end wall-clock (ms); from migration 018. */
114
+ totalMs?: number;
115
+ /** Tools kept after relevance pass. */
116
+ toolsCount?: number;
117
+ /** Number of history messages at compile time. */
118
+ historyDepth?: number;
119
+ /** Rendered system prompt size in characters. */
120
+ systemPromptChars?: number;
121
+ cacheReadInputTokens: number;
122
+ cacheCreationInputTokens: number;
123
+ historyCacheableTokens: number;
124
+ /** Derived: cacheReadInputTokens / max(tokensIn, 1). 0-1. */
125
+ inputCacheHitRatio: number;
126
+ fellOverFrom?: string;
127
+ fallbackReason?: FallbackReason;
128
+ /** Up to 2 alternatives. Empty array (not undefined) when none qualify. */
129
+ counterfactuals?: TraceCounterfactual[];
130
+ /** Undefined when 7d volume < 5/day (insufficient data). */
131
+ projectedDailyCostUsd?: number;
132
+ /**
133
+ * alpha.29+ — translator activity for this trace. Empty array (not
134
+ * undefined) when no rewrites fired or pre-019 row. Surfaced in the
135
+ * Glass-Box Coaching card as synthetic info-level rows. PII-safe by
136
+ * construction: only sectionId + kind + rule + summary cross the wire.
137
+ */
138
+ sectionRewritesApplied: TraceSectionRewrite[];
139
+ health: TraceHealth;
140
+ }
141
+
142
+ 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 { t as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, n as CallAttempt } from './ir-DeYMLWge.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.9",
4
- "description": "Prompt compiler + central learning brain for multi-model AI apps. Swap models without rewriting prompts.",
3
+ "version": "2.0.0-alpha.90",
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,13 +20,47 @@
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",
63
+ "test:stress": "node scripts/stress-test.mjs",
30
64
  "typecheck": "tsc --noEmit",
31
65
  "prepublishOnly": "npm run typecheck && npm run test && npm run build"
32
66
  },
@@ -40,20 +74,39 @@
40
74
  "gemini",
41
75
  "deepseek",
42
76
  "prompt-cache",
43
- "self-improving"
77
+ "model-fallback"
44
78
  ],
45
79
  "license": "MIT",
46
- "dependencies": {},
80
+ "repository": {
81
+ "type": "git",
82
+ "url": "git+https://github.com/stue/kgauto.git",
83
+ "directory": "v2"
84
+ },
85
+ "homepage": "https://github.com/stue/kgauto/tree/main/v2#readme",
47
86
  "peerDependencies": {
48
- "js-tiktoken": ">=1.0.0"
87
+ "js-tiktoken": ">=1.0.0",
88
+ "react": ">=18.0.0",
89
+ "react-dom": ">=18.0.0"
49
90
  },
50
91
  "peerDependenciesMeta": {
51
- "js-tiktoken": { "optional": true }
92
+ "js-tiktoken": {
93
+ "optional": true
94
+ },
95
+ "react": {
96
+ "optional": true
97
+ },
98
+ "react-dom": {
99
+ "optional": true
100
+ }
52
101
  },
53
102
  "devDependencies": {
54
103
  "@types/node": "^22.10.0",
104
+ "@types/react": "^19.2.15",
105
+ "@types/react-dom": "^19.2.3",
106
+ "react": "^19.2.6",
107
+ "react-dom": "^19.2.6",
55
108
  "tsup": "^8.4.0",
56
109
  "typescript": "^5.7.0",
57
110
  "vitest": "^3.1.0"
58
111
  }
59
- }
112
+ }