{"version":3,"file":"Anthropic.mjs","names":[],"sources":["../src/Anthropic.ts"],"sourcesContent":["import {\n  Context,\n  Effect,\n  Layer,\n  Match,\n  Option,\n  Redacted,\n  Result,\n  Schema,\n  Stream,\n  pipe,\n} from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport {\n  type CommonRequest,\n  LanguageModel,\n  type LanguageModelService,\n  turnFromStream,\n} from \"@effect-uai/core/LanguageModel\"\nimport * as SSE from \"@effect-uai/core/SSE\"\nimport { descriptorsOf, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport { type Turn, TurnEvent } from \"@effect-uai/core/Turn\"\nimport { renderProviderTools } from \"./AnthropicTools.js\"\nimport {\n  type Accumulator,\n  type CacheControl,\n  type CacheTtl,\n  type ThinkingConfig,\n  accumulatorToTurn,\n  buildRequestBody,\n  emptyAccumulator,\n} from \"./codec.js\"\nimport type { AnthropicModel } from \"./models.js\"\nimport { KnownProviderEvent, ProviderEvent, applyEvent } from \"./streamEvents.js\"\n\nexport {\n  codeExecutionTool,\n  webSearchTool,\n  type WebSearchOptions,\n  type UserLocation,\n} from \"./AnthropicTools.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type AnthropicRequest = Omit<CommonRequest, \"model\"> & {\n  /**\n   * Narrows `CommonRequest.model` (`string`) to the typed `AnthropicModel`\n   * literal union for autocomplete.\n   */\n  readonly model: AnthropicModel\n  /**\n   * Top-K nucleus sampling parameter. Anthropic-specific; not exposed on the\n   * common surface.\n   */\n  readonly topK?: number\n  /** Stop sequences that abort generation when matched. */\n  readonly stopSequences?: ReadonlyArray<string>\n  /**\n   * Extended thinking configuration. `0` budget is equivalent to disabled.\n   * Only the `claude-sonnet-4-x`, `claude-haiku-4-x`, and pre-Opus-4.7\n   * model lines support extended thinking.\n   */\n  readonly thinking?: ThinkingConfig\n  /**\n   * `metadata.user_id` on the wire. End-user tracking identifier.\n   */\n  readonly user?: string\n}\n\nexport type AnthropicService = {\n  /**\n   * Stream the provider's native event vocabulary (post-SSE-decode).\n   * Use this when you need full vendor fidelity (e.g. `signature_delta` for\n   * encrypted reasoning state). For provider-portable code, use `streamTurn`.\n   */\n  readonly streamNative: (\n    request: AnthropicRequest,\n  ) => Stream.Stream<ProviderEvent, AiError.AiError>\n  /**\n   * Stream canonical `TurnEvent`s. Implemented as\n   * `streamNative |> toCanonical`.\n   */\n  readonly streamTurn: (request: AnthropicRequest) => Stream.Stream<TurnEvent, AiError.AiError>\n  /**\n   * Drain a single turn and return the assembled `Turn`. Derived from\n   * `streamTurn` — Anthropic's non-streaming `/messages` endpoint\n   * differs from the streamed one in subtle ways (no incremental\n   * thinking deltas), so we route everything through streaming for\n   * consistency.\n   */\n  readonly turn: (request: AnthropicRequest) => Effect.Effect<Turn, AiError.AiError>\n  /**\n   * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n   * Stateful (threads an `Accumulator` for tool-call lookup and\n   * accumulator-to-Turn assembly).\n   */\n  readonly toCanonical: <E, R>(\n    s: Stream.Stream<ProviderEvent, E, R>,\n  ) => Stream.Stream<TurnEvent, E, R>\n}\n\n/**\n * Provider-typed service tag. Yield this when you want Anthropic-specific\n * options (`topK`, `stopSequences`, `thinking`); yield the generic\n * `LanguageModel` tag for provider-portable code. Both are registered by\n * `layer`.\n */\nexport class Anthropic extends Context.Service<Anthropic, AnthropicService>()(\n  \"@betalyra/effect-uai/providers/anthropic/Anthropic\",\n) {}\n\nexport type Config = {\n  readonly apiKey: Redacted.Redacted\n  readonly baseUrl?: string\n  /**\n   * Default `max_tokens` for requests that don't override via\n   * `request.maxOutputTokens`. Anthropic requires this field; we default to\n   * 4096 if neither is set.\n   */\n  readonly defaultMaxTokens?: number\n  /**\n   * Prompt caching. Off by default, so the library stays unopinionated about\n   * a setting that changes billing. `true` is `{}`: cache with the 5-minute\n   * default TTL.\n   *\n   * Anthropic caches the `tools` → `system` → `messages` prefix and moves the\n   * breakpoint forward as the conversation grows, so a long system prompt and\n   * tool definitions are paid for once rather than on every turn. Read\n   * `usage.input_tokens_details.cached_tokens` to see it working.\n   *\n   * Mutating earlier history (rewriting an old message, compaction) breaks\n   * the prefix from that point on. Anthropic falls back to the longest\n   * unchanged prefix, so this costs savings but never correctness.\n   */\n  readonly promptCaching?: boolean | { readonly ttl?: CacheTtl }\n}\n\nconst ANTHROPIC_VERSION = \"2023-06-01\"\nconst STRUCTURED_OUTPUTS_BETA = \"structured-outputs-2025-11-13\"\nconst FALLBACK_MAX_TOKENS = 4096\n\nconst outputConfig = (request: AnthropicRequest): Option.Option<Record<string, unknown>> =>\n  pipe(\n    Option.fromUndefinedOr(request.structured),\n    Option.map((format) => ({\n      format: {\n        type: \"json_schema\",\n        schema: format.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n      },\n    })),\n  )\n\nconst resolvedMaxTokens = (cfg: Config, request: AnthropicRequest): number =>\n  request.maxOutputTokens ?? cfg.defaultMaxTokens ?? FALLBACK_MAX_TOKENS\n\n/**\n * One request-level breakpoint when caching is on. Anthropic places it on the\n * last cacheable block itself, so nothing has to be marked per-block and the\n * breakpoint stays correct as history grows.\n */\nconst cacheControlOf = (cfg: Config): Option.Option<CacheControl> =>\n  pipe(\n    Option.fromUndefinedOr(cfg.promptCaching),\n    Option.flatMap((opt) =>\n      opt === false\n        ? Option.none<CacheControl>()\n        : Option.some<CacheControl>({\n            type: \"ephemeral\",\n            ...(opt !== true && opt.ttl !== undefined && { ttl: opt.ttl }),\n          }),\n    ),\n  )\n\nconst functionToolDescriptors = (\n  request: AnthropicRequest,\n): ReadonlyArray<Record<string, unknown>> =>\n  descriptorsOf(request.tools).map((t) => ({\n    name: t.name,\n    description: t.description,\n    input_schema: t.inputSchema,\n  }))\n\n/**\n * Merge the custom function-tool declarations with the native hosted-tool\n * entries into the single `tools` array Anthropic expects. `providerWire` is\n * pre-rendered (and validated) by the caller.\n */\nconst toolsWire = (\n  request: AnthropicRequest,\n  providerWire: ReadonlyArray<Record<string, unknown>>,\n): Option.Option<ReadonlyArray<Record<string, unknown>>> => {\n  const tools = [...functionToolDescriptors(request), ...providerWire]\n  return tools.length > 0 ? Option.some(tools) : Option.none()\n}\n\nconst toolChoiceWire = (request: AnthropicRequest): Option.Option<Record<string, unknown>> =>\n  pipe(\n    Option.fromUndefinedOr(request.toolChoice),\n    Option.map((choice) =>\n      choice === \"auto\"\n        ? { type: \"auto\" }\n        : choice === \"required\"\n          ? { type: \"any\" }\n          : choice === \"none\"\n            ? { type: \"none\" }\n            : { type: \"tool\", name: choice.name },\n    ),\n  )\n\n// ---------------------------------------------------------------------------\n// SSE event → ProviderEvent\n// ---------------------------------------------------------------------------\n\nconst decodeKnown = Schema.decodeUnknownEffect(KnownProviderEvent)\nconst parseJsonUnknown = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))\n\nconst makeUnknown = (raw: unknown): ProviderEvent => ({ type: \"_unknown\", raw })\n\n/**\n * Parse one SSE event's `data` payload into a typed `ProviderEvent`. Never\n * fails: JSON-parse and schema-decode failures both produce a synthesized\n * `_unknown` event so consumers of `streamNative` never silently miss a\n * wire event we didn't model. When the payload IS valid JSON but doesn't\n * match the known-event schema, `_unknown.raw` carries the parsed value;\n * when JSON parsing fails outright, it carries the raw string.\n */\nconst sseEventToProviderEvent = (ev: SSE.Event): Effect.Effect<ProviderEvent> =>\n  parseJsonUnknown(ev.data).pipe(\n    Effect.flatMap((parsed) =>\n      decodeKnown(parsed).pipe(Effect.orElseSucceed(() => makeUnknown(parsed))),\n    ),\n    Effect.orElseSucceed(() => makeUnknown(ev.data)),\n  )\n\n// ---------------------------------------------------------------------------\n// Per-event derivation of TurnEvents. Drives off the new accumulator and the\n// raw event, since some deltas (`tool_call_args_delta`) need the call_id\n// which lives on the accumulator's per-index block.\n// ---------------------------------------------------------------------------\n\nconst deltasFromEvent = (next: Accumulator, event: ProviderEvent): ReadonlyArray<TurnEvent> =>\n  Match.value(event).pipe(\n    Match.discriminatorsExhaustive(\"type\")({\n      content_block_start: (e) =>\n        e.content_block.type === \"tool_use\"\n          ? [\n              TurnEvent.ToolCallStart({\n                call_id: e.content_block.id,\n                name: e.content_block.name,\n              }),\n            ]\n          : [],\n      content_block_delta: (e) =>\n        Match.value(e.delta).pipe(\n          Match.discriminatorsExhaustive(\"type\")({\n            text_delta: (d) => [TurnEvent.TextDelta({ text: d.text })],\n            thinking_delta: (d) => [TurnEvent.ReasoningDelta({ text: d.thinking, kind: \"trace\" })],\n            input_json_delta: (d) => {\n              const block = next.blocks[e.index]\n              if (block === undefined) return []\n              const callId = Option.getOrElse(block.id, () => \"\")\n              return callId.length === 0\n                ? []\n                : [TurnEvent.ToolCallArgsDelta({ call_id: callId, delta: d.partial_json })]\n            },\n            // Encrypted reasoning state - flows through `streamNative` but has\n            // no canonical representation.\n            signature_delta: () => [],\n          }),\n        ),\n      message_start: (e) =>\n        e.message.usage === undefined ? [] : [TurnEvent.UsageUpdate({ usage: next.usage })],\n      message_delta: (e) =>\n        e.usage === undefined ? [] : [TurnEvent.UsageUpdate({ usage: next.usage })],\n      message_stop: () => [TurnEvent.TurnComplete({ turn: accumulatorToTurn(next) })],\n      content_block_stop: () => [],\n      ping: () => [],\n      error: () => [],\n      _unknown: () => [],\n    }),\n  )\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nconst httpStatusError = (status: number, body: string): AiError.AiError => {\n  const provider = \"anthropic\"\n  const raw = body\n  if (status === 429) return new AiError.RateLimited({ provider, raw })\n  if (status === 408 || status === 504) return new AiError.Timeout({ provider, raw })\n  if (status === 401) return new AiError.AuthFailed({ provider, subtype: \"auth\", raw })\n  if (status === 403) return new AiError.AuthFailed({ provider, subtype: \"permission\", raw })\n  if (status === 402) return new AiError.AuthFailed({ provider, subtype: \"billing\", raw })\n  if (status === 413) return new AiError.ContextLengthExceeded({ provider, raw })\n  if (status === 529) return new AiError.Unavailable({ provider, status, raw })\n  if (status >= 500) return new AiError.Unavailable({ provider, status, raw })\n  return new AiError.InvalidRequest({ provider, raw })\n}\n\nconst buildNativeStream = (cfg: Config) => {\n  const baseUrl = cfg.baseUrl ?? \"https://api.anthropic.com\"\n  const url = `${baseUrl}/v1/messages`\n  return (\n    request: AnthropicRequest,\n  ): Stream.Stream<ProviderEvent, AiError.AiError, HttpClient.HttpClient> =>\n    Stream.unwrap(\n      Effect.gen(function* () {\n        const structured = outputConfig(request)\n        const providerWire = yield* Result.match(\n          renderProviderTools(providerToolsOf(request.tools)),\n          {\n            onFailure: (e) =>\n              Effect.fail(\n                new AiError.Unsupported({\n                  provider: \"anthropic\",\n                  capability: e.capability,\n                  reason: e.reason,\n                }),\n              ),\n            onSuccess: (wire) => Effect.succeed(wire),\n          },\n        )\n        yield* Capabilities.warnDroppedBlocks(request.history, \"output_image\", {\n          provider: \"anthropic\",\n          capability: \"output_image\",\n          reason:\n            \"Assistant messages carry no image on this wire. Use `Turn.imagesAsInput` to resend it as user content.\",\n        })\n        const bodyResult = buildRequestBody({\n          model: request.model,\n          history: request.history,\n          maxTokens: resolvedMaxTokens(cfg, request),\n          temperature: Option.fromUndefinedOr(request.temperature),\n          topP: Option.fromUndefinedOr(request.topP),\n          topK: Option.fromUndefinedOr(request.topK),\n          stopSequences: Option.fromUndefinedOr(request.stopSequences),\n          thinking: Option.fromUndefinedOr(request.thinking),\n          tools: toolsWire(request, providerWire),\n          toolChoice: toolChoiceWire(request),\n          userId: Option.fromUndefinedOr(request.user),\n          outputConfig: structured,\n          cacheControl: cacheControlOf(cfg),\n        })\n\n        const body = yield* Result.match(bodyResult, {\n          onFailure: (cause) =>\n            Effect.fail(\n              new AiError.InvalidRequest({\n                provider: \"anthropic\",\n                param: \"input.function_call.arguments\",\n                raw: cause,\n              }),\n            ),\n          onSuccess: (b) => Effect.succeed(b),\n        })\n\n        const client = yield* HttpClient.HttpClient\n        const baseRequest = HttpClientRequest.post(url).pipe(\n          HttpClientRequest.setHeader(\"x-api-key\", Redacted.value(cfg.apiKey)),\n          HttpClientRequest.setHeader(\"anthropic-version\", ANTHROPIC_VERSION),\n          HttpClientRequest.bodyJsonUnsafe(body),\n          HttpClientRequest.accept(\"text/event-stream\"),\n        )\n        const httpRequest = Option.isSome(structured)\n          ? baseRequest.pipe(HttpClientRequest.setHeader(\"anthropic-beta\", STRUCTURED_OUTPUTS_BETA))\n          : baseRequest\n        const response = yield* client\n          .execute(httpRequest)\n          .pipe(\n            Effect.mapError(\n              (cause): AiError.AiError =>\n                new AiError.Unavailable({ provider: \"anthropic\", raw: cause }),\n            ),\n          )\n        if (response.status >= 400) {\n          const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n          return Stream.fail(httpStatusError(response.status, text))\n        }\n\n        return response.stream.pipe(\n          Stream.mapError(\n            (cause): AiError.AiError =>\n              new AiError.Unavailable({ provider: \"anthropic\", raw: cause }),\n          ),\n          SSE.fromBytes,\n          Stream.mapEffect(sseEventToProviderEvent),\n          Stream.flatMap((event) =>\n            event.type === \"error\"\n              ? Stream.fail(new AiError.Unavailable({ provider: \"anthropic\", raw: event }))\n              : Stream.succeed(event),\n          ),\n        )\n      }),\n    )\n}\n\n/**\n * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n * Threads a fresh `Accumulator` per stream so tool-call lookup and\n * `accumulatorToTurn` assembly work correctly across the run.\n */\nexport const toCanonical = <E, R>(\n  s: Stream.Stream<ProviderEvent, E, R>,\n): Stream.Stream<TurnEvent, E, R> =>\n  s.pipe(\n    Stream.mapAccum(\n      () => emptyAccumulator,\n      (acc, event) => {\n        const next = applyEvent(acc, event)\n        const deltas = deltasFromEvent(next, event)\n        return [next, deltas] as const\n      },\n    ),\n  )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Build an `AnthropicService` value. For Layer-based setup, prefer `layer`.\n */\nexport const make = (cfg: Config): Effect.Effect<AnthropicService, never, HttpClient.HttpClient> =>\n  Effect.map(HttpClient.HttpClient, (client) => {\n    const streamNative: AnthropicService[\"streamNative\"] = (request) =>\n      buildNativeStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client))\n    const streamTurn: AnthropicService[\"streamTurn\"] = (request) =>\n      toCanonical(streamNative(request))\n    return {\n      streamNative,\n      streamTurn,\n      turn: turnFromStream(streamTurn),\n      toCanonical,\n    }\n  })\n\n/**\n * Layer that registers both the provider-specific `Anthropic` tag and the\n * generic `LanguageModel` tag, sharing one underlying implementation.\n *\n * The generic tag accepts `CommonRequest`; the typed tag accepts the full\n * `AnthropicRequest` surface.\n */\nexport const layer = (\n  cfg: Config,\n): Layer.Layer<Anthropic | LanguageModel, never, HttpClient.HttpClient> => {\n  const typed = Layer.effect(Anthropic, make(cfg))\n  const generic = Layer.effect(\n    LanguageModel,\n    Effect.map(make(cfg), (s): LanguageModelService => ({\n      streamTurn: (request) => s.streamTurn(request as AnthropicRequest),\n      turn: (request) => s.turn(request as AnthropicRequest),\n    })),\n  )\n  return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA+GA,IAAa,YAAb,cAA+B,QAAQ,QAAqC,CAAC,CAC3E,oDACF,CAAC,CAAC,CAAC;AA4BH,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB,YACpB,KACE,OAAO,gBAAgB,QAAQ,UAAU,GACzC,OAAO,KAAK,YAAY,EACtB,QAAQ;CACN,MAAM;CACN,QAAQ,OAAO,OAAO,YAAY,CAAC,WAAW,MAAM,EAAE,QAAQ,gBAAgB,CAAC;AACjF,EACF,EAAE,CACJ;AAEF,MAAM,qBAAqB,KAAa,YACtC,QAAQ,mBAAmB,IAAI,oBAAoB;;;;;;AAOrD,MAAM,kBAAkB,QACtB,KACE,OAAO,gBAAgB,IAAI,aAAa,GACxC,OAAO,SAAS,QACd,QAAQ,QACJ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