@warmdrift/kgauto-compiler 2.0.0-alpha.17 → 2.0.0-alpha.18

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,19 @@
1
+ import {
2
+ getPubSub
3
+ } from "./chunk-NUTC7NUC.mjs";
4
+
5
+ // src/glassbox/subscribe.ts
6
+ function subscribe(traceId) {
7
+ if (!traceId) {
8
+ return new ReadableStream({
9
+ start(controller) {
10
+ controller.close();
11
+ }
12
+ });
13
+ }
14
+ return getPubSub().subscribe(traceId);
15
+ }
16
+
17
+ export {
18
+ subscribe
19
+ };
@@ -1,125 +1,8 @@
1
- import { j as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, g as CallAttempt } from '../ir-C3P4gDt0.mjs';
1
+ import { G as GlassboxEvent } from '../types-DWF6mPGg.mjs';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-DWF6mPGg.mjs';
3
+ import '../ir-C3P4gDt0.mjs';
2
4
  import '../dialect.mjs';
3
5
 
4
- /**
5
- * Glass-Box observability types (alpha.17).
6
- *
7
- * The substrate for kgauto's in-flight observability surface — a Chrome MV3
8
- * side panel that renders compile + execute + advisor outputs in real-time.
9
- * See design doc:
10
- * ~/.gstack/projects/stue-kgauto/stgreen-claude-serene-williamson-51a105-design-20260518-175356.md
11
- *
12
- * Wire shape is intentionally minimal:
13
- * { kind, at, data } — discriminated union by `kind`.
14
- *
15
- * Critical-path safety (L-086 derived): emit MUST NEVER fail the user's
16
- * `call()` invocation. emit.ts wraps every adapter write in try/catch +
17
- * silently drops on error. Consumers in Vercel Edge runtimes can lose one
18
- * event without losing the response.
19
- */
20
-
21
- /**
22
- * Discriminator. Six event kinds cover the v1 substrate. New kinds added
23
- * additively; the side-panel renderer treats unknown kinds as "ignore".
24
- */
25
- type GlassboxEventKind = 'compile.start' | 'compile.done' | 'execute.attempt' | 'execute.success' | 'advisory.fired' | 'fallback.walked';
26
- /**
27
- * Wire envelope. Every emit lands as one of these.
28
- *
29
- * - kind: discriminator
30
- * - at: unix milliseconds (Date.now())
31
- * - data: kind-specific payload
32
- *
33
- * `data` typed loosely as Record<string, unknown> for serialization-friendliness;
34
- * the per-kind builders below populate it with the structured shape expected
35
- * by the renderer. We deliberately do NOT typescript-narrow `data` by kind on
36
- * the wire type — the side panel reads JSON from SSE and only the renderer
37
- * needs the narrowed shape. Internal callers (emit.ts) get type assistance via
38
- * the typed factory helpers in emit.ts.
39
- */
40
- interface GlassboxEvent {
41
- kind: GlassboxEventKind;
42
- at: number;
43
- data: Record<string, unknown>;
44
- }
45
- /**
46
- * Per-kind data shapes. Surfaced as type aids; not enforced at the
47
- * GlassboxEvent boundary (intentionally — see comment above).
48
- */
49
- interface CompileStartData {
50
- appId: string;
51
- archetype: string;
52
- models: string[];
53
- }
54
- interface CompileDoneData {
55
- target: string;
56
- provider: string;
57
- fallbackChain: string[];
58
- tokensIn: number;
59
- estimatedCostUsd: number;
60
- mutationsApplied: MutationApplied[];
61
- advisories: BestPracticeAdvisory[];
62
- }
63
- interface ExecuteAttemptData {
64
- model: string;
65
- attemptIndex: number;
66
- }
67
- interface ExecuteSuccessData {
68
- model: string;
69
- tokensIn: number;
70
- tokensOut: number;
71
- latencyMs: number;
72
- }
73
- interface AdvisoryFiredData {
74
- code: string;
75
- message: string;
76
- }
77
- interface FallbackWalkedData {
78
- from: string;
79
- to: string;
80
- reason: FallbackReason | 'unknown';
81
- attempt: CallAttempt;
82
- }
83
- /**
84
- * Pub/sub backend interface. Two adapters implement it: in-memory (dev /
85
- * single-process) and Upstash Redis Streams (Vercel Edge multi-instance).
86
- *
87
- * The choice is made at module load (NOT per-call) based on env-var presence:
88
- * if (UPSTASH_REDIS_URL && UPSTASH_REDIS_TOKEN) → Upstash
89
- * else → in-memory
90
- *
91
- * Stream TTL: 60s after last event. After that, subscriber stream closes
92
- * cleanly. The adapter owns its own TTL clock; subscribe() is agnostic.
93
- */
94
- interface GlassboxPubSub {
95
- /**
96
- * Publish a single event for a traceId. Returns a promise that resolves
97
- * after the event is durably appended (or rejects on adapter failure —
98
- * callers in emit.ts always swallow rejections).
99
- */
100
- publish(traceId: string, event: GlassboxEvent): Promise<void>;
101
- /**
102
- * Subscribe to events for a traceId. Returns a ReadableStream that emits
103
- * GlassboxEvent objects as they're published. The stream closes cleanly
104
- * after the per-trace TTL elapses since the LAST event (rolling 60s).
105
- *
106
- * If the traceId has no publisher within 60s of subscription, the stream
107
- * closes empty.
108
- */
109
- subscribe(traceId: string): ReadableStream<GlassboxEvent>;
110
- /**
111
- * Test-only escape hatch. Clears any in-memory state. Upstash adapter
112
- * no-ops (server-side state isn't accessible from here). Tests reach for
113
- * this between cases to keep adapters hermetic.
114
- */
115
- _reset?(): void;
116
- }
117
- /**
118
- * TTL applied to a stream after each event. The design doc names 60s; this
119
- * constant centralizes it so both adapters + tests agree.
120
- */
121
- declare const GLASSBOX_STREAM_TTL_MS = 60000;
122
-
123
6
  /**
124
7
  * subscribe(traceId) — public Glass-Box subscription export.
125
8
  *
@@ -156,4 +39,4 @@ declare const GLASSBOX_STREAM_TTL_MS = 60000;
156
39
  */
157
40
  declare function subscribe(traceId: string): ReadableStream<GlassboxEvent>;
158
41
 
159
- export { type AdvisoryFiredData, type CompileDoneData, type CompileStartData, type ExecuteAttemptData, type ExecuteSuccessData, type FallbackWalkedData, GLASSBOX_STREAM_TTL_MS, type GlassboxEvent, type GlassboxEventKind, type GlassboxPubSub, subscribe };
42
+ export { GlassboxEvent, subscribe };
@@ -1,125 +1,8 @@
1
- import { j as MutationApplied, B as BestPracticeAdvisory, F as FallbackReason, g as CallAttempt } from '../ir-CFHU3BUT.js';
1
+ import { G as GlassboxEvent } from '../types-xeklorHU.js';
2
+ export { A as AdvisoryFiredData, C as CompileDoneData, a as CompileStartData, E as ExecuteAttemptData, b as ExecuteSuccessData, F as FallbackWalkedData, c as GLASSBOX_STREAM_TTL_MS, d as GlassboxEventKind, e as GlassboxPubSub } from '../types-xeklorHU.js';
3
+ import '../ir-CFHU3BUT.js';
2
4
  import '../dialect.js';
3
5
 
4
- /**
5
- * Glass-Box observability types (alpha.17).
6
- *
7
- * The substrate for kgauto's in-flight observability surface — a Chrome MV3
8
- * side panel that renders compile + execute + advisor outputs in real-time.
9
- * See design doc:
10
- * ~/.gstack/projects/stue-kgauto/stgreen-claude-serene-williamson-51a105-design-20260518-175356.md
11
- *
12
- * Wire shape is intentionally minimal:
13
- * { kind, at, data } — discriminated union by `kind`.
14
- *
15
- * Critical-path safety (L-086 derived): emit MUST NEVER fail the user's
16
- * `call()` invocation. emit.ts wraps every adapter write in try/catch +
17
- * silently drops on error. Consumers in Vercel Edge runtimes can lose one
18
- * event without losing the response.
19
- */
20
-
21
- /**
22
- * Discriminator. Six event kinds cover the v1 substrate. New kinds added
23
- * additively; the side-panel renderer treats unknown kinds as "ignore".
24
- */
25
- type GlassboxEventKind = 'compile.start' | 'compile.done' | 'execute.attempt' | 'execute.success' | 'advisory.fired' | 'fallback.walked';
26
- /**
27
- * Wire envelope. Every emit lands as one of these.
28
- *
29
- * - kind: discriminator
30
- * - at: unix milliseconds (Date.now())
31
- * - data: kind-specific payload
32
- *
33
- * `data` typed loosely as Record<string, unknown> for serialization-friendliness;
34
- * the per-kind builders below populate it with the structured shape expected
35
- * by the renderer. We deliberately do NOT typescript-narrow `data` by kind on
36
- * the wire type — the side panel reads JSON from SSE and only the renderer
37
- * needs the narrowed shape. Internal callers (emit.ts) get type assistance via
38
- * the typed factory helpers in emit.ts.
39
- */
40
- interface GlassboxEvent {
41
- kind: GlassboxEventKind;
42
- at: number;
43
- data: Record<string, unknown>;
44
- }
45
- /**
46
- * Per-kind data shapes. Surfaced as type aids; not enforced at the
47
- * GlassboxEvent boundary (intentionally — see comment above).
48
- */
49
- interface CompileStartData {
50
- appId: string;
51
- archetype: string;
52
- models: string[];
53
- }
54
- interface CompileDoneData {
55
- target: string;
56
- provider: string;
57
- fallbackChain: string[];
58
- tokensIn: number;
59
- estimatedCostUsd: number;
60
- mutationsApplied: MutationApplied[];
61
- advisories: BestPracticeAdvisory[];
62
- }
63
- interface ExecuteAttemptData {
64
- model: string;
65
- attemptIndex: number;
66
- }
67
- interface ExecuteSuccessData {
68
- model: string;
69
- tokensIn: number;
70
- tokensOut: number;
71
- latencyMs: number;
72
- }
73
- interface AdvisoryFiredData {
74
- code: string;
75
- message: string;
76
- }
77
- interface FallbackWalkedData {
78
- from: string;
79
- to: string;
80
- reason: FallbackReason | 'unknown';
81
- attempt: CallAttempt;
82
- }
83
- /**
84
- * Pub/sub backend interface. Two adapters implement it: in-memory (dev /
85
- * single-process) and Upstash Redis Streams (Vercel Edge multi-instance).
86
- *
87
- * The choice is made at module load (NOT per-call) based on env-var presence:
88
- * if (UPSTASH_REDIS_URL && UPSTASH_REDIS_TOKEN) → Upstash
89
- * else → in-memory
90
- *
91
- * Stream TTL: 60s after last event. After that, subscriber stream closes
92
- * cleanly. The adapter owns its own TTL clock; subscribe() is agnostic.
93
- */
94
- interface GlassboxPubSub {
95
- /**
96
- * Publish a single event for a traceId. Returns a promise that resolves
97
- * after the event is durably appended (or rejects on adapter failure —
98
- * callers in emit.ts always swallow rejections).
99
- */
100
- publish(traceId: string, event: GlassboxEvent): Promise<void>;
101
- /**
102
- * Subscribe to events for a traceId. Returns a ReadableStream that emits
103
- * GlassboxEvent objects as they're published. The stream closes cleanly
104
- * after the per-trace TTL elapses since the LAST event (rolling 60s).
105
- *
106
- * If the traceId has no publisher within 60s of subscription, the stream
107
- * closes empty.
108
- */
109
- subscribe(traceId: string): ReadableStream<GlassboxEvent>;
110
- /**
111
- * Test-only escape hatch. Clears any in-memory state. Upstash adapter
112
- * no-ops (server-side state isn't accessible from here). Tests reach for
113
- * this between cases to keep adapters hermetic.
114
- */
115
- _reset?(): void;
116
- }
117
- /**
118
- * TTL applied to a stream after each event. The design doc names 60s; this
119
- * constant centralizes it so both adapters + tests agree.
120
- */
121
- declare const GLASSBOX_STREAM_TTL_MS = 60000;
122
-
123
6
  /**
124
7
  * subscribe(traceId) — public Glass-Box subscription export.
125
8
  *
@@ -156,4 +39,4 @@ declare const GLASSBOX_STREAM_TTL_MS = 60000;
156
39
  */
157
40
  declare function subscribe(traceId: string): ReadableStream<GlassboxEvent>;
158
41
 
159
- export { type AdvisoryFiredData, type CompileDoneData, type CompileStartData, type ExecuteAttemptData, type ExecuteSuccessData, type FallbackWalkedData, GLASSBOX_STREAM_TTL_MS, type GlassboxEvent, type GlassboxEventKind, type GlassboxPubSub, subscribe };
42
+ export { GlassboxEvent, subscribe };
@@ -1,19 +1,9 @@
1
1
  import {
2
- GLASSBOX_STREAM_TTL_MS,
3
- getPubSub
2
+ subscribe
3
+ } from "../chunk-VZGMWKRT.mjs";
4
+ import {
5
+ GLASSBOX_STREAM_TTL_MS
4
6
  } from "../chunk-NUTC7NUC.mjs";
5
-
6
- // src/glassbox/subscribe.ts
7
- function subscribe(traceId) {
8
- if (!traceId) {
9
- return new ReadableStream({
10
- start(controller) {
11
- controller.close();
12
- }
13
- });
14
- }
15
- return getPubSub().subscribe(traceId);
16
- }
17
7
  export {
18
8
  GLASSBOX_STREAM_TTL_MS,
19
9
  subscribe
@@ -0,0 +1,73 @@
1
+ import { G as GlassboxEvent } from '../types-DWF6mPGg.mjs';
2
+ import '../ir-C3P4gDt0.mjs';
3
+ import '../dialect.mjs';
4
+
5
+ /**
6
+ * Public entry point for `@warmdrift/kgauto-compiler/glassbox-routes`.
7
+ *
8
+ * One factory call from a Vercel Edge consumer route handler gets you both
9
+ * the replay-query (`proxy`) and live-SSE (`stream`) endpoints that the
10
+ * Glass-Box Chrome panel reads. Wiring is ~6 lines per app:
11
+ *
12
+ * // app/api/glassbox/proxy/route.ts
13
+ * import { createGlassboxRoutes } from '@warmdrift/kgauto-compiler/glassbox-routes';
14
+ * const { proxy } = createGlassboxRoutes({
15
+ * installToken: process.env.GLASSBOX_INSTALL_TOKEN!,
16
+ * extensionId: process.env.GLASSBOX_EXTENSION_ID!,
17
+ * brainEndpoint: process.env.GLASSBOX_BRAIN_ENDPOINT!,
18
+ * brainJwt: process.env.GLASSBOX_BRAIN_JWT!,
19
+ * appId: 'playbacksam',
20
+ * });
21
+ * export { proxy as GET };
22
+ *
23
+ * Auth model (defense in depth):
24
+ * - Bearer install token → primary, constant-time compared
25
+ * - chrome-extension Origin → secondary CSRF gate
26
+ *
27
+ * Scrub: optional sanitization runs at the proxy boundary before events or
28
+ * rows leave the consumer's infrastructure. Per pii-scrubber-call-site-not-
29
+ * package: kgauto stays naive to PII policy; consumers pass scrub hooks
30
+ * that encode their own data-handling rules.
31
+ *
32
+ * Brain reads use the scoped JWT minted via migration 013. RLS enforces
33
+ * `app_id = jwt.claim.app_id`; the proxy filter is belt-and-suspenders for
34
+ * payload size + log legibility.
35
+ */
36
+
37
+ interface GlassboxRoutesConfig {
38
+ /** Bearer token validated on every request via constant-time compare. Required. */
39
+ installToken: string;
40
+ /** chrome-extension://<id> — exact match required on Origin header. Required. */
41
+ extensionId: string;
42
+ /** Brain endpoint base (e.g. https://kgauto-brain.supabase.co). Used by `proxy` for replay queries. */
43
+ brainEndpoint: string;
44
+ /** Scoped JWT for brain reads. Use the per-consumer JWT minted via migration 013 (claim: app_id). */
45
+ brainJwt: string;
46
+ /** App scope filter — must match the JWT's app_id claim. */
47
+ appId: string;
48
+ /**
49
+ * Optional sanitization hook. Called with each event/trace BEFORE it leaves the consumer.
50
+ * Default: identity (no scrub). PII policy lives at the call-site, not in the package.
51
+ */
52
+ scrub?: (event: GlassboxEvent | Record<string, unknown>) => GlassboxEvent | Record<string, unknown>;
53
+ /**
54
+ * Test-only seam: override the brain fetch implementation. Production
55
+ * code never sets this; tests use it to mock PostgREST responses.
56
+ */
57
+ fetch?: typeof fetch;
58
+ /**
59
+ * Test-only seam: override the live-stream subscriber. Production code
60
+ * resolves to the alpha.17 `subscribe()` export; tests inject a fake
61
+ * source ReadableStream<GlassboxEvent>.
62
+ */
63
+ subscribe?: (traceId: string) => ReadableStream<GlassboxEvent>;
64
+ }
65
+ interface GlassboxRoutes {
66
+ /** GET /api/glassbox/proxy?traceId=<id> OR ?limit=20 (recent traces) */
67
+ proxy: (req: Request) => Promise<Response>;
68
+ /** GET /api/glassbox/stream?traceId=<id> (SSE) */
69
+ stream: (req: Request) => Promise<Response>;
70
+ }
71
+ declare function createGlassboxRoutes(config: GlassboxRoutesConfig): GlassboxRoutes;
72
+
73
+ export { type GlassboxRoutes, type GlassboxRoutesConfig, createGlassboxRoutes };
@@ -0,0 +1,73 @@
1
+ import { G as GlassboxEvent } from '../types-xeklorHU.js';
2
+ import '../ir-CFHU3BUT.js';
3
+ import '../dialect.js';
4
+
5
+ /**
6
+ * Public entry point for `@warmdrift/kgauto-compiler/glassbox-routes`.
7
+ *
8
+ * One factory call from a Vercel Edge consumer route handler gets you both
9
+ * the replay-query (`proxy`) and live-SSE (`stream`) endpoints that the
10
+ * Glass-Box Chrome panel reads. Wiring is ~6 lines per app:
11
+ *
12
+ * // app/api/glassbox/proxy/route.ts
13
+ * import { createGlassboxRoutes } from '@warmdrift/kgauto-compiler/glassbox-routes';
14
+ * const { proxy } = createGlassboxRoutes({
15
+ * installToken: process.env.GLASSBOX_INSTALL_TOKEN!,
16
+ * extensionId: process.env.GLASSBOX_EXTENSION_ID!,
17
+ * brainEndpoint: process.env.GLASSBOX_BRAIN_ENDPOINT!,
18
+ * brainJwt: process.env.GLASSBOX_BRAIN_JWT!,
19
+ * appId: 'playbacksam',
20
+ * });
21
+ * export { proxy as GET };
22
+ *
23
+ * Auth model (defense in depth):
24
+ * - Bearer install token → primary, constant-time compared
25
+ * - chrome-extension Origin → secondary CSRF gate
26
+ *
27
+ * Scrub: optional sanitization runs at the proxy boundary before events or
28
+ * rows leave the consumer's infrastructure. Per pii-scrubber-call-site-not-
29
+ * package: kgauto stays naive to PII policy; consumers pass scrub hooks
30
+ * that encode their own data-handling rules.
31
+ *
32
+ * Brain reads use the scoped JWT minted via migration 013. RLS enforces
33
+ * `app_id = jwt.claim.app_id`; the proxy filter is belt-and-suspenders for
34
+ * payload size + log legibility.
35
+ */
36
+
37
+ interface GlassboxRoutesConfig {
38
+ /** Bearer token validated on every request via constant-time compare. Required. */
39
+ installToken: string;
40
+ /** chrome-extension://<id> — exact match required on Origin header. Required. */
41
+ extensionId: string;
42
+ /** Brain endpoint base (e.g. https://kgauto-brain.supabase.co). Used by `proxy` for replay queries. */
43
+ brainEndpoint: string;
44
+ /** Scoped JWT for brain reads. Use the per-consumer JWT minted via migration 013 (claim: app_id). */
45
+ brainJwt: string;
46
+ /** App scope filter — must match the JWT's app_id claim. */
47
+ appId: string;
48
+ /**
49
+ * Optional sanitization hook. Called with each event/trace BEFORE it leaves the consumer.
50
+ * Default: identity (no scrub). PII policy lives at the call-site, not in the package.
51
+ */
52
+ scrub?: (event: GlassboxEvent | Record<string, unknown>) => GlassboxEvent | Record<string, unknown>;
53
+ /**
54
+ * Test-only seam: override the brain fetch implementation. Production
55
+ * code never sets this; tests use it to mock PostgREST responses.
56
+ */
57
+ fetch?: typeof fetch;
58
+ /**
59
+ * Test-only seam: override the live-stream subscriber. Production code
60
+ * resolves to the alpha.17 `subscribe()` export; tests inject a fake
61
+ * source ReadableStream<GlassboxEvent>.
62
+ */
63
+ subscribe?: (traceId: string) => ReadableStream<GlassboxEvent>;
64
+ }
65
+ interface GlassboxRoutes {
66
+ /** GET /api/glassbox/proxy?traceId=<id> OR ?limit=20 (recent traces) */
67
+ proxy: (req: Request) => Promise<Response>;
68
+ /** GET /api/glassbox/stream?traceId=<id> (SSE) */
69
+ stream: (req: Request) => Promise<Response>;
70
+ }
71
+ declare function createGlassboxRoutes(config: GlassboxRoutesConfig): GlassboxRoutes;
72
+
73
+ export { type GlassboxRoutes, type GlassboxRoutesConfig, createGlassboxRoutes };