@brizz/sdk 0.1.57 → 0.1.59
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 +52 -3
- package/dist/chunk-4QNEI7VZ.cjs +984 -0
- package/dist/{chunk-DCXOK7PX.cjs → chunk-5QZM5EVP.cjs} +8 -8
- package/dist/{chunk-O2IBZJOJ.cjs → chunk-6QXPHZEO.cjs} +4 -4
- package/dist/chunk-EZCNPWKM.js +984 -0
- package/dist/{chunk-7PRTTYWM.js → chunk-GABRGNAU.js} +1 -1
- package/dist/{chunk-GUKWVI53.js → chunk-GISL4K6Z.js} +27 -1
- package/dist/{chunk-RV7JIIDG.cjs → chunk-NF52RMLW.cjs} +27 -1
- package/dist/{chunk-42KYS2LU.js → chunk-ZGX52S4U.js} +2 -2
- package/dist/index.cjs +280 -966
- package/dist/index.js +238 -924
- package/dist/interrupt-36U5562Z.cjs +12 -0
- package/dist/{interrupt-UKJK5WOA.js → interrupt-6BSXUK3O.js} +2 -2
- package/dist/{mcp-FBTQYIOL.js → mcp-TTECBPGZ.js} +4 -3
- package/dist/{mcp-WHXEBLRI.cjs → mcp-UPBKSTB7.cjs} +19 -18
- package/dist/session.cjs +78 -0
- package/dist/session.js +78 -0
- package/dist/types/cjs/index.d.ts +2 -2
- package/dist/types/cjs/internal/error-type.d.ts +1 -0
- package/dist/types/cjs/internal/instrumentation/mcp/semantic-conventions.d.ts +1 -1
- package/dist/types/cjs/internal/instrumentation/typesafe.d.ts +0 -8
- package/dist/types/cjs/internal/log/emit.d.ts +8 -0
- package/dist/types/cjs/internal/log/logging.d.ts +2 -2
- package/dist/types/cjs/internal/semantic-conventions.d.ts +13 -0
- package/dist/types/cjs/internal/serialization.d.ts +2 -0
- package/dist/types/cjs/internal/trace/decision-call.d.ts +24 -0
- package/dist/types/cjs/internal/trace/index.d.ts +2 -0
- package/dist/types/cjs/internal/trace/session.d.ts +2 -1
- package/dist/types/cjs/session.d.ts +6 -0
- package/dist/types/esm/index.d.ts +2 -2
- package/dist/types/esm/internal/error-type.d.ts +1 -0
- package/dist/types/esm/internal/instrumentation/mcp/semantic-conventions.d.ts +1 -1
- package/dist/types/esm/internal/instrumentation/typesafe.d.ts +0 -8
- package/dist/types/esm/internal/log/emit.d.ts +8 -0
- package/dist/types/esm/internal/log/logging.d.ts +2 -2
- package/dist/types/esm/internal/semantic-conventions.d.ts +13 -0
- package/dist/types/esm/internal/serialization.d.ts +2 -0
- package/dist/types/esm/internal/trace/decision-call.d.ts +24 -0
- package/dist/types/esm/internal/trace/index.d.ts +2 -0
- package/dist/types/esm/internal/trace/session.d.ts +2 -1
- package/dist/types/esm/session.d.ts +6 -0
- package/package.json +29 -18
- package/dist/interrupt-BYLSBXTV.cjs +0 -12
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
import {
|
|
2
|
+
brizzTracerProvider,
|
|
3
|
+
extractTraceContext,
|
|
4
|
+
injectTraceContext
|
|
5
|
+
} from "./chunk-TDPQDITP.js";
|
|
6
|
+
import {
|
|
7
|
+
logger
|
|
8
|
+
} from "./chunk-Y4HNUX3Q.js";
|
|
9
|
+
import {
|
|
10
|
+
AGENT_ID,
|
|
11
|
+
AGENT_NAME,
|
|
12
|
+
AGENT_PARENT_ID,
|
|
13
|
+
BRIZZ,
|
|
14
|
+
EXTERNAL_LINK_EVENT_NAME,
|
|
15
|
+
EXTERNAL_LINK_TITLE,
|
|
16
|
+
EXTERNAL_LINK_TYPE,
|
|
17
|
+
EXTERNAL_LINK_URL,
|
|
18
|
+
FEEDBACK_ATTR_PREFIX,
|
|
19
|
+
FEEDBACK_COMMENT,
|
|
20
|
+
FEEDBACK_EVENT_NAME,
|
|
21
|
+
FEEDBACK_REASON,
|
|
22
|
+
FEEDBACK_SCORE,
|
|
23
|
+
FEEDBACK_SOURCE,
|
|
24
|
+
FEEDBACK_TYPE,
|
|
25
|
+
MESSAGE_ID,
|
|
26
|
+
METRIC_ATTRIBUTE_PREFIX,
|
|
27
|
+
METRIC_COMMENT,
|
|
28
|
+
METRIC_EVENT_NAME,
|
|
29
|
+
METRIC_MAX,
|
|
30
|
+
METRIC_MIN,
|
|
31
|
+
METRIC_NAME,
|
|
32
|
+
METRIC_POLARITY,
|
|
33
|
+
METRIC_POLARITY_NEGATIVE,
|
|
34
|
+
METRIC_POLARITY_POSITIVE,
|
|
35
|
+
METRIC_SCOPE,
|
|
36
|
+
METRIC_SCOPE_SESSION,
|
|
37
|
+
METRIC_SCOPE_TRACE,
|
|
38
|
+
METRIC_TIMESTAMP,
|
|
39
|
+
METRIC_TRACE_ID,
|
|
40
|
+
METRIC_UNIT,
|
|
41
|
+
METRIC_VALUE,
|
|
42
|
+
MUTE_INPUT,
|
|
43
|
+
MUTE_OUTPUT,
|
|
44
|
+
MUTE_TOOLS,
|
|
45
|
+
ORGANIZATION_DOMAIN,
|
|
46
|
+
ORGANIZATION_ID,
|
|
47
|
+
ORGANIZATION_NAME,
|
|
48
|
+
ORGANIZATION_PLAN,
|
|
49
|
+
PROPERTIES_CONTEXT_KEY,
|
|
50
|
+
RESERVED_METRIC_NAMES,
|
|
51
|
+
SERVICE_NAME,
|
|
52
|
+
SESSION_ID,
|
|
53
|
+
SESSION_INPUT,
|
|
54
|
+
SESSION_INPUT_CONTEXT,
|
|
55
|
+
SESSION_OBJECT_CONTEXT_KEY,
|
|
56
|
+
SESSION_OUTPUT,
|
|
57
|
+
SESSION_OUTPUT_CONTEXT,
|
|
58
|
+
SESSION_SPAN_NAME,
|
|
59
|
+
SESSION_TITLE,
|
|
60
|
+
SESSION_TITLE_GENERATION,
|
|
61
|
+
SESSION_TITLE_SPAN_NAME,
|
|
62
|
+
USER_EMAIL,
|
|
63
|
+
USER_ID,
|
|
64
|
+
USER_NAME,
|
|
65
|
+
USER_PLAN,
|
|
66
|
+
USER_ROLE
|
|
67
|
+
} from "./chunk-GISL4K6Z.js";
|
|
68
|
+
|
|
69
|
+
// src/internal/log/emit.ts
|
|
70
|
+
import { SeverityNumber } from "@opentelemetry/api";
|
|
71
|
+
var localSink = null;
|
|
72
|
+
var STATE_KEY = /* @__PURE__ */ Symbol.for("brizz.sdk.eventSink");
|
|
73
|
+
function state() {
|
|
74
|
+
const holder = globalThis;
|
|
75
|
+
holder[STATE_KEY] ??= { sinks: [] };
|
|
76
|
+
return holder[STATE_KEY];
|
|
77
|
+
}
|
|
78
|
+
function setEventSink(sink) {
|
|
79
|
+
localSink = sink;
|
|
80
|
+
const shared = state();
|
|
81
|
+
shared.sinks = shared.sinks.filter((other) => other !== sink);
|
|
82
|
+
shared.sinks.push(sink);
|
|
83
|
+
}
|
|
84
|
+
function clearEventSink(sink) {
|
|
85
|
+
if (localSink === sink) {
|
|
86
|
+
localSink = null;
|
|
87
|
+
}
|
|
88
|
+
const shared = state();
|
|
89
|
+
shared.sinks = shared.sinks.filter((other) => other !== sink);
|
|
90
|
+
}
|
|
91
|
+
function emitEvent(name, attributes, body, severityNumber = SeverityNumber.INFO) {
|
|
92
|
+
const sink = localSink ?? state().sinks.at(-1);
|
|
93
|
+
if (!sink) {
|
|
94
|
+
throw new Error("Brizz must be initialized before accessing LoggingModule");
|
|
95
|
+
}
|
|
96
|
+
sink.emitEvent(name, attributes, body, severityNumber);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// src/internal/trace/session.ts
|
|
100
|
+
import { context, isSpanContextValid, trace, SpanStatusCode } from "@opentelemetry/api";
|
|
101
|
+
var sessionTracer = brizzTracerProvider.getTracer("@brizz/sdk");
|
|
102
|
+
function setCurrentSpanCustomProperties(properties) {
|
|
103
|
+
const current = trace.getActiveSpan();
|
|
104
|
+
if (!current || !current.isRecording()) {
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
108
|
+
try {
|
|
109
|
+
current.setAttribute(`${BRIZZ}.${key}`, value);
|
|
110
|
+
} catch {
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
function callWithProperties(properties, fn, thisArg, ...args) {
|
|
115
|
+
const base = context.active();
|
|
116
|
+
const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
|
|
117
|
+
const merged = prev ? { ...prev, ...properties } : properties;
|
|
118
|
+
const next = base.setValue(PROPERTIES_CONTEXT_KEY, merged);
|
|
119
|
+
return context.with(next, fn, thisArg, ...args);
|
|
120
|
+
}
|
|
121
|
+
function withProperties(properties, fn, thisArg) {
|
|
122
|
+
return function wrapped(...args) {
|
|
123
|
+
return callWithProperties(
|
|
124
|
+
properties,
|
|
125
|
+
fn,
|
|
126
|
+
thisArg !== void 0 ? thisArg : this,
|
|
127
|
+
...args
|
|
128
|
+
);
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function propagatePropertiesImperatively(properties, base = context.active()) {
|
|
132
|
+
try {
|
|
133
|
+
const manager = context;
|
|
134
|
+
const mgr = manager._getContextManager?.();
|
|
135
|
+
const store = mgr?._asyncLocalStorage;
|
|
136
|
+
if (!store || typeof store.enterWith !== "function") {
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const prev = base.getValue(PROPERTIES_CONTEXT_KEY);
|
|
140
|
+
const merged = prev ? { ...prev, ...properties } : properties;
|
|
141
|
+
store.enterWith(base.setValue(PROPERTIES_CONTEXT_KEY, merged));
|
|
142
|
+
} catch {
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function setUser(user) {
|
|
146
|
+
const properties = { [USER_ID]: user.id };
|
|
147
|
+
if (user.email !== void 0) {
|
|
148
|
+
properties[USER_EMAIL] = user.email;
|
|
149
|
+
}
|
|
150
|
+
if (user.name !== void 0) {
|
|
151
|
+
properties[USER_NAME] = user.name;
|
|
152
|
+
}
|
|
153
|
+
if (user.role !== void 0) {
|
|
154
|
+
properties[USER_ROLE] = user.role;
|
|
155
|
+
}
|
|
156
|
+
if (user.plan !== void 0) {
|
|
157
|
+
properties[USER_PLAN] = user.plan;
|
|
158
|
+
}
|
|
159
|
+
if (user.traits) {
|
|
160
|
+
for (const [key, value] of Object.entries(user.traits)) {
|
|
161
|
+
const k = `user.${key}`;
|
|
162
|
+
if (properties[k] === void 0) {
|
|
163
|
+
properties[k] = value;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
setCurrentSpanCustomProperties(properties);
|
|
168
|
+
propagatePropertiesImperatively(properties);
|
|
169
|
+
}
|
|
170
|
+
function setOrganization(org) {
|
|
171
|
+
const properties = { [ORGANIZATION_ID]: org.id };
|
|
172
|
+
if (org.name !== void 0) {
|
|
173
|
+
properties[ORGANIZATION_NAME] = org.name;
|
|
174
|
+
}
|
|
175
|
+
if (org.plan !== void 0) {
|
|
176
|
+
properties[ORGANIZATION_PLAN] = org.plan;
|
|
177
|
+
}
|
|
178
|
+
if (org.domain !== void 0) {
|
|
179
|
+
properties[ORGANIZATION_DOMAIN] = org.domain;
|
|
180
|
+
}
|
|
181
|
+
if (org.traits) {
|
|
182
|
+
for (const [key, value] of Object.entries(org.traits)) {
|
|
183
|
+
const k = `organization.${key}`;
|
|
184
|
+
if (properties[k] === void 0) {
|
|
185
|
+
properties[k] = value;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
setCurrentSpanCustomProperties(properties);
|
|
190
|
+
propagatePropertiesImperatively(properties);
|
|
191
|
+
}
|
|
192
|
+
function setMessageId(id) {
|
|
193
|
+
const properties = { [MESSAGE_ID]: id };
|
|
194
|
+
setCurrentSpanCustomProperties(properties);
|
|
195
|
+
propagatePropertiesImperatively(properties);
|
|
196
|
+
}
|
|
197
|
+
function setSessionId(id) {
|
|
198
|
+
const properties = { [SESSION_ID]: id };
|
|
199
|
+
setCurrentSpanCustomProperties(properties);
|
|
200
|
+
propagatePropertiesImperatively(properties);
|
|
201
|
+
}
|
|
202
|
+
var SERVICE_NAME_MAX_BYTES = 256;
|
|
203
|
+
function serviceNameProblem(name) {
|
|
204
|
+
if (typeof name !== "string" || name === "") {
|
|
205
|
+
return "must be a non-empty string";
|
|
206
|
+
}
|
|
207
|
+
if (/[\r\n\0]/.test(name)) {
|
|
208
|
+
return `${JSON.stringify(name)} contains CR, LF, or NUL`;
|
|
209
|
+
}
|
|
210
|
+
const byteLength = new globalThis.TextEncoder().encode(name).length;
|
|
211
|
+
if (byteLength > SERVICE_NAME_MAX_BYTES) {
|
|
212
|
+
return `is ${byteLength} bytes, over the ${SERVICE_NAME_MAX_BYTES}-byte limit`;
|
|
213
|
+
}
|
|
214
|
+
return void 0;
|
|
215
|
+
}
|
|
216
|
+
function serviceNameProperties(name) {
|
|
217
|
+
const problem = serviceNameProblem(name);
|
|
218
|
+
if (problem !== void 0) {
|
|
219
|
+
logger.warn(`Service name ${problem}; keeping the configured appName.`);
|
|
220
|
+
return {};
|
|
221
|
+
}
|
|
222
|
+
return { [SERVICE_NAME]: name };
|
|
223
|
+
}
|
|
224
|
+
function setServiceName(name) {
|
|
225
|
+
const properties = serviceNameProperties(name);
|
|
226
|
+
setCurrentSpanCustomProperties(properties);
|
|
227
|
+
propagatePropertiesImperatively(properties);
|
|
228
|
+
}
|
|
229
|
+
function callWithServiceName(name, fn, thisArg, ...args) {
|
|
230
|
+
return callWithProperties(serviceNameProperties(name), fn, thisArg, ...args);
|
|
231
|
+
}
|
|
232
|
+
function withServiceName(name, fn, thisArg) {
|
|
233
|
+
return withProperties(serviceNameProperties(name), fn, thisArg);
|
|
234
|
+
}
|
|
235
|
+
function resolveServiceNameFromContext() {
|
|
236
|
+
const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
|
|
237
|
+
return props?.[SERVICE_NAME];
|
|
238
|
+
}
|
|
239
|
+
function userProperties(user) {
|
|
240
|
+
const properties = { [USER_ID]: user.id };
|
|
241
|
+
if (user.email !== void 0) {
|
|
242
|
+
properties[USER_EMAIL] = user.email;
|
|
243
|
+
}
|
|
244
|
+
if (user.name !== void 0) {
|
|
245
|
+
properties[USER_NAME] = user.name;
|
|
246
|
+
}
|
|
247
|
+
if (user.role !== void 0) {
|
|
248
|
+
properties[USER_ROLE] = user.role;
|
|
249
|
+
}
|
|
250
|
+
if (user.plan !== void 0) {
|
|
251
|
+
properties[USER_PLAN] = user.plan;
|
|
252
|
+
}
|
|
253
|
+
if (user.traits) {
|
|
254
|
+
for (const [key, value] of Object.entries(user.traits)) {
|
|
255
|
+
const k = `user.${key}`;
|
|
256
|
+
if (properties[k] === void 0) {
|
|
257
|
+
properties[k] = value;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
return properties;
|
|
262
|
+
}
|
|
263
|
+
function organizationProperties(org) {
|
|
264
|
+
const properties = { [ORGANIZATION_ID]: org.id };
|
|
265
|
+
if (org.name !== void 0) {
|
|
266
|
+
properties[ORGANIZATION_NAME] = org.name;
|
|
267
|
+
}
|
|
268
|
+
if (org.plan !== void 0) {
|
|
269
|
+
properties[ORGANIZATION_PLAN] = org.plan;
|
|
270
|
+
}
|
|
271
|
+
if (org.domain !== void 0) {
|
|
272
|
+
properties[ORGANIZATION_DOMAIN] = org.domain;
|
|
273
|
+
}
|
|
274
|
+
if (org.traits) {
|
|
275
|
+
for (const [key, value] of Object.entries(org.traits)) {
|
|
276
|
+
const k = `organization.${key}`;
|
|
277
|
+
if (properties[k] === void 0) {
|
|
278
|
+
properties[k] = value;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
return properties;
|
|
283
|
+
}
|
|
284
|
+
function callWithUser(user, fn, thisArg, ...args) {
|
|
285
|
+
return callWithProperties(userProperties(user), fn, thisArg, ...args);
|
|
286
|
+
}
|
|
287
|
+
function withUser(user, fn, thisArg) {
|
|
288
|
+
return withProperties(userProperties(user), fn, thisArg);
|
|
289
|
+
}
|
|
290
|
+
function callWithOrganization(org, fn, thisArg, ...args) {
|
|
291
|
+
return callWithProperties(organizationProperties(org), fn, thisArg, ...args);
|
|
292
|
+
}
|
|
293
|
+
function withOrganization(org, fn, thisArg) {
|
|
294
|
+
return withProperties(organizationProperties(org), fn, thisArg);
|
|
295
|
+
}
|
|
296
|
+
function callWithMessageId(id, fn, thisArg, ...args) {
|
|
297
|
+
return callWithProperties({ [MESSAGE_ID]: id }, fn, thisArg, ...args);
|
|
298
|
+
}
|
|
299
|
+
function withMessageId(id, fn, thisArg) {
|
|
300
|
+
return withProperties({ [MESSAGE_ID]: id }, fn, thisArg);
|
|
301
|
+
}
|
|
302
|
+
function inheritedMuteTools() {
|
|
303
|
+
const properties = context.active().getValue(PROPERTIES_CONTEXT_KEY);
|
|
304
|
+
return properties?.[MUTE_TOOLS];
|
|
305
|
+
}
|
|
306
|
+
function muteProperties(options) {
|
|
307
|
+
const { input = true, output = true, tools = output } = options;
|
|
308
|
+
const properties = {};
|
|
309
|
+
if (input) {
|
|
310
|
+
properties[MUTE_INPUT] = "true";
|
|
311
|
+
}
|
|
312
|
+
if (output) {
|
|
313
|
+
properties[MUTE_OUTPUT] = "true";
|
|
314
|
+
}
|
|
315
|
+
if (tools !== output) {
|
|
316
|
+
properties[MUTE_TOOLS] = String(tools);
|
|
317
|
+
} else {
|
|
318
|
+
const inherited = inheritedMuteTools();
|
|
319
|
+
if (tools && inherited === "false") {
|
|
320
|
+
properties[MUTE_TOOLS] = "true";
|
|
321
|
+
} else if (options.tools === false && inherited === "true") {
|
|
322
|
+
properties[MUTE_TOOLS] = "false";
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
return properties;
|
|
326
|
+
}
|
|
327
|
+
function callWithMute(options, fn, thisArg, ...args) {
|
|
328
|
+
return callWithProperties(muteProperties(options), fn, thisArg, ...args);
|
|
329
|
+
}
|
|
330
|
+
function withMute(options, fn, thisArg) {
|
|
331
|
+
return withProperties(muteProperties(options), fn, thisArg);
|
|
332
|
+
}
|
|
333
|
+
function withSessionId(sessionId, fn, thisArg, extraProperties) {
|
|
334
|
+
const properties = { [SESSION_ID]: sessionId, ...extraProperties };
|
|
335
|
+
return withProperties(properties, fn, thisArg);
|
|
336
|
+
}
|
|
337
|
+
function callWithSessionId(sessionId, fn, thisArg, ...args) {
|
|
338
|
+
return callWithProperties({ [SESSION_ID]: sessionId }, fn, thisArg, ...args);
|
|
339
|
+
}
|
|
340
|
+
var Session = class {
|
|
341
|
+
span;
|
|
342
|
+
inputs = [];
|
|
343
|
+
outputs = [];
|
|
344
|
+
inputContexts = [];
|
|
345
|
+
outputContexts = [];
|
|
346
|
+
sessionId;
|
|
347
|
+
constructor(sessionId, span) {
|
|
348
|
+
this.sessionId = sessionId;
|
|
349
|
+
this.span = span;
|
|
350
|
+
}
|
|
351
|
+
/**
|
|
352
|
+
* Append a user turn to session input tracking.
|
|
353
|
+
*
|
|
354
|
+
* Each call appends one element to `brizz.session.input` (the text) AND one
|
|
355
|
+
* element to `brizz.session.input.context` (the per-turn context bag). The
|
|
356
|
+
* two arrays stay index-aligned — the ingestion pipeline zips them together
|
|
357
|
+
* so the i-th context bag lands on the i-th user_display conversation item's
|
|
358
|
+
* `span_attributes` map.
|
|
359
|
+
*
|
|
360
|
+
* @param text - Text to append (null becomes a null/"hide marker")
|
|
361
|
+
* @param context - Optional per-turn context bag to attach to this turn
|
|
362
|
+
*/
|
|
363
|
+
setInput(text, context3) {
|
|
364
|
+
this.inputs.push(text);
|
|
365
|
+
this.inputContexts.push(context3 ?? {});
|
|
366
|
+
this.span.setAttribute(SESSION_INPUT, JSON.stringify(this.inputs));
|
|
367
|
+
this.span.setAttribute(SESSION_INPUT_CONTEXT, JSON.stringify(this.inputContexts));
|
|
368
|
+
}
|
|
369
|
+
/**
|
|
370
|
+
* Append an assistant turn to session output tracking.
|
|
371
|
+
*
|
|
372
|
+
* Symmetric to {@link setInput} — appends one text element and one
|
|
373
|
+
* context-bag element to the index-aligned `brizz.session.output` /
|
|
374
|
+
* `brizz.session.output.context` arrays.
|
|
375
|
+
*
|
|
376
|
+
* @param text - Text to append (null becomes a null/"hide marker")
|
|
377
|
+
* @param context - Optional per-turn context bag to attach to this turn
|
|
378
|
+
*/
|
|
379
|
+
setOutput(text, context3) {
|
|
380
|
+
this.outputs.push(text);
|
|
381
|
+
this.outputContexts.push(context3 ?? {});
|
|
382
|
+
this.span.setAttribute(SESSION_OUTPUT, JSON.stringify(this.outputs));
|
|
383
|
+
this.span.setAttribute(SESSION_OUTPUT_CONTEXT, JSON.stringify(this.outputContexts));
|
|
384
|
+
}
|
|
385
|
+
/**
|
|
386
|
+
* Set the session title on the span.
|
|
387
|
+
*
|
|
388
|
+
* @param title - The generated title string
|
|
389
|
+
*/
|
|
390
|
+
setTitle(title) {
|
|
391
|
+
this.span.setAttribute(SESSION_TITLE, title);
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Update custom properties on the session span.
|
|
395
|
+
* Properties are prefixed with 'brizz.'.
|
|
396
|
+
*
|
|
397
|
+
* @param properties - Key-value properties to set on the session
|
|
398
|
+
*/
|
|
399
|
+
updateProperties(properties) {
|
|
400
|
+
for (const [key, value] of Object.entries(properties)) {
|
|
401
|
+
this.span.setAttribute(`${BRIZZ}.${key}`, value);
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Set end-user identity on the session span: `brizz.user.id` and, when
|
|
406
|
+
* provided, `brizz.user.email` / `brizz.user.name`. Undefined fields are omitted.
|
|
407
|
+
*
|
|
408
|
+
* @param user - User identity (`id` required; `email` / `name` optional)
|
|
409
|
+
*/
|
|
410
|
+
setUser(user) {
|
|
411
|
+
if (user.traits) {
|
|
412
|
+
for (const [key, value] of Object.entries(user.traits)) {
|
|
413
|
+
this.span.setAttribute(`${BRIZZ}.user.${key}`, value);
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
this.span.setAttribute(`${BRIZZ}.${USER_ID}`, user.id);
|
|
417
|
+
if (user.email !== void 0) {
|
|
418
|
+
this.span.setAttribute(`${BRIZZ}.${USER_EMAIL}`, user.email);
|
|
419
|
+
}
|
|
420
|
+
if (user.name !== void 0) {
|
|
421
|
+
this.span.setAttribute(`${BRIZZ}.${USER_NAME}`, user.name);
|
|
422
|
+
}
|
|
423
|
+
if (user.role !== void 0) {
|
|
424
|
+
this.span.setAttribute(`${BRIZZ}.${USER_ROLE}`, user.role);
|
|
425
|
+
}
|
|
426
|
+
if (user.plan !== void 0) {
|
|
427
|
+
this.span.setAttribute(`${BRIZZ}.${USER_PLAN}`, user.plan);
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Set organization identity on the session span: `brizz.organization.id` and,
|
|
432
|
+
* when provided, `brizz.organization.name`. Undefined fields are omitted.
|
|
433
|
+
*
|
|
434
|
+
* @param org - Organization identity (`id` required; `name` optional)
|
|
435
|
+
*/
|
|
436
|
+
setOrganization(org) {
|
|
437
|
+
if (org.traits) {
|
|
438
|
+
for (const [key, value] of Object.entries(org.traits)) {
|
|
439
|
+
this.span.setAttribute(`${BRIZZ}.organization.${key}`, value);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_ID}`, org.id);
|
|
443
|
+
if (org.name !== void 0) {
|
|
444
|
+
this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_NAME}`, org.name);
|
|
445
|
+
}
|
|
446
|
+
if (org.plan !== void 0) {
|
|
447
|
+
this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_PLAN}`, org.plan);
|
|
448
|
+
}
|
|
449
|
+
if (org.domain !== void 0) {
|
|
450
|
+
this.span.setAttribute(`${BRIZZ}.${ORGANIZATION_DOMAIN}`, org.domain);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
/**
|
|
454
|
+
* Attach an external link (URL) to this session.
|
|
455
|
+
*
|
|
456
|
+
* The link surfaces on the session's detail panel in Brizz — use it to
|
|
457
|
+
* correlate a session with an external record such as a Datadog trace,
|
|
458
|
+
* Sentry issue, or internal dashboard. Re-sending the same URL is idempotent;
|
|
459
|
+
* distinct URLs add separate links.
|
|
460
|
+
*
|
|
461
|
+
* @param url - The link target
|
|
462
|
+
* @param options - Optional `title` (defaults to the URL host) and `linkType`
|
|
463
|
+
* (free-form category, defaults to `'generic'`)
|
|
464
|
+
*/
|
|
465
|
+
addExternalLink(url, options) {
|
|
466
|
+
emitExternalLink(this.sessionId, url, options?.title, options?.linkType);
|
|
467
|
+
}
|
|
468
|
+
};
|
|
469
|
+
var SessionTitle = class {
|
|
470
|
+
span;
|
|
471
|
+
constructor(span) {
|
|
472
|
+
this.span = span;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Set the generated title on the wrapper span.
|
|
476
|
+
*
|
|
477
|
+
* @param title - The generated title string
|
|
478
|
+
*/
|
|
479
|
+
setTitle(title) {
|
|
480
|
+
this.span.setAttribute(SESSION_TITLE, title);
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
function getActiveSession() {
|
|
484
|
+
return context.active().getValue(SESSION_OBJECT_CONTEXT_KEY);
|
|
485
|
+
}
|
|
486
|
+
function resolveSessionIdFromContext() {
|
|
487
|
+
const active = getActiveSession();
|
|
488
|
+
if (active) {
|
|
489
|
+
return active.sessionId;
|
|
490
|
+
}
|
|
491
|
+
const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
|
|
492
|
+
return props?.[SESSION_ID];
|
|
493
|
+
}
|
|
494
|
+
function resolveMessageIdFromContext() {
|
|
495
|
+
const props = context.active().getValue(PROPERTIES_CONTEXT_KEY);
|
|
496
|
+
return props?.[MESSAGE_ID];
|
|
497
|
+
}
|
|
498
|
+
function emitEventWithSessionId(sessionId, name, attributes, body, severityNumber) {
|
|
499
|
+
return callWithSessionId(sessionId, () => {
|
|
500
|
+
emitEvent(name, attributes, body, severityNumber);
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
function emitExternalLink(sessionId, url, title, linkType) {
|
|
504
|
+
try {
|
|
505
|
+
emitEventWithSessionId(sessionId, EXTERNAL_LINK_EVENT_NAME, {
|
|
506
|
+
[EXTERNAL_LINK_URL]: url,
|
|
507
|
+
[EXTERNAL_LINK_TITLE]: title ?? "",
|
|
508
|
+
[EXTERNAL_LINK_TYPE]: linkType ?? "generic"
|
|
509
|
+
});
|
|
510
|
+
} catch (error) {
|
|
511
|
+
logger.warn("addExternalLink: failed to emit external link", error);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
function addExternalLink(url, options) {
|
|
515
|
+
const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
|
|
516
|
+
if (!sessionId) {
|
|
517
|
+
logger.warn(
|
|
518
|
+
"addExternalLink called without a resolvable session id; link dropped. Pass options.sessionId or call inside a startSession/callWithSessionId scope."
|
|
519
|
+
);
|
|
520
|
+
return;
|
|
521
|
+
}
|
|
522
|
+
emitExternalLink(sessionId, url, options?.title, options?.linkType);
|
|
523
|
+
}
|
|
524
|
+
function recordFeedback(type, options) {
|
|
525
|
+
const eventAttributes = { [FEEDBACK_TYPE]: type };
|
|
526
|
+
if (options?.score !== void 0) {
|
|
527
|
+
eventAttributes[FEEDBACK_SCORE] = options.score;
|
|
528
|
+
}
|
|
529
|
+
if (options?.reason !== void 0) {
|
|
530
|
+
eventAttributes[FEEDBACK_REASON] = options.reason;
|
|
531
|
+
}
|
|
532
|
+
if (options?.comment !== void 0) {
|
|
533
|
+
eventAttributes[FEEDBACK_COMMENT] = options.comment;
|
|
534
|
+
}
|
|
535
|
+
if (options?.source !== void 0) {
|
|
536
|
+
eventAttributes[FEEDBACK_SOURCE] = options.source;
|
|
537
|
+
}
|
|
538
|
+
if (options?.attributes) {
|
|
539
|
+
for (const [key, value] of Object.entries(options.attributes)) {
|
|
540
|
+
const k = `${FEEDBACK_ATTR_PREFIX}${key}`;
|
|
541
|
+
if (eventAttributes[k] === void 0) {
|
|
542
|
+
eventAttributes[k] = value;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
const messageId = options?.messageId ?? resolveMessageIdFromContext();
|
|
547
|
+
const sessionId = options?.sessionId ?? resolveSessionIdFromContext();
|
|
548
|
+
if (messageId === void 0 && sessionId === void 0) {
|
|
549
|
+
logger.warn(
|
|
550
|
+
"recordFeedback called with no resolvable message id or session id; the feedback cannot be attributed to a message or conversation. Pass options.messageId / options.sessionId or call inside a startSession/callWithMessageId scope."
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
const anchor = {};
|
|
554
|
+
if (messageId !== void 0) {
|
|
555
|
+
anchor[MESSAGE_ID] = messageId;
|
|
556
|
+
}
|
|
557
|
+
if (sessionId !== void 0) {
|
|
558
|
+
anchor[SESSION_ID] = sessionId;
|
|
559
|
+
}
|
|
560
|
+
try {
|
|
561
|
+
if (Object.keys(anchor).length === 0) {
|
|
562
|
+
emitEvent(FEEDBACK_EVENT_NAME, eventAttributes);
|
|
563
|
+
} else {
|
|
564
|
+
callWithProperties(anchor, () => emitEvent(FEEDBACK_EVENT_NAME, eventAttributes));
|
|
565
|
+
}
|
|
566
|
+
} catch (error) {
|
|
567
|
+
logger.warn("recordFeedback: failed to emit feedback event", error);
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
var METRIC_NAME_PATTERN = /^[a-z][a-z0-9_.-]{0,63}$/;
|
|
571
|
+
var METRIC_COMMENT_MAX_LEN = 4096;
|
|
572
|
+
var METRIC_ATTRIBUTES_MAX = 20;
|
|
573
|
+
var METRIC_ATTRIBUTE_VALUE_MAX_LEN = 256;
|
|
574
|
+
function recordMetric(options) {
|
|
575
|
+
try {
|
|
576
|
+
recordMetricImpl(options);
|
|
577
|
+
} catch (error) {
|
|
578
|
+
logger.warn(`recordMetric(${JSON.stringify(options?.name)}) failed; metric dropped.`, error);
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
function recordMetricImpl(options) {
|
|
582
|
+
const name = typeof options.name === "string" ? options.name.toLowerCase() : "";
|
|
583
|
+
if (!METRIC_NAME_PATTERN.test(name)) {
|
|
584
|
+
logger.warn(
|
|
585
|
+
`recordMetric called with an invalid name ${JSON.stringify(options.name)}; metric dropped. Names must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
|
|
586
|
+
);
|
|
587
|
+
return;
|
|
588
|
+
}
|
|
589
|
+
if (RESERVED_METRIC_NAMES.has(name)) {
|
|
590
|
+
logger.warn(
|
|
591
|
+
`recordMetric called with the reserved name ${JSON.stringify(name)}; metric dropped. Brizz computes this metric itself \u2014 pick a different name.`
|
|
592
|
+
);
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
const { value } = options;
|
|
596
|
+
let numericValue;
|
|
597
|
+
if (typeof value === "boolean") {
|
|
598
|
+
numericValue = value ? 1 : 0;
|
|
599
|
+
} else if (typeof value === "number" && Number.isFinite(value)) {
|
|
600
|
+
numericValue = value;
|
|
601
|
+
} else {
|
|
602
|
+
logger.warn(
|
|
603
|
+
`recordMetric(${name}) called with a non-finite or non-numeric value ${JSON.stringify(value)}; metric dropped.`
|
|
604
|
+
);
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (options.serviceName !== void 0) {
|
|
608
|
+
const problem = serviceNameProblem(options.serviceName);
|
|
609
|
+
if (problem !== void 0) {
|
|
610
|
+
logger.warn(`recordMetric(${name}) service name ${problem}; metric dropped.`);
|
|
611
|
+
return;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
const scope = options.scope ?? METRIC_SCOPE_SESSION;
|
|
615
|
+
if (scope !== METRIC_SCOPE_SESSION && scope !== METRIC_SCOPE_TRACE) {
|
|
616
|
+
logger.warn(
|
|
617
|
+
`recordMetric(${name}) called with an invalid scope ${JSON.stringify(scope)}; expected '${METRIC_SCOPE_SESSION}' or '${METRIC_SCOPE_TRACE}'. Metric dropped.`
|
|
618
|
+
);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const eventAttributes = {
|
|
622
|
+
[METRIC_NAME]: name,
|
|
623
|
+
[METRIC_VALUE]: numericValue
|
|
624
|
+
};
|
|
625
|
+
if (options.scope !== void 0) {
|
|
626
|
+
eventAttributes[METRIC_SCOPE] = scope;
|
|
627
|
+
}
|
|
628
|
+
if (options.unit !== void 0) {
|
|
629
|
+
eventAttributes[METRIC_UNIT] = options.unit;
|
|
630
|
+
}
|
|
631
|
+
if (options.minValue !== void 0) {
|
|
632
|
+
eventAttributes[METRIC_MIN] = options.minValue;
|
|
633
|
+
}
|
|
634
|
+
if (options.maxValue !== void 0) {
|
|
635
|
+
eventAttributes[METRIC_MAX] = options.maxValue;
|
|
636
|
+
}
|
|
637
|
+
if (options.comment !== void 0) {
|
|
638
|
+
let comment = options.comment;
|
|
639
|
+
if (comment.length > METRIC_COMMENT_MAX_LEN) {
|
|
640
|
+
logger.warn(
|
|
641
|
+
`recordMetric(${name}) comment exceeds ${METRIC_COMMENT_MAX_LEN} characters; truncated.`
|
|
642
|
+
);
|
|
643
|
+
comment = comment.slice(0, METRIC_COMMENT_MAX_LEN);
|
|
644
|
+
}
|
|
645
|
+
eventAttributes[METRIC_COMMENT] = comment;
|
|
646
|
+
}
|
|
647
|
+
if (options.polarity !== void 0) {
|
|
648
|
+
const polarity = options.polarity;
|
|
649
|
+
if (polarity === METRIC_POLARITY_POSITIVE || polarity === METRIC_POLARITY_NEGATIVE) {
|
|
650
|
+
eventAttributes[METRIC_POLARITY] = polarity;
|
|
651
|
+
} else {
|
|
652
|
+
logger.warn(
|
|
653
|
+
`recordMetric(${name}) called with an invalid polarity ${JSON.stringify(polarity)}; expected '${METRIC_POLARITY_POSITIVE}' or '${METRIC_POLARITY_NEGATIVE}'. Emitting the metric without it.`
|
|
654
|
+
);
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
if (options.timestamp !== void 0) {
|
|
658
|
+
if (Number.isFinite(options.timestamp.getTime())) {
|
|
659
|
+
eventAttributes[METRIC_TIMESTAMP] = options.timestamp.toISOString();
|
|
660
|
+
} else {
|
|
661
|
+
logger.warn(
|
|
662
|
+
`recordMetric(${name}) called with an invalid timestamp; emitting the metric without it.`
|
|
663
|
+
);
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (options.attributes) {
|
|
667
|
+
let accepted = 0;
|
|
668
|
+
for (const [key, attrValue] of Object.entries(options.attributes)) {
|
|
669
|
+
if (accepted >= METRIC_ATTRIBUTES_MAX) {
|
|
670
|
+
logger.warn(
|
|
671
|
+
`recordMetric(${name}) called with more than ${METRIC_ATTRIBUTES_MAX} attributes; the excess was dropped.`
|
|
672
|
+
);
|
|
673
|
+
break;
|
|
674
|
+
}
|
|
675
|
+
const normalizedKey = key.toLowerCase();
|
|
676
|
+
if (!METRIC_NAME_PATTERN.test(normalizedKey)) {
|
|
677
|
+
logger.warn(
|
|
678
|
+
`recordMetric(${name}) called with an invalid attribute key ${JSON.stringify(key)}; that attribute was dropped. Keys must match ${METRIC_NAME_PATTERN.source} after lowercasing.`
|
|
679
|
+
);
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
let text = typeof attrValue === "string" ? attrValue : String(attrValue);
|
|
683
|
+
if (text.length > METRIC_ATTRIBUTE_VALUE_MAX_LEN) {
|
|
684
|
+
logger.warn(
|
|
685
|
+
`recordMetric(${name}) attribute ${JSON.stringify(normalizedKey)} exceeds ${METRIC_ATTRIBUTE_VALUE_MAX_LEN} characters; truncated.`
|
|
686
|
+
);
|
|
687
|
+
text = text.slice(0, METRIC_ATTRIBUTE_VALUE_MAX_LEN);
|
|
688
|
+
}
|
|
689
|
+
eventAttributes[`${METRIC_ATTRIBUTE_PREFIX}${normalizedKey}`] = text;
|
|
690
|
+
accepted += 1;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
const traceId = typeof options.traceId === "string" && options.traceId !== "" ? options.traceId : void 0;
|
|
694
|
+
if (traceId !== void 0) {
|
|
695
|
+
eventAttributes[METRIC_TRACE_ID] = traceId;
|
|
696
|
+
}
|
|
697
|
+
if (scope === METRIC_SCOPE_TRACE && traceId === void 0) {
|
|
698
|
+
const spanContext = trace.getActiveSpan()?.spanContext();
|
|
699
|
+
if (!spanContext || !isSpanContextValid(spanContext)) {
|
|
700
|
+
logger.warn(
|
|
701
|
+
`recordMetric(${name}) called with scope 'trace' but no trace; metric dropped. Pass options.traceId, or call inside the span of the trace being scored.`
|
|
702
|
+
);
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
eventAttributes[METRIC_TRACE_ID] = spanContext.traceId;
|
|
706
|
+
}
|
|
707
|
+
const sessionId = options.sessionId ?? (traceId === void 0 ? resolveSessionIdFromContext() : void 0);
|
|
708
|
+
if (sessionId === void 0 && traceId === void 0) {
|
|
709
|
+
logger.warn(
|
|
710
|
+
`recordMetric(${name}) called with no resolvable session id or trace id; the metric cannot be attributed to a conversation and is dropped. Pass options.sessionId or options.traceId, or call inside a startSession/callWithSessionId scope.`
|
|
711
|
+
);
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
const base = context.active();
|
|
715
|
+
const ambient = base.getValue(PROPERTIES_CONTEXT_KEY);
|
|
716
|
+
const properties = { ...ambient };
|
|
717
|
+
if (sessionId === void 0) {
|
|
718
|
+
delete properties[SESSION_ID];
|
|
719
|
+
delete properties[MESSAGE_ID];
|
|
720
|
+
} else {
|
|
721
|
+
properties[SESSION_ID] = sessionId;
|
|
722
|
+
}
|
|
723
|
+
if (options.serviceName !== void 0) {
|
|
724
|
+
properties[SERVICE_NAME] = options.serviceName;
|
|
725
|
+
}
|
|
726
|
+
try {
|
|
727
|
+
context.with(
|
|
728
|
+
base.setValue(PROPERTIES_CONTEXT_KEY, properties),
|
|
729
|
+
() => emitEvent(METRIC_EVENT_NAME, eventAttributes)
|
|
730
|
+
);
|
|
731
|
+
} catch (error) {
|
|
732
|
+
logger.warn("recordMetric: failed to emit metric event", error);
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
function startSession(sessionId, callback, extraProperties, options) {
|
|
736
|
+
const isTitle = options?.mode === "title";
|
|
737
|
+
const spanName = isTitle ? SESSION_TITLE_SPAN_NAME : SESSION_SPAN_NAME;
|
|
738
|
+
return sessionTracer.startActiveSpan(spanName, (span) => {
|
|
739
|
+
span.setAttribute(`${BRIZZ}.${SESSION_ID}`, sessionId);
|
|
740
|
+
if (extraProperties) {
|
|
741
|
+
for (const [key, value] of Object.entries(extraProperties)) {
|
|
742
|
+
span.setAttribute(`${BRIZZ}.${key}`, value);
|
|
743
|
+
}
|
|
744
|
+
}
|
|
745
|
+
const session = new Session(sessionId, span);
|
|
746
|
+
const contextProperties = { [SESSION_ID]: sessionId };
|
|
747
|
+
if (isTitle) {
|
|
748
|
+
contextProperties[SESSION_TITLE_GENERATION] = "true";
|
|
749
|
+
}
|
|
750
|
+
if (extraProperties) {
|
|
751
|
+
for (const [key, value] of Object.entries(extraProperties)) {
|
|
752
|
+
contextProperties[key] = String(value);
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
return callWithProperties(contextProperties, () => {
|
|
756
|
+
const sessionCtx = context.active().setValue(SESSION_OBJECT_CONTEXT_KEY, session);
|
|
757
|
+
return context.with(sessionCtx, () => {
|
|
758
|
+
try {
|
|
759
|
+
const result = callback(session);
|
|
760
|
+
if (result && typeof result.then === "function") {
|
|
761
|
+
return result.then((value) => {
|
|
762
|
+
span.end();
|
|
763
|
+
return value;
|
|
764
|
+
}).catch((error) => {
|
|
765
|
+
span.recordException(error);
|
|
766
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
767
|
+
span.end();
|
|
768
|
+
throw error;
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
span.end();
|
|
772
|
+
return result;
|
|
773
|
+
} catch (error) {
|
|
774
|
+
span.recordException(error);
|
|
775
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
776
|
+
span.end();
|
|
777
|
+
throw error;
|
|
778
|
+
}
|
|
779
|
+
});
|
|
780
|
+
});
|
|
781
|
+
});
|
|
782
|
+
}
|
|
783
|
+
function startSessionTitle(callback, options) {
|
|
784
|
+
const resolvedSessionId = options?.sessionId ?? getActiveSession()?.sessionId;
|
|
785
|
+
return sessionTracer.startActiveSpan(SESSION_TITLE_SPAN_NAME, (span) => {
|
|
786
|
+
if (resolvedSessionId) {
|
|
787
|
+
span.setAttribute(`${BRIZZ}.${SESSION_ID}`, resolvedSessionId);
|
|
788
|
+
}
|
|
789
|
+
const sessionTitle = new SessionTitle(span);
|
|
790
|
+
const properties = { [SESSION_TITLE_GENERATION]: "true" };
|
|
791
|
+
if (resolvedSessionId) {
|
|
792
|
+
properties[SESSION_ID] = resolvedSessionId;
|
|
793
|
+
}
|
|
794
|
+
return callWithProperties(properties, () => {
|
|
795
|
+
try {
|
|
796
|
+
const result = callback(sessionTitle);
|
|
797
|
+
if (result && typeof result.then === "function") {
|
|
798
|
+
return result.then((value) => {
|
|
799
|
+
span.end();
|
|
800
|
+
return value;
|
|
801
|
+
}).catch((error) => {
|
|
802
|
+
span.recordException(error);
|
|
803
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
804
|
+
span.end();
|
|
805
|
+
throw error;
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
span.end();
|
|
809
|
+
return result;
|
|
810
|
+
} catch (error) {
|
|
811
|
+
span.recordException(error);
|
|
812
|
+
span.setStatus({ code: SpanStatusCode.ERROR });
|
|
813
|
+
span.end();
|
|
814
|
+
throw error;
|
|
815
|
+
}
|
|
816
|
+
});
|
|
817
|
+
});
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// src/internal/trace/agent.ts
|
|
821
|
+
import { randomUUID } from "crypto";
|
|
822
|
+
import { context as context2 } from "@opentelemetry/api";
|
|
823
|
+
function newInstanceId() {
|
|
824
|
+
return randomUUID().replaceAll("-", "").slice(0, 8);
|
|
825
|
+
}
|
|
826
|
+
function activeProperties() {
|
|
827
|
+
return context2.active().getValue(PROPERTIES_CONTEXT_KEY) ?? {};
|
|
828
|
+
}
|
|
829
|
+
function encodeToken(agent) {
|
|
830
|
+
const payload = {
|
|
831
|
+
id: agent.id,
|
|
832
|
+
parentId: agent.parentId,
|
|
833
|
+
name: agent.name,
|
|
834
|
+
traceparent: agent.traceparent,
|
|
835
|
+
sessionId: agent.sessionId
|
|
836
|
+
};
|
|
837
|
+
return Buffer.from(JSON.stringify(payload), "utf8").toString("base64url");
|
|
838
|
+
}
|
|
839
|
+
function currentTraceparent() {
|
|
840
|
+
const carrier = {};
|
|
841
|
+
try {
|
|
842
|
+
injectTraceContext(context2.active(), carrier);
|
|
843
|
+
} catch {
|
|
844
|
+
}
|
|
845
|
+
return carrier["traceparent"] ?? "";
|
|
846
|
+
}
|
|
847
|
+
function agentHandle(id, parentId, name) {
|
|
848
|
+
const opened = {
|
|
849
|
+
id,
|
|
850
|
+
parentId,
|
|
851
|
+
name,
|
|
852
|
+
traceparent: currentTraceparent(),
|
|
853
|
+
sessionId: activeProperties()[SESSION_ID] ?? ""
|
|
854
|
+
};
|
|
855
|
+
return {
|
|
856
|
+
...opened,
|
|
857
|
+
get token() {
|
|
858
|
+
return encodeToken(opened);
|
|
859
|
+
}
|
|
860
|
+
};
|
|
861
|
+
}
|
|
862
|
+
function decodeToken(token) {
|
|
863
|
+
try {
|
|
864
|
+
const payload = JSON.parse(Buffer.from(token, "base64url").toString("utf8"));
|
|
865
|
+
return payload.id ? payload : void 0;
|
|
866
|
+
} catch {
|
|
867
|
+
return void 0;
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
function unreadableAgent(agent) {
|
|
871
|
+
return {
|
|
872
|
+
id: "",
|
|
873
|
+
parentId: "",
|
|
874
|
+
name: "",
|
|
875
|
+
traceparent: "",
|
|
876
|
+
sessionId: "",
|
|
877
|
+
token: typeof agent === "string" ? "" : agent.token ?? ""
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
function resolveAgent(agent) {
|
|
881
|
+
const options = typeof agent === "string" ? { name: agent } : agent;
|
|
882
|
+
let id;
|
|
883
|
+
let parentId;
|
|
884
|
+
let name;
|
|
885
|
+
let sessionId = "";
|
|
886
|
+
let parentContext = context2.active();
|
|
887
|
+
if (options.token === void 0) {
|
|
888
|
+
id = options.id || newInstanceId();
|
|
889
|
+
parentId = options.parentId || activeProperties()[AGENT_ID] || "";
|
|
890
|
+
name = options.name ?? "";
|
|
891
|
+
} else {
|
|
892
|
+
const decoded = decodeToken(options.token);
|
|
893
|
+
if (!decoded) {
|
|
894
|
+
logger.warn("Brizz: ignoring an unreadable agent token");
|
|
895
|
+
return void 0;
|
|
896
|
+
}
|
|
897
|
+
id = decoded.id;
|
|
898
|
+
parentId = decoded.parentId;
|
|
899
|
+
name = decoded.name;
|
|
900
|
+
sessionId = decoded.sessionId;
|
|
901
|
+
if (decoded.traceparent) {
|
|
902
|
+
try {
|
|
903
|
+
parentContext = extractTraceContext(parentContext, { traceparent: decoded.traceparent });
|
|
904
|
+
} catch {
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
const properties = { [AGENT_ID]: id, [AGENT_NAME]: name };
|
|
909
|
+
if (parentId) {
|
|
910
|
+
properties[AGENT_PARENT_ID] = parentId;
|
|
911
|
+
}
|
|
912
|
+
if (sessionId) {
|
|
913
|
+
properties[SESSION_ID] = sessionId;
|
|
914
|
+
}
|
|
915
|
+
return { id, parentId, name, properties, parentContext };
|
|
916
|
+
}
|
|
917
|
+
function startAgent(agent, callback) {
|
|
918
|
+
const resolved = resolveAgent(agent);
|
|
919
|
+
if (!resolved) {
|
|
920
|
+
return callback(unreadableAgent(agent));
|
|
921
|
+
}
|
|
922
|
+
const { id, parentId, name, properties, parentContext } = resolved;
|
|
923
|
+
return context2.with(
|
|
924
|
+
parentContext,
|
|
925
|
+
() => callWithProperties(properties, () => callback(agentHandle(id, parentId, name)))
|
|
926
|
+
);
|
|
927
|
+
}
|
|
928
|
+
function withAgent(agent, fn, thisArg) {
|
|
929
|
+
return function wrapped(...args) {
|
|
930
|
+
return startAgent(
|
|
931
|
+
agent,
|
|
932
|
+
() => fn.apply(thisArg !== void 0 ? thisArg : this, args)
|
|
933
|
+
);
|
|
934
|
+
};
|
|
935
|
+
}
|
|
936
|
+
function setAgent(agent) {
|
|
937
|
+
const resolved = resolveAgent(agent);
|
|
938
|
+
if (!resolved) {
|
|
939
|
+
return unreadableAgent(agent);
|
|
940
|
+
}
|
|
941
|
+
const { id, parentId, name, properties, parentContext } = resolved;
|
|
942
|
+
setCurrentSpanCustomProperties(properties);
|
|
943
|
+
propagatePropertiesImperatively(properties, parentContext);
|
|
944
|
+
return agentHandle(id, parentId, name);
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
export {
|
|
948
|
+
setEventSink,
|
|
949
|
+
clearEventSink,
|
|
950
|
+
emitEvent,
|
|
951
|
+
setCurrentSpanCustomProperties,
|
|
952
|
+
callWithProperties,
|
|
953
|
+
withProperties,
|
|
954
|
+
setUser,
|
|
955
|
+
setOrganization,
|
|
956
|
+
setMessageId,
|
|
957
|
+
setSessionId,
|
|
958
|
+
setServiceName,
|
|
959
|
+
callWithServiceName,
|
|
960
|
+
withServiceName,
|
|
961
|
+
resolveServiceNameFromContext,
|
|
962
|
+
callWithUser,
|
|
963
|
+
withUser,
|
|
964
|
+
callWithOrganization,
|
|
965
|
+
withOrganization,
|
|
966
|
+
callWithMessageId,
|
|
967
|
+
withMessageId,
|
|
968
|
+
callWithMute,
|
|
969
|
+
withMute,
|
|
970
|
+
withSessionId,
|
|
971
|
+
callWithSessionId,
|
|
972
|
+
Session,
|
|
973
|
+
SessionTitle,
|
|
974
|
+
getActiveSession,
|
|
975
|
+
emitEventWithSessionId,
|
|
976
|
+
addExternalLink,
|
|
977
|
+
recordFeedback,
|
|
978
|
+
recordMetric,
|
|
979
|
+
startSession,
|
|
980
|
+
startSessionTitle,
|
|
981
|
+
startAgent,
|
|
982
|
+
withAgent,
|
|
983
|
+
setAgent
|
|
984
|
+
};
|