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

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,300 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/glassbox/index.ts
21
+ var glassbox_exports = {};
22
+ __export(glassbox_exports, {
23
+ GLASSBOX_STREAM_TTL_MS: () => GLASSBOX_STREAM_TTL_MS,
24
+ subscribe: () => subscribe
25
+ });
26
+ module.exports = __toCommonJS(glassbox_exports);
27
+
28
+ // src/glassbox/types.ts
29
+ var GLASSBOX_STREAM_TTL_MS = 6e4;
30
+
31
+ // src/glassbox/pubsub-memory.ts
32
+ var MemoryPubSub = class {
33
+ subscribers = /* @__PURE__ */ new Map();
34
+ async publish(traceId, event) {
35
+ const subs = this.subscribers.get(traceId);
36
+ if (!subs || subs.size === 0) return;
37
+ for (const sub of subs) {
38
+ if (sub.closed) continue;
39
+ try {
40
+ sub.controller.enqueue(event);
41
+ } catch {
42
+ sub.closed = true;
43
+ continue;
44
+ }
45
+ this.refreshTtl(traceId, sub);
46
+ }
47
+ }
48
+ subscribe(traceId) {
49
+ const self = this;
50
+ let sub;
51
+ return new ReadableStream({
52
+ start(controller) {
53
+ sub = {
54
+ controller,
55
+ ttlTimer: setTimeout(() => {
56
+ self.closeSubscriber(traceId, sub);
57
+ }, GLASSBOX_STREAM_TTL_MS),
58
+ closed: false
59
+ };
60
+ let set = self.subscribers.get(traceId);
61
+ if (!set) {
62
+ set = /* @__PURE__ */ new Set();
63
+ self.subscribers.set(traceId, set);
64
+ }
65
+ set.add(sub);
66
+ },
67
+ cancel() {
68
+ if (sub) self.removeSubscriber(traceId, sub);
69
+ }
70
+ });
71
+ }
72
+ /**
73
+ * Refresh the rolling TTL for a subscriber after an event lands. Replaces
74
+ * the existing timer with a fresh 60s one.
75
+ */
76
+ refreshTtl(traceId, sub) {
77
+ clearTimeout(sub.ttlTimer);
78
+ sub.ttlTimer = setTimeout(() => {
79
+ this.closeSubscriber(traceId, sub);
80
+ }, GLASSBOX_STREAM_TTL_MS);
81
+ }
82
+ /**
83
+ * Close the subscriber's stream cleanly and remove from the fan-out set.
84
+ * Idempotent — safe to call multiple times.
85
+ */
86
+ closeSubscriber(traceId, sub) {
87
+ if (sub.closed) return;
88
+ sub.closed = true;
89
+ clearTimeout(sub.ttlTimer);
90
+ try {
91
+ sub.controller.close();
92
+ } catch {
93
+ }
94
+ this.removeSubscriber(traceId, sub);
95
+ }
96
+ removeSubscriber(traceId, sub) {
97
+ clearTimeout(sub.ttlTimer);
98
+ const set = this.subscribers.get(traceId);
99
+ if (!set) return;
100
+ set.delete(sub);
101
+ if (set.size === 0) this.subscribers.delete(traceId);
102
+ }
103
+ /**
104
+ * Test-only reset. Tears down all subscribers, clears all state. Calling
105
+ * outside of tests is harmless but cancels every active stream.
106
+ */
107
+ _reset() {
108
+ for (const [, set] of this.subscribers) {
109
+ for (const sub of set) {
110
+ this.closeSubscriber("", sub);
111
+ }
112
+ }
113
+ this.subscribers.clear();
114
+ }
115
+ };
116
+
117
+ // src/glassbox/pubsub-upstash.ts
118
+ var UpstashPubSub = class {
119
+ url;
120
+ token;
121
+ fetchImpl;
122
+ blockMs;
123
+ maxLen;
124
+ constructor(cfg) {
125
+ this.url = cfg.url.replace(/\/$/, "");
126
+ this.token = cfg.token;
127
+ this.fetchImpl = cfg.fetchImpl ?? globalThis.fetch.bind(globalThis);
128
+ this.blockMs = cfg.blockMs ?? 100;
129
+ this.maxLen = cfg.maxLen ?? 100;
130
+ }
131
+ async publish(traceId, event) {
132
+ const key = streamKey(traceId);
133
+ const payload = JSON.stringify(event);
134
+ await this.cmd([
135
+ "XADD",
136
+ key,
137
+ "MAXLEN",
138
+ "~",
139
+ String(this.maxLen),
140
+ "*",
141
+ "event",
142
+ payload
143
+ ]);
144
+ await this.cmd(["EXPIRE", key, String(Math.ceil(GLASSBOX_STREAM_TTL_MS / 1e3))]);
145
+ }
146
+ subscribe(traceId) {
147
+ const key = streamKey(traceId);
148
+ const self = this;
149
+ let cursor = "$";
150
+ let cancelled = false;
151
+ let ttlDeadline = Date.now() + GLASSBOX_STREAM_TTL_MS;
152
+ return new ReadableStream({
153
+ async start(controller) {
154
+ try {
155
+ while (!cancelled && Date.now() < ttlDeadline) {
156
+ const resp = await self.cmd([
157
+ "XREAD",
158
+ "BLOCK",
159
+ String(self.blockMs),
160
+ "STREAMS",
161
+ key,
162
+ cursor
163
+ ]);
164
+ if (cancelled) break;
165
+ const parsed = parseXReadResult(resp.result);
166
+ if (parsed.entries.length === 0) {
167
+ continue;
168
+ }
169
+ for (const entry of parsed.entries) {
170
+ const evt = decodeEvent(entry.fields);
171
+ if (evt) {
172
+ try {
173
+ controller.enqueue(evt);
174
+ } catch {
175
+ cancelled = true;
176
+ break;
177
+ }
178
+ }
179
+ cursor = entry.id;
180
+ }
181
+ ttlDeadline = Date.now() + GLASSBOX_STREAM_TTL_MS;
182
+ }
183
+ } catch (err) {
184
+ if (!cancelled) {
185
+ try {
186
+ controller.error(err);
187
+ } catch {
188
+ }
189
+ return;
190
+ }
191
+ }
192
+ try {
193
+ controller.close();
194
+ } catch {
195
+ }
196
+ },
197
+ cancel() {
198
+ cancelled = true;
199
+ }
200
+ });
201
+ }
202
+ async cmd(args) {
203
+ const res = await this.fetchImpl(this.url, {
204
+ method: "POST",
205
+ headers: {
206
+ Authorization: `Bearer ${this.token}`,
207
+ "Content-Type": "application/json"
208
+ },
209
+ body: JSON.stringify(args)
210
+ });
211
+ if (!res.ok) {
212
+ throw new Error(`Upstash ${args[0]} failed: HTTP ${res.status}`);
213
+ }
214
+ const json = await res.json();
215
+ if (json.error) {
216
+ throw new Error(`Upstash ${args[0]} failed: ${json.error}`);
217
+ }
218
+ return json;
219
+ }
220
+ };
221
+ function streamKey(traceId) {
222
+ return `glassbox:trace:${traceId}`;
223
+ }
224
+ function decodeEvent(fields) {
225
+ const raw = fields["event"];
226
+ if (!raw) return void 0;
227
+ try {
228
+ const parsed = JSON.parse(raw);
229
+ if (typeof parsed.kind === "string" && typeof parsed.at === "number") {
230
+ return parsed;
231
+ }
232
+ return void 0;
233
+ } catch {
234
+ return void 0;
235
+ }
236
+ }
237
+ function parseXReadResult(raw) {
238
+ if (!Array.isArray(raw)) return { entries: [] };
239
+ const entries = [];
240
+ for (const stream of raw) {
241
+ if (!Array.isArray(stream) || stream.length < 2) continue;
242
+ const streamEntries = stream[1];
243
+ if (!Array.isArray(streamEntries)) continue;
244
+ for (const entry of streamEntries) {
245
+ if (!Array.isArray(entry) || entry.length < 2) continue;
246
+ const id = String(entry[0]);
247
+ const flat = entry[1];
248
+ if (!Array.isArray(flat)) continue;
249
+ const fields = {};
250
+ for (let i = 0; i < flat.length; i += 2) {
251
+ const k = flat[i];
252
+ const v = flat[i + 1];
253
+ if (typeof k === "string") fields[k] = String(v ?? "");
254
+ }
255
+ entries.push({ id, fields });
256
+ }
257
+ }
258
+ return { entries };
259
+ }
260
+
261
+ // src/glassbox/emit.ts
262
+ var activePubSub;
263
+ function getPubSub() {
264
+ if (activePubSub) return activePubSub;
265
+ const url = readEnv("UPSTASH_REDIS_URL");
266
+ const token = readEnv("UPSTASH_REDIS_TOKEN");
267
+ if (url && token) {
268
+ activePubSub = new UpstashPubSub({ url, token });
269
+ } else {
270
+ activePubSub = new MemoryPubSub();
271
+ }
272
+ return activePubSub;
273
+ }
274
+ function readEnv(key) {
275
+ try {
276
+ if (typeof process !== "undefined" && process.env) {
277
+ const v = process.env[key];
278
+ return v && v.trim() !== "" ? v : void 0;
279
+ }
280
+ } catch {
281
+ }
282
+ return void 0;
283
+ }
284
+
285
+ // src/glassbox/subscribe.ts
286
+ function subscribe(traceId) {
287
+ if (!traceId) {
288
+ return new ReadableStream({
289
+ start(controller) {
290
+ controller.close();
291
+ }
292
+ });
293
+ }
294
+ return getPubSub().subscribe(traceId);
295
+ }
296
+ // Annotate the CommonJS export names for ESM import in node:
297
+ 0 && (module.exports = {
298
+ GLASSBOX_STREAM_TTL_MS,
299
+ subscribe
300
+ });
@@ -0,0 +1,20 @@
1
+ import {
2
+ GLASSBOX_STREAM_TTL_MS,
3
+ getPubSub
4
+ } 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
+ export {
18
+ GLASSBOX_STREAM_TTL_MS,
19
+ subscribe
20
+ };
package/dist/index.d.mts CHANGED
@@ -1,5 +1,7 @@
1
- import { M as ModelProfile, C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory, f as Provider } from './profiles-BoLYdl7F.mjs';
2
- export { g as ALIASES, h as CacheStrategy, i as CallAttempt, j as CallError, k as CliffRule, l as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, L as LoweringSpec, m as Message, n as MutationApplied, o as NormalizedTokens, p as PromptSection, q as RecoveryRule, S as StructuredOutputCapability, r as SystemPromptMode, T as ToolCall, s as ToolDefinition, t as allProfiles, u as getProfile, v as profilesByProvider, w as tryGetProfile } from './profiles-BoLYdl7F.mjs';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory, f as Provider } from './ir-C3P4gDt0.mjs';
2
+ export { g as CallAttempt, h as CallError, i as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, j as MutationApplied, k as NormalizedTokens, l as PromptSection, T as ToolCall, m as ToolDefinition } from './ir-C3P4gDt0.mjs';
3
+ import { ModelProfile } from './profiles.mjs';
4
+ export { ALIASES, CacheStrategy, CliffRule, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, profilesByProvider, tryGetProfile } from './profiles.mjs';
3
5
  import { IntentArchetypeName } from './dialect.mjs';
4
6
  export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.mjs';
5
7
 
package/dist/index.d.ts CHANGED
@@ -1,5 +1,7 @@
1
- import { M as ModelProfile, C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory, f as Provider } from './profiles-CVB2_5C8.js';
2
- export { g as ALIASES, h as CacheStrategy, i as CallAttempt, j as CallError, k as CliffRule, l as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, L as LoweringSpec, m as Message, n as MutationApplied, o as NormalizedTokens, p as PromptSection, q as RecoveryRule, S as StructuredOutputCapability, r as SystemPromptMode, T as ToolCall, s as ToolDefinition, t as allProfiles, u as getProfile, v as profilesByProvider, w as tryGetProfile } from './profiles-CVB2_5C8.js';
1
+ import { C as CompilePolicy, N as NormalizedResponse, A as ApiKeys, P as ProviderOverrides, a as CompiledRequest, b as PromptIR, c as CallOptions, d as CallResult, R as RecordInput, O as OracleScore, e as CompileResult, B as BestPracticeAdvisory, f as Provider } from './ir-CFHU3BUT.js';
2
+ export { g as CallAttempt, h as CallError, i as Constraints, F as FallbackReason, H as HistoryCachePolicy, I as IntentDeclaration, M as Message, j as MutationApplied, k as NormalizedTokens, l as PromptSection, T as ToolCall, m as ToolDefinition } from './ir-CFHU3BUT.js';
3
+ import { ModelProfile } from './profiles.js';
4
+ export { ALIASES, CacheStrategy, CliffRule, LoweringSpec, RecoveryRule, StructuredOutputCapability, SystemPromptMode, allProfiles, getProfile, profilesByProvider, tryGetProfile } from './profiles.js';
3
5
  import { IntentArchetypeName } from './dialect.js';
4
6
  export { ALL_ARCHETYPES, ContextBucket, DIALECT_VERSION, HistoryDepth, INTENT_ARCHETYPES, OutputMode, ShapeSignature, ToolCountBucket, bucketContext, bucketHistory, bucketToolCount, hashShape, isArchetype, learningKey } from './dialect.js';
5
7