@umituz/web-ai 1.0.9 → 1.0.10

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 (43) hide show
  1. package/dist/{AIErrors-CSk4nvN1.d.ts → AIErrors-TuSFl--T.d.ts} +1 -1
  2. package/dist/{AIErrors-Dq9o95R_.d.cts → AIErrors-_IyXRWj1.d.cts} +1 -1
  3. package/dist/{cancellation-error-CpkPd67D.d.cts → cancellation-error-_39nYWwz.d.cts} +3 -3
  4. package/dist/{cancellation-error-Ci8fQhNF.d.ts → cancellation-error-hYcE9AS9.d.ts} +3 -3
  5. package/dist/chat/index.d.cts +4 -4
  6. package/dist/chat/index.d.ts +4 -4
  7. package/dist/{chat.service-BRtiA7H9.d.cts → chat.service-8MaW9pum.d.cts} +2 -2
  8. package/dist/{chat.service-Cqga2h1e.d.ts → chat.service-B4Isrckn.d.ts} +2 -2
  9. package/dist/content/index.d.cts +7 -7
  10. package/dist/content/index.d.ts +7 -7
  11. package/dist/core/index.cjs +6 -4
  12. package/dist/core/index.cjs.map +1 -1
  13. package/dist/core/index.d.cts +7 -26
  14. package/dist/core/index.d.ts +7 -26
  15. package/dist/core/index.js +6 -4
  16. package/dist/core/index.js.map +1 -1
  17. package/dist/{create-ai-DW7eHMBF.d.ts → create-ai-D-oEWzf9.d.ts} +3 -3
  18. package/dist/{create-ai-DeOpUgZ-.d.cts → create-ai-DRysRImc.d.cts} +3 -3
  19. package/dist/hooks/index.d.cts +9 -9
  20. package/dist/hooks/index.d.ts +9 -9
  21. package/dist/{index-Ca5o4gBK.d.ts → index-1e91KRYU.d.ts} +1 -1
  22. package/dist/{index-itgxPeLz.d.cts → index-Dv8gRzAu.d.cts} +1 -1
  23. package/dist/{index-DDzvTDg0.d.ts → index-OhvYUTXf.d.cts} +1 -2
  24. package/dist/{index-DDzvTDg0.d.cts → index-OhvYUTXf.d.ts} +1 -2
  25. package/dist/index.cjs +305 -4
  26. package/dist/index.cjs.map +1 -1
  27. package/dist/index.d.cts +11 -11
  28. package/dist/index.d.ts +11 -11
  29. package/dist/index.js +304 -5
  30. package/dist/index.js.map +1 -1
  31. package/dist/{provider.factory-CJuI08Xr.d.ts → provider.factory-B9RNUTYj.d.ts} +1 -1
  32. package/dist/{provider.factory-DG2CYFgh.d.cts → provider.factory-Ce6Een1G.d.cts} +1 -1
  33. package/dist/providers/index.cjs +381 -0
  34. package/dist/providers/index.cjs.map +1 -1
  35. package/dist/providers/index.d.cts +61 -11
  36. package/dist/providers/index.d.ts +61 -11
  37. package/dist/providers/index.js +380 -1
  38. package/dist/providers/index.js.map +1 -1
  39. package/dist/{requestQueue-D-RCbxuR.d.ts → requestQueue-AP6n_bRH.d.ts} +4 -4
  40. package/dist/{requestQueue-O6f8VBl5.d.cts → requestQueue-D89wx91Q.d.cts} +4 -4
  41. package/dist/{request-deduplicator.util-NDo0_n1y.d.cts → tool-call-accumulator-C7KhaXZA.d.cts} +20 -1
  42. package/dist/{request-deduplicator.util-NDo0_n1y.d.ts → tool-call-accumulator-C7KhaXZA.d.ts} +20 -1
  43. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
- import { b as TextTier } from './index-DDzvTDg0.js';
2
- import { e as ProviderFactory } from './provider.factory-CJuI08Xr.js';
3
- import { c as TierModelMap } from './index-Ca5o4gBK.js';
1
+ import { b as TextTier } from './index-OhvYUTXf.js';
2
+ import { e as ProviderFactory } from './provider.factory-B9RNUTYj.js';
3
+ import { c as TierModelMap } from './index-1e91KRYU.js';
4
4
  import { c as GeminiConfig, F as FalConfig, P as PrunaConfig } from './ProviderConfig-DIFa9nmG.js';
5
5
 
6
6
  declare const ANTHROPIC_MODELS: {
@@ -1,6 +1,6 @@
1
- import { b as TextTier } from './index-DDzvTDg0.cjs';
2
- import { e as ProviderFactory } from './provider.factory-DG2CYFgh.cjs';
3
- import { c as TierModelMap } from './index-itgxPeLz.cjs';
1
+ import { b as TextTier } from './index-OhvYUTXf.cjs';
2
+ import { e as ProviderFactory } from './provider.factory-Ce6Een1G.cjs';
3
+ import { c as TierModelMap } from './index-Dv8gRzAu.cjs';
4
4
  import { c as GeminiConfig, F as FalConfig, P as PrunaConfig } from './ProviderConfig-DIFa9nmG.cjs';
5
5
 
6
6
  declare const ANTHROPIC_MODELS: {
@@ -1,15 +1,15 @@
1
1
  import { B as BlogGenerationRequest, G as GeneratedBlog, m as SocialContentRequest, h as GeneratedSocialContent, c as ContentTone, q as VideoScriptRequest, i as GeneratedVideoScript, b as ContentCalendarEntry, E as Emotion, f as ContentWizardStep, e as ContentWizardData, k as ImageWizardStep, j as ImageWizardData, s as VideoWizardStep, r as VideoWizardData } from '../index-BulSkB2L.cjs';
2
- import { d as AIErrorCode, t as SentimentAnalysisResult, C as ContentAnalysisRequest, g as ContentAnalysisResult, S as SEOOptimizationRequest, q as SEOOptimizationResult, r as SEOScoreBreakdown, b as ABTestRequest, a as ABTestPrediction, A as ABTestComparison, G as GenerationResult, k as GenerationProgress, l as GenerationStatus, n as ImageGenerationInput, v as VideoGenerationInput, m as GenerationType, o as ImageQuality, w as VideoQuality } from '../AIErrors-Dq9o95R_.cjs';
3
- export { f as AspectRatio, h as CreditCost, i as GENERATION_COSTS, j as GenerationMetadata, x as calculateCreditCost } from '../AIErrors-Dq9o95R_.cjs';
2
+ import { d as AIErrorCode, t as SentimentAnalysisResult, C as ContentAnalysisRequest, g as ContentAnalysisResult, S as SEOOptimizationRequest, q as SEOOptimizationResult, r as SEOScoreBreakdown, b as ABTestRequest, a as ABTestPrediction, A as ABTestComparison, G as GenerationResult, k as GenerationProgress, l as GenerationStatus, n as ImageGenerationInput, v as VideoGenerationInput, m as GenerationType, o as ImageQuality, w as VideoQuality } from '../AIErrors-_IyXRWj1.cjs';
3
+ export { f as AspectRatio, h as CreditCost, i as GENERATION_COSTS, j as GenerationMetadata, x as calculateCreditCost } from '../AIErrors-_IyXRWj1.cjs';
4
4
  import { d as ProviderConfig, I as ImageGenerationRequest, G as GeneratedContent, V as VideoGenerationRequest, a as ImageToVideoRequest, b as VideoToVideoRequest } from '../ProviderConfig-DIFa9nmG.cjs';
5
- import { c as ITextGenerator, d as ITextProvider, e as ProviderFactory } from '../provider.factory-DG2CYFgh.cjs';
6
- import { A as AIProviderConfig, q as GroqGenerationConfig } from '../create-ai-DeOpUgZ-.cjs';
7
- import { b as TextTier } from '../index-DDzvTDg0.cjs';
5
+ import { c as ITextGenerator, d as ITextProvider, e as ProviderFactory } from '../provider.factory-Ce6Een1G.cjs';
6
+ import { A as AIProviderConfig, q as GroqGenerationConfig } from '../create-ai-DRysRImc.cjs';
7
+ import { b as TextTier } from '../index-OhvYUTXf.cjs';
8
8
  import { C as CacheManager, b as CacheStats } from '../cache-manager-Df9LLYGA.cjs';
9
- import { d as ChatService, U as UseChatOptions, k as UseChatReturn } from '../chat.service-BRtiA7H9.cjs';
10
- import { T as TextGenerationService, j as PrunaResult, G as GenerateOptions, e as PrunaInput, a as GenerationStage } from '../cancellation-error-CpkPd67D.cjs';
11
- export { C as CancellationError } from '../cancellation-error-CpkPd67D.cjs';
12
- import '../index-itgxPeLz.cjs';
9
+ import { d as ChatService, U as UseChatOptions, k as UseChatReturn } from '../chat.service-8MaW9pum.cjs';
10
+ import { T as TextGenerationService, j as PrunaResult, G as GenerateOptions, e as PrunaInput, a as GenerationStage } from '../cancellation-error-_39nYWwz.cjs';
11
+ export { C as CancellationError } from '../cancellation-error-_39nYWwz.cjs';
12
+ import '../index-Dv8gRzAu.cjs';
13
13
 
14
14
  /** Provider config for the underlying AIContentService — new AIProviderConfig,
15
15
  * legacy ProviderConfig, or a custom ITextGenerator. */
@@ -1,15 +1,15 @@
1
1
  import { B as BlogGenerationRequest, G as GeneratedBlog, m as SocialContentRequest, h as GeneratedSocialContent, c as ContentTone, q as VideoScriptRequest, i as GeneratedVideoScript, b as ContentCalendarEntry, E as Emotion, f as ContentWizardStep, e as ContentWizardData, k as ImageWizardStep, j as ImageWizardData, s as VideoWizardStep, r as VideoWizardData } from '../index-BUVULo3h.js';
2
- import { d as AIErrorCode, t as SentimentAnalysisResult, C as ContentAnalysisRequest, g as ContentAnalysisResult, S as SEOOptimizationRequest, q as SEOOptimizationResult, r as SEOScoreBreakdown, b as ABTestRequest, a as ABTestPrediction, A as ABTestComparison, G as GenerationResult, k as GenerationProgress, l as GenerationStatus, n as ImageGenerationInput, v as VideoGenerationInput, m as GenerationType, o as ImageQuality, w as VideoQuality } from '../AIErrors-CSk4nvN1.js';
3
- export { f as AspectRatio, h as CreditCost, i as GENERATION_COSTS, j as GenerationMetadata, x as calculateCreditCost } from '../AIErrors-CSk4nvN1.js';
2
+ import { d as AIErrorCode, t as SentimentAnalysisResult, C as ContentAnalysisRequest, g as ContentAnalysisResult, S as SEOOptimizationRequest, q as SEOOptimizationResult, r as SEOScoreBreakdown, b as ABTestRequest, a as ABTestPrediction, A as ABTestComparison, G as GenerationResult, k as GenerationProgress, l as GenerationStatus, n as ImageGenerationInput, v as VideoGenerationInput, m as GenerationType, o as ImageQuality, w as VideoQuality } from '../AIErrors-TuSFl--T.js';
3
+ export { f as AspectRatio, h as CreditCost, i as GENERATION_COSTS, j as GenerationMetadata, x as calculateCreditCost } from '../AIErrors-TuSFl--T.js';
4
4
  import { d as ProviderConfig, I as ImageGenerationRequest, G as GeneratedContent, V as VideoGenerationRequest, a as ImageToVideoRequest, b as VideoToVideoRequest } from '../ProviderConfig-DIFa9nmG.js';
5
- import { c as ITextGenerator, d as ITextProvider, e as ProviderFactory } from '../provider.factory-CJuI08Xr.js';
6
- import { A as AIProviderConfig, q as GroqGenerationConfig } from '../create-ai-DW7eHMBF.js';
7
- import { b as TextTier } from '../index-DDzvTDg0.js';
5
+ import { c as ITextGenerator, d as ITextProvider, e as ProviderFactory } from '../provider.factory-B9RNUTYj.js';
6
+ import { A as AIProviderConfig, q as GroqGenerationConfig } from '../create-ai-D-oEWzf9.js';
7
+ import { b as TextTier } from '../index-OhvYUTXf.js';
8
8
  import { C as CacheManager, b as CacheStats } from '../cache-manager-Df9LLYGA.js';
9
- import { d as ChatService, U as UseChatOptions, k as UseChatReturn } from '../chat.service-Cqga2h1e.js';
10
- import { T as TextGenerationService, j as PrunaResult, G as GenerateOptions, e as PrunaInput, a as GenerationStage } from '../cancellation-error-Ci8fQhNF.js';
11
- export { C as CancellationError } from '../cancellation-error-Ci8fQhNF.js';
12
- import '../index-Ca5o4gBK.js';
9
+ import { d as ChatService, U as UseChatOptions, k as UseChatReturn } from '../chat.service-B4Isrckn.js';
10
+ import { T as TextGenerationService, j as PrunaResult, G as GenerateOptions, e as PrunaInput, a as GenerationStage } from '../cancellation-error-hYcE9AS9.js';
11
+ export { C as CancellationError } from '../cancellation-error-hYcE9AS9.js';
12
+ import '../index-1e91KRYU.js';
13
13
 
14
14
  /** Provider config for the underlying AIContentService — new AIProviderConfig,
15
15
  * legacy ProviderConfig, or a custom ITextGenerator. */
@@ -1,4 +1,4 @@
1
- import { b as TextTier } from './index-DDzvTDg0.js';
1
+ import { b as TextTier } from './index-OhvYUTXf.js';
2
2
 
3
3
  declare enum AIErrorType {
4
4
  INVALID_API_KEY = "INVALID_API_KEY",
@@ -1,4 +1,4 @@
1
- import { b as TextTier } from './index-DDzvTDg0.cjs';
1
+ import { b as TextTier } from './index-OhvYUTXf.cjs';
2
2
 
3
3
  declare enum AIErrorType {
4
4
  INVALID_API_KEY = "INVALID_API_KEY",
@@ -13,8 +13,8 @@ interface TokenUsage {
13
13
  readonly inputTokens: number;
14
14
  readonly outputTokens: number;
15
15
  readonly totalTokens?: number;
16
+ readonly reasoningTokens?: number;
16
17
  }
17
- /** What every text-generating method returns — usage is never discarded. */
18
18
  interface GenerationResult {
19
19
  readonly text: string;
20
20
  readonly usage?: TokenUsage;
@@ -22,7 +22,6 @@ interface GenerationResult {
22
22
  readonly providerId: string;
23
23
  readonly finishReason?: FinishReason;
24
24
  }
25
- /** Universal chat message shape; providers translate to their own wire format. */
26
25
  interface ChatMessage {
27
26
  readonly role: "system" | "user" | "assistant";
28
27
  readonly content: string;
@@ -13,8 +13,8 @@ interface TokenUsage {
13
13
  readonly inputTokens: number;
14
14
  readonly outputTokens: number;
15
15
  readonly totalTokens?: number;
16
+ readonly reasoningTokens?: number;
16
17
  }
17
- /** What every text-generating method returns — usage is never discarded. */
18
18
  interface GenerationResult {
19
19
  readonly text: string;
20
20
  readonly usage?: TokenUsage;
@@ -22,7 +22,6 @@ interface GenerationResult {
22
22
  readonly providerId: string;
23
23
  readonly finishReason?: FinishReason;
24
24
  }
25
- /** Universal chat message shape; providers translate to their own wire format. */
26
25
  interface ChatMessage {
27
26
  readonly role: "system" | "user" | "assistant";
28
27
  readonly content: string;
package/dist/index.cjs CHANGED
@@ -1453,17 +1453,19 @@ function buildSystemPrompt(input = {}) {
1453
1453
  const now = input.now ?? /* @__PURE__ */ new Date();
1454
1454
  const identity = input.identity ?? DEFAULT_AI_IDENTITY;
1455
1455
  const parts = [identity, `Current date: ${now.toISOString().slice(0, 10)}.`];
1456
+ const projectName = input.project?.name;
1456
1457
  const projectInstructions = input.project?.instructions?.trim();
1457
- if (projectInstructions) {
1458
+ if (projectName && projectInstructions) {
1458
1459
  parts.push(
1459
- `The user is working inside the project "${input.project.name}". Follow these project instructions:
1460
+ `The user is working inside the project "${projectName}". Follow these project instructions:
1460
1461
  ${projectInstructions}`
1461
1462
  );
1462
1463
  }
1464
+ const agentName = input.agent?.name;
1463
1465
  const agentInstructions = input.agent?.instructions?.trim();
1464
- if (agentInstructions) {
1466
+ if (agentName && agentInstructions) {
1465
1467
  parts.push(
1466
- `You are operating as the agent "${input.agent.name}". Follow these agent instructions:
1468
+ `You are operating as the agent "${agentName}". Follow these agent instructions:
1467
1469
  ${agentInstructions}`
1468
1470
  );
1469
1471
  }
@@ -5510,6 +5512,303 @@ function createOpenAiImageAdapter(config) {
5510
5512
  };
5511
5513
  }
5512
5514
 
5515
+ // src/providers/adapters/openai-compatible.adapter.ts
5516
+ function toWireMessage(message) {
5517
+ if (message.role === "tool") {
5518
+ return { role: "tool", content: message.content, tool_call_id: message.toolCallId ?? "" };
5519
+ }
5520
+ if (message.role === "assistant" && message.toolCalls && message.toolCalls.length > 0) {
5521
+ return {
5522
+ role: "assistant",
5523
+ content: message.content,
5524
+ tool_calls: message.toolCalls.map((call) => ({
5525
+ id: call.id,
5526
+ type: "function",
5527
+ function: { name: call.name, arguments: call.arguments }
5528
+ }))
5529
+ };
5530
+ }
5531
+ if (message.role === "user") return { role: "user", content: message.content };
5532
+ return { role: message.role, content: message.content };
5533
+ }
5534
+ function mergeImages(messages, images) {
5535
+ if (images.length === 0) return [...messages];
5536
+ const parts = images.map((image) => ({
5537
+ type: "image_url",
5538
+ image_url: { url: `data:${image.mimeType};base64,${image.dataBase64}` }
5539
+ }));
5540
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
5541
+ const message = messages[index];
5542
+ if (message.role !== "user") continue;
5543
+ const textParts = typeof message.content === "string" ? message.content.length > 0 ? [{ type: "text", text: message.content }] : [] : message.content;
5544
+ return [
5545
+ ...messages.slice(0, index),
5546
+ { role: "user", content: [...textParts, ...parts] },
5547
+ ...messages.slice(index + 1)
5548
+ ];
5549
+ }
5550
+ return [...messages, { role: "user", content: [...parts] }];
5551
+ }
5552
+ async function extractErrorDetail(response) {
5553
+ try {
5554
+ const body = await response.json();
5555
+ return body.error;
5556
+ } catch {
5557
+ return void 0;
5558
+ }
5559
+ }
5560
+ async function* parseSseEvent2(rawEvent, toolCallAccumulator) {
5561
+ for (const line of rawEvent.split("\n")) {
5562
+ if (!line.startsWith("data:")) continue;
5563
+ const payload = line.slice(5).trim();
5564
+ if (payload.length === 0 || payload === "[DONE]") continue;
5565
+ let chunk;
5566
+ try {
5567
+ chunk = JSON.parse(payload);
5568
+ } catch {
5569
+ continue;
5570
+ }
5571
+ const delta = chunk.choices?.[0]?.delta;
5572
+ if (delta?.reasoning) {
5573
+ yield { type: "delta", channel: "reasoning", text: delta.reasoning };
5574
+ }
5575
+ if (delta?.content) {
5576
+ yield { type: "delta", channel: "answer", text: delta.content };
5577
+ }
5578
+ if (delta?.tool_calls) {
5579
+ for (const toolCallDelta of delta.tool_calls) toolCallAccumulator.push(toolCallDelta);
5580
+ }
5581
+ if (chunk.usage) {
5582
+ yield {
5583
+ type: "usage",
5584
+ usage: {
5585
+ inputTokens: chunk.usage.prompt_tokens ?? 0,
5586
+ outputTokens: chunk.usage.completion_tokens ?? 0,
5587
+ reasoningTokens: chunk.usage.completion_tokens_details?.reasoning_tokens
5588
+ }
5589
+ };
5590
+ }
5591
+ }
5592
+ }
5593
+ async function* parseSseStream(body) {
5594
+ const reader = body.getReader();
5595
+ const decoder = new TextDecoder();
5596
+ const toolCallAccumulator = new ToolCallAccumulator();
5597
+ let buffer = "";
5598
+ try {
5599
+ while (true) {
5600
+ const { done, value } = await reader.read();
5601
+ if (done) break;
5602
+ buffer += decoder.decode(value, { stream: true });
5603
+ let separator = buffer.indexOf("\n\n");
5604
+ while (separator !== -1) {
5605
+ const rawEvent = buffer.slice(0, separator);
5606
+ buffer = buffer.slice(separator + 2);
5607
+ separator = buffer.indexOf("\n\n");
5608
+ yield* parseSseEvent2(rawEvent, toolCallAccumulator);
5609
+ }
5610
+ }
5611
+ } catch (err) {
5612
+ throw errorFromUnknown(err);
5613
+ } finally {
5614
+ reader.releaseLock();
5615
+ }
5616
+ const calls = toolCallAccumulator.finish();
5617
+ if (calls.length > 0) yield { type: "tool_calls", calls };
5618
+ }
5619
+ function createOpenAiCompatibleAdapter(config) {
5620
+ return {
5621
+ async *stream(req) {
5622
+ const timeout = AbortSignal.timeout(config.timeoutMs);
5623
+ const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout;
5624
+ let response;
5625
+ try {
5626
+ response = await fetch(`${config.baseUrl}/chat/completions`, {
5627
+ method: "POST",
5628
+ headers: {
5629
+ Authorization: `Bearer ${config.apiKey}`,
5630
+ "Content-Type": "application/json"
5631
+ },
5632
+ body: JSON.stringify({
5633
+ model: req.externalModelId,
5634
+ messages: mergeImages(req.messages.map(toWireMessage), req.images ?? []),
5635
+ temperature: req.temperature,
5636
+ max_completion_tokens: req.maxOutputTokens,
5637
+ top_p: req.topP,
5638
+ stream: true,
5639
+ stream_options: { include_usage: true },
5640
+ ...req.tools && req.tools.length > 0 ? {
5641
+ tools: req.tools.map((tool) => ({ type: "function", function: tool })),
5642
+ tool_choice: "auto"
5643
+ } : {}
5644
+ }),
5645
+ signal
5646
+ });
5647
+ } catch (err) {
5648
+ throw errorFromUnknown(err);
5649
+ }
5650
+ if (!response.ok || !response.body) {
5651
+ const detail = await extractErrorDetail(response);
5652
+ throw errorFromStatus(response.status, detail?.message, detail);
5653
+ }
5654
+ yield* parseSseStream(response.body);
5655
+ }
5656
+ };
5657
+ }
5658
+
5659
+ // src/providers/adapters/anthropic.adapter.ts
5660
+ var ANTHROPIC_VERSION = "2023-06-01";
5661
+ var ERROR_TYPE_TO_CODE = {
5662
+ invalid_request_error: "invalid_request",
5663
+ authentication_error: "invalid_key",
5664
+ permission_error: "invalid_key",
5665
+ not_found_error: "model_unavailable",
5666
+ request_too_large: "invalid_request",
5667
+ rate_limit_error: "rate_limited",
5668
+ overloaded_error: "capacity",
5669
+ api_error: "upstream_error"
5670
+ };
5671
+ function mergeImages2(messages, images) {
5672
+ if (images.length === 0) return [...messages];
5673
+ const blocks = images.map((image) => ({
5674
+ type: "image",
5675
+ source: { type: "base64", media_type: image.mimeType, data: image.dataBase64 }
5676
+ }));
5677
+ for (let index = messages.length - 1; index >= 0; index -= 1) {
5678
+ const message = messages[index];
5679
+ if (message.role !== "user") continue;
5680
+ const textBlocks = typeof message.content === "string" ? message.content.length > 0 ? [{ type: "text", text: message.content }] : [] : message.content;
5681
+ return [
5682
+ ...messages.slice(0, index),
5683
+ { role: "user", content: [...textBlocks, ...blocks] },
5684
+ ...messages.slice(index + 1)
5685
+ ];
5686
+ }
5687
+ return [...messages, { role: "user", content: [...blocks] }];
5688
+ }
5689
+ async function extractErrorDetail2(response) {
5690
+ try {
5691
+ const body = await response.json();
5692
+ return body.error?.message;
5693
+ } catch {
5694
+ return void 0;
5695
+ }
5696
+ }
5697
+ function wireError(error) {
5698
+ const code = error.type && ERROR_TYPE_TO_CODE[error.type] || "upstream_error";
5699
+ return new AiError(code, error.message);
5700
+ }
5701
+ function* parseAnthropicEvent(rawEvent) {
5702
+ for (const line of rawEvent.split("\n")) {
5703
+ if (!line.startsWith("data:")) continue;
5704
+ const payload = line.slice(5).trim();
5705
+ if (payload.length === 0) continue;
5706
+ try {
5707
+ yield JSON.parse(payload);
5708
+ } catch {
5709
+ continue;
5710
+ }
5711
+ }
5712
+ }
5713
+ function mergeOutputTokens(previous, outputTokens) {
5714
+ return {
5715
+ inputTokens: previous?.inputTokens ?? 0,
5716
+ outputTokens,
5717
+ reasoningTokens: previous?.reasoningTokens
5718
+ };
5719
+ }
5720
+ async function* parseAnthropicStream(body) {
5721
+ const reader = body.getReader();
5722
+ const decoder = new TextDecoder();
5723
+ let buffer = "";
5724
+ let usage = null;
5725
+ let usageEmitted = false;
5726
+ const flushUsage = function* () {
5727
+ if (usage && !usageEmitted && (usage.inputTokens > 0 || usage.outputTokens > 0)) {
5728
+ usageEmitted = true;
5729
+ yield { type: "usage", usage };
5730
+ }
5731
+ };
5732
+ try {
5733
+ while (true) {
5734
+ const { done, value } = await reader.read();
5735
+ if (done) break;
5736
+ buffer += decoder.decode(value, { stream: true });
5737
+ let separator = buffer.indexOf("\n\n");
5738
+ while (separator !== -1) {
5739
+ const rawEvent = buffer.slice(0, separator);
5740
+ buffer = buffer.slice(separator + 2);
5741
+ separator = buffer.indexOf("\n\n");
5742
+ for (const event of parseAnthropicEvent(rawEvent)) {
5743
+ if (event.error) throw wireError(event.error);
5744
+ if (event.type === "message_start" && event.message?.usage) {
5745
+ usage = {
5746
+ inputTokens: event.message.usage.input_tokens ?? 0,
5747
+ outputTokens: 0,
5748
+ reasoningTokens: void 0
5749
+ };
5750
+ } else if (event.type === "message_delta" && event.usage) {
5751
+ usage = mergeOutputTokens(usage, event.usage.output_tokens ?? 0);
5752
+ } else if (event.type === "message_stop") {
5753
+ yield* flushUsage();
5754
+ } else if (event.delta?.type === "text_delta" && event.delta.text) {
5755
+ yield { type: "delta", channel: "answer", text: event.delta.text };
5756
+ } else if (event.delta?.type === "thinking_delta" && event.delta.thinking) {
5757
+ yield { type: "delta", channel: "reasoning", text: event.delta.thinking };
5758
+ }
5759
+ }
5760
+ }
5761
+ }
5762
+ yield* flushUsage();
5763
+ } catch (err) {
5764
+ throw err instanceof AiError ? err : errorFromUnknown(err);
5765
+ } finally {
5766
+ reader.releaseLock();
5767
+ }
5768
+ }
5769
+ function createAnthropicAdapter(config) {
5770
+ return {
5771
+ async *stream(req) {
5772
+ const timeout = AbortSignal.timeout(config.timeoutMs);
5773
+ const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout;
5774
+ const system = req.messages.filter((message) => message.role === "system").map((message) => message.content).join("\n\n");
5775
+ const messages = mergeImages2(
5776
+ req.messages.filter((message) => message.role !== "system").map((message) => {
5777
+ if (message.role === "user") return { role: "user", content: message.content };
5778
+ return { role: "assistant", content: message.content };
5779
+ }),
5780
+ req.images ?? []
5781
+ );
5782
+ let response;
5783
+ try {
5784
+ response = await fetch(`${config.baseUrl}/v1/messages`, {
5785
+ method: "POST",
5786
+ headers: {
5787
+ "x-api-key": config.apiKey,
5788
+ "anthropic-version": ANTHROPIC_VERSION,
5789
+ "Content-Type": "application/json"
5790
+ },
5791
+ body: JSON.stringify({
5792
+ model: req.externalModelId,
5793
+ messages,
5794
+ ...system.length > 0 ? { system } : {},
5795
+ max_tokens: req.maxOutputTokens,
5796
+ stream: true
5797
+ }),
5798
+ signal
5799
+ });
5800
+ } catch (err) {
5801
+ throw errorFromUnknown(err);
5802
+ }
5803
+ if (!response.ok || !response.body) {
5804
+ const detail = await extractErrorDetail2(response);
5805
+ throw errorFromStatus(response.status, detail);
5806
+ }
5807
+ yield* parseAnthropicStream(response.body);
5808
+ }
5809
+ };
5810
+ }
5811
+
5513
5812
  // src/content/domain/calculations/ContentCreditCost.ts
5514
5813
  var CREDIT_COSTS = {
5515
5814
  "text-to-image": { standard: 1, hd: 2, "4k": 4 },
@@ -7268,12 +7567,14 @@ exports.consumeGroqStream = consumeGroqStream;
7268
7567
  exports.cosineSimilarity = cosineSimilarity;
7269
7568
  exports.countChanges = countChanges;
7270
7569
  exports.createAI = createAI;
7570
+ exports.createAnthropicAdapter = createAnthropicAdapter;
7271
7571
  exports.createAssistantMessage = createAssistantMessage;
7272
7572
  exports.createFalProvider = createFalProvider;
7273
7573
  exports.createGeminiProvider = createGeminiProvider;
7274
7574
  exports.createGroqProvider = createGroqProvider;
7275
7575
  exports.createMessage = createMessage;
7276
7576
  exports.createOpenAiAudioTranscriptionAdapter = createOpenAiAudioTranscriptionAdapter;
7577
+ exports.createOpenAiCompatibleAdapter = createOpenAiCompatibleAdapter;
7277
7578
  exports.createOpenAiEmbeddingsAdapter = createOpenAiEmbeddingsAdapter;
7278
7579
  exports.createOpenAiImageAdapter = createOpenAiImageAdapter;
7279
7580
  exports.createOpenAiSpeechAdapter = createOpenAiSpeechAdapter;