@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,3 +1,6 @@
1
+ import { createRequire as __gatewayCreateRequire } from "module";
2
+ const require = __gatewayCreateRequire(import.meta.url);
3
+
1
4
  // src/context/index.ts
2
5
  var GatewayContextError = class extends Error {
3
6
  constructor(message, options) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/context/index.ts"],"sourcesContent":["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"],"mappings":";AA0LO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAEO,IAAM,8BAAN,cAA0C,oBAAoB;AAAA,EAC1D;AAAA,EAET,YAAY,SAAiB,cAAuB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,eAAe;AAAA,EACtB;AACF;AAEO,IAAM,iBAAN,MAAM,gBAAe;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA8B;AACxC,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,SAAsC,CAAC,GAAG;AACvD,UAAM,OACJ,OAAO,QAAQ,QAAQ,IAAI,gBAAgB,QAAQ,IAAI;AACzD,UAAM,YACJ,OAAO,aACP,QAAQ,IAAI,sBACZ,QAAQ,IAAI;AACd,UAAM,YACJ,OAAO,aACP,QAAQ,IAAI,sBACZ,QAAQ,IAAI;AAEd,UAAM,UAAU;AAAA,MACd,CAAC,QAAQ,IAAI;A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C5C,SAAO,WACJ,MAAM,GAAG,EACT,OAAO,OAAO,EACd,IAAI,CAAC,SAAS,mBAAmB,IAAI,CAAC,EACtC,KAAK,GAAG;AACb;AAEA,SAAS,SAAS,OAAwC;AACxD,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,WAAO,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAC/D,SACD,CAAC;AAAA,EACP,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,IAAM,UAAU;AAAA,EACrB,SAAS,eAAe;AAC1B;","names":["identifier"]}
1
+ {"version":3,"sources":["../../src/context/index.ts"],"sourcesContent":["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"],"mappings":";;;;AA0LO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB,SAA+B;AAC1D,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS;AAAA,EACxB;AACF;AAEO,IAAM,8BAAN,cAA0C,oBAAoB;AAAA,EAC1D;AAAA,EAET,YAAY,SAAiB,cAAuB;AAClD,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,eAAe;AAAA,EACtB;AACF;AAEO,IAAM,iBAAN,MAAM,gBAAe;AAAA,EACT;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEjB,YAAY,QAA8B;AACxC,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,SAAsC,CAAC,GAAG;AACvD,UAAM,OACJ,OAAO,QAAQ,QAAQ,IAAI,gBAAgB,QAAQ,IAAI;AACzD,UAAM,YACJ,OAAO,aACP,QAAQ,IAAI,sBACZ,QAAQ,IAAI;AACd,U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GAAI,QAAQ,WAAW,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA,EAC3D;AACF;AAEA,SAAS,iBAAiB,YAAoB;AAC5C,SAAO,WACJ,MAAM,GAAG,EACT,OAAO,OAAO,EACd,IAAI,CAAC,SAAS,mBAAmB,IAAI,CAAC,EACtC,KAAK,GAAG;AACb;AAEA,SAAS,SAAS,OAAwC;AACxD,MAAI;AACF,UAAM,SAAS,KAAK,MAAM,KAAK;AAC/B,WAAO,UAAU,OAAO,WAAW,YAAY,CAAC,MAAM,QAAQ,MAAM,IAC/D,SACD,CAAC;AAAA,EACP,QAAQ;AACN,WAAO,CAAC;AAAA,EACV;AACF;AAEO,IAAM,UAAU;AAAA,EACrB,SAAS,eAAe;AAC1B;","names":["identifier"]}
@@ -1,3 +1,5 @@
1
+ import { createRequire as __gatewayCreateRequire } from "module";
2
+ const require = __gatewayCreateRequire(import.meta.url);
1
3
  var __defProp = Object.defineProperty;
2
4
  var __export = (target, all) => {
3
5
  for (var name in all)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../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"],"sourcesContent":["/**\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"],"mappings":";;;;;;;AASA,SAAS,kBAAkB;AAGpB,SAAS,YAAY,eAAuB,QAAwB;AACzE,QAAM,MAAM,WAAW,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,MAAI,aAAa;AACjB,aAAW,WAAW,OAAO,UAAU;AACrC,kBAAc,QAAQ,SAAS;AAC/B,QAAI,mBAAmB,YAAY;AACjC,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO,OAAO,SAAS,OAAO,SAAS,SAAS,CAAC,KAAK;AACxD;;;ACrCA,SAAS,yBAAy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AA,EAEjC,MAAM,aAA4B;AAAA,EAAC;AACrC;AAEO,SAAS,wBACd,MACA,cACA,YACA,QACM;AACN,OAAK,aAAa,sBAAsB,eAAe,YAAY;AACnE,OAAK,aAAa,sBAAsB,aAAa,UAAU;AAC/D,OAAK,aAAa,sBAAsB,SAAS,MAAM;AACzD;;;AC/CA;AAAA;AAAA,gCAAAA;AAAA,EAAA,aAAAC;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeA,IAAI,SAAkC;AAa/B,SAAS,KAAK,QAA0B;AAC7C,WAAS,IAAI,iBAAiB;AAAA,IAC5B,QAAQ,OAAO;AAAA,IACf,QAAQ,OAAO;AAAA,IACf,WAAW,OAAO;AAAA,IAClB,WAAW,OAAO,aAAa;AAAA,EACjC,CAAC;AACH;AAKA,eAAsB,SAAS,OAA+C;AAC5E,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,SAAS,KAAK;AAC9B;AAKA,eAAsB,WACpB,eACA,QACA,SAC2B;AAC3B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,WAAW,eAAe,QAAQ,OAAO;AACzD;AAKA,eAAsBC,OAAM,gBAA0C;AACpE,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,MAAM,cAAc;AACpC;AAKA,eAAsB,WAA0B;AAC9C,MAAI,QAAQ;AACV,UAAM,OAAO,SAAS;AACtB,aAAS;AAAA,EACX;AAEA,yBAAa;AACf;AAUO,SAASC,0BAA+B;AAC7C,yBAAa;AACf;AAMO,SAAS,YAAqC;AACnD,SAAO;AACT;","names":["clearExperimentContext","fetch","fetch","clearExperimentContext"]}
1
+ {"version":3,"sources":["../../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"],"sourcesContent":["/**\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"],"mappings":";;;;;;;;;AASA,SAAS,kBAAkB;AAGpB,SAAS,YAAY,eAAuB,QAAwB;AACzE,QAAM,MAAM,WAAW,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,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AA,IACF;AAAA,EACF;AACA,SAAO,OAAO,WAAW,eAAe,QAAQ,OAAO;AACzD;AAKA,eAAsBC,OAAM,gBAA0C;AACpE,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI;AAAA,MACR;AAAA,IACF;AAAA,EACF;AACA,SAAO,OAAO,MAAM,cAAc;AACpC;AAKA,eAAsB,WAA0B;AAC9C,MAAI,QAAQ;AACV,UAAM,OAAO,SAAS;AACtB,aAAS;AAAA,EACX;AAEA,yBAAa;AACf;AAUO,SAASC,0BAA+B;AAC7C,yBAAa;AACf;AAMO,SAAS,YAAqC;AACnD,SAAO;AACT;","names":["clearExperimentContext","fetch","fetch","clearExperimentContext"]}
@@ -154,6 +154,79 @@ declare function isInitialized(): boolean;
154
154
  */
155
155
  declare function isGatewayConfigured(): boolean;
156
156
 
157
+ type ObservationKind = "AGENT" | "CHAIN" | "TOOL" | "LLM" | "RETRIEVER";
158
+ interface ObserveOptions {
159
+ /** Recorded as input.value on the span (JSON-stringified if not a string). */
160
+ input?: unknown;
161
+ /** OpenInference span kind. Defaults to "AGENT" for the outer run. */
162
+ kind?: ObservationKind;
163
+ /**
164
+ * When true (default), the callback's return value is recorded as
165
+ * output.value. Set false if the return value is large/uninteresting.
166
+ */
167
+ captureOutput?: boolean;
168
+ }
169
+ /**
170
+ * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented
171
+ * client calls, nested observe() calls) nests under it, forming one trace.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * const result = await observe("my-agent.run", async () => {
176
+ * // client.chat.completions.create(...) here becomes a child GENERATION
177
+ * return finalText;
178
+ * }, { input: prompt });
179
+ * ```
180
+ */
181
+ declare function observe<T>(name: string, fn: () => Promise<T>, options?: ObserveOptions): Promise<T>;
182
+
183
+ /**
184
+ * Client wrappers that turn an SDK's calls into spans on the Gateway provider.
185
+ *
186
+ * Node ESM can't retroactively patch a module the app already imported, so — as
187
+ * Langfuse does with `observeOpenAI` — the app hands us the client and we
188
+ * instrument it explicitly. One SDK call, no OpenTelemetry in the app.
189
+ *
190
+ * The OpenInference instrumentations are bundled optional deps of this package;
191
+ * we load them with require() (the ESM build injects a real createRequire).
192
+ */
193
+ /**
194
+ * Instrument an OpenAI client so its requests become GENERATION spans on the
195
+ * Gateway provider. Returns the same client (its class prototype is patched, so
196
+ * this and every other instance of that client are traced).
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * import OpenAI from "openai";
201
+ * import { init, observeOpenAI } from "@withgateway/sdk/tracing";
202
+ * init();
203
+ * const client = observeOpenAI(new OpenAI());
204
+ * ```
205
+ */
206
+ declare function observeOpenAI<T extends object>(client: T): T;
207
+ /**
208
+ * Instrument an Anthropic client so its requests become GENERATION spans.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * import Anthropic from "@anthropic-ai/sdk";
213
+ * import { init, observeAnthropic } from "@withgateway/sdk/tracing";
214
+ * init();
215
+ * const client = observeAnthropic(new Anthropic());
216
+ * ```
217
+ */
218
+ declare function observeAnthropic<T extends object>(client: T): T;
219
+
220
+ interface ObserveClaudeOptions {
221
+ /** Root span name (becomes the trace name). */
222
+ name: string;
223
+ /** Recorded as input.value on the root span → trace-level input. */
224
+ input?: string;
225
+ /** Model label for the generation spans. */
226
+ model?: string;
227
+ }
228
+ declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
229
+
157
230
  /**
158
231
  * Tracing module for GatewaySDK TypeScript SDK.
159
232
  *
@@ -179,15 +252,22 @@ declare function isGatewayConfigured(): boolean;
179
252
  * ```
180
253
  */
181
254
 
255
+ type _tracingModule_ObservationKind = ObservationKind;
256
+ type _tracingModule_ObserveClaudeOptions = ObserveClaudeOptions;
257
+ type _tracingModule_ObserveOptions = ObserveOptions;
182
258
  type _tracingModule_TracingConfig = TracingConfig;
183
259
  type _tracingModule_TracingState = TracingState;
184
260
  declare const _tracingModule_flush: typeof flush;
185
261
  declare const _tracingModule_init: typeof init;
186
262
  declare const _tracingModule_isGatewayConfigured: typeof isGatewayConfigured;
187
263
  declare const _tracingModule_isInitialized: typeof isInitialized;
264
+ declare const _tracingModule_observe: typeof observe;
265
+ declare const _tracingModule_observeAnthropic: typeof observeAnthropic;
266
+ declare const _tracingModule_observeClaude: typeof observeClaude;
267
+ declare const _tracingModule_observeOpenAI: typeof observeOpenAI;
188
268
  declare const _tracingModule_shutdown: typeof shutdown;
189
269
  declare namespace _tracingModule {
190
- export { type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingState as TracingState, _tracingModule_flush as flush, _tracingModule_init as init, _tracingModule_isGatewayConfigured as isGatewayConfigured, _tracingModule_isInitialized as isInitialized, _tracingModule_shutdown as shutdown };
270
+ export { type _tracingModule_ObservationKind as ObservationKind, type _tracingModule_ObserveClaudeOptions as ObserveClaudeOptions, type _tracingModule_ObserveOptions as ObserveOptions, type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingState as TracingState, _tracingModule_flush as flush, _tracingModule_init as init, _tracingModule_isGatewayConfigured as isGatewayConfigured, _tracingModule_isInitialized as isInitialized, _tracingModule_observe as observe, _tracingModule_observeAnthropic as observeAnthropic, _tracingModule_observeClaude as observeClaude, _tracingModule_observeOpenAI as observeOpenAI, _tracingModule_shutdown as shutdown };
191
271
  }
192
272
 
193
- export { type TracingConfig as T, _tracingModule as _, type TracingState as a, isGatewayConfigured as b, isInitialized as c, flush as f, init as i, shutdown as s };
273
+ export { type ObservationKind as O, type TracingConfig as T, _tracingModule as _, type ObserveClaudeOptions as a, type ObserveOptions as b, type TracingState as c, isGatewayConfigured as d, isInitialized as e, flush as f, observeAnthropic as g, observeClaude as h, init as i, observeOpenAI as j, observe as o, shutdown as s };
@@ -154,6 +154,79 @@ declare function isInitialized(): boolean;
154
154
  */
155
155
  declare function isGatewayConfigured(): boolean;
156
156
 
157
+ type ObservationKind = "AGENT" | "CHAIN" | "TOOL" | "LLM" | "RETRIEVER";
158
+ interface ObserveOptions {
159
+ /** Recorded as input.value on the span (JSON-stringified if not a string). */
160
+ input?: unknown;
161
+ /** OpenInference span kind. Defaults to "AGENT" for the outer run. */
162
+ kind?: ObservationKind;
163
+ /**
164
+ * When true (default), the callback's return value is recorded as
165
+ * output.value. Set false if the return value is large/uninteresting.
166
+ */
167
+ captureOutput?: boolean;
168
+ }
169
+ /**
170
+ * Run `fn` inside a span named `name`. Anything traced inside (auto-instrumented
171
+ * client calls, nested observe() calls) nests under it, forming one trace.
172
+ *
173
+ * @example
174
+ * ```ts
175
+ * const result = await observe("my-agent.run", async () => {
176
+ * // client.chat.completions.create(...) here becomes a child GENERATION
177
+ * return finalText;
178
+ * }, { input: prompt });
179
+ * ```
180
+ */
181
+ declare function observe<T>(name: string, fn: () => Promise<T>, options?: ObserveOptions): Promise<T>;
182
+
183
+ /**
184
+ * Client wrappers that turn an SDK's calls into spans on the Gateway provider.
185
+ *
186
+ * Node ESM can't retroactively patch a module the app already imported, so — as
187
+ * Langfuse does with `observeOpenAI` — the app hands us the client and we
188
+ * instrument it explicitly. One SDK call, no OpenTelemetry in the app.
189
+ *
190
+ * The OpenInference instrumentations are bundled optional deps of this package;
191
+ * we load them with require() (the ESM build injects a real createRequire).
192
+ */
193
+ /**
194
+ * Instrument an OpenAI client so its requests become GENERATION spans on the
195
+ * Gateway provider. Returns the same client (its class prototype is patched, so
196
+ * this and every other instance of that client are traced).
197
+ *
198
+ * @example
199
+ * ```ts
200
+ * import OpenAI from "openai";
201
+ * import { init, observeOpenAI } from "@withgateway/sdk/tracing";
202
+ * init();
203
+ * const client = observeOpenAI(new OpenAI());
204
+ * ```
205
+ */
206
+ declare function observeOpenAI<T extends object>(client: T): T;
207
+ /**
208
+ * Instrument an Anthropic client so its requests become GENERATION spans.
209
+ *
210
+ * @example
211
+ * ```ts
212
+ * import Anthropic from "@anthropic-ai/sdk";
213
+ * import { init, observeAnthropic } from "@withgateway/sdk/tracing";
214
+ * init();
215
+ * const client = observeAnthropic(new Anthropic());
216
+ * ```
217
+ */
218
+ declare function observeAnthropic<T extends object>(client: T): T;
219
+
220
+ interface ObserveClaudeOptions {
221
+ /** Root span name (becomes the trace name). */
222
+ name: string;
223
+ /** Recorded as input.value on the root span → trace-level input. */
224
+ input?: string;
225
+ /** Model label for the generation spans. */
226
+ model?: string;
227
+ }
228
+ declare function observeClaude(stream: AsyncIterable<any>, options: ObserveClaudeOptions): AsyncGenerator<any>;
229
+
157
230
  /**
158
231
  * Tracing module for GatewaySDK TypeScript SDK.
159
232
  *
@@ -179,15 +252,22 @@ declare function isGatewayConfigured(): boolean;
179
252
  * ```
180
253
  */
181
254
 
255
+ type _tracingModule_ObservationKind = ObservationKind;
256
+ type _tracingModule_ObserveClaudeOptions = ObserveClaudeOptions;
257
+ type _tracingModule_ObserveOptions = ObserveOptions;
182
258
  type _tracingModule_TracingConfig = TracingConfig;
183
259
  type _tracingModule_TracingState = TracingState;
184
260
  declare const _tracingModule_flush: typeof flush;
185
261
  declare const _tracingModule_init: typeof init;
186
262
  declare const _tracingModule_isGatewayConfigured: typeof isGatewayConfigured;
187
263
  declare const _tracingModule_isInitialized: typeof isInitialized;
264
+ declare const _tracingModule_observe: typeof observe;
265
+ declare const _tracingModule_observeAnthropic: typeof observeAnthropic;
266
+ declare const _tracingModule_observeClaude: typeof observeClaude;
267
+ declare const _tracingModule_observeOpenAI: typeof observeOpenAI;
188
268
  declare const _tracingModule_shutdown: typeof shutdown;
189
269
  declare namespace _tracingModule {
190
- export { type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingState as TracingState, _tracingModule_flush as flush, _tracingModule_init as init, _tracingModule_isGatewayConfigured as isGatewayConfigured, _tracingModule_isInitialized as isInitialized, _tracingModule_shutdown as shutdown };
270
+ export { type _tracingModule_ObservationKind as ObservationKind, type _tracingModule_ObserveClaudeOptions as ObserveClaudeOptions, type _tracingModule_ObserveOptions as ObserveOptions, type _tracingModule_TracingConfig as TracingConfig, type _tracingModule_TracingState as TracingState, _tracingModule_flush as flush, _tracingModule_init as init, _tracingModule_isGatewayConfigured as isGatewayConfigured, _tracingModule_isInitialized as isInitialized, _tracingModule_observe as observe, _tracingModule_observeAnthropic as observeAnthropic, _tracingModule_observeClaude as observeClaude, _tracingModule_observeOpenAI as observeOpenAI, _tracingModule_shutdown as shutdown };
191
271
  }
192
272
 
193
- export { type TracingConfig as T, _tracingModule as _, type TracingState as a, isGatewayConfigured as b, isInitialized as c, flush as f, init as i, shutdown as s };
273
+ export { type ObservationKind as O, type TracingConfig as T, _tracingModule as _, type ObserveClaudeOptions as a, type ObserveOptions as b, type TracingState as c, isGatewayConfigured as d, isInitialized as e, flush as f, observeAnthropic as g, observeClaude as h, init as i, observeOpenAI as j, observe as o, shutdown as s };
package/dist/index.d.mts CHANGED
@@ -2,7 +2,7 @@ export { EXPERIMENT_ATTRIBUTES, ExperimentClient, ExperimentClientConfig, Experi
2
2
  export { GatewayContext, GatewayContextCommit, GatewayContextConfig, GatewayContextConflictError, GatewayContextError, GatewayContextFileEntry, GatewayContextFileInput, GatewayContextListOptions, GatewayContextListResponse, GatewayContextPullOptions, GatewayContextPushOptions, GatewayContextPushResponse, GatewayContextRepo, GatewayContextRepoKind, GatewayContextRuntimeContext, GatewayContextSnapshot, GatewayContextWritePolicy, GatewayRenderSystemOptions, GatewayResolvedAgentContext, GatewayResolvedContextRef, context, renderAgentSystem } from './context/index.mjs';
3
3
  export { GatewayMemory, GatewayMemoryCommit, GatewayMemoryConfig, GatewayMemoryConflictError, GatewayMemoryDeleteOptions, GatewayMemoryError, GatewayMemoryFileEntry, GatewayMemoryPullOptions, GatewayMemoryPushResponse, GatewayMemoryRepo, GatewayMemoryRuntimeContext, GatewayMemorySnapshot, GatewayMemoryWriteOptions, GatewayMemoryWritePolicy, memory } from './memory/index.mjs';
4
4
  export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, GatewaySecurityContext, GatewaySecurityError, GatewayToolApprovalRequiredError, GatewayToolBlockedError, GatewayToolCallAuthorizeResponse, GatewayToolDescriptor, GatewayToolsetResolveResponse, SecureToolsOptions, gateway } from './security/index.mjs';
5
- import { _ as _tracingModule } from './index-Caw3XVub.mjs';
5
+ import { _ as _tracingModule } from './index-yJgb8wh6.mjs';
6
6
  import 'async_hooks';
7
7
  import '@opentelemetry/api';
8
8
  import '@opentelemetry/sdk-trace-base';
package/dist/index.d.ts CHANGED
@@ -2,7 +2,7 @@ export { EXPERIMENT_ATTRIBUTES, ExperimentClient, ExperimentClientConfig, Experi
2
2
  export { GatewayContext, GatewayContextCommit, GatewayContextConfig, GatewayContextConflictError, GatewayContextError, GatewayContextFileEntry, GatewayContextFileInput, GatewayContextListOptions, GatewayContextListResponse, GatewayContextPullOptions, GatewayContextPushOptions, GatewayContextPushResponse, GatewayContextRepo, GatewayContextRepoKind, GatewayContextRuntimeContext, GatewayContextSnapshot, GatewayContextWritePolicy, GatewayRenderSystemOptions, GatewayResolvedAgentContext, GatewayResolvedContextRef, context, renderAgentSystem } from './context/index.js';
3
3
  export { GatewayMemory, GatewayMemoryCommit, GatewayMemoryConfig, GatewayMemoryConflictError, GatewayMemoryDeleteOptions, GatewayMemoryError, GatewayMemoryFileEntry, GatewayMemoryPullOptions, GatewayMemoryPushResponse, GatewayMemoryRepo, GatewayMemoryRuntimeContext, GatewayMemorySnapshot, GatewayMemoryWriteOptions, GatewayMemoryWritePolicy, memory } from './memory/index.js';
4
4
  export { GatewayAgentDescriptor, GatewaySecurity, GatewaySecurityConfig, GatewaySecurityContext, GatewaySecurityError, GatewayToolApprovalRequiredError, GatewayToolBlockedError, GatewayToolCallAuthorizeResponse, GatewayToolDescriptor, GatewayToolsetResolveResponse, SecureToolsOptions, gateway } from './security/index.js';
5
- import { _ as _tracingModule } from './index-Caw3XVub.js';
5
+ import { _ as _tracingModule } from './index-yJgb8wh6.js';
6
6
  import 'async_hooks';
7
7
  import '@opentelemetry/api';
8
8
  import '@opentelemetry/sdk-trace-base';