@withgateway/sdk 0.1.3 → 0.1.5
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/context/index.mjs +3 -0
- package/dist/context/index.mjs.map +1 -1
- package/dist/experiments/index.mjs +2 -0
- package/dist/experiments/index.mjs.map +1 -1
- 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 +1715 -20
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1686 -19
- package/dist/index.mjs.map +1 -1
- package/dist/memory/index.mjs +3 -0
- package/dist/memory/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/security/index.mjs +2 -0
- package/dist/security/index.mjs.map +1 -1
- 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 +435 -8
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +431 -8
- 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 +25 -1
- package/dist/index-Caw3XVub.d.mts +0 -193
- package/dist/index-Caw3XVub.d.ts +0 -193
|
@@ -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 sessions = {\n load: loadSession,\n};\n"],"mappings":";;;;AA0BA,SAAS,WAAW,qBAAqB;AACzC,SAAS,eAAe;AAEjB,IAAM,mBAAmB;AACzB,IAAM,yBAAyB;AAC/B,IAAM,yBAAyB;AAE/B,IAAM,0BAA0B;AAGhC,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAkBO,SAAS,0BACd,KACoB;AACpB,SAAO;AAAA,IACL,IAAI,OAAO,IAAI,MAAM,EAAE;AAAA,IACvB,MAAM,eAAe,IAAI,IAAI;AAAA,IAC7B,MAAM,eAAe,IAAI,IAAI;AAAA,IAC7B,OAAO,eAAe,IAAI,KAAK;AAAA,IAC/B,eAAe,eAAe,IAAI,aAAa;AAAA,IAC/C,OAAO,eAAe,IAAI,KAAK;AAAA,IAC/B,OAAO,IAAI;AAAA,IACX,QAAQ,IAAI;AAAA,IACZ,UAAU,IAAI,YAAY;AAAA,IAC1B,qBAAqB,eAAe,IAAI,mBAAmB;AAAA,IAC3D,WAAW,IAAI,YAAY,OAAO,IAAI,SAAS,IAAI;AAAA,IACnD,SAAS,IAAI,UAAU,OAAO,IAAI,OAAO,IAAI;AAAA,EAC/C;AACF;AAcO,IAAM,eAAN,MAAM,cAAa;AAAA,EACf;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAET,YAAY,QAA4B;AACtC,SAAK,KAAK,OAAO;AACjB,SAAK,OAAO,OAAO;AACnB,SAAK,YAAY,OAA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IACnD,CAAC;AAAA,EACH,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,0BAA0B,SAAS,KAAK,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;AAAA,MAC9F,EAAE,OAAO,MAAM;AAAA,IACjB;AAAA,EACF;AACA,MAAI,SAAS,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 { T as TracingConfig,
|
|
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 { T as TracingConfig,
|
|
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,14 +20,227 @@ 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,
|
|
31
|
+
observe: () => observe,
|
|
32
|
+
observeAnthropic: () => observeAnthropic,
|
|
33
|
+
observeClaude: () => observeClaude,
|
|
34
|
+
observeOpenAI: () => observeOpenAI,
|
|
35
|
+
resetAmbientUser: () => resetAmbientUser,
|
|
36
|
+
resolveUserId: () => resolveUserId,
|
|
27
37
|
shutdown: () => shutdown
|
|
28
38
|
});
|
|
29
39
|
module.exports = __toCommonJS(tracing_exports);
|
|
30
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
|
+
|
|
31
244
|
// src/tracing/init.ts
|
|
32
245
|
var ENV_VARS = {
|
|
33
246
|
HOST: ["GATEWAY_HOST", "GATEWAY_HOST"],
|
|
@@ -55,12 +268,7 @@ function log(message, ...args) {
|
|
|
55
268
|
function warn(message, ...args) {
|
|
56
269
|
console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
|
|
57
270
|
}
|
|
58
|
-
function
|
|
59
|
-
if (state.initialized) {
|
|
60
|
-
log("Tracing already initialized. Call shutdown() first to reinitialize.");
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
state.debug = config.debug ?? false;
|
|
271
|
+
function buildProvider(config, logFn) {
|
|
64
272
|
const host = config.host ?? getEnv(ENV_VARS.HOST);
|
|
65
273
|
const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);
|
|
66
274
|
const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);
|
|
@@ -137,17 +345,18 @@ function init(config = {}) {
|
|
|
137
345
|
Authorization: authHeader
|
|
138
346
|
}
|
|
139
347
|
});
|
|
140
|
-
|
|
348
|
+
logFn("Configured Gateway exporter: endpoint=%s", endpoint);
|
|
141
349
|
const spanProcessors = [];
|
|
142
350
|
if (config.customSpanProcessors) {
|
|
143
351
|
for (const sp of config.customSpanProcessors) {
|
|
144
352
|
spanProcessors.push(sp);
|
|
145
|
-
|
|
353
|
+
logFn(
|
|
146
354
|
"Added custom span processor: %s",
|
|
147
355
|
sp.constructor?.name ?? "unknown"
|
|
148
356
|
);
|
|
149
357
|
}
|
|
150
358
|
}
|
|
359
|
+
spanProcessors.push(new IdentitySpanProcessor());
|
|
151
360
|
const batchConfig = {};
|
|
152
361
|
if (config.batch?.maxQueueSize) {
|
|
153
362
|
batchConfig.maxQueueSize = config.batch.maxQueueSize;
|
|
@@ -172,6 +381,15 @@ function init(config = {}) {
|
|
|
172
381
|
spanProcessors
|
|
173
382
|
});
|
|
174
383
|
}
|
|
384
|
+
return provider;
|
|
385
|
+
}
|
|
386
|
+
function init(config = {}) {
|
|
387
|
+
if (state.initialized) {
|
|
388
|
+
log("Tracing already initialized. Call shutdown() first to reinitialize.");
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
state.debug = config.debug ?? false;
|
|
392
|
+
const provider = buildProvider(config, log);
|
|
175
393
|
provider.register();
|
|
176
394
|
state.provider = provider;
|
|
177
395
|
state.initialized = true;
|
|
@@ -180,6 +398,33 @@ function init(config = {}) {
|
|
|
180
398
|
config.serviceName ?? "gatewaysdk-tracing"
|
|
181
399
|
);
|
|
182
400
|
}
|
|
401
|
+
function initIsolated(config = {}) {
|
|
402
|
+
const debugLog2 = config.debug ? (message, ...args) => console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args) : () => {
|
|
403
|
+
};
|
|
404
|
+
const provider = buildProvider(config, debugLog2);
|
|
405
|
+
const tracer = provider.getTracer("@withgateway/sdk");
|
|
406
|
+
debugLog2(
|
|
407
|
+
"Isolated tracing provider created (service=%s)",
|
|
408
|
+
config.serviceName ?? "gatewaysdk-tracing"
|
|
409
|
+
);
|
|
410
|
+
return {
|
|
411
|
+
tracer,
|
|
412
|
+
async flush() {
|
|
413
|
+
try {
|
|
414
|
+
await provider.forceFlush();
|
|
415
|
+
} catch (e) {
|
|
416
|
+
warn("Error during isolated flush:", e);
|
|
417
|
+
}
|
|
418
|
+
},
|
|
419
|
+
async shutdown() {
|
|
420
|
+
try {
|
|
421
|
+
await provider.shutdown();
|
|
422
|
+
} catch (e) {
|
|
423
|
+
warn("Error during isolated shutdown:", e);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
};
|
|
427
|
+
}
|
|
183
428
|
async function flush() {
|
|
184
429
|
if (!state.provider) {
|
|
185
430
|
log("No provider to flush");
|
|
@@ -215,12 +460,194 @@ function isGatewayConfigured() {
|
|
|
215
460
|
const secretKey = getEnv(ENV_VARS.SECRET_KEY);
|
|
216
461
|
return !!(host && publicKey && secretKey);
|
|
217
462
|
}
|
|
463
|
+
|
|
464
|
+
// src/tracing/observe.ts
|
|
465
|
+
var import_api2 = require("@opentelemetry/api");
|
|
466
|
+
function asAttr(value) {
|
|
467
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
468
|
+
}
|
|
469
|
+
async function observe(name, fn, options = {}) {
|
|
470
|
+
const tracer = options.tracer ?? import_api2.trace.getTracer("@withgateway/sdk");
|
|
471
|
+
const span = tracer.startSpan(name, {
|
|
472
|
+
attributes: {
|
|
473
|
+
"openinference.span.kind": options.kind ?? "AGENT",
|
|
474
|
+
...options.input !== void 0 ? { "input.value": asAttr(options.input) } : {},
|
|
475
|
+
...options.attributes ?? {}
|
|
476
|
+
}
|
|
477
|
+
});
|
|
478
|
+
try {
|
|
479
|
+
const result = await import_api2.context.with(
|
|
480
|
+
import_api2.trace.setSpan(import_api2.context.active(), span),
|
|
481
|
+
fn
|
|
482
|
+
);
|
|
483
|
+
if (options.captureOutput !== false && result !== void 0) {
|
|
484
|
+
span.setAttribute("output.value", asAttr(result));
|
|
485
|
+
}
|
|
486
|
+
span.setStatus({ code: import_api2.SpanStatusCode.OK });
|
|
487
|
+
return result;
|
|
488
|
+
} catch (error) {
|
|
489
|
+
span.setStatus({
|
|
490
|
+
code: import_api2.SpanStatusCode.ERROR,
|
|
491
|
+
message: error instanceof Error ? error.message : String(error)
|
|
492
|
+
});
|
|
493
|
+
throw error;
|
|
494
|
+
} finally {
|
|
495
|
+
span.end();
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
// src/tracing/instrument.ts
|
|
500
|
+
function warn2(message, ...args) {
|
|
501
|
+
console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
|
|
502
|
+
}
|
|
503
|
+
function observeOpenAI(client) {
|
|
504
|
+
try {
|
|
505
|
+
const {
|
|
506
|
+
OpenAIInstrumentation
|
|
507
|
+
} = require("@arizeai/openinference-instrumentation-openai");
|
|
508
|
+
const OpenAIClass = client.constructor;
|
|
509
|
+
new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });
|
|
510
|
+
} catch (error) {
|
|
511
|
+
warn2(
|
|
512
|
+
"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai \u2014 OpenAI calls will not be traced.",
|
|
513
|
+
error
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
return client;
|
|
517
|
+
}
|
|
518
|
+
function observeAnthropic(client) {
|
|
519
|
+
try {
|
|
520
|
+
const {
|
|
521
|
+
AnthropicInstrumentation
|
|
522
|
+
} = require("@arizeai/openinference-instrumentation-anthropic");
|
|
523
|
+
const AnthropicClass = client.constructor;
|
|
524
|
+
new AnthropicInstrumentation().manuallyInstrument({
|
|
525
|
+
Messages: AnthropicClass.Messages
|
|
526
|
+
});
|
|
527
|
+
} catch (error) {
|
|
528
|
+
warn2(
|
|
529
|
+
"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic \u2014 Anthropic calls will not be traced.",
|
|
530
|
+
error
|
|
531
|
+
);
|
|
532
|
+
}
|
|
533
|
+
return client;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// src/tracing/claude.ts
|
|
537
|
+
var import_api3 = require("@opentelemetry/api");
|
|
538
|
+
function cleanToolName(name) {
|
|
539
|
+
return name.replace(/^mcp__[^_]+__/, "");
|
|
540
|
+
}
|
|
541
|
+
function toolResultText(content) {
|
|
542
|
+
if (typeof content === "string") return content;
|
|
543
|
+
if (Array.isArray(content))
|
|
544
|
+
return content.map(
|
|
545
|
+
(b) => b && typeof b === "object" && "text" in b ? String(b.text) : JSON.stringify(b)
|
|
546
|
+
).join("");
|
|
547
|
+
return JSON.stringify(content ?? "");
|
|
548
|
+
}
|
|
549
|
+
async function* observeClaude(stream, options) {
|
|
550
|
+
const tracer = options.tracer ?? import_api3.trace.getTracer("@withgateway/sdk");
|
|
551
|
+
const root = tracer.startSpan(options.name, {
|
|
552
|
+
attributes: {
|
|
553
|
+
"openinference.span.kind": "AGENT",
|
|
554
|
+
...options.input !== void 0 ? { "input.value": options.input } : {},
|
|
555
|
+
...options.attributes ?? {}
|
|
556
|
+
}
|
|
557
|
+
});
|
|
558
|
+
const rootCtx = import_api3.trace.setSpan(import_api3.context.active(), root);
|
|
559
|
+
const openTools = /* @__PURE__ */ new Map();
|
|
560
|
+
const model = options.model ?? "claude";
|
|
561
|
+
let finalText = "";
|
|
562
|
+
try {
|
|
563
|
+
for await (const message of stream) {
|
|
564
|
+
if (message?.type === "assistant") {
|
|
565
|
+
let turnText = "";
|
|
566
|
+
const toolUses = [];
|
|
567
|
+
for (const block of message.message?.content ?? []) {
|
|
568
|
+
if (block?.type === "text") {
|
|
569
|
+
finalText += block.text;
|
|
570
|
+
turnText += block.text;
|
|
571
|
+
}
|
|
572
|
+
if (block?.type === "tool_use") {
|
|
573
|
+
toolUses.push({ id: block.id, name: block.name, input: block.input });
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const gen = tracer.startSpan(
|
|
577
|
+
"assistant",
|
|
578
|
+
{
|
|
579
|
+
attributes: {
|
|
580
|
+
"openinference.span.kind": "LLM",
|
|
581
|
+
"llm.model_name": model,
|
|
582
|
+
"llm.provider": "anthropic",
|
|
583
|
+
"output.value": turnText || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
|
|
584
|
+
}
|
|
585
|
+
},
|
|
586
|
+
rootCtx
|
|
587
|
+
);
|
|
588
|
+
const usage = message.message?.usage;
|
|
589
|
+
if (usage?.input_tokens != null)
|
|
590
|
+
gen.setAttribute("llm.token_count.prompt", usage.input_tokens);
|
|
591
|
+
if (usage?.output_tokens != null)
|
|
592
|
+
gen.setAttribute("llm.token_count.completion", usage.output_tokens);
|
|
593
|
+
gen.end();
|
|
594
|
+
for (const t of toolUses) {
|
|
595
|
+
const span = tracer.startSpan(
|
|
596
|
+
`tool.${cleanToolName(t.name)}`,
|
|
597
|
+
{
|
|
598
|
+
attributes: {
|
|
599
|
+
"openinference.span.kind": "TOOL",
|
|
600
|
+
"tool.name": cleanToolName(t.name),
|
|
601
|
+
"input.value": JSON.stringify(t.input)
|
|
602
|
+
}
|
|
603
|
+
},
|
|
604
|
+
rootCtx
|
|
605
|
+
);
|
|
606
|
+
openTools.set(t.id, span);
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
if (message?.type === "user") {
|
|
610
|
+
const content = message.message?.content;
|
|
611
|
+
if (Array.isArray(content)) {
|
|
612
|
+
for (const block of content) {
|
|
613
|
+
if (block?.type === "tool_result") {
|
|
614
|
+
const span = openTools.get(block.tool_use_id);
|
|
615
|
+
if (span) {
|
|
616
|
+
span.setAttribute("output.value", toolResultText(block.content));
|
|
617
|
+
span.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
618
|
+
span.end();
|
|
619
|
+
openTools.delete(block.tool_use_id);
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
yield message;
|
|
626
|
+
}
|
|
627
|
+
} finally {
|
|
628
|
+
for (const span of openTools.values()) span.end();
|
|
629
|
+
openTools.clear();
|
|
630
|
+
root.setAttribute("output.value", finalText);
|
|
631
|
+
root.setStatus({ code: import_api3.SpanStatusCode.OK });
|
|
632
|
+
root.end();
|
|
633
|
+
}
|
|
634
|
+
}
|
|
218
635
|
// Annotate the CommonJS export names for ESM import in node:
|
|
219
636
|
0 && (module.exports = {
|
|
637
|
+
IdentitySpanProcessor,
|
|
638
|
+
USER_ID_ATTRIBUTE,
|
|
220
639
|
flush,
|
|
640
|
+
identify,
|
|
221
641
|
init,
|
|
642
|
+
initIsolated,
|
|
222
643
|
isGatewayConfigured,
|
|
223
644
|
isInitialized,
|
|
645
|
+
observe,
|
|
646
|
+
observeAnthropic,
|
|
647
|
+
observeClaude,
|
|
648
|
+
observeOpenAI,
|
|
649
|
+
resetAmbientUser,
|
|
650
|
+
resolveUserId,
|
|
224
651
|
shutdown
|
|
225
652
|
});
|
|
226
653
|
//# sourceMappingURL=index.js.map
|