@effect-uai/anthropic 0.11.0 → 0.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { ThinkingConfig } from "./codec.mjs";
1
+ import { CacheTtl, ThinkingConfig } from "./codec.mjs";
2
2
  import { AnthropicModel } from "./models.mjs";
3
3
  import { ProviderEvent } from "./streamEvents.mjs";
4
4
  import { UserLocation, WebSearchOptions, codeExecutionTool, webSearchTool } from "./AnthropicTools.mjs";
@@ -7,8 +7,6 @@ import { HttpClient } from "effect/unstable/http";
7
7
  import * as AiError from "@effect-uai/core/AiError";
8
8
  import { CommonRequest, LanguageModel } from "@effect-uai/core/LanguageModel";
9
9
  import { Turn, TurnEvent } from "@effect-uai/core/Turn";
10
-
11
- //#region src/Anthropic.d.ts
12
10
  declare namespace Anthropic_d_exports {
13
11
  export { Anthropic, AnthropicRequest, AnthropicService, Config, UserLocation, WebSearchOptions, codeExecutionTool, layer, make, toCanonical, webSearchTool };
14
12
  }
@@ -22,7 +20,8 @@ type AnthropicRequest = Omit<CommonRequest, "model"> & {
22
20
  * Top-K nucleus sampling parameter. Anthropic-specific; not exposed on the
23
21
  * common surface.
24
22
  */
25
- readonly topK?: number; /** Stop sequences that abort generation when matched. */
23
+ readonly topK?: number;
24
+ /** Stop sequences that abort generation when matched. */
26
25
  readonly stopSequences?: ReadonlyArray<string>;
27
26
  /**
28
27
  * Extended thinking configuration. `0` budget is equivalent to disabled.
@@ -79,6 +78,23 @@ type Config = {
79
78
  * 4096 if neither is set.
80
79
  */
81
80
  readonly defaultMaxTokens?: number;
81
+ /**
82
+ * Prompt caching. Off by default, so the library stays unopinionated about
83
+ * a setting that changes billing. `true` is `{}`: cache with the 5-minute
84
+ * default TTL.
85
+ *
86
+ * Anthropic caches the `tools` → `system` → `messages` prefix and moves the
87
+ * breakpoint forward as the conversation grows, so a long system prompt and
88
+ * tool definitions are paid for once rather than on every turn. Read
89
+ * `usage.input_tokens_details.cached_tokens` to see it working.
90
+ *
91
+ * Mutating earlier history (rewriting an old message, compaction) breaks
92
+ * the prefix from that point on. Anthropic falls back to the longest
93
+ * unchanged prefix, so this costs savings but never correctness.
94
+ */
95
+ readonly promptCaching?: boolean | {
96
+ readonly ttl?: CacheTtl;
97
+ };
82
98
  };
83
99
  /**
84
100
  * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.
@@ -1 +1 @@
1
- {"version":3,"file":"Anthropic.d.mts","names":[],"sources":["../src/Anthropic.ts"],"mappings":";;;;;;;;;;;;;;KA6CY,gBAAA,GAAmB,IAAA,CAAK,aAAA;;;;;WAKzB,KAAA,EAAO,cAAA;;;;;WAKP,IAAA;WAEA,aAAA,GAAgB,aAAA;;;;AAZ3B;;WAkBW,QAAA,GAAW,cAAA;EAlBc;;;EAAA,SAsBzB,IAAA;AAAA;AAAA,KAGC,gBAAA;EAPwB;;;;;EAAA,SAazB,YAAA,GACP,OAAA,EAAS,gBAAA,KACN,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,OAAA,CAAQ,OAAA;EArBjC;;;;EAAA,SA0BA,UAAA,GAAa,OAAA,EAAS,gBAAA,KAAqB,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,OAAA,CAAQ,OAAA;EAhBxE;;AAGf;;;;;EAHe,SAwBJ,IAAA,GAAO,OAAA,EAAS,gBAAA,KAAqB,MAAA,CAAO,MAAA,CAAO,IAAA,EAAM,OAAA,CAAQ,OAAA;EAbrE;;;;;EAAA,SAmBI,WAAA,SACP,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,CAAA,EAAG,CAAA,MAChC,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,CAAA,EAAG,CAAA;AAAA;AAAA,cAClC,cAAA;;;;;;;cAQY,SAAA,SAAkB,cAAA;AAAA,KAInB,MAAA;EAAA,SACD,MAAA,EAAQ,QAAA,CAAS,QAAA;EAAA,SACjB,OAAA;EAtCA;;;;;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
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { codeExecutionTool, renderProviderTools, webSearchTool } from "./AnthropicTools.mjs";
3
3
  import { accumulatorToTurn, buildRequestBody, emptyAccumulator } from "./codec.mjs";
4
4
  import { KnownProviderEvent, applyEvent } from "./streamEvents.mjs";
@@ -33,6 +33,15 @@ const outputConfig = (request) => pipe(Option.fromUndefinedOr(request.structured
33
33
  schema: format.schema["~standard"].jsonSchema.input({ target: "draft-2020-12" })
34
34
  } })));
35
35
  const resolvedMaxTokens = (cfg, request) => request.maxOutputTokens ?? cfg.defaultMaxTokens ?? FALLBACK_MAX_TOKENS;
36
+ /**
37
+ * One request-level breakpoint when caching is on. Anthropic places it on the
38
+ * last cacheable block itself, so nothing has to be marked per-block and the
39
+ * breakpoint stays correct as history grows.
40
+ */
41
+ const cacheControlOf = (cfg) => pipe(Option.fromUndefinedOr(cfg.promptCaching), Option.flatMap((opt) => opt === false ? Option.none() : Option.some({
42
+ type: "ephemeral",
43
+ ...opt !== true && opt.ttl !== void 0 && { ttl: opt.ttl }
44
+ })));
36
45
  const functionToolDescriptors = (request) => descriptorsOf(request.tools).map((t) => ({
37
46
  name: t.name,
38
47
  description: t.description,
@@ -165,7 +174,8 @@ const buildNativeStream = (cfg) => {
165
174
  tools: toolsWire(request, providerWire),
166
175
  toolChoice: toolChoiceWire(request),
167
176
  userId: Option.fromUndefinedOr(request.user),
168
- outputConfig: structured
177
+ outputConfig: structured,
178
+ cacheControl: cacheControlOf(cfg)
169
179
  });
170
180
  const body = yield* Result.match(bodyResult, {
171
181
  onFailure: (cause) => Effect.fail(new AiError.InvalidRequest({
@@ -1 +1 @@
1
- {"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/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\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 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\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\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 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 })\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(\n make(cfg),\n (s): LanguageModelService => ({\n streamTurn: (request) => s.streamTurn(request as AnthropicRequest),\n turn: (request) => s.turn(request as AnthropicRequest),\n }),\n ),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,IAAa,YAAb,cAA+B,QAAQ,SAAsC,CAC3E,qDACD,CAAC;AAaF,MAAM,oBAAoB;AAC1B,MAAM,0BAA0B;AAChC,MAAM,sBAAsB;AAE5B,MAAM,gBAAgB,YACpB,KACE,OAAO,gBAAgB,QAAQ,WAAW,EAC1C,OAAO,KAAK,YAAY,EACtB,QAAQ;CACN,MAAM;CACN,QAAQ,OAAO,OAAO,aAAa,WAAW,MAAM,EAAE,QAAQ,iBAAiB,CAAC;CACjF,EACF,EAAE,CACJ;AAEH,MAAM,qBAAqB,KAAa,YACtC,QAAQ,mBAAmB,IAAI,oBAAoB;AAErD,MAAM,2BACJ,YAEA,cAAc,QAAQ,MAAM,CAAC,KAAK,OAAO;CACvC,MAAM,EAAE;CACR,aAAa,EAAE;CACf,cAAc,EAAE;CACjB,EAAE;;;;;;AAOL,MAAM,aACJ,SACA,iBAC0D;CAC1D,MAAM,QAAQ,CAAC,GAAG,wBAAwB,QAAQ,EAAE,GAAG,aAAa;AACpE,QAAO,MAAM,SAAS,IAAI,OAAO,KAAK,MAAM,GAAG,OAAO,MAAM;;AAG9D,MAAM,kBAAkB,YACtB,KACE,OAA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AAQ,MAAM,OAAO,WAAW,KAAK,IAAI,CAAC;CAChD,MAAM,UAAU,MAAM,OACpB,eACA,OAAO,IACL,KAAK,IAAI,GACR,OAA6B;EAC5B,aAAa,YAAY,EAAE,WAAW,QAA4B;EAClE,OAAO,YAAY,EAAE,KAAK,QAA4B;EACvD,EACF,CACF;AACD,QAAO,MAAM,MAAM,OAAO,QAAQ"}
1
+ {"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/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\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 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":";;;;;;;;;;;;;;;;;;;;;;;;;;AA8GA,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,OAAO,KAAmB,IAC1B,OAAO,KAAmB;CACxB,MAAM;CACN,GAAI,QAAQ,QAAQ,IAAI,QAAQ,KAAA,KAAa,EAAE,KAAK,IAAI,IAAI;AAC9D,CAAC,CACP,CACF;AAEF,MAAM,2BACJ,YAEA,cAAc,QAAQ,KAAK,CAAC,CAAC,KAAK,OAAO;CACvC,MAAM,EAAE;CACR,aAAa,EAAE;CACf,cAAc,EAAE;AAClB,EAAE;;;;;;AAOJ,MAAM,aACJ,SACA,iBAC0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;CAC5C,MAAM,gBAAkD,YACtD,kBAAkB,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,OAAO,eAAe,WAAW,YAAY,MAAM,CAAC;CAC3F,MAAM,cAA8C,YAClD,YAAY,aAAa,OAAO,CAAC;CACnC,OAAO;EACL;EACA;EACA,MAAM,eAAe,UAAU;EAC/B;CACF;AACF,CAAC;;;;;;;;AASH,MAAa,SACX,QACyE;CACzE,MAAM,QAAQ,MAAM,OAAO,WAAW,KAAK,GAAG,CAAC;CAC/C,MAAM,UAAU,MAAM,OACpB,eACA,OAAO,IAAI,KAAK,GAAG,IAAI,OAA6B;EAClD,aAAa,YAAY,EAAE,WAAW,OAA2B;EACjE,OAAO,YAAY,EAAE,KAAK,OAA2B;CACvD,EAAE,CACJ;CACA,OAAO,MAAM,MAAM,OAAO,OAAO;AACnC"}
@@ -1,7 +1,5 @@
1
1
  import { Result, Schema } from "effect";
2
2
  import * as Tool from "@effect-uai/core/Tool";
3
-
4
- //#region src/AnthropicTools.d.ts
5
3
  declare namespace AnthropicTools_d_exports {
6
4
  export { AnthropicToolConfig, ToolRenderError, UserLocation, WebSearchOptions, codeExecutionTool, renderProviderTools, webSearchTool };
7
5
  }
@@ -37,9 +35,19 @@ type WebSearchOptions = {
37
35
  readonly userLocation?: UserLocation;
38
36
  };
39
37
  /** Anthropic-hosted web search. */
40
- declare const webSearchTool: (opts?: WebSearchOptions) => any;
38
+ declare const webSearchTool: (opts?: WebSearchOptions) => Tool.ProviderTool<"web_search", Record<string, never>, "anthropic", {
39
+ readonly maxUses?: number;
40
+ readonly allowedDomains?: ReadonlyArray<string>;
41
+ readonly blockedDomains?: ReadonlyArray<string>;
42
+ readonly userLocation?: UserLocation;
43
+ readonly kind: "web_search";
44
+ readonly type: "web_search_20250305";
45
+ }>;
41
46
  /** Anthropic-hosted code execution (Python sandbox). */
42
- declare const codeExecutionTool: any;
47
+ declare const codeExecutionTool: Tool.ProviderTool<"code_execution", Record<string, never>, "anthropic", {
48
+ readonly kind: "code_execution";
49
+ readonly type: "code_execution_20250522";
50
+ }>;
43
51
  /**
44
52
  * A provider tool this adapter cannot render — a foreign `provider` or an
45
53
  * unrecognized `config`. Carried as data so `Anthropic.ts` can lift it into a
@@ -1 +1 @@
1
- {"version":3,"file":"AnthropicTools.d.mts","names":[],"sources":["../src/AnthropicTools.ts"],"mappings":";;;;;;;cAeM,YAAA,EAAY,MAAA,CAAA,MAAA;EAAA;;;;;KAMN,YAAA,UAAsB,YAAA,CAAa,IAAA;;cAiBlC,mBAAA,EAAmB,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;KACpB,mBAAA,UAA6B,mBAAA,CAAoB,IAAA;AAAA,KAEjD,gBAAA;EAAA,SACD,OAAA;EAAA,SACA,cAAA,GAAiB,aAAA;EAAA,SACjB,cAAA,GAAiB,aAAA;EAAA,SACjB,YAAA,GAAe,YAAA;AAAA;;cAIb,aAAA,GAAiB,IAAA,GAAM,gBAAA;;cAUvB,iBAAA;;;;;;KAaD,eAAA;EAAA,SACD,UAAA;EAAA,SACA,MAAA;AAAA;;;;;;cAkDE,mBAAA,GACX,KAAA,EAAO,aAAA,CAAc,IAAA,CAAK,YAAA,gCACzB,MAAA,CAAO,MAAA,CAAO,aAAA,CAAc,MAAA,oBAA0B,eAAA"}
1
+ {"version":3,"file":"AnthropicTools.d.mts","names":[],"sources":["../src/AnthropicTools.ts"],"mappings":";;;;;cAeM,cAAY,OAAA;;;;;;KAMN,sBAAsB,aAAa;;cAiBlC,qBAAmB,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;KACpB,6BAA6B,oBAAoB;KAEjD;WACD;WACA,iBAAiB;WACjB,iBAAiB;WACjB,eAAe;;;cAIb,gBAAa,OAAU,qBAAgB,KAAA,2BAAA;WAP/B;WACO,iBAAA;WACA,iBAAA;WACF,eAAA;WAUN;;;;cAIP,mBAAiB,KAAA,+BAAA;WAKZ;;;;;;;;KAQN;WACD;WACA;;;;;;;cAgDE,sBAAmB,OACvB,cAAc,KAAK,4CACzB,OAAO,OAAO,cAAc,0BAA0B"}
@@ -1,4 +1,4 @@
1
- import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { Match, Result, Schema } from "effect";
3
3
  import * as Tool from "@effect-uai/core/Tool";
4
4
  //#region src/AnthropicTools.ts
@@ -1 +1 @@
1
- {"version":3,"file":"AnthropicTools.mjs","names":[],"sources":["../src/AnthropicTools.ts"],"sourcesContent":["import { Match, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\n\n// ---------------------------------------------------------------------------\n// Anthropic provider-hosted tools. Each is a `Tool.provider` whose `config`\n// carries the version-dated wire `type` string plus its options; the renderer\n// maps it to a native entry appended to the `tools` array alongside custom\n// tools. The `inputSchema` is never sent (provider tools are partitioned out\n// of the custom-tool declarations), so `Tool.noInput` suffices.\n// Reference: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool\n// ---------------------------------------------------------------------------\n\nconst WEB_SEARCH_TYPE = \"web_search_20250305\"\nconst CODE_EXECUTION_TYPE = \"code_execution_20250522\"\n\nconst UserLocation = Schema.Struct({\n city: Schema.optional(Schema.String),\n region: Schema.optional(Schema.String),\n country: Schema.optional(Schema.String),\n timezone: Schema.optional(Schema.String),\n})\nexport type UserLocation = typeof UserLocation.Type\n\nconst WebSearchConfig = Schema.Struct({\n kind: Schema.Literal(\"web_search\"),\n type: Schema.String,\n maxUses: Schema.optional(Schema.Number),\n allowedDomains: Schema.optional(Schema.Array(Schema.String)),\n blockedDomains: Schema.optional(Schema.Array(Schema.String)),\n userLocation: Schema.optional(UserLocation),\n})\n\nconst CodeExecutionConfig = Schema.Struct({\n kind: Schema.Literal(\"code_execution\"),\n type: Schema.String,\n})\n\n/** Discriminated config for an Anthropic hosted tool. */\nexport const AnthropicToolConfig = Schema.Union([WebSearchConfig, CodeExecutionConfig])\nexport type AnthropicToolConfig = typeof AnthropicToolConfig.Type\n\nexport type WebSearchOptions = {\n readonly maxUses?: number\n readonly allowedDomains?: ReadonlyArray<string>\n readonly blockedDomains?: ReadonlyArray<string>\n readonly userLocation?: UserLocation\n}\n\n/** Anthropic-hosted web search. */\nexport const webSearchTool = (opts: WebSearchOptions = {}) =>\n Tool.provider({\n name: \"web_search\",\n description: \"Search the web, executed by Anthropic.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { kind: \"web_search\", type: WEB_SEARCH_TYPE, ...opts } as const,\n })\n\n/** Anthropic-hosted code execution (Python sandbox). */\nexport const codeExecutionTool = Tool.provider({\n name: \"code_execution\",\n description: \"Run Python in a sandbox, executed by Anthropic.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { kind: \"code_execution\", type: CODE_EXECUTION_TYPE } as const,\n})\n\n/**\n * A provider tool this adapter cannot render — a foreign `provider` or an\n * unrecognized `config`. Carried as data so `Anthropic.ts` can lift it into a\n * typed `AiError.Unsupported`.\n */\nexport type ToolRenderError = {\n readonly capability: string\n readonly reason: string\n}\n\nconst userLocationWire = (loc: UserLocation): Record<string, unknown> => ({\n type: \"approximate\",\n ...(loc.city !== undefined && { city: loc.city }),\n ...(loc.region !== undefined && { region: loc.region }),\n ...(loc.country !== undefined && { country: loc.country }),\n ...(loc.timezone !== undefined && { timezone: loc.timezone }),\n})\n\nconst configToWire = Match.type<AnthropicToolConfig>().pipe(\n Match.discriminatorsExhaustive(\"kind\")({\n web_search: (c): Record<string, unknown> => ({\n type: c.type,\n name: \"web_search\",\n ...(c.maxUses !== undefined && { max_uses: c.maxUses }),\n ...(c.allowedDomains !== undefined && { allowed_domains: c.allowedDomains }),\n ...(c.blockedDomains !== undefined && { blocked_domains: c.blockedDomains }),\n ...(c.userLocation !== undefined && { user_location: userLocationWire(c.userLocation) }),\n }),\n code_execution: (c): Record<string, unknown> => ({ type: c.type, name: \"code_execution\" }),\n }),\n)\n\nconst decodeConfig = Schema.decodeUnknownResult(AnthropicToolConfig)\n\nconst renderOne = (\n tool: Tool.ProviderTool<string, any, string, any>,\n): Result.Result<Record<string, unknown>, ToolRenderError> =>\n tool.provider !== \"anthropic\"\n ? Result.fail({\n capability: `providerTool:${tool.provider}`,\n reason: `tool \"${tool.name}\" is hosted by \"${tool.provider}\", not anthropic`,\n })\n : decodeConfig(tool.config).pipe(\n Result.map(configToWire),\n Result.mapError(\n (): ToolRenderError => ({\n capability: \"providerTool\",\n reason: `unrecognized Anthropic provider tool config on \"${tool.name}\"`,\n }),\n ),\n )\n\n/**\n * Render a toolkit's Anthropic provider tools to native `tools` entries. Fails\n * with a `ToolRenderError` on the first foreign or unrecognized tool rather\n * than dropping it.\n */\nexport const renderProviderTools = (\n tools: ReadonlyArray<Tool.ProviderTool<string, any, string, any>>,\n): Result.Result<ReadonlyArray<Record<string, unknown>>, ToolRenderError> =>\n Result.all(tools.map(renderOne))\n"],"mappings":";;;;;;;;;;AAYA,MAAM,kBAAkB;AACxB,MAAM,sBAAsB;AAE5B,MAAM,eAAe,OAAO,OAAO;CACjC,MAAM,OAAO,SAAS,OAAO,OAAO;CACpC,QAAQ,OAAO,SAAS,OAAO,OAAO;CACtC,SAAS,OAAO,SAAS,OAAO,OAAO;CACvC,UAAU,OAAO,SAAS,OAAO,OAAO;CACzC,CAAC;AAGF,MAAM,kBAAkB,OAAO,OAAO;CACpC,MAAM,OAAO,QAAQ,aAAa;CAClC,MAAM,OAAO;CACb,SAAS,OAAO,SAAS,OAAO,OAAO;CACvC,gBAAgB,OAAO,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC;CAC5D,gBAAgB,OAAO,SAAS,OAAO,MAAM,OAAO,OAAO,CAAC;CAC5D,cAAc,OAAO,SAAS,aAAa;CAC5C,CAAC;AAEF,MAAM,sBAAsB,OAAO,OAAO;CACxC,MAAM,OAAO,QAAQ,iBAAiB;CACtC,MAAM,OAAO;CACd,CAAC;;AAGF,MAAa,sBAAsB,OAAO,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AK;CACjC,QAAQ,SAAS,KAAK,KAAK,kBAAkB,KAAK,SAAS;CAC5D,CAAC,GACF,aAAa,KAAK,OAAO,CAAC,KACxB,OAAO,IAAI,aAAa,EACxB,OAAO,gBACmB;CACtB,YAAY;CACZ,QAAQ,mDAAmD,KAAK,KAAK;CACtE,EACF,CACF;;;;;;AAOP,MAAa,uBACX,UAEA,OAAO,IAAI,MAAM,IAAI,UAAU,CAAC"}
1
+ {"version":3,"file":"AnthropicTools.mjs","names":[],"sources":["../src/AnthropicTools.ts"],"sourcesContent":["import { Match, Result, Schema } from \"effect\"\nimport * as Tool from \"@effect-uai/core/Tool\"\n\n// ---------------------------------------------------------------------------\n// Anthropic provider-hosted tools. Each is a `Tool.provider` whose `config`\n// carries the version-dated wire `type` string plus its options; the renderer\n// maps it to a native entry appended to the `tools` array alongside custom\n// tools. The `inputSchema` is never sent (provider tools are partitioned out\n// of the custom-tool declarations), so `Tool.noInput` suffices.\n// Reference: https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/web-search-tool\n// ---------------------------------------------------------------------------\n\nconst WEB_SEARCH_TYPE = \"web_search_20250305\"\nconst CODE_EXECUTION_TYPE = \"code_execution_20250522\"\n\nconst UserLocation = Schema.Struct({\n city: Schema.optional(Schema.String),\n region: Schema.optional(Schema.String),\n country: Schema.optional(Schema.String),\n timezone: Schema.optional(Schema.String),\n})\nexport type UserLocation = typeof UserLocation.Type\n\nconst WebSearchConfig = Schema.Struct({\n kind: Schema.Literal(\"web_search\"),\n type: Schema.String,\n maxUses: Schema.optional(Schema.Number),\n allowedDomains: Schema.optional(Schema.Array(Schema.String)),\n blockedDomains: Schema.optional(Schema.Array(Schema.String)),\n userLocation: Schema.optional(UserLocation),\n})\n\nconst CodeExecutionConfig = Schema.Struct({\n kind: Schema.Literal(\"code_execution\"),\n type: Schema.String,\n})\n\n/** Discriminated config for an Anthropic hosted tool. */\nexport const AnthropicToolConfig = Schema.Union([WebSearchConfig, CodeExecutionConfig])\nexport type AnthropicToolConfig = typeof AnthropicToolConfig.Type\n\nexport type WebSearchOptions = {\n readonly maxUses?: number\n readonly allowedDomains?: ReadonlyArray<string>\n readonly blockedDomains?: ReadonlyArray<string>\n readonly userLocation?: UserLocation\n}\n\n/** Anthropic-hosted web search. */\nexport const webSearchTool = (opts: WebSearchOptions = {}) =>\n Tool.provider({\n name: \"web_search\",\n description: \"Search the web, executed by Anthropic.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { kind: \"web_search\", type: WEB_SEARCH_TYPE, ...opts } as const,\n })\n\n/** Anthropic-hosted code execution (Python sandbox). */\nexport const codeExecutionTool = Tool.provider({\n name: \"code_execution\",\n description: \"Run Python in a sandbox, executed by Anthropic.\",\n inputSchema: Tool.noInput,\n provider: \"anthropic\",\n config: { kind: \"code_execution\", type: CODE_EXECUTION_TYPE } as const,\n})\n\n/**\n * A provider tool this adapter cannot render — a foreign `provider` or an\n * unrecognized `config`. Carried as data so `Anthropic.ts` can lift it into a\n * typed `AiError.Unsupported`.\n */\nexport type ToolRenderError = {\n readonly capability: string\n readonly reason: string\n}\n\nconst userLocationWire = (loc: UserLocation): Record<string, unknown> => ({\n type: \"approximate\",\n ...(loc.city !== undefined && { city: loc.city }),\n ...(loc.region !== undefined && { region: loc.region }),\n ...(loc.country !== undefined && { country: loc.country }),\n ...(loc.timezone !== undefined && { timezone: loc.timezone }),\n})\n\nconst configToWire = Match.type<AnthropicToolConfig>().pipe(\n Match.discriminatorsExhaustive(\"kind\")({\n web_search: (c): Record<string, unknown> => ({\n type: c.type,\n name: \"web_search\",\n ...(c.maxUses !== undefined && { max_uses: c.maxUses }),\n ...(c.allowedDomains !== undefined && { allowed_domains: c.allowedDomains }),\n ...(c.blockedDomains !== undefined && { blocked_domains: c.blockedDomains }),\n ...(c.userLocation !== undefined && { user_location: userLocationWire(c.userLocation) }),\n }),\n code_execution: (c): Record<string, unknown> => ({ type: c.type, name: \"code_execution\" }),\n }),\n)\n\nconst decodeConfig = Schema.decodeUnknownResult(AnthropicToolConfig)\n\nconst renderOne = (\n tool: Tool.ProviderTool<string, any, string, any>,\n): Result.Result<Record<string, unknown>, ToolRenderError> =>\n tool.provider !== \"anthropic\"\n ? Result.fail({\n capability: `providerTool:${tool.provider}`,\n reason: `tool \"${tool.name}\" is hosted by \"${tool.provider}\", not anthropic`,\n })\n : decodeConfig(tool.config).pipe(\n Result.map(configToWire),\n Result.mapError((): ToolRenderError => ({\n capability: \"providerTool\",\n reason: `unrecognized Anthropic provider tool config on \"${tool.name}\"`,\n })),\n )\n\n/**\n * Render a toolkit's Anthropic provider tools to native `tools` entries. Fails\n * with a `ToolRenderError` on the first foreign or unrecognized tool rather\n * than dropping it.\n */\nexport const renderProviderTools = (\n tools: ReadonlyArray<Tool.ProviderTool<string, any, string, any>>,\n): Result.Result<ReadonlyArray<Record<string, unknown>>, ToolRenderError> =>\n Result.all(tools.map(renderOne))\n"],"mappings":";;;;;;;;;;AAYA,MAAM,kBAAkB;AACxB,MAAM,sBAAsB;AAE5B,MAAM,eAAe,OAAO,OAAO;CACjC,MAAM,OAAO,SAAS,OAAO,MAAM;CACnC,QAAQ,OAAO,SAAS,OAAO,MAAM;CACrC,SAAS,OAAO,SAAS,OAAO,MAAM;CACtC,UAAU,OAAO,SAAS,OAAO,MAAM;AACzC,CAAC;AAGD,MAAM,kBAAkB,OAAO,OAAO;CACpC,MAAM,OAAO,QAAQ,YAAY;CACjC,MAAM,OAAO;CACb,SAAS,OAAO,SAAS,OAAO,MAAM;CACtC,gBAAgB,OAAO,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC;CAC3D,gBAAgB,OAAO,SAAS,OAAO,MAAM,OAAO,MAAM,CAAC;CAC3D,cAAc,OAAO,SAAS,YAAY;AAC5C,CAAC;AAED,MAAM,sBAAsB,OAAO,OAAO;CACxC,MAAM,OAAO,QAAQ,gBAAgB;CACrC,MAAM,OAAO;AACf,CAAC;;AAGD,MAAa,sBAAsB,OAAO,MAAM,CAAC,iBAAiB,mBA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