@withgateway/sdk 0.1.7 → 0.1.8
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.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +64 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +64 -0
- package/dist/index.mjs.map +1 -1
- package/dist/tracing/index.js +64 -0
- package/dist/tracing/index.js.map +1 -1
- package/dist/tracing/index.mjs +64 -0
- package/dist/tracing/index.mjs.map +1 -1
- package/dist/users/index.d.mts +50 -1
- package/dist/users/index.d.ts +50 -1
- package/dist/users/index.js +64 -0
- package/dist/users/index.js.map +1 -1
- package/dist/users/index.mjs +64 -0
- package/dist/users/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/experiments/assignment.ts","../src/experiments/context.ts","../src/experiments/exposure-logger.ts","../src/experiments/client.ts","../src/experiments/otel.ts","../src/experiments/singleton.ts","../src/context/index.ts","../src/memory/index.ts","../src/personas/index.ts","../src/sessions/index.ts","../src/replay/index.ts","../src/security/index.ts","../src/users/index.ts","../src/tracing/identity.ts","../src/tracing/index.ts","../src/tracing/init.ts","../src/tracing/observe.ts","../src/tracing/instrument.ts","../src/tracing/claude.ts"],"sourcesContent":["export * from \"./experiments/index\";\nexport * from \"./context/index\";\nexport * from \"./memory/index\";\nexport * from \"./personas/index\";\nexport * from \"./replay/index\";\nexport * from \"./security/index\";\nexport * from \"./sessions/index\";\nexport * from \"./users/index\";\n\n// Top-level like the Python SDK's `gatewaysdk.identify` (lives in tracing/identity).\nexport { identify, resolveUserId } from \"./tracing/identity\";\nexport type { IdentifyOptions } from \"./tracing/identity\";\n\nimport * as _tracingModule from \"./tracing/index\";\nimport type { TracingConfig } from \"./tracing/types\";\nimport { ExperimentSpanProcessor } from \"./experiments/otel\";\n\n/**\n * Tracing module with automatic ExperimentSpanProcessor wiring.\n *\n * When imported from the main entry (\"@withgateway/sdk\"), init() automatically\n * adds ExperimentSpanProcessor so spans are tagged with experiment context.\n * Both modules share the same bundle, so the AsyncLocalStorage context is\n * shared — no cross-bundle duplication.\n */\nexport const tracing: typeof _tracingModule = {\n ..._tracingModule,\n init(config: TracingConfig = {}) {\n if (config.enableExperiments !== false) {\n const processors = [\n new ExperimentSpanProcessor(),\n ...(config.customSpanProcessors ?? []),\n ];\n return _tracingModule.init({\n ...config,\n customSpanProcessors: processors,\n });\n }\n return _tracingModule.init(config);\n },\n};\n","/**\n * Deterministic variant assignment for A/B experiments.\n *\n * Algorithm:\n * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)\n * 2. If bucket >= traffic_percent/100 → user not in experiment\n * 3. Otherwise, normalize bucket within traffic and assign to variant by weight\n */\n\nimport { createHash } from \"crypto\";\nimport type { ExperimentConfig, Variant } from \"./types\";\n\nexport function computeHash(experimentKey: string, userId: string): number {\n const raw = createHash(\"sha256\")\n .update(`${experimentKey}:${userId}`)\n .digest(\"hex\");\n // Divide by 2³² to keep range strictly [0, 1)\n return parseInt(raw.slice(0, 8), 16) / 0x100000000;\n}\n\nexport function assignVariant(\n config: ExperimentConfig,\n userId: string,\n): Variant | null {\n if (!config.variants || config.variants.length === 0) {\n return null;\n }\n\n const bucket = computeHash(config.key, userId);\n const trafficThreshold = config.trafficPercent / 100;\n\n if (bucket >= trafficThreshold) {\n return null;\n }\n\n const normalizedBucket = bucket / trafficThreshold;\n const totalWeight = config.variants.reduce((sum, v) => sum + v.weight, 0);\n\n if (totalWeight <= 0) {\n return config.variants[0] ?? null;\n }\n\n let cumulative = 0;\n for (const variant of config.variants) {\n cumulative += variant.weight / totalWeight;\n if (normalizedBucket < cumulative) {\n return variant;\n }\n }\n\n return config.variants[config.variants.length - 1] ?? null;\n}\n","/**\n * Async context management for experiments.\n *\n * Uses AsyncLocalStorage.enterWith() to set context that persists for the\n * remainder of the current async execution context. This provides:\n *\n * - Request isolation in concurrent server environments\n * - Context that survives across async boundaries (streaming, etc.)\n * - No callback wrapper required\n *\n * The context persists until clearExperimentContext() is called or the\n * async context naturally ends (e.g., request completes).\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ExperimentContext } from \"./types\";\n\n// AsyncLocalStorage for request-scoped context\nexport const experimentContextStorage =\n new AsyncLocalStorage<ExperimentContext>();\n\n/**\n * Get the current experiment context.\n */\nexport function getExperimentContext(): ExperimentContext | undefined {\n return experimentContextStorage.getStore();\n}\n\n/**\n * Set the experiment context for the current async execution.\n *\n * Uses enterWith() which sets context for the remainder of the current\n * async execution without requiring a callback wrapper. This means:\n * - Context persists across await boundaries\n * - Context is isolated per request in concurrent environments\n * - Context persists until clearExperimentContext() or request ends\n *\n * Called by getVariant() when a user is assigned to a variant.\n */\nexport function setExperimentContext(context: ExperimentContext): void {\n experimentContextStorage.enterWith(context);\n}\n\n/**\n * Clear the experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing spans to the experiment.\n *\n * Note: In most server frameworks, the async context naturally ends when the\n * request completes, so this is optional but recommended for explicit cleanup.\n */\nexport function clearExperimentContext(): void {\n // enterWith(undefined) effectively clears the context\n experimentContextStorage.enterWith(undefined as unknown as ExperimentContext);\n}\n\n/**\n * Run a function with experiment context (scoped).\n *\n * The context is automatically cleared when the function completes.\n * This is useful for synchronous operations or fully-contained async operations.\n *\n * For streaming/async patterns, prefer setExperimentContext() which persists\n * across async boundaries.\n */\nexport function runWithExperimentContext<T>(\n context: ExperimentContext,\n fn: () => T,\n): T {\n return experimentContextStorage.run(context, fn);\n}\n","/**\n * Batched asynchronous exposure logging.\n *\n * Collects exposure events in memory and flushes periodically\n * or when the batch size threshold is reached.\n */\n\nimport type { Exposure, ExposureLoggerConfig } from \"./types\";\n\nexport class ExposureLogger {\n private buffer: Exposure[] = [];\n private readonly batchSize: number;\n private readonly flushIntervalMs: number;\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n\n constructor(config: ExposureLoggerConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.batchSize = config.batchSize ?? 100;\n this.flushIntervalMs = config.flushIntervalMs ?? 5_000;\n\n this.flushTimer = setInterval(() => {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }, this.flushIntervalMs);\n\n if (this.flushTimer.unref) {\n this.flushTimer.unref();\n }\n }\n\n log(exposure: Exposure): void {\n this.buffer.push(exposure);\n if (this.buffer.length >= this.batchSize) {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }\n }\n\n async flush(): Promise<void> {\n if (this.isFlushing || this.buffer.length === 0) {\n return;\n }\n\n this.isFlushing = true;\n const batch = this.buffer.splice(0, this.buffer.length);\n\n try {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(\n `${this.apiUrl}/api/public/experiments/exposures/batch`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n exposures: batch,\n }),\n },\n );\n if (!response.ok) {\n this.buffer.unshift(...batch);\n console.error(\n `[gateway] Failed to log exposures: ${response.status} ${response.statusText}`,\n );\n }\n } catch (error) {\n this.buffer.unshift(...batch);\n console.error(\"[gateway] Network error logging exposures:\", error);\n } finally {\n this.isFlushing = false;\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.flush();\n }\n}\n","/**\n * Main A/B experiment client for TypeScript.\n *\n * Mirrors the Python SDK's ExperimentClient in:\n * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py\n */\n\nimport { assignVariant } from \"./assignment\";\nimport { runWithExperimentContext, setExperimentContext } from \"./context\";\nimport { ExposureLogger } from \"./exposure-logger\";\nimport type {\n ExperimentClientConfig,\n ExperimentConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nexport class ExperimentClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private readonly projectId: string;\n private readonly configs = new Map<string, ExperimentConfig>();\n private readonly exposureLogger: ExposureLogger;\n\n constructor(config: ExperimentClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.projectId = config.projectId;\n this.exposureLogger = new ExposureLogger({\n apiUrl: this.apiUrl,\n apiKey: this.apiKey,\n secretKey: this.secretKey,\n batchSize: config.exposureLogger?.batchSize,\n flushIntervalMs: config.exposureLogger?.flushIntervalMs,\n });\n }\n\n async register(input: RegisterExperimentInput): Promise<void> {\n const config: ExperimentConfig = {\n key: input.key,\n trafficPercent: input.trafficPercent ?? 100,\n variants: input.variants.map((v) => ({\n key: v.key,\n weight: v.weight ?? 1,\n config: v.config ?? {},\n })),\n };\n\n this.configs.set(config.key, config);\n\n const syncToBackend = input.syncToBackend ?? true;\n if (syncToBackend) {\n this.syncToBackendAsync(config, input.evaluatorNames).catch((err) => {\n console.error(\n `[gateway] Failed to sync experiment ${config.key}:`,\n err,\n );\n });\n }\n }\n\n async fetch(experimentKeys?: string[]): Promise<void> {\n const url = new URL(`${this.apiUrl}/api/public/experiments`);\n if (experimentKeys && experimentKeys.length > 0) {\n url.searchParams.set(\"keys\", experimentKeys.join(\",\"));\n }\n\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: authHeader,\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch experiments: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as {\n experiments: ExperimentConfig[];\n };\n for (const config of data.experiments) {\n this.configs.set(config.key, config);\n }\n }\n\n async getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n ): Promise<GetVariantResult> {\n const fetchIfMissing = options?.fetchIfMissing ?? true;\n\n let config = this.configs.get(experimentKey);\n if (!config && fetchIfMissing) {\n try {\n await this.fetch([experimentKey]);\n config = this.configs.get(experimentKey);\n } catch (error) {\n console.error(\n `[gateway] Failed to fetch experiment ${experimentKey}:`,\n error,\n );\n }\n }\n\n if (!config) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n const variant = assignVariant(config, userId);\n if (!variant) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n this.exposureLogger.log({\n userId,\n experimentId: experimentKey,\n variantKey: variant.key,\n timestamp: new Date().toISOString(),\n });\n\n const context = {\n experimentId: experimentKey,\n variantKey: variant.key,\n userId,\n };\n\n // Set context via enterWith() so spans created anywhere in this async chain are tagged.\n // Context is automatically isolated per request - no cross-request contamination.\n setExperimentContext(context);\n\n return {\n variant,\n inExperiment: true,\n experimentKey,\n run: (fn) => runWithExperimentContext(context, fn),\n };\n }\n\n getConfig(experimentKey: string): ExperimentConfig | undefined {\n return this.configs.get(experimentKey);\n }\n\n async shutdown(): Promise<void> {\n await this.exposureLogger.shutdown();\n }\n\n private async syncToBackendAsync(\n config: ExperimentConfig,\n evaluatorNames?: string[],\n ): Promise<void> {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(`${this.apiUrl}/api/public/experiments`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n key: config.key,\n trafficPercent: config.trafficPercent,\n variants: config.variants,\n evaluatorNames: evaluatorNames ?? [],\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `Failed to sync experiment: ${response.status} ${response.statusText} - ${text}`,\n );\n }\n\n console.log(`[gateway] Synced experiment '${config.key}' to backend`);\n }\n}\n","/**\n * OpenTelemetry integration for A/B experiments.\n *\n * Provides a SpanProcessor that automatically injects experiment\n * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.\n */\n\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n SpanProcessor,\n Span,\n ReadableSpan,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { getExperimentContext } from \"./context\";\n\nexport const EXPERIMENT_ATTRIBUTES = {\n EXPERIMENT_ID: \"gateway.experiment.id\",\n VARIANT_KEY: \"gateway.variant.key\",\n USER_ID: \"gateway.experiment.user_id\",\n} as const;\n\nexport class ExperimentSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const ctx = getExperimentContext();\n if (ctx) {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, ctx.experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, ctx.variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, ctx.userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport function addExperimentAttributes(\n span: Span,\n experimentId: string,\n variantKey: string,\n userId: string,\n): void {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, userId);\n}\n","/**\n * Singleton experiment client for simple usage.\n *\n * This mirrors the Python SDK's `gateway.experiments` singleton pattern.\n * For advanced use cases, instantiate ExperimentClient directly.\n */\n\nimport { ExperimentClient } from \"./client\";\nimport { clearExperimentContext as clearContext } from \"./context\";\nimport type {\n ExperimentClientConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nlet client: ExperimentClient | null = null;\n\nexport interface InitConfig {\n apiKey: string;\n secretKey?: string;\n baseUrl: string;\n projectId?: string;\n}\n\n/**\n * Initialize the experiments singleton.\n * Must be called before using other methods.\n */\nexport function init(config: InitConfig): void {\n client = new ExperimentClient({\n apiUrl: config.baseUrl,\n apiKey: config.apiKey,\n secretKey: config.secretKey,\n projectId: config.projectId ?? \"\",\n });\n}\n\n/**\n * Register an experiment configuration.\n */\nexport async function register(input: RegisterExperimentInput): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.register(input);\n}\n\n/**\n * Get variant for a user. Returns null if user is not in experiment.\n */\nexport async function getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n): Promise<GetVariantResult> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.getVariant(experimentKey, userId, options);\n}\n\n/**\n * Fetch experiment configurations from the backend.\n */\nexport async function fetch(experimentKeys?: string[]): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.fetch(experimentKeys);\n}\n\n/**\n * Flush pending exposures and shut down the client.\n */\nexport async function shutdown(): Promise<void> {\n if (client) {\n await client.shutdown();\n client = null;\n }\n // Also clear any lingering experiment context\n clearContext();\n}\n\n/**\n * Clear the current experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing new spans to the experiment.\n *\n * This mirrors Python's `gateway.experiments.clear_current_experiment()`.\n */\nexport function clearExperimentContext(): void {\n clearContext();\n}\n\n/**\n * Get the underlying ExperimentClient instance.\n * Returns null if not initialized.\n */\nexport function getClient(): ExperimentClient | null {\n return client;\n}\n","type ContextRepoKind = \"agent\" | \"prompt\" | \"skill\" | \"memory\";\ntype ContextWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype ContextFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype ContextRepo<TKind extends ContextRepoKind = ContextRepoKind> = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: TKind;\n description: string;\n readme: string;\n tags: string[];\n writePolicy: ContextWritePolicy;\n write_policy: ContextWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype ContextCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype ContextSnapshot<TKind extends ContextRepoKind = ContextRepoKind> = {\n repo: ContextRepo<TKind>;\n commit: ContextCommit;\n files: Record<string, ContextFileEntry>;\n};\n\ntype ContextListResponse<TKind extends ContextRepoKind = ContextRepoKind> = {\n repos: ContextRepo<TKind>[];\n limit: number;\n offset: number;\n total: number;\n};\n\ntype ContextPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype ContextFileInput =\n | {\n content: string;\n mimeType?: string;\n mime_type?: string;\n }\n | {\n repoHandle?: string;\n repo_handle?: string;\n kind?: \"agent\" | \"skill\";\n type?: \"agent\" | \"skill\";\n commitId?: string | null;\n commit_id?: string | null;\n }\n | null;\n\ntype ContextRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ContextPullOptions = {\n version?: string;\n};\n\ntype ContextListOptions = {\n query?: string;\n isPublic?: boolean;\n isArchived?: boolean;\n limit?: number;\n offset?: number;\n};\n\ntype ContextPushOptions = ContextRuntimeContext & {\n files: Record<string, ContextFileInput>;\n parentCommit?: string;\n description?: string;\n readme?: string;\n tags?: string[];\n isPublic?: boolean;\n writePolicy?: ContextWritePolicy;\n message?: string;\n};\n\ntype ContextRepoRef =\n | string\n | {\n identifier?: string;\n repoHandle?: string;\n repo_handle?: string;\n label?: string;\n version?: string;\n writable?: boolean;\n };\n\ntype ResolvedContextRef<TKind extends ContextRepoKind = ContextRepoKind> = {\n identifier: string;\n version?: string;\n writable?: boolean;\n snapshot: ContextSnapshot<TKind>;\n primaryPath: string | null;\n content: string;\n};\n\ntype ResolvedAgentContext = {\n agent: ContextSnapshot<\"agent\">;\n config: Record<string, unknown>;\n prompt: ResolvedContextRef<\"prompt\"> | null;\n prompts: ResolvedContextRef<\"prompt\">[];\n skills: ResolvedContextRef<\"skill\">[];\n memory: ResolvedContextRef<\"memory\">[];\n system: string;\n renderSystem: (options?: RenderSystemOptions) => string;\n provenance: ContextProvenance[];\n};\n\ntype ContextProvenance = {\n kind: ContextRepoKind;\n repoHandle: string;\n commitHash: string;\n label?: string;\n};\n\ntype RenderSystemOptions = {\n includeAgent?: boolean;\n includePrompts?: boolean;\n includeSkills?: boolean;\n includeMemory?: boolean;\n};\n\ntype GatewayContextConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayContextFromEnvConfig = Partial<GatewayContextConfig>;\n\nexport class GatewayContextError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayContextError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayContextConflictError extends GatewayContextError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayContextConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayContext {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayContextConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayContextFromEnvConfig = {}) {\n const host =\n config.host ?? process.env.GATEWAY_HOST ?? process.env.GATEWAY_HOST;\n const publicKey =\n config.publicKey ??\n process.env.GATEWAY_PUBLIC_KEY ??\n process.env.GATEWAY_PUBLIC_KEY;\n const secretKey =\n config.secretKey ??\n process.env.GATEWAY_SECRET_KEY ??\n process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewayContextError(\n `Missing Gateway context configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayContext({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n pullAgent(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"agent\", identifier, options);\n }\n\n pullPrompt(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"prompt\", identifier, options);\n }\n\n pullSkill(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"skill\", identifier, options);\n }\n\n pullMemory(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"memory\", identifier, options);\n }\n\n pushAgent(identifier: string, options: ContextPushOptions) {\n return this.push(\"agent\", identifier, options);\n }\n\n pushPrompt(identifier: string, options: ContextPushOptions) {\n return this.push(\"prompt\", identifier, options);\n }\n\n pushSkill(identifier: string, options: ContextPushOptions) {\n return this.push(\"skill\", identifier, options);\n }\n\n pushMemory(identifier: string, options: ContextPushOptions) {\n return this.push(\"memory\", identifier, options);\n }\n\n listAgents(options: ContextListOptions = {}) {\n return this.list(\"agent\", options);\n }\n\n listPrompts(options: ContextListOptions = {}) {\n return this.list(\"prompt\", options);\n }\n\n listSkills(options: ContextListOptions = {}) {\n return this.list(\"skill\", options);\n }\n\n listMemory(options: ContextListOptions = {}) {\n return this.list(\"memory\", options);\n }\n\n agentExists(identifier: string) {\n return this.exists(\"agent\", identifier);\n }\n\n promptExists(identifier: string) {\n return this.exists(\"prompt\", identifier);\n }\n\n skillExists(identifier: string) {\n return this.exists(\"skill\", identifier);\n }\n\n memoryExists(identifier: string) {\n return this.exists(\"memory\", identifier);\n }\n\n deleteAgent(identifier: string) {\n return this.delete(\"agent\", identifier);\n }\n\n deletePrompt(identifier: string) {\n return this.delete(\"prompt\", identifier);\n }\n\n deleteSkill(identifier: string) {\n return this.delete(\"skill\", identifier);\n }\n\n deleteMemory(identifier: string) {\n return this.delete(\"memory\", identifier);\n }\n\n async resolveAgent(\n identifier: string,\n runtimeContext: ContextRuntimeContext = {},\n ): Promise<ResolvedAgentContext> {\n const agent = await this.pullAgent(identifier);\n const config = parseJsonFile(agent, \"config.json\");\n const prompts = await this.resolveRefs(\"prompt\", getPromptRefs(config));\n const skills = await this.resolveRefs(\"skill\", getRefList(config.skills));\n const memory = await this.resolveRefs(\"memory\", getRefList(config.memory));\n const bundleBase = {\n agent,\n config,\n prompt: prompts[0] ?? null,\n prompts,\n skills,\n memory,\n provenance: [\n provenanceFor(agent),\n ...prompts.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...skills.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...memory.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ],\n };\n\n const renderSystem = (options: RenderSystemOptions = {}) =>\n renderAgentSystem(bundleBase, options);\n\n if (Object.keys(runtimeContext).length > 0) {\n this.log(\"resolveAgent runtime context %o\", runtimeContext);\n }\n\n return {\n ...bundleBase,\n system: renderSystem(),\n renderSystem,\n };\n }\n\n async pull<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPullOptions = {},\n ): Promise<ContextSnapshot<TKind>> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextSnapshot<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}${suffix}`,\n );\n }\n\n async push<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPushOptions,\n ): Promise<ContextPushResponse> {\n return this.requestJson<ContextPushResponse>(\n \"POST\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}`,\n {\n files: options.files,\n ...(options.parentCommit ? { parentCommit: options.parentCommit } : {}),\n ...(options.description ? { description: options.description } : {}),\n ...(options.readme ? { readme: options.readme } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n ...(options.isPublic !== undefined ? { isPublic: options.isPublic } : {}),\n ...(options.writePolicy ? { writePolicy: options.writePolicy } : {}),\n ...(options.message ? { message: options.message } : {}),\n ...runtimeContextPayload(options),\n },\n );\n }\n\n async list<TKind extends ContextRepoKind>(\n kind: TKind,\n options: ContextListOptions = {},\n ): Promise<ContextListResponse<TKind>> {\n const query = new URLSearchParams();\n if (options.query) query.set(\"query\", options.query);\n if (options.isPublic !== undefined) query.set(\"isPublic\", String(options.isPublic));\n if (options.isArchived !== undefined)\n query.set(\"isArchived\", String(options.isArchived));\n if (options.limit !== undefined) query.set(\"limit\", String(options.limit));\n if (options.offset !== undefined) query.set(\"offset\", String(options.offset));\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextListResponse<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}${suffix}`,\n );\n }\n\n async exists(kind: ContextRepoKind, identifier: string): Promise<boolean> {\n const query = new URLSearchParams({ exists: \"true\" });\n const response = await this.requestJson<{ exists: boolean }>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}?${query.toString()}`,\n );\n return response.exists;\n }\n\n async delete(kind: ContextRepoKind, identifier: string) {\n return this.requestJson<{ deleted: boolean; repoHandle: string; repo_handle: string }>(\n \"DELETE\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(identifier)}`,\n );\n }\n\n private async resolveRefs<TKind extends ContextRepoKind>(\n kind: TKind,\n refs: ContextRepoRef[],\n ): Promise<ResolvedContextRef<TKind>[]> {\n const resolved: ResolvedContextRef<TKind>[] = [];\n for (const ref of refs) {\n const normalized = normalizeRef(ref);\n if (!normalized) continue;\n const snapshot = await this.pull(kind, normalized.identifier, {\n version: normalized.version,\n });\n const primaryPath = primaryPathForKind(kind, snapshot);\n const content = primaryPath ? readFile(snapshot, primaryPath) ?? \"\" : \"\";\n resolved.push({\n ...normalized,\n snapshot,\n primaryPath,\n content,\n });\n }\n return resolved;\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayContextConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayContextError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.context] ${message}`, ...args);\n }\n }\n}\n\nfunction renderAgentSystem(\n bundle: Omit<ResolvedAgentContext, \"system\" | \"renderSystem\">,\n options: RenderSystemOptions = {},\n) {\n const includeAgent = options.includeAgent ?? true;\n const includePrompts = options.includePrompts ?? true;\n const includeSkills = options.includeSkills ?? true;\n const includeMemory = options.includeMemory ?? false;\n const sections: string[] = [];\n\n if (includeAgent) {\n const agentContent = readFile(bundle.agent, \"AGENTS.md\");\n if (agentContent) sections.push(formatSection(\"Agent\", bundle.agent, agentContent));\n }\n\n if (includePrompts) {\n for (const prompt of bundle.prompts) {\n if (prompt.content) {\n sections.push(formatSection(\"Prompt\", prompt.snapshot, prompt.content));\n }\n }\n }\n\n if (includeSkills) {\n for (const skill of bundle.skills) {\n if (skill.content) {\n sections.push(formatSection(\"Skill\", skill.snapshot, skill.content));\n }\n }\n }\n\n if (includeMemory) {\n for (const memory of bundle.memory) {\n if (memory.content) {\n sections.push(formatSection(\"Memory\", memory.snapshot, memory.content));\n }\n }\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nfunction formatSection(\n title: string,\n snapshot: ContextSnapshot,\n content: string,\n) {\n return [\n `# ${title}: ${snapshot.repo.repoHandle}`,\n `<!-- commit: ${snapshot.commit.commitHash} -->`,\n \"\",\n content.trim(),\n ].join(\"\\n\");\n}\n\nfunction getPromptRefs(config: Record<string, unknown>): ContextRepoRef[] {\n const refs = [\n ...getRefList(config.prompt),\n ...getRefList(config.promptRef),\n ...getRefList(config.prompt_ref),\n ...getRefList(config.prompts),\n ];\n return dedupeRefs(refs);\n}\n\nfunction getRefList(value: unknown): ContextRepoRef[] {\n if (!value) return [];\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isContextRepoRef);\n if (isContextRepoRef(value)) return [value];\n return [];\n}\n\nfunction isContextRepoRef(value: unknown): value is ContextRepoRef {\n if (typeof value === \"string\") return true;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return [\"identifier\", \"repoHandle\", \"repo_handle\"].some(\n (key) => typeof record[key] === \"string\",\n );\n}\n\nfunction dedupeRefs(refs: ContextRepoRef[]) {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n const normalized = normalizeRef(ref);\n if (!normalized) return false;\n const key = `${normalized.identifier}:${normalized.version ?? \"\"}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction normalizeRef(ref: ContextRepoRef) {\n if (typeof ref === \"string\") {\n const identifier = ref.trim();\n return identifier ? { identifier } : null;\n }\n\n const identifier = (\n ref.identifier ??\n ref.repoHandle ??\n ref.repo_handle ??\n \"\"\n ).trim();\n if (!identifier) return null;\n\n return {\n identifier,\n version: ref.version ?? ref.label,\n writable: ref.writable,\n };\n}\n\nfunction primaryPathForKind(kind: ContextRepoKind, snapshot: ContextSnapshot) {\n const preferred =\n kind === \"agent\"\n ? \"AGENTS.md\"\n : kind === \"prompt\"\n ? \"PROMPT.md\"\n : kind === \"skill\"\n ? \"SKILL.md\"\n : \"MEMORY.md\";\n if (readFile(snapshot, preferred)) return preferred;\n return (\n Object.entries(snapshot.files).find(\n ([path, entry]) => entry.type === \"file\" && path.endsWith(\".md\"),\n )?.[0] ?? null\n );\n}\n\nfunction parseJsonFile(snapshot: ContextSnapshot, path: string) {\n const content = readFile(snapshot, path);\n if (!content) return {};\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction readFile(snapshot: ContextSnapshot, path: string) {\n const entry = snapshot.files[path];\n return entry?.type === \"file\" ? entry.content : null;\n}\n\nfunction provenanceFor(\n snapshot: ContextSnapshot,\n label?: string,\n): ContextProvenance {\n return {\n kind: snapshot.repo.kind,\n repoHandle: snapshot.repo.repoHandle,\n commitHash: snapshot.commit.commitHash,\n ...(label ? { label } : {}),\n };\n}\n\nfunction endpointForKind(kind: ContextRepoKind) {\n return kind === \"memory\" ? \"memory\" : `${kind}s`;\n}\n\nfunction runtimeContextPayload(options: ContextRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const context = {\n fromEnv: GatewayContext.fromEnv,\n};\n\nexport { renderAgentSystem };\n\nexport type {\n GatewayContextConfig,\n ContextCommit as GatewayContextCommit,\n ContextFileEntry as GatewayContextFileEntry,\n ContextFileInput as GatewayContextFileInput,\n ContextListOptions as GatewayContextListOptions,\n ContextListResponse as GatewayContextListResponse,\n ContextPullOptions as GatewayContextPullOptions,\n ContextPushOptions as GatewayContextPushOptions,\n ContextPushResponse as GatewayContextPushResponse,\n ContextRepo as GatewayContextRepo,\n ContextRepoKind as GatewayContextRepoKind,\n ContextRuntimeContext as GatewayContextRuntimeContext,\n ContextSnapshot as GatewayContextSnapshot,\n ContextWritePolicy as GatewayContextWritePolicy,\n RenderSystemOptions as GatewayRenderSystemOptions,\n ResolvedAgentContext as GatewayResolvedAgentContext,\n ResolvedContextRef as GatewayResolvedContextRef,\n};\n","type MemoryWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype MemoryFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype MemoryRepo = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: \"memory\";\n description: string;\n readme: string;\n tags: string[];\n writePolicy: MemoryWritePolicy;\n write_policy: MemoryWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype MemoryCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype MemorySnapshot = {\n repo: MemoryRepo;\n commit: MemoryCommit;\n files: Record<string, MemoryFileEntry>;\n};\n\ntype MemoryPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype MemoryRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype MemoryPullOptions = {\n version?: string;\n};\n\ntype MemoryWriteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n mimeType?: string;\n};\n\ntype MemoryDeleteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n};\n\ntype GatewayMemoryConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayMemoryFromEnvConfig = Partial<GatewayMemoryConfig>;\n\nexport class GatewayMemoryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayMemoryError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayMemoryConflictError extends GatewayMemoryError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayMemoryConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayMemory {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayMemoryConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayMemoryFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewayMemoryError(\n `Missing Gateway memory configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayMemory({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async pull(\n identifier: string,\n options: MemoryPullOptions = {},\n ): Promise<MemorySnapshot> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<MemorySnapshot>(\n \"GET\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}${suffix}`,\n );\n }\n\n async read(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryPullOptions = {},\n ): Promise<string | null> {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target, options) : target;\n const file = snapshot.files[path];\n return file?.type === \"file\" ? file.content : null;\n }\n\n async write(\n target: string | MemorySnapshot,\n path: string,\n content: string,\n options: MemoryWriteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: {\n [path]: {\n content,\n ...(options.mimeType ? { mimeType: options.mimeType } : {}),\n },\n },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n async delete(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryDeleteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: { [path]: null },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n private async push(\n identifier: string,\n payload: Record<string, unknown>,\n ): Promise<MemoryPushResponse> {\n return this.requestJson<MemoryPushResponse>(\n \"POST\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}`,\n payload,\n );\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayMemoryConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayMemoryError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.memory] ${message}`, ...args);\n }\n }\n}\n\nfunction runtimeContextPayload(options: MemoryRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const memory = {\n fromEnv: GatewayMemory.fromEnv,\n};\n\nexport type {\n GatewayMemoryConfig,\n MemoryCommit as GatewayMemoryCommit,\n MemoryDeleteOptions as GatewayMemoryDeleteOptions,\n MemoryFileEntry as GatewayMemoryFileEntry,\n MemoryPullOptions as GatewayMemoryPullOptions,\n MemoryPushResponse as GatewayMemoryPushResponse,\n MemoryRepo as GatewayMemoryRepo,\n MemoryRuntimeContext as GatewayMemoryRuntimeContext,\n MemorySnapshot as GatewayMemorySnapshot,\n MemoryWriteOptions as GatewayMemoryWriteOptions,\n MemoryWritePolicy as GatewayMemoryWritePolicy,\n};\n","/**\n * Personas — simulated users served by the Gateway platform.\n *\n * A persona is a crafted user profile (usually derived from real sessions on\n * the platform) that Gateway serves as an endpoint. Use it to drive your agent\n * in tests: the persona plays the user, your agent plays itself.\n *\n * Example:\n * ```ts\n * import { PersonasClient } from \"@withgateway/sdk/personas\";\n *\n * const personas = PersonasClient.fromEnv();\n * const persona = await personas.get(\"persona_id\");\n *\n * const messages: PersonaMessage[] = [];\n * let reply = await persona.respond(messages); // persona opens the conversation\n * while (!reply.done) {\n * messages.push({ role: \"user\", content: reply.content });\n * const agentAnswer = await myAgent(messages); // your agent under test\n * messages.push({ role: \"assistant\", content: agentAnswer });\n * reply = await persona.respond(messages);\n * }\n * ```\n *\n * Message roles are from YOUR agent's perspective: `user` = the simulated\n * user's turns, `assistant` = your agent's turns.\n */\n\ntype PersonaMessage = {\n role: \"user\" | \"assistant\";\n content: string;\n};\n\n/** One simulated-user turn. */\ntype PersonaReply = {\n content: string;\n done: boolean;\n};\n\ntype PersonasClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype PersonasClientFromEnvConfig = Partial<PersonasClientConfig>;\n\n/** Raised when the Gateway personas API cannot complete a request. */\nexport class PersonaError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"PersonaError\";\n this.cause = options?.cause;\n }\n}\n\n/** A persona definition plus a bound `respond` helper. */\nexport class Persona {\n readonly id: string;\n readonly name: string;\n readonly description: string | null;\n readonly version: number;\n readonly instructions: string;\n readonly examples: string[];\n private readonly client: PersonasClient | null;\n\n constructor(fields: {\n id: string;\n name: string;\n description: string | null;\n version: number;\n instructions: string;\n examples?: string[];\n client?: PersonasClient | null;\n }) {\n this.id = fields.id;\n this.name = fields.name;\n this.description = fields.description;\n this.version = fields.version;\n this.instructions = fields.instructions;\n this.examples = fields.examples ?? [];\n this.client = fields.client ?? null;\n }\n\n /**\n * Get the persona's next user message for a conversation.\n *\n * `messages` use your agent's perspective: role `user` for the simulated\n * user's prior turns, `assistant` for your agent's turns.\n * `done` is true when the persona considers its goal met.\n */\n respond(messages: PersonaMessage[]): Promise<PersonaReply> {\n if (this.client === null) {\n throw new PersonaError(\"Persona is not bound to a client.\");\n }\n return this.client.chat(this.id, messages);\n }\n}\n\n/** Client for Gateway's persona endpoints (HTTP Basic project keys). */\nexport class PersonasClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: PersonasClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 120;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: PersonasClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new PersonaError(\n `Missing Gateway persona configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new PersonasClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** List the project's personas (without full instructions). */\n async list(): Promise<Persona[]> {\n const payload = await this.requestJson(\"GET\", \"/api/public/personas\");\n const items = Array.isArray(payload.data) ? payload.data : [];\n return items\n .filter(isRecord)\n .map(\n (item) =>\n new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: \"\",\n client: this,\n }),\n );\n }\n\n /** Fetch a persona (full definition) bound to this client. */\n async get(personaId: string): Promise<Persona> {\n const item = await this.requestJson(\n \"GET\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n );\n return new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: typeof item.instructions === \"string\" ? item.instructions : \"\",\n examples: Array.isArray(item.examples)\n ? item.examples.map((example) => String(example))\n : [],\n client: this,\n });\n }\n\n /** Play one persona turn. See {@link Persona.respond}. */\n async chat(\n personaId: string,\n messages: PersonaMessage[],\n ): Promise<PersonaReply> {\n const payload = await this.requestJson(\n \"POST\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n { messages },\n );\n return {\n content: typeof payload.content === \"string\" ? payload.content : \"\",\n done: Boolean(payload.done),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new PersonaError(`${method} ${path} failed: ${reason}`, {\n cause: error,\n });\n }\n\n const text = await response.text();\n if (!response.ok) {\n const detail = text.slice(0, 500);\n throw new PersonaError(\n `${method} ${path} failed (${response.status}): ${detail}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.personas] ${message}`, ...args);\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport const personas = {\n fromEnv: PersonasClient.fromEnv,\n};\n\nexport type {\n PersonaMessage,\n PersonaReply,\n PersonasClientConfig,\n PersonasClientFromEnvConfig,\n};\n","/**\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","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by the dream agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\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, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const replay = {\n suite,\n run: runSuite,\n};\n","type AgentDescriptor = {\n id?: string;\n name?: string;\n version?: string;\n};\n\ntype SecurityContext = {\n executionId?: string;\n userId?: string;\n teamId?: string;\n environment?: string;\n contextLabel?: string;\n contextBundleHash?: string;\n traceId?: string;\n sessionId?: string;\n spanId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolDescriptor = {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolsetResolveResponse = {\n toolsetId: string;\n mode: \"observe\" | \"filter\" | \"enforce\";\n policyVersion: number;\n ttlSeconds: number;\n allowedToolIds: string[];\n blockedToolIds: string[];\n approvalToolIds: string[];\n secretBindings: Record<string, string[]>;\n failMode: \"open\" | \"closed\";\n};\n\ntype ToolCallAuthorizeResponse = {\n decisionId: string;\n outcome: \"allow\" | \"flag\" | \"block\" | \"approval_required\";\n reasonCode: string;\n message: string;\n policyVersion: number;\n};\n\ntype ToolObject = {\n description?: string;\n execute?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n};\n\ntype ToolCollection = Record<\n string,\n ToolObject | ((...args: unknown[]) => unknown)\n>;\n\ntype SecureToolsOptions<TTools extends ToolCollection> = {\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: TTools;\n context?: SecurityContext;\n toolIds?: Partial<Record<keyof TTools & string, string>>;\n toolMetadata?: Partial<\n Record<keyof TTools & string, Record<string, unknown>>\n >;\n};\n\ntype GatewaySecurityConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n agent?: AgentDescriptor;\n debug?: boolean;\n failOpen?: boolean;\n};\n\ntype GatewaySecurityFromEnvConfig = Partial<\n Pick<GatewaySecurityConfig, \"host\" | \"publicKey\" | \"secretKey\">\n> &\n Pick<GatewaySecurityConfig, \"agent\" | \"debug\" | \"failOpen\">;\n\nconst SECURITY_ATTRIBUTES = {\n AGENT_ID: \"gateway.agent.id\",\n AGENT_NAME: \"gateway.agent.name\",\n AGENT_VERSION: \"gateway.agent.version\",\n TOOLSET_ID: \"gateway.toolset.id\",\n TOOL_ID: \"gateway.tool.id\",\n SECURITY_MODE: \"gateway.security.mode\",\n POLICY_VERSION: \"gateway.security.policy_version\",\n DECISION_OUTCOME: \"gateway.decision.outcome\",\n DECISION_REASON_CODE: \"gateway.decision.reason_code\",\n} as const;\n\nexport class GatewaySecurityError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewaySecurityError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayToolBlockedError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway blocked tool ${toolId}`);\n this.name = \"GatewayToolBlockedError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\n/**\n * Thrown when Gateway's policy returns `approval_required` for a tool call.\n * The SDK does NOT execute the tool — a human/system approval is needed first\n * (the server engine and the runtime MCP PEP both honor this; this closes the\n * SDK leg of the step-up gate so an approval decision can't be silently run).\n */\nexport class GatewayToolApprovalRequiredError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway requires approval for tool ${toolId}`);\n this.name = \"GatewayToolApprovalRequiredError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\nexport class GatewaySecurity {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly agent: AgentDescriptor;\n private readonly debug: boolean;\n private readonly failOpen: boolean;\n\n constructor(config: GatewaySecurityConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.agent = config.agent ?? {};\n this.debug = config.debug ?? false;\n this.failOpen = config.failOpen ?? false;\n }\n\n static fromEnv(config: GatewaySecurityFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewaySecurityError(\n `Missing Gateway security configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewaySecurity({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async secureTools<TTools extends ToolCollection>(\n options: SecureToolsOptions<TTools>,\n ): Promise<TTools> {\n const entries = Object.entries(options.tools);\n const descriptors = entries.map(([key, tool]) =>\n this.describeTool(key, tool, options),\n );\n const resolve = await this.resolveToolset({\n agent: this.agent,\n toolsetId: options.toolsetId,\n toolsetName: options.toolsetName,\n provider: options.provider,\n tools: descriptors,\n context: this.normalizeContext(options.context),\n });\n\n const securedEntries = entries.flatMap(([key, tool]) => {\n const descriptor = descriptors.find((item) => item.name === key)!;\n if (!this.shouldExposeTool(resolve, descriptor.id)) {\n this.log(\"Hiding tool %s in %s mode\", descriptor.id, resolve.mode);\n return [];\n }\n\n return [\n [\n key,\n this.wrapTool(tool, {\n toolId: descriptor.id,\n toolsetId: options.toolsetId,\n context: this.normalizeContext(options.context),\n resolve,\n }),\n ],\n ];\n });\n\n return Object.fromEntries(securedEntries) as TTools;\n }\n\n private async resolveToolset(input: {\n agent: AgentDescriptor;\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: ToolDescriptor[];\n context: SecurityContext;\n }) {\n return this.postJson<ToolsetResolveResponse>(\n \"/api/public/security/toolsets/resolve\",\n input,\n );\n }\n\n private async authorizeToolCall(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n return this.postJson<ToolCallAuthorizeResponse>(\n \"/api/public/security/tool-calls/authorize\",\n {\n agent: this.agent,\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: input.inputMetadata,\n },\n );\n }\n\n private wrapTool(\n tool: ToolObject | ((...args: unknown[]) => unknown),\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n if (typeof tool === \"function\") {\n return this.wrapExecute(tool, input);\n }\n\n if (typeof tool.execute !== \"function\") {\n return tool;\n }\n\n return {\n ...tool,\n execute: this.wrapExecute(tool.execute.bind(tool), input),\n };\n }\n\n private wrapExecute(\n execute: (...args: unknown[]) => unknown,\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n return async (...args: unknown[]) => {\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.AGENT_ID]: this.agent.id,\n [SECURITY_ATTRIBUTES.AGENT_NAME]: this.agent.name,\n [SECURITY_ATTRIBUTES.AGENT_VERSION]: this.agent.version,\n [SECURITY_ATTRIBUTES.TOOLSET_ID]: input.toolsetId,\n [SECURITY_ATTRIBUTES.TOOL_ID]: input.toolId,\n [SECURITY_ATTRIBUTES.SECURITY_MODE]: input.resolve.mode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: input.resolve.policyVersion,\n });\n\n const decision = await this.authorizeOrFallback({\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: { args },\n });\n\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.DECISION_OUTCOME]: decision.outcome,\n [SECURITY_ATTRIBUTES.DECISION_REASON_CODE]: decision.reasonCode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: decision.policyVersion,\n });\n\n if (decision.outcome === \"block\") {\n throw new GatewayToolBlockedError(input.toolId, decision);\n }\n if (decision.outcome === \"approval_required\") {\n // Enforce the step-up gate: do NOT execute until approved. The tool\n // stays callable (so the approval flow can be triggered), but a call\n // is refused with a typed error rather than running unapproved.\n throw new GatewayToolApprovalRequiredError(input.toolId, decision);\n }\n\n return execute(...args);\n };\n }\n\n private async authorizeOrFallback(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n try {\n return await this.authorizeToolCall(input);\n } catch (error) {\n if (this.failOpen) {\n this.log(\"Authorization failed open for tool %s\", input.toolId, error);\n return {\n decisionId: \"local-fail-open\",\n outcome: \"flag\" as const,\n reasonCode: \"authorization_unavailable_fail_open\",\n message:\n \"Gateway authorization was unavailable; failOpen allowed execution.\",\n policyVersion: 0,\n };\n }\n throw new GatewaySecurityError(\n `Gateway authorization failed for tool ${input.toolId}`,\n { cause: error },\n );\n }\n }\n\n private async postJson<TResponse>(\n path: string,\n payload: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method: \"POST\",\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new GatewaySecurityError(\n `Gateway API ${response.status} on ${path}: ${body || response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n }\n\n private describeTool<TTools extends ToolCollection>(\n key: string,\n tool: ToolObject | ((...args: unknown[]) => unknown),\n options: SecureToolsOptions<TTools>,\n ): ToolDescriptor & { name: string } {\n const toolObject = typeof tool === \"function\" ? undefined : tool;\n const id =\n options.toolIds?.[key] ?? `${options.toolsetId}.${toSnakeCase(key)}`;\n return {\n id,\n name: key,\n description:\n typeof toolObject?.description === \"string\"\n ? toolObject.description\n : undefined,\n metadata: options.toolMetadata?.[key] ?? {},\n };\n }\n\n private shouldExposeTool(resolve: ToolsetResolveResponse, toolId: string) {\n if (resolve.mode === \"observe\") return true;\n if (resolve.blockedToolIds.includes(toolId)) return false;\n return true;\n }\n\n private normalizeContext(context?: SecurityContext): SecurityContext {\n return {\n ...(context ?? {}),\n metadata: context?.metadata ?? {},\n };\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private setSpanAttributes(attributes: Record<string, unknown>) {\n const span = getActiveSpan();\n if (!span) return;\n\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined || value === null) continue;\n span.setAttribute(key, value);\n }\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.security] ${message}`, ...args);\n }\n }\n}\n\nfunction getActiveSpan(): {\n setAttribute: (key: string, value: unknown) => void;\n} | null {\n try {\n // Optional peer dependency. Avoid making security unusable without tracing.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const otel = require(\"@opentelemetry/api\") as {\n trace?: {\n getActiveSpan?: () =>\n | { setAttribute: (key: string, value: unknown) => void }\n | undefined;\n };\n };\n return otel.trace?.getActiveSpan?.() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction toSnakeCase(value: string) {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[\\s-]+/g, \"_\")\n .toLowerCase();\n}\n\nexport const gateway = {\n fromEnv: GatewaySecurity.fromEnv,\n};\n\nexport type {\n AgentDescriptor as GatewayAgentDescriptor,\n GatewaySecurityConfig,\n SecurityContext as GatewaySecurityContext,\n SecureToolsOptions,\n ToolCallAuthorizeResponse as GatewayToolCallAuthorizeResponse,\n ToolDescriptor as GatewayToolDescriptor,\n ToolsetResolveResponse as GatewayToolsetResolveResponse,\n};\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n","/**\n * Initialization and lifecycle management for GatewaySDK tracing.\n *\n * This module provides the core init(), shutdown(), and flush() functions\n * for managing the OpenTelemetry TracerProvider lifecycle, plus\n * initIsolated() for creating additional self-contained providers (e.g. one\n * process exporting different agents to different Gateway projects).\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\n\n// Environment variable names. (A legacy BRIDGELAYER_* prefix predated the\n// rebrand but was never in any published release, so only GATEWAY_* exists.)\nconst ENV_VARS = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nconst DEFAULT_OTLP_PATH = \"/api/public/otel/v1/traces\";\n\n// Module-level state\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/**\n * Build a fully-configured NodeTracerProvider from config + env. Shared by\n * init() (which registers it globally) and initIsolated() (which does not).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n // Resolve configuration from params or environment\n const host = config.host ?? getEnv(ENV_VARS.HOST);\n const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(ENV_VARS.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${DEFAULT_OTLP_PATH}` : undefined);\n\n // Validate required configuration\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Dynamically import OpenTelemetry modules (they're peer dependencies)\n // Using 'any' to avoid version conflicts between OTel packages\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n // Handle both old (Resource class) and new (resourceFromAttributes function) APIs\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n // Try semantic conventions, fall back to string literal\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new Error(\n \"OpenTelemetry packages not found. Install them with:\\n\" +\n \"npm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \" +\n \"@opentelemetry/exporter-trace-otlp-http @opentelemetry/resources\",\n );\n }\n\n // Build resource attributes\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Security check: block insecure HTTP (except localhost/127.0.0.1)\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n // Construct Basic Auth header\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Build span processors — custom processors go first (before the BatchSpanProcessor)\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(sp);\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n // Stamp the ambient end-user identity (identify() / GATEWAY_USER_ID) on\n // every span at start — mirrors the Python SDK's TracingContextSpanProcessor.\n spanProcessors.push(new IdentitySpanProcessor());\n\n // Add BatchSpanProcessor with exporter\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));\n\n // Create provider — detect v1 vs v2 API via runtime feature check.\n // v1 has addSpanProcessor(); v2 removed it and requires spanProcessors in constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n // v1 API: register each processor individually\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n // v2 API: must pass spanProcessors in constructor — recreate\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return provider;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n // Store debug flag in state for log() function\n state.debug = config.debug ?? false;\n\n const provider = buildProvider(config, log);\n provider.register();\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook (e.g. the Vercel AI SDK's\n * `experimental_telemetry.tracer`). Context propagation still works across\n * providers, so nesting behaves exactly as with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const provider = buildProvider(config, debugLog);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n const host = getEnv(ENV_VARS.HOST);\n const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = getEnv(ENV_VARS.SECRET_KEY);\n return !!(host && publicKey && secretKey);\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,oBAA2B;AAGpB,SAAS,YAAY,eAAuB,QAAwB;AACzE,QAAM,UAAM,0BAAW,QAAQ,EAC5B,OAAO,GAAG,a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AI;AAAA,IACX;AAAA,EACF;AACF;;;AnB3OO,IAAM,UAAiC;AAAA,EAC5C,GAAG;AAAA,EACH,KAAK,SAAwB,CAAC,GAAG;AAC/B,QAAI,OAAO,sBAAsB,OAAO;AACtC,YAAM,aAAa;AAAA,QACjB,IAAI,wBAAwB;AAAA,QAC5B,GAAI,OAAO,wBAAwB,CAAC;AAAA,MACtC;AACA,aAAsBC,MAAK;AAAA,QACzB,GAAG;AAAA,QACH,sBAAsB;AAAA,MACxB,CAAC;AAAA,IACH;AACA,WAAsBA,MAAK,MAAM;AAAA,EACnC;AACF;","names":["context","context","clearExperimentContext","fetch","fetch","clearExperimentContext","memory","identifier","encodeIdentifier","runtimeContextPayload","safeJson","safeJson","trace","import_node_path","isPlainObject","context","safeJson","import_async_hooks","init","shutdown","init","debugLog","shutdown","import_api","warn","client","import_api","init"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/experiments/assignment.ts","../src/experiments/context.ts","../src/experiments/exposure-logger.ts","../src/experiments/client.ts","../src/experiments/otel.ts","../src/experiments/singleton.ts","../src/context/index.ts","../src/memory/index.ts","../src/personas/index.ts","../src/sessions/index.ts","../src/replay/index.ts","../src/security/index.ts","../src/users/index.ts","../src/tracing/identity.ts","../src/tracing/index.ts","../src/tracing/init.ts","../src/tracing/observe.ts","../src/tracing/instrument.ts","../src/tracing/claude.ts"],"sourcesContent":["export * from \"./experiments/index\";\nexport * from \"./context/index\";\nexport * from \"./memory/index\";\nexport * from \"./personas/index\";\nexport * from \"./replay/index\";\nexport * from \"./security/index\";\nexport * from \"./sessions/index\";\nexport * from \"./users/index\";\n\n// Top-level like the Python SDK's `gatewaysdk.identify` (lives in tracing/identity).\nexport { identify, resolveUserId } from \"./tracing/identity\";\nexport type { IdentifyOptions } from \"./tracing/identity\";\n\nimport * as _tracingModule from \"./tracing/index\";\nimport type { TracingConfig } from \"./tracing/types\";\nimport { ExperimentSpanProcessor } from \"./experiments/otel\";\n\n/**\n * Tracing module with automatic ExperimentSpanProcessor wiring.\n *\n * When imported from the main entry (\"@withgateway/sdk\"), init() automatically\n * adds ExperimentSpanProcessor so spans are tagged with experiment context.\n * Both modules share the same bundle, so the AsyncLocalStorage context is\n * shared — no cross-bundle duplication.\n */\nexport const tracing: typeof _tracingModule = {\n ..._tracingModule,\n init(config: TracingConfig = {}) {\n if (config.enableExperiments !== false) {\n const processors = [\n new ExperimentSpanProcessor(),\n ...(config.customSpanProcessors ?? []),\n ];\n return _tracingModule.init({\n ...config,\n customSpanProcessors: processors,\n });\n }\n return _tracingModule.init(config);\n },\n};\n","/**\n * Deterministic variant assignment for A/B experiments.\n *\n * Algorithm:\n * 1. Hash (experiment_key + user_id) → deterministic bucket [0, 1)\n * 2. If bucket >= traffic_percent/100 → user not in experiment\n * 3. Otherwise, normalize bucket within traffic and assign to variant by weight\n */\n\nimport { createHash } from \"crypto\";\nimport type { ExperimentConfig, Variant } from \"./types\";\n\nexport function computeHash(experimentKey: string, userId: string): number {\n const raw = createHash(\"sha256\")\n .update(`${experimentKey}:${userId}`)\n .digest(\"hex\");\n // Divide by 2³² to keep range strictly [0, 1)\n return parseInt(raw.slice(0, 8), 16) / 0x100000000;\n}\n\nexport function assignVariant(\n config: ExperimentConfig,\n userId: string,\n): Variant | null {\n if (!config.variants || config.variants.length === 0) {\n return null;\n }\n\n const bucket = computeHash(config.key, userId);\n const trafficThreshold = config.trafficPercent / 100;\n\n if (bucket >= trafficThreshold) {\n return null;\n }\n\n const normalizedBucket = bucket / trafficThreshold;\n const totalWeight = config.variants.reduce((sum, v) => sum + v.weight, 0);\n\n if (totalWeight <= 0) {\n return config.variants[0] ?? null;\n }\n\n let cumulative = 0;\n for (const variant of config.variants) {\n cumulative += variant.weight / totalWeight;\n if (normalizedBucket < cumulative) {\n return variant;\n }\n }\n\n return config.variants[config.variants.length - 1] ?? null;\n}\n","/**\n * Async context management for experiments.\n *\n * Uses AsyncLocalStorage.enterWith() to set context that persists for the\n * remainder of the current async execution context. This provides:\n *\n * - Request isolation in concurrent server environments\n * - Context that survives across async boundaries (streaming, etc.)\n * - No callback wrapper required\n *\n * The context persists until clearExperimentContext() is called or the\n * async context naturally ends (e.g., request completes).\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport type { ExperimentContext } from \"./types\";\n\n// AsyncLocalStorage for request-scoped context\nexport const experimentContextStorage =\n new AsyncLocalStorage<ExperimentContext>();\n\n/**\n * Get the current experiment context.\n */\nexport function getExperimentContext(): ExperimentContext | undefined {\n return experimentContextStorage.getStore();\n}\n\n/**\n * Set the experiment context for the current async execution.\n *\n * Uses enterWith() which sets context for the remainder of the current\n * async execution without requiring a callback wrapper. This means:\n * - Context persists across await boundaries\n * - Context is isolated per request in concurrent environments\n * - Context persists until clearExperimentContext() or request ends\n *\n * Called by getVariant() when a user is assigned to a variant.\n */\nexport function setExperimentContext(context: ExperimentContext): void {\n experimentContextStorage.enterWith(context);\n}\n\n/**\n * Clear the experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing spans to the experiment.\n *\n * Note: In most server frameworks, the async context naturally ends when the\n * request completes, so this is optional but recommended for explicit cleanup.\n */\nexport function clearExperimentContext(): void {\n // enterWith(undefined) effectively clears the context\n experimentContextStorage.enterWith(undefined as unknown as ExperimentContext);\n}\n\n/**\n * Run a function with experiment context (scoped).\n *\n * The context is automatically cleared when the function completes.\n * This is useful for synchronous operations or fully-contained async operations.\n *\n * For streaming/async patterns, prefer setExperimentContext() which persists\n * across async boundaries.\n */\nexport function runWithExperimentContext<T>(\n context: ExperimentContext,\n fn: () => T,\n): T {\n return experimentContextStorage.run(context, fn);\n}\n","/**\n * Batched asynchronous exposure logging.\n *\n * Collects exposure events in memory and flushes periodically\n * or when the batch size threshold is reached.\n */\n\nimport type { Exposure, ExposureLoggerConfig } from \"./types\";\n\nexport class ExposureLogger {\n private buffer: Exposure[] = [];\n private readonly batchSize: number;\n private readonly flushIntervalMs: number;\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private flushTimer: ReturnType<typeof setInterval> | null = null;\n private isFlushing = false;\n\n constructor(config: ExposureLoggerConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.batchSize = config.batchSize ?? 100;\n this.flushIntervalMs = config.flushIntervalMs ?? 5_000;\n\n this.flushTimer = setInterval(() => {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }, this.flushIntervalMs);\n\n if (this.flushTimer.unref) {\n this.flushTimer.unref();\n }\n }\n\n log(exposure: Exposure): void {\n this.buffer.push(exposure);\n if (this.buffer.length >= this.batchSize) {\n this.flush().catch((err) => {\n console.error(\"[gateway] Exposure flush error:\", err);\n });\n }\n }\n\n async flush(): Promise<void> {\n if (this.isFlushing || this.buffer.length === 0) {\n return;\n }\n\n this.isFlushing = true;\n const batch = this.buffer.splice(0, this.buffer.length);\n\n try {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(\n `${this.apiUrl}/api/public/experiments/exposures/batch`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n exposures: batch,\n }),\n },\n );\n if (!response.ok) {\n this.buffer.unshift(...batch);\n console.error(\n `[gateway] Failed to log exposures: ${response.status} ${response.statusText}`,\n );\n }\n } catch (error) {\n this.buffer.unshift(...batch);\n console.error(\"[gateway] Network error logging exposures:\", error);\n } finally {\n this.isFlushing = false;\n }\n }\n\n async shutdown(): Promise<void> {\n if (this.flushTimer) {\n clearInterval(this.flushTimer);\n this.flushTimer = null;\n }\n await this.flush();\n }\n}\n","/**\n * Main A/B experiment client for TypeScript.\n *\n * Mirrors the Python SDK's ExperimentClient in:\n * gatewaysdk/sdk/src/gatewaysdk/experiments/client.py\n */\n\nimport { assignVariant } from \"./assignment\";\nimport { runWithExperimentContext, setExperimentContext } from \"./context\";\nimport { ExposureLogger } from \"./exposure-logger\";\nimport type {\n ExperimentClientConfig,\n ExperimentConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nexport class ExperimentClient {\n private readonly apiUrl: string;\n private readonly apiKey: string;\n private readonly secretKey: string;\n private readonly projectId: string;\n private readonly configs = new Map<string, ExperimentConfig>();\n private readonly exposureLogger: ExposureLogger;\n\n constructor(config: ExperimentClientConfig) {\n this.apiUrl = config.apiUrl.replace(/\\/$/, \"\");\n this.apiKey = config.apiKey;\n this.secretKey = config.secretKey ?? \"\";\n this.projectId = config.projectId;\n this.exposureLogger = new ExposureLogger({\n apiUrl: this.apiUrl,\n apiKey: this.apiKey,\n secretKey: this.secretKey,\n batchSize: config.exposureLogger?.batchSize,\n flushIntervalMs: config.exposureLogger?.flushIntervalMs,\n });\n }\n\n async register(input: RegisterExperimentInput): Promise<void> {\n const config: ExperimentConfig = {\n key: input.key,\n trafficPercent: input.trafficPercent ?? 100,\n variants: input.variants.map((v) => ({\n key: v.key,\n weight: v.weight ?? 1,\n config: v.config ?? {},\n })),\n };\n\n this.configs.set(config.key, config);\n\n const syncToBackend = input.syncToBackend ?? true;\n if (syncToBackend) {\n this.syncToBackendAsync(config, input.evaluatorNames).catch((err) => {\n console.error(\n `[gateway] Failed to sync experiment ${config.key}:`,\n err,\n );\n });\n }\n }\n\n async fetch(experimentKeys?: string[]): Promise<void> {\n const url = new URL(`${this.apiUrl}/api/public/experiments`);\n if (experimentKeys && experimentKeys.length > 0) {\n url.searchParams.set(\"keys\", experimentKeys.join(\",\"));\n }\n\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(url.toString(), {\n method: \"GET\",\n headers: {\n Authorization: authHeader,\n },\n });\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch experiments: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = (await response.json()) as {\n experiments: ExperimentConfig[];\n };\n for (const config of data.experiments) {\n this.configs.set(config.key, config);\n }\n }\n\n async getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n ): Promise<GetVariantResult> {\n const fetchIfMissing = options?.fetchIfMissing ?? true;\n\n let config = this.configs.get(experimentKey);\n if (!config && fetchIfMissing) {\n try {\n await this.fetch([experimentKey]);\n config = this.configs.get(experimentKey);\n } catch (error) {\n console.error(\n `[gateway] Failed to fetch experiment ${experimentKey}:`,\n error,\n );\n }\n }\n\n if (!config) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n const variant = assignVariant(config, userId);\n if (!variant) {\n return {\n variant: null,\n inExperiment: false,\n experimentKey,\n run: (fn) => fn(),\n };\n }\n\n this.exposureLogger.log({\n userId,\n experimentId: experimentKey,\n variantKey: variant.key,\n timestamp: new Date().toISOString(),\n });\n\n const context = {\n experimentId: experimentKey,\n variantKey: variant.key,\n userId,\n };\n\n // Set context via enterWith() so spans created anywhere in this async chain are tagged.\n // Context is automatically isolated per request - no cross-request contamination.\n setExperimentContext(context);\n\n return {\n variant,\n inExperiment: true,\n experimentKey,\n run: (fn) => runWithExperimentContext(context, fn),\n };\n }\n\n getConfig(experimentKey: string): ExperimentConfig | undefined {\n return this.configs.get(experimentKey);\n }\n\n async shutdown(): Promise<void> {\n await this.exposureLogger.shutdown();\n }\n\n private async syncToBackendAsync(\n config: ExperimentConfig,\n evaluatorNames?: string[],\n ): Promise<void> {\n const authHeader = this.secretKey\n ? `Basic ${Buffer.from(`${this.apiKey}:${this.secretKey}`).toString(\"base64\")}`\n : `Bearer ${this.apiKey}`;\n\n const response = await fetch(`${this.apiUrl}/api/public/experiments`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: authHeader,\n },\n body: JSON.stringify({\n key: config.key,\n trafficPercent: config.trafficPercent,\n variants: config.variants,\n evaluatorNames: evaluatorNames ?? [],\n }),\n });\n\n if (!response.ok) {\n const text = await response.text();\n throw new Error(\n `Failed to sync experiment: ${response.status} ${response.statusText} - ${text}`,\n );\n }\n\n console.log(`[gateway] Synced experiment '${config.key}' to backend`);\n }\n}\n","/**\n * OpenTelemetry integration for A/B experiments.\n *\n * Provides a SpanProcessor that automatically injects experiment\n * context into spans. Mirrors the Python SDK's TracingContextSpanProcessor.\n */\n\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n SpanProcessor,\n Span,\n ReadableSpan,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { getExperimentContext } from \"./context\";\n\nexport const EXPERIMENT_ATTRIBUTES = {\n EXPERIMENT_ID: \"gateway.experiment.id\",\n VARIANT_KEY: \"gateway.variant.key\",\n USER_ID: \"gateway.experiment.user_id\",\n} as const;\n\nexport class ExperimentSpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const ctx = getExperimentContext();\n if (ctx) {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, ctx.experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, ctx.variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, ctx.userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nexport function addExperimentAttributes(\n span: Span,\n experimentId: string,\n variantKey: string,\n userId: string,\n): void {\n span.setAttribute(EXPERIMENT_ATTRIBUTES.EXPERIMENT_ID, experimentId);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.VARIANT_KEY, variantKey);\n span.setAttribute(EXPERIMENT_ATTRIBUTES.USER_ID, userId);\n}\n","/**\n * Singleton experiment client for simple usage.\n *\n * This mirrors the Python SDK's `gateway.experiments` singleton pattern.\n * For advanced use cases, instantiate ExperimentClient directly.\n */\n\nimport { ExperimentClient } from \"./client\";\nimport { clearExperimentContext as clearContext } from \"./context\";\nimport type {\n ExperimentClientConfig,\n GetVariantResult,\n RegisterExperimentInput,\n} from \"./types\";\n\nlet client: ExperimentClient | null = null;\n\nexport interface InitConfig {\n apiKey: string;\n secretKey?: string;\n baseUrl: string;\n projectId?: string;\n}\n\n/**\n * Initialize the experiments singleton.\n * Must be called before using other methods.\n */\nexport function init(config: InitConfig): void {\n client = new ExperimentClient({\n apiUrl: config.baseUrl,\n apiKey: config.apiKey,\n secretKey: config.secretKey,\n projectId: config.projectId ?? \"\",\n });\n}\n\n/**\n * Register an experiment configuration.\n */\nexport async function register(input: RegisterExperimentInput): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.register(input);\n}\n\n/**\n * Get variant for a user. Returns null if user is not in experiment.\n */\nexport async function getVariant(\n experimentKey: string,\n userId: string,\n options?: { fetchIfMissing?: boolean },\n): Promise<GetVariantResult> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.getVariant(experimentKey, userId, options);\n}\n\n/**\n * Fetch experiment configurations from the backend.\n */\nexport async function fetch(experimentKeys?: string[]): Promise<void> {\n if (!client) {\n throw new Error(\n \"Experiments not initialized. Call experiments.init() first.\",\n );\n }\n return client.fetch(experimentKeys);\n}\n\n/**\n * Flush pending exposures and shut down the client.\n */\nexport async function shutdown(): Promise<void> {\n if (client) {\n await client.shutdown();\n client = null;\n }\n // Also clear any lingering experiment context\n clearContext();\n}\n\n/**\n * Clear the current experiment context.\n *\n * Call this when you're done with an experiment session (e.g., after handling\n * a user request) to stop attributing new spans to the experiment.\n *\n * This mirrors Python's `gateway.experiments.clear_current_experiment()`.\n */\nexport function clearExperimentContext(): void {\n clearContext();\n}\n\n/**\n * Get the underlying ExperimentClient instance.\n * Returns null if not initialized.\n */\nexport function getClient(): ExperimentClient | null {\n return client;\n}\n","type ContextRepoKind = \"agent\" | \"prompt\" | \"skill\" | \"memory\";\ntype ContextWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype ContextFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype ContextRepo<TKind extends ContextRepoKind = ContextRepoKind> = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: TKind;\n description: string;\n readme: string;\n tags: string[];\n writePolicy: ContextWritePolicy;\n write_policy: ContextWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype ContextCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype ContextSnapshot<TKind extends ContextRepoKind = ContextRepoKind> = {\n repo: ContextRepo<TKind>;\n commit: ContextCommit;\n files: Record<string, ContextFileEntry>;\n};\n\ntype ContextListResponse<TKind extends ContextRepoKind = ContextRepoKind> = {\n repos: ContextRepo<TKind>[];\n limit: number;\n offset: number;\n total: number;\n};\n\ntype ContextPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype ContextFileInput =\n | {\n content: string;\n mimeType?: string;\n mime_type?: string;\n }\n | {\n repoHandle?: string;\n repo_handle?: string;\n kind?: \"agent\" | \"skill\";\n type?: \"agent\" | \"skill\";\n commitId?: string | null;\n commit_id?: string | null;\n }\n | null;\n\ntype ContextRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ContextPullOptions = {\n version?: string;\n};\n\ntype ContextListOptions = {\n query?: string;\n isPublic?: boolean;\n isArchived?: boolean;\n limit?: number;\n offset?: number;\n};\n\ntype ContextPushOptions = ContextRuntimeContext & {\n files: Record<string, ContextFileInput>;\n parentCommit?: string;\n description?: string;\n readme?: string;\n tags?: string[];\n isPublic?: boolean;\n writePolicy?: ContextWritePolicy;\n message?: string;\n};\n\ntype ContextRepoRef =\n | string\n | {\n identifier?: string;\n repoHandle?: string;\n repo_handle?: string;\n label?: string;\n version?: string;\n writable?: boolean;\n };\n\ntype ResolvedContextRef<TKind extends ContextRepoKind = ContextRepoKind> = {\n identifier: string;\n version?: string;\n writable?: boolean;\n snapshot: ContextSnapshot<TKind>;\n primaryPath: string | null;\n content: string;\n};\n\ntype ResolvedAgentContext = {\n agent: ContextSnapshot<\"agent\">;\n config: Record<string, unknown>;\n prompt: ResolvedContextRef<\"prompt\"> | null;\n prompts: ResolvedContextRef<\"prompt\">[];\n skills: ResolvedContextRef<\"skill\">[];\n memory: ResolvedContextRef<\"memory\">[];\n system: string;\n renderSystem: (options?: RenderSystemOptions) => string;\n provenance: ContextProvenance[];\n};\n\ntype ContextProvenance = {\n kind: ContextRepoKind;\n repoHandle: string;\n commitHash: string;\n label?: string;\n};\n\ntype RenderSystemOptions = {\n includeAgent?: boolean;\n includePrompts?: boolean;\n includeSkills?: boolean;\n includeMemory?: boolean;\n};\n\ntype GatewayContextConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayContextFromEnvConfig = Partial<GatewayContextConfig>;\n\nexport class GatewayContextError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayContextError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayContextConflictError extends GatewayContextError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayContextConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayContext {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayContextConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayContextFromEnvConfig = {}) {\n const host =\n config.host ?? process.env.GATEWAY_HOST ?? process.env.GATEWAY_HOST;\n const publicKey =\n config.publicKey ??\n process.env.GATEWAY_PUBLIC_KEY ??\n process.env.GATEWAY_PUBLIC_KEY;\n const secretKey =\n config.secretKey ??\n process.env.GATEWAY_SECRET_KEY ??\n process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewayContextError(\n `Missing Gateway context configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayContext({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n pullAgent(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"agent\", identifier, options);\n }\n\n pullPrompt(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"prompt\", identifier, options);\n }\n\n pullSkill(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"skill\", identifier, options);\n }\n\n pullMemory(identifier: string, options: ContextPullOptions = {}) {\n return this.pull(\"memory\", identifier, options);\n }\n\n pushAgent(identifier: string, options: ContextPushOptions) {\n return this.push(\"agent\", identifier, options);\n }\n\n pushPrompt(identifier: string, options: ContextPushOptions) {\n return this.push(\"prompt\", identifier, options);\n }\n\n pushSkill(identifier: string, options: ContextPushOptions) {\n return this.push(\"skill\", identifier, options);\n }\n\n pushMemory(identifier: string, options: ContextPushOptions) {\n return this.push(\"memory\", identifier, options);\n }\n\n listAgents(options: ContextListOptions = {}) {\n return this.list(\"agent\", options);\n }\n\n listPrompts(options: ContextListOptions = {}) {\n return this.list(\"prompt\", options);\n }\n\n listSkills(options: ContextListOptions = {}) {\n return this.list(\"skill\", options);\n }\n\n listMemory(options: ContextListOptions = {}) {\n return this.list(\"memory\", options);\n }\n\n agentExists(identifier: string) {\n return this.exists(\"agent\", identifier);\n }\n\n promptExists(identifier: string) {\n return this.exists(\"prompt\", identifier);\n }\n\n skillExists(identifier: string) {\n return this.exists(\"skill\", identifier);\n }\n\n memoryExists(identifier: string) {\n return this.exists(\"memory\", identifier);\n }\n\n deleteAgent(identifier: string) {\n return this.delete(\"agent\", identifier);\n }\n\n deletePrompt(identifier: string) {\n return this.delete(\"prompt\", identifier);\n }\n\n deleteSkill(identifier: string) {\n return this.delete(\"skill\", identifier);\n }\n\n deleteMemory(identifier: string) {\n return this.delete(\"memory\", identifier);\n }\n\n async resolveAgent(\n identifier: string,\n runtimeContext: ContextRuntimeContext = {},\n ): Promise<ResolvedAgentContext> {\n const agent = await this.pullAgent(identifier);\n const config = parseJsonFile(agent, \"config.json\");\n const prompts = await this.resolveRefs(\"prompt\", getPromptRefs(config));\n const skills = await this.resolveRefs(\"skill\", getRefList(config.skills));\n const memory = await this.resolveRefs(\"memory\", getRefList(config.memory));\n const bundleBase = {\n agent,\n config,\n prompt: prompts[0] ?? null,\n prompts,\n skills,\n memory,\n provenance: [\n provenanceFor(agent),\n ...prompts.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...skills.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ...memory.map(({ snapshot, version }) => provenanceFor(snapshot, version)),\n ],\n };\n\n const renderSystem = (options: RenderSystemOptions = {}) =>\n renderAgentSystem(bundleBase, options);\n\n if (Object.keys(runtimeContext).length > 0) {\n this.log(\"resolveAgent runtime context %o\", runtimeContext);\n }\n\n return {\n ...bundleBase,\n system: renderSystem(),\n renderSystem,\n };\n }\n\n async pull<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPullOptions = {},\n ): Promise<ContextSnapshot<TKind>> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextSnapshot<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}${suffix}`,\n );\n }\n\n async push<TKind extends ContextRepoKind>(\n kind: TKind,\n identifier: string,\n options: ContextPushOptions,\n ): Promise<ContextPushResponse> {\n return this.requestJson<ContextPushResponse>(\n \"POST\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}`,\n {\n files: options.files,\n ...(options.parentCommit ? { parentCommit: options.parentCommit } : {}),\n ...(options.description ? { description: options.description } : {}),\n ...(options.readme ? { readme: options.readme } : {}),\n ...(options.tags ? { tags: options.tags } : {}),\n ...(options.isPublic !== undefined ? { isPublic: options.isPublic } : {}),\n ...(options.writePolicy ? { writePolicy: options.writePolicy } : {}),\n ...(options.message ? { message: options.message } : {}),\n ...runtimeContextPayload(options),\n },\n );\n }\n\n async list<TKind extends ContextRepoKind>(\n kind: TKind,\n options: ContextListOptions = {},\n ): Promise<ContextListResponse<TKind>> {\n const query = new URLSearchParams();\n if (options.query) query.set(\"query\", options.query);\n if (options.isPublic !== undefined) query.set(\"isPublic\", String(options.isPublic));\n if (options.isArchived !== undefined)\n query.set(\"isArchived\", String(options.isArchived));\n if (options.limit !== undefined) query.set(\"limit\", String(options.limit));\n if (options.offset !== undefined) query.set(\"offset\", String(options.offset));\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<ContextListResponse<TKind>>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}${suffix}`,\n );\n }\n\n async exists(kind: ContextRepoKind, identifier: string): Promise<boolean> {\n const query = new URLSearchParams({ exists: \"true\" });\n const response = await this.requestJson<{ exists: boolean }>(\n \"GET\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(\n identifier,\n )}?${query.toString()}`,\n );\n return response.exists;\n }\n\n async delete(kind: ContextRepoKind, identifier: string) {\n return this.requestJson<{ deleted: boolean; repoHandle: string; repo_handle: string }>(\n \"DELETE\",\n `/api/public/context/${endpointForKind(kind)}/${encodeIdentifier(identifier)}`,\n );\n }\n\n private async resolveRefs<TKind extends ContextRepoKind>(\n kind: TKind,\n refs: ContextRepoRef[],\n ): Promise<ResolvedContextRef<TKind>[]> {\n const resolved: ResolvedContextRef<TKind>[] = [];\n for (const ref of refs) {\n const normalized = normalizeRef(ref);\n if (!normalized) continue;\n const snapshot = await this.pull(kind, normalized.identifier, {\n version: normalized.version,\n });\n const primaryPath = primaryPathForKind(kind, snapshot);\n const content = primaryPath ? readFile(snapshot, primaryPath) ?? \"\" : \"\";\n resolved.push({\n ...normalized,\n snapshot,\n primaryPath,\n content,\n });\n }\n return resolved;\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\" | \"DELETE\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayContextConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayContextError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.context] ${message}`, ...args);\n }\n }\n}\n\nfunction renderAgentSystem(\n bundle: Omit<ResolvedAgentContext, \"system\" | \"renderSystem\">,\n options: RenderSystemOptions = {},\n) {\n const includeAgent = options.includeAgent ?? true;\n const includePrompts = options.includePrompts ?? true;\n const includeSkills = options.includeSkills ?? true;\n const includeMemory = options.includeMemory ?? false;\n const sections: string[] = [];\n\n if (includeAgent) {\n const agentContent = readFile(bundle.agent, \"AGENTS.md\");\n if (agentContent) sections.push(formatSection(\"Agent\", bundle.agent, agentContent));\n }\n\n if (includePrompts) {\n for (const prompt of bundle.prompts) {\n if (prompt.content) {\n sections.push(formatSection(\"Prompt\", prompt.snapshot, prompt.content));\n }\n }\n }\n\n if (includeSkills) {\n for (const skill of bundle.skills) {\n if (skill.content) {\n sections.push(formatSection(\"Skill\", skill.snapshot, skill.content));\n }\n }\n }\n\n if (includeMemory) {\n for (const memory of bundle.memory) {\n if (memory.content) {\n sections.push(formatSection(\"Memory\", memory.snapshot, memory.content));\n }\n }\n }\n\n return sections.join(\"\\n\\n---\\n\\n\");\n}\n\nfunction formatSection(\n title: string,\n snapshot: ContextSnapshot,\n content: string,\n) {\n return [\n `# ${title}: ${snapshot.repo.repoHandle}`,\n `<!-- commit: ${snapshot.commit.commitHash} -->`,\n \"\",\n content.trim(),\n ].join(\"\\n\");\n}\n\nfunction getPromptRefs(config: Record<string, unknown>): ContextRepoRef[] {\n const refs = [\n ...getRefList(config.prompt),\n ...getRefList(config.promptRef),\n ...getRefList(config.prompt_ref),\n ...getRefList(config.prompts),\n ];\n return dedupeRefs(refs);\n}\n\nfunction getRefList(value: unknown): ContextRepoRef[] {\n if (!value) return [];\n if (typeof value === \"string\") return [value];\n if (Array.isArray(value)) return value.filter(isContextRepoRef);\n if (isContextRepoRef(value)) return [value];\n return [];\n}\n\nfunction isContextRepoRef(value: unknown): value is ContextRepoRef {\n if (typeof value === \"string\") return true;\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n const record = value as Record<string, unknown>;\n return [\"identifier\", \"repoHandle\", \"repo_handle\"].some(\n (key) => typeof record[key] === \"string\",\n );\n}\n\nfunction dedupeRefs(refs: ContextRepoRef[]) {\n const seen = new Set<string>();\n return refs.filter((ref) => {\n const normalized = normalizeRef(ref);\n if (!normalized) return false;\n const key = `${normalized.identifier}:${normalized.version ?? \"\"}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n}\n\nfunction normalizeRef(ref: ContextRepoRef) {\n if (typeof ref === \"string\") {\n const identifier = ref.trim();\n return identifier ? { identifier } : null;\n }\n\n const identifier = (\n ref.identifier ??\n ref.repoHandle ??\n ref.repo_handle ??\n \"\"\n ).trim();\n if (!identifier) return null;\n\n return {\n identifier,\n version: ref.version ?? ref.label,\n writable: ref.writable,\n };\n}\n\nfunction primaryPathForKind(kind: ContextRepoKind, snapshot: ContextSnapshot) {\n const preferred =\n kind === \"agent\"\n ? \"AGENTS.md\"\n : kind === \"prompt\"\n ? \"PROMPT.md\"\n : kind === \"skill\"\n ? \"SKILL.md\"\n : \"MEMORY.md\";\n if (readFile(snapshot, preferred)) return preferred;\n return (\n Object.entries(snapshot.files).find(\n ([path, entry]) => entry.type === \"file\" && path.endsWith(\".md\"),\n )?.[0] ?? null\n );\n}\n\nfunction parseJsonFile(snapshot: ContextSnapshot, path: string) {\n const content = readFile(snapshot, path);\n if (!content) return {};\n try {\n const parsed = JSON.parse(content);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nfunction readFile(snapshot: ContextSnapshot, path: string) {\n const entry = snapshot.files[path];\n return entry?.type === \"file\" ? entry.content : null;\n}\n\nfunction provenanceFor(\n snapshot: ContextSnapshot,\n label?: string,\n): ContextProvenance {\n return {\n kind: snapshot.repo.kind,\n repoHandle: snapshot.repo.repoHandle,\n commitHash: snapshot.commit.commitHash,\n ...(label ? { label } : {}),\n };\n}\n\nfunction endpointForKind(kind: ContextRepoKind) {\n return kind === \"memory\" ? \"memory\" : `${kind}s`;\n}\n\nfunction runtimeContextPayload(options: ContextRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const context = {\n fromEnv: GatewayContext.fromEnv,\n};\n\nexport { renderAgentSystem };\n\nexport type {\n GatewayContextConfig,\n ContextCommit as GatewayContextCommit,\n ContextFileEntry as GatewayContextFileEntry,\n ContextFileInput as GatewayContextFileInput,\n ContextListOptions as GatewayContextListOptions,\n ContextListResponse as GatewayContextListResponse,\n ContextPullOptions as GatewayContextPullOptions,\n ContextPushOptions as GatewayContextPushOptions,\n ContextPushResponse as GatewayContextPushResponse,\n ContextRepo as GatewayContextRepo,\n ContextRepoKind as GatewayContextRepoKind,\n ContextRuntimeContext as GatewayContextRuntimeContext,\n ContextSnapshot as GatewayContextSnapshot,\n ContextWritePolicy as GatewayContextWritePolicy,\n RenderSystemOptions as GatewayRenderSystemOptions,\n ResolvedAgentContext as GatewayResolvedAgentContext,\n ResolvedContextRef as GatewayResolvedContextRef,\n};\n","type MemoryWritePolicy = \"read_only\" | \"propose\" | \"commit\";\n\ntype MemoryFileEntry =\n | {\n type: \"file\";\n content: string;\n mimeType: string;\n mime_type: string;\n }\n | {\n type: \"agent\" | \"skill\";\n repoHandle: string;\n repo_handle: string;\n commitId?: string | null;\n commit_id?: string | null;\n };\n\ntype MemoryRepo = {\n id: string;\n repoHandle: string;\n repo_handle: string;\n ownerHandle: string;\n owner_handle: string;\n kind: \"memory\";\n description: string;\n readme: string;\n tags: string[];\n writePolicy: MemoryWritePolicy;\n write_policy: MemoryWritePolicy;\n isPublic: boolean;\n is_public: boolean;\n isArchived: boolean;\n is_archived: boolean;\n url?: string;\n createdAt: string;\n created_at: string;\n updatedAt: string;\n updated_at: string;\n};\n\ntype MemoryCommit = {\n id: string;\n commitHash: string;\n commit_hash: string;\n parentCommitHash: string | null;\n parent_commit_hash: string | null;\n createdAt: string;\n created_at: string;\n};\n\ntype MemorySnapshot = {\n repo: MemoryRepo;\n commit: MemoryCommit;\n files: Record<string, MemoryFileEntry>;\n};\n\ntype MemoryPushResponse = {\n url: string;\n status: \"committed\" | \"proposed\";\n repoId: string;\n repo_id: string;\n commitId: string | null;\n commit_id: string | null;\n commitHash: string | null;\n commit_hash: string | null;\n proposalId?: string | null;\n proposal_id?: string | null;\n};\n\ntype MemoryRuntimeContext = {\n source?: \"sdk\" | \"agent\" | \"dream\" | \"api\" | \"platform\";\n actorType?: \"api_key\" | \"agent\" | \"process\" | \"user\";\n proposedBy?: string;\n agentId?: string;\n agentStableId?: string;\n processId?: string;\n traceId?: string;\n spanId?: string;\n sessionId?: string;\n userId?: string;\n teamId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype MemoryPullOptions = {\n version?: string;\n};\n\ntype MemoryWriteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n mimeType?: string;\n};\n\ntype MemoryDeleteOptions = MemoryRuntimeContext & {\n parentCommit?: string;\n message?: string;\n};\n\ntype GatewayMemoryConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n debug?: boolean;\n};\n\ntype GatewayMemoryFromEnvConfig = Partial<GatewayMemoryConfig>;\n\nexport class GatewayMemoryError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewayMemoryError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayMemoryConflictError extends GatewayMemoryError {\n readonly latestCommit: unknown;\n\n constructor(message: string, latestCommit: unknown) {\n super(message);\n this.name = \"GatewayMemoryConflictError\";\n this.latestCommit = latestCommit;\n }\n}\n\nexport class GatewayMemory {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly debug: boolean;\n\n constructor(config: GatewayMemoryConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.debug = config.debug ?? false;\n }\n\n static fromEnv(config: GatewayMemoryFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewayMemoryError(\n `Missing Gateway memory configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewayMemory({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async pull(\n identifier: string,\n options: MemoryPullOptions = {},\n ): Promise<MemorySnapshot> {\n const query = new URLSearchParams();\n if (options.version) query.set(\"version\", options.version);\n const suffix = query.toString() ? `?${query.toString()}` : \"\";\n return this.requestJson<MemorySnapshot>(\n \"GET\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}${suffix}`,\n );\n }\n\n async read(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryPullOptions = {},\n ): Promise<string | null> {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target, options) : target;\n const file = snapshot.files[path];\n return file?.type === \"file\" ? file.content : null;\n }\n\n async write(\n target: string | MemorySnapshot,\n path: string,\n content: string,\n options: MemoryWriteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: {\n [path]: {\n content,\n ...(options.mimeType ? { mimeType: options.mimeType } : {}),\n },\n },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n async delete(\n target: string | MemorySnapshot,\n path: string,\n options: MemoryDeleteOptions = {},\n ) {\n const snapshot =\n typeof target === \"string\" ? await this.pull(target) : target;\n return this.push(snapshot.repo.repoHandle, {\n files: { [path]: null },\n parentCommit: options.parentCommit ?? snapshot.commit.commitHash,\n message: options.message,\n ...runtimeContextPayload(options),\n });\n }\n\n private async push(\n identifier: string,\n payload: Record<string, unknown>,\n ): Promise<MemoryPushResponse> {\n return this.requestJson<MemoryPushResponse>(\n \"POST\",\n `/api/public/context/memory/${encodeIdentifier(identifier)}`,\n payload,\n );\n }\n\n private async requestJson<TResponse>(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n ...(payload ? { \"Content-Type\": \"application/json\" } : {}),\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n });\n\n const text = await response.text();\n const body = text ? safeJson(text) : {};\n if (!response.ok) {\n const message =\n typeof body.message === \"string\"\n ? body.message\n : `Gateway API ${response.status} on ${path}`;\n if (response.status === 409) {\n throw new GatewayMemoryConflictError(\n message,\n body.latestCommit ?? null,\n );\n }\n throw new GatewayMemoryError(message);\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return body as TResponse;\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.memory] ${message}`, ...args);\n }\n }\n}\n\nfunction runtimeContextPayload(options: MemoryRuntimeContext) {\n return {\n ...(options.source ? { source: options.source } : {}),\n ...(options.actorType ? { actorType: options.actorType } : {}),\n ...(options.proposedBy ? { proposedBy: options.proposedBy } : {}),\n ...(options.agentId ? { agentId: options.agentId } : {}),\n ...(options.agentStableId ? { agentStableId: options.agentStableId } : {}),\n ...(options.processId ? { processId: options.processId } : {}),\n ...(options.traceId ? { traceId: options.traceId } : {}),\n ...(options.spanId ? { spanId: options.spanId } : {}),\n ...(options.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options.userId ? { userId: options.userId } : {}),\n ...(options.teamId ? { teamId: options.teamId } : {}),\n ...(options.metadata ? { metadata: options.metadata } : {}),\n };\n}\n\nfunction encodeIdentifier(identifier: string) {\n return identifier\n .split(\"/\")\n .filter(Boolean)\n .map((part) => encodeURIComponent(part))\n .join(\"/\");\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const memory = {\n fromEnv: GatewayMemory.fromEnv,\n};\n\nexport type {\n GatewayMemoryConfig,\n MemoryCommit as GatewayMemoryCommit,\n MemoryDeleteOptions as GatewayMemoryDeleteOptions,\n MemoryFileEntry as GatewayMemoryFileEntry,\n MemoryPullOptions as GatewayMemoryPullOptions,\n MemoryPushResponse as GatewayMemoryPushResponse,\n MemoryRepo as GatewayMemoryRepo,\n MemoryRuntimeContext as GatewayMemoryRuntimeContext,\n MemorySnapshot as GatewayMemorySnapshot,\n MemoryWriteOptions as GatewayMemoryWriteOptions,\n MemoryWritePolicy as GatewayMemoryWritePolicy,\n};\n","/**\n * Personas — simulated users served by the Gateway platform.\n *\n * A persona is a crafted user profile (usually derived from real sessions on\n * the platform) that Gateway serves as an endpoint. Use it to drive your agent\n * in tests: the persona plays the user, your agent plays itself.\n *\n * Example:\n * ```ts\n * import { PersonasClient } from \"@withgateway/sdk/personas\";\n *\n * const personas = PersonasClient.fromEnv();\n * const persona = await personas.get(\"persona_id\");\n *\n * const messages: PersonaMessage[] = [];\n * let reply = await persona.respond(messages); // persona opens the conversation\n * while (!reply.done) {\n * messages.push({ role: \"user\", content: reply.content });\n * const agentAnswer = await myAgent(messages); // your agent under test\n * messages.push({ role: \"assistant\", content: agentAnswer });\n * reply = await persona.respond(messages);\n * }\n * ```\n *\n * Message roles are from YOUR agent's perspective: `user` = the simulated\n * user's turns, `assistant` = your agent's turns.\n */\n\ntype PersonaMessage = {\n role: \"user\" | \"assistant\";\n content: string;\n};\n\n/** One simulated-user turn. */\ntype PersonaReply = {\n content: string;\n done: boolean;\n};\n\ntype PersonasClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype PersonasClientFromEnvConfig = Partial<PersonasClientConfig>;\n\n/** Raised when the Gateway personas API cannot complete a request. */\nexport class PersonaError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"PersonaError\";\n this.cause = options?.cause;\n }\n}\n\n/** A persona definition plus a bound `respond` helper. */\nexport class Persona {\n readonly id: string;\n readonly name: string;\n readonly description: string | null;\n readonly version: number;\n readonly instructions: string;\n readonly examples: string[];\n private readonly client: PersonasClient | null;\n\n constructor(fields: {\n id: string;\n name: string;\n description: string | null;\n version: number;\n instructions: string;\n examples?: string[];\n client?: PersonasClient | null;\n }) {\n this.id = fields.id;\n this.name = fields.name;\n this.description = fields.description;\n this.version = fields.version;\n this.instructions = fields.instructions;\n this.examples = fields.examples ?? [];\n this.client = fields.client ?? null;\n }\n\n /**\n * Get the persona's next user message for a conversation.\n *\n * `messages` use your agent's perspective: role `user` for the simulated\n * user's prior turns, `assistant` for your agent's turns.\n * `done` is true when the persona considers its goal met.\n */\n respond(messages: PersonaMessage[]): Promise<PersonaReply> {\n if (this.client === null) {\n throw new PersonaError(\"Persona is not bound to a client.\");\n }\n return this.client.chat(this.id, messages);\n }\n}\n\n/** Client for Gateway's persona endpoints (HTTP Basic project keys). */\nexport class PersonasClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: PersonasClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 120;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: PersonasClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new PersonaError(\n `Missing Gateway persona configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new PersonasClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** List the project's personas (without full instructions). */\n async list(): Promise<Persona[]> {\n const payload = await this.requestJson(\"GET\", \"/api/public/personas\");\n const items = Array.isArray(payload.data) ? payload.data : [];\n return items\n .filter(isRecord)\n .map(\n (item) =>\n new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: \"\",\n client: this,\n }),\n );\n }\n\n /** Fetch a persona (full definition) bound to this client. */\n async get(personaId: string): Promise<Persona> {\n const item = await this.requestJson(\n \"GET\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n );\n return new Persona({\n id: String(item.id),\n name: String(item.name),\n description: (item.description as string | null | undefined) ?? null,\n version: typeof item.version === \"number\" ? item.version : 1,\n instructions: typeof item.instructions === \"string\" ? item.instructions : \"\",\n examples: Array.isArray(item.examples)\n ? item.examples.map((example) => String(example))\n : [],\n client: this,\n });\n }\n\n /** Play one persona turn. See {@link Persona.respond}. */\n async chat(\n personaId: string,\n messages: PersonaMessage[],\n ): Promise<PersonaReply> {\n const payload = await this.requestJson(\n \"POST\",\n `/api/public/personas/${encodeURIComponent(personaId)}/chat`,\n { messages },\n );\n return {\n content: typeof payload.content === \"string\" ? payload.content : \"\",\n done: Boolean(payload.done),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new PersonaError(`${method} ${path} failed: ${reason}`, {\n cause: error,\n });\n }\n\n const text = await response.text();\n if (!response.ok) {\n const detail = text.slice(0, 500);\n throw new PersonaError(\n `${method} ${path} failed (${response.status}): ${detail}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.personas] ${message}`, ...args);\n }\n }\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return Boolean(value) && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return isRecord(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nexport const personas = {\n fromEnv: PersonasClient.fromEnv,\n};\n\nexport type {\n PersonaMessage,\n PersonaReply,\n PersonasClientConfig,\n PersonasClientFromEnvConfig,\n};\n","/**\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","/**\n * Regression suites replayed from platform task sets.\n *\n * A TASK SET on the platform (filed by the dream agent or a human) is a\n * runnable regression suite: each task carries its prompt, expected behavior,\n * and provenance to the RECORDED SESSION that motivated it. This module turns\n * that into tests:\n *\n * ```typescript\n * import { suite } from \"@withgateway/sdk/replay\";\n *\n * const regressions = await suite(\"groceat-regressions\");\n * for (const testCase of regressions) {\n * const stubs = await testCase.stubs(); // the recorded world\n * const out = await myAgent(testCase.prompt, stubs.asRegistry());\n * const result = testCase.check(out, { calledTools: stubs.calledNames() });\n * assert.ok(result.passed, result.explain());\n * }\n * ```\n *\n * Three layers pin three different things:\n * - tool stubs pin THE WORLD (recorded tool outputs → deterministic replay)\n * - invariants pin THE CONTRACT (must/must-not tool calls)\n * - your own assertions / platform judges pin THE SEMANTICS\n *\n * Case triage is three-way: PASS, FAIL (real regression — the world simulated\n * fine and the contract broke), and DRIFT (the recorded world no longer\n * matches the system — stub misses, renamed tools; the TEST is stale, not the\n * agent).\n *\n * Mirrors the Python SDK's `gatewaysdk.replay` package.\n */\n\nimport {\n DEFAULT_TIMEOUT_SECONDS,\n ENV_GATEWAY_HOST,\n ENV_GATEWAY_PUBLIC_KEY,\n ENV_GATEWAY_SECRET_KEY,\n SessionLoadError,\n type SessionObservation,\n SessionRecording,\n basicAuthHeader,\n loadSession,\n} from \"../sessions/index\";\nimport { join } from \"node:path\";\n\n/** Base error for replay loading/config problems. */\nexport class ReplayError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"ReplayError\";\n this.cause = options?.cause;\n }\n}\n\n/** Strict-mode stub lookup failed — the recorded world has no answer. */\nexport class StubMissError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"StubMissError\";\n }\n}\n\n/** The recorded session no longer matches the system (re-baseline the case). */\nexport class DriftError extends ReplayError {\n constructor(message: string) {\n super(message);\n this.name = \"DriftError\";\n }\n}\n\n// ---------------------------------------------------------------------------\n// World simulation: recorded tool stubs\n// ---------------------------------------------------------------------------\n\n// Single-key envelopes that auto-instrumentors wrap tool inputs in (e.g. the\n// OpenInference openai-agents instrumentor records {\"args_json\": \"<json>\"},\n// agent-as-tool records {\"input\": \"...\"}). Recorded inputs must compare equal\n// to the args a live agent passes, so both sides are unwrapped before match.\nconst WRAPPER_KEYS = [\"args_json\", \"arguments\", \"kwargs\", \"args\", \"input\"];\n\nfunction canonicalize(value: unknown): unknown {\n if (typeof value === \"string\") {\n const stripped = value.trim();\n if (stripped.startsWith(\"{\") || stripped.startsWith(\"[\")) {\n try {\n return canonicalize(JSON.parse(stripped));\n } catch {\n return value;\n }\n }\n return value;\n }\n if (Array.isArray(value)) {\n return value.map(canonicalize);\n }\n if (isPlainObject(value)) {\n const entries = Object.entries(value);\n if (entries.length === 1 && WRAPPER_KEYS.includes(entries[0][0])) {\n return canonicalize(entries[0][1]);\n }\n return Object.fromEntries(\n entries.map(([key, inner]) => [key, canonicalize(inner)]),\n );\n }\n return value;\n}\n\nfunction sortKeysDeep(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(sortKeysDeep);\n }\n if (isPlainObject(value)) {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value).sort()) {\n sorted[key] = sortKeysDeep(value[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction normalizeInput(value: unknown): string {\n try {\n return (\n JSON.stringify(sortKeysDeep(canonicalize(value ?? null))) ?? \"null\"\n );\n } catch {\n return String(value);\n }\n}\n\nexport type RecordedToolCall = {\n name: string;\n input: unknown;\n output: unknown;\n observationId: string;\n};\n\nexport type MissPolicy = \"error\" | \"reuse\" | \"passthrough\";\nexport type StubMatch =\n | \"local\"\n | \"exact\"\n | \"exact-repeat\"\n | \"ordinal\"\n | \"reuse\"\n | \"miss\";\nexport type StubCallLogEntry = {\n tool: string;\n match: StubMatch;\n input: unknown;\n};\nexport type StubFallback = (toolName: string, toolInput: unknown) => unknown;\nexport type LocalTool = (toolInput: unknown) => unknown;\nexport type ToolStub = (toolInput?: unknown) => unknown;\n\n/**\n * Tool registry that synthesizes stubs for unknown names (see\n * `ToolStubRegistry.asRegistry`). Indexing an unknown name returns a callable\n * that routes through `lookup()`, so the call is LOGGED and follows the miss\n * policy instead of dying on an undefined-is-not-a-function error.\n */\nexport type StubRegistryMapping = Record<string, ToolStub>;\n\ntype StubRegistryOptions = {\n missPolicy?: MissPolicy;\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n};\n\n/**\n * Replays recorded tool outputs from a case's recorded session.\n *\n * Match strategies (tried in order):\n * local — the tool was declared `local`: run its live impl (new\n * or deterministic tools that never need recordings)\n * exact — normalized-JSON equality of the tool input\n * exact-repeat — same (name, input) already replayed: return that output\n * again (idempotent world reads never exhaust)\n * ordinal — nth un-consumed recording for that tool name (robust to\n * arg phrasing drift across models/prompts)\n *\n * Miss policy:\n * \"error\" — throw StubMissError (strict replay; recorded as drift).\n * NOTE: most agent frameworks catch tool errors and feed\n * them to the model as error output, so this does NOT\n * hard-stop such runs — the drift still lands in the\n * report either way.\n * \"reuse\" — exhausted a tool's recordings? replay the LAST recorded\n * output for that name again (drift recorded). Keeps\n * research-heavy agents running when they make more calls\n * than the recording holds. Never-recorded names still\n * throw (or hit `fallback` when provided).\n * \"passthrough\" — call the `fallback` callable (live tool) and record the\n * miss as drift for the report\n */\nexport class ToolStubRegistry {\n readonly callLog: StubCallLogEntry[] = [];\n readonly driftEvents: string[] = [];\n\n private readonly recorded: RecordedToolCall[];\n private readonly consumed = new Set<number>();\n private readonly consumptionOrder: number[] = [];\n private missPolicy: MissPolicy;\n private fallback: StubFallback | null;\n private readonly local: Record<string, LocalTool>;\n\n constructor(calls: RecordedToolCall[], options: StubRegistryOptions = {}) {\n const missPolicy = options.missPolicy ?? \"error\";\n if (![\"error\", \"reuse\", \"passthrough\"].includes(missPolicy)) {\n throw new ReplayError(`Unknown missPolicy: ${missPolicy}`);\n }\n this.recorded = calls;\n this.missPolicy = missPolicy;\n this.fallback = options.fallback ?? null;\n this.local = { ...(options.local ?? {}) };\n }\n\n static fromSession(\n session: SessionRecording,\n options: StubRegistryOptions = {},\n ): ToolStubRegistry {\n const calls = session.toolCalls().map(\n (observation: SessionObservation): RecordedToolCall => ({\n name: observation.name ?? \"\",\n input: observation.input,\n output: observation.output,\n observationId: observation.id,\n }),\n );\n return new ToolStubRegistry(calls, options);\n }\n\n /** Resolve a tool call against the recorded world. */\n lookup(toolName: string, toolInput: unknown = null): unknown {\n // declared-local tool: always run live, logged but never drift\n if (toolName in this.local) {\n this.callLog.push({ tool: toolName, match: \"local\", input: toolInput });\n return this.local[toolName](toolInput);\n }\n const normalized = normalizeInput(toolInput);\n // exact match first\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (\n !this.consumed.has(index) &&\n record.name === toolName &&\n normalizeInput(record.input) === normalized\n ) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({ tool: toolName, match: \"exact\", input: toolInput });\n return record.output;\n }\n }\n // exact-repeat: the same (name, input) was already replayed — treat the\n // recorded pair as a stable world fact and serve it again rather than\n // exhausting into ordinal/miss on idempotent re-reads\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName && normalizeInput(record.input) === normalized) {\n this.callLog.push({\n tool: toolName,\n match: \"exact-repeat\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // ordinal fallback: next un-consumed recording for this tool name\n for (let index = 0; index < this.recorded.length; index++) {\n const record = this.recorded[index];\n if (!this.consumed.has(index) && record.name === toolName) {\n this.consumed.add(index);\n this.consumptionOrder.push(index);\n this.callLog.push({\n tool: toolName,\n match: \"ordinal\",\n input: toolInput,\n });\n return record.output;\n }\n }\n // reuse: recordings for this name exist but are exhausted — replay the\n // last one again so over-calling agents (extra searches, retries) finish\n // the run; the drift below still tells the truth in triage\n if (this.missPolicy === \"reuse\") {\n for (let index = this.recorded.length - 1; index >= 0; index--) {\n const record = this.recorded[index];\n if (record.name === toolName) {\n this.driftEvents.push(\n `recordings for tool '${toolName}' exhausted — ` +\n \"replayed the last one again (reuse policy)\",\n );\n this.callLog.push({\n tool: toolName,\n match: \"reuse\",\n input: toolInput,\n });\n return record.output;\n }\n }\n }\n // miss\n const recordedNames = [...new Set(this.recorded.map((r) => r.name))].sort();\n const drift = `no recording for tool '${toolName}' (recorded tools: ${JSON.stringify(recordedNames)})`;\n this.driftEvents.push(drift);\n this.callLog.push({ tool: toolName, match: \"miss\", input: toolInput });\n if (\n this.fallback !== null &&\n (this.missPolicy === \"passthrough\" || this.missPolicy === \"reuse\")\n ) {\n return this.fallback(toolName, toolInput);\n }\n throw new StubMissError(drift);\n }\n\n /**\n * Mapping of toolName → callable, drop-in for most agent tool layers.\n *\n * `local` merges in tools that should ALWAYS run live (new tools the\n * recording predates, or deterministic/pure helpers) — they're logged for\n * the contract check but never count as drift.\n *\n * UNKNOWN tool names also resolve (to a stub that routes through\n * `lookup()`), so a call to an un-recorded tool is LOGGED and follows the\n * miss policy instead of dying on an undefined lookup — that log is what\n * lets `check()` classify a forbidden-but-unrecorded call as FAIL.\n */\n asRegistry(\n options: {\n fallback?: StubFallback;\n local?: Record<string, LocalTool>;\n } = {},\n ): StubRegistryMapping {\n if (options.fallback) {\n this.fallback = options.fallback;\n this.missPolicy = \"passthrough\";\n }\n if (options.local) {\n Object.assign(this.local, options.local);\n }\n\n const make =\n (name: string): ToolStub =>\n (toolInput?: unknown) =>\n this.lookup(name, toolInput === undefined ? {} : toolInput);\n\n const target: Record<string, ToolStub> = {};\n const names = new Set([\n ...this.recorded.map((record) => record.name),\n ...Object.keys(this.local),\n ]);\n for (const name of names) {\n if (name) {\n target[name] = make(name);\n }\n }\n return new Proxy(target, {\n get(current, prop, receiver) {\n if (typeof prop !== \"string\" || prop in current) {\n return Reflect.get(current, prop, receiver);\n }\n return make(prop);\n },\n });\n }\n\n calledNames(): string[] {\n return this.callLog.map((entry) => entry.tool);\n }\n\n /**\n * 1:1 comparison of this replay against the recorded trace.\n *\n * The recording is the expectation: every recorded tool call should be\n * replayed exactly once, in order, with nothing extra. Use for strict\n * did-it-do-everything-the-original-did checks (`mode: \"exact\"`).\n *\n * `includeLocal`: count local-tool calls as extras (default false — local\n * tools are declared live on purpose; their recorded calls are likewise\n * excluded from \"missing\", since local bypasses recordings).\n */\n compare(options: { includeLocal?: boolean } = {}): TraceDiff {\n const includeLocal = options.includeLocal ?? false;\n const missing = this.recorded\n .map((record, index) => ({ record, index }))\n .filter(\n ({ record, index }) =>\n !this.consumed.has(index) &&\n (includeLocal || !(record.name in this.local)),\n )\n .map(({ record }) => `${record.name}(${normalizeInput(record.input)})`);\n const extra: string[] = [];\n for (const entry of this.callLog) {\n if (\n [\"miss\", \"reuse\", \"exact-repeat\"].includes(entry.match) ||\n (includeLocal && entry.match === \"local\")\n ) {\n extra.push(\n `${entry.tool}(${normalizeInput(entry.input)}) [${entry.match}]`,\n );\n }\n }\n const outOfOrder: string[] = [];\n let last = -1;\n for (const index of this.consumptionOrder) {\n if (index < last) {\n const record = this.recorded[index];\n outOfOrder.push(`${record.name}(${normalizeInput(record.input)})`);\n } else {\n last = index;\n }\n }\n const matched = this.consumptionOrder.map(\n (index) => this.recorded[index].name,\n );\n return new TraceDiff({ matched, missing, extra, outOfOrder });\n }\n\n get drifted(): boolean {\n return this.driftEvents.length > 0;\n }\n}\n\n/** Replayed-vs-recorded trace comparison (see `ToolStubRegistry.compare`). */\nexport class TraceDiff {\n readonly matched: string[];\n readonly missing: string[];\n readonly extra: string[];\n readonly outOfOrder: string[];\n\n constructor(\n fields: {\n matched?: string[];\n missing?: string[];\n extra?: string[];\n outOfOrder?: string[];\n } = {},\n ) {\n this.matched = fields.matched ?? [];\n this.missing = fields.missing ?? [];\n this.extra = fields.extra ?? [];\n this.outOfOrder = fields.outOfOrder ?? [];\n }\n\n get identical(): boolean {\n return (\n this.missing.length === 0 &&\n this.extra.length === 0 &&\n this.outOfOrder.length === 0\n );\n }\n\n explain(): string {\n if (this.identical) {\n return `1:1 replay — all ${this.matched.length} recorded tool calls reproduced in order`;\n }\n const lines = [\n `trace diverges from recording (${this.matched.length} matched):`,\n ];\n lines.push(...this.missing.map((item) => ` not reproduced: ${item}`));\n lines.push(...this.extra.map((item) => ` extra call: ${item}`));\n lines.push(...this.outOfOrder.map((item) => ` out of order: ${item}`));\n return lines.join(\"\\n\");\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tasks, cases, checks\n// ---------------------------------------------------------------------------\n\ntype ReplayTaskFields = {\n id: string;\n name?: string | null;\n prompt?: unknown;\n expectedOutput?: unknown;\n metadata?: Record<string, unknown>;\n};\n\n/** One task-set item as served by GET /task-sets/{id}/tasks. */\nexport class ReplayTask {\n readonly id: string;\n readonly name: string | null;\n readonly prompt: unknown;\n readonly expectedOutput: unknown;\n readonly metadata: Record<string, unknown>;\n\n constructor(fields: ReplayTaskFields) {\n this.id = fields.id;\n this.name = fields.name ?? null;\n this.prompt = fields.prompt;\n this.expectedOutput = fields.expectedOutput;\n this.metadata = fields.metadata ?? {};\n }\n\n get sourceSessionId(): string | null {\n const value = this.metadata.sourceSessionId;\n return value ? String(value) : null;\n }\n\n get sourceTraceId(): string | null {\n const value = this.metadata.sourceTraceId;\n return value ? String(value) : null;\n }\n\n static fromApi(raw: Record<string, unknown>): ReplayTask {\n const metadata = raw.metadata;\n return new ReplayTask({\n id: String(raw.id ?? \"\"),\n name: typeof raw.name === \"string\" ? raw.name : null,\n prompt: raw.prompt,\n expectedOutput: raw.expectedOutput,\n metadata: isPlainObject(metadata) ? { ...metadata } : {},\n });\n }\n}\n\nexport type ReplayStatus = \"PASS\" | \"FAIL\" | \"DRIFT\";\n\n/** Triage result: PASS | FAIL | DRIFT (+ human-readable reasons). */\nexport class ReplayCheck {\n readonly status: ReplayStatus;\n readonly failures: string[];\n readonly drift: string[];\n readonly traceDiff: TraceDiff | null;\n\n constructor(\n status: ReplayStatus,\n fields: {\n failures?: string[];\n drift?: string[];\n traceDiff?: TraceDiff | null;\n } = {},\n ) {\n this.status = status;\n this.failures = fields.failures ?? [];\n this.drift = fields.drift ?? [];\n this.traceDiff = fields.traceDiff ?? null;\n }\n\n get passed(): boolean {\n return this.status === \"PASS\";\n }\n\n get drifted(): boolean {\n return this.status === \"DRIFT\";\n }\n\n explain(): string {\n if (this.status === \"PASS\") {\n return \"PASS\";\n }\n const lines: string[] = [this.status];\n lines.push(...this.failures.map((failure) => ` FAIL: ${failure}`));\n for (const event of this.drift) {\n if (event.includes(\"reuse policy\")) {\n // exhausted-then-reused recordings = the agent explored more than\n // the recording holds, not necessarily a stale test\n lines.push(\n ` DRIFT: ${event} — recording under-covers this run; ` +\n \"re-record for exact coverage or keep the reuse policy.\",\n );\n } else {\n lines.push(\n ` DRIFT: ${event} — the test is stale, not the agent; ` +\n \"re-record the session (or declare the tool local).\",\n );\n }\n }\n return lines.join(\"\\n\");\n }\n}\n\nexport type SessionLoader = (\n sessionId: string,\n) => SessionRecording | Promise<SessionRecording>;\n\nexport type ReplayMode = \"contract\" | \"exact\";\n\ntype CheckOptions = {\n calledTools?: string[];\n stubs?: ToolStubRegistry;\n mode?: ReplayMode;\n};\n\n/** One regression case: a task bound to the session it was filed from. */\nexport class ReplayCase {\n readonly task: ReplayTask;\n private readonly loader: SessionLoader;\n private _recording: SessionRecording | null = null;\n private _stubs: ToolStubRegistry | null = null;\n\n constructor(task: ReplayTask, options: { loader: SessionLoader }) {\n this.task = task;\n this.loader = options.loader;\n }\n\n // -- identity ------------------------------------------------------------\n get id(): string {\n return this.task.id;\n }\n\n get name(): string {\n return this.task.name ?? this.task.id;\n }\n\n get prompt(): unknown {\n return this.task.prompt;\n }\n\n get expected(): unknown {\n return this.task.expectedOutput;\n }\n\n // -- recorded source session ----------------------------------------------\n /** The full recorded session this case was filed from. */\n async recording(): Promise<SessionRecording> {\n if (this._recording === null) {\n const source = this.task.sourceSessionId;\n if (!source) {\n throw new DriftError(\n `Task ${this.name} has no sourceSessionId provenance — ` +\n \"file it from a session (add_session_to_task_set) or set \" +\n \"metadata.sourceSessionId.\",\n );\n }\n this._recording = await this.loader(source);\n }\n return this._recording;\n }\n\n async stubs(options: StubRegistryOptions = {}): Promise<ToolStubRegistry> {\n this._stubs = ToolStubRegistry.fromSession(await this.recording(), options);\n return this._stubs;\n }\n\n /**\n * The recorded conversation's user messages, one per turn — feed them to\n * your agent in order to re-drive the full session (each turn was one\n * trace in the recording).\n */\n async conversation(): Promise<string[]> {\n const messages = (await this.recording()).userMessages();\n const found = messages.filter(\n (message): message is string => Boolean(message),\n );\n return found.length > 0 ? found : [String(this.prompt)];\n }\n\n // -- grading ---------------------------------------------------------------\n /**\n * Contract invariants + drift triage.\n *\n * Invariants come from task metadata (the workbench-style contract):\n * metadata.expectTools — every listed tool MUST have been called\n * metadata.mustNotCall — none of these may have been called\n * Semantic grading stays with the caller (assert on `output` /\n * `case.expected`, or run a platform judge on the replay trace).\n *\n * `mode` (or task `metadata.replayMode`):\n * \"contract\" (default) — grade only the invariants above\n * \"exact\" — true 1:1 replay: the agent must reproduce EVERY\n * recorded tool call, in order, with nothing extra\n * (see TraceDiff); any divergence is a FAIL. The\n * full diff lands in the failure reasons and\n * `traceDiff`.\n */\n check(output: unknown = undefined, options: CheckOptions = {}): ReplayCheck {\n const registry = options.stubs ?? this._stubs;\n const drift = registry ? [...registry.driftEvents] : [];\n const called =\n options.calledTools ?? (registry ? registry.calledNames() : []);\n\n // VIOLATIONS are positive evidence the contract broke (a forbidden call\n // happened, produced output contradicts an exact expectation) — they\n // FAIL even on a drifted world. OMISSIONS (an expected tool never\n // called) only FAIL on a CLEAN world: when the run drifted (stub miss\n // aborted it, tools were renamed), the drift explains the omission and\n // the right verdict is DRIFT → re-record, not \"agent regressed\".\n const violations: string[] = [];\n const omissions: string[] = [];\n const expectTools = this.task.metadata.expectTools;\n if (Array.isArray(expectTools)) {\n for (const toolName of expectTools) {\n if (!called.includes(toolName)) {\n omissions.push(`expected tool not called: ${toolName}`);\n }\n }\n }\n const mustNot = this.task.metadata.mustNotCall;\n if (Array.isArray(mustNot)) {\n for (const toolName of mustNot) {\n if (called.includes(toolName)) {\n violations.push(`must_not_call violated: ${toolName}`);\n }\n }\n }\n if (\n typeof this.expected === \"string\" &&\n this.expected.trim() &&\n typeof output === \"string\" &&\n this.task.metadata.outputExact === true &&\n output.trim() !== this.expected.trim()\n ) {\n violations.push(\"output does not exactly match expectedOutput\");\n }\n\n const replayMode = (options.mode ??\n this.task.metadata.replayMode ??\n \"contract\") as ReplayMode;\n let traceDiff: TraceDiff | null = null;\n if (registry) {\n traceDiff = registry.compare();\n }\n if (replayMode === \"exact\" && traceDiff && !traceDiff.identical) {\n violations.push(\n ...[\n ...traceDiff.missing.map((item) => `not reproduced: ${item}`),\n ...traceDiff.extra.map((item) => `extra call: ${item}`),\n ...traceDiff.outOfOrder.map((item) => `out of order: ${item}`),\n ].map((line) => `1:1 replay diverged — ${line}`),\n );\n }\n\n if (violations.length > 0) {\n return new ReplayCheck(\"FAIL\", {\n failures: [...violations, ...(drift.length > 0 ? [] : omissions)],\n drift,\n traceDiff,\n });\n }\n if (drift.length > 0) {\n return new ReplayCheck(\"DRIFT\", { drift, traceDiff });\n }\n if (omissions.length > 0) {\n return new ReplayCheck(\"FAIL\", { failures: omissions, traceDiff });\n }\n return new ReplayCheck(\"PASS\", { traceDiff });\n }\n}\n\n// ---------------------------------------------------------------------------\n// Suite loading (platform task sets)\n// ---------------------------------------------------------------------------\n\nexport type ReplayCredentials = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n};\n\nexport type ReplaySuiteLoadOptions = {\n host?: string;\n publicKey?: string;\n secretKey?: string;\n timeoutSeconds?: number;\n};\n\ntype ReplaySuiteFields = {\n taskSetId: string;\n taskSetName: string;\n cases: ReplayCase[];\n /** Platform credentials for recording replay runs back to the task set. */\n credentials?: ReplayCredentials | null;\n};\n\n/** All cases of one task set, iterable and indexable by name or id. */\nexport class ReplaySuite implements Iterable<ReplayCase> {\n readonly taskSetId: string;\n readonly taskSetName: string;\n readonly cases: ReplayCase[];\n /** Credentials for recording replay runs back to the platform. */\n readonly credentials: ReplayCredentials | null;\n\n constructor(fields: ReplaySuiteFields) {\n this.taskSetId = fields.taskSetId;\n this.taskSetName = fields.taskSetName;\n this.cases = fields.cases;\n this.credentials = fields.credentials ?? null;\n }\n\n [Symbol.iterator](): Iterator<ReplayCase> {\n return this.cases[Symbol.iterator]();\n }\n\n get length(): number {\n return this.cases.length;\n }\n\n /** Look up a case by id or name (throws when absent). */\n get(key: string): ReplayCase {\n for (const testCase of this.cases) {\n if (testCase.id === key || testCase.name === key) {\n return testCase;\n }\n }\n throw new ReplayError(\n `No case '${key}' in task set ${this.taskSetName} ` +\n `(cases: ${JSON.stringify(this.cases.map((c) => c.name))})`,\n );\n }\n\n static async fromTaskSet(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n ): Promise<ReplaySuite> {\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, \" +\n \"GATEWAY_PUBLIC_KEY and GATEWAY_SECRET_KEY.\",\n );\n }\n const headers = { Authorization: basicAuthHeader(publicKey, secretKey) };\n\n const fetchTasks = async (\n datasetId: string,\n ): Promise<Array<Record<string, unknown>> | null> => {\n const tasks: Array<Record<string, unknown>> = [];\n let page = 0;\n for (;;) {\n const response = await fetch(\n `${host}/api/public/task-sets/${encodeURIComponent(datasetId)}/tasks?page=${page}&limit=200`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n if (response.status === 404) {\n return null;\n }\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to list tasks for ${datasetId}: ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const pageTasks = Array.isArray(payload.tasks) ? payload.tasks : [];\n tasks.push(...pageTasks.filter(isPlainObject));\n if (tasks.length >= Number(payload.totalTasks ?? 0)) {\n return tasks;\n }\n page += 1;\n }\n };\n\n // Try as an id first, then resolve as a name.\n let taskSetId = nameOrId;\n let taskSetName = nameOrId;\n let rawTasks = await fetchTasks(nameOrId);\n if (rawTasks === null) {\n const response = await fetch(\n `${host}/api/public/task-sets?name=${encodeURIComponent(nameOrId)}`,\n { headers, signal: AbortSignal.timeout(timeoutSeconds * 1000) },\n );\n const text = await response.text();\n if (!response.ok) {\n throw new ReplayError(\n `Failed to resolve task set '${nameOrId}': ` +\n `HTTP ${response.status} — ${text.slice(0, 300)}`,\n );\n }\n const payload = parseJsonObject(text);\n const matches = Array.isArray(payload.taskSets)\n ? payload.taskSets.filter(isPlainObject)\n : [];\n if (matches.length === 0) {\n throw new ReplayError(`Task set not found: ${nameOrId}`);\n }\n taskSetId = String(matches[0].datasetId);\n taskSetName = String(matches[0].name);\n rawTasks = (await fetchTasks(taskSetId)) ?? [];\n }\n\n const loader: SessionLoader = (sessionId) =>\n loadSession(sessionId, { host, publicKey, secretKey, timeoutSeconds });\n const cases = rawTasks.map(\n (raw) => new ReplayCase(ReplayTask.fromApi(raw), { loader }),\n );\n return new ReplaySuite({\n taskSetId,\n taskSetName,\n cases,\n credentials: { host, publicKey, secretKey, timeoutSeconds },\n });\n }\n\n /** Run the whole suite against `agent` — see `runSuite()`. */\n run(agent: ReplayAgent, options: RunSuiteOptions = {}): Promise<ReplayReport> {\n return runSuite(this, agent, options);\n }\n\n /** Pin every case's recorded session into the repo as JSON fixtures. */\n async snapshot(directory: string): Promise<string[]> {\n const written: string[] = [];\n for (const testCase of this.cases) {\n if (!testCase.task.sourceSessionId) {\n continue;\n }\n const recording = await testCase.recording();\n written.push(\n recording.toFixture(join(directory, `${testCase.name}.recording.json`)),\n );\n }\n return written;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Runner\n// ---------------------------------------------------------------------------\n\n/**\n * The agent under test. Always invoked as `agent(prompt, tools, replayCase)`\n * — declare only the parameters you need (this replaces the Python SDK's\n * signature sniffing with idiomatic JavaScript):\n *\n * `(prompt) => ...` — prompt-only agents\n * `(prompt, tools) => ...` — the common shape\n * `(prompt, tools, replayCase) => ...` — full case access\n * (rebuild stubs via `replayCase.stubs()`)\n */\nexport type ReplayAgent = (\n prompt: unknown,\n tools: StubRegistryMapping,\n replayCase: ReplayCase,\n) => unknown | Promise<unknown>;\n\nexport class ReplayReport {\n readonly results: Record<string, ReplayCheck>;\n readonly runName: string | null;\n readonly recordingErrors: string[];\n\n constructor(\n results: Record<string, ReplayCheck>,\n fields: { runName?: string | null; recordingErrors?: string[] } = {},\n ) {\n this.results = results;\n this.runName = fields.runName ?? null;\n this.recordingErrors = fields.recordingErrors ?? [];\n }\n\n get passed(): number {\n return this.count(\"PASS\");\n }\n\n get failed(): number {\n return this.count(\"FAIL\");\n }\n\n get drifted(): number {\n return this.count(\"DRIFT\");\n }\n\n /** True when nothing FAILED (drift is stale-test signal, not failure). */\n get ok(): boolean {\n return this.failed === 0;\n }\n\n explain(): string {\n const lines = [\n `${this.passed} PASS · ${this.failed} FAIL · ${this.drifted} DRIFT` +\n (this.runName ? ` · run '${this.runName}'` : \"\"),\n ];\n for (const [name, check] of Object.entries(this.results)) {\n if (check.status !== \"PASS\") {\n lines.push(`${name}: ${check.explain()}`);\n }\n }\n for (const error of this.recordingErrors) {\n lines.push(`recording: ${error}`);\n }\n return lines.join(\"\\n\");\n }\n\n private count(status: ReplayStatus): number {\n return Object.values(this.results).filter(\n (check) => check.status === status,\n ).length;\n }\n}\n\n/**\n * Replay traffic records under this environment — the platform hides it from\n * the sessions/traces tables by default (users opt back in via the\n * environment filter), so regression runs never pollute real usage views.\n */\nexport const REPLAY_ENVIRONMENT = \"gateway-replay\";\n\n/**\n * File one dataset-run item so the replay run shows on the task set.\n *\n * Retries on 404: a replay trace reaches ClickHouse asynchronously after\n * flush, and the endpoint rejects items whose trace does not exist yet.\n * Returns an error string on final failure (recording never throws).\n */\nasync function recordRunItem(\n suiteToRecord: ReplaySuite,\n testCase: ReplayCase,\n runName: string,\n traceId: string | null,\n triage: ReplayCheck,\n options: { retries?: number; retryDelaySeconds?: number } = {},\n): Promise<string | null> {\n const retries = options.retries ?? 10;\n const retryDelaySeconds = options.retryDelaySeconds ?? 3;\n const credentials = suiteToRecord.credentials;\n if (!credentials) {\n return \"suite has no platform credentials\";\n }\n const payload = {\n runName,\n runDescription: `gatewaysdk.replay run over '${suiteToRecord.taskSetName}'`,\n datasetItemId: testCase.id,\n traceId: traceId ?? randomHex(),\n metadata: {\n replay: true,\n status: triage.status,\n failures: triage.failures,\n drift: triage.drift,\n sourceSessionId: testCase.task.sourceSessionId,\n },\n };\n let lastError = \"unknown\";\n for (let attempt = 0; attempt < retries; attempt++) {\n try {\n const response = await fetch(\n `${credentials.host}/api/public/dataset-run-items`,\n {\n method: \"POST\",\n headers: {\n Authorization: basicAuthHeader(\n credentials.publicKey,\n credentials.secretKey,\n ),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(DEFAULT_TIMEOUT_SECONDS * 1000),\n },\n );\n if (response.status === 200) {\n return null;\n }\n const text = await response.text();\n lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;\n // 404 = trace not ingested yet — wait and retry; anything else is final.\n if (response.status !== 404) {\n return lastError;\n }\n } catch (error) {\n lastError = error instanceof Error ? error.message : String(error);\n }\n if (attempt < retries - 1) {\n await sleep(retryDelaySeconds * 1000);\n }\n }\n return lastError;\n}\n\nexport type RunSuiteOptions = {\n missPolicy?: MissPolicy;\n record?: boolean;\n runName?: string;\n};\n\n/**\n * Run every case and triage. The agent is invoked as\n * `agent(prompt, tools, replayCase)` — declare only what you need.\n *\n * Recording (`record` undefined → auto when the suite was loaded from the\n * platform): each case is filed as a dataset-run item on the task set, so\n * the replay run shows up in the task set's runs with per-case status.\n *\n * NOTE: unlike the Python SDK, cases are not auto-wrapped in a traced span —\n * the TypeScript tracing module has no per-trace context primitive yet. Run\n * items are filed with a synthetic trace id, exactly like a Python run\n * without tracing configured.\n */\nexport async function runSuite(\n suiteToRun: ReplaySuite,\n agent: ReplayAgent,\n options: RunSuiteOptions = {},\n): Promise<ReplayReport> {\n const missPolicy = options.missPolicy ?? \"error\";\n const record = options.record ?? Boolean(suiteToRun.credentials);\n const runName = options.runName ?? `replay-${randomHex().slice(0, 8)}`;\n\n const results: Record<string, ReplayCheck> = {};\n const pendingRecords: Array<[ReplayCase, string | null, ReplayCheck]> = [];\n for (const testCase of suiteToRun) {\n try {\n const stubs = await testCase.stubs({ missPolicy });\n const output = await agent(\n testCase.prompt,\n stubs.asRegistry(),\n testCase,\n );\n // Triage with the case's LATEST registry — a case-driven agent may\n // have rebuilt stubs via replayCase.stubs() inside its own body.\n results[testCase.name] = testCase.check(output);\n } catch (error) {\n if (error instanceof StubMissError) {\n // The world was missing an answer — but the CONTRACT may also have\n // been violated by that very call (e.g. a forbidden tool that was\n // never recorded because the original agent never called it). Run\n // the check: FAIL dominates drift.\n let triage = testCase.check();\n if (triage.status !== \"FAIL\") {\n triage = new ReplayCheck(\"DRIFT\", {\n drift: triage.drift.length > 0 ? triage.drift : [error.message],\n });\n }\n results[testCase.name] = triage;\n } else if (error instanceof DriftError) {\n results[testCase.name] = new ReplayCheck(\"DRIFT\", {\n drift: [error.message],\n });\n } else {\n throw error;\n }\n }\n\n if (record) {\n pendingRecords.push([testCase, null, results[testCase.name]]);\n }\n }\n\n const recordingErrors: string[] = [];\n for (const [testCase, traceId, triage] of pendingRecords) {\n const error = await recordRunItem(\n suiteToRun,\n testCase,\n runName,\n traceId,\n triage,\n );\n if (error) {\n recordingErrors.push(`${testCase.name}: ${error}`);\n }\n }\n\n return new ReplayReport(results, {\n runName: record ? runName : null,\n recordingErrors,\n });\n}\n\n/**\n * Shorthand for `ReplaySuite.fromTaskSet` — the intuitive entrypoint:\n *\n * ```typescript\n * import * as replay from \"@withgateway/sdk/replay\";\n * const report = await (await replay.suite(\"checkout-regressions\")).run(myAgent);\n * ```\n */\nexport function suite(\n nameOrId: string,\n options: ReplaySuiteLoadOptions = {},\n): Promise<ReplaySuite> {\n return ReplaySuite.fromTaskSet(nameOrId, options);\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction parseJsonObject(text: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(text);\n return isPlainObject(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\nfunction randomHex(): string {\n return crypto.randomUUID().replace(/-/g, \"\");\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nexport const replay = {\n suite,\n run: runSuite,\n};\n","type AgentDescriptor = {\n id?: string;\n name?: string;\n version?: string;\n};\n\ntype SecurityContext = {\n executionId?: string;\n userId?: string;\n teamId?: string;\n environment?: string;\n contextLabel?: string;\n contextBundleHash?: string;\n traceId?: string;\n sessionId?: string;\n spanId?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolDescriptor = {\n id: string;\n name?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n};\n\ntype ToolsetResolveResponse = {\n toolsetId: string;\n mode: \"observe\" | \"filter\" | \"enforce\";\n policyVersion: number;\n ttlSeconds: number;\n allowedToolIds: string[];\n blockedToolIds: string[];\n approvalToolIds: string[];\n secretBindings: Record<string, string[]>;\n failMode: \"open\" | \"closed\";\n};\n\ntype ToolCallAuthorizeResponse = {\n decisionId: string;\n outcome: \"allow\" | \"flag\" | \"block\" | \"approval_required\";\n reasonCode: string;\n message: string;\n policyVersion: number;\n};\n\ntype ToolObject = {\n description?: string;\n execute?: (...args: unknown[]) => unknown;\n [key: string]: unknown;\n};\n\ntype ToolCollection = Record<\n string,\n ToolObject | ((...args: unknown[]) => unknown)\n>;\n\ntype SecureToolsOptions<TTools extends ToolCollection> = {\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: TTools;\n context?: SecurityContext;\n toolIds?: Partial<Record<keyof TTools & string, string>>;\n toolMetadata?: Partial<\n Record<keyof TTools & string, Record<string, unknown>>\n >;\n};\n\ntype GatewaySecurityConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n agent?: AgentDescriptor;\n debug?: boolean;\n failOpen?: boolean;\n};\n\ntype GatewaySecurityFromEnvConfig = Partial<\n Pick<GatewaySecurityConfig, \"host\" | \"publicKey\" | \"secretKey\">\n> &\n Pick<GatewaySecurityConfig, \"agent\" | \"debug\" | \"failOpen\">;\n\nconst SECURITY_ATTRIBUTES = {\n AGENT_ID: \"gateway.agent.id\",\n AGENT_NAME: \"gateway.agent.name\",\n AGENT_VERSION: \"gateway.agent.version\",\n TOOLSET_ID: \"gateway.toolset.id\",\n TOOL_ID: \"gateway.tool.id\",\n SECURITY_MODE: \"gateway.security.mode\",\n POLICY_VERSION: \"gateway.security.policy_version\",\n DECISION_OUTCOME: \"gateway.decision.outcome\",\n DECISION_REASON_CODE: \"gateway.decision.reason_code\",\n} as const;\n\nexport class GatewaySecurityError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"GatewaySecurityError\";\n this.cause = options?.cause;\n }\n}\n\nexport class GatewayToolBlockedError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway blocked tool ${toolId}`);\n this.name = \"GatewayToolBlockedError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\n/**\n * Thrown when Gateway's policy returns `approval_required` for a tool call.\n * The SDK does NOT execute the tool — a human/system approval is needed first\n * (the server engine and the runtime MCP PEP both honor this; this closes the\n * SDK leg of the step-up gate so an approval decision can't be silently run).\n */\nexport class GatewayToolApprovalRequiredError extends GatewaySecurityError {\n readonly decision: ToolCallAuthorizeResponse;\n readonly toolId: string;\n\n constructor(toolId: string, decision: ToolCallAuthorizeResponse) {\n super(decision.message || `Gateway requires approval for tool ${toolId}`);\n this.name = \"GatewayToolApprovalRequiredError\";\n this.toolId = toolId;\n this.decision = decision;\n }\n}\n\nexport class GatewaySecurity {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly agent: AgentDescriptor;\n private readonly debug: boolean;\n private readonly failOpen: boolean;\n\n constructor(config: GatewaySecurityConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.agent = config.agent ?? {};\n this.debug = config.debug ?? false;\n this.failOpen = config.failOpen ?? false;\n }\n\n static fromEnv(config: GatewaySecurityFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new GatewaySecurityError(\n `Missing Gateway security configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new GatewaySecurity({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n async secureTools<TTools extends ToolCollection>(\n options: SecureToolsOptions<TTools>,\n ): Promise<TTools> {\n const entries = Object.entries(options.tools);\n const descriptors = entries.map(([key, tool]) =>\n this.describeTool(key, tool, options),\n );\n const resolve = await this.resolveToolset({\n agent: this.agent,\n toolsetId: options.toolsetId,\n toolsetName: options.toolsetName,\n provider: options.provider,\n tools: descriptors,\n context: this.normalizeContext(options.context),\n });\n\n const securedEntries = entries.flatMap(([key, tool]) => {\n const descriptor = descriptors.find((item) => item.name === key)!;\n if (!this.shouldExposeTool(resolve, descriptor.id)) {\n this.log(\"Hiding tool %s in %s mode\", descriptor.id, resolve.mode);\n return [];\n }\n\n return [\n [\n key,\n this.wrapTool(tool, {\n toolId: descriptor.id,\n toolsetId: options.toolsetId,\n context: this.normalizeContext(options.context),\n resolve,\n }),\n ],\n ];\n });\n\n return Object.fromEntries(securedEntries) as TTools;\n }\n\n private async resolveToolset(input: {\n agent: AgentDescriptor;\n toolsetId: string;\n toolsetName?: string;\n provider?: string;\n tools: ToolDescriptor[];\n context: SecurityContext;\n }) {\n return this.postJson<ToolsetResolveResponse>(\n \"/api/public/security/toolsets/resolve\",\n input,\n );\n }\n\n private async authorizeToolCall(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n return this.postJson<ToolCallAuthorizeResponse>(\n \"/api/public/security/tool-calls/authorize\",\n {\n agent: this.agent,\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: input.inputMetadata,\n },\n );\n }\n\n private wrapTool(\n tool: ToolObject | ((...args: unknown[]) => unknown),\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n if (typeof tool === \"function\") {\n return this.wrapExecute(tool, input);\n }\n\n if (typeof tool.execute !== \"function\") {\n return tool;\n }\n\n return {\n ...tool,\n execute: this.wrapExecute(tool.execute.bind(tool), input),\n };\n }\n\n private wrapExecute(\n execute: (...args: unknown[]) => unknown,\n input: {\n toolId: string;\n toolsetId: string;\n context: SecurityContext;\n resolve: ToolsetResolveResponse;\n },\n ) {\n return async (...args: unknown[]) => {\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.AGENT_ID]: this.agent.id,\n [SECURITY_ATTRIBUTES.AGENT_NAME]: this.agent.name,\n [SECURITY_ATTRIBUTES.AGENT_VERSION]: this.agent.version,\n [SECURITY_ATTRIBUTES.TOOLSET_ID]: input.toolsetId,\n [SECURITY_ATTRIBUTES.TOOL_ID]: input.toolId,\n [SECURITY_ATTRIBUTES.SECURITY_MODE]: input.resolve.mode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: input.resolve.policyVersion,\n });\n\n const decision = await this.authorizeOrFallback({\n toolsetId: input.toolsetId,\n toolId: input.toolId,\n context: input.context,\n inputMetadata: { args },\n });\n\n this.setSpanAttributes({\n [SECURITY_ATTRIBUTES.DECISION_OUTCOME]: decision.outcome,\n [SECURITY_ATTRIBUTES.DECISION_REASON_CODE]: decision.reasonCode,\n [SECURITY_ATTRIBUTES.POLICY_VERSION]: decision.policyVersion,\n });\n\n if (decision.outcome === \"block\") {\n throw new GatewayToolBlockedError(input.toolId, decision);\n }\n if (decision.outcome === \"approval_required\") {\n // Enforce the step-up gate: do NOT execute until approved. The tool\n // stays callable (so the approval flow can be triggered), but a call\n // is refused with a typed error rather than running unapproved.\n throw new GatewayToolApprovalRequiredError(input.toolId, decision);\n }\n\n return execute(...args);\n };\n }\n\n private async authorizeOrFallback(input: {\n toolsetId: string;\n toolId: string;\n context: SecurityContext;\n inputMetadata: Record<string, unknown>;\n }) {\n try {\n return await this.authorizeToolCall(input);\n } catch (error) {\n if (this.failOpen) {\n this.log(\"Authorization failed open for tool %s\", input.toolId, error);\n return {\n decisionId: \"local-fail-open\",\n outcome: \"flag\" as const,\n reasonCode: \"authorization_unavailable_fail_open\",\n message:\n \"Gateway authorization was unavailable; failOpen allowed execution.\",\n policyVersion: 0,\n };\n }\n throw new GatewaySecurityError(\n `Gateway authorization failed for tool ${input.toolId}`,\n { cause: error },\n );\n }\n }\n\n private async postJson<TResponse>(\n path: string,\n payload: Record<string, unknown>,\n ): Promise<TResponse> {\n const response = await fetch(`${this.host}${path}`, {\n method: \"POST\",\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(payload),\n });\n\n if (!response.ok) {\n const body = await response.text();\n throw new GatewaySecurityError(\n `Gateway API ${response.status} on ${path}: ${body || response.statusText}`,\n );\n }\n\n return (await response.json()) as TResponse;\n }\n\n private describeTool<TTools extends ToolCollection>(\n key: string,\n tool: ToolObject | ((...args: unknown[]) => unknown),\n options: SecureToolsOptions<TTools>,\n ): ToolDescriptor & { name: string } {\n const toolObject = typeof tool === \"function\" ? undefined : tool;\n const id =\n options.toolIds?.[key] ?? `${options.toolsetId}.${toSnakeCase(key)}`;\n return {\n id,\n name: key,\n description:\n typeof toolObject?.description === \"string\"\n ? toolObject.description\n : undefined,\n metadata: options.toolMetadata?.[key] ?? {},\n };\n }\n\n private shouldExposeTool(resolve: ToolsetResolveResponse, toolId: string) {\n if (resolve.mode === \"observe\") return true;\n if (resolve.blockedToolIds.includes(toolId)) return false;\n return true;\n }\n\n private normalizeContext(context?: SecurityContext): SecurityContext {\n return {\n ...(context ?? {}),\n metadata: context?.metadata ?? {},\n };\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private setSpanAttributes(attributes: Record<string, unknown>) {\n const span = getActiveSpan();\n if (!span) return;\n\n for (const [key, value] of Object.entries(attributes)) {\n if (value === undefined || value === null) continue;\n span.setAttribute(key, value);\n }\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.security] ${message}`, ...args);\n }\n }\n}\n\nfunction getActiveSpan(): {\n setAttribute: (key: string, value: unknown) => void;\n} | null {\n try {\n // Optional peer dependency. Avoid making security unusable without tracing.\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const otel = require(\"@opentelemetry/api\") as {\n trace?: {\n getActiveSpan?: () =>\n | { setAttribute: (key: string, value: unknown) => void }\n | undefined;\n };\n };\n return otel.trace?.getActiveSpan?.() ?? null;\n } catch {\n return null;\n }\n}\n\nfunction toSnakeCase(value: string) {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[\\s-]+/g, \"_\")\n .toLowerCase();\n}\n\nexport const gateway = {\n fromEnv: GatewaySecurity.fromEnv,\n};\n\nexport type {\n AgentDescriptor as GatewayAgentDescriptor,\n GatewaySecurityConfig,\n SecurityContext as GatewaySecurityContext,\n SecureToolsOptions,\n ToolCallAuthorizeResponse as GatewayToolCallAuthorizeResponse,\n ToolDescriptor as GatewayToolDescriptor,\n ToolsetResolveResponse as GatewayToolsetResolveResponse,\n};\n","/**\n * End-user profiles — attribute usage and ROI to the real people behind\n * your agent's traffic.\n *\n * Profiles pair with the platform's per-user usage metrics (traces, tokens,\n * lifetime cost) on the Users page. Attributes merge by default, so pushing\n * an incremental ROI fact is one call:\n *\n * ```typescript\n * import { UsersClient } from \"@withgateway/sdk/users\";\n *\n * const users = UsersClient.fromEnv();\n * await users.update(\"user-123\", {\n * displayName: \"Acme Corp — Jane D.\",\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n *\n * Tip: `identify(\"user-123\", { attributes: {...} })` does this in the\n * background AND attributes the current trace/session to the user.\n *\n * Mirrors the Python SDK's `gatewaysdk.users` module.\n */\n\ntype UserProfile = {\n userId: string;\n displayName: string | null;\n email: string | null;\n attributes: Record<string, string>;\n notes: string | null;\n};\n\ntype UserProfileUpdate = {\n displayName?: string;\n email?: string;\n attributes?: Record<string, string>;\n notes?: string;\n /**\n * Attributes merge with the stored set by default. Set `merge: false`\n * to replace the stored attributes wholesale.\n */\n merge?: boolean;\n};\n\ntype UserEvent = {\n id: string;\n userId: string;\n event: string;\n /** Emitter-defined value (e.g. minutes saved, revenue). Summed at rollup. */\n value: number | null;\n metadata: Record<string, unknown>;\n traceId: string | null;\n sessionId: string | null;\n createdAt: Date;\n};\n\ntype UserEventOptions = {\n /** Worth of the event in your terms (minutes saved, revenue…). */\n value?: number;\n metadata?: Record<string, unknown>;\n /** Link to the trace that produced the event. */\n traceId?: string;\n /** Link to the session that produced the event. */\n sessionId?: string;\n};\n\ntype UsersClientConfig = {\n host: string;\n publicKey: string;\n secretKey: string;\n timeoutSeconds?: number;\n debug?: boolean;\n};\n\ntype UsersClientFromEnvConfig = Partial<UsersClientConfig>;\n\n/** Raised when the Gateway user-profiles API cannot complete a request. */\nexport class UserProfileError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message);\n this.name = \"UserProfileError\";\n this.cause = options?.cause;\n }\n}\n\n/** Client for Gateway's end-user profile endpoints (Basic project keys). */\nexport class UsersClient {\n private readonly host: string;\n private readonly publicKey: string;\n private readonly secretKey: string;\n private readonly timeoutSeconds: number;\n private readonly debug: boolean;\n\n constructor(config: UsersClientConfig) {\n this.host = config.host.replace(/\\/$/, \"\");\n this.publicKey = config.publicKey;\n this.secretKey = config.secretKey;\n this.timeoutSeconds = config.timeoutSeconds ?? 15;\n this.debug = config.debug ?? false;\n }\n\n /** Create a client from GATEWAY_HOST / GATEWAY_PUBLIC_KEY / GATEWAY_SECRET_KEY. */\n static fromEnv(config: UsersClientFromEnvConfig = {}) {\n const host = config.host ?? process.env.GATEWAY_HOST;\n const publicKey = config.publicKey ?? process.env.GATEWAY_PUBLIC_KEY;\n const secretKey = config.secretKey ?? process.env.GATEWAY_SECRET_KEY;\n\n const missing = [\n [\"host\", host],\n [\"publicKey\", publicKey],\n [\"secretKey\", secretKey],\n ]\n .filter(([, value]) => !value)\n .map(([name]) => name);\n\n if (missing.length > 0) {\n throw new UserProfileError(\n `Missing Gateway user-profile configuration: ${missing.join(\", \")}`,\n );\n }\n\n return new UsersClient({\n ...config,\n host: host!,\n publicKey: publicKey!,\n secretKey: secretKey!,\n });\n }\n\n /** Fetch a user's stored profile. */\n async get(userId: string): Promise<UserProfile> {\n return parseProfile(\n await this.requestJson(\n \"GET\",\n `/api/public/user-profiles/${encodeURIComponent(userId)}`,\n ),\n );\n }\n\n /**\n * Upsert a user's profile. `attributes` merge with the stored set unless\n * `merge: false` (which replaces it).\n */\n async update(\n userId: string,\n update: UserProfileUpdate = {},\n ): Promise<UserProfile> {\n const body: Record<string, unknown> = {\n userId,\n attributes: update.attributes ?? {},\n mergeAttributes: update.merge ?? true,\n ...(update.displayName !== undefined\n ? { displayName: update.displayName }\n : {}),\n ...(update.email !== undefined ? { email: update.email } : {}),\n ...(update.notes !== undefined ? { notes: update.notes } : {}),\n };\n return parseProfile(\n await this.requestJson(\"POST\", \"/api/public/user-profiles\", body),\n );\n }\n\n /**\n * Record a VALUE EVENT for a user — the per-user ROI stream. `value` is\n * whatever the event is worth in your terms (minutes saved, revenue…);\n * Gateway sums it in the hours-saved/ROI rollups, and evals and task-set\n * replays can assert against the events. Link `traceId`/`sessionId` to tie\n * the event to the run that produced it.\n *\n * @example\n * ```ts\n * await client.trackEvent(\"user-123\", \"checkout_completed\", {\n * value: 25,\n * metadata: { cartSize: 3 },\n * sessionId,\n * });\n * ```\n */\n async trackEvent(\n userId: string,\n event: string,\n options: UserEventOptions = {},\n ): Promise<UserEvent> {\n const body: Record<string, unknown> = {\n userId,\n event,\n metadata: options.metadata ?? {},\n ...(options.value !== undefined ? { value: options.value } : {}),\n ...(options.traceId !== undefined ? { traceId: options.traceId } : {}),\n ...(options.sessionId !== undefined\n ? { sessionId: options.sessionId }\n : {}),\n };\n return parseEvent(\n await this.requestJson(\"POST\", \"/api/public/user-events\", body),\n );\n }\n\n /** List a project's user events, optionally filtered by user/event/time. */\n async listEvents(\n filter: {\n userId?: string;\n event?: string;\n fromTimestamp?: Date;\n toTimestamp?: Date;\n page?: number;\n limit?: number;\n } = {},\n ): Promise<{ data: UserEvent[]; totalItems: number }> {\n const params = new URLSearchParams();\n if (filter.userId) params.set(\"userId\", filter.userId);\n if (filter.event) params.set(\"event\", filter.event);\n if (filter.fromTimestamp)\n params.set(\"fromTimestamp\", filter.fromTimestamp.toISOString());\n if (filter.toTimestamp)\n params.set(\"toTimestamp\", filter.toTimestamp.toISOString());\n if (filter.page) params.set(\"page\", String(filter.page));\n if (filter.limit) params.set(\"limit\", String(filter.limit));\n const qs = params.toString();\n const payload = await this.requestJson(\n \"GET\",\n `/api/public/user-events${qs ? `?${qs}` : \"\"}`,\n );\n const rows = Array.isArray(payload.data) ? payload.data : [];\n const meta =\n payload.meta && typeof payload.meta === \"object\"\n ? (payload.meta as Record<string, unknown>)\n : {};\n return {\n data: rows.map((row) => parseEvent(row as Record<string, unknown>)),\n totalItems: Number(meta.totalItems ?? rows.length),\n };\n }\n\n private async requestJson(\n method: \"GET\" | \"POST\",\n path: string,\n payload?: Record<string, unknown>,\n ): Promise<Record<string, unknown>> {\n let response: Response;\n try {\n response = await fetch(`${this.host}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader(),\n \"Content-Type\": \"application/json\",\n },\n ...(payload ? { body: JSON.stringify(payload) } : {}),\n signal: AbortSignal.timeout(this.timeoutSeconds * 1000),\n });\n } catch (error) {\n throw new UserProfileError(\n `${method} ${path} failed: ${error instanceof Error ? error.message : String(error)}`,\n { cause: error },\n );\n }\n\n const text = await response.text();\n if (!response.ok) {\n throw new UserProfileError(\n `${method} ${path} failed (${response.status}): ${text.slice(0, 500)}`,\n );\n }\n\n this.log(\"%s %s -> %s\", method, path, response.status);\n return safeJson(text);\n }\n\n private authHeader() {\n return `Basic ${Buffer.from(`${this.publicKey}:${this.secretKey}`).toString(\n \"base64\",\n )}`;\n }\n\n private log(message: string, ...args: unknown[]) {\n if (this.debug) {\n console.log(`[gateway.users] ${message}`, ...args);\n }\n }\n}\n\nfunction parseEvent(payload: Record<string, unknown>): UserEvent {\n return {\n id: String(payload.id ?? \"\"),\n userId: String(payload.userId ?? \"\"),\n event: String(payload.event ?? \"\"),\n value: typeof payload.value === \"number\" ? payload.value : null,\n metadata:\n payload.metadata &&\n typeof payload.metadata === \"object\" &&\n !Array.isArray(payload.metadata)\n ? (payload.metadata as Record<string, unknown>)\n : {},\n traceId: typeof payload.traceId === \"string\" ? payload.traceId : null,\n sessionId:\n typeof payload.sessionId === \"string\" ? payload.sessionId : null,\n createdAt:\n typeof payload.createdAt === \"string\"\n ? new Date(payload.createdAt)\n : new Date(0),\n };\n}\n\nfunction parseProfile(payload: Record<string, unknown>): UserProfile {\n return {\n userId: String(payload.userId ?? \"\"),\n displayName:\n typeof payload.displayName === \"string\" ? payload.displayName : null,\n email: typeof payload.email === \"string\" ? payload.email : null,\n attributes: parseAttributes(payload.attributes),\n notes: typeof payload.notes === \"string\" ? payload.notes : null,\n };\n}\n\nfunction parseAttributes(value: unknown): Record<string, string> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n const attributes: Record<string, string> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n attributes[key] = String(entry);\n }\n return attributes;\n}\n\nfunction safeJson(value: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(value);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n return {};\n }\n}\n\nexport const users = {\n fromEnv: UsersClient.fromEnv,\n};\n\nexport type {\n UserProfile,\n UserProfileUpdate,\n UserEvent,\n UserEventOptions,\n UsersClientConfig,\n UsersClientFromEnvConfig,\n};\n","/**\n * End-user identity for GatewaySDK tracing.\n *\n * Mirrors the Python SDK's `gatewaysdk.tracing.identity` user half:\n *\n * - The ambient user is set via `identify()` and stored in an\n * AsyncLocalStorage (the TS analogue of Python's ContextVar), so\n * concurrent requests serving different users never bleed into each other.\n * - `IdentitySpanProcessor` (registered by `tracing.init()`) stamps the\n * ambient user on every span at start, so everything traced after\n * `identify()` is attributed automatically — the same seam as Python's\n * `TracingContextSpanProcessor` and this SDK's `ExperimentSpanProcessor`.\n * - `identify()` also stamps the currently open span directly, because\n * ingestion treats `gateway.user.id` on ANY span as a trace-level update —\n * the in-flight trace is attributed immediately.\n */\n\nimport { AsyncLocalStorage } from \"async_hooks\";\nimport { isSpanContextValid, trace } from \"@opentelemetry/api\";\nimport type { Context } from \"@opentelemetry/api\";\nimport type {\n ReadableSpan,\n Span,\n SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { UsersClient } from \"../users/index\";\n\nexport const USER_ID_ATTRIBUTE = \"gateway.user.id\";\n\n// Per-async-context user identity set via identify() — AsyncLocalStorage so\n// concurrent requests serving different users never bleed into each other.\nconst currentUserStorage = new AsyncLocalStorage<string>();\n\n/**\n * The active end-user id: identify() context > GATEWAY_USER_ID env.\n *\n * Per-request user attribution (e.g. from auth middleware) can also override\n * per span by setting the `gateway.user.id` attribute directly — explicit\n * set wins over the ambient default stamped at span start.\n */\nexport function resolveUserId(): string | undefined {\n const contextual = currentUserStorage.getStore();\n if (contextual) return contextual;\n const envUser = process.env.GATEWAY_USER_ID?.trim();\n return envUser ? envUser : undefined;\n}\n\nexport interface IdentifyOptions {\n /** Profile attributes to merge into the user's stored profile. */\n attributes?: Record<string, string | number | boolean>;\n displayName?: string;\n email?: string;\n}\n\n/**\n * Attribute everything that follows (and the current trace) to a user.\n *\n * - Sets the user for all spans started in this async context, and stamps\n * the currently open span so the in-flight trace is attributed immediately.\n * - When `attributes`/`displayName`/`email` are given, the user's platform\n * profile is updated in the background (attributes merge with what's\n * stored — ideal for incremental ROI facts like plan or account_value).\n * Requires GATEWAY_HOST/GATEWAY_PUBLIC_KEY/GATEWAY_SECRET_KEY for the\n * profile update; tracing attribution works without them. Failures are\n * swallowed (debug-logged) and never produce unhandled rejections.\n *\n * @example\n * ```typescript\n * import { identify } from \"@withgateway/sdk\";\n *\n * identify(\"user-123\", {\n * attributes: { plan: \"enterprise\", account_value: \"48000\" },\n * });\n * ```\n */\nexport function identify(userId: string, options: IdentifyOptions = {}): void {\n const cleaned = userId.trim();\n if (!cleaned) return;\n\n currentUserStorage.enterWith(cleaned);\n\n // Stamp the open span so the in-flight trace is upserted with the user —\n // ingestion treats user.id on ANY span as a trace-level update.\n try {\n const span = trace.getActiveSpan();\n if (span && isSpanContextValid(span.spanContext())) {\n span.setAttribute(USER_ID_ATTRIBUTE, cleaned);\n }\n } catch (error) {\n debugLog(\"identify(): no active span to stamp\", error);\n }\n\n if (options.attributes || options.displayName || options.email) {\n void pushProfile(cleaned, options);\n }\n}\n\nasync function pushProfile(\n userId: string,\n options: IdentifyOptions,\n): Promise<void> {\n try {\n const attributes: Record<string, string> = {};\n for (const [key, value] of Object.entries(options.attributes ?? {})) {\n attributes[key] = String(value);\n }\n await UsersClient.fromEnv().update(userId, {\n ...(options.displayName !== undefined\n ? { displayName: options.displayName }\n : {}),\n ...(options.email !== undefined ? { email: options.email } : {}),\n attributes,\n });\n } catch (error) {\n debugLog(\"identify(): profile update failed\", error);\n }\n}\n\n/** Testing hook: clear the ambient user for the current async context. */\nexport function resetAmbientUser(): void {\n currentUserStorage.enterWith(undefined as unknown as string);\n}\n\n/**\n * Stamps the ambient end-user identity (identify() context or\n * GATEWAY_USER_ID env) on every span at start. Registered automatically by\n * `tracing.init()`. Explicit `setAttribute` calls after span start win over\n * this ambient default.\n */\nexport class IdentitySpanProcessor implements SpanProcessor {\n onStart(span: Span, _parentContext: Context): void {\n const userId = resolveUserId();\n if (userId) {\n span.setAttribute(USER_ID_ATTRIBUTE, userId);\n }\n }\n\n onEnd(_span: ReadableSpan): void {}\n\n async shutdown(): Promise<void> {}\n\n async forceFlush(): Promise<void> {}\n}\n\nfunction debugLog(message: string, ...args: unknown[]): void {\n if (process.env.GATEWAY_DEBUG) {\n console.debug(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n","/**\n * Tracing module for GatewaySDK TypeScript SDK.\n *\n * Provides a simple init() function that configures OpenTelemetry with\n * Gateway, mirroring the Python SDK's tracing.init() experience.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Initialize with environment variables\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * });\n *\n * // Ensure cleanup on shutdown\n * process.on(\"SIGTERM\", () => tracing.shutdown());\n * ```\n */\n\nexport type { TracingConfig, TracingState } from \"./types\";\n\nexport {\n init,\n initIsolated,\n shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\nexport type { TracingHandle } from \"./init\";\n\nexport {\n identify,\n resolveUserId,\n resetAmbientUser,\n IdentitySpanProcessor,\n USER_ID_ATTRIBUTE,\n} from \"./identity\";\nexport type { IdentifyOptions } from \"./identity\";\n\nexport { observe } from \"./observe\";\nexport type { ObserveOptions, ObservationKind } from \"./observe\";\n\nexport { observeOpenAI, observeAnthropic } from \"./instrument\";\n\nexport { observeClaude } from \"./claude\";\nexport type { ObserveClaudeOptions } from \"./claude\";\n","/**\n * Initialization and lifecycle management for GatewaySDK tracing.\n *\n * This module provides the core init(), shutdown(), and flush() functions\n * for managing the OpenTelemetry TracerProvider lifecycle, plus\n * initIsolated() for creating additional self-contained providers (e.g. one\n * process exporting different agents to different Gateway projects).\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { Tracer } from \"@opentelemetry/api\";\nimport type { TracingConfig, TracingState } from \"./types\";\nimport { IdentitySpanProcessor } from \"./identity\";\n\n// Environment variable names. (A legacy BRIDGELAYER_* prefix predated the\n// rebrand but was never in any published release, so only GATEWAY_* exists.)\nconst ENV_VARS = {\n HOST: \"GATEWAY_HOST\",\n PUBLIC_KEY: \"GATEWAY_PUBLIC_KEY\",\n SECRET_KEY: \"GATEWAY_SECRET_KEY\",\n ENDPOINT: \"GATEWAY_OTLP_ENDPOINT\",\n} as const;\n\nconst DEFAULT_OTLP_PATH = \"/api/public/otel/v1/traces\";\n\n// Module-level state\nconst state: TracingState & { debug?: boolean } = {\n initialized: false,\n provider: null,\n};\n\nfunction getEnv(key: string): string | undefined {\n const value = process.env[key];\n return value ? value : undefined;\n}\n\nfunction log(message: string, ...args: unknown[]): void {\n if (state.debug) {\n console.log(`[gatewaysdk.tracing] ${message}`, ...args);\n }\n}\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\ntype LogFn = (message: string, ...args: unknown[]) => void;\n\n/**\n * Handle to an isolated tracing provider created by initIsolated().\n * Spans started from `tracer` export to that provider's Gateway project;\n * the global tracer (from init()) is untouched.\n */\nexport interface TracingHandle {\n tracer: Tracer;\n /** Force-flush pending spans for this provider only. */\n flush(): Promise<void>;\n /** Flush and shut down this provider only. */\n shutdown(): Promise<void>;\n}\n\n/**\n * Build a fully-configured NodeTracerProvider from config + env. Shared by\n * init() (which registers it globally) and initIsolated() (which does not).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\nfunction buildProvider(config: TracingConfig, logFn: LogFn): any {\n // Resolve configuration from params or environment\n const host = config.host ?? getEnv(ENV_VARS.HOST);\n const publicKey = config.publicKey ?? getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = config.secretKey ?? getEnv(ENV_VARS.SECRET_KEY);\n const endpoint =\n config.endpoint ??\n getEnv(ENV_VARS.ENDPOINT) ??\n (host ? `${host.replace(/\\/$/, \"\")}${DEFAULT_OTLP_PATH}` : undefined);\n\n // Validate required configuration\n const missing: string[] = [];\n if (!host) missing.push(\"host (or GATEWAY_HOST env var)\");\n if (!publicKey) missing.push(\"publicKey (or GATEWAY_PUBLIC_KEY env var)\");\n if (!secretKey) missing.push(\"secretKey (or GATEWAY_SECRET_KEY env var)\");\n\n if (missing.length > 0) {\n throw new Error(\n `Missing required Gateway configuration: ${missing.join(\", \")}. ` +\n \"Provide these values via init() parameters or environment variables.\",\n );\n }\n\n // Dynamically import OpenTelemetry modules (they're peer dependencies)\n // Using 'any' to avoid version conflicts between OTel packages\n let NodeTracerProvider: any;\n let BatchSpanProcessor: any;\n let OTLPTraceExporter: any;\n let createResource: (attrs: Record<string, string>) => any;\n let ATTR_SERVICE_NAME: string;\n\n try {\n const traceNode = require(\"@opentelemetry/sdk-trace-node\");\n const traceBase = require(\"@opentelemetry/sdk-trace-base\");\n const otlpHttp = require(\"@opentelemetry/exporter-trace-otlp-http\");\n const resources = require(\"@opentelemetry/resources\");\n\n NodeTracerProvider = traceNode.NodeTracerProvider;\n BatchSpanProcessor = traceBase.BatchSpanProcessor;\n OTLPTraceExporter = otlpHttp.OTLPTraceExporter;\n\n // Handle both old (Resource class) and new (resourceFromAttributes function) APIs\n if (resources.Resource) {\n createResource = (attrs) => new resources.Resource(attrs);\n } else if (resources.resourceFromAttributes) {\n createResource = resources.resourceFromAttributes;\n } else {\n createResource = () => resources.defaultResource();\n }\n\n // Try semantic conventions, fall back to string literal\n try {\n const semconv = require(\"@opentelemetry/semantic-conventions\");\n ATTR_SERVICE_NAME =\n semconv.ATTR_SERVICE_NAME ?? semconv.SEMRESATTRS_SERVICE_NAME ?? \"service.name\";\n } catch {\n ATTR_SERVICE_NAME = \"service.name\";\n }\n } catch {\n throw new Error(\n \"OpenTelemetry packages not found. Install them with:\\n\" +\n \"npm install @opentelemetry/sdk-trace-node @opentelemetry/sdk-trace-base \" +\n \"@opentelemetry/exporter-trace-otlp-http @opentelemetry/resources\",\n );\n }\n\n // Build resource attributes\n const resourceAttrs: Record<string, string> = {\n [ATTR_SERVICE_NAME]: config.serviceName ?? \"gatewaysdk-tracing\",\n };\n if (config.environment) {\n resourceAttrs[\"gateway.environment\"] = config.environment;\n }\n if (config.version) {\n resourceAttrs[\"gateway.version\"] = config.version;\n }\n\n // Security check: block insecure HTTP (except localhost/127.0.0.1)\n let isLocalhost = false;\n if (endpoint) {\n try {\n const parsed = new URL(endpoint);\n isLocalhost =\n parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n isLocalhost = false;\n }\n }\n if (endpoint && !endpoint.startsWith(\"https://\") && !isLocalhost) {\n throw new Error(\n `Refusing to send credentials over insecure HTTP to ${endpoint}. ` +\n \"Use HTTPS or localhost for development.\",\n );\n }\n\n // Construct Basic Auth header\n const credentials = `${publicKey}:${secretKey}`;\n const encoded = Buffer.from(credentials).toString(\"base64\");\n const authHeader = `Basic ${encoded}`;\n\n // Create OTLP exporter\n const exporter = new OTLPTraceExporter({\n url: endpoint,\n headers: {\n Authorization: authHeader,\n },\n });\n\n logFn(\"Configured Gateway exporter: endpoint=%s\", endpoint);\n\n // Build span processors — custom processors go first (before the BatchSpanProcessor)\n const spanProcessors: any[] = [];\n\n if (config.customSpanProcessors) {\n for (const sp of config.customSpanProcessors) {\n spanProcessors.push(sp);\n logFn(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\n\n // Stamp the ambient end-user identity (identify() / GATEWAY_USER_ID) on\n // every span at start — mirrors the Python SDK's TracingContextSpanProcessor.\n spanProcessors.push(new IdentitySpanProcessor());\n\n // Add BatchSpanProcessor with exporter\n const batchConfig: Record<string, number> = {};\n if (config.batch?.maxQueueSize) {\n batchConfig.maxQueueSize = config.batch.maxQueueSize;\n }\n if (config.batch?.scheduledDelayMillis) {\n batchConfig.scheduledDelayMillis = config.batch.scheduledDelayMillis;\n }\n if (config.batch?.maxExportBatchSize) {\n batchConfig.maxExportBatchSize = config.batch.maxExportBatchSize;\n }\n\n spanProcessors.push(new BatchSpanProcessor(exporter, batchConfig));\n\n // Create provider — detect v1 vs v2 API via runtime feature check.\n // v1 has addSpanProcessor(); v2 removed it and requires spanProcessors in constructor.\n let provider: any = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n });\n\n if (typeof provider.addSpanProcessor === \"function\") {\n // v1 API: register each processor individually\n for (const sp of spanProcessors) {\n provider.addSpanProcessor(sp);\n }\n } else {\n // v2 API: must pass spanProcessors in constructor — recreate\n provider = new NodeTracerProvider({\n resource: createResource(resourceAttrs),\n spanProcessors,\n });\n }\n\n return provider;\n}\n/* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n/**\n * Initialize GatewaySDK tracing with automatic OpenTelemetry configuration.\n *\n * This function configures OpenTelemetry with a connection to Gateway\n * and sets up the ExperimentSpanProcessor for automatic experiment tagging.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * // Using environment variables (GATEWAY_HOST, GATEWAY_PUBLIC_KEY, GATEWAY_SECRET_KEY)\n * tracing.init();\n *\n * // Or with explicit configuration\n * tracing.init({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-...\",\n * secretKey: \"sk-lf-...\",\n * serviceName: \"my-agent\",\n * environment: \"production\",\n * });\n * ```\n */\nexport function init(config: TracingConfig = {}): void {\n if (state.initialized) {\n log(\"Tracing already initialized. Call shutdown() first to reinitialize.\");\n return;\n }\n\n // Store debug flag in state for log() function\n state.debug = config.debug ?? false;\n\n const provider = buildProvider(config, log);\n provider.register();\n\n state.provider = provider;\n state.initialized = true;\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n}\n\n/**\n * Create an ISOLATED tracing provider that is NOT registered globally.\n *\n * Use this when one process must export different work to different Gateway\n * projects (e.g. a server hosting several agents, each with its own project\n * keys), or when the process already has its own global OpenTelemetry\n * provider that must not be replaced.\n *\n * Spans only reach the isolated provider when started from its `tracer` —\n * pass it explicitly to observe()/observeClaude() via their `tracer` option,\n * or to a framework's telemetry hook (e.g. the Vercel AI SDK's\n * `experimental_telemetry.tracer`). Context propagation still works across\n * providers, so nesting behaves exactly as with init().\n *\n * Can be called any number of times; each handle has its own exporter,\n * batch queue, and lifecycle.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * const support = tracing.initIsolated({\n * host: \"https://app.gateway.dev\",\n * publicKey: \"pk-lf-support...\",\n * secretKey: \"sk-lf-support...\",\n * serviceName: \"support-agent\",\n * });\n *\n * await tracing.observe(\"support.run\", run, { tracer: support.tracer });\n * await support.flush();\n * ```\n */\nexport function initIsolated(config: TracingConfig = {}): TracingHandle {\n const debugLog: LogFn = config.debug\n ? (message, ...args) =>\n console.log(`[gatewaysdk.tracing:isolated] ${message}`, ...args)\n : () => {};\n\n const provider = buildProvider(config, debugLog);\n const tracer = provider.getTracer(\"@withgateway/sdk\") as Tracer;\n\n debugLog(\n \"Isolated tracing provider created (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\n );\n\n return {\n tracer,\n async flush() {\n try {\n await (provider as { forceFlush: () => Promise<void> }).forceFlush();\n } catch (e) {\n warn(\"Error during isolated flush:\", e);\n }\n },\n async shutdown() {\n try {\n await (provider as { shutdown: () => Promise<void> }).shutdown();\n } catch (e) {\n warn(\"Error during isolated shutdown:\", e);\n }\n },\n };\n}\n\n/**\n * Force flush all pending spans without shutting down.\n *\n * Useful for ensuring spans are exported at specific points\n * (e.g., after completing a batch of work) without ending the tracing session.\n *\n * @returns Promise that resolves when flush completes\n */\nexport async function flush(): Promise<void> {\n if (!state.provider) {\n log(\"No provider to flush\");\n return;\n }\n\n try {\n await (state.provider as { forceFlush: () => Promise<void> }).forceFlush();\n log(\"Flush completed successfully\");\n } catch (e) {\n warn(\"Error during flush:\", e);\n }\n}\n\n/**\n * Force flush all pending spans and shutdown the tracer provider.\n *\n * This function should be called before process exit to ensure all spans\n * are exported. It is safe to call multiple times.\n *\n * @example\n * ```typescript\n * import { tracing } from \"@withgateway/sdk\";\n *\n * tracing.init();\n *\n * // On shutdown\n * process.on(\"SIGTERM\", async () => {\n * await tracing.shutdown();\n * process.exit(0);\n * });\n * ```\n */\nexport async function shutdown(): Promise<void> {\n if (!state.initialized || !state.provider) {\n log(\"Tracing not initialized, nothing to shutdown\");\n return;\n }\n\n try {\n await (state.provider as { shutdown: () => Promise<void> }).shutdown();\n log(\"Shutdown complete\");\n } catch (e) {\n warn(\"Error during shutdown:\", e);\n }\n\n state.provider = null;\n state.initialized = false;\n}\n\n/**\n * Check if tracing has been initialized.\n */\nexport function isInitialized(): boolean {\n return state.initialized;\n}\n\n/**\n * Check if Gateway is configured via environment variables.\n */\nexport function isGatewayConfigured(): boolean {\n const host = getEnv(ENV_VARS.HOST);\n const publicKey = getEnv(ENV_VARS.PUBLIC_KEY);\n const secretKey = getEnv(ENV_VARS.SECRET_KEY);\n return !!(host && publicKey && secretKey);\n}\n","/**\n * observe() — group a unit of work (an agent run, a tool call) into a single\n * span so nested LLM/tool spans attach to it and the whole thing is one trace.\n *\n * Mirrors Langfuse's `observe()` / `startActiveObservation()`. This is what an\n * app uses to define a trace boundary when it drives a raw client loop (which\n * has no framework root span of its own): the callback runs inside the span's\n * OpenTelemetry context, so any auto-instrumented calls (see observeOpenAI) and\n * any nested observe() calls become children of it.\n *\n * The span carries OpenInference attributes (openinference.span.kind, input.value,\n * output.value), and Gateway maps a root span's input.value/output.value to the\n * trace-level input/output — so the trace shows the user input and final output.\n */\nimport { trace, context, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Tracer } from \"@opentelemetry/api\";\n\nexport type ObservationKind = \"AGENT\" | \"CHAIN\" | \"TOOL\" | \"LLM\" | \"RETRIEVER\";\n\nexport interface ObserveOptions {\n /** Recorded as input.value on the span (JSON-stringified if not a string). */\n input?: unknown;\n /** OpenInference span kind. Defaults to \"AGENT\" for the outer run. */\n kind?: ObservationKind;\n /**\n * When true (default), the callback's return value is recorded as\n * output.value. Set false if the return value is large/uninteresting.\n */\n captureOutput?: boolean;\n /**\n * Tracer to start the span from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * observation to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the span — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n */\n attributes?: Record<string, string>;\n}\n\nfunction asAttr(value: unknown): string {\n return typeof value === \"string\" ? value : JSON.stringify(value);\n}\n\n/**\n * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented\n * client calls, nested observe() calls) nests under it, forming one trace.\n *\n * @example\n * ```ts\n * const result = await observe(\"my-agent.run\", async () => {\n * // client.chat.completions.create(...) here becomes a child GENERATION\n * return finalText;\n * }, { input: prompt });\n * ```\n */\nexport async function observe<T>(\n name: string,\n fn: () => Promise<T>,\n options: ObserveOptions = {},\n): Promise<T> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const span = tracer.startSpan(name, {\n attributes: {\n \"openinference.span.kind\": options.kind ?? \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": asAttr(options.input) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n\n try {\n const result = await context.with(\n trace.setSpan(context.active(), span),\n fn,\n );\n if (options.captureOutput !== false && result !== undefined) {\n span.setAttribute(\"output.value\", asAttr(result));\n }\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: error instanceof Error ? error.message : String(error),\n });\n throw error;\n } finally {\n span.end();\n }\n}\n","/**\n * Client wrappers that turn an SDK's calls into spans on the Gateway provider.\n *\n * Node ESM can't retroactively patch a module the app already imported, so — as\n * Langfuse does with `observeOpenAI` — the app hands us the client and we\n * instrument it explicitly. One SDK call, no OpenTelemetry in the app.\n *\n * The OpenInference instrumentations are bundled optional deps of this package;\n * we load them with require() (the ESM build injects a real createRequire).\n */\n/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\nfunction warn(message: string, ...args: unknown[]): void {\n console.warn(`[gatewaysdk.tracing] ${message}`, ...args);\n}\n\n/**\n * Instrument an OpenAI client so its requests become GENERATION spans on the\n * Gateway provider. Returns the same client (its class prototype is patched, so\n * this and every other instance of that client are traced).\n *\n * @example\n * ```ts\n * import OpenAI from \"openai\";\n * import { init, observeOpenAI } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeOpenAI(new OpenAI());\n * ```\n */\nexport function observeOpenAI<T extends object>(client: T): T {\n try {\n const {\n OpenAIInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-openai\");\n // OpenInference patches `module.OpenAI.Chat.Completions.prototype`, so it\n // needs an object shaped like the openai module. Reconstruct it from the\n // instance's class (client.constructor === the OpenAI class).\n const OpenAIClass = (client as { constructor: unknown }).constructor;\n new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });\n } catch (error) {\n warn(\n \"observeOpenAI: could not load @arizeai/openinference-instrumentation-openai — OpenAI calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n\n/**\n * Instrument an Anthropic client so its requests become GENERATION spans.\n *\n * @example\n * ```ts\n * import Anthropic from \"@anthropic-ai/sdk\";\n * import { init, observeAnthropic } from \"@withgateway/sdk/tracing\";\n * init();\n * const client = observeAnthropic(new Anthropic());\n * ```\n */\nexport function observeAnthropic<T extends object>(client: T): T {\n try {\n const {\n AnthropicInstrumentation,\n } = require(\"@arizeai/openinference-instrumentation-anthropic\");\n // The instrumentor patches `module.Messages.prototype.create`, so it wants\n // an object whose `Messages` is the Anthropic client's Messages class (a\n // static on the class). `client.messages` resolves `create` through that\n // prototype, so patching it traces this client and every other instance.\n const AnthropicClass = (client as { constructor: { Messages?: unknown } })\n .constructor;\n new AnthropicInstrumentation().manuallyInstrument({\n Messages: AnthropicClass.Messages,\n });\n } catch (error) {\n warn(\n \"observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic — Anthropic calls will not be traced.\",\n error,\n );\n }\n return client;\n}\n","/**\n * observeClaude() — trace a Claude Agent SDK run.\n *\n * The Claude Agent SDK runs the agent in a separate `claude` CLI subprocess, so\n * there's nothing in-process to patch. What the app has is the message stream it\n * iterates. Wrap that stream with observeClaude() and it yields the same\n * messages unchanged while emitting spans on the Gateway provider.\n *\n * Default (one trace per run):\n *\n * AGENT (root)\n * ├─ GENERATION per assistant turn (with per-turn token usage)\n * └─ TOOL per tool call (input from tool_use, output from the\n * matching tool_result, matched by id)\n *\n * With `perTurn: true` (one trace PER ASSISTANT TURN — long agent runs read as\n * a session of turn traces, the way a chat thread does):\n *\n * AGENT \"<name> · turn N\" (detached root; session/user attributes on every turn)\n * ├─ GENERATION (that turn's usage + text)\n * └─ TOOL per tool call in the turn\n *\n * The TS equivalent of the Python SDK's claude-agent-sdk instrumentor.\n *\n * @example\n * ```ts\n * const stream = query({ prompt, options });\n * for await (const message of observeClaude(stream, { name, input: prompt })) {\n * // ...consume messages as usual\n * }\n * ```\n */\nimport {\n trace,\n context,\n SpanStatusCode,\n type Span,\n type Context,\n type Tracer,\n} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name; per-turn mode appends `· turn N`). */\n name: string;\n /** Recorded as input.value on the root span → trace-level input. */\n input?: string;\n /** Model label for the generation spans. */\n model?: string;\n /**\n * Tracer to start spans from. Defaults to the GLOBAL tracer (set up by\n * tracing.init()). Pass an initIsolated() handle's tracer to route this\n * run to that handle's Gateway project instead.\n */\n tracer?: Tracer;\n /**\n * Extra attributes for the root span(s) — e.g. gateway.session.id /\n * gateway.user.id to group runs into a session and attribute them to a user.\n * In per-turn mode these ride EVERY turn root, so each turn trace maps to\n * the session.\n */\n attributes?: Record<string, string>;\n /**\n * Emit one TRACE PER ASSISTANT TURN instead of a single trace for the whole\n * run. Each turn's trace carries that turn's generation and tool calls; the\n * turn's input is the run input (turn 1) or the tool results that fed it\n * (later turns). Turn roots are detached (`root: true`), so they never nest\n * under ambient spans. Combine with `attributes.gateway.session.id` to read\n * a whole run as a session of turns.\n */\n perTurn?: boolean;\n}\n\n/** Strip the `mcp__<server>__` prefix so tool names read cleanly. */\nfunction cleanToolName(name: string): string {\n return name.replace(/^mcp__[^_]+__/, \"\");\n}\n\nfunction toolResultText(content: unknown): string {\n if (typeof content === \"string\") return content;\n if (Array.isArray(content))\n return content\n .map((b) =>\n b && typeof b === \"object\" && \"text\" in b\n ? String((b as { text: unknown }).text)\n : JSON.stringify(b),\n )\n .join(\"\");\n return JSON.stringify(content ?? \"\");\n}\n\nconst TURN_INPUT_MAX = 4000;\n\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = options.tracer ?? trace.getTracer(\"@withgateway/sdk\");\n const model = options.model ?? \"claude\";\n const openTools = new Map<string, Span>();\n\n // Single-trace mode: one root for the whole run.\n let root: Span | null = null;\n let rootCtx: Context | null = null;\n if (!options.perTurn) {\n root = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined\n ? { \"input.value\": options.input }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n rootCtx = trace.setSpan(context.active(), root);\n }\n\n // Per-turn mode: the current turn's root, rotated on each assistant message.\n let turnRoot: Span | null = null;\n let turnCtx: Context | null = null;\n let turnIndex = 0;\n let turnText = \"\";\n // What fed the CURRENT turn: the run input for turn 1, then the tool results\n // produced since the previous assistant message.\n let pendingTurnInput = options.input ?? \"\";\n\n let finalText = \"\";\n\n const endTurn = () => {\n if (!turnRoot) return;\n if (turnText) turnRoot.setAttribute(\"output.value\", turnText);\n turnRoot.setStatus({ code: SpanStatusCode.OK });\n turnRoot.end();\n turnRoot = null;\n turnCtx = null;\n };\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n if (options.perTurn) {\n // A new assistant message starts a new turn: any tools still open\n // belong to the previous turn — settle them, then rotate the root.\n for (const span of openTools.values()) span.end();\n openTools.clear();\n endTurn();\n turnIndex += 1;\n turnText = \"\";\n turnRoot = tracer.startSpan(`${options.name} · turn ${turnIndex}`, {\n root: true,\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(pendingTurnInput\n ? { \"input.value\": pendingTurnInput.slice(0, TURN_INPUT_MAX) }\n : {}),\n ...(options.attributes ?? {}),\n },\n });\n turnCtx = trace.setSpan(context.active(), turnRoot);\n pendingTurnInput = \"\";\n }\n const childCtx = (options.perTurn ? turnCtx : rootCtx)!;\n\n let text = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> =\n [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n text += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({\n id: block.id,\n name: block.name,\n input: block.input,\n });\n }\n }\n turnText += text;\n\n const gen = tracer.startSpan(\n \"assistant\",\n {\n attributes: {\n \"openinference.span.kind\": \"LLM\",\n \"llm.model_name\": model,\n \"llm.provider\": \"anthropic\",\n \"output.value\":\n text ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n childCtx,\n );\n const usage = message.message?.usage;\n if (usage?.input_tokens != null)\n gen.setAttribute(\"llm.token_count.prompt\", usage.input_tokens);\n if (usage?.output_tokens != null)\n gen.setAttribute(\"llm.token_count.completion\", usage.output_tokens);\n gen.end();\n\n for (const t of toolUses) {\n const span = tracer.startSpan(\n `tool.${cleanToolName(t.name)}`,\n {\n attributes: {\n \"openinference.span.kind\": \"TOOL\",\n \"tool.name\": cleanToolName(t.name),\n \"input.value\": JSON.stringify(t.input),\n },\n },\n childCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span, and in\n // per-turn mode also becomes part of the NEXT turn's input.\n if (message?.type === \"user\") {\n const content = message.message?.content;\n if (Array.isArray(content)) {\n for (const block of content) {\n if (block?.type === \"tool_result\") {\n const resultText = toolResultText(block.content);\n const span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", resultText);\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\n }\n if (\n options.perTurn &&\n pendingTurnInput.length < TURN_INPUT_MAX\n ) {\n pendingTurnInput +=\n (pendingTurnInput ? \"\\n\" : \"\") +\n resultText.slice(0, TURN_INPUT_MAX - pendingTurnInput.length);\n }\n }\n }\n }\n }\n\n yield message;\n }\n } finally {\n for (const span of openTools.values()) span.end();\n openTools.clear();\n if (options.perTurn) {\n endTurn();\n } else if (root) {\n root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSA,oBAA2B;AAGpB,SAAS,YAAY,eAAuB,QAAwB;AACzE,QAAM,UAAM,0BAAW,QAAQ,EAC5B,OAAO,GAAG,aAAa,IAAI,MAAM,EAAE,EACnC,OAAO,KAAK;AAEf,SAAO,SAAS,IAAI,MAAM,GAAG,CAAC,GAAG,EAAE,IAAI;AACzC;AAEO,SAAS,cACd,QACA,QACgB;AAChB,MAAI,CAAC,OAAO,YAAY,OAAO,SAAS,WAAW,GAAG;AACpD,WAAO;AAAA,EACT;AAEA,QAAM,SAAS,YAAY,OAAO,KAAK,MAAM;AAC7C,QAAM,mBAAmB,OAAO,iBAAiB;AAEjD,MAAI,UAAU,kBAAkB;AAC9B,WAAO;AAAA,EACT;AAEA,QAAM,mBAAmB,SAAS;AAClC,QAAM,cAAc,OAAO,SAAS,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AAExE,MAAI,eAAe,GAAG;AACpB,WAAO,OAAO,SAAS,CAAC,KAAK;AAAA,EAC/B;AAEA,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AAAA,EACF,UAAE;AACA,eAAW,QAAQ,UAAU,OAAO,EAAG,MAAK,IAAI;AAChD,cAAU,MAAM;AAChB,QAAI,QAAQ,SAAS;AACnB,cAAQ;AAAA,IACV,WAAW,MAAM;AACf,WAAK,aAAa,gBAAgB,SAAS;AAC3C,WAAK,UAAU,EAAE,MAAM,2BAAe,GAAG,CAAC;AAC1C,WAAK,IAAI;AAAA,IACX;AAAA,EACF;AACF;;;AnB3OO,IAAM,UAAiC;AAAA,EAC5C,GAAG;AAAA,EACH,KAAK,SAAwB,CAAC,GAAG;AAC/B,QAAI,OAAO,sBAAsB,OAAO;AACtC,YAAM,aAAa;AAAA,QACjB,IAAI,wBAAwB;AAAA,QAC5B,GAAI,OAAO,wBAAwB,CAAC;AAAA,MACtC;AACA,aAAsBC,MAAK;AAAA,QACzB,GAAG;AAAA,QACH,sBAAsB;AAAA,MACxB,CAAC;AAAA,IACH;AACA,WAAsBA,MAAK,MAAM;AAAA,EACnC;AACF;","names":["context","context","clearExperimentContext","fetch","fetch","clearExperimentContext","memory","identifier","encodeIdentifier","runtimeContextPayload","safeJson","safeJson","trace","import_node_path","isPlainObject","context","safeJson","import_async_hooks","init","shutdown","init","debugLog","shutdown","import_api","warn","client","import_api","init"]}
|