@withgateway/sdk 0.1.4 → 0.1.6
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/dist/index-DnowA8MG.d.mts +447 -0
- package/dist/index-DnowA8MG.d.ts +447 -0
- package/dist/index.d.mts +6 -1
- package/dist/index.d.ts +6 -1
- package/dist/index.js +1551 -33
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1511 -27
- package/dist/index.mjs.map +1 -1
- package/dist/personas/index.d.mts +102 -0
- package/dist/personas/index.d.ts +102 -0
- package/dist/personas/index.js +205 -0
- package/dist/personas/index.js.map +1 -0
- package/dist/personas/index.mjs +180 -0
- package/dist/personas/index.mjs.map +1 -0
- package/dist/replay/index.d.mts +351 -0
- package/dist/replay/index.d.ts +351 -0
- package/dist/replay/index.js +1094 -0
- package/dist/replay/index.js.map +1 -0
- package/dist/replay/index.mjs +1057 -0
- package/dist/replay/index.mjs.map +1 -0
- package/dist/sessions/index.d.mts +143 -0
- package/dist/sessions/index.d.ts +143 -0
- package/dist/sessions/index.js +320 -0
- package/dist/sessions/index.js.map +1 -0
- package/dist/sessions/index.mjs +288 -0
- package/dist/sessions/index.mjs.map +1 -0
- package/dist/tracing/index.d.mts +3 -1
- package/dist/tracing/index.d.ts +3 -1
- package/dist/tracing/index.js +277 -31
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +266 -26
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/users/index.d.mts +81 -0
- package/dist/users/index.d.ts +81 -0
- package/dist/users/index.js +168 -0
- package/dist/users/index.js.map +1 -0
- package/dist/users/index.mjs +144 -0
- package/dist/users/index.mjs.map +1 -0
- package/package.json +21 -1
- package/dist/index-yJgb8wh6.d.mts +0 -273
- package/dist/index-yJgb8wh6.d.ts +0 -273
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/sessions/index.ts"],"sourcesContent":["/**\n * Load Gateway sessions for replay and test-fixture generation.\n *\n * The premier workflow: pull a real production session from the platform and\n * turn it into a regression test in your repo.\n *\n * ```typescript\n * import { loadSession } from \"@withgateway/sdk/sessions\";\n *\n * const session = await loadSession(\"session-id\"); // env-configured Gateway\n * for (const turn of session.turns()) { // (input, output) per trace\n * const result = await myAgent(turn.input);\n * assert.deepEqual(result, turn.output); // or fuzzier assertions\n * }\n *\n * session.toFixture(\"tests/fixtures/checkout_regression.json\");\n * ```\n *\n * Auth/config mirror the tracing exporter: GATEWAY_HOST, GATEWAY_PUBLIC_KEY,\n * GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey explicitly). Data comes\n * from `GET /api/public/sessions/{id}?includeIO=true` — one call, full\n * untruncated input/output for every trace and observation.\n *\n * Mirrors the Python SDK's `gatewaysdk.sessions` module.\n */\n\nimport { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\n\nexport const ENV_GATEWAY_HOST = \"GATEWAY_HOST\";\nexport const ENV_GATEWAY_PUBLIC_KEY = \"GATEWAY_PUBLIC_KEY\";\nexport const ENV_GATEWAY_SECRET_KEY = \"GATEWAY_SECRET_KEY\";\n\nexport const DEFAULT_TIMEOUT_SECONDS = 30;\n\n/** Raised when a session cannot be loaded from Gateway. */\nexport class SessionLoadError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"SessionLoadError\";\n this.cause = options?.cause;\n }\n}\n\n/** One observation (LLM generation, tool call, span) with full IO. */\nexport type SessionObservation = {\n id: string;\n type: string | null;\n name: string | null;\n level: string | null;\n statusMessage: string | null;\n model: string | null;\n input: unknown;\n output: unknown;\n metadata: unknown;\n parentObservationId: string | null;\n startTime: string | null;\n endTime: string | null;\n};\n\nexport function sessionObservationFromApi(\n raw: Record<string, unknown>,\n): SessionObservation {\n return {\n id: String(raw.id ?? \"\"),\n type: asStringOrNull(raw.type),\n name: asStringOrNull(raw.name),\n level: asStringOrNull(raw.level),\n statusMessage: asStringOrNull(raw.statusMessage),\n model: asStringOrNull(raw.model),\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n parentObservationId: asStringOrNull(raw.parentObservationId),\n startTime: raw.startTime ? String(raw.startTime) : null,\n endTime: raw.endTime ? String(raw.endTime) : null,\n };\n}\n\ntype SessionTraceFields = {\n id: string;\n name: string | null;\n timestamp: string | null;\n input: unknown;\n output: unknown;\n metadata?: unknown;\n tags?: string[];\n observations?: SessionObservation[];\n};\n\n/** One trace (agent turn) in the session, with full IO + observations. */\nexport class SessionTrace {\n readonly id: string;\n readonly name: string | null;\n readonly timestamp: string | null;\n readonly input: unknown;\n readonly output: unknown;\n readonly metadata: unknown;\n readonly tags: string[];\n readonly observations: SessionObservation[];\n\n constructor(fields: SessionTraceFields) {\n this.id = fields.id;\n this.name = fields.name;\n this.timestamp = fields.timestamp;\n this.input = fields.input;\n this.output = fields.output;\n this.metadata = fields.metadata ?? null;\n this.tags = fields.tags ?? [];\n this.observations = fields.observations ?? [];\n }\n\n get toolCalls(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"TOOL\",\n );\n }\n\n get generations(): SessionObservation[] {\n return this.observations.filter(\n (o) => (o.type ?? \"\").toUpperCase() === \"GENERATION\",\n );\n }\n\n /**\n * The user message that started this turn.\n *\n * Handles the common recorded shapes: a plain string input, an OpenAI\n * message list (last role=user entry wins — earlier ones are carried\n * history), or an object with a content/input field.\n */\n userMessage(): string | null {\n const value = this.input;\n if (typeof value === \"string\") {\n return value;\n }\n if (Array.isArray(value)) {\n for (let i = value.length - 1; i >= 0; i--) {\n const entry = value[i];\n if (isPlainObject(entry) && entry.role === \"user\") {\n const content = entry.content;\n if (typeof content === \"string\") {\n return content;\n }\n if (Array.isArray(content)) {\n // content-part lists\n const parts = content\n .filter(isPlainObject)\n .map((part) => (typeof part.text === \"string\" ? part.text : \"\"));\n return parts.join(\"\") || null;\n }\n }\n }\n return null;\n }\n if (isPlainObject(value)) {\n for (const key of [\"content\", \"input\", \"text\", \"message\"]) {\n if (typeof value[key] === \"string\") {\n return value[key] as string;\n }\n }\n }\n return null;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionTrace {\n return new SessionTrace({\n id: String(raw.id ?? \"\"),\n name: asStringOrNull(raw.name),\n timestamp: raw.timestamp ? String(raw.timestamp) : null,\n input: raw.input,\n output: raw.output,\n metadata: raw.metadata ?? null,\n tags: Array.isArray(raw.tags) ? raw.tags.map(String) : [],\n observations: (Array.isArray(raw.observations) ? raw.observations : [])\n .filter(isPlainObject)\n .map(sessionObservationFromApi),\n });\n }\n}\n\ntype SessionRecordingFields = {\n sessionId: string;\n projectId: string | null;\n environment: string | null;\n traces?: SessionTrace[];\n};\n\ntype SelectFilter = {\n type?: string;\n name?: string;\n level?: string;\n};\n\n/** A fully-loaded session: every trace, every observation, full IO. */\nexport class SessionRecording {\n readonly sessionId: string;\n readonly projectId: string | null;\n readonly environment: string | null;\n readonly traces: SessionTrace[];\n\n constructor(fields: SessionRecordingFields) {\n this.sessionId = fields.sessionId;\n this.projectId = fields.projectId;\n this.environment = fields.environment;\n this.traces = fields.traces ?? [];\n }\n\n /** Traces in chronological order — one per agent turn. */\n turns(): SessionTrace[] {\n return [...this.traces].sort((a, b) => {\n const left = a.timestamp ?? \"\";\n const right = b.timestamp ?? \"\";\n return left < right ? -1 : left > right ? 1 : 0;\n });\n }\n\n /** The nth chronological turn (negative indices allowed). */\n turn(index: number): SessionTrace {\n const ordered = this.turns();\n const found = ordered.at(index);\n if (!found) {\n throw new RangeError(\n `Turn index ${index} out of range (session has ${ordered.length} turns)`,\n );\n }\n return found;\n }\n\n /**\n * The user message of each turn, in order — feed these back to an agent\n * to re-drive the recorded conversation.\n */\n userMessages(): Array<string | null> {\n return this.turns().map((trace) => trace.userMessage());\n }\n\n /** Output of the last chronological turn (null when empty). */\n finalOutput(): unknown {\n const ordered = this.turns();\n return ordered.length > 0 ? ordered[ordered.length - 1].output : null;\n }\n\n /** Every TOOL observation across the session, chronological. */\n toolCalls(): SessionObservation[] {\n return this.select({ type: \"TOOL\" });\n }\n\n /** Every GENERATION observation across the session, chronological. */\n generations(): SessionObservation[] {\n return this.select({ type: \"GENERATION\" });\n }\n\n /** Filter observations across all turns (chronological order). */\n select(filter: SelectFilter = {}): SessionObservation[] {\n const selected: SessionObservation[] = [];\n for (const trace of this.turns()) {\n for (const observation of trace.observations) {\n if (\n filter.type &&\n (observation.type ?? \"\").toUpperCase() !== filter.type.toUpperCase()\n ) {\n continue;\n }\n if (filter.name && observation.name !== filter.name) {\n continue;\n }\n if (\n filter.level &&\n (observation.level ?? \"\").toUpperCase() !== filter.level.toUpperCase()\n ) {\n continue;\n }\n selected.push(observation);\n }\n }\n return selected;\n }\n\n toJSON(): Record<string, unknown> {\n return {\n sessionId: this.sessionId,\n projectId: this.projectId,\n environment: this.environment,\n traces: this.turns().map((trace) => ({\n id: trace.id,\n name: trace.name,\n timestamp: trace.timestamp,\n input: trace.input,\n output: trace.output,\n metadata: trace.metadata,\n tags: trace.tags,\n observations: trace.observations.map((o) => ({ ...o })),\n })),\n };\n }\n\n /** Dump the full session as a JSON fixture (for regression tests). */\n toFixture(path: string): string {\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, JSON.stringify(this.toJSON(), null, 2), \"utf-8\");\n return path;\n }\n\n static fromApi(raw: Record<string, unknown>): SessionRecording {\n return new SessionRecording({\n sessionId: String(raw.id ?? \"\"),\n projectId: asStringOrNull(raw.projectId),\n environment: asStringOrNull(raw.environment),\n traces: (Array.isArray(raw.traces) ? raw.traces : [])\n .filter(isPlainObject)\n .map(SessionTrace.fromApi),\n });\n }\n}\n\nexport type LoadSessionOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\n/**\n * Load a full session (all traces + observations, untruncated IO).\n *\n * Credentials default to the same environment variables the tracing\n * exporter uses: GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY.\n */\nexport async function loadSession(\n sessionId: string,\n options: LoadSessionOptions = {},\n): Promise<SessionRecording> {\n const host = (options.host ?? process.env[ENV_GATEWAY_HOST] ?? \"\").replace(\n /\\/+$/,\n \"\",\n );\n const publicKey =\n options.publicKey ?? process.env[ENV_GATEWAY_PUBLIC_KEY] ?? \"\";\n const secretKey =\n options.secretKey ?? process.env[ENV_GATEWAY_SECRET_KEY] ?? \"\";\n const timeoutSeconds = options.timeoutSeconds ?? DEFAULT_TIMEOUT_SECONDS;\n if (!host || !publicKey || !secretKey) {\n throw new SessionLoadError(\n \"Gateway is not configured — set GATEWAY_HOST, GATEWAY_PUBLIC_KEY \" +\n \"and GATEWAY_SECRET_KEY (or pass host/publicKey/secretKey).\",\n );\n }\n\n const url = `${host}/api/public/sessions/${encodeURIComponent(sessionId)}?includeIO=true`;\n let response: Response;\n try {\n response = await fetch(url, {\n method: \"GET\",\n headers: { Authorization: basicAuthHeader(publicKey, secretKey) },\n signal: AbortSignal.timeout(timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n if (response.status === 404) {\n throw new SessionLoadError(`Session not found: ${sessionId}`);\n }\n const text = await response.text();\n if (!response.ok) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n let payload: unknown;\n try {\n payload = JSON.parse(text);\n } catch (error) {\n throw new SessionLoadError(\n `Failed to load session ${sessionId}: response is not valid JSON`,\n { cause: error },\n );\n }\n return SessionRecording.fromApi(\n isPlainObject(payload) ? payload : {},\n );\n}\n\nexport function basicAuthHeader(publicKey: string, secretKey: string): string {\n return `Basic ${Buffer.from(`${publicKey}:${secretKey}`).toString(\"base64\")}`;\n}\n\nfunction asStringOrNull(value: unknown): string | null {\n return typeof value === \"string\" ? value : null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nexport const s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S,WAAW,KAAK;AAC3B,UAAM,IAAI,iBAAiB,sBAAsB,SAAS,EAAE;AAAA,EAC9D;AACA,QAAM,OAAO,MAAM,SAAS,KAAK;AACjC,MAAI,CAAC,SAAS,IAAI;AAChB,UAAM,IAAI;AAAA,MACR,0BAA0B,SAAS,UAAU,SAAS,MAAM,WAAM,KAAK,MAAM,GAAG,GAAG,CAAC;AAAA,IACtF;AAAA,EACF;AACA,MAAI;AACJ,MAAI;AACF,cAAU,KAAK,MAAM,IAAI;AAAA,EAC3B,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,0BAA0B,SAAS;AAAA,MACnC,EAAE,OAAO,MAAM;AAAA,IACjB;AAAA,EACF;AACA,SAAO,iBAAiB;AAAA,IACtB,cAAc,OAAO,IAAI,UAAU,CAAC;AAAA,EACtC;AACF;AAEO,SAAS,gBAAgB,WAAmB,WAA2B;AAC5E,SAAO,SAAS,OAAO,KAAK,GAAG,SAAS,IAAI,SAAS,EAAE,EAAE,SAAS,QAAQ,CAAC;AAC7E;AAEA,SAAS,eAAe,OAA+B;AACrD,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,SAAS,cAAc,OAAkD;AACvE,SAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEO,IAAM,WAAW;AAAA,EACtB,MAAM;AACR;","names":[]}
|
package/dist/tracing/index.d.mts
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
export { O as ObservationKind,
|
|
1
|
+
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-DnowA8MG.mjs';
|
|
2
|
+
import '@opentelemetry/api';
|
|
3
|
+
import '@opentelemetry/sdk-trace-base';
|
package/dist/tracing/index.d.ts
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
export { O as ObservationKind,
|
|
1
|
+
export { I as IdentifyOptions, a as IdentitySpanProcessor, O as ObservationKind, b as ObserveClaudeOptions, c as ObserveOptions, T as TracingConfig, d as TracingHandle, e as TracingState, U as USER_ID_ATTRIBUTE, f as flush, i as identify, g as init, h as initIsolated, j as isGatewayConfigured, k as isInitialized, o as observe, l as observeAnthropic, m as observeClaude, n as observeOpenAI, p as resetAmbientUser, r as resolveUserId, s as shutdown } from '../index-DnowA8MG.js';
|
|
2
|
+
import '@opentelemetry/api';
|
|
3
|
+
import '@opentelemetry/sdk-trace-base';
|
package/dist/tracing/index.js
CHANGED
|
@@ -20,36 +20,242 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
20
20
|
// src/tracing/index.ts
|
|
21
21
|
var tracing_exports = {};
|
|
22
22
|
__export(tracing_exports, {
|
|
23
|
+
IdentitySpanProcessor: () => IdentitySpanProcessor,
|
|
24
|
+
USER_ID_ATTRIBUTE: () => USER_ID_ATTRIBUTE,
|
|
23
25
|
flush: () => flush,
|
|
26
|
+
identify: () => identify,
|
|
24
27
|
init: () => init,
|
|
28
|
+
initIsolated: () => initIsolated,
|
|
25
29
|
isGatewayConfigured: () => isGatewayConfigured,
|
|
26
30
|
isInitialized: () => isInitialized,
|
|
27
31
|
observe: () => observe,
|
|
28
32
|
observeAnthropic: () => observeAnthropic,
|
|
29
33
|
observeClaude: () => observeClaude,
|
|
30
34
|
observeOpenAI: () => observeOpenAI,
|
|
35
|
+
resetAmbientUser: () => resetAmbientUser,
|
|
36
|
+
resolveUserId: () => resolveUserId,
|
|
31
37
|
shutdown: () => shutdown
|
|
32
38
|
});
|
|
33
39
|
module.exports = __toCommonJS(tracing_exports);
|
|
34
40
|
|
|
41
|
+
// src/tracing/identity.ts
|
|
42
|
+
var import_async_hooks = require("async_hooks");
|
|
43
|
+
var import_api = require("@opentelemetry/api");
|
|
44
|
+
|
|
45
|
+
// src/users/index.ts
|
|
46
|
+
var UserProfileError = class extends Error {
|
|
47
|
+
constructor(message, options) {
|
|
48
|
+
super(message);
|
|
49
|
+
this.name = "UserProfileError";
|
|
50
|
+
this.cause = options?.cause;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
var UsersClient = class _UsersClient {
|
|
54
|
+
host;
|
|
55
|
+
publicKey;
|
|
56
|
+
secretKey;
|
|
57
|
+
timeoutSeconds;
|
|
58
|
+
debug;
|
|
59
|
+
constructor(config) {
|
|
60
|
+
this.host = config.host.replace(/\/$/, "");
|
|
61
|
+
this.publicKey = config.publicKey;
|
|
62
|
+
this.secretKey = config.secretKey;
|
|
63
|
+
this.timeoutSeconds = config.timeoutSeconds ?? 15;
|
|
64
|
+
this.debug = config.debug ?? false;
|
|
65
|
+
}
|
|
66
|
+
/** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */
|
|
67
|
+
static fromEnv(config = {}) {
|
|
68
|
+
const host = config.host ?? process.env.GATEWAY_HOST;
|
|
69
|
+
const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;
|
|
70
|
+
const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;
|
|
71
|
+
const missing = [
|
|
72
|
+
["host", host],
|
|
73
|
+
["publicKey", publicKey],
|
|
74
|
+
["secretKey", secretKey]
|
|
75
|
+
].filter(([, value]) => !value).map(([name]) => name);
|
|
76
|
+
if (missing.length > 0) {
|
|
77
|
+
throw new UserProfileError(
|
|
78
|
+
`Missing Gateway user-profile configuration: ${missing.join(", ")}`
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
return new _UsersClient({
|
|
82
|
+
...config,
|
|
83
|
+
host,
|
|
84
|
+
publicKey,
|
|
85
|
+
secretKey
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** Fetch a user's stored profile. */
|
|
89
|
+
async get(userId) {
|
|
90
|
+
return parseProfile(
|
|
91
|
+
await this.requestJson(
|
|
92
|
+
"GET",
|
|
93
|
+
`/api/public/user-profiles/${encodeURIComponent(userId)}`
|
|
94
|
+
)
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Upsert a user's profile. `attributes` merge with the stored set unless
|
|
99
|
+
* `merge: false` (which replaces it).
|
|
100
|
+
*/
|
|
101
|
+
async update(userId, update = {}) {
|
|
102
|
+
const body = {
|
|
103
|
+
userId,
|
|
104
|
+
attributes: update.attributes ?? {},
|
|
105
|
+
mergeAttributes: update.merge ?? true,
|
|
106
|
+
...update.displayName !== void 0 ? { displayName: update.displayName } : {},
|
|
107
|
+
...update.email !== void 0 ? { email: update.email } : {},
|
|
108
|
+
...update.notes !== void 0 ? { notes: update.notes } : {}
|
|
109
|
+
};
|
|
110
|
+
return parseProfile(
|
|
111
|
+
await this.requestJson("POST", "/api/public/user-profiles", body)
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
async requestJson(method, path, payload) {
|
|
115
|
+
let response;
|
|
116
|
+
try {
|
|
117
|
+
response = await fetch(`${this.host}${path}`, {
|
|
118
|
+
method,
|
|
119
|
+
headers: {
|
|
120
|
+
Authorization: this.authHeader(),
|
|
121
|
+
"Content-Type": "application/json"
|
|
122
|
+
},
|
|
123
|
+
...payload ? { body: JSON.stringify(payload) } : {},
|
|
124
|
+
signal: AbortSignal.timeout(this.timeoutSeconds * 1e3)
|
|
125
|
+
});
|
|
126
|
+
} catch (error) {
|
|
127
|
+
throw new UserProfileError(
|
|
128
|
+
`${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
129
|
+
{ cause: error }
|
|
130
|
+
);
|
|
131
|
+
}
|
|
132
|
+
const text = await response.text();
|
|
133
|
+
if (!response.ok) {
|
|
134
|
+
throw new UserProfileError(
|
|
135
|
+
`${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`
|
|
136
|
+
);
|
|
137
|
+
}
|
|
138
|
+
this.log("%s %s -> %s", method, path, response.status);
|
|
139
|
+
return safeJson(text);
|
|
140
|
+
}
|
|
141
|
+
authHeader() {
|
|
142
|
+
return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(
|
|
143
|
+
"base64"
|
|
144
|
+
)}`;
|
|
145
|
+
}
|
|
146
|
+
log(message, ...args) {
|
|
147
|
+
if (this.debug) {
|
|
148
|
+
console.log(`[gateway.users] ${message}`, ...args);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
function parseProfile(payload) {
|
|
153
|
+
return {
|
|
154
|
+
userId: String(payload.userId ?? ""),
|
|
155
|
+
displayName: typeof payload.displayName === "string" ? payload.displayName : null,
|
|
156
|
+
email: typeof payload.email === "string" ? payload.email : null,
|
|
157
|
+
attributes: parseAttributes(payload.attributes),
|
|
158
|
+
notes: typeof payload.notes === "string" ? payload.notes : null
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
function parseAttributes(value) {
|
|
162
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
163
|
+
const attributes = {};
|
|
164
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
165
|
+
attributes[key] = String(entry);
|
|
166
|
+
}
|
|
167
|
+
return attributes;
|
|
168
|
+
}
|
|
169
|
+
function safeJson(value) {
|
|
170
|
+
try {
|
|
171
|
+
const parsed = JSON.parse(value);
|
|
172
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
173
|
+
} catch {
|
|
174
|
+
return {};
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
var users = {
|
|
178
|
+
fromEnv: UsersClient.fromEnv
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
// src/tracing/identity.ts
|
|
182
|
+
var USER_ID_ATTRIBUTE = "gateway.user.id";
|
|
183
|
+
var currentUserStorage = new import_async_hooks.AsyncLocalStorage();
|
|
184
|
+
function resolveUserId() {
|
|
185
|
+
const contextual = currentUserStorage.getStore();
|
|
186
|
+
if (contextual) return contextual;
|
|
187
|
+
const envUser = process.env.GATEWAY_USER_ID?.trim();
|
|
188
|
+
return envUser ? envUser : void 0;
|
|
189
|
+
}
|
|
190
|
+
function identify(userId, options = {}) {
|
|
191
|
+
const cleaned = userId.trim();
|
|
192
|
+
if (!cleaned) return;
|
|
193
|
+
currentUserStorage.enterWith(cleaned);
|
|
194
|
+
try {
|
|
195
|
+
const span = import_api.trace.getActiveSpan();
|
|
196
|
+
if (span && (0, import_api.isSpanContextValid)(span.spanContext())) {
|
|
197
|
+
span.setAttribute(USER_ID_ATTRIBUTE, cleaned);
|
|
198
|
+
}
|
|
199
|
+
} catch (error) {
|
|
200
|
+
debugLog("identify(): no active span to stamp", error);
|
|
201
|
+
}
|
|
202
|
+
if (options.attributes || options.displayName || options.email) {
|
|
203
|
+
void pushProfile(cleaned, options);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
async function pushProfile(userId, options) {
|
|
207
|
+
try {
|
|
208
|
+
const attributes = {};
|
|
209
|
+
for (const [key, value] of Object.entries(options.attributes ?? {})) {
|
|
210
|
+
attributes[key] = String(value);
|
|
211
|
+
}
|
|
212
|
+
await UsersClient.fromEnv().update(userId, {
|
|
213
|
+
...options.displayName !== void 0 ? { displayName: options.displayName } : {},
|
|
214
|
+
...options.email !== void 0 ? { email: options.email } : {},
|
|
215
|
+
attributes
|
|
216
|
+
});
|
|
217
|
+
} catch (error) {
|
|
218
|
+
debugLog("identify(): profile update failed", error);
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
function resetAmbientUser() {
|
|
222
|
+
currentUserStorage.enterWith(void 0);
|
|
223
|
+
}
|
|
224
|
+
var IdentitySpanProcessor = class {
|
|
225
|
+
onStart(span, _parentContext) {
|
|
226
|
+
const userId = resolveUserId();
|
|
227
|
+
if (userId) {
|
|
228
|
+
span.setAttribute(USER_ID_ATTRIBUTE, userId);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
onEnd(_span) {
|
|
232
|
+
}
|
|
233
|
+
async shutdown() {
|
|
234
|
+
}
|
|
235
|
+
async forceFlush() {
|
|
236
|
+
}
|
|
237
|
+
};
|
|
238
|
+
function debugLog(message, ...args) {
|
|
239
|
+
if (process.env.GATEWAY_DEBUG) {
|
|
240
|
+
console.debug(`[gatewaysdk.tracing] ${message}`, ...args);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
35
244
|
// src/tracing/init.ts
|
|
36
245
|
var ENV_VARS = {
|
|
37
|
-
HOST:
|
|
38
|
-
PUBLIC_KEY:
|
|
39
|
-
SECRET_KEY:
|
|
40
|
-
ENDPOINT:
|
|
246
|
+
HOST: "GATEWAY_HOST",
|
|
247
|
+
PUBLIC_KEY: "GATEWAY_PUBLIC_KEY",
|
|
248
|
+
SECRET_KEY: "GATEWAY_SECRET_KEY",
|
|
249
|
+
ENDPOINT: "GATEWAY_OTLP_ENDPOINT"
|
|
41
250
|
};
|
|
42
251
|
var DEFAULT_OTLP_PATH = "/api/public/otel/v1/traces";
|
|
43
252
|
var state = {
|
|
44
253
|
initialized: false,
|
|
45
254
|
provider: null
|
|
46
255
|
};
|
|
47
|
-
function getEnv(
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
if (value) return value;
|
|
51
|
-
}
|
|
52
|
-
return void 0;
|
|
256
|
+
function getEnv(key) {
|
|
257
|
+
const value = process.env[key];
|
|
258
|
+
return value ? value : void 0;
|
|
53
259
|
}
|
|
54
260
|
function log(message, ...args) {
|
|
55
261
|
if (state.debug) {
|
|
@@ -59,12 +265,7 @@ function log(message, ...args) {
|
|
|
59
265
|
function warn(message, ...args) {
|
|
60
266
|
console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
|
|
61
267
|
}
|
|
62
|
-
function
|
|
63
|
-
if (state.initialized) {
|
|
64
|
-
log("Tracing already initialized. Call shutdown() first to reinitialize.");
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
state.debug = config.debug ?? false;
|
|
268
|
+
function buildProvider(config, logFn) {
|
|
68
269
|
const host = config.host ?? getEnv(ENV_VARS.HOST);
|
|
69
270
|
const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
|
|
70
271
|
const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
|
|
@@ -141,17 +342,18 @@ function init(config = {}) {
|
|
|
141
342
|
Authorization: authHeader
|
|
142
343
|
}
|
|
143
344
|
});
|
|
144
|
-
|
|
345
|
+
logFn("Configured Gateway exporter: endpoint=%s", endpoint);
|
|
145
346
|
const spanProcessors = [];
|
|
146
347
|
if (config.customSpanProcessors) {
|
|
147
348
|
for (const sp of config.customSpanProcessors) {
|
|
148
349
|
spanProcessors.push(sp);
|
|
149
|
-
|
|
350
|
+
logFn(
|
|
150
351
|
"Added custom span processor: %s",
|
|
151
352
|
sp.constructor?.name ?? "unknown"
|
|
152
353
|
);
|
|
153
354
|
}
|
|
154
355
|
}
|
|
356
|
+
spanProcessors.push(new IdentitySpanProcessor());
|
|
155
357
|
const batchConfig = {};
|
|
156
358
|
if (config.batch?.maxQueueSize) {
|
|
157
359
|
batchConfig.maxQueueSize = config.batch.maxQueueSize;
|
|
@@ -176,6 +378,15 @@ function init(config = {}) {
|
|
|
176
378
|
spanProcessors
|
|
177
379
|
});
|
|
178
380
|
}
|
|
381
|
+
return provider;
|
|
382
|
+
}
|
|
383
|
+
function init(config = {}) {
|
|
384
|
+
if (state.initialized) {
|
|
385
|
+
log("Tracing already initialized. Call shutdown() first to reinitialize.");
|
|
386
|
+
return;
|
|
387
|
+
}
|
|
388
|
+
state.debug = config.debug ?? false;
|
|
389
|
+
const provider = buildProvider(config, log);
|
|
179
390
|
provider.register();
|
|
180
391
|
state.provider = provider;
|
|
181
392
|
state.initialized = true;
|
|
@@ -184,6 +395,33 @@ function init(config = {}) {
|
|
|
184
395
|
config.serviceName ?? "gatewaysdk-tracing"
|
|
185
396
|
);
|
|
186
397
|
}
|
|
398
|
+
function initIsolated(config = {}) {
|
|
399
|
+
const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
|
|
400
|
+
};
|
|
401
|
+
const provider = buildProvider(config, debugLog2);
|
|
402
|
+
const tracer = provider.getTracer("@withgateway/sdk");
|
|
403
|
+
debugLog2(
|
|
404
|
+
"Isolated tracing provider created (service=%s)",
|
|
405
|
+
config.serviceName ?? "gatewaysdk-tracing"
|
|
406
|
+
);
|
|
407
|
+
return {
|
|
408
|
+
tracer,
|
|
409
|
+
async flush() {
|
|
410
|
+
try {
|
|
411
|
+
await provider.forceFlush();
|
|
412
|
+
} catch (e) {
|
|
413
|
+
warn("Error during isolated flush:", e);
|
|
414
|
+
}
|
|
415
|
+
},
|
|
416
|
+
async shutdown() {
|
|
417
|
+
try {
|
|
418
|
+
await provider.shutdown();
|
|
419
|
+
} catch (e) {
|
|
420
|
+
warn("Error during isolated shutdown:", e);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
}
|
|
187
425
|
async function flush() {
|
|
188
426
|
if (!state.provider) {
|
|
189
427
|
log("No provider to flush");
|
|
@@ -221,31 +459,32 @@ function isGatewayConfigured() {
|
|
|
221
459
|
}
|
|
222
460
|
|
|
223
461
|
// src/tracing/observe.ts
|
|
224
|
-
var
|
|
462
|
+
var import_api2 = require("@opentelemetry/api");
|
|
225
463
|
function asAttr(value) {
|
|
226
464
|
return typeof value === "string" ? value : JSON.stringify(value);
|
|
227
465
|
}
|
|
228
466
|
async function observe(name, fn, options = {}) {
|
|
229
|
-
const tracer =
|
|
467
|
+
const tracer = options.tracer ?? import_api2.trace.getTracer("@withgateway/sdk");
|
|
230
468
|
const span = tracer.startSpan(name, {
|
|
231
469
|
attributes: {
|
|
232
470
|
"openinference.span.kind": options.kind ?? "AGENT",
|
|
233
|
-
...options.input !== void 0 ? { "input.value": asAttr(options.input) } : {}
|
|
471
|
+
...options.input !== void 0 ? { "input.value": asAttr(options.input) } : {},
|
|
472
|
+
...options.attributes ?? {}
|
|
234
473
|
}
|
|
235
474
|
});
|
|
236
475
|
try {
|
|
237
|
-
const result = await
|
|
238
|
-
|
|
476
|
+
const result = await import_api2.context.with(
|
|
477
|
+
import_api2.trace.setSpan(import_api2.context.active(), span),
|
|
239
478
|
fn
|
|
240
479
|
);
|
|
241
480
|
if (options.captureOutput !== false && result !== void 0) {
|
|
242
481
|
span.setAttribute("output.value", asAttr(result));
|
|
243
482
|
}
|
|
244
|
-
span.setStatus({ code:
|
|
483
|
+
span.setStatus({ code: import_api2.SpanStatusCode.OK });
|
|
245
484
|
return result;
|
|
246
485
|
} catch (error) {
|
|
247
486
|
span.setStatus({
|
|
248
|
-
code:
|
|
487
|
+
code: import_api2.SpanStatusCode.ERROR,
|
|
249
488
|
message: error instanceof Error ? error.message : String(error)
|
|
250
489
|
});
|
|
251
490
|
throw error;
|
|
@@ -292,7 +531,7 @@ function observeAnthropic(client) {
|
|
|
292
531
|
}
|
|
293
532
|
|
|
294
533
|
// src/tracing/claude.ts
|
|
295
|
-
var
|
|
534
|
+
var import_api3 = require("@opentelemetry/api");
|
|
296
535
|
function cleanToolName(name) {
|
|
297
536
|
return name.replace(/^mcp__[^_]+__/, "");
|
|
298
537
|
}
|
|
@@ -305,14 +544,15 @@ function toolResultText(content) {
|
|
|
305
544
|
return JSON.stringify(content ?? "");
|
|
306
545
|
}
|
|
307
546
|
async function* observeClaude(stream, options) {
|
|
308
|
-
const tracer =
|
|
547
|
+
const tracer = options.tracer ?? import_api3.trace.getTracer("@withgateway/sdk");
|
|
309
548
|
const root = tracer.startSpan(options.name, {
|
|
310
549
|
attributes: {
|
|
311
550
|
"openinference.span.kind": "AGENT",
|
|
312
|
-
...options.input !== void 0 ? { "input.value": options.input } : {}
|
|
551
|
+
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
552
|
+
...options.attributes ?? {}
|
|
313
553
|
}
|
|
314
554
|
});
|
|
315
|
-
const rootCtx =
|
|
555
|
+
const rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
|
|
316
556
|
const openTools = /* @__PURE__ */ new Map();
|
|
317
557
|
const model = options.model ?? "claude";
|
|
318
558
|
let finalText = "";
|
|
@@ -371,7 +611,7 @@ async function* observeClaude(stream, options) {
|
|
|
371
611
|
const span = openTools.get(block.tool_use_id);
|
|
372
612
|
if (span) {
|
|
373
613
|
span.setAttribute("output.value", toolResultText(block.content));
|
|
374
|
-
span.setStatus({ code:
|
|
614
|
+
span.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
375
615
|
span.end();
|
|
376
616
|
openTools.delete(block.tool_use_id);
|
|
377
617
|
}
|
|
@@ -385,20 +625,26 @@ async function* observeClaude(stream, options) {
|
|
|
385
625
|
for (const span of openTools.values()) span.end();
|
|
386
626
|
openTools.clear();
|
|
387
627
|
root.setAttribute("output.value", finalText);
|
|
388
|
-
root.setStatus({ code:
|
|
628
|
+
root.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
389
629
|
root.end();
|
|
390
630
|
}
|
|
391
631
|
}
|
|
392
632
|
// Annotate the CommonJS export names for ESM import in node:
|
|
393
633
|
0 && (module.exports = {
|
|
634
|
+
IdentitySpanProcessor,
|
|
635
|
+
USER_ID_ATTRIBUTE,
|
|
394
636
|
flush,
|
|
637
|
+
identify,
|
|
395
638
|
init,
|
|
639
|
+
initIsolated,
|
|
396
640
|
isGatewayConfigured,
|
|
397
641
|
isInitialized,
|
|
398
642
|
observe,
|
|
399
643
|
observeAnthropic,
|
|
400
644
|
observeClaude,
|
|
401
645
|
observeOpenAI,
|
|
646
|
+
resetAmbientUser,
|
|
647
|
+
resolveUserId,
|
|
402
648
|
shutdown
|
|
403
649
|
});
|
|
404
650
|
//# sourceMappingURL=index.js.map
|