@amplitude/ai 0.2.1 → 0.3.0

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.
Files changed (104) hide show
  1. package/.claude/commands/instrument-with-amplitude-ai.md +12 -0
  2. package/.cursor/skills/instrument-with-amplitude-ai/SKILL.md +4 -42
  3. package/AGENTS.md +86 -28
  4. package/README.md +190 -111
  5. package/amplitude-ai.md +463 -0
  6. package/bin/amplitude-ai-doctor.mjs +0 -0
  7. package/bin/amplitude-ai-instrument.mjs +0 -0
  8. package/bin/amplitude-ai-mcp.mjs +0 -0
  9. package/bin/amplitude-ai-register-catalog.mjs +0 -0
  10. package/bin/amplitude-ai-status.mjs +0 -0
  11. package/bin/amplitude-ai.mjs +14 -5
  12. package/data/agent_event_catalog.json +52 -2
  13. package/dist/bound-agent.d.ts +18 -14
  14. package/dist/bound-agent.d.ts.map +1 -1
  15. package/dist/bound-agent.js +4 -1
  16. package/dist/bound-agent.js.map +1 -1
  17. package/dist/cli/status.d.ts.map +1 -1
  18. package/dist/cli/status.js +31 -19
  19. package/dist/cli/status.js.map +1 -1
  20. package/dist/client.d.ts +14 -14
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +38 -0
  23. package/dist/client.js.map +1 -1
  24. package/dist/context.d.ts +5 -0
  25. package/dist/context.d.ts.map +1 -1
  26. package/dist/context.js +4 -0
  27. package/dist/context.js.map +1 -1
  28. package/dist/core/constants.d.ts +3 -1
  29. package/dist/core/constants.d.ts.map +1 -1
  30. package/dist/core/constants.js +3 -1
  31. package/dist/core/constants.js.map +1 -1
  32. package/dist/core/tracking.d.ts +12 -2
  33. package/dist/core/tracking.d.ts.map +1 -1
  34. package/dist/core/tracking.js +13 -2
  35. package/dist/core/tracking.js.map +1 -1
  36. package/dist/decorators.d.ts +1 -1
  37. package/dist/decorators.d.ts.map +1 -1
  38. package/dist/decorators.js +4 -3
  39. package/dist/decorators.js.map +1 -1
  40. package/dist/index.d.ts +7 -4
  41. package/dist/index.js +5 -2
  42. package/dist/mcp/contract.d.ts +4 -0
  43. package/dist/mcp/contract.d.ts.map +1 -1
  44. package/dist/mcp/contract.js +6 -2
  45. package/dist/mcp/contract.js.map +1 -1
  46. package/dist/mcp/generate-verify-test.d.ts +7 -0
  47. package/dist/mcp/generate-verify-test.d.ts.map +1 -0
  48. package/dist/mcp/generate-verify-test.js +25 -0
  49. package/dist/mcp/generate-verify-test.js.map +1 -0
  50. package/dist/mcp/index.d.ts +2 -1
  51. package/dist/mcp/index.js +2 -1
  52. package/dist/mcp/instrument-file.d.ts +14 -0
  53. package/dist/mcp/instrument-file.d.ts.map +1 -0
  54. package/dist/mcp/instrument-file.js +139 -0
  55. package/dist/mcp/instrument-file.js.map +1 -0
  56. package/dist/mcp/scan-project.d.ts +52 -0
  57. package/dist/mcp/scan-project.d.ts.map +1 -0
  58. package/dist/mcp/scan-project.js +309 -0
  59. package/dist/mcp/scan-project.js.map +1 -0
  60. package/dist/mcp/server.d.ts.map +1 -1
  61. package/dist/mcp/server.js +79 -4
  62. package/dist/mcp/server.js.map +1 -1
  63. package/dist/mcp/validate-file.d.ts +4 -0
  64. package/dist/mcp/validate-file.d.ts.map +1 -1
  65. package/dist/mcp/validate-file.js +559 -11
  66. package/dist/mcp/validate-file.js.map +1 -1
  67. package/dist/middleware.js +2 -1
  68. package/dist/middleware.js.map +1 -1
  69. package/dist/node_modules/.pnpm/acorn-typescript@1.4.13_acorn@8.16.0/node_modules/acorn-typescript/lib/index.js +2389 -0
  70. package/dist/node_modules/.pnpm/acorn-typescript@1.4.13_acorn@8.16.0/node_modules/acorn-typescript/lib/index.js.map +1 -0
  71. package/dist/node_modules/.pnpm/acorn@8.16.0/node_modules/acorn/dist/acorn.js +5128 -0
  72. package/dist/node_modules/.pnpm/acorn@8.16.0/node_modules/acorn/dist/acorn.js.map +1 -0
  73. package/dist/node_modules/.pnpm/zod@3.25.76/node_modules/zod/v3/types.js +1 -1
  74. package/dist/patching.d.ts.map +1 -1
  75. package/dist/providers/anthropic.d.ts.map +1 -1
  76. package/dist/providers/anthropic.js +1 -0
  77. package/dist/providers/anthropic.js.map +1 -1
  78. package/dist/providers/base.d.ts +2 -1
  79. package/dist/providers/base.d.ts.map +1 -1
  80. package/dist/providers/base.js +4 -0
  81. package/dist/providers/base.js.map +1 -1
  82. package/dist/providers/openai.d.ts.map +1 -1
  83. package/dist/providers/openai.js +2 -0
  84. package/dist/providers/openai.js.map +1 -1
  85. package/dist/serverless.d.ts +19 -0
  86. package/dist/serverless.d.ts.map +1 -0
  87. package/dist/serverless.js +35 -0
  88. package/dist/serverless.js.map +1 -0
  89. package/dist/session.d.ts +24 -8
  90. package/dist/session.d.ts.map +1 -1
  91. package/dist/session.js +20 -1
  92. package/dist/session.js.map +1 -1
  93. package/dist/types.d.ts +1 -0
  94. package/dist/types.d.ts.map +1 -1
  95. package/dist/types.js.map +1 -1
  96. package/llms-full.txt +353 -69
  97. package/llms.txt +6 -2
  98. package/mcp.schema.json +7 -3
  99. package/package.json +10 -5
  100. package/bin/amplitude-ai-init.mjs +0 -27
  101. package/dist/cli/init.d.ts +0 -14
  102. package/dist/cli/init.d.ts.map +0 -1
  103. package/dist/cli/init.js +0 -40
  104. package/dist/cli/init.js.map +0 -1
@@ -3156,5 +3156,5 @@ const preprocessType = ZodEffects.createWithPreprocess;
3156
3156
  const pipelineType = ZodPipeline.create;
3157
3157
 
3158
3158
  //#endregion
3159
- export { ZodFirstPartyTypeKind, ZodOptional, enumType, numberType, objectType, stringType };
3159
+ export { ZodFirstPartyTypeKind, ZodOptional, arrayType, enumType, numberType, objectType, stringType };
3160
3160
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"patching.d.ts","names":[],"sources":["../src/patching.ts"],"sourcesContent":[],"mappings":";;;;AAoLgB,iBAjJA,gBAAA,CAAA,CAkJD,EAAW,MAAA,EAAA;AAuHV,iBApNA,WAAA,CAqND,OAAA,EAAW;EA6CV,WAAA,EAjQD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c,CA/TN,iBA+TM,GA/Tc,aA+Td,CAAA,OAAA,CAAA,CAAA;EAAN,QAAA,WAAA;EAAK,QAAA,mBAAA;;;iBAxBF,4BAAA;iBAmBA,uBAAA,UACL,MAAM;;;aAIJ,MAAM"}
@@ -223,6 +223,7 @@ var WrappedMessages = class {
223
223
  sessionId: ctx.sessionId,
224
224
  traceId: ctx.traceId,
225
225
  turnId: ctx.turnId ?? void 0,
226
+ messageSource: ctx.parentAgentId ? "agent" : "user",
226
227
  agentId: ctx.agentId,
227
228
  parentAgentId: ctx.parentAgentId,
228
229
  customerOrgId: ctx.customerOrgId,
@@ -1 +1 @@
1
- {"version":3,"file":"anthropic.js","names":["_AnthropicModule: Record<string, unknown> | null","clientOpts: Record<string, unknown>","costUsd: number | null","reasoning: string | undefined","toolCalls: Array<Record<string, unknown>>"],"sources":["../../src/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic provider wrapper with automatic tracking.\n */\n\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport { trackUserMessage } from '../core/tracking.js';\nimport { getDefaultPropagateContext, injectContext } from '../propagation.js';\nimport type {\n AmplitudeLike,\n AmplitudeOrAI,\n AnthropicResponse,\n TrackFn,\n} from '../types.js';\nimport { calculateCost } from '../utils/costs.js';\nimport { tryRequire } from '../utils/resolve-module.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\nimport {\n applySessionContext,\n BaseAIProvider,\n contextFields,\n type ProviderTrackOptions,\n} from './base.js';\n\nconst _resolved = tryRequire('@anthropic-ai/sdk');\nexport const ANTHROPIC_AVAILABLE = _resolved != null;\nconst _AnthropicModule: Record<string, unknown> | null = _resolved;\n\nexport { _AnthropicModule };\n\nexport interface AnthropicOptions {\n amplitude: AmplitudeOrAI;\n apiKey?: string;\n privacyConfig?: PrivacyConfig | null;\n propagateContext?: boolean;\n /** Pass the `@anthropic-ai/sdk` module directly to bypass `tryRequire` (required in bundler environments). */\n anthropicModule?: unknown;\n}\n\nexport class Anthropic<\n TClient extends Record<string, unknown> = Record<string, unknown>,\n> extends BaseAIProvider {\n private _client: TClient;\n readonly messages: WrappedMessages;\n private _propagateContext: boolean;\n\n constructor(options: AnthropicOptions) {\n super({\n amplitude: options.amplitude,\n privacyConfig: options.privacyConfig,\n providerName: 'anthropic',\n });\n\n const mod =\n (options.anthropicModule as Record<string, unknown> | null) ??\n _AnthropicModule;\n if (mod == null) {\n throw new Error(\n '@anthropic-ai/sdk package is required. Install it with: npm install @anthropic-ai/sdk — or pass the module directly via the anthropicModule option.',\n );\n }\n\n const AnthropicSDK = mod.Anthropic as new (\n opts: Record<string, unknown>,\n ) => unknown;\n\n const clientOpts: Record<string, unknown> = {};\n if (options.apiKey) clientOpts.apiKey = options.apiKey;\n\n this._client = new AnthropicSDK(clientOpts) as TClient;\n this._propagateContext =\n options.propagateContext ?? getDefaultPropagateContext();\n this.messages = new WrappedMessages(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n }\n\n get client(): TClient {\n return this._client;\n }\n}\n\nexport class WrappedMessages {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n ) {\n const clientObj = client as Record<string, unknown>;\n this._original = clientObj.messages as Record<string, unknown>;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<AnthropicResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.messages as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n\n const resp = response as AnthropicResponse;\n const usage = resp.usage;\n const extracted = extractAnthropicContent(\n resp.content as unknown as Array<Record<string, unknown>> | undefined,\n );\n const firstTextBlock = resp.content?.find((b) => b.type === 'text');\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n\n const cacheRead = usage?.cache_read_input_tokens ?? 0;\n const cacheCreation = usage?.cache_creation_input_tokens ?? 0;\n const rawInput = usage?.input_tokens ?? 0;\n const normalizedInput =\n cacheRead || cacheCreation\n ? rawInput + cacheRead + cacheCreation\n : rawInput;\n\n let costUsd: number | null = null;\n if (usage?.input_tokens != null && usage?.output_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: normalizedInput,\n outputTokens: usage.output_tokens,\n cacheReadInputTokens: cacheRead,\n cacheCreationInputTokens: cacheCreation,\n defaultProvider: 'anthropic',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: 'anthropic',\n responseContent: String(firstTextBlock?.text ?? ''),\n reasoningContent: extracted.reasoning,\n latencyMs,\n inputTokens: normalizedInput || undefined,\n outputTokens: usage?.output_tokens,\n cacheReadInputTokens: cacheRead || undefined,\n cacheCreationInputTokens: cacheCreation || undefined,\n totalCostUsd: costUsd,\n finishReason: resp.stop_reason,\n toolCalls:\n extracted.toolCalls.length > 0 ? extracted.toolCalls : undefined,\n isStreaming: false,\n systemPrompt: extractAnthropicSystemPrompt(requestParams.system),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as AnthropicResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: 'anthropic',\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n\n throw error;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n let reasoningContent = '';\n\n try {\n for await (const event of stream) {\n const evt = event as Record<string, unknown>;\n const type = evt.type as string | undefined;\n\n if (type === 'content_block_delta') {\n const delta = evt.delta as Record<string, unknown> | undefined;\n if (delta?.type === 'text_delta' && delta.text != null) {\n accumulator.addContent(String(delta.text));\n } else if (\n delta?.type === 'thinking_delta' &&\n delta.thinking != null\n ) {\n reasoningContent += String(delta.thinking);\n }\n } else if (type === 'content_block_start') {\n const block = evt.content_block as\n | Record<string, unknown>\n | undefined;\n if (block?.type === 'tool_use') {\n accumulator.addToolCall({\n type: 'function',\n id: block.id,\n function: {\n name: String(block.name ?? ''),\n arguments:\n typeof block.input === 'string'\n ? block.input\n : JSON.stringify(block.input ?? {}),\n },\n });\n }\n } else if (type === 'message_delta') {\n const delta = evt.delta as Record<string, unknown> | undefined;\n if (delta?.stop_reason != null) {\n accumulator.finishReason = String(delta.stop_reason);\n }\n const usage = evt.usage as Record<string, number> | undefined;\n if (usage != null) {\n accumulator.setUsage({\n outputTokens: usage.output_tokens,\n });\n }\n } else if (type === 'message_start') {\n const message = evt.message as Record<string, unknown> | undefined;\n if (message?.model != null) {\n accumulator.model = String(message.model);\n }\n const usage = message?.usage as Record<string, number> | undefined;\n if (usage != null) {\n accumulator.setUsage({\n inputTokens: usage.input_tokens,\n cacheReadTokens: usage.cache_read_input_tokens,\n cacheCreationTokens: usage.cache_creation_input_tokens,\n });\n }\n }\n\n yield event;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n const modelName = String(accumulator.model ?? params.model ?? 'unknown');\n\n const streamCacheRead = state.cacheReadTokens ?? 0;\n const streamCacheCreation = state.cacheCreationTokens ?? 0;\n const streamRawInput = state.inputTokens ?? 0;\n const streamNormalizedInput =\n streamCacheRead || streamCacheCreation\n ? streamRawInput + streamCacheRead + streamCacheCreation\n : streamRawInput;\n\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: streamNormalizedInput,\n outputTokens: state.outputTokens,\n cacheReadInputTokens: streamCacheRead,\n cacheCreationInputTokens: streamCacheCreation,\n defaultProvider: 'anthropic',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName,\n provider: 'anthropic',\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: streamNormalizedInput || undefined,\n outputTokens: state.outputTokens,\n cacheReadInputTokens: streamCacheRead || undefined,\n cacheCreationInputTokens: streamCacheCreation || undefined,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : undefined,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n reasoningContent: reasoningContent || undefined,\n systemPrompt: extractAnthropicSystemPrompt(params.system),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n messages: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n if (!Array.isArray(messages)) return;\n for (const msg of messages) {\n const role = (msg as Record<string, unknown>)?.role;\n if (role !== 'user') continue;\n const rawContent = (msg as Record<string, unknown>)?.content;\n const content = Array.isArray(rawContent)\n ? rawContent\n .map((part) => {\n if (typeof part === 'string') return part;\n const text = (part as Record<string, unknown>)?.text;\n return typeof text === 'string' ? text : '';\n })\n .join('')\n : typeof rawContent === 'string'\n ? rawContent\n : '';\n if (!content) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: content,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nfunction _isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value != null &&\n typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] ===\n 'function'\n );\n}\n\nexport function extractAnthropicSystemPrompt(\n system: unknown,\n): string | undefined {\n if (typeof system === 'string') return system;\n if (Array.isArray(system)) {\n return system\n .map((block) => {\n if (typeof block === 'string') return block;\n if (typeof block === 'object' && block != null) {\n return String((block as Record<string, unknown>).text ?? '');\n }\n return '';\n })\n .filter(Boolean)\n .join('\\n');\n }\n return undefined;\n}\n\nexport function extractAnthropicContent(\n content: Array<Record<string, unknown>> | undefined,\n): {\n text: string;\n reasoning: string | undefined;\n toolCalls: Array<Record<string, unknown>>;\n} {\n let text = '';\n let reasoning: string | undefined;\n const toolCalls: Array<Record<string, unknown>> = [];\n\n if (!content) return { text, reasoning, toolCalls };\n\n for (const block of content) {\n if (block.type === 'text') {\n text += String(block.text ?? '');\n } else if (block.type === 'thinking') {\n reasoning = String(block.thinking ?? '');\n } else if (block.type === 'tool_use') {\n toolCalls.push({\n type: 'function',\n id: block.id,\n function: {\n name: String(block.name ?? ''),\n arguments:\n typeof block.input === 'string'\n ? block.input\n : JSON.stringify(block.input ?? {}),\n },\n });\n }\n }\n\n return { text, reasoning, toolCalls };\n}\n"],"mappings":";;;;;;;;AAuBA,MAAM,YAAY,WAAW,oBAAoB;AACjD,MAAa,sBAAsB,aAAa;AAChD,MAAMA,mBAAmD;AAazD,IAAa,YAAb,cAEU,eAAe;CACvB,AAAQ;CACR,AAAS;CACT,AAAQ;CAER,YAAY,SAA2B;AACrC,QAAM;GACJ,WAAW,QAAQ;GACnB,eAAe,QAAQ;GACvB,cAAc;GACf,CAAC;EAEF,MAAM,MACH,QAAQ,mBACT;AACF,MAAI,OAAO,KACT,OAAM,IAAI,MACR,sJACD;EAGH,MAAM,eAAe,IAAI;EAIzB,MAAMC,aAAsC,EAAE;AAC9C,MAAI,QAAQ,OAAQ,YAAW,SAAS,QAAQ;AAEhD,OAAK,UAAU,IAAI,aAAa,WAAW;AAC3C,OAAK,oBACH,QAAQ,oBAAoB,4BAA4B;AAC1D,OAAK,WAAW,IAAI,gBAClB,KAAK,SACL,KAAK,SAAS,EACd,KAAK,YACL,KAAK,gBACL,KAAK,kBACN;;CAGH,IAAI,SAAkB;AACpB,SAAO,KAAK;;;AAIhB,IAAa,kBAAb,MAA6B;CAC3B;CACA,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,QACA,SACA,WACA,eACA,kBACA;AAEA,OAAK,YADa,OACS;AAC3B,OAAK,WACH,OAAO,YAAY,aACf,UACC,QAA8C,SAAS;AAC9D,OAAK,aAAa;AAClB,OAAK,iBAAiB;AACtB,OAAK,oBAAoB;;CAG3B,MAAM,OACJ,QACA,oBACqD;EACrD,MAAM,WAAW,KAAK,UAAU;EAGhC,MAAM,YAAY,YAAY,KAA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CACf,KAAK,KAAK;;AAKjB,SAAgB,wBACd,SAKA;CACA,IAAI,OAAO;CACX,IAAIC;CACJ,MAAMC,YAA4C,EAAE;AAEpD,KAAI,CAAC,QAAS,QAAO;EAAE;EAAM;EAAW;EAAW;AAEnD,MAAK,MAAM,SAAS,QAClB,KAAI,MAAM,SAAS,OACjB,SAAQ,OAAO,MAAM,QAAQ,GAAG;UACvB,MAAM,SAAS,WACxB,aAAY,OAAO,MAAM,YAAY,GAAG;UAC/B,MAAM,SAAS,WACxB,WAAU,KAAK;EACb,MAAM;EACN,IAAI,MAAM;EACV,UAAU;GACR,MAAM,OAAO,MAAM,QAAQ,GAAG;GAC9B,WACE,OAAO,MAAM,UAAU,WACnB,MAAM,QACN,KAAK,UAAU,MAAM,SAAS,EAAE,CAAC;GACxC;EACF,CAAC;AAIN,QAAO;EAAE;EAAM;EAAW;EAAW"}
1
+ {"version":3,"file":"anthropic.js","names":["_AnthropicModule: Record<string, unknown> | null","clientOpts: Record<string, unknown>","costUsd: number | null","reasoning: string | undefined","toolCalls: Array<Record<string, unknown>>"],"sources":["../../src/providers/anthropic.ts"],"sourcesContent":["/**\n * Anthropic provider wrapper with automatic tracking.\n */\n\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport { trackUserMessage } from '../core/tracking.js';\nimport { getDefaultPropagateContext, injectContext } from '../propagation.js';\nimport type {\n AmplitudeLike,\n AmplitudeOrAI,\n AnthropicResponse,\n TrackFn,\n} from '../types.js';\nimport { calculateCost } from '../utils/costs.js';\nimport { tryRequire } from '../utils/resolve-module.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\nimport {\n applySessionContext,\n BaseAIProvider,\n contextFields,\n type ProviderTrackOptions,\n} from './base.js';\n\nconst _resolved = tryRequire('@anthropic-ai/sdk');\nexport const ANTHROPIC_AVAILABLE = _resolved != null;\nconst _AnthropicModule: Record<string, unknown> | null = _resolved;\n\nexport { _AnthropicModule };\n\nexport interface AnthropicOptions {\n amplitude: AmplitudeOrAI;\n apiKey?: string;\n privacyConfig?: PrivacyConfig | null;\n propagateContext?: boolean;\n /** Pass the `@anthropic-ai/sdk` module directly to bypass `tryRequire` (required in bundler environments). */\n anthropicModule?: unknown;\n}\n\nexport class Anthropic<\n TClient extends Record<string, unknown> = Record<string, unknown>,\n> extends BaseAIProvider {\n private _client: TClient;\n readonly messages: WrappedMessages;\n private _propagateContext: boolean;\n\n constructor(options: AnthropicOptions) {\n super({\n amplitude: options.amplitude,\n privacyConfig: options.privacyConfig,\n providerName: 'anthropic',\n });\n\n const mod =\n (options.anthropicModule as Record<string, unknown> | null) ??\n _AnthropicModule;\n if (mod == null) {\n throw new Error(\n '@anthropic-ai/sdk package is required. Install it with: npm install @anthropic-ai/sdk — or pass the module directly via the anthropicModule option.',\n );\n }\n\n const AnthropicSDK = mod.Anthropic as new (\n opts: Record<string, unknown>,\n ) => unknown;\n\n const clientOpts: Record<string, unknown> = {};\n if (options.apiKey) clientOpts.apiKey = options.apiKey;\n\n this._client = new AnthropicSDK(clientOpts) as TClient;\n this._propagateContext =\n options.propagateContext ?? getDefaultPropagateContext();\n this.messages = new WrappedMessages(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n }\n\n get client(): TClient {\n return this._client;\n }\n}\n\nexport class WrappedMessages {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n ) {\n const clientObj = client as Record<string, unknown>;\n this._original = clientObj.messages as Record<string, unknown>;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<AnthropicResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.messages as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n\n const resp = response as AnthropicResponse;\n const usage = resp.usage;\n const extracted = extractAnthropicContent(\n resp.content as unknown as Array<Record<string, unknown>> | undefined,\n );\n const firstTextBlock = resp.content?.find((b) => b.type === 'text');\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n\n const cacheRead = usage?.cache_read_input_tokens ?? 0;\n const cacheCreation = usage?.cache_creation_input_tokens ?? 0;\n const rawInput = usage?.input_tokens ?? 0;\n const normalizedInput =\n cacheRead || cacheCreation\n ? rawInput + cacheRead + cacheCreation\n : rawInput;\n\n let costUsd: number | null = null;\n if (usage?.input_tokens != null && usage?.output_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: normalizedInput,\n outputTokens: usage.output_tokens,\n cacheReadInputTokens: cacheRead,\n cacheCreationInputTokens: cacheCreation,\n defaultProvider: 'anthropic',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: 'anthropic',\n responseContent: String(firstTextBlock?.text ?? ''),\n reasoningContent: extracted.reasoning,\n latencyMs,\n inputTokens: normalizedInput || undefined,\n outputTokens: usage?.output_tokens,\n cacheReadInputTokens: cacheRead || undefined,\n cacheCreationInputTokens: cacheCreation || undefined,\n totalCostUsd: costUsd,\n finishReason: resp.stop_reason,\n toolCalls:\n extracted.toolCalls.length > 0 ? extracted.toolCalls : undefined,\n isStreaming: false,\n systemPrompt: extractAnthropicSystemPrompt(requestParams.system),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as AnthropicResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: 'anthropic',\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n\n throw error;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n let reasoningContent = '';\n\n try {\n for await (const event of stream) {\n const evt = event as Record<string, unknown>;\n const type = evt.type as string | undefined;\n\n if (type === 'content_block_delta') {\n const delta = evt.delta as Record<string, unknown> | undefined;\n if (delta?.type === 'text_delta' && delta.text != null) {\n accumulator.addContent(String(delta.text));\n } else if (\n delta?.type === 'thinking_delta' &&\n delta.thinking != null\n ) {\n reasoningContent += String(delta.thinking);\n }\n } else if (type === 'content_block_start') {\n const block = evt.content_block as\n | Record<string, unknown>\n | undefined;\n if (block?.type === 'tool_use') {\n accumulator.addToolCall({\n type: 'function',\n id: block.id,\n function: {\n name: String(block.name ?? ''),\n arguments:\n typeof block.input === 'string'\n ? block.input\n : JSON.stringify(block.input ?? {}),\n },\n });\n }\n } else if (type === 'message_delta') {\n const delta = evt.delta as Record<string, unknown> | undefined;\n if (delta?.stop_reason != null) {\n accumulator.finishReason = String(delta.stop_reason);\n }\n const usage = evt.usage as Record<string, number> | undefined;\n if (usage != null) {\n accumulator.setUsage({\n outputTokens: usage.output_tokens,\n });\n }\n } else if (type === 'message_start') {\n const message = evt.message as Record<string, unknown> | undefined;\n if (message?.model != null) {\n accumulator.model = String(message.model);\n }\n const usage = message?.usage as Record<string, number> | undefined;\n if (usage != null) {\n accumulator.setUsage({\n inputTokens: usage.input_tokens,\n cacheReadTokens: usage.cache_read_input_tokens,\n cacheCreationTokens: usage.cache_creation_input_tokens,\n });\n }\n }\n\n yield event;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n const modelName = String(accumulator.model ?? params.model ?? 'unknown');\n\n const streamCacheRead = state.cacheReadTokens ?? 0;\n const streamCacheCreation = state.cacheCreationTokens ?? 0;\n const streamRawInput = state.inputTokens ?? 0;\n const streamNormalizedInput =\n streamCacheRead || streamCacheCreation\n ? streamRawInput + streamCacheRead + streamCacheCreation\n : streamRawInput;\n\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: streamNormalizedInput,\n outputTokens: state.outputTokens,\n cacheReadInputTokens: streamCacheRead,\n cacheCreationInputTokens: streamCacheCreation,\n defaultProvider: 'anthropic',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName,\n provider: 'anthropic',\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: streamNormalizedInput || undefined,\n outputTokens: state.outputTokens,\n cacheReadInputTokens: streamCacheRead || undefined,\n cacheCreationInputTokens: streamCacheCreation || undefined,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : undefined,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n reasoningContent: reasoningContent || undefined,\n systemPrompt: extractAnthropicSystemPrompt(params.system),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n messages: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n if (!Array.isArray(messages)) return;\n for (const msg of messages) {\n const role = (msg as Record<string, unknown>)?.role;\n if (role !== 'user') continue;\n const rawContent = (msg as Record<string, unknown>)?.content;\n const content = Array.isArray(rawContent)\n ? rawContent\n .map((part) => {\n if (typeof part === 'string') return part;\n const text = (part as Record<string, unknown>)?.text;\n return typeof text === 'string' ? text : '';\n })\n .join('')\n : typeof rawContent === 'string'\n ? rawContent\n : '';\n if (!content) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: content,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n messageSource: ctx.parentAgentId ? 'agent' : 'user',\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nfunction _isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value != null &&\n typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] ===\n 'function'\n );\n}\n\nexport function extractAnthropicSystemPrompt(\n system: unknown,\n): string | undefined {\n if (typeof system === 'string') return system;\n if (Array.isArray(system)) {\n return system\n .map((block) => {\n if (typeof block === 'string') return block;\n if (typeof block === 'object' && block != null) {\n return String((block as Record<string, unknown>).text ?? '');\n }\n return '';\n })\n .filter(Boolean)\n .join('\\n');\n }\n return undefined;\n}\n\nexport function extractAnthropicContent(\n content: Array<Record<string, unknown>> | undefined,\n): {\n text: string;\n reasoning: string | undefined;\n toolCalls: Array<Record<string, unknown>>;\n} {\n let text = '';\n let reasoning: string | undefined;\n const toolCalls: Array<Record<string, unknown>> = [];\n\n if (!content) return { text, reasoning, toolCalls };\n\n for (const block of content) {\n if (block.type === 'text') {\n text += String(block.text ?? '');\n } else if (block.type === 'thinking') {\n reasoning = String(block.thinking ?? '');\n } else if (block.type === 'tool_use') {\n toolCalls.push({\n type: 'function',\n id: block.id,\n function: {\n name: String(block.name ?? ''),\n arguments:\n typeof block.input === 'string'\n ? block.input\n : JSON.stringify(block.input ?? {}),\n },\n });\n }\n }\n\n return { text, reasoning, toolCalls };\n}\n"],"mappings":";;;;;;;;AAuBA,MAAM,YAAY,WAAW,oBAAoB;AACjD,MAAa,sBAAsB,aAAa;AAChD,MAAMA,mBAAmD;AAazD,IAAa,YAAb,cAEU,eAAe;CACvB,AAAQ;CACR,AAAS;CACT,AAAQ;CAER,YAAY,SAA2B;AACrC,QAAM;GACJ,WAAW,QAAQ;GACnB,eAAe,QAAQ;GACvB,cAAc;GACf,CAAC;EAEF,MAAM,MACH,QAAQ,mBACT;AACF,MAAI,OAAO,KACT,OAAM,IAAI,MACR,sJACD;EAGH,MAAM,eAAe,IAAI;EAIzB,MAAMC,aAAsC,EAAE;AAC9C,MAAI,QAAQ,OAAQ,YAAW,SAAS,QAAQ;AAEhD,OAAK,UAAU,IAAI,aAAa,WAAW;AAC3C,OAAK,oBACH,QAAQ,oBAAoB,4BAA4B;AAC1D,OAAK,WAAW,IAAI,gBAClB,KAAK,SACL,KAAK,SAAS,EACd,KAAK,YACL,KAAK,gBACL,KAAK,kBACN;;CAGH,IAAI,SAAkB;AACpB,SAAO,KAAK;;;AAIhB,IAAa,kBAAb,MAA6B;CAC3B;CACA,AAAQ;CACR,AAAQ;CACR,AAAQ;CACR,AAAQ;CAER,YACE,QACA,SACA,WACA,eACA,kBACA;AAEA,OAAK,YADa,OACS;AAC3B,OAAK,WACH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,SAAU,QAAO;AACvC,KAAI,MAAM,QAAQ,OAAO,CACvB,QAAO,OACJ,KAAK,UAAU;AACd,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,OAAO,UAAU,YAAY,SAAS,KACxC,QAAO,OAAQ,MAAkC,QAAQ,GAAG;AAE9D,SAAO;GACP,CACD,OAAO,QAAQ,CACf,KAAK,KAAK;;AAKjB,SAAgB,wBACd,SAKA;CACA,IAAI,OAAO;CACX,IAAIC;CACJ,MAAMC,YAA4C,EAAE;AAEpD,KAAI,CAAC,QAAS,QAAO;EAAE;EAAM;EAAW;EAAW;AAEnD,MAAK,MAAM,SAAS,QAClB,KAAI,MAAM,SAAS,OACjB,SAAQ,OAAO,MAAM,QAAQ,GAAG;UACvB,MAAM,SAAS,WACxB,aAAY,OAAO,MAAM,YAAY,GAAG;UAC/B,MAAM,SAAS,WACxB,WAAU,KAAK;EACb,MAAM;EACN,IAAI,MAAM;EACV,UAAU;GACR,MAAM,OAAO,MAAM,QAAQ,GAAG;GAC9B,WACE,OAAO,MAAM,UAAU,WACnB,MAAM,QACN,KAAK,UAAU,MAAM,SAAS,EAAE,CAAC;GACxC;EACF,CAAC;AAIN,QAAO;EAAE;EAAM;EAAW;EAAW"}
@@ -23,6 +23,7 @@ interface ProviderTrackOptions {
23
23
  parentAgentId?: string | null;
24
24
  customerOrgId?: string | null;
25
25
  agentVersion?: string | null;
26
+ description?: string | null;
26
27
  context?: Record<string, unknown> | null;
27
28
  env?: string | null;
28
29
  groups?: Record<string, unknown> | null;
@@ -46,7 +47,7 @@ declare function applySessionContext(overrides?: ProviderTrackOptions): Provider
46
47
  * flat object suitable for spreading into _trackFn() / _track() calls.
47
48
  * Ensures all 13 context fields propagate consistently.
48
49
  */
49
- type TrackContextFields = Pick<TrackCallOptions, 'userId' | 'sessionId' | 'traceId' | 'turnId' | 'agentId' | 'parentAgentId' | 'customerOrgId' | 'agentVersion' | 'context' | 'env' | 'groups' | 'eventProperties'>;
50
+ type TrackContextFields = Pick<TrackCallOptions, 'userId' | 'sessionId' | 'traceId' | 'turnId' | 'agentId' | 'parentAgentId' | 'customerOrgId' | 'agentVersion' | 'description' | 'context' | 'env' | 'groups' | 'eventProperties'>;
50
51
  declare function contextFields(ctx: ProviderTrackOptions): TrackContextFields;
51
52
  declare abstract class BaseAIProvider {
52
53
  protected _amplitude: AmplitudeLike;
@@ -1 +1 @@
1
- {"version":3,"file":"base.d.ts","names":[],"sources":["../../src/providers/base.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AA2DA;AAgDA;AAgBA;AAiBA;;;;AAOoB,UAjHH,oBAAA,CAiHG;EAQU,MAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAL,SAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAmCZ,OAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAKe,MAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAsB,OAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAKrC,aAAA,CAAA,EAAA,MAAA,GAAsB,IAAA;EAEX,aAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAIA,YAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAeK,OAAA,CAAA,EAlLjB,MAkLiB,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAAX,GAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAQM,MAAA,CAAA,EAxLb,MAwLa,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAIF,eAAA,CAAA,EA3LF,MA2LE,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAAyB;;;;;;;;;;;iBA9K/B,mBAAA,aACH,uBACV;;;;;;;;KA8CS,kBAAA,GAAqB,KAC/B;iBAec,aAAA,MAAmB,uBAAuB;uBAiBpC,cAAA;wBACE;4BACI;;;eAIb;oBACK;;;yBAQK,KAAK;aAmCjB;4BAKe;;cAKf,sBAAA;;wBAEW;;;wBAIA;;;kBAeN,WAAW;;wBAQL;uBAIF"}
1
+ {"version":3,"file":"base.d.ts","names":[],"sources":["../../src/providers/base.ts"],"sourcesContent":[],"mappings":";;;;;;;;;AA4DA;AAiDA;AAiBA;AAkBA;;;;AAOoB,UArHH,oBAAA,CAqHG;EAQU,MAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAL,SAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAqCZ,OAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAKe,MAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAsB,OAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAKrC,aAAA,CAAA,EAAA,MAAA,GAAsB,IAAA;EAEX,aAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAIA,YAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAeK,WAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAAX,OAAA,CAAA,EAvLN,MAuLM,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAQM,GAAA,CAAA,EAAA,MAAA,GAAA,IAAA;EAIF,MAAA,CAAA,EAjMX,MAiMW,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;EAAyB,eAAA,CAAA,EAhM3B,MAgM2B,CAAA,MAAA,EAAA,OAAA,CAAA,GAAA,IAAA;;;;;;;;;;;;iBAnL/B,mBAAA,aACH,uBACV;;;;;;;;KA+CS,kBAAA,GAAqB,KAC/B;iBAgBc,aAAA,MAAmB,uBAAuB;uBAkBpC,cAAA;wBACE;4BACI;;;eAIb;oBACK;;;yBAQK,KAAK;aAqCjB;4BAKe;;cAKf,sBAAA;;wBAEW;;;wBAIA;;;kBAeN,WAAW;;wBAQL;uBAIF"}
@@ -26,6 +26,7 @@ function applySessionContext(overrides = {}) {
26
26
  if (!result.parentAgentId) result.parentAgentId = ctx.parentAgentId;
27
27
  if (!result.customerOrgId) result.customerOrgId = ctx.customerOrgId;
28
28
  if (!result.agentVersion) result.agentVersion = ctx.agentVersion;
29
+ if (!result.description) result.description = ctx.description;
29
30
  if (!result.context) result.context = ctx.context;
30
31
  if (!result.env) result.env = ctx.env;
31
32
  if (!result.groups) result.groups = ctx.groups;
@@ -51,6 +52,7 @@ function contextFields(ctx) {
51
52
  parentAgentId: ctx.parentAgentId,
52
53
  customerOrgId: ctx.customerOrgId,
53
54
  agentVersion: ctx.agentVersion,
55
+ description: ctx.description,
54
56
  context: ctx.context,
55
57
  env: ctx.env,
56
58
  groups: ctx.groups,
@@ -76,6 +78,7 @@ var BaseAIProvider = class {
76
78
  parentAgentId: opts.parentAgentId,
77
79
  customerOrgId: opts.customerOrgId,
78
80
  agentVersion: opts.agentVersion,
81
+ description: opts.description,
79
82
  context: opts.context,
80
83
  env: opts.env,
81
84
  groups: opts.groups,
@@ -92,6 +95,7 @@ var BaseAIProvider = class {
92
95
  parentAgentId: merged.parentAgentId ?? opts.parentAgentId,
93
96
  customerOrgId: merged.customerOrgId ?? opts.customerOrgId,
94
97
  agentVersion: merged.agentVersion ?? opts.agentVersion,
98
+ description: merged.description ?? opts.description,
95
99
  context: merged.context ?? opts.context,
96
100
  env: merged.env ?? opts.env,
97
101
  groups: merged.groups ?? opts.groups,
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":["result: Record<string, unknown>"],"sources":["../../src/providers/base.ts"],"sourcesContent":["/**\n * Base class for AI provider wrappers.\n *\n * Provides shared tracking logic and session context integration.\n */\n\nimport { getActiveContext } from '../context.js';\nimport {\n PROP_IDLE_TIMEOUT_MINUTES,\n PROP_SESSION_REPLAY_ID,\n} from '../core/constants.js';\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport {\n trackAiMessage,\n type TrackAiMessageOptions,\n} from '../core/tracking.js';\nimport {\n resolveAmplitude,\n type AmplitudeLike,\n type AmplitudeOrAI,\n type TrackCallOptions,\n type TrackFn,\n} from '../types.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\n\n/**\n * Per-call context overrides for provider wrappers.\n *\n * Pass as the second argument to wrapped provider methods\n * (e.g., `openai.chat.completions.create(params, overrides)`)\n * to set Amplitude tracking context for that specific call.\n * Any fields left `null`/`undefined` are filled from the\n * active `SessionContext` via `AsyncLocalStorage`.\n */\nexport interface ProviderTrackOptions {\n userId?: string | null;\n sessionId?: string | null;\n traceId?: string | null;\n turnId?: number | null;\n agentId?: string | null;\n parentAgentId?: string | null;\n customerOrgId?: string | null;\n agentVersion?: string | null;\n context?: Record<string, unknown> | null;\n env?: string | null;\n groups?: Record<string, unknown> | null;\n eventProperties?: Record<string, unknown> | null;\n /**\n * Controls whether provider wrappers auto-track user input payloads.\n * Set to false when you already call `trackUserMessage()` explicitly.\n */\n trackInputMessages?: boolean;\n}\n\n/**\n * Apply session context fields from AsyncLocalStorage to tracking options.\n * Returns a merged set of fields with explicit values taking precedence.\n * Also injects idle_timeout_minutes and session_replay_id from the context.\n */\nexport function applySessionContext(\n overrides: ProviderTrackOptions = {},\n): ProviderTrackOptions & { userId: string } {\n const ctx = getActiveContext();\n const result: Record<string, unknown> = { ...overrides };\n\n if (ctx != null) {\n if (!result.userId) result.userId = ctx.userId;\n if (!result.sessionId) result.sessionId = ctx.sessionId;\n if (!result.traceId) result.traceId = ctx.traceId;\n if (!result.agentId) result.agentId = ctx.agentId;\n if (!result.parentAgentId) result.parentAgentId = ctx.parentAgentId;\n if (!result.customerOrgId) result.customerOrgId = ctx.customerOrgId;\n if (!result.agentVersion) result.agentVersion = ctx.agentVersion;\n if (!result.context) result.context = ctx.context;\n if (!result.env) result.env = ctx.env;\n if (!result.groups) result.groups = ctx.groups;\n\n if (result.turnId == null) {\n const turnId = ctx.nextTurnId();\n if (turnId != null) result.turnId = turnId;\n }\n\n const existingEp = result.eventProperties as Record<string, unknown> | null;\n const ep = existingEp != null ? { ...existingEp } : {};\n if (ctx.idleTimeoutMinutes != null && !(PROP_IDLE_TIMEOUT_MINUTES in ep)) {\n ep[PROP_IDLE_TIMEOUT_MINUTES] = ctx.idleTimeoutMinutes;\n }\n if (\n ctx.deviceId &&\n ctx.browserSessionId &&\n !(PROP_SESSION_REPLAY_ID in ep)\n ) {\n ep[PROP_SESSION_REPLAY_ID] = `${ctx.deviceId}/${ctx.browserSessionId}`;\n }\n if (Object.keys(ep).length > 0) {\n result.eventProperties = ep;\n }\n }\n\n return result as unknown as ProviderTrackOptions & { userId: string };\n}\n\n/**\n * Extract all context fields from a resolved ProviderTrackOptions into a\n * flat object suitable for spreading into _trackFn() / _track() calls.\n * Ensures all 13 context fields propagate consistently.\n */\nexport type TrackContextFields = Pick<\n TrackCallOptions,\n | 'userId'\n | 'sessionId'\n | 'traceId'\n | 'turnId'\n | 'agentId'\n | 'parentAgentId'\n | 'customerOrgId'\n | 'agentVersion'\n | 'context'\n | 'env'\n | 'groups'\n | 'eventProperties'\n>;\n\nexport function contextFields(ctx: ProviderTrackOptions): TrackContextFields {\n return {\n userId: ctx.userId ?? 'unknown',\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n };\n}\n\nexport abstract class BaseAIProvider {\n protected _amplitude: AmplitudeLike;\n protected _privacyConfig: PrivacyConfig | null;\n readonly _providerName: string;\n\n constructor(options: {\n amplitude: AmplitudeOrAI;\n privacyConfig?: PrivacyConfig | null;\n providerName: string;\n }) {\n this._amplitude = resolveAmplitude(options.amplitude);\n this._privacyConfig = options.privacyConfig ?? null;\n this._providerName = options.providerName;\n }\n\n protected _track(opts: Omit<TrackAiMessageOptions, 'amplitude'>): string {\n const merged = applySessionContext({\n userId: opts.userId,\n sessionId: opts.sessionId,\n traceId: opts.traceId,\n turnId: opts.turnId,\n agentId: opts.agentId,\n parentAgentId: opts.parentAgentId,\n customerOrgId: opts.customerOrgId,\n agentVersion: opts.agentVersion,\n context: opts.context,\n env: opts.env,\n groups: opts.groups,\n eventProperties: opts.eventProperties,\n });\n\n return trackAiMessage({\n ...opts,\n amplitude: this._amplitude,\n userId: merged.userId ?? opts.userId,\n sessionId: merged.sessionId ?? opts.sessionId,\n traceId: merged.traceId ?? opts.traceId,\n turnId: merged.turnId ?? opts.turnId,\n agentId: merged.agentId ?? opts.agentId,\n parentAgentId: merged.parentAgentId ?? opts.parentAgentId,\n customerOrgId: merged.customerOrgId ?? opts.customerOrgId,\n agentVersion: merged.agentVersion ?? opts.agentVersion,\n context: merged.context ?? opts.context,\n env: merged.env ?? opts.env,\n groups: merged.groups ?? opts.groups,\n eventProperties: merged.eventProperties ?? opts.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n\n trackFn(): TrackFn {\n return (opts: TrackCallOptions) =>\n this._track(opts as Omit<TrackAiMessageOptions, 'amplitude'>);\n }\n\n createStreamingTracker(): SimpleStreamingTracker {\n return new SimpleStreamingTracker(this);\n }\n}\n\nexport class SimpleStreamingTracker {\n private _trackFn: TrackFn;\n readonly accumulator: StreamingAccumulator;\n private _modelName = 'unknown';\n private _providerName: string;\n\n constructor(provider: BaseAIProvider) {\n this._trackFn = provider.trackFn();\n this._providerName = provider._providerName;\n this.accumulator = new StreamingAccumulator();\n }\n\n setModel(model: string): void {\n this._modelName = model;\n this.accumulator.model = model;\n }\n\n addContent(chunk: string): void {\n this.accumulator.addContent(chunk);\n }\n\n setUsage(usage: Parameters<StreamingAccumulator['setUsage']>[0]): void {\n this.accumulator.setUsage(usage);\n }\n\n setFinishReason(reason: string): void {\n this.accumulator.finishReason = reason;\n }\n\n addToolCall(toolCall: Record<string, unknown>): void {\n this.accumulator.addToolCall(toolCall);\n }\n\n finalize(overrides: ProviderTrackOptions = {}): string {\n const state = this.accumulator.getState();\n\n return this._trackFn({\n ...contextFields(overrides),\n modelName: this._modelName,\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: this.accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n cacheReadInputTokens: state.cacheReadTokens,\n cacheCreationInputTokens: state.cacheCreationTokens,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : null,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA2DA,SAAgB,oBACd,YAAkC,EAAE,EACO;CAC3C,MAAM,MAAM,kBAAkB;CAC9B,MAAMA,SAAkC,EAAE,GAAG,WAAW;AAExD,KAAI,OAAO,MAAM;AACf,MAAI,CAAC,OAAO,OAAQ,QAAO,SAAS,IAAI;AACxC,MAAI,CAAC,OAAO,UAAW,QAAO,YAAY,IAAI;AAC9C,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,cAAe,QAAO,gBAAgB,IAAI;AACtD,MAAI,CAAC,OAAO,cAAe,QAAO,gBAAgB,IAAI;AACtD,MAAI,CAAC,OAAO,aAAc,QAAO,eAAe,IAAI;AACpD,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,IAAK,QAAO,MAAM,IAAI;AAClC,MAAI,CAAC,OAAO,OAAQ,QAAO,SAAS,IAAI;AAExC,MAAI,OAAO,UAAU,MAAM;GACzB,MAAM,SAAS,IAAI,YAAY;AAC/B,OAAI,UAAU,KAAM,QAAO,SAAS;;EAGtC,MAAM,aAAa,OAAO;EAC1B,MAAM,KAAK,cAAc,OAAO,EAAE,GAAG,YAAY,GAAG,EAAE;AACtD,MAAI,IAAI,sBAAsB,QAAQ,EAAE,6BAA6B,IACnE,IAAG,6BAA6B,IAAI;AAEtC,MACE,IAAI,YACJ,IAAI,oBACJ,EAAE,0BAA0B,IAE5B,IAAG,0BAA0B,GAAG,IAAI,SAAS,GAAG,IAAI;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AO,mBAAmB,KAAK;GAChD,eAAe,KAAK;GACrB,CAAC;;CAGJ,UAAmB;AACjB,UAAQ,SACN,KAAK,OAAO,KAAiD;;CAGjE,yBAAiD;AAC/C,SAAO,IAAI,uBAAuB,KAAK;;;AAI3C,IAAa,yBAAb,MAAoC;CAClC,AAAQ;CACR,AAAS;CACT,AAAQ,aAAa;CACrB,AAAQ;CAER,YAAY,UAA0B;AACpC,OAAK,WAAW,SAAS,SAAS;AAClC,OAAK,gBAAgB,SAAS;AAC9B,OAAK,cAAc,IAAI,sBAAsB;;CAG/C,SAAS,OAAqB;AAC5B,OAAK,aAAa;AAClB,OAAK,YAAY,QAAQ;;CAG3B,WAAW,OAAqB;AAC9B,OAAK,YAAY,WAAW,MAAM;;CAGpC,SAAS,OAA8D;AACrE,OAAK,YAAY,SAAS,MAAM;;CAGlC,gBAAgB,QAAsB;AACpC,OAAK,YAAY,eAAe;;CAGlC,YAAY,UAAyC;AACnD,OAAK,YAAY,YAAY,SAAS;;CAGxC,SAAS,YAAkC,EAAE,EAAU;EACrD,MAAM,QAAQ,KAAK,YAAY,UAAU;AAEzC,SAAO,KAAK,SAAS;GACnB,GAAG,cAAc,UAAU;GAC3B,WAAW,KAAK;GAChB,UAAU,KAAK;GACf,iBAAiB,MAAM;GACvB,WAAW,KAAK,YAAY;GAC5B,aAAa,MAAM;GACnB,cAAc,MAAM;GACpB,aAAa,MAAM;GACnB,iBAAiB,MAAM;GACvB,sBAAsB,MAAM;GAC5B,0BAA0B,MAAM;GAChC,cAAc,MAAM;GACpB,WAAW,MAAM,UAAU,SAAS,IAAI,MAAM,YAAY;GAC1D,gBAAgB,MAAM;GACtB,aAAa;GACd,CAAC"}
1
+ {"version":3,"file":"base.js","names":["result: Record<string, unknown>"],"sources":["../../src/providers/base.ts"],"sourcesContent":["/**\n * Base class for AI provider wrappers.\n *\n * Provides shared tracking logic and session context integration.\n */\n\nimport { getActiveContext } from '../context.js';\nimport {\n PROP_IDLE_TIMEOUT_MINUTES,\n PROP_SESSION_REPLAY_ID,\n} from '../core/constants.js';\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport {\n trackAiMessage,\n type TrackAiMessageOptions,\n} from '../core/tracking.js';\nimport {\n resolveAmplitude,\n type AmplitudeLike,\n type AmplitudeOrAI,\n type TrackCallOptions,\n type TrackFn,\n} from '../types.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\n\n/**\n * Per-call context overrides for provider wrappers.\n *\n * Pass as the second argument to wrapped provider methods\n * (e.g., `openai.chat.completions.create(params, overrides)`)\n * to set Amplitude tracking context for that specific call.\n * Any fields left `null`/`undefined` are filled from the\n * active `SessionContext` via `AsyncLocalStorage`.\n */\nexport interface ProviderTrackOptions {\n userId?: string | null;\n sessionId?: string | null;\n traceId?: string | null;\n turnId?: number | null;\n agentId?: string | null;\n parentAgentId?: string | null;\n customerOrgId?: string | null;\n agentVersion?: string | null;\n description?: string | null;\n context?: Record<string, unknown> | null;\n env?: string | null;\n groups?: Record<string, unknown> | null;\n eventProperties?: Record<string, unknown> | null;\n /**\n * Controls whether provider wrappers auto-track user input payloads.\n * Set to false when you already call `trackUserMessage()` explicitly.\n */\n trackInputMessages?: boolean;\n}\n\n/**\n * Apply session context fields from AsyncLocalStorage to tracking options.\n * Returns a merged set of fields with explicit values taking precedence.\n * Also injects idle_timeout_minutes and session_replay_id from the context.\n */\nexport function applySessionContext(\n overrides: ProviderTrackOptions = {},\n): ProviderTrackOptions & { userId: string } {\n const ctx = getActiveContext();\n const result: Record<string, unknown> = { ...overrides };\n\n if (ctx != null) {\n if (!result.userId) result.userId = ctx.userId;\n if (!result.sessionId) result.sessionId = ctx.sessionId;\n if (!result.traceId) result.traceId = ctx.traceId;\n if (!result.agentId) result.agentId = ctx.agentId;\n if (!result.parentAgentId) result.parentAgentId = ctx.parentAgentId;\n if (!result.customerOrgId) result.customerOrgId = ctx.customerOrgId;\n if (!result.agentVersion) result.agentVersion = ctx.agentVersion;\n if (!result.description) result.description = ctx.description;\n if (!result.context) result.context = ctx.context;\n if (!result.env) result.env = ctx.env;\n if (!result.groups) result.groups = ctx.groups;\n\n if (result.turnId == null) {\n const turnId = ctx.nextTurnId();\n if (turnId != null) result.turnId = turnId;\n }\n\n const existingEp = result.eventProperties as Record<string, unknown> | null;\n const ep = existingEp != null ? { ...existingEp } : {};\n if (ctx.idleTimeoutMinutes != null && !(PROP_IDLE_TIMEOUT_MINUTES in ep)) {\n ep[PROP_IDLE_TIMEOUT_MINUTES] = ctx.idleTimeoutMinutes;\n }\n if (\n ctx.deviceId &&\n ctx.browserSessionId &&\n !(PROP_SESSION_REPLAY_ID in ep)\n ) {\n ep[PROP_SESSION_REPLAY_ID] = `${ctx.deviceId}/${ctx.browserSessionId}`;\n }\n if (Object.keys(ep).length > 0) {\n result.eventProperties = ep;\n }\n }\n\n return result as unknown as ProviderTrackOptions & { userId: string };\n}\n\n/**\n * Extract all context fields from a resolved ProviderTrackOptions into a\n * flat object suitable for spreading into _trackFn() / _track() calls.\n * Ensures all 13 context fields propagate consistently.\n */\nexport type TrackContextFields = Pick<\n TrackCallOptions,\n | 'userId'\n | 'sessionId'\n | 'traceId'\n | 'turnId'\n | 'agentId'\n | 'parentAgentId'\n | 'customerOrgId'\n | 'agentVersion'\n | 'description'\n | 'context'\n | 'env'\n | 'groups'\n | 'eventProperties'\n>;\n\nexport function contextFields(ctx: ProviderTrackOptions): TrackContextFields {\n return {\n userId: ctx.userId ?? 'unknown',\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n description: ctx.description,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n };\n}\n\nexport abstract class BaseAIProvider {\n protected _amplitude: AmplitudeLike;\n protected _privacyConfig: PrivacyConfig | null;\n readonly _providerName: string;\n\n constructor(options: {\n amplitude: AmplitudeOrAI;\n privacyConfig?: PrivacyConfig | null;\n providerName: string;\n }) {\n this._amplitude = resolveAmplitude(options.amplitude);\n this._privacyConfig = options.privacyConfig ?? null;\n this._providerName = options.providerName;\n }\n\n protected _track(opts: Omit<TrackAiMessageOptions, 'amplitude'>): string {\n const merged = applySessionContext({\n userId: opts.userId,\n sessionId: opts.sessionId,\n traceId: opts.traceId,\n turnId: opts.turnId,\n agentId: opts.agentId,\n parentAgentId: opts.parentAgentId,\n customerOrgId: opts.customerOrgId,\n agentVersion: opts.agentVersion,\n description: opts.description,\n context: opts.context,\n env: opts.env,\n groups: opts.groups,\n eventProperties: opts.eventProperties,\n });\n\n return trackAiMessage({\n ...opts,\n amplitude: this._amplitude,\n userId: merged.userId ?? opts.userId,\n sessionId: merged.sessionId ?? opts.sessionId,\n traceId: merged.traceId ?? opts.traceId,\n turnId: merged.turnId ?? opts.turnId,\n agentId: merged.agentId ?? opts.agentId,\n parentAgentId: merged.parentAgentId ?? opts.parentAgentId,\n customerOrgId: merged.customerOrgId ?? opts.customerOrgId,\n agentVersion: merged.agentVersion ?? opts.agentVersion,\n description: merged.description ?? opts.description,\n context: merged.context ?? opts.context,\n env: merged.env ?? opts.env,\n groups: merged.groups ?? opts.groups,\n eventProperties: merged.eventProperties ?? opts.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n\n trackFn(): TrackFn {\n return (opts: TrackCallOptions) =>\n this._track(opts as Omit<TrackAiMessageOptions, 'amplitude'>);\n }\n\n createStreamingTracker(): SimpleStreamingTracker {\n return new SimpleStreamingTracker(this);\n }\n}\n\nexport class SimpleStreamingTracker {\n private _trackFn: TrackFn;\n readonly accumulator: StreamingAccumulator;\n private _modelName = 'unknown';\n private _providerName: string;\n\n constructor(provider: BaseAIProvider) {\n this._trackFn = provider.trackFn();\n this._providerName = provider._providerName;\n this.accumulator = new StreamingAccumulator();\n }\n\n setModel(model: string): void {\n this._modelName = model;\n this.accumulator.model = model;\n }\n\n addContent(chunk: string): void {\n this.accumulator.addContent(chunk);\n }\n\n setUsage(usage: Parameters<StreamingAccumulator['setUsage']>[0]): void {\n this.accumulator.setUsage(usage);\n }\n\n setFinishReason(reason: string): void {\n this.accumulator.finishReason = reason;\n }\n\n addToolCall(toolCall: Record<string, unknown>): void {\n this.accumulator.addToolCall(toolCall);\n }\n\n finalize(overrides: ProviderTrackOptions = {}): string {\n const state = this.accumulator.getState();\n\n return this._trackFn({\n ...contextFields(overrides),\n modelName: this._modelName,\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: this.accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n cacheReadInputTokens: state.cacheReadTokens,\n cacheCreationInputTokens: state.cacheCreationTokens,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : null,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA4DA,SAAgB,oBACd,YAAkC,EAAE,EACO;CAC3C,MAAM,MAAM,kBAAkB;CAC9B,MAAMA,SAAkC,EAAE,GAAG,WAAW;AAExD,KAAI,OAAO,MAAM;AACf,MAAI,CAAC,OAAO,OAAQ,QAAO,SAAS,IAAI;AACxC,MAAI,CAAC,OAAO,UAAW,QAAO,YAAY,IAAI;AAC9C,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,cAAe,QAAO,gBAAgB,IAAI;AACtD,MAAI,CAAC,OAAO,cAAe,QAAO,gBAAgB,IAAI;AACtD,MAAI,CAAC,OAAO,aAAc,QAAO,eAAe,IAAI;AACpD,MAAI,CAAC,OAAO,YAAa,QAAO,cAAc,IAAI;AAClD,MAAI,CAAC,OAAO,QAAS,QAAO,UAAU,IAAI;AAC1C,MAAI,CAAC,OAAO,IAAK,QA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UM,aAuUN,GAAA,IAAA,EAAA,gBAAA,EAAA,OAAA,EAAA,YAAA,CAAA,EAAA,MAAA;EACE,MAAA,CAAA,MAAA,EAxTH,MAwTG,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,kBAAA,CAAA,EAvTU,oBAuTV,CAAA,EAtTV,OAsTU,CAtTF,sBAsTE,GAtTuB,aAsTvB,CAAA,OAAA,CAAA,CAAA;EACI,KAAA,CAAA,MAAA,EA9MP,MA8MO,CAAA,MAAA,EAAA,OAAA,CAAA,EAAA,kBAAA,CAAA,EA7MM,oBA6MN,CAAA,EA5Md,OA4Mc,CA5MN,sBA4MM,GA5MmB,aA4MnB,CAAA,OAAA,CAAA,CAAA;EAkBP,QAAA,WAAA;EACa,QAAA,mBAAA;EACZ,QAAA,mBAAA;;AAAR,cAhCQ,gBAAA,CAgCR;EAmFO,SAAA,EAlHC,MAkHD,CAAA,MAAA,EAAA,OAAA,CAAA;EACa,QAAA,QAAA;EACZ,QAAA,UAAA;EAAR,QAAA,cAAA;EAAO,QAAA,iBAAA;EAgLI,QAAA,aAAA;wCA3RH,oBACE,8BACI;iBAkBP,8CACa,uBACpB,QAAQ,iBAAiB;iBAmFlB,8CACa,uBACpB,QAAQ;;;;;iBAgLG,mBAAA,SACN"}
@@ -246,6 +246,7 @@ var WrappedCompletions = class {
246
246
  sessionId: ctx.sessionId,
247
247
  traceId: ctx.traceId,
248
248
  turnId: ctx.turnId ?? void 0,
249
+ messageSource: ctx.parentAgentId ? "agent" : "user",
249
250
  agentId: ctx.agentId,
250
251
  parentAgentId: ctx.parentAgentId,
251
252
  customerOrgId: ctx.customerOrgId,
@@ -444,6 +445,7 @@ var WrappedResponses = class {
444
445
  sessionId: ctx.sessionId,
445
446
  traceId: ctx.traceId,
446
447
  turnId: ctx.turnId ?? void 0,
448
+ messageSource: ctx.parentAgentId ? "agent" : "user",
447
449
  agentId: ctx.agentId,
448
450
  parentAgentId: ctx.parentAgentId,
449
451
  customerOrgId: ctx.customerOrgId,
@@ -1 +1 @@
1
- {"version":3,"file":"openai.js","names":["_OpenAIModule: Record<string, unknown> | null","clientOpts: Record<string, unknown>","costUsd: number | null","toolCalls: Array<Record<string, unknown>>","result: string[]"],"sources":["../../src/providers/openai.ts"],"sourcesContent":["/**\n * OpenAI provider wrapper with automatic tracking.\n *\n * Wraps the OpenAI client and instruments:\n * - chat.completions.create()\n * - responses.create()\n * to track AI response events via Amplitude.\n */\n\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport { trackUserMessage } from '../core/tracking.js';\nimport { getDefaultPropagateContext, injectContext } from '../propagation.js';\nimport type {\n AmplitudeLike,\n AmplitudeOrAI,\n ChatCompletionResponse,\n ChatMessage,\n OpenAIResponse,\n OpenAIResponseInput,\n OpenAIResponseOutputItem,\n TrackFn,\n} from '../types.js';\nimport { calculateCost } from '../utils/costs.js';\nimport { tryRequire } from '../utils/resolve-module.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\nimport {\n applySessionContext,\n BaseAIProvider,\n contextFields,\n type ProviderTrackOptions,\n} from './base.js';\n\nconst _resolved = tryRequire('openai');\nexport const OPENAI_AVAILABLE = _resolved != null;\nconst _OpenAIModule: Record<string, unknown> | null = _resolved;\n\nexport { _OpenAIModule };\n\nexport interface OpenAIOptions {\n amplitude: AmplitudeOrAI;\n apiKey?: string;\n baseUrl?: string;\n privacyConfig?: PrivacyConfig | null;\n propagateContext?: boolean;\n /** Pass the `openai` module directly to bypass `tryRequire` (required in bundler environments). */\n openaiModule?: unknown;\n}\n\nexport class OpenAI<\n TClient extends Record<string, unknown> = Record<string, unknown>,\n> extends BaseAIProvider {\n private _client: TClient;\n readonly chat: WrappedChat;\n readonly responses: WrappedResponses;\n private _propagateContext: boolean;\n\n constructor(options: OpenAIOptions) {\n super({\n amplitude: options.amplitude,\n privacyConfig: options.privacyConfig,\n providerName: 'openai',\n });\n\n const mod =\n (options.openaiModule as Record<string, unknown> | null) ?? _OpenAIModule;\n if (mod == null) {\n throw new Error(\n 'openai package is required. Install it with: npm install openai — or pass the module directly via the openaiModule option.',\n );\n }\n\n const OpenAISDK = mod.OpenAI as new (\n opts: Record<string, unknown>,\n ) => unknown;\n\n const clientOpts: Record<string, unknown> = {};\n if (options.apiKey) clientOpts.apiKey = options.apiKey;\n if (options.baseUrl) clientOpts.baseURL = options.baseUrl;\n\n this._client = new OpenAISDK(clientOpts) as TClient;\n this._propagateContext =\n options.propagateContext ?? getDefaultPropagateContext();\n this.chat = new WrappedChat(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n this.responses = new WrappedResponses(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n }\n\n get client(): TClient {\n return this._client;\n }\n}\n\nexport class WrappedChat {\n readonly completions: WrappedCompletions;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n ) {\n const clientObj = client as Record<string, unknown>;\n const chat = clientObj.chat as Record<string, unknown>;\n this.completions = new WrappedCompletions(\n chat.completions as Record<string, unknown>,\n trackFn,\n amplitude,\n privacyConfig,\n propagateContext,\n );\n }\n}\n\nexport class WrappedCompletions {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n private _providerName: string;\n\n constructor(\n completions: Record<string, unknown>,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n providerName = 'openai',\n ) {\n this._original = completions;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n this._providerName = providerName;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<ChatCompletionResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n let requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n if (requestParams.stream === true && requestParams.stream_options == null) {\n requestParams = {\n ...requestParams,\n stream_options: { include_usage: true },\n };\n }\n\n try {\n this._trackInputMessages(\n requestParams.messages as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n\n const resp = response as ChatCompletionResponse;\n const usage = resp.usage;\n const choice = resp.choices?.[0];\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n const toolCalls = choice?.message?.tool_calls;\n\n const usageExt = usage as Record<string, unknown> | undefined;\n const promptDetails = usageExt?.prompt_tokens_details as\n | Record<string, number>\n | undefined;\n const completionDetails = usageExt?.completion_tokens_details as\n | Record<string, number>\n | undefined;\n const reasoningTokens = completionDetails?.reasoning_tokens;\n const cachedTokens = promptDetails?.cached_tokens;\n\n let costUsd: number | null = null;\n if (usage?.prompt_tokens != null && usage?.completion_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: usage.prompt_tokens,\n outputTokens: usage.completion_tokens,\n reasoningTokens: reasoningTokens ?? 0,\n cacheReadInputTokens: cachedTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: this._providerName,\n responseContent: String(choice?.message?.content ?? ''),\n latencyMs,\n inputTokens: usage?.prompt_tokens,\n outputTokens: usage?.completion_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens,\n cacheReadInputTokens: cachedTokens,\n totalCostUsd: costUsd,\n finishReason: choice?.finish_reason,\n toolCalls: toolCalls ?? undefined,\n isStreaming: false,\n systemPrompt: extractSystemPrompt(requestParams),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as ChatCompletionResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n\n throw error;\n }\n }\n\n async parse(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<ChatCompletionResponse | AsyncIterable<unknown>> {\n const parseFn = this._original.parse as\n | ((...args: unknown[]) => Promise<unknown>)\n | undefined;\n if (typeof parseFn !== 'function') {\n throw new Error('OpenAI SDK does not expose chat.completions.parse');\n }\n const originalCreate = this._original.create;\n this._original.create = parseFn;\n try {\n return await this.create(params, amplitudeOverrides);\n } finally {\n this._original.create = originalCreate;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n let reasoningContent = '';\n\n try {\n for await (const chunk of stream) {\n const c = chunk as Record<string, unknown>;\n const choices = c.choices as Array<Record<string, unknown>> | undefined;\n const delta = choices?.[0]?.delta as\n | Record<string, unknown>\n | undefined;\n\n if (delta?.content != null) {\n accumulator.addContent(String(delta.content));\n }\n\n const deltaToolCalls = delta?.tool_calls as\n | Array<Record<string, unknown>>\n | undefined;\n if (Array.isArray(deltaToolCalls)) {\n for (const call of deltaToolCalls) {\n const idx = call.index as number | undefined;\n const id = call.id as string | undefined;\n const fn = call.function as Record<string, unknown> | undefined;\n if (idx != null && id && fn?.name != null) {\n accumulator.setToolCallAt(idx, {\n type: 'function',\n id,\n function: {\n name: fn.name,\n arguments: ((fn.arguments as string) ?? ''),\n },\n });\n } else if (idx != null && fn?.arguments) {\n accumulator.appendToolCallArgs(idx, fn.arguments as string);\n } else {\n accumulator.addToolCall(call);\n }\n }\n }\n\n if (delta?.reasoning_content != null) {\n reasoningContent += String(delta.reasoning_content);\n }\n\n const finishReason = choices?.[0]?.finish_reason;\n if (finishReason != null) {\n accumulator.finishReason = String(finishReason);\n }\n\n const usage = c.usage as Record<string, unknown> | undefined;\n if (usage != null) {\n const promptDetails = usage.prompt_tokens_details as\n | Record<string, number>\n | undefined;\n const completionDetails = usage.completion_tokens_details as\n | Record<string, number>\n | undefined;\n\n accumulator.setUsage({\n inputTokens: usage.prompt_tokens as number | undefined,\n outputTokens: usage.completion_tokens as number | undefined,\n totalTokens: usage.total_tokens as number | undefined,\n reasoningTokens: completionDetails?.reasoning_tokens,\n cacheReadTokens: promptDetails?.cached_tokens,\n });\n }\n\n yield chunk;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n const modelName = String(accumulator.model ?? params.model ?? 'unknown');\n\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n reasoningTokens: state.reasoningTokens ?? 0,\n cacheReadInputTokens: state.cacheReadTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName,\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n cacheReadInputTokens: state.cacheReadTokens,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : undefined,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n reasoningContent: reasoningContent || undefined,\n systemPrompt: extractSystemPrompt(params),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n messages: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n if (!Array.isArray(messages)) return;\n for (const msg of messages as ChatMessage[]) {\n if (msg?.role !== 'user') continue;\n const content = msg.content;\n if (typeof content !== 'string' || content.length === 0) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: content,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nexport class WrappedResponses {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n private _providerName: string;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n providerName = 'openai',\n ) {\n const clientObj = client as Record<string, unknown>;\n const responses = (clientObj.responses ?? {}) as Record<string, unknown>;\n this._original = responses;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n this._providerName = providerName;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<OpenAIResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.input as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n const resp = response as OpenAIResponse;\n const usage = resp.usage;\n const responseText = extractResponsesText(resp);\n const responseToolCalls = extractResponsesToolCalls(resp);\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n\n let costUsd: number | null = null;\n if (usage?.input_tokens != null && usage?.output_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n reasoningTokens: usage.output_tokens_details?.reasoning_tokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: this._providerName,\n responseContent: responseText,\n latencyMs,\n inputTokens: usage?.input_tokens,\n outputTokens: usage?.output_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens: usage?.output_tokens_details?.reasoning_tokens,\n totalCostUsd: costUsd,\n finishReason: extractResponsesFinishReason(resp),\n toolCalls: responseToolCalls.length > 0 ? responseToolCalls : undefined,\n isStreaming: false,\n systemPrompt: extractResponsesSystemPrompt(requestParams),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_output_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as OpenAIResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n async stream(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<AsyncIterable<unknown>> {\n const streamFn = this._original.stream as\n | ((...args: unknown[]) => Promise<unknown>)\n | undefined;\n if (typeof streamFn !== 'function') {\n throw new Error('OpenAI SDK does not expose responses.stream');\n }\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.input as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await streamFn.call(this._original, requestParams);\n if (!_isAsyncIterable(response)) {\n throw new Error('OpenAI responses.stream did not return AsyncIterable');\n }\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n } catch (error) {\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs: performance.now() - startTime,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n isStreaming: true,\n });\n throw error;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n\n try {\n for await (const event of stream) {\n const e = event as Record<string, unknown>;\n const type = e.type as string | undefined;\n if (type === 'response.output_text.delta') {\n const delta = e.delta;\n if (typeof delta === 'string') accumulator.addContent(delta);\n } else if (type === 'response.completed') {\n const response = e.response as OpenAIResponse | undefined;\n if (response != null) {\n const outputText = extractResponsesText(response);\n if (outputText.length > 0) {\n accumulator.content = outputText;\n }\n const usage = response.usage;\n accumulator.setUsage({\n inputTokens: usage?.input_tokens,\n outputTokens: usage?.output_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens: usage?.output_tokens_details?.reasoning_tokens,\n });\n const finishReason = extractResponsesFinishReason(response);\n if (finishReason != null) accumulator.finishReason = finishReason;\n }\n }\n yield event;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName: String(accumulator.model ?? params.model ?? 'unknown'),\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n reasoningTokens: state.reasoningTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName: String(accumulator.model ?? params.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n systemPrompt: extractResponsesSystemPrompt(params),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_output_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n input: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n for (const text of extractResponsesUserInputs(input)) {\n if (!text) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: text,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nfunction _isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value != null &&\n typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] ===\n 'function'\n );\n}\n\nexport function extractSystemPrompt(\n params: Record<string, unknown>,\n): string | undefined {\n const messages = params.messages as\n | Array<Record<string, unknown>>\n | undefined;\n if (!messages?.length) return undefined;\n const systemMsg = messages.find(\n (m) => m.role === 'system' || m.role === 'developer',\n );\n return systemMsg ? String(systemMsg.content ?? '') : undefined;\n}\n\nfunction extractResponsesSystemPrompt(\n params: Record<string, unknown>,\n): string | undefined {\n const instructions = params.instructions;\n return typeof instructions === 'string' ? instructions : undefined;\n}\n\nfunction extractResponsesFinishReason(\n resp: OpenAIResponse,\n): string | undefined {\n const status = resp.status;\n if (typeof status === 'string' && status.length > 0) return status;\n const out = resp.output?.[0];\n if (out != null && typeof out.status === 'string') return out.status;\n return undefined;\n}\n\nfunction extractResponsesText(resp: OpenAIResponse): string {\n if (typeof resp.output_text === 'string') return resp.output_text;\n const outputs = resp.output ?? [];\n let text = '';\n for (const item of outputs) {\n text += extractOutputItemText(item);\n }\n return text;\n}\n\nfunction extractResponsesToolCalls(\n resp: OpenAIResponse,\n): Array<Record<string, unknown>> {\n const toolCalls: Array<Record<string, unknown>> = [];\n const outputs = resp.output ?? [];\n for (const item of outputs) {\n if (!Array.isArray(item.content)) continue;\n for (const contentItem of item.content) {\n if (\n contentItem?.type === 'tool_call' ||\n contentItem?.type === 'function_call'\n ) {\n toolCalls.push(contentItem as Record<string, unknown>);\n }\n }\n }\n return toolCalls;\n}\n\nfunction extractOutputItemText(item: OpenAIResponseOutputItem): string {\n if (!Array.isArray(item.content)) return '';\n let text = '';\n for (const c of item.content) {\n if (typeof c?.text === 'string') text += c.text;\n }\n return text;\n}\n\nfunction extractResponsesUserInputs(input: unknown): string[] {\n if (typeof input === 'string') return [input];\n if (!Array.isArray(input)) return [];\n\n const result: string[] = [];\n for (const entry of input as OpenAIResponseInput[]) {\n if (typeof entry === 'string') {\n result.push(entry);\n continue;\n }\n const role = entry.role;\n if (role !== 'user') continue;\n const content = entry.content;\n if (typeof content === 'string') {\n result.push(content);\n } else if (Array.isArray(content)) {\n for (const part of content) {\n if (typeof part?.text === 'string') result.push(part.text);\n }\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;AAgCA,MAAM,YAAY,WAAW,SAAS;AACtC,MAAa,mBAAmB,aAAa;AAC7C,MAAMA,gBAAgD;AActD,IAAa,SAAb,cAEU,eAAe;CACvB,AAAQ;CACR,AAAS;CACT,AAAS;CACT,AAAQ;CAER,YAAY,SAAwB;AAClC,QAAM;GACJ,WAAW,QAAQ;GACnB,eAAe,QAAQ;GACvB,cAAc;GACf,CAAC;EAEF,MAAM,MACH,QAAQ,gBAAmD;AAC9D,MAAI,OAAO,KACT,OAAM,IAAI,MACR,6HACD;EAGH,MAAM,YAAY,IAAI;EAItB,MAAMC,aAAsC,EAAE;AAC9C,MAAI,QAAQ,OAAQ,YAAW,SAAS,QAAQ;AAChD,MAAI,QAAQ,QAAS,YAAW,UAAU,QAAQ;AAElD,OAAK,UAAU,IAAI,UAAU,WAAW;AACxC,OAAK,oBACH,QAAQ,oBAAoB,4BAA4B;AAC1D,OAAK,OAAO,IAAI,YACd,KAAK,SACL,K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C,MAAM;AAC7C,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO,EAAE;CAEpC,MAAMC,SAAmB,EAAE;AAC3B,MAAK,MAAM,SAAS,OAAgC;AAClD,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAO,KAAK,MAAM;AAClB;;AAGF,MADa,MAAM,SACN,OAAQ;EACrB,MAAM,UAAU,MAAM;AACtB,MAAI,OAAO,YAAY,SACrB,QAAO,KAAK,QAAQ;WACX,MAAM,QAAQ,QAAQ,EAC/B;QAAK,MAAM,QAAQ,QACjB,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,KAAK,KAAK,KAAK;;;AAIhE,QAAO"}
1
+ {"version":3,"file":"openai.js","names":["_OpenAIModule: Record<string, unknown> | null","clientOpts: Record<string, unknown>","costUsd: number | null","toolCalls: Array<Record<string, unknown>>","result: string[]"],"sources":["../../src/providers/openai.ts"],"sourcesContent":["/**\n * OpenAI provider wrapper with automatic tracking.\n *\n * Wraps the OpenAI client and instruments:\n * - chat.completions.create()\n * - responses.create()\n * to track AI response events via Amplitude.\n */\n\nimport type { PrivacyConfig } from '../core/privacy.js';\nimport { trackUserMessage } from '../core/tracking.js';\nimport { getDefaultPropagateContext, injectContext } from '../propagation.js';\nimport type {\n AmplitudeLike,\n AmplitudeOrAI,\n ChatCompletionResponse,\n ChatMessage,\n OpenAIResponse,\n OpenAIResponseInput,\n OpenAIResponseOutputItem,\n TrackFn,\n} from '../types.js';\nimport { calculateCost } from '../utils/costs.js';\nimport { tryRequire } from '../utils/resolve-module.js';\nimport { StreamingAccumulator } from '../utils/streaming.js';\nimport {\n applySessionContext,\n BaseAIProvider,\n contextFields,\n type ProviderTrackOptions,\n} from './base.js';\n\nconst _resolved = tryRequire('openai');\nexport const OPENAI_AVAILABLE = _resolved != null;\nconst _OpenAIModule: Record<string, unknown> | null = _resolved;\n\nexport { _OpenAIModule };\n\nexport interface OpenAIOptions {\n amplitude: AmplitudeOrAI;\n apiKey?: string;\n baseUrl?: string;\n privacyConfig?: PrivacyConfig | null;\n propagateContext?: boolean;\n /** Pass the `openai` module directly to bypass `tryRequire` (required in bundler environments). */\n openaiModule?: unknown;\n}\n\nexport class OpenAI<\n TClient extends Record<string, unknown> = Record<string, unknown>,\n> extends BaseAIProvider {\n private _client: TClient;\n readonly chat: WrappedChat;\n readonly responses: WrappedResponses;\n private _propagateContext: boolean;\n\n constructor(options: OpenAIOptions) {\n super({\n amplitude: options.amplitude,\n privacyConfig: options.privacyConfig,\n providerName: 'openai',\n });\n\n const mod =\n (options.openaiModule as Record<string, unknown> | null) ?? _OpenAIModule;\n if (mod == null) {\n throw new Error(\n 'openai package is required. Install it with: npm install openai — or pass the module directly via the openaiModule option.',\n );\n }\n\n const OpenAISDK = mod.OpenAI as new (\n opts: Record<string, unknown>,\n ) => unknown;\n\n const clientOpts: Record<string, unknown> = {};\n if (options.apiKey) clientOpts.apiKey = options.apiKey;\n if (options.baseUrl) clientOpts.baseURL = options.baseUrl;\n\n this._client = new OpenAISDK(clientOpts) as TClient;\n this._propagateContext =\n options.propagateContext ?? getDefaultPropagateContext();\n this.chat = new WrappedChat(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n this.responses = new WrappedResponses(\n this._client,\n this.trackFn(),\n this._amplitude,\n this._privacyConfig,\n this._propagateContext,\n );\n }\n\n get client(): TClient {\n return this._client;\n }\n}\n\nexport class WrappedChat {\n readonly completions: WrappedCompletions;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n ) {\n const clientObj = client as Record<string, unknown>;\n const chat = clientObj.chat as Record<string, unknown>;\n this.completions = new WrappedCompletions(\n chat.completions as Record<string, unknown>,\n trackFn,\n amplitude,\n privacyConfig,\n propagateContext,\n );\n }\n}\n\nexport class WrappedCompletions {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n private _providerName: string;\n\n constructor(\n completions: Record<string, unknown>,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n providerName = 'openai',\n ) {\n this._original = completions;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n this._providerName = providerName;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<ChatCompletionResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n let requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n if (requestParams.stream === true && requestParams.stream_options == null) {\n requestParams = {\n ...requestParams,\n stream_options: { include_usage: true },\n };\n }\n\n try {\n this._trackInputMessages(\n requestParams.messages as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n\n const resp = response as ChatCompletionResponse;\n const usage = resp.usage;\n const choice = resp.choices?.[0];\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n const toolCalls = choice?.message?.tool_calls;\n\n const usageExt = usage as Record<string, unknown> | undefined;\n const promptDetails = usageExt?.prompt_tokens_details as\n | Record<string, number>\n | undefined;\n const completionDetails = usageExt?.completion_tokens_details as\n | Record<string, number>\n | undefined;\n const reasoningTokens = completionDetails?.reasoning_tokens;\n const cachedTokens = promptDetails?.cached_tokens;\n\n let costUsd: number | null = null;\n if (usage?.prompt_tokens != null && usage?.completion_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: usage.prompt_tokens,\n outputTokens: usage.completion_tokens,\n reasoningTokens: reasoningTokens ?? 0,\n cacheReadInputTokens: cachedTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: this._providerName,\n responseContent: String(choice?.message?.content ?? ''),\n latencyMs,\n inputTokens: usage?.prompt_tokens,\n outputTokens: usage?.completion_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens,\n cacheReadInputTokens: cachedTokens,\n totalCostUsd: costUsd,\n finishReason: choice?.finish_reason,\n toolCalls: toolCalls ?? undefined,\n isStreaming: false,\n systemPrompt: extractSystemPrompt(requestParams),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as ChatCompletionResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n\n throw error;\n }\n }\n\n async parse(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<ChatCompletionResponse | AsyncIterable<unknown>> {\n const parseFn = this._original.parse as\n | ((...args: unknown[]) => Promise<unknown>)\n | undefined;\n if (typeof parseFn !== 'function') {\n throw new Error('OpenAI SDK does not expose chat.completions.parse');\n }\n const originalCreate = this._original.create;\n this._original.create = parseFn;\n try {\n return await this.create(params, amplitudeOverrides);\n } finally {\n this._original.create = originalCreate;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n let reasoningContent = '';\n\n try {\n for await (const chunk of stream) {\n const c = chunk as Record<string, unknown>;\n const choices = c.choices as Array<Record<string, unknown>> | undefined;\n const delta = choices?.[0]?.delta as\n | Record<string, unknown>\n | undefined;\n\n if (delta?.content != null) {\n accumulator.addContent(String(delta.content));\n }\n\n const deltaToolCalls = delta?.tool_calls as\n | Array<Record<string, unknown>>\n | undefined;\n if (Array.isArray(deltaToolCalls)) {\n for (const call of deltaToolCalls) {\n const idx = call.index as number | undefined;\n const id = call.id as string | undefined;\n const fn = call.function as Record<string, unknown> | undefined;\n if (idx != null && id && fn?.name != null) {\n accumulator.setToolCallAt(idx, {\n type: 'function',\n id,\n function: {\n name: fn.name,\n arguments: ((fn.arguments as string) ?? ''),\n },\n });\n } else if (idx != null && fn?.arguments) {\n accumulator.appendToolCallArgs(idx, fn.arguments as string);\n } else {\n accumulator.addToolCall(call);\n }\n }\n }\n\n if (delta?.reasoning_content != null) {\n reasoningContent += String(delta.reasoning_content);\n }\n\n const finishReason = choices?.[0]?.finish_reason;\n if (finishReason != null) {\n accumulator.finishReason = String(finishReason);\n }\n\n const usage = c.usage as Record<string, unknown> | undefined;\n if (usage != null) {\n const promptDetails = usage.prompt_tokens_details as\n | Record<string, number>\n | undefined;\n const completionDetails = usage.completion_tokens_details as\n | Record<string, number>\n | undefined;\n\n accumulator.setUsage({\n inputTokens: usage.prompt_tokens as number | undefined,\n outputTokens: usage.completion_tokens as number | undefined,\n totalTokens: usage.total_tokens as number | undefined,\n reasoningTokens: completionDetails?.reasoning_tokens,\n cacheReadTokens: promptDetails?.cached_tokens,\n });\n }\n\n yield chunk;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n const modelName = String(accumulator.model ?? params.model ?? 'unknown');\n\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n reasoningTokens: state.reasoningTokens ?? 0,\n cacheReadInputTokens: state.cacheReadTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName,\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n cacheReadInputTokens: state.cacheReadTokens,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n toolCalls: state.toolCalls.length > 0 ? state.toolCalls : undefined,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n reasoningContent: reasoningContent || undefined,\n systemPrompt: extractSystemPrompt(params),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n messages: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n if (!Array.isArray(messages)) return;\n for (const msg of messages as ChatMessage[]) {\n if (msg?.role !== 'user') continue;\n const content = msg.content;\n if (typeof content !== 'string' || content.length === 0) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: content,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n messageSource: ctx.parentAgentId ? 'agent' : 'user',\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nexport class WrappedResponses {\n _original: Record<string, unknown>;\n private _trackFn: TrackFn;\n private _amplitude: AmplitudeLike;\n private _privacyConfig: PrivacyConfig | null;\n private _propagateContext: boolean;\n private _providerName: string;\n\n constructor(\n client: unknown,\n trackFn: TrackFn,\n amplitude: AmplitudeLike,\n privacyConfig: PrivacyConfig | null,\n propagateContext: boolean,\n providerName = 'openai',\n ) {\n const clientObj = client as Record<string, unknown>;\n const responses = (clientObj.responses ?? {}) as Record<string, unknown>;\n this._original = responses;\n this._trackFn =\n typeof trackFn === 'function'\n ? trackFn\n : (trackFn as unknown as { trackFn(): TrackFn }).trackFn();\n this._amplitude = amplitude;\n this._privacyConfig = privacyConfig;\n this._propagateContext = propagateContext;\n this._providerName = providerName;\n }\n\n async create(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<OpenAIResponse | AsyncIterable<unknown>> {\n const createFn = this._original.create as (\n ...args: unknown[]\n ) => Promise<unknown>;\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.input as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await createFn.call(this._original, requestParams);\n if (requestParams.stream === true && _isAsyncIterable(response)) {\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n }\n\n const latencyMs = performance.now() - startTime;\n const resp = response as OpenAIResponse;\n const usage = resp.usage;\n const responseText = extractResponsesText(resp);\n const responseToolCalls = extractResponsesToolCalls(resp);\n const modelName = String(resp.model ?? requestParams.model ?? 'unknown');\n\n let costUsd: number | null = null;\n if (usage?.input_tokens != null && usage?.output_tokens != null) {\n try {\n costUsd = calculateCost({\n modelName,\n inputTokens: usage.input_tokens,\n outputTokens: usage.output_tokens,\n reasoningTokens: usage.output_tokens_details?.reasoning_tokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n\n this._trackFn({\n ...contextFields(ctx),\n modelName,\n provider: this._providerName,\n responseContent: responseText,\n latencyMs,\n inputTokens: usage?.input_tokens,\n outputTokens: usage?.output_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens: usage?.output_tokens_details?.reasoning_tokens,\n totalCostUsd: costUsd,\n finishReason: extractResponsesFinishReason(resp),\n toolCalls: responseToolCalls.length > 0 ? responseToolCalls : undefined,\n isStreaming: false,\n systemPrompt: extractResponsesSystemPrompt(requestParams),\n temperature: requestParams.temperature as number | undefined,\n maxOutputTokens: requestParams.max_output_tokens as number | undefined,\n topP: requestParams.top_p as number | undefined,\n });\n\n return response as OpenAIResponse;\n } catch (error) {\n const latencyMs = performance.now() - startTime;\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n async stream(\n params: Record<string, unknown>,\n amplitudeOverrides?: ProviderTrackOptions,\n ): Promise<AsyncIterable<unknown>> {\n const streamFn = this._original.stream as\n | ((...args: unknown[]) => Promise<unknown>)\n | undefined;\n if (typeof streamFn !== 'function') {\n throw new Error('OpenAI SDK does not expose responses.stream');\n }\n const startTime = performance.now();\n const requestParams = this._withContextHeaders(params);\n const ctx = applySessionContext(amplitudeOverrides);\n\n try {\n this._trackInputMessages(\n requestParams.input as unknown,\n ctx,\n amplitudeOverrides?.trackInputMessages ?? true,\n );\n const response = await streamFn.call(this._original, requestParams);\n if (!_isAsyncIterable(response)) {\n throw new Error('OpenAI responses.stream did not return AsyncIterable');\n }\n return this._wrapStream(\n response as AsyncIterable<unknown>,\n requestParams,\n startTime,\n ctx,\n );\n } catch (error) {\n this._trackFn({\n ...contextFields(ctx),\n modelName: String(requestParams.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: '',\n latencyMs: performance.now() - startTime,\n isError: true,\n errorMessage: error instanceof Error ? error.message : String(error),\n isStreaming: true,\n });\n throw error;\n }\n }\n\n private async *_wrapStream(\n stream: AsyncIterable<unknown>,\n params: Record<string, unknown>,\n _startTime: number,\n sessionCtx: ProviderTrackOptions,\n ): AsyncGenerator<unknown> {\n const accumulator = new StreamingAccumulator();\n accumulator.model = String(params.model ?? 'unknown');\n\n try {\n for await (const event of stream) {\n const e = event as Record<string, unknown>;\n const type = e.type as string | undefined;\n if (type === 'response.output_text.delta') {\n const delta = e.delta;\n if (typeof delta === 'string') accumulator.addContent(delta);\n } else if (type === 'response.completed') {\n const response = e.response as OpenAIResponse | undefined;\n if (response != null) {\n const outputText = extractResponsesText(response);\n if (outputText.length > 0) {\n accumulator.content = outputText;\n }\n const usage = response.usage;\n accumulator.setUsage({\n inputTokens: usage?.input_tokens,\n outputTokens: usage?.output_tokens,\n totalTokens: usage?.total_tokens,\n reasoningTokens: usage?.output_tokens_details?.reasoning_tokens,\n });\n const finishReason = extractResponsesFinishReason(response);\n if (finishReason != null) accumulator.finishReason = finishReason;\n }\n }\n yield event;\n }\n } catch (error) {\n accumulator.setError(\n error instanceof Error ? error.message : String(error),\n );\n throw error;\n } finally {\n const state = accumulator.getState();\n let costUsd: number | null = null;\n if (state.inputTokens != null && state.outputTokens != null) {\n try {\n costUsd = calculateCost({\n modelName: String(accumulator.model ?? params.model ?? 'unknown'),\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n reasoningTokens: state.reasoningTokens ?? 0,\n defaultProvider: 'openai',\n });\n } catch {\n // cost calculation is best-effort\n }\n }\n this._trackFn({\n ...contextFields(sessionCtx),\n modelName: String(accumulator.model ?? params.model ?? 'unknown'),\n provider: this._providerName,\n responseContent: state.content,\n latencyMs: accumulator.elapsedMs,\n inputTokens: state.inputTokens,\n outputTokens: state.outputTokens,\n totalTokens: state.totalTokens,\n reasoningTokens: state.reasoningTokens,\n totalCostUsd: costUsd,\n finishReason: state.finishReason,\n providerTtfbMs: state.ttfbMs,\n isStreaming: true,\n isError: state.isError,\n errorMessage: state.errorMessage,\n systemPrompt: extractResponsesSystemPrompt(params),\n temperature: params.temperature as number | undefined,\n maxOutputTokens: params.max_output_tokens as number | undefined,\n topP: params.top_p as number | undefined,\n });\n }\n }\n\n private _withContextHeaders(\n params: Record<string, unknown>,\n ): Record<string, unknown> {\n if (!this._propagateContext) return params;\n const existing = (params.extra_headers ?? params.headers) as\n | Record<string, string>\n | undefined;\n const injected = injectContext(existing);\n return {\n ...params,\n extra_headers: injected,\n };\n }\n\n private _trackInputMessages(\n input: unknown,\n ctx: ProviderTrackOptions,\n shouldTrackInputMessages: boolean,\n ): void {\n if (!shouldTrackInputMessages) return;\n if (ctx.userId == null || ctx.sessionId == null) return;\n for (const text of extractResponsesUserInputs(input)) {\n if (!text) continue;\n trackUserMessage({\n amplitude: this._amplitude,\n userId: ctx.userId,\n messageContent: text,\n sessionId: ctx.sessionId,\n traceId: ctx.traceId,\n turnId: ctx.turnId ?? undefined,\n messageSource: ctx.parentAgentId ? 'agent' : 'user',\n agentId: ctx.agentId,\n parentAgentId: ctx.parentAgentId,\n customerOrgId: ctx.customerOrgId,\n agentVersion: ctx.agentVersion,\n context: ctx.context,\n env: ctx.env,\n groups: ctx.groups,\n eventProperties: ctx.eventProperties,\n privacyConfig: this._privacyConfig,\n });\n }\n }\n}\n\nfunction _isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value != null &&\n typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] ===\n 'function'\n );\n}\n\nexport function extractSystemPrompt(\n params: Record<string, unknown>,\n): string | undefined {\n const messages = params.messages as\n | Array<Record<string, unknown>>\n | undefined;\n if (!messages?.length) return undefined;\n const systemMsg = messages.find(\n (m) => m.role === 'system' || m.role === 'developer',\n );\n return systemMsg ? String(systemMsg.content ?? '') : undefined;\n}\n\nfunction extractResponsesSystemPrompt(\n params: Record<string, unknown>,\n): string | undefined {\n const instructions = params.instructions;\n return typeof instructions === 'string' ? instructions : undefined;\n}\n\nfunction extractResponsesFinishReason(\n resp: OpenAIResponse,\n): string | undefined {\n const status = resp.status;\n if (typeof status === 'string' && status.length > 0) return status;\n const out = resp.output?.[0];\n if (out != null && typeof out.status === 'string') return out.status;\n return undefined;\n}\n\nfunction extractResponsesText(resp: OpenAIResponse): string {\n if (typeof resp.output_text === 'string') return resp.output_text;\n const outputs = resp.output ?? [];\n let text = '';\n for (const item of outputs) {\n text += extractOutputItemText(item);\n }\n return text;\n}\n\nfunction extractResponsesToolCalls(\n resp: OpenAIResponse,\n): Array<Record<string, unknown>> {\n const toolCalls: Array<Record<string, unknown>> = [];\n const outputs = resp.output ?? [];\n for (const item of outputs) {\n if (!Array.isArray(item.content)) continue;\n for (const contentItem of item.content) {\n if (\n contentItem?.type === 'tool_call' ||\n contentItem?.type === 'function_call'\n ) {\n toolCalls.push(contentItem as Record<string, unknown>);\n }\n }\n }\n return toolCalls;\n}\n\nfunction extractOutputItemText(item: OpenAIResponseOutputItem): string {\n if (!Array.isArray(item.content)) return '';\n let text = '';\n for (const c of item.content) {\n if (typeof c?.text === 'string') text += c.text;\n }\n return text;\n}\n\nfunction extractResponsesUserInputs(input: unknown): string[] {\n if (typeof input === 'string') return [input];\n if (!Array.isArray(input)) return [];\n\n const result: string[] = [];\n for (const entry of input as OpenAIResponseInput[]) {\n if (typeof entry === 'string') {\n result.push(entry);\n continue;\n }\n const role = entry.role;\n if (role !== 'user') continue;\n const content = entry.content;\n if (typeof content === 'string') {\n result.push(content);\n } else if (Array.isArray(content)) {\n for (const part of content) {\n if (typeof part?.text === 'string') result.push(part.text);\n }\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;AAgCA,MAAM,YAAY,WAAW,SAAS;AACtC,MAAa,mBAAmB,aAAa;AAC7C,MAAMA,gBAAgD;AActD,IAAa,SAAb,cAEU,eAAe;CACvB,AAA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,0BACP,MACgC;CAChC,MAAMC,YAA4C,EAAE;CACpD,MAAM,UAAU,KAAK,UAAU,EAAE;AACjC,MAAK,MAAM,QAAQ,SAAS;AAC1B,MAAI,CAAC,MAAM,QAAQ,KAAK,QAAQ,CAAE;AAClC,OAAK,MAAM,eAAe,KAAK,QAC7B,KACE,aAAa,SAAS,eACtB,aAAa,SAAS,gBAEtB,WAAU,KAAK,YAAuC;;AAI5D,QAAO;;AAGT,SAAS,sBAAsB,MAAwC;AACrE,KAAI,CAAC,MAAM,QAAQ,KAAK,QAAQ,CAAE,QAAO;CACzC,IAAI,OAAO;AACX,MAAK,MAAM,KAAK,KAAK,QACnB,KAAI,OAAO,GAAG,SAAS,SAAU,SAAQ,EAAE;AAE7C,QAAO;;AAGT,SAAS,2BAA2B,OAA0B;AAC5D,KAAI,OAAO,UAAU,SAAU,QAAO,CAAC,MAAM;AAC7C,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO,EAAE;CAEpC,MAAMC,SAAmB,EAAE;AAC3B,MAAK,MAAM,SAAS,OAAgC;AAClD,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAO,KAAK,MAAM;AAClB;;AAGF,MADa,MAAM,SACN,OAAQ;EACrB,MAAM,UAAU,MAAM;AACtB,MAAI,OAAO,YAAY,SACrB,QAAO,KAAK,QAAQ;WACX,MAAM,QAAQ,QAAQ,EAC/B;QAAK,MAAM,QAAQ,QACjB,KAAI,OAAO,MAAM,SAAS,SAAU,QAAO,KAAK,KAAK,KAAK;;;AAIhE,QAAO"}
@@ -0,0 +1,19 @@
1
+ //#region src/serverless.d.ts
2
+ /**
3
+ * Serverless environment detection.
4
+ *
5
+ * Used to auto-enable session flush and generate warnings when events
6
+ * might be lost due to the runtime freezing before the flush interval fires.
7
+ */
8
+ /**
9
+ * Detect whether the current process is running in a serverless environment.
10
+ *
11
+ * Checks well-known environment variables set by major serverless platforms.
12
+ * Result is cached after the first call.
13
+ */
14
+ declare function isServerless(): boolean;
15
+ /** Reset the cached result (for testing). */
16
+ declare function _resetServerlessCache(): void;
17
+ //#endregion
18
+ export { _resetServerlessCache, isServerless };
19
+ //# sourceMappingURL=serverless.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverless.d.ts","names":[],"sources":["../src/serverless.ts"],"sourcesContent":[],"mappings":";;AAwBA;AASA;;;;;;;;;;iBATgB,YAAA,CAAA;;iBASA,qBAAA,CAAA"}
@@ -0,0 +1,35 @@
1
+ //#region src/serverless.ts
2
+ /**
3
+ * Serverless environment detection.
4
+ *
5
+ * Used to auto-enable session flush and generate warnings when events
6
+ * might be lost due to the runtime freezing before the flush interval fires.
7
+ */
8
+ const SERVERLESS_ENV_VARS = [
9
+ "AWS_LAMBDA_FUNCTION_NAME",
10
+ "VERCEL",
11
+ "NETLIFY",
12
+ "FUNCTION_TARGET",
13
+ "WEBSITE_INSTANCE_ID",
14
+ "CF_PAGES"
15
+ ];
16
+ let _cached = null;
17
+ /**
18
+ * Detect whether the current process is running in a serverless environment.
19
+ *
20
+ * Checks well-known environment variables set by major serverless platforms.
21
+ * Result is cached after the first call.
22
+ */
23
+ function isServerless() {
24
+ if (_cached != null) return _cached;
25
+ _cached = SERVERLESS_ENV_VARS.some((v) => process.env[v] != null && process.env[v] !== "");
26
+ return _cached;
27
+ }
28
+ /** Reset the cached result (for testing). */
29
+ function _resetServerlessCache() {
30
+ _cached = null;
31
+ }
32
+
33
+ //#endregion
34
+ export { _resetServerlessCache, isServerless };
35
+ //# sourceMappingURL=serverless.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"serverless.js","names":["_cached: boolean | null"],"sources":["../src/serverless.ts"],"sourcesContent":["/**\n * Serverless environment detection.\n *\n * Used to auto-enable session flush and generate warnings when events\n * might be lost due to the runtime freezing before the flush interval fires.\n */\n\nconst SERVERLESS_ENV_VARS = [\n 'AWS_LAMBDA_FUNCTION_NAME', // AWS Lambda\n 'VERCEL', // Vercel Functions\n 'NETLIFY', // Netlify Functions\n 'FUNCTION_TARGET', // Google Cloud Functions\n 'WEBSITE_INSTANCE_ID', // Azure Functions\n 'CF_PAGES', // Cloudflare Pages Functions\n] as const;\n\nlet _cached: boolean | null = null;\n\n/**\n * Detect whether the current process is running in a serverless environment.\n *\n * Checks well-known environment variables set by major serverless platforms.\n * Result is cached after the first call.\n */\nexport function isServerless(): boolean {\n if (_cached != null) return _cached;\n _cached = SERVERLESS_ENV_VARS.some(\n (v) => process.env[v] != null && process.env[v] !== '',\n );\n return _cached;\n}\n\n/** Reset the cached result (for testing). */\nexport function _resetServerlessCache(): void {\n _cached = null;\n}\n"],"mappings":";;;;;;;AAOA,MAAM,sBAAsB;CAC1B;CACA;CACA;CACA;CACA;CACA;CACD;AAED,IAAIA,UAA0B;;;;;;;AAQ9B,SAAgB,eAAwB;AACtC,KAAI,WAAW,KAAM,QAAO;AAC5B,WAAU,oBAAoB,MAC3B,MAAM,QAAQ,IAAI,MAAM,QAAQ,QAAQ,IAAI,OAAO,GACrD;AACD,QAAO;;;AAIT,SAAgB,wBAA8B;AAC5C,WAAU"}
package/dist/session.d.ts CHANGED
@@ -3,6 +3,21 @@ import { AiMessageOpts, BoundAgent, EmbeddingOpts, ScoreOpts, SpanOpts, ToolCall
3
3
 
4
4
  //#region src/session.d.ts
5
5
 
6
+ interface SessionOptions {
7
+ sessionId?: string | null;
8
+ idleTimeoutMinutes?: number | null;
9
+ userId?: string | null;
10
+ deviceId?: string | null;
11
+ browserSessionId?: string | null;
12
+ /**
13
+ * Automatically flush pending events when `run()` completes.
14
+ *
15
+ * - `true` — always flush (recommended for serverless)
16
+ * - `false` — never flush (for long-running servers where the periodic timer handles it)
17
+ * - `undefined` (default) — auto-detect: flush if a serverless environment is detected
18
+ */
19
+ autoFlush?: boolean;
20
+ }
6
21
  declare class Session {
7
22
  readonly sessionId: string;
8
23
  traceId: string | null;
@@ -10,22 +25,22 @@ declare class Session {
10
25
  readonly userId: string | null;
11
26
  readonly deviceId: string | null;
12
27
  readonly browserSessionId: string | null;
28
+ readonly autoFlush: boolean;
13
29
  private _agent;
14
30
  private _enrichments;
15
31
  private _sessionReplayId;
16
- constructor(agent: BoundAgent, opts?: {
17
- sessionId?: string | null;
18
- idleTimeoutMinutes?: number | null;
19
- userId?: string | null;
20
- deviceId?: string | null;
21
- browserSessionId?: string | null;
22
- });
32
+ constructor(agent: BoundAgent, opts?: SessionOptions);
23
33
  private _buildSessionContext;
24
34
  newTrace(): string;
25
35
  setEnrichments(enrichments: SessionEnrichments): void;
26
36
  /**
27
37
  * Run a callback within this session context.
28
38
  * This is the Node.js equivalent of Python's `with session as s:` block.
39
+ *
40
+ * When {@link autoFlush} is `true` (default in serverless environments),
41
+ * all pending events are flushed before the promise resolves. This
42
+ * prevents event loss when the serverless runtime freezes or terminates
43
+ * after the handler returns.
29
44
  */
30
45
  run<T>(fn: (session: Session) => T | Promise<T>): Promise<T>;
31
46
  /**
@@ -56,6 +71,7 @@ declare class Session {
56
71
  */
57
72
  runAsSync<T>(childAgent: BoundAgent, fn: (session: Session) => T): T;
58
73
  private _autoEnd;
74
+ private _flush;
59
75
  private _inject;
60
76
  trackUserMessage(content: string, opts?: UserMessageOpts): string;
61
77
  trackAiMessage(content: string, model: string, provider: string, latencyMs: number, opts?: AiMessageOpts): string;
@@ -65,5 +81,5 @@ declare class Session {
65
81
  score(name: string, value: number, targetId: string, opts?: ScoreOpts): void;
66
82
  }
67
83
  //#endregion
68
- export { Session };
84
+ export { Session, SessionOptions };
69
85
  //# sourceMappingURL=session.d.ts.map