@withgateway/sdk 0.1.3 → 0.1.4

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["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"],"mappings":";AA4GO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAEO,IAAM,6BAAN,cAAyC,mBAAmB;AAAA,EACxD;AAAA,EAET,YAAY,SAAiB,cAAuB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,eAAe;AAAA,EACtB;AACF;AAEO,IAAM,gBAAN,MAAM,eAAc;AAAA,EACR;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA6B;AACvC,SAAK,OAAO,OAAO,KAAK,QAAQ,OAAO,EAAE;AACzC,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,OAAO;AACxB,SAAK,QAAQ,OAAO,SAAS;AAAA,EAC/B;AAAA,EAEA,OAAO,QAAQ,SAAqC,CAAC,GAAG;AACtD,UAAM,OAAO,OAAO,QAAQ,QAAQ,IAAI;AACxC,UAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAClD,UAAM,YAAY,OAAO,aAAa,QAAQ,IAAI;AAElD,UAAM,UAAU;AAAA,MACd,CAAC,QAAQ,IAAI;AAAA,MACb,CAAC,aAAa,SAAS;AAAA,MACvB,CAAC,aAAa,SAAS;AAAA,IACzB,EACG,OAAO,CAAC,CAAC,EAAE,KAAK,MAAM,CAAC,KAAK,EAC5B,IAAI,CAAC,CAAC,IAAI,MAAM,IAAI;AAEvB,QAAI,QAAQ,SAAS,GAAG;AACtB,YAAM,IAAI;AAAA,QACR,yCAAyC,QAAQ,KAAK,IAAI,CAAC;AAAA,MAC7D;AAAA,IACF;AAEA,WAAO,IAAI,eAAc;AAAA,MACvB,GAAG;AAAA,MACH;AAA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,SACD,CAAC;AAAA,EACP,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,IAAM,SAAS;AAAA,EACpB,SAAS,cAAc;AACzB;","names":[]}
1
+ {"version":3,"sources":["../../src/memory/index.ts"],"sourcesContent":["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 GatewayMemo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ACD,CAAC;AAAA,EACP,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,IAAM,SAAS;AAAA,EACpB,SAAS,cAAc;AACzB;","names":[]}
@@ -1,3 +1,5 @@
1
+ import { createRequire as __gatewayCreateRequire } from "module";
2
+ const require = __gatewayCreateRequire(import.meta.url);
1
3
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
4
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
5
  }) : x)(function(x) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/security/index.ts"],"sourcesContent":["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 ToolsetResolveRespon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B,MAAiB;AAC/C,QAAI,KAAK,OAAO;AACd,cAAQ,IAAI,sBAAsB,OAAO,IAAI,GAAG,IAAI;AAAA,IACtD;AAAA,EACF;AACF;AAEA,SAAS,gBAEA;AACP,MAAI;AAGF,UAAM,OAAO,UAAQ,oBAAoB;AAOzC,WAAO,KAAK,OAAO,gBAAgB,KAAK;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,YAAY,OAAe;AAClC,SAAO,MACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,WAAW,GAAG,EACtB,YAAY;AACjB;AAEO,IAAM,UAAU;AAAA,EACrB,SAAS,gBAAgB;AAC3B;","names":[]}
1
+ {"version":3,"sources":["../../src/security/index.ts"],"sourcesContent":["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"],"mappings":";;;;;;;;;;AAmFA,IAAM,sBAAsB;AAAA,EAC1B,UAAU;AAAA,EACV,YAAY;AAAA,EACZ,eAAe;AAAA,EACf,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,eAAe;AAAA,EACf,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,sBAAsB;AACxB;AAEO,IAAM,uBAAN,cAAmC,MAAM;AAAA,EAC9C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAEO,IAAM,0BAAN,cAAsC,qBAAqB;AAAA,EACvD;AAAA,EACA;AAAA,EAET,YAAY,QAAgB,UAAqC;AAC/D,UAAM,SAAS,WAAW,wBAAwB,MAAM,EAAE;AAC1D,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AACF;AAQO,IAAM,mCAAN,cAA+C,qBAAqB;AAAA,EAChE;AAAA,EACA;AAAA,EAET,YAAY,QAAgB,UAAqC;AAC/D,UAAM,SAAS,WAAW,sCAAsC,MAAM,EAAE;AACxE,SAAK,OAAO;AACZ,SAAK,SAAS;AACd,SAAK,WAAW;AAAA,EAClB;AACF;AAEO,IAAM,kBAAN,MAAM,iBAAgB;AAAA,EACV;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA+B;AACzC,SAAK,OAAO,OAAO,KAAK,QAAQ,OAAO,EAAE;AACzC,SAAK,YAAY,OAAO;AACxB,SAAK,YAAY,OAAO;AACxB,SAAK,QAAQ,OAAO,SAAS,CAAC;AAC9B,SAAK,QAAQ,OAAO,SAAS;AAC7B,SAAK,WAAW,OAAO,YAAY;AAAA,EACrC;AAAA,EAEA,OAAO,QAAQ,SA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3C,WAAK,aAAa,KAAK,KAAK;AAAA,IAC9B;AAAA,EACF;AAAA,EAEQ,IAAI,YAAoB,MAAiB;AAC/C,QAAI,KAAK,OAAO;AACd,cAAQ,IAAI,sBAAsB,OAAO,IAAI,GAAG,IAAI;AAAA,IACtD;AAAA,EACF;AACF;AAEA,SAAS,gBAEA;AACP,MAAI;AAGF,UAAM,OAAO,UAAQ,oBAAoB;AAOzC,WAAO,KAAK,OAAO,gBAAgB,KAAK;AAAA,EAC1C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEA,SAAS,YAAY,OAAe;AAClC,SAAO,MACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,WAAW,GAAG,EACtB,YAAY;AACjB;AAEO,IAAM,UAAU;AAAA,EACrB,SAAS,gBAAgB;AAC3B;","names":[]}
@@ -1 +1 @@
1
- export { T as TracingConfig, a as TracingState, f as flush, i as init, b as isGatewayConfigured, c as isInitialized, s as shutdown } from '../index-Caw3XVub.mjs';
1
+ export { O as ObservationKind, a as ObserveClaudeOptions, b as ObserveOptions, T as TracingConfig, c as TracingState, f as flush, i as init, d as isGatewayConfigured, e as isInitialized, o as observe, g as observeAnthropic, h as observeClaude, j as observeOpenAI, s as shutdown } from '../index-yJgb8wh6.mjs';
@@ -1 +1 @@
1
- export { T as TracingConfig, a as TracingState, f as flush, i as init, b as isGatewayConfigured, c as isInitialized, s as shutdown } from '../index-Caw3XVub.js';
1
+ export { O as ObservationKind, a as ObserveClaudeOptions, b as ObserveOptions, T as TracingConfig, c as TracingState, f as flush, i as init, d as isGatewayConfigured, e as isInitialized, o as observe, g as observeAnthropic, h as observeClaude, j as observeOpenAI, s as shutdown } from '../index-yJgb8wh6.js';
@@ -24,6 +24,10 @@ __export(tracing_exports, {
24
24
  init: () => init,
25
25
  isGatewayConfigured: () => isGatewayConfigured,
26
26
  isInitialized: () => isInitialized,
27
+ observe: () => observe,
28
+ observeAnthropic: () => observeAnthropic,
29
+ observeClaude: () => observeClaude,
30
+ observeOpenAI: () => observeOpenAI,
27
31
  shutdown: () => shutdown
28
32
  });
29
33
  module.exports = __toCommonJS(tracing_exports);
@@ -215,12 +219,186 @@ function isGatewayConfigured() {
215
219
  const secretKey = getEnv(ENV_VARS.SECRET_KEY);
216
220
  return !!(host && publicKey && secretKey);
217
221
  }
222
+
223
+ // src/tracing/observe.ts
224
+ var import_api = require("@opentelemetry/api");
225
+ function asAttr(value) {
226
+ return typeof value === "string" ? value : JSON.stringify(value);
227
+ }
228
+ async function observe(name, fn, options = {}) {
229
+ const tracer = import_api.trace.getTracer("@withgateway/sdk");
230
+ const span = tracer.startSpan(name, {
231
+ attributes: {
232
+ "openinference.span.kind": options.kind ?? "AGENT",
233
+ ...options.input !== void 0 ? { "input.value": asAttr(options.input) } : {}
234
+ }
235
+ });
236
+ try {
237
+ const result = await import_api.context.with(
238
+ import_api.trace.setSpan(import_api.context.active(), span),
239
+ fn
240
+ );
241
+ if (options.captureOutput !== false && result !== void 0) {
242
+ span.setAttribute("output.value", asAttr(result));
243
+ }
244
+ span.setStatus({ code: import_api.SpanStatusCode.OK });
245
+ return result;
246
+ } catch (error) {
247
+ span.setStatus({
248
+ code: import_api.SpanStatusCode.ERROR,
249
+ message: error instanceof Error ? error.message : String(error)
250
+ });
251
+ throw error;
252
+ } finally {
253
+ span.end();
254
+ }
255
+ }
256
+
257
+ // src/tracing/instrument.ts
258
+ function warn2(message, ...args) {
259
+ console.warn(`[gatewaysdk.tracing] ${message}`, ...args);
260
+ }
261
+ function observeOpenAI(client) {
262
+ try {
263
+ const {
264
+ OpenAIInstrumentation
265
+ } = require("@arizeai/openinference-instrumentation-openai");
266
+ const OpenAIClass = client.constructor;
267
+ new OpenAIInstrumentation().manuallyInstrument({ OpenAI: OpenAIClass });
268
+ } catch (error) {
269
+ warn2(
270
+ "observeOpenAI: could not load @arizeai/openinference-instrumentation-openai \u2014 OpenAI calls will not be traced.",
271
+ error
272
+ );
273
+ }
274
+ return client;
275
+ }
276
+ function observeAnthropic(client) {
277
+ try {
278
+ const {
279
+ AnthropicInstrumentation
280
+ } = require("@arizeai/openinference-instrumentation-anthropic");
281
+ const AnthropicClass = client.constructor;
282
+ new AnthropicInstrumentation().manuallyInstrument({
283
+ Messages: AnthropicClass.Messages
284
+ });
285
+ } catch (error) {
286
+ warn2(
287
+ "observeAnthropic: could not load @arizeai/openinference-instrumentation-anthropic \u2014 Anthropic calls will not be traced.",
288
+ error
289
+ );
290
+ }
291
+ return client;
292
+ }
293
+
294
+ // src/tracing/claude.ts
295
+ var import_api2 = require("@opentelemetry/api");
296
+ function cleanToolName(name) {
297
+ return name.replace(/^mcp__[^_]+__/, "");
298
+ }
299
+ function toolResultText(content) {
300
+ if (typeof content === "string") return content;
301
+ if (Array.isArray(content))
302
+ return content.map(
303
+ (b) => b && typeof b === "object" && "text" in b ? String(b.text) : JSON.stringify(b)
304
+ ).join("");
305
+ return JSON.stringify(content ?? "");
306
+ }
307
+ async function* observeClaude(stream, options) {
308
+ const tracer = import_api2.trace.getTracer("@withgateway/sdk");
309
+ const root = tracer.startSpan(options.name, {
310
+ attributes: {
311
+ "openinference.span.kind": "AGENT",
312
+ ...options.input !== void 0 ? { "input.value": options.input } : {}
313
+ }
314
+ });
315
+ const rootCtx = import_api2.trace.setSpan(import_api2.context.active(), root);
316
+ const openTools = /* @__PURE__ */ new Map();
317
+ const model = options.model ?? "claude";
318
+ let finalText = "";
319
+ try {
320
+ for await (const message of stream) {
321
+ if (message?.type === "assistant") {
322
+ let turnText = "";
323
+ const toolUses = [];
324
+ for (const block of message.message?.content ?? []) {
325
+ if (block?.type === "text") {
326
+ finalText += block.text;
327
+ turnText += block.text;
328
+ }
329
+ if (block?.type === "tool_use") {
330
+ toolUses.push({ id: block.id, name: block.name, input: block.input });
331
+ }
332
+ }
333
+ const gen = tracer.startSpan(
334
+ "assistant",
335
+ {
336
+ attributes: {
337
+ "openinference.span.kind": "LLM",
338
+ "llm.model_name": model,
339
+ "llm.provider": "anthropic",
340
+ "output.value": turnText || toolUses.map((t) => `\u2192 ${cleanToolName(t.name)}`).join(", ")
341
+ }
342
+ },
343
+ rootCtx
344
+ );
345
+ const usage = message.message?.usage;
346
+ if (usage?.input_tokens != null)
347
+ gen.setAttribute("llm.token_count.prompt", usage.input_tokens);
348
+ if (usage?.output_tokens != null)
349
+ gen.setAttribute("llm.token_count.completion", usage.output_tokens);
350
+ gen.end();
351
+ for (const t of toolUses) {
352
+ const span = tracer.startSpan(
353
+ `tool.${cleanToolName(t.name)}`,
354
+ {
355
+ attributes: {
356
+ "openinference.span.kind": "TOOL",
357
+ "tool.name": cleanToolName(t.name),
358
+ "input.value": JSON.stringify(t.input)
359
+ }
360
+ },
361
+ rootCtx
362
+ );
363
+ openTools.set(t.id, span);
364
+ }
365
+ }
366
+ if (message?.type === "user") {
367
+ const content = message.message?.content;
368
+ if (Array.isArray(content)) {
369
+ for (const block of content) {
370
+ if (block?.type === "tool_result") {
371
+ const span = openTools.get(block.tool_use_id);
372
+ if (span) {
373
+ span.setAttribute("output.value", toolResultText(block.content));
374
+ span.setStatus({ code: import_api2.SpanStatusCode.OK });
375
+ span.end();
376
+ openTools.delete(block.tool_use_id);
377
+ }
378
+ }
379
+ }
380
+ }
381
+ }
382
+ yield message;
383
+ }
384
+ } finally {
385
+ for (const span of openTools.values()) span.end();
386
+ openTools.clear();
387
+ root.setAttribute("output.value", finalText);
388
+ root.setStatus({ code: import_api2.SpanStatusCode.OK });
389
+ root.end();
390
+ }
391
+ }
218
392
  // Annotate the CommonJS export names for ESM import in node:
219
393
  0 && (module.exports = {
220
394
  flush,
221
395
  init,
222
396
  isGatewayConfigured,
223
397
  isInitialized,
398
+ observe,
399
+ observeAnthropic,
400
+ observeClaude,
401
+ observeOpenAI,
224
402
  shutdown
225
403
  });
226
404
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/tracing/index.ts","../../src/tracing/init.ts"],"sourcesContent":["/**\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 shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\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.\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { TracingConfig, TracingState } from \"./types\";\n\n// Environment variable names (support both GATEWAY_* and GATEWAY_* prefixes)\nconst ENV_VARS = {\n HOST: [\"GATEWAY_HOST\", \"GATEWAY_HOST\"],\n PUBLIC_KEY: [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_PUBLIC_KEY\"],\n SECRET_KEY: [\"GATEWAY_SECRET_KEY\", \"GATEWAY_SECRET_KEY\"],\n ENDPOINT: [\"GATEWAY_OTLP_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(keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = process.env[key];\n if (value) return value;\n }\n return 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\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 // 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 /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\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 log(\"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 log(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\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 provider.register();\n\n state.provider = provider;\n state.initialized = true;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\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"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,IAAM,WAAW;AAAA,EACf,MAAM,CAAC,gBAAgB,cAAc;AAAA,EACrC,YAAY,CAAC,sBAAsB,oBAAoB;AAAA,EACvD,YAAY,CAAC,sBAAsB,oBAAoB;AAAA,EACvD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AA,EACpC,SAAS,GAAG;AACV,SAAK,uBAAuB,CAAC;AAAA,EAC/B;AACF;AAqBA,eAAsB,WAA0B;AAC9C,MAAI,CAAC,MAAM,eAAe,CAAC,MAAM,UAAU;AACzC,QAAI,8CAA8C;AAClD;AAAA,EACF;AAEA,MAAI;AACF,UAAO,MAAM,SAA+C,SAAS;AACrE,QAAI,mBAAmB;AAAA,EACzB,SAAS,GAAG;AACV,SAAK,0BAA0B,CAAC;AAAA,EAClC;AAEA,QAAM,WAAW;AACjB,QAAM,cAAc;AACtB;AAKO,SAAS,gBAAyB;AACvC,SAAO,MAAM;AACf;AAKO,SAAS,sBAA+B;AAC7C,QAAM,OAAO,OAAO,SAAS,IAAI;AACjC,QAAM,YAAY,OAAO,SAAS,UAAU;AAC5C,QAAM,YAAY,OAAO,SAAS,UAAU;AAC5C,SAAO,CAAC,EAAE,QAAQ,aAAa;AACjC;","names":[]}
1
+ {"version":3,"sources":["../../src/tracing/index.ts","../../src/tracing/init.ts","../../src/tracing/observe.ts","../../src/tracing/instrument.ts","../../src/tracing/claude.ts"],"sourcesContent":["/**\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 shutdown,\n flush,\n isInitialized,\n isGatewayConfigured,\n} from \"./init\";\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.\n *\n * Mirrors the Python SDK's tracing.init() for a consistent developer experience.\n */\n\nimport type { TracingConfig, TracingState } from \"./types\";\n\n// Environment variable names (support both GATEWAY_* and GATEWAY_* prefixes)\nconst ENV_VARS = {\n HOST: [\"GATEWAY_HOST\", \"GATEWAY_HOST\"],\n PUBLIC_KEY: [\"GATEWAY_PUBLIC_KEY\", \"GATEWAY_PUBLIC_KEY\"],\n SECRET_KEY: [\"GATEWAY_SECRET_KEY\", \"GATEWAY_SECRET_KEY\"],\n ENDPOINT: [\"GATEWAY_OTLP_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(keys: readonly string[]): string | undefined {\n for (const key of keys) {\n const value = process.env[key];\n if (value) return value;\n }\n return 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\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 // 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 /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\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 log(\"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 log(\n \"Added custom span processor: %s\",\n (sp as { constructor?: { name?: string } }).constructor?.name ??\n \"unknown\",\n );\n }\n }\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 provider.register();\n\n state.provider = provider;\n state.initialized = true;\n /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-require-imports */\n\n log(\n \"GatewaySDK tracing initialized successfully (service=%s)\",\n config.serviceName ?? \"gatewaysdk-tracing\",\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\";\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\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 = 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 },\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 * 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 * 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} from \"@opentelemetry/api\";\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface ObserveClaudeOptions {\n /** Root span name (becomes the trace name). */\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\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\nexport async function* observeClaude(\n stream: AsyncIterable<any>,\n options: ObserveClaudeOptions,\n): AsyncGenerator<any> {\n const tracer = trace.getTracer(\"@withgateway/sdk\");\n const root: Span = tracer.startSpan(options.name, {\n attributes: {\n \"openinference.span.kind\": \"AGENT\",\n ...(options.input !== undefined ? { \"input.value\": options.input } : {}),\n },\n });\n const rootCtx: Context = trace.setSpan(context.active(), root);\n const openTools = new Map<string, Span>();\n const model = options.model ?? \"claude\";\n let finalText = \"\";\n\n try {\n for await (const message of stream) {\n if (message?.type === \"assistant\") {\n let turnText = \"\";\n const toolUses: Array<{ id: string; name: string; input: unknown }> = [];\n for (const block of message.message?.content ?? []) {\n if (block?.type === \"text\") {\n finalText += block.text;\n turnText += block.text;\n }\n if (block?.type === \"tool_use\") {\n toolUses.push({ id: block.id, name: block.name, input: block.input });\n }\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 turnText ||\n toolUses.map((t) => `→ ${cleanToolName(t.name)}`).join(\", \"),\n },\n },\n rootCtx,\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 rootCtx,\n );\n openTools.set(t.id, span);\n }\n }\n\n // tool_result (in a `user` message) closes the matching TOOL span.\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 span = openTools.get(block.tool_use_id);\n if (span) {\n span.setAttribute(\"output.value\", toolResultText(block.content));\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n openTools.delete(block.tool_use_id);\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 root.setAttribute(\"output.value\", finalText);\n root.setStatus({ code: SpanStatusCode.OK });\n root.end();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACYA,IAAM,WAAW;AAAA,EACf,MAAM,CAAC,gBAAgB,cAAc;AAAA,EACrC,YAAY,CAAC,sBAAsB,oBAAoB;AAAA,EACvD,YAAY,CAAC,sBAAsB,oBAAoB;AAAA,EACvD,UAAU,CAAC,yBAAyB,uBAAuB;AAC7D;AAEA,IAAM,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