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