@withgateway/sdk 0.1.3

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 (40) hide show
  1. package/README.md +229 -0
  2. package/dist/context/index.d.mts +225 -0
  3. package/dist/context/index.d.ts +225 -0
  4. package/dist/context/index.js +440 -0
  5. package/dist/context/index.js.map +1 -0
  6. package/dist/context/index.mjs +411 -0
  7. package/dist/context/index.mjs.map +1 -0
  8. package/dist/experiments/index.d.mts +260 -0
  9. package/dist/experiments/index.d.ts +260 -0
  10. package/dist/experiments/index.js +407 -0
  11. package/dist/experiments/index.js.map +1 -0
  12. package/dist/experiments/index.mjs +374 -0
  13. package/dist/experiments/index.mjs.map +1 -0
  14. package/dist/index-Caw3XVub.d.mts +193 -0
  15. package/dist/index-Caw3XVub.d.ts +193 -0
  16. package/dist/index.d.mts +20 -0
  17. package/dist/index.d.ts +20 -0
  18. package/dist/index.js +1476 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/index.mjs +1434 -0
  21. package/dist/index.mjs.map +1 -0
  22. package/dist/memory/index.d.mts +124 -0
  23. package/dist/memory/index.d.ts +124 -0
  24. package/dist/memory/index.js +192 -0
  25. package/dist/memory/index.js.map +1 -0
  26. package/dist/memory/index.mjs +164 -0
  27. package/dist/memory/index.mjs.map +1 -0
  28. package/dist/security/index.d.mts +114 -0
  29. package/dist/security/index.d.ts +114 -0
  30. package/dist/security/index.js +297 -0
  31. package/dist/security/index.js.map +1 -0
  32. package/dist/security/index.mjs +275 -0
  33. package/dist/security/index.mjs.map +1 -0
  34. package/dist/tracing/index.d.mts +1 -0
  35. package/dist/tracing/index.d.ts +1 -0
  36. package/dist/tracing/index.js +226 -0
  37. package/dist/tracing/index.js.map +1 -0
  38. package/dist/tracing/index.mjs +202 -0
  39. package/dist/tracing/index.mjs.map +1 -0
  40. package/package.json +112 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1434 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
+ }) : x)(function(x) {
5
+ if (typeof require !== "undefined") return require.apply(this, arguments);
6
+ throw Error('Dynamic require of "' + x + '" is not supported');
7
+ });
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+
13
+ // src/experiments/assignment.ts
14
+ import { createHash } from "crypto";
15
+ function computeHash(experimentKey, userId) {
16
+ const raw = createHash("sha256").update(`${experimentKey}:${userId}`).digest("hex");
17
+ return parseInt(raw.slice(0, 8), 16) / 4294967296;
18
+ }
19
+ function assignVariant(config, userId) {
20
+ if (!config.variants || config.variants.length === 0) {
21
+ return null;
22
+ }
23
+ const bucket = computeHash(config.key, userId);
24
+ const trafficThreshold = config.trafficPercent / 100;
25
+ if (bucket >= trafficThreshold) {
26
+ return null;
27
+ }
28
+ const normalizedBucket = bucket / trafficThreshold;
29
+ const totalWeight = config.variants.reduce((sum, v) => sum + v.weight, 0);
30
+ if (totalWeight <= 0) {
31
+ return config.variants[0] ?? null;
32
+ }
33
+ let cumulative = 0;
34
+ for (const variant of config.variants) {
35
+ cumulative += variant.weight / totalWeight;
36
+ if (normalizedBucket < cumulative) {
37
+ return variant;
38
+ }
39
+ }
40
+ return config.variants[config.variants.length - 1] ?? null;
41
+ }
42
+
43
+ // src/experiments/context.ts
44
+ import { AsyncLocalStorage } from "async_hooks";
45
+ var experimentContextStorage = new AsyncLocalStorage();
46
+ function getExperimentContext() {
47
+ return experimentContextStorage.getStore();
48
+ }
49
+ function setExperimentContext(context2) {
50
+ experimentContextStorage.enterWith(context2);
51
+ }
52
+ function clearExperimentContext() {
53
+ experimentContextStorage.enterWith(void 0);
54
+ }
55
+ function runWithExperimentContext(context2, fn) {
56
+ return experimentContextStorage.run(context2, fn);
57
+ }
58
+
59
+ // src/experiments/exposure-logger.ts
60
+ var ExposureLogger = class {
61
+ buffer = [];
62
+ batchSize;
63
+ flushIntervalMs;
64
+ apiUrl;
65
+ apiKey;
66
+ secretKey;
67
+ flushTimer = null;
68
+ isFlushing = false;
69
+ constructor(config) {
70
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
71
+ this.apiKey = config.apiKey;
72
+ this.secretKey = config.secretKey ?? "";
73
+ this.batchSize = config.batchSize ?? 100;
74
+ this.flushIntervalMs = config.flushIntervalMs ?? 5e3;
75
+ this.flushTimer = setInterval(() => {
76
+ this.flush().catch((err) => {
77
+ console.error("[gateway] Exposure flush error:", err);
78
+ });
79
+ }, this.flushIntervalMs);
80
+ if (this.flushTimer.unref) {
81
+ this.flushTimer.unref();
82
+ }
83
+ }
84
+ log(exposure) {
85
+ this.buffer.push(exposure);
86
+ if (this.buffer.length >= this.batchSize) {
87
+ this.flush().catch((err) => {
88
+ console.error("[gateway] Exposure flush error:", err);
89
+ });
90
+ }
91
+ }
92
+ async flush() {
93
+ if (this.isFlushing || this.buffer.length === 0) {
94
+ return;
95
+ }
96
+ this.isFlushing = true;
97
+ const batch = this.buffer.splice(0, this.buffer.length);
98
+ try {
99
+ const authHeader = this.secretKey ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString("base64")}` : `Bearer ${this.apiKey}`;
100
+ const response = await fetch(
101
+ `${this.apiUrl}/api/public/experiments/exposures/batch`,
102
+ {
103
+ method: "POST",
104
+ headers: {
105
+ "Content-Type": "application/json",
106
+ Authorization: authHeader
107
+ },
108
+ body: JSON.stringify({
109
+ exposures: batch
110
+ })
111
+ }
112
+ );
113
+ if (!response.ok) {
114
+ this.buffer.unshift(...batch);
115
+ console.error(
116
+ `[gateway] Failed to log exposures: ${response.status} ${response.statusText}`
117
+ );
118
+ }
119
+ } catch (error) {
120
+ this.buffer.unshift(...batch);
121
+ console.error("[gateway] Network error logging exposures:", error);
122
+ } finally {
123
+ this.isFlushing = false;
124
+ }
125
+ }
126
+ async shutdown() {
127
+ if (this.flushTimer) {
128
+ clearInterval(this.flushTimer);
129
+ this.flushTimer = null;
130
+ }
131
+ await this.flush();
132
+ }
133
+ };
134
+
135
+ // src/experiments/client.ts
136
+ var ExperimentClient = class {
137
+ apiUrl;
138
+ apiKey;
139
+ secretKey;
140
+ projectId;
141
+ configs = /* @__PURE__ */ new Map();
142
+ exposureLogger;
143
+ constructor(config) {
144
+ this.apiUrl = config.apiUrl.replace(/\/$/, "");
145
+ this.apiKey = config.apiKey;
146
+ this.secretKey = config.secretKey ?? "";
147
+ this.projectId = config.projectId;
148
+ this.exposureLogger = new ExposureLogger({
149
+ apiUrl: this.apiUrl,
150
+ apiKey: this.apiKey,
151
+ secretKey: this.secretKey,
152
+ batchSize: config.exposureLogger?.batchSize,
153
+ flushIntervalMs: config.exposureLogger?.flushIntervalMs
154
+ });
155
+ }
156
+ async register(input) {
157
+ const config = {
158
+ key: input.key,
159
+ trafficPercent: input.trafficPercent ?? 100,
160
+ variants: input.variants.map((v) => ({
161
+ key: v.key,
162
+ weight: v.weight ?? 1,
163
+ config: v.config ?? {}
164
+ }))
165
+ };
166
+ this.configs.set(config.key, config);
167
+ const syncToBackend = input.syncToBackend ?? true;
168
+ if (syncToBackend) {
169
+ this.syncToBackendAsync(config, input.evaluatorNames).catch((err) => {
170
+ console.error(
171
+ `[gateway] Failed to sync experiment ${config.key}:`,
172
+ err
173
+ );
174
+ });
175
+ }
176
+ }
177
+ async fetch(experimentKeys) {
178
+ const url = new URL(`${this.apiUrl}/api/public/experiments`);
179
+ if (experimentKeys && experimentKeys.length > 0) {
180
+ url.searchParams.set("keys", experimentKeys.join(","));
181
+ }
182
+ const authHeader = this.secretKey ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString("base64")}` : `Bearer ${this.apiKey}`;
183
+ const response = await fetch(url.toString(), {
184
+ method: "GET",
185
+ headers: {
186
+ Authorization: authHeader
187
+ }
188
+ });
189
+ if (!response.ok) {
190
+ throw new Error(
191
+ `Failed to fetch experiments: ${response.status} ${response.statusText}`
192
+ );
193
+ }
194
+ const data = await response.json();
195
+ for (const config of data.experiments) {
196
+ this.configs.set(config.key, config);
197
+ }
198
+ }
199
+ async getVariant(experimentKey, userId, options) {
200
+ const fetchIfMissing = options?.fetchIfMissing ?? true;
201
+ let config = this.configs.get(experimentKey);
202
+ if (!config && fetchIfMissing) {
203
+ try {
204
+ await this.fetch([experimentKey]);
205
+ config = this.configs.get(experimentKey);
206
+ } catch (error) {
207
+ console.error(
208
+ `[gateway] Failed to fetch experiment ${experimentKey}:`,
209
+ error
210
+ );
211
+ }
212
+ }
213
+ if (!config) {
214
+ return {
215
+ variant: null,
216
+ inExperiment: false,
217
+ experimentKey,
218
+ run: (fn) => fn()
219
+ };
220
+ }
221
+ const variant = assignVariant(config, userId);
222
+ if (!variant) {
223
+ return {
224
+ variant: null,
225
+ inExperiment: false,
226
+ experimentKey,
227
+ run: (fn) => fn()
228
+ };
229
+ }
230
+ this.exposureLogger.log({
231
+ userId,
232
+ experimentId: experimentKey,
233
+ variantKey: variant.key,
234
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
235
+ });
236
+ const context2 = {
237
+ experimentId: experimentKey,
238
+ variantKey: variant.key,
239
+ userId
240
+ };
241
+ setExperimentContext(context2);
242
+ return {
243
+ variant,
244
+ inExperiment: true,
245
+ experimentKey,
246
+ run: (fn) => runWithExperimentContext(context2, fn)
247
+ };
248
+ }
249
+ getConfig(experimentKey) {
250
+ return this.configs.get(experimentKey);
251
+ }
252
+ async shutdown() {
253
+ await this.exposureLogger.shutdown();
254
+ }
255
+ async syncToBackendAsync(config, evaluatorNames) {
256
+ const authHeader = this.secretKey ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString("base64")}` : `Bearer ${this.apiKey}`;
257
+ const response = await fetch(`${this.apiUrl}/api/public/experiments`, {
258
+ method: "POST",
259
+ headers: {
260
+ "Content-Type": "application/json",
261
+ Authorization: authHeader
262
+ },
263
+ body: JSON.stringify({
264
+ key: config.key,
265
+ trafficPercent: config.trafficPercent,
266
+ variants: config.variants,
267
+ evaluatorNames: evaluatorNames ?? []
268
+ })
269
+ });
270
+ if (!response.ok) {
271
+ const text = await response.text();
272
+ throw new Error(
273
+ `Failed to sync experiment: ${response.status} ${response.statusText} - ${text}`
274
+ );
275
+ }
276
+ console.log(`[gateway] Synced experiment '${config.key}' to backend`);
277
+ }
278
+ };
279
+
280
+ // src/experiments/otel.ts
281
+ var EXPERIMENT_ATTRIBUTES = {
282
+ EXPERIMENT_ID: "gateway.experiment.id",
283
+ VARIANT_KEY: "gateway.variant.key",
284
+ USER_ID: "gateway.experiment.user_id"
285
+ };
286
+ var ExperimentSpanProcessor = class {
287
+ onStart(span, _parentContext) {
288
+ const ctx = getExperimentContext();
289
+ if (ctx) {
290
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, ctx.experimentId);
291
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, ctx.variantKey);
292
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, ctx.userId);
293
+ }
294
+ }
295
+ onEnd(_span) {
296
+ }
297
+ async shutdown() {
298
+ }
299
+ async forceFlush() {
300
+ }
301
+ };
302
+ function addExperimentAttributes(span, experimentId, variantKey, userId) {
303
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, experimentId);
304
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, variantKey);
305
+ span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, userId);
306
+ }
307
+
308
+ // src/experiments/singleton.ts
309
+ var singleton_exports = {};
310
+ __export(singleton_exports, {
311
+ clearExperimentContext: () => clearExperimentContext2,
312
+ fetch: () => fetch2,
313
+ getClient: () => getClient,
314
+ getVariant: () => getVariant,
315
+ init: () => init,
316
+ register: () => register,
317
+ shutdown: () => shutdown
318
+ });
319
+ var client = null;
320
+ function init(config) {
321
+ client = new ExperimentClient({
322
+ apiUrl: config.baseUrl,
323
+ apiKey: config.apiKey,
324
+ secretKey: config.secretKey,
325
+ projectId: config.projectId ?? ""
326
+ });
327
+ }
328
+ async function register(input) {
329
+ if (!client) {
330
+ throw new Error(
331
+ "Experiments not initialized. Call experiments.init() first."
332
+ );
333
+ }
334
+ return client.register(input);
335
+ }
336
+ async function getVariant(experimentKey, userId, options) {
337
+ if (!client) {
338
+ throw new Error(
339
+ "Experiments not initialized. Call experiments.init() first."
340
+ );
341
+ }
342
+ return client.getVariant(experimentKey, userId, options);
343
+ }
344
+ async function fetch2(experimentKeys) {
345
+ if (!client) {
346
+ throw new Error(
347
+ "Experiments not initialized. Call experiments.init() first."
348
+ );
349
+ }
350
+ return client.fetch(experimentKeys);
351
+ }
352
+ async function shutdown() {
353
+ if (client) {
354
+ await client.shutdown();
355
+ client = null;
356
+ }
357
+ clearExperimentContext();
358
+ }
359
+ function clearExperimentContext2() {
360
+ clearExperimentContext();
361
+ }
362
+ function getClient() {
363
+ return client;
364
+ }
365
+
366
+ // src/context/index.ts
367
+ var GatewayContextError = class extends Error {
368
+ constructor(message, options) {
369
+ super(message);
370
+ this.name = "GatewayContextError";
371
+ this.cause = options?.cause;
372
+ }
373
+ };
374
+ var GatewayContextConflictError = class extends GatewayContextError {
375
+ latestCommit;
376
+ constructor(message, latestCommit) {
377
+ super(message);
378
+ this.name = "GatewayContextConflictError";
379
+ this.latestCommit = latestCommit;
380
+ }
381
+ };
382
+ var GatewayContext = class _GatewayContext {
383
+ host;
384
+ publicKey;
385
+ secretKey;
386
+ debug;
387
+ constructor(config) {
388
+ this.host = config.host.replace(/\/$/, "");
389
+ this.publicKey = config.publicKey;
390
+ this.secretKey = config.secretKey;
391
+ this.debug = config.debug ?? false;
392
+ }
393
+ static fromEnv(config = {}) {
394
+ const host = config.host ?? process.env.GATEWAY_HOST ?? process.env.GATEWAY_HOST;
395
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY ?? process.env.GATEWAY_PUBLIC_KEY;
396
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY ?? process.env.GATEWAY_SECRET_KEY;
397
+ const missing = [
398
+ ["host", host],
399
+ ["publicKey", publicKey],
400
+ ["secretKey", secretKey]
401
+ ].filter(([, value]) => !value).map(([name]) => name);
402
+ if (missing.length > 0) {
403
+ throw new GatewayContextError(
404
+ `Missing Gateway context configuration: ${missing.join(", ")}`
405
+ );
406
+ }
407
+ return new _GatewayContext({
408
+ ...config,
409
+ host,
410
+ publicKey,
411
+ secretKey
412
+ });
413
+ }
414
+ pullAgent(identifier, options = {}) {
415
+ return this.pull("agent", identifier, options);
416
+ }
417
+ pullPrompt(identifier, options = {}) {
418
+ return this.pull("prompt", identifier, options);
419
+ }
420
+ pullSkill(identifier, options = {}) {
421
+ return this.pull("skill", identifier, options);
422
+ }
423
+ pullMemory(identifier, options = {}) {
424
+ return this.pull("memory", identifier, options);
425
+ }
426
+ pushAgent(identifier, options) {
427
+ return this.push("agent", identifier, options);
428
+ }
429
+ pushPrompt(identifier, options) {
430
+ return this.push("prompt", identifier, options);
431
+ }
432
+ pushSkill(identifier, options) {
433
+ return this.push("skill", identifier, options);
434
+ }
435
+ pushMemory(identifier, options) {
436
+ return this.push("memory", identifier, options);
437
+ }
438
+ listAgents(options = {}) {
439
+ return this.list("agent", options);
440
+ }
441
+ listPrompts(options = {}) {
442
+ return this.list("prompt", options);
443
+ }
444
+ listSkills(options = {}) {
445
+ return this.list("skill", options);
446
+ }
447
+ listMemory(options = {}) {
448
+ return this.list("memory", options);
449
+ }
450
+ agentExists(identifier) {
451
+ return this.exists("agent", identifier);
452
+ }
453
+ promptExists(identifier) {
454
+ return this.exists("prompt", identifier);
455
+ }
456
+ skillExists(identifier) {
457
+ return this.exists("skill", identifier);
458
+ }
459
+ memoryExists(identifier) {
460
+ return this.exists("memory", identifier);
461
+ }
462
+ deleteAgent(identifier) {
463
+ return this.delete("agent", identifier);
464
+ }
465
+ deletePrompt(identifier) {
466
+ return this.delete("prompt", identifier);
467
+ }
468
+ deleteSkill(identifier) {
469
+ return this.delete("skill", identifier);
470
+ }
471
+ deleteMemory(identifier) {
472
+ return this.delete("memory", identifier);
473
+ }
474
+ async resolveAgent(identifier, runtimeContext = {}) {
475
+ const agent = await this.pullAgent(identifier);
476
+ const config = parseJsonFile(agent, "config.json");
477
+ const prompts = await this.resolveRefs("prompt", getPromptRefs(config));
478
+ const skills = await this.resolveRefs("skill", getRefList(config.skills));
479
+ const memory2 = await this.resolveRefs("memory", getRefList(config.memory));
480
+ const bundleBase = {
481
+ agent,
482
+ config,
483
+ prompt: prompts[0] ?? null,
484
+ prompts,
485
+ skills,
486
+ memory: memory2,
487
+ provenance: [
488
+ provenanceFor(agent),
489
+ ...prompts.map(({ snapshot, version }) => provenanceFor(snapshot, version)),
490
+ ...skills.map(({ snapshot, version }) => provenanceFor(snapshot, version)),
491
+ ...memory2.map(({ snapshot, version }) => provenanceFor(snapshot, version))
492
+ ]
493
+ };
494
+ const renderSystem = (options = {}) => renderAgentSystem(bundleBase, options);
495
+ if (Object.keys(runtimeContext).length > 0) {
496
+ this.log("resolveAgent runtime context %o", runtimeContext);
497
+ }
498
+ return {
499
+ ...bundleBase,
500
+ system: renderSystem(),
501
+ renderSystem
502
+ };
503
+ }
504
+ async pull(kind, identifier, options = {}) {
505
+ const query = new URLSearchParams();
506
+ if (options.version) query.set("version", options.version);
507
+ const suffix = query.toString() ? `?${query.toString()}` : "";
508
+ return this.requestJson(
509
+ "GET",
510
+ `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(
511
+ identifier
512
+ )}${suffix}`
513
+ );
514
+ }
515
+ async push(kind, identifier, options) {
516
+ return this.requestJson(
517
+ "POST",
518
+ `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(
519
+ identifier
520
+ )}`,
521
+ {
522
+ files: options.files,
523
+ ...options.parentCommit ? { parentCommit: options.parentCommit } : {},
524
+ ...options.description ? { description: options.description } : {},
525
+ ...options.readme ? { readme: options.readme } : {},
526
+ ...options.tags ? { tags: options.tags } : {},
527
+ ...options.isPublic !== void 0 ? { isPublic: options.isPublic } : {},
528
+ ...options.writePolicy ? { writePolicy: options.writePolicy } : {},
529
+ ...options.message ? { message: options.message } : {},
530
+ ...runtimeContextPayload(options)
531
+ }
532
+ );
533
+ }
534
+ async list(kind, options = {}) {
535
+ const query = new URLSearchParams();
536
+ if (options.query) query.set("query", options.query);
537
+ if (options.isPublic !== void 0) query.set("isPublic", String(options.isPublic));
538
+ if (options.isArchived !== void 0)
539
+ query.set("isArchived", String(options.isArchived));
540
+ if (options.limit !== void 0) query.set("limit", String(options.limit));
541
+ if (options.offset !== void 0) query.set("offset", String(options.offset));
542
+ const suffix = query.toString() ? `?${query.toString()}` : "";
543
+ return this.requestJson(
544
+ "GET",
545
+ `/api/public/context/${endpointForKind(kind)}${suffix}`
546
+ );
547
+ }
548
+ async exists(kind, identifier) {
549
+ const query = new URLSearchParams({ exists: "true" });
550
+ const response = await this.requestJson(
551
+ "GET",
552
+ `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(
553
+ identifier
554
+ )}?${query.toString()}`
555
+ );
556
+ return response.exists;
557
+ }
558
+ async delete(kind, identifier) {
559
+ return this.requestJson(
560
+ "DELETE",
561
+ `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(identifier)}`
562
+ );
563
+ }
564
+ async resolveRefs(kind, refs) {
565
+ const resolved = [];
566
+ for (const ref of refs) {
567
+ const normalized = normalizeRef(ref);
568
+ if (!normalized) continue;
569
+ const snapshot = await this.pull(kind, normalized.identifier, {
570
+ version: normalized.version
571
+ });
572
+ const primaryPath = primaryPathForKind(kind, snapshot);
573
+ const content = primaryPath ? readFile(snapshot, primaryPath) ?? "" : "";
574
+ resolved.push({
575
+ ...normalized,
576
+ snapshot,
577
+ primaryPath,
578
+ content
579
+ });
580
+ }
581
+ return resolved;
582
+ }
583
+ async requestJson(method, path, payload) {
584
+ const response = await fetch(`${this.host}${path}`, {
585
+ method,
586
+ headers: {
587
+ Authorization: this.authHeader(),
588
+ ...payload ? { "Content-Type": "application/json" } : {}
589
+ },
590
+ ...payload ? { body: JSON.stringify(payload) } : {}
591
+ });
592
+ const text = await response.text();
593
+ const body = text ? safeJson(text) : {};
594
+ if (!response.ok) {
595
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path}`;
596
+ if (response.status === 409) {
597
+ throw new GatewayContextConflictError(
598
+ message,
599
+ body.latestCommit ?? null
600
+ );
601
+ }
602
+ throw new GatewayContextError(message);
603
+ }
604
+ this.log("%s %s -> %s", method, path, response.status);
605
+ return body;
606
+ }
607
+ authHeader() {
608
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
609
+ "base64"
610
+ )}`;
611
+ }
612
+ log(message, ...args) {
613
+ if (this.debug) {
614
+ console.log(`[gateway.context] ${message}`, ...args);
615
+ }
616
+ }
617
+ };
618
+ function renderAgentSystem(bundle, options = {}) {
619
+ const includeAgent = options.includeAgent ?? true;
620
+ const includePrompts = options.includePrompts ?? true;
621
+ const includeSkills = options.includeSkills ?? true;
622
+ const includeMemory = options.includeMemory ?? false;
623
+ const sections = [];
624
+ if (includeAgent) {
625
+ const agentContent = readFile(bundle.agent, "AGENTS.md");
626
+ if (agentContent) sections.push(formatSection("Agent", bundle.agent, agentContent));
627
+ }
628
+ if (includePrompts) {
629
+ for (const prompt of bundle.prompts) {
630
+ if (prompt.content) {
631
+ sections.push(formatSection("Prompt", prompt.snapshot, prompt.content));
632
+ }
633
+ }
634
+ }
635
+ if (includeSkills) {
636
+ for (const skill of bundle.skills) {
637
+ if (skill.content) {
638
+ sections.push(formatSection("Skill", skill.snapshot, skill.content));
639
+ }
640
+ }
641
+ }
642
+ if (includeMemory) {
643
+ for (const memory2 of bundle.memory) {
644
+ if (memory2.content) {
645
+ sections.push(formatSection("Memory", memory2.snapshot, memory2.content));
646
+ }
647
+ }
648
+ }
649
+ return sections.join("\n\n---\n\n");
650
+ }
651
+ function formatSection(title, snapshot, content) {
652
+ return [
653
+ `# ${title}: ${snapshot.repo.repoHandle}`,
654
+ `<!-- commit: ${snapshot.commit.commitHash} -->`,
655
+ "",
656
+ content.trim()
657
+ ].join("\n");
658
+ }
659
+ function getPromptRefs(config) {
660
+ const refs = [
661
+ ...getRefList(config.prompt),
662
+ ...getRefList(config.promptRef),
663
+ ...getRefList(config.prompt_ref),
664
+ ...getRefList(config.prompts)
665
+ ];
666
+ return dedupeRefs(refs);
667
+ }
668
+ function getRefList(value) {
669
+ if (!value) return [];
670
+ if (typeof value === "string") return [value];
671
+ if (Array.isArray(value)) return value.filter(isContextRepoRef);
672
+ if (isContextRepoRef(value)) return [value];
673
+ return [];
674
+ }
675
+ function isContextRepoRef(value) {
676
+ if (typeof value === "string") return true;
677
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
678
+ const record = value;
679
+ return ["identifier", "repoHandle", "repo_handle"].some(
680
+ (key) => typeof record[key] === "string"
681
+ );
682
+ }
683
+ function dedupeRefs(refs) {
684
+ const seen = /* @__PURE__ */ new Set();
685
+ return refs.filter((ref) => {
686
+ const normalized = normalizeRef(ref);
687
+ if (!normalized) return false;
688
+ const key = `${normalized.identifier}:${normalized.version ?? ""}`;
689
+ if (seen.has(key)) return false;
690
+ seen.add(key);
691
+ return true;
692
+ });
693
+ }
694
+ function normalizeRef(ref) {
695
+ if (typeof ref === "string") {
696
+ const identifier2 = ref.trim();
697
+ return identifier2 ? { identifier: identifier2 } : null;
698
+ }
699
+ const identifier = (ref.identifier ?? ref.repoHandle ?? ref.repo_handle ?? "").trim();
700
+ if (!identifier) return null;
701
+ return {
702
+ identifier,
703
+ version: ref.version ?? ref.label,
704
+ writable: ref.writable
705
+ };
706
+ }
707
+ function primaryPathForKind(kind, snapshot) {
708
+ const preferred = kind === "agent" ? "AGENTS.md" : kind === "prompt" ? "PROMPT.md" : kind === "skill" ? "SKILL.md" : "MEMORY.md";
709
+ if (readFile(snapshot, preferred)) return preferred;
710
+ return Object.entries(snapshot.files).find(
711
+ ([path, entry]) => entry.type === "file" && path.endsWith(".md")
712
+ )?.[0] ?? null;
713
+ }
714
+ function parseJsonFile(snapshot, path) {
715
+ const content = readFile(snapshot, path);
716
+ if (!content) return {};
717
+ try {
718
+ const parsed = JSON.parse(content);
719
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
720
+ } catch {
721
+ return {};
722
+ }
723
+ }
724
+ function readFile(snapshot, path) {
725
+ const entry = snapshot.files[path];
726
+ return entry?.type === "file" ? entry.content : null;
727
+ }
728
+ function provenanceFor(snapshot, label) {
729
+ return {
730
+ kind: snapshot.repo.kind,
731
+ repoHandle: snapshot.repo.repoHandle,
732
+ commitHash: snapshot.commit.commitHash,
733
+ ...label ? { label } : {}
734
+ };
735
+ }
736
+ function endpointForKind(kind) {
737
+ return kind === "memory" ? "memory" : `${kind}s`;
738
+ }
739
+ function runtimeContextPayload(options) {
740
+ return {
741
+ ...options.source ? { source: options.source } : {},
742
+ ...options.actorType ? { actorType: options.actorType } : {},
743
+ ...options.proposedBy ? { proposedBy: options.proposedBy } : {},
744
+ ...options.agentId ? { agentId: options.agentId } : {},
745
+ ...options.agentStableId ? { agentStableId: options.agentStableId } : {},
746
+ ...options.processId ? { processId: options.processId } : {},
747
+ ...options.traceId ? { traceId: options.traceId } : {},
748
+ ...options.spanId ? { spanId: options.spanId } : {},
749
+ ...options.sessionId ? { sessionId: options.sessionId } : {},
750
+ ...options.userId ? { userId: options.userId } : {},
751
+ ...options.teamId ? { teamId: options.teamId } : {},
752
+ ...options.metadata ? { metadata: options.metadata } : {}
753
+ };
754
+ }
755
+ function encodeIdentifier(identifier) {
756
+ return identifier.split("/").filter(Boolean).map((part) => encodeURIComponent(part)).join("/");
757
+ }
758
+ function safeJson(value) {
759
+ try {
760
+ const parsed = JSON.parse(value);
761
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
762
+ } catch {
763
+ return {};
764
+ }
765
+ }
766
+ var context = {
767
+ fromEnv: GatewayContext.fromEnv
768
+ };
769
+
770
+ // src/memory/index.ts
771
+ var GatewayMemoryError = class extends Error {
772
+ constructor(message, options) {
773
+ super(message);
774
+ this.name = "GatewayMemoryError";
775
+ this.cause = options?.cause;
776
+ }
777
+ };
778
+ var GatewayMemoryConflictError = class extends GatewayMemoryError {
779
+ latestCommit;
780
+ constructor(message, latestCommit) {
781
+ super(message);
782
+ this.name = "GatewayMemoryConflictError";
783
+ this.latestCommit = latestCommit;
784
+ }
785
+ };
786
+ var GatewayMemory = class _GatewayMemory {
787
+ host;
788
+ publicKey;
789
+ secretKey;
790
+ debug;
791
+ constructor(config) {
792
+ this.host = config.host.replace(/\/$/, "");
793
+ this.publicKey = config.publicKey;
794
+ this.secretKey = config.secretKey;
795
+ this.debug = config.debug ?? false;
796
+ }
797
+ static fromEnv(config = {}) {
798
+ const host = config.host ?? process.env.GATEWAY_HOST;
799
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
800
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
801
+ const missing = [
802
+ ["host", host],
803
+ ["publicKey", publicKey],
804
+ ["secretKey", secretKey]
805
+ ].filter(([, value]) => !value).map(([name]) => name);
806
+ if (missing.length > 0) {
807
+ throw new GatewayMemoryError(
808
+ `Missing Gateway memory configuration: ${missing.join(", ")}`
809
+ );
810
+ }
811
+ return new _GatewayMemory({
812
+ ...config,
813
+ host,
814
+ publicKey,
815
+ secretKey
816
+ });
817
+ }
818
+ async pull(identifier, options = {}) {
819
+ const query = new URLSearchParams();
820
+ if (options.version) query.set("version", options.version);
821
+ const suffix = query.toString() ? `?${query.toString()}` : "";
822
+ return this.requestJson(
823
+ "GET",
824
+ `/api/public/context/memory/${encodeIdentifier2(identifier)}${suffix}`
825
+ );
826
+ }
827
+ async read(target, path, options = {}) {
828
+ const snapshot = typeof target === "string" ? await this.pull(target, options) : target;
829
+ const file = snapshot.files[path];
830
+ return file?.type === "file" ? file.content : null;
831
+ }
832
+ async write(target, path, content, options = {}) {
833
+ const snapshot = typeof target === "string" ? await this.pull(target) : target;
834
+ return this.push(snapshot.repo.repoHandle, {
835
+ files: {
836
+ [path]: {
837
+ content,
838
+ ...options.mimeType ? { mimeType: options.mimeType } : {}
839
+ }
840
+ },
841
+ parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
842
+ message: options.message,
843
+ ...runtimeContextPayload2(options)
844
+ });
845
+ }
846
+ async delete(target, path, options = {}) {
847
+ const snapshot = typeof target === "string" ? await this.pull(target) : target;
848
+ return this.push(snapshot.repo.repoHandle, {
849
+ files: { [path]: null },
850
+ parentCommit: options.parentCommit ?? snapshot.commit.commitHash,
851
+ message: options.message,
852
+ ...runtimeContextPayload2(options)
853
+ });
854
+ }
855
+ async push(identifier, payload) {
856
+ return this.requestJson(
857
+ "POST",
858
+ `/api/public/context/memory/${encodeIdentifier2(identifier)}`,
859
+ payload
860
+ );
861
+ }
862
+ async requestJson(method, path, payload) {
863
+ const response = await fetch(`${this.host}${path}`, {
864
+ method,
865
+ headers: {
866
+ Authorization: this.authHeader(),
867
+ ...payload ? { "Content-Type": "application/json" } : {}
868
+ },
869
+ ...payload ? { body: JSON.stringify(payload) } : {}
870
+ });
871
+ const text = await response.text();
872
+ const body = text ? safeJson2(text) : {};
873
+ if (!response.ok) {
874
+ const message = typeof body.message === "string" ? body.message : `Gateway API ${response.status} on ${path}`;
875
+ if (response.status === 409) {
876
+ throw new GatewayMemoryConflictError(
877
+ message,
878
+ body.latestCommit ?? null
879
+ );
880
+ }
881
+ throw new GatewayMemoryError(message);
882
+ }
883
+ this.log("%s %s -> %s", method, path, response.status);
884
+ return body;
885
+ }
886
+ authHeader() {
887
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
888
+ "base64"
889
+ )}`;
890
+ }
891
+ log(message, ...args) {
892
+ if (this.debug) {
893
+ console.log(`[gateway.memory] ${message}`, ...args);
894
+ }
895
+ }
896
+ };
897
+ function runtimeContextPayload2(options) {
898
+ return {
899
+ ...options.source ? { source: options.source } : {},
900
+ ...options.actorType ? { actorType: options.actorType } : {},
901
+ ...options.proposedBy ? { proposedBy: options.proposedBy } : {},
902
+ ...options.agentId ? { agentId: options.agentId } : {},
903
+ ...options.agentStableId ? { agentStableId: options.agentStableId } : {},
904
+ ...options.processId ? { processId: options.processId } : {},
905
+ ...options.traceId ? { traceId: options.traceId } : {},
906
+ ...options.spanId ? { spanId: options.spanId } : {},
907
+ ...options.sessionId ? { sessionId: options.sessionId } : {},
908
+ ...options.userId ? { userId: options.userId } : {},
909
+ ...options.teamId ? { teamId: options.teamId } : {},
910
+ ...options.metadata ? { metadata: options.metadata } : {}
911
+ };
912
+ }
913
+ function encodeIdentifier2(identifier) {
914
+ return identifier.split("/").filter(Boolean).map((part) => encodeURIComponent(part)).join("/");
915
+ }
916
+ function safeJson2(value) {
917
+ try {
918
+ const parsed = JSON.parse(value);
919
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
920
+ } catch {
921
+ return {};
922
+ }
923
+ }
924
+ var memory = {
925
+ fromEnv: GatewayMemory.fromEnv
926
+ };
927
+
928
+ // src/security/index.ts
929
+ var SECURITY_ATTRIBUTES = {
930
+ AGENT_ID: "gateway.agent.id",
931
+ AGENT_NAME: "gateway.agent.name",
932
+ AGENT_VERSION: "gateway.agent.version",
933
+ TOOLSET_ID: "gateway.toolset.id",
934
+ TOOL_ID: "gateway.tool.id",
935
+ SECURITY_MODE: "gateway.security.mode",
936
+ POLICY_VERSION: "gateway.security.policy_version",
937
+ DECISION_OUTCOME: "gateway.decision.outcome",
938
+ DECISION_REASON_CODE: "gateway.decision.reason_code"
939
+ };
940
+ var GatewaySecurityError = class extends Error {
941
+ constructor(message, options) {
942
+ super(message);
943
+ this.name = "GatewaySecurityError";
944
+ this.cause = options?.cause;
945
+ }
946
+ };
947
+ var GatewayToolBlockedError = class extends GatewaySecurityError {
948
+ decision;
949
+ toolId;
950
+ constructor(toolId, decision) {
951
+ super(decision.message || `Gateway blocked tool ${toolId}`);
952
+ this.name = "GatewayToolBlockedError";
953
+ this.toolId = toolId;
954
+ this.decision = decision;
955
+ }
956
+ };
957
+ var GatewayToolApprovalRequiredError = class extends GatewaySecurityError {
958
+ decision;
959
+ toolId;
960
+ constructor(toolId, decision) {
961
+ super(decision.message || `Gateway requires approval for tool ${toolId}`);
962
+ this.name = "GatewayToolApprovalRequiredError";
963
+ this.toolId = toolId;
964
+ this.decision = decision;
965
+ }
966
+ };
967
+ var GatewaySecurity = class _GatewaySecurity {
968
+ host;
969
+ publicKey;
970
+ secretKey;
971
+ agent;
972
+ debug;
973
+ failOpen;
974
+ constructor(config) {
975
+ this.host = config.host.replace(/\/$/, "");
976
+ this.publicKey = config.publicKey;
977
+ this.secretKey = config.secretKey;
978
+ this.agent = config.agent ?? {};
979
+ this.debug = config.debug ?? false;
980
+ this.failOpen = config.failOpen ?? false;
981
+ }
982
+ static fromEnv(config = {}) {
983
+ const host = config.host ?? process.env.GATEWAY_HOST;
984
+ const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
985
+ const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
986
+ const missing = [
987
+ ["host", host],
988
+ ["publicKey", publicKey],
989
+ ["secretKey", secretKey]
990
+ ].filter(([, value]) => !value).map(([name]) => name);
991
+ if (missing.length > 0) {
992
+ throw new GatewaySecurityError(
993
+ `Missing Gateway security configuration: ${missing.join(", ")}`
994
+ );
995
+ }
996
+ return new _GatewaySecurity({
997
+ ...config,
998
+ host,
999
+ publicKey,
1000
+ secretKey
1001
+ });
1002
+ }
1003
+ async secureTools(options) {
1004
+ const entries = Object.entries(options.tools);
1005
+ const descriptors = entries.map(
1006
+ ([key, tool]) => this.describeTool(key, tool, options)
1007
+ );
1008
+ const resolve = await this.resolveToolset({
1009
+ agent: this.agent,
1010
+ toolsetId: options.toolsetId,
1011
+ toolsetName: options.toolsetName,
1012
+ provider: options.provider,
1013
+ tools: descriptors,
1014
+ context: this.normalizeContext(options.context)
1015
+ });
1016
+ const securedEntries = entries.flatMap(([key, tool]) => {
1017
+ const descriptor = descriptors.find((item) => item.name === key);
1018
+ if (!this.shouldExposeTool(resolve, descriptor.id)) {
1019
+ this.log("Hiding tool %s in %s mode", descriptor.id, resolve.mode);
1020
+ return [];
1021
+ }
1022
+ return [
1023
+ [
1024
+ key,
1025
+ this.wrapTool(tool, {
1026
+ toolId: descriptor.id,
1027
+ toolsetId: options.toolsetId,
1028
+ context: this.normalizeContext(options.context),
1029
+ resolve
1030
+ })
1031
+ ]
1032
+ ];
1033
+ });
1034
+ return Object.fromEntries(securedEntries);
1035
+ }
1036
+ async resolveToolset(input) {
1037
+ return this.postJson(
1038
+ "/api/public/security/toolsets/resolve",
1039
+ input
1040
+ );
1041
+ }
1042
+ async authorizeToolCall(input) {
1043
+ return this.postJson(
1044
+ "/api/public/security/tool-calls/authorize",
1045
+ {
1046
+ agent: this.agent,
1047
+ toolsetId: input.toolsetId,
1048
+ toolId: input.toolId,
1049
+ context: input.context,
1050
+ inputMetadata: input.inputMetadata
1051
+ }
1052
+ );
1053
+ }
1054
+ wrapTool(tool, input) {
1055
+ if (typeof tool === "function") {
1056
+ return this.wrapExecute(tool, input);
1057
+ }
1058
+ if (typeof tool.execute !== "function") {
1059
+ return tool;
1060
+ }
1061
+ return {
1062
+ ...tool,
1063
+ execute: this.wrapExecute(tool.execute.bind(tool), input)
1064
+ };
1065
+ }
1066
+ wrapExecute(execute, input) {
1067
+ return async (...args) => {
1068
+ this.setSpanAttributes({
1069
+ [SECURITY_ATTRIBUTES.AGENT_ID]: this.agent.id,
1070
+ [SECURITY_ATTRIBUTES.AGENT_NAME]: this.agent.name,
1071
+ [SECURITY_ATTRIBUTES.AGENT_VERSION]: this.agent.version,
1072
+ [SECURITY_ATTRIBUTES.TOOLSET_ID]: input.toolsetId,
1073
+ [SECURITY_ATTRIBUTES.TOOL_ID]: input.toolId,
1074
+ [SECURITY_ATTRIBUTES.SECURITY_MODE]: input.resolve.mode,
1075
+ [SECURITY_ATTRIBUTES.POLICY_VERSION]: input.resolve.policyVersion
1076
+ });
1077
+ const decision = await this.authorizeOrFallback({
1078
+ toolsetId: input.toolsetId,
1079
+ toolId: input.toolId,
1080
+ context: input.context,
1081
+ inputMetadata: { args }
1082
+ });
1083
+ this.setSpanAttributes({
1084
+ [SECURITY_ATTRIBUTES.DECISION_OUTCOME]: decision.outcome,
1085
+ [SECURITY_ATTRIBUTES.DECISION_REASON_CODE]: decision.reasonCode,
1086
+ [SECURITY_ATTRIBUTES.POLICY_VERSION]: decision.policyVersion
1087
+ });
1088
+ if (decision.outcome === "block") {
1089
+ throw new GatewayToolBlockedError(input.toolId, decision);
1090
+ }
1091
+ if (decision.outcome === "approval_required") {
1092
+ throw new GatewayToolApprovalRequiredError(input.toolId, decision);
1093
+ }
1094
+ return execute(...args);
1095
+ };
1096
+ }
1097
+ async authorizeOrFallback(input) {
1098
+ try {
1099
+ return await this.authorizeToolCall(input);
1100
+ } catch (error) {
1101
+ if (this.failOpen) {
1102
+ this.log("Authorization failed open for tool %s", input.toolId, error);
1103
+ return {
1104
+ decisionId: "local-fail-open",
1105
+ outcome: "flag",
1106
+ reasonCode: "authorization_unavailable_fail_open",
1107
+ message: "Gateway authorization was unavailable; failOpen allowed execution.",
1108
+ policyVersion: 0
1109
+ };
1110
+ }
1111
+ throw new GatewaySecurityError(
1112
+ `Gateway authorization failed for tool ${input.toolId}`,
1113
+ { cause: error }
1114
+ );
1115
+ }
1116
+ }
1117
+ async postJson(path, payload) {
1118
+ const response = await fetch(`${this.host}${path}`, {
1119
+ method: "POST",
1120
+ headers: {
1121
+ Authorization: this.authHeader(),
1122
+ "Content-Type": "application/json"
1123
+ },
1124
+ body: JSON.stringify(payload)
1125
+ });
1126
+ if (!response.ok) {
1127
+ const body = await response.text();
1128
+ throw new GatewaySecurityError(
1129
+ `Gateway API ${response.status} on ${path}: ${body || response.statusText}`
1130
+ );
1131
+ }
1132
+ return await response.json();
1133
+ }
1134
+ describeTool(key, tool, options) {
1135
+ const toolObject = typeof tool === "function" ? void 0 : tool;
1136
+ const id = options.toolIds?.[key] ?? `${options.toolsetId}.${toSnakeCase(key)}`;
1137
+ return {
1138
+ id,
1139
+ name: key,
1140
+ description: typeof toolObject?.description === "string" ? toolObject.description : void 0,
1141
+ metadata: options.toolMetadata?.[key] ?? {}
1142
+ };
1143
+ }
1144
+ shouldExposeTool(resolve, toolId) {
1145
+ if (resolve.mode === "observe") return true;
1146
+ if (resolve.blockedToolIds.includes(toolId)) return false;
1147
+ return true;
1148
+ }
1149
+ normalizeContext(context2) {
1150
+ return {
1151
+ ...context2 ?? {},
1152
+ metadata: context2?.metadata ?? {}
1153
+ };
1154
+ }
1155
+ authHeader() {
1156
+ return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
1157
+ "base64"
1158
+ )}`;
1159
+ }
1160
+ setSpanAttributes(attributes) {
1161
+ const span = getActiveSpan();
1162
+ if (!span) return;
1163
+ for (const [key, value] of Object.entries(attributes)) {
1164
+ if (value === void 0 || value === null) continue;
1165
+ span.setAttribute(key, value);
1166
+ }
1167
+ }
1168
+ log(message, ...args) {
1169
+ if (this.debug) {
1170
+ console.log(`[gateway.security] ${message}`, ...args);
1171
+ }
1172
+ }
1173
+ };
1174
+ function getActiveSpan() {
1175
+ try {
1176
+ const otel = __require("@opentelemetry/api");
1177
+ return otel.trace?.getActiveSpan?.() ?? null;
1178
+ } catch {
1179
+ return null;
1180
+ }
1181
+ }
1182
+ function toSnakeCase(value) {
1183
+ return value.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[\s-]+/g, "_").toLowerCase();
1184
+ }
1185
+ var gateway = {
1186
+ fromEnv: GatewaySecurity.fromEnv
1187
+ };
1188
+
1189
+ // src/tracing/index.ts
1190
+ var tracing_exports = {};
1191
+ __export(tracing_exports, {
1192
+ flush: () => flush,
1193
+ init: () => init2,
1194
+ isGatewayConfigured: () => isGatewayConfigured,
1195
+ isInitialized: () => isInitialized,
1196
+ shutdown: () => shutdown2
1197
+ });
1198
+
1199
+ // src/tracing/init.ts
1200
+ var ENV_VARS = {
1201
+ HOST: ["GATEWAY_HOST", "GATEWAY_HOST"],
1202
+ PUBLIC_KEY: ["GATEWAY_PUBLIC_KEY", "GATEWAY_PUBLIC_KEY"],
1203
+ SECRET_KEY: ["GATEWAY_SECRET_KEY", "GATEWAY_SECRET_KEY"],
1204
+ ENDPOINT: ["GATEWAY_OTLP_ENDPOINT", "GATEWAY_OTLP_ENDPOINT"]
1205
+ };
1206
+ var DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
1207
+ var state = {
1208
+ initialized: false,
1209
+ provider: null
1210
+ };
1211
+ function getEnv(keys) {
1212
+ for (const key of keys) {
1213
+ const value = process.env[key];
1214
+ if (value) return value;
1215
+ }
1216
+ return void 0;
1217
+ }
1218
+ function log(message, ...args) {
1219
+ if (state.debug) {
1220
+ console.log(`[gatewaysdk.tracing] ${message}`, ...args);
1221
+ }
1222
+ }
1223
+ function warn(message, ...args) {
1224
+ console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
1225
+ }
1226
+ function init2(config = {}) {
1227
+ if (state.initialized) {
1228
+ log("Tracing already initialized. Call shutdown() first to reinitialize.");
1229
+ return;
1230
+ }
1231
+ state.debug = config.debug ?? false;
1232
+ const host = config.host ?? getEnv(ENV_VARS.HOST);
1233
+ const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
1234
+ const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
1235
+ const endpoint = config.endpoint ?? getEnv(ENV_VARS.ENDPOINT) ?? (host ? `${host.replace(/\/$/, "")}${DEFAULT_OTLP_PATH}` : void 0);
1236
+ const missing = [];
1237
+ if (!host) missing.push("host (or GATEWAY_HOST env var)");
1238
+ if (!publicKey) missing.push("publicKey (or GATEWAY_PUBLIC_KEY env var)");
1239
+ if (!secretKey) missing.push("secretKey (or GATEWAY_SECRET_KEY env var)");
1240
+ if (missing.length > 0) {
1241
+ throw new Error(
1242
+ `Missing required Gateway configuration: ${missing.join(", ")}. Provide these values via init() parameters or environment variables.`
1243
+ );
1244
+ }
1245
+ let NodeTracerProvider;
1246
+ let BatchSpanProcessor;
1247
+ let OTLPTraceExporter;
1248
+ let createResource;
1249
+ let ATTR_SERVICE_NAME;
1250
+ try {
1251
+ const traceNode = __require("@opentelemetry/sdk-trace-node");
1252
+ const traceBase = __require("@opentelemetry/sdk-trace-base");
1253
+ const otlpHttp = __require("@opentelemetry/exporter-trace-otlp-http");
1254
+ const resources = __require("@opentelemetry/resources");
1255
+ NodeTracerProvider = traceNode.NodeTracerProvider;
1256
+ BatchSpanProcessor = traceBase.BatchSpanProcessor;
1257
+ OTLPTraceExporter = otlpHttp.OTLPTraceExporter;
1258
+ if (resources.Resource) {
1259
+ createResource = (attrs) => new resources.Resource(attrs);
1260
+ } else if (resources.resourceFromAttributes) {
1261
+ createResource = resources.resourceFromAttributes;
1262
+ } else {
1263
+ createResource = () => resources.defaultResource();
1264
+ }
1265
+ try {
1266
+ const semconv = __require("@opentelemetry/semantic-conventions");
1267
+ ATTR_SERVICE_NAME = semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? "service.name";
1268
+ } catch {
1269
+ ATTR_SERVICE_NAME = "service.name";
1270
+ }
1271
+ } catch {
1272
+ throw new Error(
1273
+ "OpenTelemetry packages not found. Install them with:\nnpm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base @opentelemetry/exporter-trace-otlp-http @opentelemetry/resources"
1274
+ );
1275
+ }
1276
+ const resourceAttrs = {
1277
+ [ATTR_SERVICE_NAME]: config.serviceName ?? "gatewaysdk-tracing"
1278
+ };
1279
+ if (config.environment) {
1280
+ resourceAttrs["gateway.environment"] = config.environment;
1281
+ }
1282
+ if (config.version) {
1283
+ resourceAttrs["gateway.version"] = config.version;
1284
+ }
1285
+ let isLocalhost = false;
1286
+ if (endpoint) {
1287
+ try {
1288
+ const parsed = new URL(endpoint);
1289
+ isLocalhost = parsed.hostname === "localhost" || parsed.hostname === "127.0.0.1";
1290
+ } catch {
1291
+ isLocalhost = false;
1292
+ }
1293
+ }
1294
+ if (endpoint && !endpoint.startsWith("https://") && !isLocalhost) {
1295
+ throw new Error(
1296
+ `Refusing to send credentials over insecure HTTP to ${endpoint}. Use HTTPS or localhost for development.`
1297
+ );
1298
+ }
1299
+ const credentials = `${publicKey}:${secretKey}`;
1300
+ const encoded = Buffer.from(credentials).toString("base64");
1301
+ const authHeader = `Basic ${encoded}`;
1302
+ const exporter = new OTLPTraceExporter({
1303
+ url: endpoint,
1304
+ headers: {
1305
+ Authorization: authHeader
1306
+ }
1307
+ });
1308
+ log("Configured Gateway exporter: endpoint=%s", endpoint);
1309
+ const spanProcessors = [];
1310
+ if (config.customSpanProcessors) {
1311
+ for (const sp of config.customSpanProcessors) {
1312
+ spanProcessors.push(sp);
1313
+ log(
1314
+ "Added custom span processor: %s",
1315
+ sp.constructor?.name ?? "unknown"
1316
+ );
1317
+ }
1318
+ }
1319
+ const batchConfig = {};
1320
+ if (config.batch?.maxQueueSize) {
1321
+ batchConfig.maxQueueSize = config.batch.maxQueueSize;
1322
+ }
1323
+ if (config.batch?.scheduledDelayMillis) {
1324
+ batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;
1325
+ }
1326
+ if (config.batch?.maxExportBatchSize) {
1327
+ batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;
1328
+ }
1329
+ spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));
1330
+ let provider = new NodeTracerProvider({
1331
+ resource: createResource(resourceAttrs)
1332
+ });
1333
+ if (typeof provider.addSpanProcessor === "function") {
1334
+ for (const sp of spanProcessors) {
1335
+ provider.addSpanProcessor(sp);
1336
+ }
1337
+ } else {
1338
+ provider = new NodeTracerProvider({
1339
+ resource: createResource(resourceAttrs),
1340
+ spanProcessors
1341
+ });
1342
+ }
1343
+ provider.register();
1344
+ state.provider = provider;
1345
+ state.initialized = true;
1346
+ log(
1347
+ "GatewaySDK tracing initialized successfully (service=%s)",
1348
+ config.serviceName ?? "gatewaysdk-tracing"
1349
+ );
1350
+ }
1351
+ async function flush() {
1352
+ if (!state.provider) {
1353
+ log("No provider to flush");
1354
+ return;
1355
+ }
1356
+ try {
1357
+ await state.provider.forceFlush();
1358
+ log("Flush completed successfully");
1359
+ } catch (e) {
1360
+ warn("Error during flush:", e);
1361
+ }
1362
+ }
1363
+ async function shutdown2() {
1364
+ if (!state.initialized || !state.provider) {
1365
+ log("Tracing not initialized, nothing to shutdown");
1366
+ return;
1367
+ }
1368
+ try {
1369
+ await state.provider.shutdown();
1370
+ log("Shutdown complete");
1371
+ } catch (e) {
1372
+ warn("Error during shutdown:", e);
1373
+ }
1374
+ state.provider = null;
1375
+ state.initialized = false;
1376
+ }
1377
+ function isInitialized() {
1378
+ return state.initialized;
1379
+ }
1380
+ function isGatewayConfigured() {
1381
+ const host = getEnv(ENV_VARS.HOST);
1382
+ const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);
1383
+ const secretKey = getEnv(ENV_VARS.SECRET_KEY);
1384
+ return !!(host && publicKey && secretKey);
1385
+ }
1386
+
1387
+ // src/index.ts
1388
+ var tracing = {
1389
+ ...tracing_exports,
1390
+ init(config = {}) {
1391
+ if (config.enableExperiments !== false) {
1392
+ const processors = [
1393
+ new ExperimentSpanProcessor(),
1394
+ ...config.customSpanProcessors ?? []
1395
+ ];
1396
+ return init2({
1397
+ ...config,
1398
+ customSpanProcessors: processors
1399
+ });
1400
+ }
1401
+ return init2(config);
1402
+ }
1403
+ };
1404
+ export {
1405
+ EXPERIMENT_ATTRIBUTES,
1406
+ ExperimentClient,
1407
+ ExperimentSpanProcessor,
1408
+ ExposureLogger,
1409
+ GatewayContext,
1410
+ GatewayContextConflictError,
1411
+ GatewayContextError,
1412
+ GatewayMemory,
1413
+ GatewayMemoryConflictError,
1414
+ GatewayMemoryError,
1415
+ GatewaySecurity,
1416
+ GatewaySecurityError,
1417
+ GatewayToolApprovalRequiredError,
1418
+ GatewayToolBlockedError,
1419
+ addExperimentAttributes,
1420
+ assignVariant,
1421
+ clearExperimentContext,
1422
+ computeHash,
1423
+ context,
1424
+ experimentContextStorage,
1425
+ singleton_exports as experiments,
1426
+ gateway,
1427
+ getExperimentContext,
1428
+ memory,
1429
+ renderAgentSystem,
1430
+ runWithExperimentContext,
1431
+ setExperimentContext,
1432
+ tracing
1433
+ };
1434
+ //# sourceMappingURL=index.mjs.map