@cldmv/llm-translator 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +11 -7
  2. package/dist/api/convert/openai/chat/to/anthropic/messages/request.mjs +5 -3
  3. package/dist/api/convert/openai/chat/to/anthropic/messages/response.mjs +1 -1
  4. package/dist/api/convert/openai/chat/to/anthropic/messages/stream.mjs +1 -1
  5. package/dist/api/detect.mjs +1 -1
  6. package/dist/api/driver/anthropic/info.mjs +1 -1
  7. package/dist/api/driver/compatible/info.mjs +1 -1
  8. package/dist/api/driver/deepseek/info.mjs +1 -1
  9. package/dist/api/driver/llamacpp/info.mjs +1 -1
  10. package/dist/api/driver/ollama/info.mjs +1 -1
  11. package/dist/api/driver/openai/info.mjs +1 -1
  12. package/dist/api/driver/sglang/info.mjs +1 -1
  13. package/dist/api/driver/vllm/info.mjs +1 -1
  14. package/dist/api/embeddings/send.mjs +2 -0
  15. package/dist/api/events/off.mjs +2 -0
  16. package/dist/api/events/on.mjs +2 -0
  17. package/dist/api/request.mjs +2 -2
  18. package/dist/api/send.mjs +1 -1
  19. package/dist/api/server/plugin.mjs +1 -1
  20. package/dist/index.mjs +1 -1
  21. package/dist/lib/cli.mjs +7 -6
  22. package/dist/lib/config.mjs +1 -1
  23. package/dist/lib/effort.mjs +1 -1
  24. package/dist/lib/events.mjs +4 -0
  25. package/dist/lib/finish.mjs +1 -1
  26. package/dist/lib/record.mjs +3 -0
  27. package/dist/lib/routes.mjs +1 -1
  28. package/dist/lib/sampling.mjs +2 -0
  29. package/dist/lib/settings.mjs +1 -1
  30. package/dist/lib/strict.mjs +2 -0
  31. package/dist/lib/usage.mjs +1 -1
  32. package/dist/lib/warn.mjs +1 -1
  33. package/package.json +1 -1
  34. package/types/src/api/driver/anthropic/info.d.mts +2 -1
  35. package/types/src/api/driver/compatible/info.d.mts +2 -1
  36. package/types/src/api/driver/deepseek/info.d.mts +2 -1
  37. package/types/src/api/driver/llamacpp/info.d.mts +2 -1
  38. package/types/src/api/driver/ollama/info.d.mts +2 -1
  39. package/types/src/api/driver/openai/info.d.mts +2 -1
  40. package/types/src/api/driver/sglang/info.d.mts +2 -1
  41. package/types/src/api/driver/vllm/info.d.mts +2 -1
  42. package/types/src/api/embeddings/send.d.mts +15 -0
  43. package/types/src/api/events/off.d.mts +7 -0
  44. package/types/src/api/events/on.d.mts +8 -0
  45. package/types/src/api/request.d.mts +7 -2
  46. package/types/src/api/send.d.mts +1 -1
  47. package/types/src/api/server/plugin.d.mts +2 -2
  48. package/types/src/index.d.mts +23 -3
  49. package/types/src/lib/effort.d.mts +6 -2
  50. package/types/src/lib/events.d.mts +86 -0
  51. package/types/src/lib/finish.d.mts +10 -3
  52. package/types/src/lib/record.d.mts +36 -0
  53. package/types/src/lib/sampling.d.mts +13 -0
  54. package/types/src/lib/settings.d.mts +15 -0
  55. package/types/src/lib/strict.d.mts +26 -0
  56. package/types/src/lib/usage.d.mts +4 -2
  57. package/types/src/lib/warn.d.mts +12 -23
package/README.md CHANGED
@@ -17,18 +17,18 @@ Use it as a library when you want the conversion without any I/O (`request`, `re
17
17
 
18
18
  ## ✨ What's New
19
19
 
20
- ### Latest: v0.4.0 (November 2026)
20
+ ### Latest: v0.6.0 (November 2026)
21
21
 
22
- - **Per-model effort levels and pinned aliases** — an `efforts` config lists the reasoning efforts each model honours, unsupported levels snap to the nearest listed one, and an alias can pin `effort` and `thinking`, so one local model can serve Claude Code's tiers at different depths. `/v1/models` lists the aliases and levels.
23
- - **Also:** non-standard finish reasons map to `max_tokens`, `end_turn` or an error; a configurable tool-error marker with opt-in `is_error` inference; `pingInterval` per upstream; and the Node.js floor drops to 22.15.
24
- - [View full v0.4.0 Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.4.0.md)
22
+ - **Embeddings pass-through** — `POST /v1/embeddings` on the OpenAI front, and `api.embeddings.send()` as a library call, forward to an OpenAI-protocol upstream that lists the model. Aliases, pools, failover, `apiKey` and `authorize` work as they do for chat.
23
+ - **Sampling, strict tools and capture** — the `sampling` setting and `metadata.sampling` send `min_p`, `repetition_penalty` and similar fields to upstreams that accept them. `strict` now round trips: a tool whose schema is outside the strict subset is sent without `strict` and reported, and a backend that does not enforce strict use gets a warning. The `capture` option records redacted request and response pairs to a directory or a callback.
24
+ - [View full v0.6.0 Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.6.0.md)
25
25
 
26
26
  ### Recent Releases
27
27
 
28
+ - **v0.5.0** (November 2026) — everything the library logs is available as events, logging is opt-in through `logs`, `json_object` reaches Anthropic upstreams as a schema with a fallback, and refusals carry `stop_details` ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.5.0.md))
29
+ - **v0.4.0** (November 2026) — per-model effort levels and aliases that pin effort and thinking, non-standard finish reasons, a configurable tool-error marker, per-upstream `pingInterval` and a Node.js 22.15 floor ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.4.0.md))
28
30
  - **v0.3.1** (November 2026) — patched the dev-only `minimatch` and `katex` lint dependencies and corrected the v0.3.0 issue links; no runtime changes ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.3.1.md))
29
31
  - **v0.3.0** (November 2026) — usage reporting from `send()`, the `route()` leaf and the server `authorize` hook; drivers for llama.cpp, Ollama, SGLang and the DeepSeek API, endpoint pools, `reasoningRoundTrip` and `toolSearch`; requires Node.js 24 ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.3.0.md))
30
- - **v0.2.0** (October 2026) — the first working translator: six Anthropic Messages and OpenAI Chat Completions converters, backend detection (vLLM, OpenAI, Anthropic, generic), model aliases, the optional Fastify server and the `llm-translator` CLI for Claude Code ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.2.0.md))
31
- - **v0.1.0** (October 2026) — package scaffold: ESM and CommonJS entry points, tsup build, the `llm-translator-dev` condition with devcheck, tests on `@cldmv/vitest-runner` and the CLDMV v4 CI/release pipeline; the only export was a placeholder ([Changelog](https://github.com/CLDMV/llm-translator/blob/master/docs/changelog/v0/v0.1.0.md))
32
32
 
33
33
  📚 **For complete version history and detailed release notes, see the [docs/changelog/](https://github.com/CLDMV/llm-translator/tree/master/docs/changelog/) folder.**
34
34
 
@@ -105,6 +105,9 @@ if (reply.stream) for await (const { event, data } of reply.stream) console.log(
105
105
  // Where would a request go, and what did it cost? (see docs/server.md)
106
106
  const { upstream, model } = api.route({ model: "claude-opus-5-5" }); // no I/O
107
107
  const { input_tokens, output_tokens, reported, estimated } = await reply.usage; // or send(body, { onUsage }); `estimated` holds the guesses written into the client reply when the upstream sent no usage
108
+
109
+ // Fallbacks, failovers and warnings are events (see docs/events.md); logging is off unless you set `logs`.
110
+ const stop = api.events.on("fallback", ({ endpoint, status, reason }) => console.log(endpoint, status, reason));
108
111
  ```
109
112
 
110
113
  ### Server and Claude Code
@@ -124,7 +127,7 @@ Then point Claude Code at it with `ANTHROPIC_BASE_URL=http://127.0.0.1:8787`. Th
124
127
 
125
128
  ## 📚 Configuration
126
129
 
127
- `createTranslator(config)` takes `front`, `upstreams` (URLs or objects with `url`, `apiKey`, `backend`, `models`, `default` and `settings`), `aliases` (a model name, or `{ model, effort, thinking }` to pin settings), `efforts` (the reasoning levels each model supports, see [docs/settings.md](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md#effort-levels-and-pinned-aliases-not-converter-settings)), global `settings`, `pool` (failover and load balancing between upstreams that serve the same model, see [docs/server.md](https://github.com/CLDMV/llm-translator/blob/master/docs/server.md#endpoint-pools-failover-and-load-balancing)), `detect` and a custom `transport`. The CLI reads the same keys from flags, `LLM_TRANSLATOR_*` environment variables and a JSON file, in that order of precedence.
130
+ `createTranslator(config)` takes `front`, `upstreams` (URLs or objects with `url`, `apiKey`, `backend`, `models`, `default` and `settings`), `aliases` (a model name, or `{ model, effort, thinking }` to pin settings), `efforts` (the reasoning levels each model supports, see [docs/settings.md](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md#effort-levels-and-pinned-aliases-not-converter-settings)), global `settings`, `pool` (failover and load balancing between upstreams that serve the same model, see [docs/server.md](https://github.com/CLDMV/llm-translator/blob/master/docs/server.md#endpoint-pools-failover-and-load-balancing)), `detect`, `logs` (off by default; `true` prints warnings, a path appends JSON lines), `events` and `onEvent` (see [docs/events.md](https://github.com/CLDMV/llm-translator/blob/master/docs/events.md)), `capture` (off by default; a directory or a callback receives redacted request and response records for debugging, see [docs/events.md](https://github.com/CLDMV/llm-translator/blob/master/docs/events.md#capture-for-debugging)) and a custom `transport`. `silent: true` is a deprecated alias for `logs: false`. The CLI reads the same keys from flags, `LLM_TRANSLATOR_*` environment variables and a JSON file, in that order of precedence.
128
131
 
129
132
  Settings tune how the converters map one protocol onto the other (`inlineSystem`, `images`, `imageFallback`, `toolStreaming`, `pingInterval` and more); they are resolved per upstream from defaults, probed values, driver defaults and your overrides. The full table is in [docs/settings.md](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md).
130
133
 
@@ -137,6 +140,7 @@ Settings tune how the converters map one protocol onto the other (`inlineSystem`
137
140
  - [Server and CLI](https://github.com/CLDMV/llm-translator/blob/master/docs/server.md)
138
141
  - [Settings](https://github.com/CLDMV/llm-translator/blob/master/docs/settings.md)
139
142
  - [Protocol support](https://github.com/CLDMV/llm-translator/blob/master/docs/protocol-support.md)
143
+ - [Events and logging](https://github.com/CLDMV/llm-translator/blob/master/docs/events.md)
140
144
  - [Drivers, detection and routing](https://github.com/CLDMV/llm-translator/blob/master/docs/drivers.md)
141
145
 
142
146
  ### Guides
@@ -1,6 +1,8 @@
1
- var v=Object.defineProperty;var f=(e,s)=>v(e,"name",{value:s,configurable:!0});import{resolve as T}from"../../../../../../../lib/settings.mjs";import{TranslatorError as x}from"../../../../../../../lib/errors.mjs";import{anthropicToolId as j,createNameFitter as q}from"../../../../../../../lib/ids.mjs";import{parseArguments as A}from"../../../../../../../lib/arguments.mjs";import{sanitize as E}from"../../../../../../../lib/schema.mjs";import{blocksOf as I}from"../../../../../../../lib/thinking.mjs";const M=new Set(["model","messages","max_tokens","max_completion_tokens","temperature","top_p","top_k","stop","stream","stream_options","tools","tool_choice","parallel_tool_calls","reasoning_effort","response_format","user","n"]),N=new Set(["metadata","store","service_tier"]),h=/^data:([^;,]+);base64,(.*)$/s;async function P(e,s){const l=T(s);if(e===null||typeof e!="object"||!Array.isArray(e.messages))throw new x("messages is a required property",{code:"invalid_request",param:"messages"});if(e.n!==void 0&&e.n!==1)throw new x("n: only a single choice (n = 1) is supported",{code:"unsupported_field",param:"n"});const o={front:"openai",model:e.model,stream:e.stream===!0,includeUsage:e.stream_options?.include_usage===!0,reasoningField:l.reasoningField,toolNames:{},dropped:[]},a=q({max:128,map:o.toolNames});for(const t of Object.keys(e))if(!(M.has(t)||N.has(t))){if(l.unknownFields==="error")throw new x(`${t}: Unrecognized request argument`,{code:"unsupported_field",param:t});g(o,t)}const c=[],p=[],m=f((t,n)=>{const i=p.at(-1);i?.role===t?i.blocks.push(...n):p.push({role:t,blocks:[...n]})},"push");for(const t of e.messages)switch(t.role){case"system":case"developer":{const n=w(t.content);n!==""&&c.push(n);break}case"user":m("user",S(t.content,o));break;case"assistant":{const n=l.reasoningRoundTrip?I(t.reasoning_details):[],i=[],u=w(t.content);u!==""?i.push({type:"text",text:u}):typeof t.refusal=="string"&&t.refusal!==""&&i.push({type:"text",text:t.refusal}),F(t)&&!n.some(d=>d.block.type==="thinking")&&g(o,"reasoning");for(const d of t.tool_calls??[])i.push({type:"tool_use",id:j(d.id),name:a(d.function.name),input:A(d.function.arguments)});const k=$(n,i);k.length>0&&m("assistant",k);break}case"tool":{const n={type:"tool_result",tool_use_id:j(t.tool_call_id),content:w(t.content)};if(l.toolErrorInference){const u=l.toolErrorMarker.trimEnd();n.content.startsWith(u)&&(n.is_error=!0,n.content=n.content.slice(u.length).replace(/^\s/,""))}const i=p.at(-1);if(i?.role==="user"){const u=i.blocks.findIndex(k=>k.type!=="tool_result");i.blocks.splice(u===-1?i.blocks.length:u,0,n)}else p.push({role:"user",blocks:[n]});break}default:throw new x(`messages: unsupported role "${t.role}"`,{code:"invalid_request",param:"messages"})}const r={model:e.model,max_tokens:e.max_completion_tokens??e.max_tokens??l.defaultMaxTokens};c.length>0&&(r.system=c.join(`
1
+ var v=Object.defineProperty;var f=(e,r)=>v(e,"name",{value:r,configurable:!0});import{resolve as N}from"../../../../../../../lib/settings.mjs";import{TranslatorError as b}from"../../../../../../../lib/errors.mjs";import{anthropicToolId as w,createNameFitter as O}from"../../../../../../../lib/ids.mjs";import{parseArguments as S}from"../../../../../../../lib/arguments.mjs";import{sanitize as q}from"../../../../../../../lib/schema.mjs";import{blocksOf as E}from"../../../../../../../lib/thinking.mjs";const I=new Set(["model","messages","max_tokens","max_completion_tokens","temperature","top_p","top_k","stop","stream","stream_options","tools","tool_choice","parallel_tool_calls","reasoning_effort","response_format","user","n"]),$=new Set(["metadata","store","service_tier"]),x=/^data:([^;,]+);base64,(.*)$/s;async function P(e,r){const i=N(r);if(e===null||typeof e!="object"||!Array.isArray(e.messages))throw new b("messages is a required property",{code:"invalid_request",param:"messages"});if(e.n!==void 0&&e.n!==1)throw new b("n: only a single choice (n = 1) is supported",{code:"unsupported_field",param:"n"});const o={front:"openai",model:e.model,stream:e.stream===!0,includeUsage:e.stream_options?.include_usage===!0,reasoningField:i.reasoningField,toolNames:{},dropped:[]},a=O({max:128,map:o.toolNames});for(const t of Object.keys(e))if(!(I.has(t)||$.has(t))){if(i.unknownFields==="error")throw new b(`${t}: Unrecognized request argument`,{code:"unsupported_field",param:t});g(o,t)}const c=[],p=[],m=f((t,s)=>{const l=p.at(-1);l?.role===t?l.blocks.push(...s):p.push({role:t,blocks:[...s]})},"push");for(const t of e.messages)switch(t.role){case"system":case"developer":{const s=j(t.content);s!==""&&c.push(s);break}case"user":m("user",F(t.content,o));break;case"assistant":{const s=i.reasoningRoundTrip?E(t.reasoning_details):[],l=[],u=j(t.content);u!==""?l.push({type:"text",text:u}):typeof t.refusal=="string"&&t.refusal!==""&&l.push({type:"text",text:t.refusal}),M(t)&&!s.some(d=>d.block.type==="thinking")&&g(o,"reasoning");for(const d of t.tool_calls??[])l.push({type:"tool_use",id:w(d.id),name:a(d.function.name),input:S(d.function.arguments)});const k=A(s,l);k.length>0&&m("assistant",k);break}case"tool":{const s={type:"tool_result",tool_use_id:w(t.tool_call_id),content:j(t.content)};if(i.toolErrorInference){const u=i.toolErrorMarker.trimEnd();s.content.startsWith(u)&&(s.is_error=!0,s.content=s.content.slice(u.length).replace(/^\s/,""))}const l=p.at(-1);if(l?.role==="user"){const u=l.blocks.findIndex(k=>k.type!=="tool_result");l.blocks.splice(u===-1?l.blocks.length:u,0,s)}else p.push({role:"user",blocks:[s]});break}default:throw new b(`messages: unsupported role "${t.role}"`,{code:"invalid_request",param:"messages"})}const n={model:e.model,max_tokens:e.max_completion_tokens??e.max_tokens??i.defaultMaxTokens};c.length>0&&(n.system=c.join(`
2
2
 
3
- `)),r.messages=p.map(t=>({role:t.role,content:t.blocks})),e.temperature!==void 0&&(r.temperature=Math.min(1,e.temperature)),e.top_p!==void 0&&(r.top_p=e.top_p),e.top_k!==void 0&&(r.top_k=e.top_k),e.stop!==void 0&&e.stop!==null&&(r.stop_sequences=[].concat(e.stop)),o.stream&&(r.stream=!0),typeof e.user=="string"&&(r.metadata={user_id:e.user});const b=[];for(const t of e.tools??[]){if(t.type!=="function"){g(o,`tool:${t.type}`);continue}const n=t.function,i=n.parameters??{type:"object",properties:{}},u={name:a(n.name),input_schema:l.toolSchema==="sanitize"?E(i):i};n.description!==void 0&&(u.description=n.description),b.push(u)}if(b.length>0){r.tools=b;let t=z(e.tool_choice,a);e.parallel_tool_calls===!1&&t.type!=="none"&&(t={...t,disable_parallel_tool_use:!0}),(e.tool_choice!==void 0||e.parallel_tool_calls===!1)&&(r.tool_choice=t)}const _=e.reasoning_effort;_==="none"?r.thinking={type:"disabled"}:_!=null&&(r.thinking={type:"adaptive"},r.output_config={effort:_==="minimal"?"low":_});const y=e.response_format;return y?.type==="json_schema"?r.output_config={...r.output_config,format:{type:"json_schema",schema:y.json_schema.schema}}:y?.type==="json_object"&&g(o,"response_format"),{body:r,state:o}}f(P,"request");function g(e,s){e.dropped.includes(s)||e.dropped.push(s)}f(g,"drop");function $(e,s){const l=[...e].sort((p,m)=>p.at-m.at),o=[];let a=0;const c=s.findIndex(p=>p.type==="tool_use");for(const p of l){const m=p.at<=1&&c!==-1?Math.min(p.at,c):p.at;for(;a<Math.min(m,s.length);)o.push(s[a++]);o.push(p.block)}return[...o,...s.slice(a)]}f($,"interleave");function F(e){return!!(e.reasoning||e.reasoning_content)}f(F,"reasoningPresent");function w(e){return typeof e=="string"?e:(e??[]).filter(s=>s.type==="text").map(s=>s.text).join(`
3
+ `)),n.messages=p.map(t=>({role:t.role,content:t.blocks})),e.temperature!==void 0&&(n.temperature=Math.min(1,e.temperature)),e.top_p!==void 0&&(n.top_p=e.top_p),e.top_k!==void 0&&(n.top_k=e.top_k),e.stop!==void 0&&e.stop!==null&&(n.stop_sequences=[].concat(e.stop)),o.stream&&(n.stream=!0),typeof e.user=="string"&&(n.metadata={user_id:e.user});const y=[];for(const t of e.tools??[]){if(t.type!=="function"){g(o,`tool:${t.type}`);continue}const s=t.function,l=s.parameters??{type:"object",properties:{}},u={name:a(s.name),input_schema:i.toolSchema==="sanitize"?q(l):l};s.description!==void 0&&(u.description=s.description),s.strict!==void 0&&(u.strict=s.strict),y.push(u)}if(y.length>0){n.tools=y;let t=R(e.tool_choice,a);e.parallel_tool_calls===!1&&t.type!=="none"&&(t={...t,disable_parallel_tool_use:!0}),(e.tool_choice!==void 0||e.parallel_tool_calls===!1)&&(n.tool_choice=t)}const _=e.reasoning_effort;_==="none"?n.thinking={type:"disabled"}:_!=null&&(n.thinking={type:"adaptive"},n.output_config={effort:_==="minimal"?"low":_});const h=e.response_format;return h?.type==="json_schema"?n.output_config={...n.output_config,format:{type:"json_schema",schema:h.json_schema.schema}}:h?.type==="json_object"&&(i.jsonObject==="schema"?(n.output_config={...n.output_config,format:{type:"json_schema",schema:{type:"object"}}},o.jsonSchemaEmulated=!0):i.jsonObject==="instruction"?n.system=n.system===void 0?T:`${n.system}
4
4
 
5
- `)}f(w,"plainText");function S(e,s){if(typeof e=="string")return e===""?[]:[{type:"text",text:e}];const l=[];for(const o of e??[])if(o.type==="text")l.push({type:"text",text:o.text});else if(o.type==="image_url"){const a=h.exec(o.image_url.url);l.push({type:"image",source:a?{type:"base64",media_type:a[1],data:a[2]}:{type:"url",url:o.image_url.url}})}else if(o.type==="file"&&typeof o.file?.file_data=="string"&&h.test(o.file.file_data)){const a=h.exec(o.file.file_data);l.push({type:"document",source:{type:"base64",media_type:a[1],data:a[2]}})}else g(s,`content:${o.type}`);return l}f(S,"userBlocks");function z(e,s){return e==="none"?{type:"none"}:e==="required"?{type:"any"}:typeof e=="object"&&e!==null?{type:"tool",name:s(e.function.name)}:{type:"auto"}}f(z,"toolChoice");export{P as request};
5
+ ${T}`:g(o,"response_format")),{body:n,state:o}}f(P,"request");const T="Respond with a single valid JSON object and nothing else.";function g(e,r){e.dropped.includes(r)||e.dropped.push(r)}f(g,"drop");function A(e,r){const i=[...e].sort((p,m)=>p.at-m.at),o=[];let a=0;const c=r.findIndex(p=>p.type==="tool_use");for(const p of i){const m=p.at<=1&&c!==-1?Math.min(p.at,c):p.at;for(;a<Math.min(m,r.length);)o.push(r[a++]);o.push(p.block)}return[...o,...r.slice(a)]}f(A,"interleave");function M(e){return!!(e.reasoning||e.reasoning_content)}f(M,"reasoningPresent");function j(e){return typeof e=="string"?e:(e??[]).filter(r=>r.type==="text").map(r=>r.text).join(`
6
+
7
+ `)}f(j,"plainText");function F(e,r){if(typeof e=="string")return e===""?[]:[{type:"text",text:e}];const i=[];for(const o of e??[])if(o.type==="text")i.push({type:"text",text:o.text});else if(o.type==="image_url"){const a=x.exec(o.image_url.url);i.push({type:"image",source:a?{type:"base64",media_type:a[1],data:a[2]}:{type:"url",url:o.image_url.url}})}else if(o.type==="file"&&typeof o.file?.file_data=="string"&&x.test(o.file.file_data)){const a=x.exec(o.file.file_data);i.push({type:"document",source:{type:"base64",media_type:a[1],data:a[2]}})}else g(r,`content:${o.type}`);return i}f(F,"userBlocks");function R(e,r){return e==="none"?{type:"none"}:e==="required"?{type:"any"}:typeof e=="object"&&e!==null?{type:"tool",name:r(e.function.name)}:{type:"auto"}}f(R,"toolChoice");export{P as request};
6
8
  //# sourceMappingURL=request.mjs.map
@@ -1,2 +1,2 @@
1
- var y=Object.defineProperty;var f=(t,n)=>y(t,"name",{value:n,configurable:!0});import{resolve as _}from"../../../../../../../lib/settings.mjs";import{TranslatorError as m}from"../../../../../../../lib/errors.mjs";import{messageId as k,anthropicToolId as T,restoreName as x}from"../../../../../../../lib/ids.mjs";import{sign as A,reasoningOf as w,reasoningKey as C,detailsText as N,splitThink as O}from"../../../../../../../lib/thinking.mjs";import{isComplete as S,parseArguments as U}from"../../../../../../../lib/arguments.mjs";import{finishError as v,toAnthropicStop as E,toAnthropicUsage as I}from"../../../../../../../lib/finish.mjs";function D(t,n,u){const c=_(u),g=t?.choices?.[0];if(!g)throw new m("Upstream response contained no choices",{code:"invalid_upstream_response",status:502});const l=v(g.finish_reason);if(l)throw new m(l.message,{code:l.code,status:l.status,type:l.type});const e=g.message??{},r=[];let a=w(e),s=typeof e.content=="string"?e.content:"";const o={};if(c.reasoningRoundTrip){const i=C(e);i&&(o[i]=e[i]),Array.isArray(e.reasoning_details)&&e.reasoning_details.length>0&&(o.reasoning_details=e.reasoning_details)}a===""&&c.thinkTags&&({reasoning:a,text:s}=O(s,c.thinkOpen)),a===""&&o.reasoning_details&&(a=N(o.reasoning_details)),(a!==""||o.reasoning_details)&&(r.push({type:"thinking",thinking:a,signature:A(Object.keys(o).length>0?o:void 0,n?.producer)}),s=s.trimStart()),s===""&&typeof e.refusal=="string"&&(s=e.refusal),s!==""&&r.push({type:"text",text:s});const h=n?.toolNames??{},p=e.tool_calls??[];for(const i of p)r.push({type:"tool_use",id:T(i.id),name:x(h,i.function.name),input:U(i.function.arguments)});r.length===0&&r.push({type:"text",text:""});const d=E(g.finish_reason,{hasToolCalls:p.length>0,matchedStop:g.stop_reason,argumentsComplete:p.length===0||S(p.at(-1).function.arguments)});return n&&t.usage&&(n.upstreamUsage=t.usage),{id:k(),type:"message",role:"assistant",model:n?.model??t.model,content:r,...d,usage:I(t.usage)}}f(D,"response");export{D as response};
1
+ var y=Object.defineProperty;var c=(t,n)=>y(t,"name",{value:n,configurable:!0});import{resolve as _}from"../../../../../../../lib/settings.mjs";import{TranslatorError as m}from"../../../../../../../lib/errors.mjs";import{messageId as k,anthropicToolId as T,restoreName as x}from"../../../../../../../lib/ids.mjs";import{sign as A,reasoningOf as w,reasoningKey as C,detailsText as N,splitThink as O}from"../../../../../../../lib/thinking.mjs";import{isComplete as S,parseArguments as U}from"../../../../../../../lib/arguments.mjs";import{finishError as v,toAnthropicStop as E,toAnthropicUsage as I}from"../../../../../../../lib/finish.mjs";function D(t,n,u){const f=_(u),l=t?.choices?.[0];if(!l)throw new m("Upstream response contained no choices",{code:"invalid_upstream_response",status:502});const g=v(l.finish_reason);if(g)throw new m(g.message,{code:g.code,status:g.status,type:g.type});const e=l.message??{},i=[];let a=w(e),s=typeof e.content=="string"?e.content:"";const o={};if(f.reasoningRoundTrip){const r=C(e);r&&(o[r]=e[r]),Array.isArray(e.reasoning_details)&&e.reasoning_details.length>0&&(o.reasoning_details=e.reasoning_details)}a===""&&f.thinkTags&&({reasoning:a,text:s}=O(s,f.thinkOpen)),a===""&&o.reasoning_details&&(a=N(o.reasoning_details)),(a!==""||o.reasoning_details)&&(i.push({type:"thinking",thinking:a,signature:A(Object.keys(o).length>0?o:void 0,n?.producer)}),s=s.trimStart()),s===""&&typeof e.refusal=="string"&&(s=e.refusal),s!==""&&i.push({type:"text",text:s});const h=n?.toolNames??{},p=e.tool_calls??[];for(const r of p)i.push({type:"tool_use",id:T(r.id),name:x(h,r.function.name),input:U(r.function.arguments)});i.length===0&&i.push({type:"text",text:""});const d=E(l.finish_reason,{hasToolCalls:p.length>0,matchedStop:l.stop_reason,refusal:e.refusal,argumentsComplete:p.length===0||S(p.at(-1).function.arguments)});return n&&t.usage&&(n.upstreamUsage=t.usage),{id:k(),type:"message",role:"assistant",model:n?.model??t.model,content:i,...d,usage:I(t.usage)}}c(D,"response");export{D as response};
2
2
  //# sourceMappingURL=response.mjs.map
@@ -1,2 +1,2 @@
1
- var G=Object.defineProperty;var l=(x,r)=>G(x,"name",{value:r,configurable:!0});import{resolve as H}from"../../../../../../../lib/settings.mjs";import{TranslatorError as L,openaiToAnthropicType as P,rewriteContextOverflow as Q}from"../../../../../../../lib/errors.mjs";import{isComplete as V}from"../../../../../../../lib/arguments.mjs";import{messageId as W,anthropicToolId as X,restoreName as Y}from"../../../../../../../lib/ids.mjs";import{sign as Z,reasoningOf as $,reasoningKey as ee,detailsText as te,mergeDetail as ne,createThinkSplitter as ie}from"../../../../../../../lib/thinking.mjs";import{finishError as oe,toAnthropicStop as se,toAnthropicUsage as z}from"../../../../../../../lib/finish.mjs";import{messages as le}from"../../../../../../../lib/sse.mjs";async function*ge(x,r,D){const u=H(D),q=r?.toolNames??{},a=u.thinkTags?ie(u.thinkOpen):null,c=new Map;let _=!1,b=0,n=null,S=null,k=null,N=null,O=!1,v=0,j=!1,A=!1,C=!1;const T=[],s=l((e,t)=>({event:e,data:{type:e,...t}}),"event"),p=l((e,t)=>s("error",{error:{type:e,message:t}}),"fail"),B=l(e=>{const t={};return u.reasoningRoundTrip&&(e.key!==null&&(t[e.key]=e.text),e.details.length>0&&(t.reasoning_details=e.details)),Object.keys(t).length>0?t:void 0},"carried");function*y(){if(n!==null){n.kind==="thinking"?yield s("content_block_delta",{index:n.index,delta:{type:"signature_delta",signature:Z(B(n.carry),r?.producer)}}):n.kind==="tool"&&(n.entry.state="closed",n.entry.sent||(yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:"{}"}}))),yield s("content_block_stop",{index:n.index}),n=null;for(const e of c.values()){if(e.state!=="pending")continue;e.state="closed";const t=b++,i=e.args.join("");yield s("content_block_start",{index:t,content_block:e.block}),yield s("content_block_delta",{index:t,delta:{type:"input_json_delta",partial_json:i===""?"{}":i}}),yield s("content_block_stop",{index:t})}}}l(y,"close");function*F(){for(const e of U()){if(e.state!=="buffered")continue;yield*g("tool",e.block,e);const t=e.args.join("");t!==""&&(e.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:t}})),yield*y()}}l(F,"flushBuffered");function U(){return[...c.entries()].sort((e,t)=>e[0]-t[0]).map(e=>e[1])}l(U,"ordered");function*g(e,t,i){yield*y(),n={kind:e,index:b++,entry:i,carry:{key:null,text:"",details:[]}},yield s("content_block_start",{index:n.index,content_block:t})}l(g,"begin");function*d(e,t,i=null){if(e==="text"&&C&&(t=t.trimStart()),t==="")return;if(C=e==="thinking",n?.kind==="tool"){T.push({kind:e,text:t,key:i});return}n?.kind!==e&&(yield*g(e,e==="text"?{type:"text",text:""}:{type:"thinking",thinking:"",signature:""})),i!==null&&(n.carry.key??=i,n.carry.text+=t);const o=e==="text"?{type:"text_delta",text:t}:{type:"thinking_delta",thinking:t};yield s("content_block_delta",{index:n.index,delta:o})}l(d,"piece");function*E(e){if(n?.kind==="tool"){T.push({kind:"details",items:e});return}n?.kind!=="thinking"&&(yield*g("thinking",{type:"thinking",thinking:"",signature:""}));for(const t of e)ne(n.carry.details,t);n.carry.key===null&&(yield*d("thinking",te(e)))}l(E,"details");function*I(e){yield*d("thinking",e.reasoning),yield*d("text",e.text)}l(I,"pieces");function*J(e){let t=e.index;t===void 0&&(t=e.id===void 0?v:c.size),v=t;let i=c.get(t);if(i===void 0){const h=e.function?.name??"",m={type:"tool_use",id:X(e.id),name:Y(q,h),input:{}};a?.pending()&&(A=!0);const f=u.toolStreaming==="buffer"||A;i={state:f?"buffered":"pending",sent:!1,args:[],block:m},c.set(t,i),!f&&n?.kind!=="tool"&&(i.state="open",yield*g("tool",m,i))}let o=e.function?.arguments;o!==null&&typeof o=="object"&&(o=JSON.stringify(o)),!(o==null||o==="")&&(i.args.push(o),i.state==="open"&&(i.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:o}})))}l(J,"toolCall");try{for await(const e of le(x)){if(e.data==="[DONE]"){O=!0;break}const t=e.data;if(t.error){const f=t.error.message??"Upstream error";yield p(P(t.error),Q(f)??f);return}_||(_=!0,yield s("message_start",{message:{id:W(),type:"message",role:"assistant",model:r?.model??t.model,content:[],stop_reason:null,stop_sequence:null,usage:z(t.usage)}})),t.usage&&(S=t.usage,r&&(r.upstreamUsage=t.usage));const i=t.choices?.[0];if(!i)continue;const o=i.delta??{},h=$(o);let m="";h!==""&&!j&&(j=!0,a&&(m=a.release().text)),yield*d("thinking",h,ee(o)),yield*d("text",m),u.reasoningRoundTrip&&Array.isArray(o.reasoning_details)&&o.reasoning_details.length>0&&(yield*E(o.reasoning_details)),typeof o.content=="string"&&o.content!==""&&(a&&!j?yield*I(a.push(o.content)):yield*d("text",o.content));for(const f of o.tool_calls??[])yield*J(f);i.finish_reason&&(k=i.finish_reason),typeof i.stop_reason=="string"&&(N=i.stop_reason)}}catch(e){yield e instanceof L?p(e.type,e.message):p("api_error",e.message);return}if(!_||k===null&&!O){yield p("api_error",_?"Upstream stream ended before completion":"Upstream stream ended without data");return}const w=oe(k);if(w){yield p(w.type,w.message);return}a&&(yield*I(a.end())),yield*F();const R=U().at(-1),K=R===void 0||V(R.args.join(""));yield*y();for(const e of T)yield*e.kind==="details"?E(e.items):d(e.kind,e.text,e.key);yield*y(),b===0&&(yield*g("text",{type:"text",text:""}),yield*y());const M=se(k,{hasToolCalls:c.size>0,matchedStop:N,argumentsComplete:K});yield s("message_delta",{delta:M,usage:z(S)}),yield s("message_stop",{})}l(ge,"stream");export{ge as stream};
1
+ var L=Object.defineProperty;var l=(b,a)=>L(b,"name",{value:a,configurable:!0});import{resolve as P}from"../../../../../../../lib/settings.mjs";import{TranslatorError as Q,openaiToAnthropicType as V,rewriteContextOverflow as W}from"../../../../../../../lib/errors.mjs";import{isComplete as X}from"../../../../../../../lib/arguments.mjs";import{messageId as Y,anthropicToolId as Z,restoreName as $}from"../../../../../../../lib/ids.mjs";import{sign as ee,reasoningOf as te,reasoningKey as ne,detailsText as ie,mergeDetail as oe,createThinkSplitter as se}from"../../../../../../../lib/thinking.mjs";import{finishError as le,toAnthropicStop as re,toAnthropicUsage as q}from"../../../../../../../lib/finish.mjs";import{messages as ae}from"../../../../../../../lib/sse.mjs";async function*_e(b,a,B){const u=P(B),F=a?.toolNames??{},d=u.thinkTags?se(u.thinkOpen):null,c=new Map;let _=!1,j=0,n=null,N=null,k=null,O=null,h="",v=!1,A=!1,C=0,T=!1,U=!1,E=!1;const w=[],s=l((e,t)=>({event:e,data:{type:e,...t}}),"event"),p=l((e,t)=>s("error",{error:{type:e,message:t}}),"fail"),J=l(e=>{const t={};return u.reasoningRoundTrip&&(e.key!==null&&(t[e.key]=e.text),e.details.length>0&&(t.reasoning_details=e.details)),Object.keys(t).length>0?t:void 0},"carried");function*y(){if(n!==null){n.kind==="thinking"?yield s("content_block_delta",{index:n.index,delta:{type:"signature_delta",signature:ee(J(n.carry),a?.producer)}}):n.kind==="tool"&&(n.entry.state="closed",n.entry.sent||(yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:"{}"}}))),yield s("content_block_stop",{index:n.index}),n=null;for(const e of c.values()){if(e.state!=="pending")continue;e.state="closed";const t=j++,i=e.args.join("");yield s("content_block_start",{index:t,content_block:e.block}),yield s("content_block_delta",{index:t,delta:{type:"input_json_delta",partial_json:i===""?"{}":i}}),yield s("content_block_stop",{index:t})}}}l(y,"close");function*K(){for(const e of I()){if(e.state!=="buffered")continue;yield*g("tool",e.block,e);const t=e.args.join("");t!==""&&(e.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:t}})),yield*y()}}l(K,"flushBuffered");function I(){return[...c.entries()].sort((e,t)=>e[0]-t[0]).map(e=>e[1])}l(I,"ordered");function*g(e,t,i){yield*y(),n={kind:e,index:j++,entry:i,carry:{key:null,text:"",details:[]}},yield s("content_block_start",{index:n.index,content_block:t})}l(g,"begin");function*r(e,t,i=null){if(e==="text"&&E&&(t=t.trimStart()),t==="")return;if(E=e==="thinking",e==="text"&&(v=!0),n?.kind==="tool"){w.push({kind:e,text:t,key:i});return}n?.kind!==e&&(yield*g(e,e==="text"?{type:"text",text:""}:{type:"thinking",thinking:"",signature:""})),i!==null&&(n.carry.key??=i,n.carry.text+=t);const o=e==="text"?{type:"text_delta",text:t}:{type:"thinking_delta",thinking:t};yield s("content_block_delta",{index:n.index,delta:o})}l(r,"piece");function*R(e){if(n?.kind==="tool"){w.push({kind:"details",items:e});return}n?.kind!=="thinking"&&(yield*g("thinking",{type:"thinking",thinking:"",signature:""}));for(const t of e)oe(n.carry.details,t);n.carry.key===null&&(yield*r("thinking",ie(e)))}l(R,"details");function*z(e){yield*r("thinking",e.reasoning),yield*r("text",e.text)}l(z,"pieces");function*M(e){let t=e.index;t===void 0&&(t=e.id===void 0?C:c.size),C=t;let i=c.get(t);if(i===void 0){const x=e.function?.name??"",m={type:"tool_use",id:Z(e.id),name:$(F,x),input:{}};d?.pending()&&(U=!0);const f=u.toolStreaming==="buffer"||U;i={state:f?"buffered":"pending",sent:!1,args:[],block:m},c.set(t,i),!f&&n?.kind!=="tool"&&(i.state="open",yield*g("tool",m,i))}let o=e.function?.arguments;o!==null&&typeof o=="object"&&(o=JSON.stringify(o)),!(o==null||o==="")&&(i.args.push(o),i.state==="open"&&(i.sent=!0,yield s("content_block_delta",{index:n.index,delta:{type:"input_json_delta",partial_json:o}})))}l(M,"toolCall");try{for await(const e of ae(b)){if(e.data==="[DONE]"){A=!0;break}const t=e.data;if(t.error){const f=t.error.message??"Upstream error";yield p(V(t.error),W(f)??f);return}_||(_=!0,yield s("message_start",{message:{id:Y(),type:"message",role:"assistant",model:a?.model??t.model,content:[],stop_reason:null,stop_sequence:null,usage:q(t.usage)}})),t.usage&&(N=t.usage,a&&(a.upstreamUsage=t.usage));const i=t.choices?.[0];if(!i)continue;const o=i.delta??{},x=te(o);let m="";x!==""&&!T&&(T=!0,d&&(m=d.release().text)),yield*r("thinking",x,ne(o)),yield*r("text",m),u.reasoningRoundTrip&&Array.isArray(o.reasoning_details)&&o.reasoning_details.length>0&&(yield*R(o.reasoning_details)),typeof o.content=="string"&&o.content!==""&&(d&&!T?yield*z(d.push(o.content)):yield*r("text",o.content)),typeof o.refusal=="string"&&(h+=o.refusal);for(const f of o.tool_calls??[])yield*M(f);i.finish_reason&&(k=i.finish_reason),typeof i.stop_reason=="string"&&(O=i.stop_reason)}}catch(e){yield e instanceof Q?p(e.type,e.message):p("api_error",e.message);return}if(!_||k===null&&!A){yield p("api_error",_?"Upstream stream ended before completion":"Upstream stream ended without data");return}const S=le(k);if(S){yield p(S.type,S.message);return}d&&(yield*z(d.end())),yield*K();const D=I().at(-1),G=D===void 0||X(D.args.join(""));yield*y();for(const e of w)yield*e.kind==="details"?R(e.items):r(e.kind,e.text,e.key);!v&&h!==""&&(yield*r("text",h)),yield*y(),j===0&&(yield*g("text",{type:"text",text:""}),yield*y());const H=re(k,{hasToolCalls:c.size>0,matchedStop:O,argumentsComplete:G,refusal:h});yield s("message_delta",{delta:H,usage:q(N)}),yield s("message_stop",{})}l(_e,"stream");export{_e as stream};
2
2
  //# sourceMappingURL=stream.mjs.map
@@ -1,2 +1,2 @@
1
- var g=Object.defineProperty;var n=(t,e)=>g(t,"name",{value:e,configurable:!0});import{context as v,self as m}from"../lib/runtime.mjs";import{capture as w}from"../lib/capture.mjs";import{TranslatorError as d}from"../lib/errors.mjs";import{warn as p}from"../lib/warn.mjs";import*as h from"../lib/http.mjs";async function U(t={}){const e=w(m,v),{status:o}=m,f=t.network!==!1;for(const r of e.drivers){const s=r.info.fields;if(s!==void 0&&!(Array.isArray(s)&&s.every(i=>typeof i=="string")))throw new d(`Driver ${r.name}: info().fields must be an array of field names`,{code:"invalid_driver",status:500})}const a={transport:e.state.transport,signal:t.signal,timeout:e.config.detectTimeout};return await Promise.all(e.state.endpoints.map(r=>y(e,r,f,a))),o()}n(U,"detect");async function y(t,e,o,f){let a,r=null;if(e.backend!=="auto"){if(a=t.drivers.find(s=>s.name===e.backend),!a)throw new d(`Unknown backend "${e.backend}" for upstream ${e.name}`,{code:"unknown_backend",status:500});r={version:e.version}}else if(o){const s={endpoint:e,...f,probes:new Map};let i=!1;for(const[c,l]of t.drivers.entries()){if(!i&&l.info.probes?.length>0){i=!0;for(const u of t.drivers.slice(c))for(const b of u.info.probes??[])h.probe(s,b)}if(r=await k(l,s),r){a=l;break}}}if(a||(a=t.drivers.find(s=>s.name==="compatible"),r={reachable:null,models:[]}),e.driver=a.name,e.protocol=a.info.protocol,e.facts=r,e.driverSettings=await a.settings?.(r)??{},e.probed={},o&&e.backend==="auto"&&a.probe){const s=n(c=>e.settings[c]!==void 0||t.config.settings[c]!==void 0,"given"),i={inlineSystem:t.settings(e).inlineSystem==="auto",images:!s("images")};(i.inlineSystem||i.images)&&(e.probed=await a.probe({endpoint:e,facts:r,want:i,...f}))}r.reachable===!1&&p(t.config,t.state,`Upstream ${e.name} (${e.url}) did not answer detection; using the generic OpenAI-compatible driver`)}n(y,"bind");async function k(t,e){try{return await t.detect?.(e)??null}catch{return null}}n(k,"detectWith");export{U as detect};
1
+ var v=Object.defineProperty;var n=(r,e)=>v(r,"name",{value:e,configurable:!0});import{context as g,self as m}from"../lib/runtime.mjs";import{capture as w}from"../lib/capture.mjs";import{TranslatorError as d}from"../lib/errors.mjs";import{warn as y}from"../lib/warn.mjs";import{emit as h}from"../lib/events.mjs";import*as p from"../lib/http.mjs";async function D(r={}){const e=w(m,g),{status:o}=m,f=r.network!==!1;for(const a of e.drivers){const s=a.info.fields;if(s!==void 0&&!(Array.isArray(s)&&s.every(i=>typeof i=="string")))throw new d(`Driver ${a.name}: info().fields must be an array of field names`,{code:"invalid_driver",status:500})}const t={transport:e.state.transport,signal:r.signal,timeout:e.config.detectTimeout};return await Promise.all(e.state.endpoints.map(a=>k(e,a,f,t))),o()}n(D,"detect");async function k(r,e,o,f){let t,a=null;if(e.backend!=="auto"){if(t=r.drivers.find(s=>s.name===e.backend),!t)throw new d(`Unknown backend "${e.backend}" for upstream ${e.name}`,{code:"unknown_backend",status:500});a={version:e.version}}else if(o){const s={endpoint:e,...f,probes:new Map};let i=!1;for(const[l,c]of r.drivers.entries()){if(!i&&c.info.probes?.length>0){i=!0;for(const u of r.drivers.slice(l))for(const b of u.info.probes??[])p.probe(s,b)}if(a=await $(c,s),a){t=c;break}}}if(t||(t=r.drivers.find(s=>s.name==="compatible"),a={reachable:null,models:[]}),e.driver=t.name,e.protocol=t.info.protocol,e.facts=a,e.driverSettings=await t.settings?.(a)??{},e.probed={},o&&e.backend==="auto"&&t.probe){const s=n(l=>e.settings[l]!==void 0||r.config.settings[l]!==void 0,"given"),i={inlineSystem:r.settings(e).inlineSystem==="auto",images:!s("images")};(i.inlineSystem||i.images)&&(e.probed=await t.probe({endpoint:e,facts:a,want:i,...f}))}a.reachable===!1?y(r.config,r.state,`Upstream ${e.name} (${e.url}) did not answer detection; using the generic OpenAI-compatible driver`,{type:"detect",kind:"unreachable",endpoint:e.name,url:e.url,driver:t.name}):h({config:r.config,state:r.state},{type:"detect",kind:"driver",level:"info",message:`Upstream ${e.name} (${e.url}): driver ${t.name}`,endpoint:e.name,url:e.url,driver:t.name})}n(k,"bind");async function $(r,e){try{return await r.detect?.(e)??null}catch{return null}}n($,"detectWith");export{D as detect};
2
2
  //# sourceMappingURL=detect.mjs.map
@@ -1,2 +1,2 @@
1
- var a=Object.defineProperty;var e=(s,o)=>a(s,"name",{value:o,configurable:!0});function t(){return{name:"anthropic",protocol:"anthropic.messages",order:20,auth:"x-api-key",headers:{"anthropic-version":"2023-06-01"},paths:{messages:"/v1/messages",models:"/v1/models",count:"/v1/messages/count_tokens"}}}e(t,"info");export{t as info};
1
+ var t=Object.defineProperty;var e=(s,o)=>t(s,"name",{value:o,configurable:!0});function a(){return{name:"anthropic",protocol:"anthropic.messages",order:20,auth:"x-api-key",strict:!0,headers:{"anthropic-version":"2023-06-01"},paths:{messages:"/v1/messages",models:"/v1/models",count:"/v1/messages/count_tokens"}}}e(a,"info");export{a as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var r=Object.defineProperty;var o=(e,t)=>r(e,"name",{value:t,configurable:!0});import{VLLM_FIELDS as a}from"../../../lib/passthrough.mjs";function m(){return{name:"compatible",protocol:"openai.chat",order:100,auth:"bearer",fields:a,paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}o(m,"info");export{m as info};
1
+ var r=Object.defineProperty;var o=(t,e)=>r(t,"name",{value:e,configurable:!0});import{VLLM_FIELDS as a}from"../../../lib/passthrough.mjs";function l(){return{name:"compatible",protocol:"openai.chat",order:100,auth:"bearer",strict:!1,fields:a,paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}o(l,"info");export{l as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var a=Object.defineProperty;var e=(o,t)=>a(o,"name",{value:t,configurable:!0});function n(){return{name:"deepseek",protocol:"openai.chat",order:35,auth:"bearer",paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}e(n,"info");export{n as info};
1
+ var a=Object.defineProperty;var e=(o,t)=>a(o,"name",{value:t,configurable:!0});function c(){return{name:"deepseek",protocol:"openai.chat",order:35,auth:"bearer",strict:!1,paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}e(c,"info");export{c as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var a=Object.defineProperty;var p=(e,t)=>a(e,"name",{value:t,configurable:!0});function r(){return{name:"llamacpp",protocol:"openai.chat",order:40,auth:"bearer",probes:["/props"],fields:["top_k","min_p","chat_template_kwargs","repetition_penalty","repeat_penalty","grammar"],paths:{chat:"/v1/chat/completions",models:"/v1/models",props:"/props"}}}p(r,"info");export{r as info};
1
+ var a=Object.defineProperty;var e=(p,t)=>a(p,"name",{value:t,configurable:!0});function r(){return{name:"llamacpp",protocol:"openai.chat",order:40,auth:"bearer",strict:!1,probes:["/props"],fields:["top_k","min_p","chat_template_kwargs","repetition_penalty","repeat_penalty","grammar"],paths:{chat:"/v1/chat/completions",models:"/v1/models",props:"/props"}}}e(r,"info");export{r as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var r=Object.defineProperty;var o=(e,a)=>r(e,"name",{value:a,configurable:!0});function t(){return{name:"ollama",protocol:"openai.chat",order:60,auth:"bearer",probes:["/api/version"],paths:{chat:"/v1/chat/completions",models:"/v1/models",version:"/api/version"}}}o(t,"info");export{t as info};
1
+ var r=Object.defineProperty;var o=(e,a)=>r(e,"name",{value:a,configurable:!0});function i(){return{name:"ollama",protocol:"openai.chat",order:60,auth:"bearer",strict:!1,probes:["/api/version"],paths:{chat:"/v1/chat/completions",models:"/v1/models",version:"/api/version"}}}o(i,"info");export{i as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var a=Object.defineProperty;var o=(e,t)=>a(e,"name",{value:t,configurable:!0});function r(){return{name:"openai",protocol:"openai.chat",order:30,auth:"bearer",paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}o(r,"info");export{r as info};
1
+ var r=Object.defineProperty;var o=(t,e)=>r(t,"name",{value:e,configurable:!0});function n(){return{name:"openai",protocol:"openai.chat",order:30,auth:"bearer",strict:!0,paths:{chat:"/v1/chat/completions",models:"/v1/models"}}}o(n,"info");export{n as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var t=Object.defineProperty;var e=(o,r)=>t(o,"name",{value:r,configurable:!0});function a(){return{name:"sglang",protocol:"openai.chat",order:50,auth:"bearer",probes:["/get_server_info"],fields:["top_k","min_p","repetition_penalty","chat_template_kwargs","skip_special_tokens","ignore_eos","regex","ebnf","separate_reasoning"],paths:{chat:"/v1/chat/completions",models:"/v1/models",serverInfo:"/get_server_info"}}}e(a,"info");export{a as info};
1
+ var r=Object.defineProperty;var e=(t,o)=>r(t,"name",{value:o,configurable:!0});function s(){return{name:"sglang",protocol:"openai.chat",order:50,auth:"bearer",strict:!1,probes:["/get_server_info"],fields:["top_k","min_p","repetition_penalty","chat_template_kwargs","skip_special_tokens","ignore_eos","regex","ebnf","separate_reasoning"],paths:{chat:"/v1/chat/completions",models:"/v1/models",serverInfo:"/get_server_info"}}}e(s,"info");export{s as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -1,2 +1,2 @@
1
- var r=Object.defineProperty;var o=(e,t)=>r(e,"name",{value:t,configurable:!0});import{VLLM_FIELDS as n}from"../../../lib/passthrough.mjs";function l(){return{name:"vllm",protocol:"openai.chat",order:10,auth:"bearer",fields:n,paths:{chat:"/v1/chat/completions",models:"/v1/models",tokenize:"/tokenize",version:"/version"}}}o(l,"info");export{l as info};
1
+ var r=Object.defineProperty;var e=(o,t)=>r(o,"name",{value:t,configurable:!0});import{VLLM_FIELDS as i}from"../../../lib/passthrough.mjs";function s(){return{name:"vllm",protocol:"openai.chat",order:10,auth:"bearer",strict:!0,fields:i,paths:{chat:"/v1/chat/completions",models:"/v1/models",tokenize:"/tokenize",version:"/version"}}}e(s,"info");export{s as info};
2
2
  //# sourceMappingURL=info.mjs.map
@@ -0,0 +1,2 @@
1
+ var _=Object.defineProperty;var f=(e,s)=>_(e,"name",{value:s,configurable:!0});import{context as g,self as b}from"../../lib/runtime.mjs";import{capture as $}from"../../lib/capture.mjs";import{resolve as w,serves as A}from"../../lib/route.mjs";import*as h from"../../lib/http.mjs";import*as v from"../../lib/pool.mjs";import{emit as O}from"../../lib/events.mjs";const P="/v1/embeddings";async function J(e,s={}){const{transport:y}=g.state,{error:m}=b,a=$(b,g,"openai"),n=f((r,t,l={})=>m.build(r,t,{...l,front:"openai"}),"fail");if(!e||typeof e!="object"||Array.isArray(e))return n(400,"The request body must be a JSON object",{code:"invalid_body"});if(typeof e.model!="string"||e.model==="")return n(400,"model is required",{code:"invalid_body",param:"model"});const T=Object.hasOwn(a.config.aliases,e.model)?a.config.aliases[e.model]:e.model;if(!a.state.endpoints.some(r=>A(r,T)))return n(404,`The model "${e.model}" is not served by any configured upstream.`,{code:"model_not_found",param:"model"});const u=w(a,e,{advance:!0}),c=u.pool.filter(r=>r.protocol==="openai.chat");if(c.length===0)return n(400,`The model "${e.model}" is served by an Anthropic-protocol upstream, which has no embeddings API.`,{code:"embeddings_unsupported",param:"model"});const j={...e,model:u.model};let i;for(let r=0;r<c.length;r++){const t=c[r],l=a.driver(t);t.health.inflight++,t.health.requests++;let o;try{o=await h.json(y,h.join(t.url,P),{method:"POST",headers:{"content-type":"application/json",accept:"application/json",...l.info.headers,...h.headers(t,l.info.auth,s.headers)},body:j,signal:s.signal})}finally{t.health.inflight--}if(s.signal?.aborted)return n(499,"The request was aborted",{code:"aborted"});const d=o.status===0;if(!d&&o.status<500)return v.succeeded(t),o.ok?o.body===null||typeof o.body!="object"?n(502,"The upstream returned a body that is not JSON",{code:"bad_gateway"}):{status:200,headers:{"content-type":"application/json"},body:o.body}:m(o.status,o.body,{},{front:"openai",upstream:t.name,native:!0,model:e.model});const p=d?`Could not reach the upstream (${t.name}): ${o.error?.message}`:`HTTP ${o.status}`;v.failed(a.config,t,p),O(a,{type:"error",kind:d?"transport":"upstream",level:"error",message:d?p:`Upstream ${t.name} answered HTTP ${o.status}`,endpoint:t.name,model:u.model,log:s.log}),i={endpoint:t,result:o,reason:p}}return i.result.status===0?n(502,i.reason,{code:"upstream_unreachable"}):m(i.result.status,i.result.body,{},{front:"openai",upstream:i.endpoint.name,native:!0,model:e.model})}f(J,"send");export{J as send};
2
+ //# sourceMappingURL=send.mjs.map
@@ -0,0 +1,2 @@
1
+ var f=Object.defineProperty;var e=(t,o)=>f(t,"name",{value:o,configurable:!0});import{context as n}from"../../lib/runtime.mjs";import*as r from"../../lib/events.mjs";function i(t,o){r.off(n.state.events,t,o)}e(i,"off");export{i as off};
2
+ //# sourceMappingURL=off.mjs.map
@@ -0,0 +1,2 @@
1
+ var n=Object.defineProperty;var e=(t,o)=>n(t,"name",{value:o,configurable:!0});import{context as r}from"../../lib/runtime.mjs";import*as m from"../../lib/events.mjs";function i(t,o){return m.on(r.state.events,t,o)}e(i,"on");export{i as on};
2
+ //# sourceMappingURL=on.mjs.map
@@ -1,3 +1,3 @@
1
- var _=Object.defineProperty;var p=(e,r)=>_(e,"name",{value:r,configurable:!0});import{context as b,self as q}from"../lib/runtime.mjs";import{capture as F}from"../lib/capture.mjs";import{resolve as S}from"../lib/route.mjs";import*as $ from"../lib/http.mjs";import{filterChatBody as T}from"../lib/passthrough.mjs";import*as j from"../lib/images.mjs";import*as x from"../lib/tools.mjs";import{LIMITS as L}from"../lib/toolsearch.mjs";import{warn as h}from"../lib/warn.mjs";import{fit as B,pinBody as I}from"../lib/effort.mjs";function M(e){return`${e.driver}:${e.protocol}:${URL.canParse(e.url)?new URL(e.url).host:e.url}`}p(M,"producerOf");async function G(e,r={}){const a=F(q,b,r.front),i=S(a,e,{endpoint:r.endpoint,advance:r.hold===!0&&r.endpoint===void 0});if(r.hold!==!0)return y(a,e,r,i);i.endpoint.health.inflight++;try{return await y(a,e,r,i)}catch(t){throw i.endpoint.health.inflight--,t}}p(G,"request");async function y(e,r,a,i){const{endpoint:t,model:m,unserved:O,convert:f,pool:U,pin:d}=i,u=Object.hasOwn(e.config.efforts,m)?e.config.efforts[m]:void 0;d&&(r=I(r,d,e.front));const n=e.driver(t),v=`${t.name}
2
- ${m}`,w=a.images===!1||e.state.textOnly.has(v)&&e.settings(t).imageFallback,l={...w?{...e.settings(t),images:!1}:e.settings(t),...d?.effort===void 0?{}:{effort:!0}},g=r.stream===!0;let o,c;if(f?({body:o,state:c}=await f.request(r,l,{producer:M(t),budget:a.budget,listed:u!==void 0}),c.toolSearch?.capped&&h(e.config,e.state,`Tool search: more than ${L.definitions} tool definitions came back in ToolSearch results for ${t.name}; the rest are not offered.`)):o=e.front==="openai"&&(a.filter??l.passthroughFilter===!0)?T(r,n.info.fields):{...r},a.usage===!0&&g&&e.front==="openai"){if(f)c.includeUsage=!0;else if(l.streamUsage){const s=o.stream_options&&typeof o.stream_options=="object"?o.stream_options:{};o.stream_options={...s,include_usage:!0}}}w&&!f&&e.front==="openai"&&(o=j.strip(o)),a.tools===!1&&(o=x.strip(o)),o.model=m,u&&t.protocol==="openai.chat"&&B(o,u,m,s=>h(e.config,e.state,s)),c?.reasoningMissing&&h(e.config,e.state,`Upstream ${t.name}: assistant turns with tool calls have no reasoning to send back (the client dropped its thinking blocks or their signatures), which servers that need it with tools will refuse.`),n.request&&(o=await n.request(o,{endpoint:t,settings:l,levels:u,state:c,warn:p(s=>h(e.config,e.state,s),"warn")}));const k=t.protocol==="openai.chat"?n.info.paths.chat:n.info.paths.messages;return{upstream:t.name,pool:U.map(s=>s.name),method:"POST",url:$.join(t.url,k),path:k,headers:{"content-type":"application/json",accept:g?"text/event-stream":"application/json",...n.info.headers,...f===null&&t.protocol==="anthropic.messages"?a.clientHeaders:void 0,...$.headers(t,n.info.auth,a.headers)},body:o,state:{v:1,upstream:t.name,front:e.front,native:f===null,model:r.model,stream:g,unserved:O,convert:c},images:{sent:j.carries(o),retry:l.imageFallback&&t.protocol==="openai.chat",key:v},tools:{sent:x.carries(o),retry:l.toolFallback&&t.protocol==="openai.chat"}}}p(y,"prepare");export{G as request};
1
+ var T=Object.defineProperty;var p=(e,n)=>T(e,"name",{value:n,configurable:!0});import{context as q,self as I}from"../lib/runtime.mjs";import{capture as L}from"../lib/capture.mjs";import{resolve as B}from"../lib/route.mjs";import*as U from"../lib/http.mjs";import{filterChatBody as E}from"../lib/passthrough.mjs";import{addSampling as M}from"../lib/sampling.mjs";import*as F from"../lib/images.mjs";import*as S from"../lib/tools.mjs";import{LIMITS as P}from"../lib/toolsearch.mjs";import{warn as b}from"../lib/warn.mjs";import{emit as R}from"../lib/events.mjs";import{fit as C,pinBody as H}from"../lib/effort.mjs";import{relax as z,strictTools as A}from"../lib/strict.mjs";import{TranslatorError as D}from"../lib/errors.mjs";function G(e){return`${e.driver}:${e.protocol}:${URL.canParse(e.url)?new URL(e.url).host:e.url}`}p(G,"producerOf");async function ne(e,n={}){const r=L(I,q,n.front),c=B(r,e,{endpoint:n.endpoint,advance:n.hold===!0&&n.endpoint===void 0});if(n.hold!==!0)return _(r,e,n,c);c.endpoint.health.inflight++;try{return await _(r,e,n,c)}catch(t){throw c.endpoint.health.inflight--,t}}p(ne,"request");function J(e,n,r,c,t,f){const g=A(n);if(g.length===0)return n;const i=g.filter(a=>a.problems.length>0);if(i.length>0&&t.unknownFields==="error")throw new D(`tools: ${i[0].name}: schema is outside the strict subset (${i[0].problems.join("; ")})`,{code:"unsupported_content",param:"tools"});const k=z(n);if(f.retry===!0)return k;const u=p((a,h)=>b(e.config,e.state,a,{kind:h,endpoint:r.name,log:f.log}),"tell");for(const a of i)u(`Upstream ${r.name}: strict tool ${a.name} has a schema outside the strict subset: ${a.problems.join("; ")} (sent without strict)`,"strict");const d=g.filter(a=>a.problems.length===0);return c.info.strict!==!0&&d.length>0&&u(`Upstream ${r.name}: the ${c.name} backend does not enforce strict tool use (${d.map(a=>a.name).join(", ")})`,"strict"),k}p(J,"checkStrict");async function _(e,n,r,c){const{endpoint:t,model:f,unserved:g,convert:i,pool:k,pin:u}=c,d=Object.hasOwn(e.config.efforts,f)?e.config.efforts[f]:void 0;u&&(n=H(n,u,e.front));const a=e.driver(t),h=`${t.name}
2
+ ${f}`,w=r.images===!1||e.state.textOnly.has(h)&&e.settings(t).imageFallback,$=e.settings(t),x=r.jsonObject==="instruction"||e.state.jsonInstruction.has(h)&&$.jsonObjectFallback,m={...w?{...$,images:!1}:$,...x?{jsonObject:"instruction"}:{},...u?.effort===void 0?{}:{effort:!0}},v=n.stream===!0;let o,s;i?({body:o,state:s}=await i.request(n,m,{producer:G(t),budget:r.budget,listed:d!==void 0}),s.toolSearch?.capped&&b(e.config,e.state,`Tool search: more than ${P.definitions} tool definitions came back in ToolSearch results for ${t.name}; the rest are not offered.`,{kind:"toolsearch",endpoint:t.name,log:r.log})):o=e.front==="openai"&&(r.filter??m.passthroughFilter===!0)?E(n,a.info.fields):{...n};const y=e.front==="anthropic"?n.metadata?.sampling:void 0;if(t.protocol==="openai.chat"){const l=[];o=M(o,y,m,a.info.fields,l),s&&s.dropped.push(...l.filter(j=>!s.dropped.includes(j)))}else if(!i&&y!==void 0&&o.metadata?.sampling!==void 0){const{sampling:l,...j}=o.metadata;o={...o,metadata:j}}if(r.usage===!0&&v&&e.front==="openai"){if(i)s.includeUsage=!0;else if(m.streamUsage){const l=o.stream_options&&typeof o.stream_options=="object"?o.stream_options:{};o.stream_options={...l,include_usage:!0}}}w&&!i&&e.front==="openai"&&(o=F.strip(o)),r.tools===!1&&(o=S.strip(o)),o.model=f,o=J(e,o,t,a,m,r),d&&t.protocol==="openai.chat"&&C(o,d,f,(l,j)=>b(e.config,e.state,l,{type:"effort",endpoint:t.name,model:f,...j,log:r.log})),s?.reasoningMissing&&b(e.config,e.state,`Upstream ${t.name}: assistant turns with tool calls have no reasoning to send back (the client dropped its thinking blocks or their signatures), which servers that need it with tools will refuse.`,{kind:"reasoning",endpoint:t.name,log:r.log}),a.request&&(o=await a.request(o,{endpoint:t,settings:m,levels:d,state:s,warn:p(l=>b(e.config,e.state,l,{kind:"driver",endpoint:t.name,log:r.log}),"warn")})),s?.dropped?.length>0&&r.retry!==!0&&R(e,{type:"dropped",level:"debug",message:`Upstream ${t.name}: dropped ${s.dropped.join(", ")}`,endpoint:t.name,model:f,fields:[...s.dropped],log:r.log});const O=t.protocol==="openai.chat"?a.info.paths.chat:a.info.paths.messages;return{upstream:t.name,pool:k.map(l=>l.name),method:"POST",url:U.join(t.url,O),path:O,headers:{"content-type":"application/json",accept:v?"text/event-stream":"application/json",...a.info.headers,...i===null&&t.protocol==="anthropic.messages"?r.clientHeaders:void 0,...U.headers(t,a.info.auth,r.headers)},body:o,state:{v:1,upstream:t.name,front:e.front,native:i===null,model:n.model,stream:v,unserved:g,convert:s},images:{sent:F.carries(o),retry:m.imageFallback&&t.protocol==="openai.chat",key:h},tools:{sent:S.carries(o),retry:m.toolFallback&&t.protocol==="openai.chat"},json:{sent:s?.jsonSchemaEmulated===!0,retry:m.jsonObjectFallback&&t.protocol==="anthropic.messages",key:h}}}p(_,"prepare");export{ne as request};
3
3
  //# sourceMappingURL=request.mjs.map
package/dist/api/send.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var G=Object.defineProperty;var s=(o,n)=>G(o,"name",{value:n,configurable:!0});import{context as q,self as D}from"../lib/runtime.mjs";import{TranslatorError as H}from"../lib/errors.mjs";import*as I from"../lib/http.mjs";import*as K from"../lib/images.mjs";import*as Q from"../lib/tools.mjs";import{parse as V}from"../lib/upstream-error.mjs";import{meter as W,normalize as X}from"../lib/usage.mjs";import{capture as Y}from"../lib/capture.mjs";import{estimate as Z,bodyLength as tt,output as et,patch as at,stream as nt}from"../lib/estimate.mjs";import{warn as rt}from"../lib/warn.mjs";import*as L from"../lib/pool.mjs";import{createBudget as ot}from"../lib/thinking.mjs";const st={"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"};async function yt(o,n={}){const{transport:h,textOnly:p}=q.state,{request:y,response:w,stream:d,error:u}=D,f=u.build,{config:r,state:b}=q,x=Y(D,q,n.front),_=o&&typeof o=="object"&&!Array.isArray(o),S={model:null,requested:_&&typeof o.model=="string"?o.model:null,upstream:null,front:n.front??r.front,stream:_&&o.stream===!0},g=W(S,n.onUsage,l=>rt(r,b,l)),j=s(l=>Object.defineProperty(l,"usage",{value:g.usage,enumerable:!1,configurable:!0}),"attach");try{return j(await ut({transport:h,textOnly:p,request:y,response:w,stream:d,error:u,captured:x},o,n,g))}catch(l){if(!(l instanceof H))throw g.finish(n.signal?.aborted?"aborted":"error"),l;return g.finish("error"),j(f(l.status,l.message,{type:l.type,code:l.code,param:l.param,front:n.front}))}}s(yt,"send");async function ut({transport:o,textOnly:n,request:h,response:p,stream:y,error:w,captured:d},u,f,r){const b={front:f.front,headers:f.headers,clientHeaders:f.clientHeaders,filter:f.filter,usage:!0,budget:ot()},x=r.meta.front==="openai"&&u?.stream_options?.include_usage!==!0,_=s(e=>{r.meta.model=e.body.model??null,r.meta.upstream=e.upstream,e.state.native?r.source(null):r.source(()=>e.state.convert?.upstreamUsage,e.state.front==="anthropic"?"openai":"folded")},"note"),S=s(e=>{if(e.state.native)return{input:!1,output:!1};const t=X(e.state.front==="anthropic"?"openai":"folded",e.state.convert?.upstreamUsage);return t===null?{input:!0,output:!0}:{input:t.input_tokens===null&&t.cache_read_input_tokens===null&&t.cache_creation_input_tokens===null,output:t.output_tokens===null}},"gaps"),g=s(async e=>{const t=d.endpoint(e.upstream),a=d.driver(t);return(a.count&&!(x&&e.state.stream)?await a.count({endpoint:t,request:e.body,transport:o,signal:f.signal,timeout:d.config.detectTimeout}):null)??Z(e.body)},"input"),j=s(async(e,t)=>{const a=S(e);return!a.input&&!a.output?null:{input_tokens:a.input?await g(e):null,output_tokens:a.output?et(t):null}},"counts"),l=s((e,t,a,c,O)=>(r.finish(O),w(e,t,a,c)),"fail"),R=s(async e=>{let t=e,a=await M(o,t,f.signal,P());if(!a.ok&&a.status===400&&(t.images.sent&&t.images.retry||t.tools.sent&&t.tools.retry)){const c=await C(a),O=V(c,400).message,v={};if(t.images.sent&&t.images.retry&&K.refused(O)?(n.add(t.images.key),v.images=!1):t.tools.sent&&t.tools.retry&&Q.refused(O)&&(v.tools=!1),!("images"in v||"tools"in v))return{upstream:t,result:a,failure:c};t=await h(u,{...b,...v,endpoint:t.upstream}),_(t),a=await M(o,t,f.signal,P())}return{upstream:t,result:a}},"attempt");let i=await h(u,{...b,hold:!0});const A=i.pool;let N=0;const $=A.length>1?d.config.pool:null,P=s(()=>$&&{connectTimeout:$.connectTimeout,headersTimeout:N+1<A.length?$.headersTimeout:0},"limitsNow");let T=d.endpoint(i.upstream);const z=s(()=>T.health.inflight--,"release");let m,E;try{for(;;){const e=T;e.health.requests++,_(i);let t=null;try{({upstream:i,result:m,failure:E}=await R(i)),!m.ok&&m.status>=500&&(t=`HTTP ${m.status}`)}catch(c){if(!(c instanceof H)||c.code!=="upstream_unreachable")throw c;t=c.message,m=void 0,E=c}if(t===null){L.succeeded(e);break}L.failed(d.config,e,t);let a=null;for(;a===null&&!f.signal?.aborted&&N+1<A.length;)try{a=await h(u,{...b,endpoint:A[++N],hold:!0})}catch(c){if(!(c instanceof H)||c.code!=="endpoint_not_in_pool")throw c}if(a===null){if(m===void 0)throw E;break}try{await m?.body?.cancel?.()}catch{}z(),T=d.endpoint(a.upstream),i=a}}catch(e){throw z(),e}const F=T;T=null,r.usage.then(()=>F.health.inflight--);const B=I.plain(m.headers);if(!m.ok)return l(m.status,E??await C(m),B,i.state,"upstream_error");if(i.state.stream){const e=y(m.body,i.state),t=i.state.native?e:nt(r.meta.front,e,{gaps:s(()=>S(i),"gaps"),input:s(()=>g(i),"input"),report:s(a=>r.estimate(a),"report")});return{status:200,headers:st,stream:r.track(t,f.signal,x)}}const J=await C(m);if(J===null||typeof J!="object")return l(502,"The upstream returned a body that is not JSON",B,i.state,"error");const k=await p(J,i.state),U=await j(i,tt(r.meta.front,k));return U&&(k.usage=at(r.meta.front,k.usage,U),r.estimate(U)),r.json(k),r.finish("done"),{status:200,headers:{"content-type":"application/json"},body:k}}s(ut,"round");async function M(o,n,h,p=null){let y,w=!1,d=h;if(p&&p.headersTimeout>0){const u=new AbortController;d=h?AbortSignal.any([h,u.signal]):u.signal,y=setTimeout(()=>{w=!0,u.abort()},p.headersTimeout)}try{return await o(n.url,{method:n.method,headers:n.headers,body:JSON.stringify(n.body),signal:d,redirect:"error",...p&&p.connectTimeout>0?{connectTimeout:p.connectTimeout}:{}})}catch(u){if(h?.aborted)throw u;const f=w?`no response headers within ${p.headersTimeout} ms`:u.message;throw new H(`Could not reach the upstream (${n.upstream}): ${f}`,{code:"upstream_unreachable",status:502,details:{cause:u}})}finally{clearTimeout(y)}}s(M,"call");async function C(o){const n=await o.text();try{return JSON.parse(n)}catch{return n===""?null:n}}s(C,"parse");export{yt as send};
1
+ var tt=Object.defineProperty;var l=(u,s)=>tt(u,"name",{value:s,configurable:!0});import{context as R,self as Q}from"../lib/runtime.mjs";import{TranslatorError as C}from"../lib/errors.mjs";import*as et from"../lib/http.mjs";import*as at from"../lib/images.mjs";import*as rt from"../lib/tools.mjs";import{parse as st}from"../lib/upstream-error.mjs";import{meter as nt,normalize as ot}from"../lib/usage.mjs";import{capture as it}from"../lib/capture.mjs";import{estimate as lt,bodyLength as ut,output as ct,patch as mt,stream as dt}from"../lib/estimate.mjs";import{warn as ft}from"../lib/warn.mjs";import{start as pt}from"../lib/record.mjs";import{emit as V}from"../lib/events.mjs";import*as W from"../lib/pool.mjs";import{createBudget as gt}from"../lib/thinking.mjs";const ht={"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"};async function Ut(u,s={}){const{transport:y,textOnly:f,jsonInstruction:k}=R.state,{request:j,response:_,stream:i,error:g}=Q,d=g.build,{config:o,state:$}=R,h=it(Q,R,s.front),S=u&&typeof u=="object"&&!Array.isArray(u),x={model:null,requested:S&&typeof u.model=="string"?u.model:null,upstream:null,front:s.front??o.front,stream:S&&u.stream===!0},w=nt(x,s.onUsage,(m,E)=>ft(o,$,m,{type:"usage",...E,log:s.log})),O=l(m=>Object.defineProperty(m,"usage",{value:w.usage,enumerable:!1,configurable:!0}),"attach");try{return O(await yt({transport:y,textOnly:f,jsonInstruction:k,request:j,response:_,stream:i,error:g,captured:h},u,s,w))}catch(m){if(!(m instanceof C))throw s.signal?.aborted||V(h,{type:"error",kind:"exception",level:"error",message:String(m?.message??m),log:s.log}),w.finish(s.signal?.aborted?"aborted":"error"),m;return w.finish("error"),O(d(m.status,m.message,{type:m.type,code:m.code,param:m.param,front:s.front}))}}l(Ut,"send");async function yt({transport:u,textOnly:s,jsonInstruction:y,request:f,response:k,stream:j,error:_,captured:i},g,d,o){const $={front:d.front,headers:d.headers,clientHeaders:d.clientHeaders,filter:d.filter,usage:!0,budget:gt(),log:d.log},h=l(e=>{V(i,{...e,log:d.log})},"announce"),S=o.meta.front==="openai"&&g?.stream_options?.include_usage!==!0,x=l(e=>{o.meta.model=e.body.model??null,o.meta.upstream=e.upstream,e.state.native?o.source(null):o.source(()=>e.state.convert?.upstreamUsage,e.state.front==="anthropic"?"openai":"folded")},"note"),w=l(e=>{if(e.state.native)return{input:!1,output:!1};const t=ot(e.state.front==="anthropic"?"openai":"folded",e.state.convert?.upstreamUsage);return t===null?{input:!0,output:!0}:{input:t.input_tokens===null&&t.cache_read_input_tokens===null&&t.cache_creation_input_tokens===null,output:t.output_tokens===null}},"gaps"),O=l(async e=>{const t=i.endpoint(e.upstream),a=i.driver(t);return(a.count&&!(S&&e.state.stream)?await a.count({endpoint:t,request:e.body,transport:u,signal:d.signal,timeout:i.config.detectTimeout}):null)??lt(e.body)},"input"),m=l(async(e,t)=>{const a=w(e);return!a.input&&!a.output?null:{input_tokens:a.input?await O(e):null,output_tokens:a.output?ct(t):null}},"counts"),E=l((e,t,a,r,I)=>(o.finish(I),_(e,t,a,r)),"fail"),Y=l(async e=>{let t=e,a=await X(u,t,d.signal,G());const r=a.status,I=r===400&&[t.images,t.tools].some(v=>v.sent&&v.retry),L=(r===400||r===422)&&t.json.sent&&t.json.retry;if(!a.ok&&(I||L)){const v=await F(a),T=st(v,r).message,p={};if(r===400&&t.images.sent&&t.images.retry&&at.refused(T)?(s.add(t.images.key),p.images=!1):r===400&&t.tools.sent&&t.tools.retry&&rt.refused(T)?p.tools=!1:L&&(p.jsonObject="instruction"),!("images"in p||"tools"in p||"jsonObject"in p))return{upstream:t,result:a,failure:v};const b={upstream:t,result:a,failure:v};if("images"in p||"tools"in p){const M="images"in p?"images":"tools";h({type:"fallback",kind:M,level:"warn",message:`Upstream ${t.upstream}: ${t.state.model} refused ${M==="images"?"images":"tools"} (${r}: "${String(T).trim().slice(0,500)}"); sent the request again without them.`,endpoint:t.upstream,model:t.body.model,status:r,reason:String(T).trim().slice(0,500),action:M==="images"?"text-only":"without-tools"})}if(t=await f(g,{...$,...p,endpoint:t.upstream,retry:!0}),x(t),a=await X(u,t,d.signal,G()),L&&"jsonObject"in p){if(!a.ok){try{await a.body?.cancel?.()}catch{}return x(b.upstream),b}y.add(b.upstream.json.key),h({type:"fallback",kind:"json_object",level:"warn",message:`Upstream ${b.upstream.upstream}: ${b.upstream.state.model} rejected the json_object schema emulation (${r}: "${String(T).trim().slice(0,500)}"); sent it as a system instruction instead. Set jsonObject: "instruction" on this upstream to skip the first attempt.`,endpoint:b.upstream.upstream,model:b.upstream.body.model,status:r,reason:String(T).trim().slice(0,500),action:"instruction"})}}return{upstream:t,result:a}},"attempt");let n=await f(g,{...$,hold:!0});const H=n.pool;let z=0;const B=H.length>1?i.config.pool:null,G=l(()=>B&&{connectTimeout:B.connectTimeout,headersTimeout:z+1<H.length?B.headersTimeout:0},"limitsNow");let U=i.endpoint(n.upstream);const K=l(()=>U.health.inflight--,"release");let c,N;try{for(;;){const e=U;e.health.requests++,x(n);let t=null;try{({upstream:n,result:c,failure:N}=await Y(n)),!c.ok&&c.status>=500&&(t=`HTTP ${c.status}`,h({type:"error",kind:"upstream",level:"error",message:`Upstream ${e.name} answered HTTP ${c.status}`,endpoint:e.name,model:n.body.model,status:c.status}))}catch(r){if(!(r instanceof C)||r.code!=="upstream_unreachable")throw r;t=r.message,c=void 0,N=r,h({type:"error",kind:"transport",level:"error",message:r.message,endpoint:e.name,model:n.body.model})}if(t===null){W.succeeded(e);break}W.failed(i.config,e,t);let a=null;for(;a===null&&!d.signal?.aborted&&z+1<H.length;)try{a=await f(g,{...$,endpoint:H[++z],hold:!0})}catch(r){if(!(r instanceof C)||r.code!=="endpoint_not_in_pool")throw r}if(a===null){if(c===void 0)throw N;break}h({type:"failover",level:"warn",message:`Upstream ${e.name} failed (${t}); trying ${a.upstream}`,from:e.name,to:a.upstream,model:a.body.model,reason:t});try{await c?.body?.cancel?.()}catch{}K(),U=i.endpoint(a.upstream),n=a}}catch(e){throw K(),e}const Z=U;U=null,o.usage.then(()=>Z.health.inflight--);const q=et.plain(c.headers),J=pt(i,{body:g,sent:n,front:o.meta.front,requested:o.meta.requested,headers:q,log:d.log});if(!c.ok){const e=N??await F(c);return J.reply(c.status,q,e),E(c.status,e,q,n.state,"upstream_error")}if(n.state.stream){const e=j(J.raw(c.body),n.state),t=n.state.native?e:dt(o.meta.front,e,{gaps:l(()=>w(n),"gaps"),input:l(()=>O(n),"input"),report:l(a=>o.estimate(a),"report")});return{status:200,headers:ht,stream:J.events(o.track(t,d.signal,S))}}const P=await F(c);if(J.reply(c.status,q,P),P===null||typeof P!="object")return h({type:"error",kind:"upstream",level:"error",message:`Upstream ${n.upstream} returned a body that is not JSON`,endpoint:n.upstream,model:n.body.model,status:502}),E(502,"The upstream returned a body that is not JSON",q,n.state,"error");const A=await k(P,n.state),D=await m(n,ut(o.meta.front,A));return D&&(A.usage=mt(o.meta.front,A.usage,D),o.estimate(D)),o.json(A),o.finish("done"),{status:200,headers:{"content-type":"application/json"},body:A}}l(yt,"round");async function X(u,s,y,f=null){let k,j=!1,_=y;if(f&&f.headersTimeout>0){const i=new AbortController;_=y?AbortSignal.any([y,i.signal]):i.signal,k=setTimeout(()=>{j=!0,i.abort()},f.headersTimeout)}try{return await u(s.url,{method:s.method,headers:s.headers,body:JSON.stringify(s.body),signal:_,redirect:"error",...f&&f.connectTimeout>0?{connectTimeout:f.connectTimeout}:{}})}catch(i){if(y?.aborted)throw i;const g=j?`no response headers within ${f.headersTimeout} ms`:i.message;throw new C(`Could not reach the upstream (${s.upstream}): ${g}`,{code:"upstream_unreachable",status:502,details:{cause:i}})}finally{clearTimeout(k)}}l(X,"call");async function F(u){const s=await u.text();try{return JSON.parse(s)}catch{return s===""?null:s}}l(F,"parse");export{Ut as send};
2
2
  //# sourceMappingURL=send.mjs.map
@@ -1,2 +1,2 @@
1
- var h=Object.defineProperty;var o=(e,t)=>h(e,"name",{value:t,configurable:!0});import{context as a,self as u}from"../../lib/runtime.mjs";import{TranslatorError as l}from"../../lib/errors.mjs";import{register as v}from"../../lib/routes.mjs";import{capture as w}from"../../lib/capture.mjs";import{resolve as b}from"../../lib/route.mjs";import{resolve as y}from"../../lib/settings.mjs";async function E(e,t={}){const{config:n}=a;if(t.front!==void 0&&t.front!=="anthropic"&&t.front!=="openai")throw new l(`front must be "anthropic" or "openai" (got ${JSON.stringify(t.front)})`,{code:"invalid_config",status:500});for(const r of["authorize","onUsage"])if(t[r]!==void 0&&typeof t[r]!="function")throw new l(`${r} must be a function`,{code:"invalid_config",status:500});const{send:d,route:g,token:m,model:i,error:p,sse:f}=u,s=t.front??n.front,c=w(u,a,s);v(e,t,{front:s,filter:n.settings.passthroughFilter!==!1,interval:o(r=>{try{return c.settings(b(c,r).endpoint).pingInterval}catch{return y(n.settings).pingInterval}},"interval"),send:d,route:g,count:m.count,list:i.list,get:i.get,build:p.build,encode:f.encode,write:f.write})}o(E,"plugin");export{E as plugin};
1
+ var w=Object.defineProperty;var n=(o,t)=>w(o,"name",{value:t,configurable:!0});import{context as s,self as u}from"../../lib/runtime.mjs";import{TranslatorError as d}from"../../lib/errors.mjs";import{register as k}from"../../lib/routes.mjs";import{capture as x}from"../../lib/capture.mjs";import{resolve as y}from"../../lib/route.mjs";import{resolve as I}from"../../lib/settings.mjs";import{emit as T}from"../../lib/events.mjs";async function N(o,t={}){const{config:r}=s;if(t.front!==void 0&&t.front!=="anthropic"&&t.front!=="openai")throw new d(`front must be "anthropic" or "openai" (got ${JSON.stringify(t.front)})`,{code:"invalid_config",status:500});for(const e of["authorize","onUsage"])if(t[e]!==void 0&&typeof t[e]!="function")throw new d(`${e} must be a function`,{code:"invalid_config",status:500});const{send:m,route:p,token:h,model:c,error:v,sse:f,embeddings:b}=u,l=t.front??r.front,{state:g}=s,{events:i}=g;i.logger=o.log,o.addHook("onClose",async()=>{i.logger===o.log&&(i.logger=null)});const a=x(u,s,l);k(o,t,{front:l,filter:r.settings.passthroughFilter!==!1,interval:n(e=>{try{return a.settings(y(a,e).endpoint).pingInterval}catch{return I(r.settings).pingInterval}},"interval"),send:m,embed:b.send,route:p,count:h.count,list:c.list,get:c.get,emit:n(e=>T({config:r,state:g},e),"emit"),build:v.build,encode:f.encode,write:f.write})}n(N,"plugin");export{N as plugin};
2
2
  //# sourceMappingURL=plugin.mjs.map
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var i=Object.defineProperty;var n=(r,t)=>i(r,"name",{value:t,configurable:!0});import{fileURLToPath as d}from"node:url";import p from"@cldmv/slothlet";import{normalize as l}from"./lib/config.mjs";import{load as m}from"./lib/pdf.mjs";import{transport as c}from"./lib/transport.mjs";import{warn as s}from"./lib/warn.mjs";async function f(r){const t=l(r),o={endpoints:t.endpoints,transport:t.transport??c,servers:new Set,warned:new Set,textOnly:new Set,cursors:new Map,front:void 0},e=await m();e.errors.canvas&&s(t,o,`@napi-rs/canvas could not be loaded (${e.errors.canvas}); PDFs will be read as text only, without page images`),e.errors.unpdf&&s(t,o,`unpdf could not be loaded (${e.errors.unpdf}); PDF documents cannot be read and fall back to a note`);const a=await p({...r.slothlet,base:d(new URL("./api",import.meta.url)),mode:"eager",context:{config:t,state:o},silent:!0});return await a.detect({network:t.detect}),a}n(f,"createTranslator");import{TranslatorError as T}from"./lib/errors.mjs";var y=f;export{T as TranslatorError,f as createTranslator,y as default};
1
+ var i=Object.defineProperty;var a=(r,t)=>i(r,"name",{value:t,configurable:!0});import{fileURLToPath as d}from"node:url";import p from"@cldmv/slothlet";import{normalize as c}from"./lib/config.mjs";import{load as l}from"./lib/pdf.mjs";import{transport as f}from"./lib/transport.mjs";import{create as m,open as u}from"./lib/events.mjs";import{warn as s}from"./lib/warn.mjs";async function w(r){const t=c(r),o={endpoints:t.endpoints,transport:t.transport??f,servers:new Set,warned:new Set,events:m(t.onEvent),textOnly:new Set,jsonInstruction:new Set,cursors:new Map,front:void 0};u(o.events,t.logs);const e=await l();e.errors.canvas&&s(t,o,`@napi-rs/canvas could not be loaded (${e.errors.canvas}); PDFs will be read as text only, without page images`,{type:"detect",kind:"canvas",reason:String(e.errors.canvas)}),e.errors.unpdf&&s(t,o,`unpdf could not be loaded (${e.errors.unpdf}); PDF documents cannot be read and fall back to a note`,{type:"detect",kind:"unpdf",reason:String(e.errors.unpdf)});const n=await p({...r.slothlet,base:d(new URL("./api",import.meta.url)),mode:"eager",context:{config:t,state:o},silent:!0});return await n.detect({network:t.detect}),n}a(w,"createTranslator");import{TranslatorError as D}from"./lib/errors.mjs";var P=w;export{D as TranslatorError,w as createTranslator,P as default};
2
2
  //# sourceMappingURL=index.mjs.map
package/dist/lib/cli.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var f=Object.defineProperty;var l=(t,e)=>f(t,"name",{value:e,configurable:!0});import{readFile as d}from"node:fs/promises";import{parseArgs as S}from"node:util";const u=`llm-translator - run Claude Code (or any Anthropic/OpenAI client) against local LLM servers
1
+ var _=Object.defineProperty;var c=(t,e)=>_(t,"name",{value:e,configurable:!0});import{readFile as d}from"node:fs/promises";import{parseArgs as g}from"node:util";const u=`llm-translator - run Claude Code (or any Anthropic/OpenAI client) against local LLM servers
2
2
 
3
3
  Usage: llm-translator --upstream <url> [options]
4
4
 
@@ -13,7 +13,8 @@ Options:
13
13
  --api-key <key> Key clients must send (x-api-key or Authorization: Bearer)
14
14
  --allow-unauthenticated Allow a non-loopback --host without --api-key
15
15
  --config <file> JSON config file (translator config plus a "server" object)
16
- --silent Suppress warnings
16
+ --logs [path] Log warnings and errors to the console (default), or append every event as a JSON line to <path>
17
+ --silent Same as logs: false (no console output, no file)
17
18
  --no-detect Skip upstream detection
18
19
  --version Print the version
19
20
  --help Print this help
@@ -21,9 +22,9 @@ Options:
21
22
  Environment: LLM_TRANSLATOR_FRONT, LLM_TRANSLATOR_UPSTREAM, LLM_TRANSLATOR_UPSTREAM_KEY, LLM_TRANSLATOR_BACKEND,
22
23
  LLM_TRANSLATOR_HOST, LLM_TRANSLATOR_PORT, LLM_TRANSLATOR_API_KEY, LLM_TRANSLATOR_ALLOW_UNAUTHENTICATED (1), LLM_TRANSLATOR_CONFIG. Flags win over the
23
24
  environment, which wins over the config file.
24
- `;function O(t){return S({args:t,allowPositionals:!1,options:{front:{type:"string"},upstream:{type:"string",multiple:!0},"upstream-key":{type:"string"},backend:{type:"string"},model:{type:"string",multiple:!0},host:{type:"string"},port:{type:"string"},"api-key":{type:"string"},"allow-unauthenticated":{type:"boolean"},config:{type:"string"},silent:{type:"boolean"},"no-detect":{type:"boolean"},version:{type:"boolean"},help:{type:"boolean"}}}).values}l(O,"parse");function y(t,e,n){const{server:L,...p}=n,s=t.upstream??(e.LLM_TRANSLATOR_UPSTREAM?e.LLM_TRANSLATOR_UPSTREAM.split(","):void 0),r={...p};if(s){const i=t["upstream-key"]??e.LLM_TRANSLATOR_UPSTREAM_KEY,a=t.backend??e.LLM_TRANSLATOR_BACKEND;r.upstreams=s.map(o=>({url:o,apiKey:i,...a?{backend:a}:{}}))}const T=t.front??e.LLM_TRANSLATOR_FRONT;if(T&&(r.front=T),t.model){r.aliases={...r.aliases};for(const i of t.model){const a=i.indexOf("=");if(a<1)throw new Error(`--model expects alias=target (got "${i}")`);r.aliases[i.slice(0,a)]=i.slice(a+1)}}t.silent&&(r.silent=!0),t["no-detect"]&&(r.detect=!1);const A=t.port??e.LLM_TRANSLATOR_PORT,c={...L,...t.host??e.LLM_TRANSLATOR_HOST?{host:t.host??e.LLM_TRANSLATOR_HOST}:{},...A?{port:Number(A)}:{},...t["api-key"]??e.LLM_TRANSLATOR_API_KEY?{apiKey:t["api-key"]??e.LLM_TRANSLATOR_API_KEY}:{},...t["allow-unauthenticated"]||e.LLM_TRANSLATOR_ALLOW_UNAUTHENTICATED==="1"?{allowUnauthenticated:!0}:{}};return{translator:r,server:c}}l(y,"merge");const N={out:l(t=>process.stdout.write(`${t}
25
- `),"out"),err:l(t=>process.stderr.write(`${t}
26
- `),"err"),onSignal:l(t=>{process.once("SIGINT",t),process.once("SIGTERM",t)},"onSignal")};async function w(t,e=process.env,n=N,L={}){let p;try{p=O(t)}catch(s){return n.err(`${s.message}
25
+ `;function S(t){const e=t.map((o,l)=>o==="--logs"&&(l===t.length-1||t[l+1].startsWith("-"))?"--logs=":o);return g({args:e,allowPositionals:!1,options:{front:{type:"string"},upstream:{type:"string",multiple:!0},"upstream-key":{type:"string"},backend:{type:"string"},model:{type:"string",multiple:!0},host:{type:"string"},port:{type:"string"},"api-key":{type:"string"},"allow-unauthenticated":{type:"boolean"},config:{type:"string"},logs:{type:"string"},silent:{type:"boolean"},"no-detect":{type:"boolean"},version:{type:"boolean"},help:{type:"boolean"}}}).values}c(S,"parse");function h(t,e,o){const{server:l,...p}=o,s=t.upstream??(e.LLM_TRANSLATOR_UPSTREAM?e.LLM_TRANSLATOR_UPSTREAM.split(","):void 0),r={...p};if(s){const i=t["upstream-key"]??e.LLM_TRANSLATOR_UPSTREAM_KEY,a=t.backend??e.LLM_TRANSLATOR_BACKEND;r.upstreams=s.map(n=>({url:n,apiKey:i,...a?{backend:a}:{}}))}const T=t.front??e.LLM_TRANSLATOR_FRONT;if(T&&(r.front=T),t.model){r.aliases={...r.aliases};for(const i of t.model){const a=i.indexOf("=");if(a<1)throw new Error(`--model expects alias=target (got "${i}")`);r.aliases[i.slice(0,a)]=i.slice(a+1)}}t.silent&&(r.logs=!1),t.logs!==void 0&&(r.logs=t.logs===""?!0:t.logs),r.logs??=r.silent!==!0,delete r.silent,t["no-detect"]&&(r.detect=!1);const A=t.port??e.LLM_TRANSLATOR_PORT,L={...l,...t.host??e.LLM_TRANSLATOR_HOST?{host:t.host??e.LLM_TRANSLATOR_HOST}:{},...A?{port:Number(A)}:{},...t["api-key"]??e.LLM_TRANSLATOR_API_KEY?{apiKey:t["api-key"]??e.LLM_TRANSLATOR_API_KEY}:{},...t["allow-unauthenticated"]||e.LLM_TRANSLATOR_ALLOW_UNAUTHENTICATED==="1"?{allowUnauthenticated:!0}:{}};return{translator:r,server:L}}c(h,"merge");const y={out:c(t=>process.stdout.write(`${t}
26
+ `),"out"),err:c(t=>process.stderr.write(`${t}
27
+ `),"err"),onSignal:c(t=>{process.once("SIGINT",t),process.once("SIGTERM",t)},"onSignal")};async function w(t,e=process.env,o=y,l={}){let p;try{p=S(t)}catch(s){return o.err(`${s.message}
27
28
 
28
- ${u}`),2}if(p.help)return n.out(u),0;if(p.version)return n.out(L.version??(await import("../../package.json",{with:{type:"json"}})).default.version),0;try{const s=p.config??e.LLM_TRANSLATOR_CONFIG,{translator:r,server:T}=y(p,e,s?JSON.parse(await d(s,"utf8")):{}),c=await(L.createTranslator??(await import("../index.mjs")).createTranslator)(r),i=await c.server.start(T),a=c.status();n.out(`llm-translator (${a.front} front) listening on ${i.url}`);for(const o of a.upstreams??[]){const R=o.version??"unknown",m=o.probed?.inlineSystem??"auto",_=o.probed?.images??"default";n.out(` upstream ${o.name} ${o.url}: driver=${o.driver} version=${R} inlineSystem=${m} images=${_}`)}return await new Promise(o=>n.onSignal(()=>o())),await c.server.stop(),await c.slothlet.shutdown(),0}catch(s){return n.err(`llm-translator: ${s.message}`),1}}l(w,"main");export{w as main,y as merge,O as parse,N as processIo};
29
+ ${u}`),2}if(p.help)return o.out(u),0;if(p.version)return o.out(l.version??(await import("../../package.json",{with:{type:"json"}})).default.version),0;try{const s=p.config??e.LLM_TRANSLATOR_CONFIG,{translator:r,server:T}=h(p,e,s?JSON.parse(await d(s,"utf8")):{}),L=await(l.createTranslator??(await import("../index.mjs")).createTranslator)(r),i=await L.server.start(T),a=L.status();o.out(`llm-translator (${a.front} front) listening on ${i.url}`);for(const n of a.upstreams??[]){const f=n.version??"unknown",m=n.probed?.inlineSystem??"auto",R=n.probed?.images??"default";o.out(` upstream ${n.name} ${n.url}: driver=${n.driver} version=${f} inlineSystem=${m} images=${R}`)}return await new Promise(n=>o.onSignal(()=>n())),await L.server.stop(),await L.slothlet.shutdown(),0}catch(s){return o.err(`llm-translator: ${s.message}`),1}}c(w,"main");export{w as main,h as merge,S as parse,y as processIo};
29
30
  //# sourceMappingURL=cli.mjs.map
@@ -1,2 +1,2 @@
1
- var n=Object.defineProperty;var s=(t,r)=>n(t,"name",{value:r,configurable:!0});import{TranslatorError as o}from"./errors.mjs";import*as a from"./pool.mjs";import{normalizeAliases as i,normalizeEfforts as l}from"./effort.mjs";function u(t){let r=t.length;for(;t[r-1]==="/";)r--;const e=t.slice(0,r);return e.endsWith("/v1")?e.slice(0,-3):e}s(u,"baseUrl");function p(t,r){const e=typeof t=="string"?{url:t}:t;if(!e||typeof e!="object"||typeof e.url!="string"||e.url==="")throw new o(`upstreams[${r}] needs a "url"`,{code:"INVALID_CONFIG",status:500});return{name:e.name??`upstream-${r}`,url:u(e.url),apiKey:e.apiKey,headers:{...e.headers},backend:e.backend??"auto",models:Array.isArray(e.models)?[...e.models]:void 0,default:e.default===!0,settings:{...e.settings},version:e.version,driver:null,facts:null,driverSettings:{},probed:{},health:a.health()}}s(p,"endpoint");function h(t={}){const r=t.front??"anthropic";if(r!=="anthropic"&&r!=="openai")throw new o(`front must be "anthropic" or "openai" (got ${JSON.stringify(r)})`,{code:"INVALID_CONFIG",status:500});let e=t.upstreams??t.upstream;if(e!==void 0&&!Array.isArray(e)&&(e=[e]),!e||e.length===0)throw new o("at least one upstream is required (config.upstreams)",{code:"INVALID_CONFIG",status:500});return{front:r,endpoints:e.map(p),...i(t.aliases),efforts:l(t.efforts),pool:a.normalize(t.pool),settings:{...t.settings},detect:t.detect!==!1,detectTimeout:t.detectTimeout??5e3,transport:t.transport,silent:t.silent===!0}}s(h,"normalize");export{p as endpoint,h as normalize};
1
+ var i=Object.defineProperty;var a=(t,r)=>i(t,"name",{value:r,configurable:!0});import{TranslatorError as s}from"./errors.mjs";import*as n from"./pool.mjs";import{valid as l}from"./record.mjs";import{normalizeAliases as u,normalizeEfforts as p}from"./effort.mjs";function d(t){let r=t.length;for(;t[r-1]==="/";)r--;const e=t.slice(0,r);return e.endsWith("/v1")?e.slice(0,-3):e}a(d,"baseUrl");function f(t,r){const e=typeof t=="string"?{url:t}:t;if(!e||typeof e!="object"||typeof e.url!="string"||e.url==="")throw new s(`upstreams[${r}] needs a "url"`,{code:"INVALID_CONFIG",status:500});return{name:e.name??`upstream-${r}`,url:d(e.url),apiKey:e.apiKey,headers:{...e.headers},backend:e.backend??"auto",models:Array.isArray(e.models)?[...e.models]:void 0,default:e.default===!0,settings:{...e.settings},version:e.version,driver:null,facts:null,driverSettings:{},probed:{},health:n.health()}}a(f,"endpoint");function N(t={}){const r=t.front??"anthropic";if(r!=="anthropic"&&r!=="openai")throw new s(`front must be "anthropic" or "openai" (got ${JSON.stringify(r)})`,{code:"INVALID_CONFIG",status:500});let e=t.upstreams??t.upstream;if(e!==void 0&&!Array.isArray(e)&&(e=[e]),!e||e.length===0)throw new s("at least one upstream is required (config.upstreams)",{code:"INVALID_CONFIG",status:500});const o=t.logs??!1;if(typeof o!="boolean"&&(typeof o!="string"||o===""))throw new s("logs must be true, false or a file path (got "+JSON.stringify(o)+")",{code:"INVALID_CONFIG",status:500});if(t.onEvent!==void 0&&typeof t.onEvent!="function")throw new s("onEvent must be a function",{code:"INVALID_CONFIG",status:500});if(!l(t.capture))throw new s("capture must be false, a directory path or a function (got "+JSON.stringify(t.capture)+")",{code:"INVALID_CONFIG",status:500});return{front:r,endpoints:e.map(f),...u(t.aliases),efforts:p(t.efforts),pool:n.normalize(t.pool),settings:{...t.settings},detect:t.detect!==!1,detectTimeout:t.detectTimeout??5e3,transport:t.transport,logs:o,capture:t.capture||!1,events:t.events!==!1,onEvent:t.onEvent}}a(N,"normalize");export{f as endpoint,N as normalize};
2
2
  //# sourceMappingURL=config.mjs.map
@@ -1,2 +1,2 @@
1
- var c=Object.defineProperty;var l=(t,f)=>c(t,"name",{value:f,configurable:!0});import{TranslatorError as g}from"./errors.mjs";const s=Object.freeze(["minimal","low","medium","high","xhigh","max"]);function a(t){return new g(t,{code:"INVALID_CONFIG",status:500})}l(a,"invalid");function k(t){const f={};for(const[i,n]of Object.entries(t??{})){const e=Array.isArray(n)?n:n?.levels;if(!Array.isArray(e)||e.length===0)throw a(`efforts.${i} must be a non-empty list of levels or { levels, default }`);for(const u of e)if(!s.includes(u))throw a(`efforts.${i}: unknown level ${JSON.stringify(u)} (expected ${s.join(", ")})`);const o=s.filter(u=>e.includes(u)),r=Array.isArray(n)?void 0:n.default;if(r!=null&&!o.includes(r))throw a(`efforts.${i}.default must be one of its levels or null (got ${JSON.stringify(r)})`);f[i]={levels:o,default:r}}return f}l(k,"normalizeEfforts");function v(t){const f={},i={};for(const[n,e]of Object.entries(t??{})){if(typeof e=="string"){f[n]=e;continue}if(e===null||typeof e!="object"||typeof e.model!="string")throw a(`aliases.${n} must be a model name or { model, effort, thinking }`);if(e.effort!==void 0&&!s.includes(e.effort))throw a(`aliases.${n}.effort must be one of ${s.join(", ")} (got ${JSON.stringify(e.effort)})`);if(e.thinking!==void 0&&typeof e.thinking!="boolean")throw a(`aliases.${n}.thinking must be true or false`);f[n]=e.model;const o={};e.effort!==void 0&&(o.effort=e.effort),e.thinking!==void 0&&(o.thinking=e.thinking),Object.keys(o).length>0&&(i[n]=o)}return{aliases:f,pins:i}}l(v,"normalizeAliases");function d(t,f){const i=s.indexOf(f);let n=t[0];for(const e of t){const o=Math.abs(s.indexOf(e)-i),r=Math.abs(s.indexOf(n)-i);(o<r||o===r&&s.indexOf(e)>s.indexOf(n))&&(n=e)}return n}l(d,"nearest");function h(t){return t.default===void 0?d(t.levels,"medium"):t.default}l(h,"defaultOf");function x(t,f,i){const n={...t};return i==="openai"?(f.effort!==void 0&&(n.reasoning_effort=f.effort),f.thinking===!1?n.reasoning_effort="none":f.thinking===!0&&n.reasoning_effort==="none"&&delete n.reasoning_effort,n):(f.effort!==void 0&&(n.output_config={...t.output_config,effort:f.effort}),f.thinking===!1?n.thinking={type:"disabled"}:f.thinking===!0&&(t.thinking===void 0||t.thinking?.type==="disabled")&&(n.thinking={type:"adaptive"}),n)}l(x,"pinBody");function $(t,f,i,n){if(t.reasoning_effort==="none"||t.chat_template_kwargs?.enable_thinking===!1)return;const e=t.reasoning_effort;if(e==null){const r=h(f);r!==null&&(t.reasoning_effort=r);return}if(f.levels.includes(e)||!s.includes(e))return;const o=d(f.levels,e);n(`Effort "${e}" is not supported by ${i} (${f.levels.join(", ")}); using "${o}".`),t.reasoning_effort=o}l($,"fit");export{s as LEVELS,h as defaultOf,$ as fit,d as nearest,v as normalizeAliases,k as normalizeEfforts,x as pinBody};
1
+ var c=Object.defineProperty;var l=(t,f)=>c(t,"name",{value:f,configurable:!0});import{TranslatorError as g}from"./errors.mjs";const s=Object.freeze(["minimal","low","medium","high","xhigh","max"]);function u(t){return new g(t,{code:"INVALID_CONFIG",status:500})}l(u,"invalid");function k(t){const f={};for(const[i,n]of Object.entries(t??{})){const e=Array.isArray(n)?n:n?.levels;if(!Array.isArray(e)||e.length===0)throw u(`efforts.${i} must be a non-empty list of levels or { levels, default }`);for(const a of e)if(!s.includes(a))throw u(`efforts.${i}: unknown level ${JSON.stringify(a)} (expected ${s.join(", ")})`);const o=s.filter(a=>e.includes(a)),r=Array.isArray(n)?void 0:n.default;if(r!=null&&!o.includes(r))throw u(`efforts.${i}.default must be one of its levels or null (got ${JSON.stringify(r)})`);f[i]={levels:o,default:r}}return f}l(k,"normalizeEfforts");function v(t){const f={},i={};for(const[n,e]of Object.entries(t??{})){if(typeof e=="string"){f[n]=e;continue}if(e===null||typeof e!="object"||typeof e.model!="string")throw u(`aliases.${n} must be a model name or { model, effort, thinking }`);if(e.effort!==void 0&&!s.includes(e.effort))throw u(`aliases.${n}.effort must be one of ${s.join(", ")} (got ${JSON.stringify(e.effort)})`);if(e.thinking!==void 0&&typeof e.thinking!="boolean")throw u(`aliases.${n}.thinking must be true or false`);f[n]=e.model;const o={};e.effort!==void 0&&(o.effort=e.effort),e.thinking!==void 0&&(o.thinking=e.thinking),Object.keys(o).length>0&&(i[n]=o)}return{aliases:f,pins:i}}l(v,"normalizeAliases");function d(t,f){const i=s.indexOf(f);let n=t[0];for(const e of t){const o=Math.abs(s.indexOf(e)-i),r=Math.abs(s.indexOf(n)-i);(o<r||o===r&&s.indexOf(e)>s.indexOf(n))&&(n=e)}return n}l(d,"nearest");function h(t){return t.default===void 0?d(t.levels,"medium"):t.default}l(h,"defaultOf");function x(t,f,i){const n={...t};return i==="openai"?(f.effort!==void 0&&(n.reasoning_effort=f.effort),f.thinking===!1?n.reasoning_effort="none":f.thinking===!0&&n.reasoning_effort==="none"&&delete n.reasoning_effort,n):(f.effort!==void 0&&(n.output_config={...t.output_config,effort:f.effort}),f.thinking===!1?n.thinking={type:"disabled"}:f.thinking===!0&&(t.thinking===void 0||t.thinking?.type==="disabled")&&(n.thinking={type:"adaptive"}),n)}l(x,"pinBody");function $(t,f,i,n){if(t.reasoning_effort==="none"||t.chat_template_kwargs?.enable_thinking===!1)return;const e=t.reasoning_effort;if(e==null){const r=h(f);r!==null&&(t.reasoning_effort=r);return}if(f.levels.includes(e)||!s.includes(e))return;const o=d(f.levels,e);n(`Effort "${e}" is not supported by ${i} (${f.levels.join(", ")}); using "${o}".`,{requested:e,used:o,levels:[...f.levels]}),t.reasoning_effort=o}l($,"fit");export{s as LEVELS,h as defaultOf,$ as fit,d as nearest,v as normalizeAliases,k as normalizeEfforts,x as pinBody};
2
2
  //# sourceMappingURL=effort.mjs.map
@@ -0,0 +1,4 @@
1
+ var m=Object.defineProperty;var s=(n,e)=>m(n,"name",{value:e,configurable:!0});import{closeSync as h,mkdirSync as $,openSync as k,appendFileSync as S}from"node:fs";import d from"node:path";function J(n){const e=new Map;return typeof n=="function"&&e.set("*",new Set([n])),{listeners:e,sink:{console:!1,file:null},logger:null}}s(J,"create");function M(n,e){if(n.sink.console=e===!0,n.sink.file=null,typeof e!="string")return;const o=d.resolve(e);try{$(d.dirname(o),{recursive:!0}),h(k(o,"a")),n.sink.file=o}catch(r){console.warn(`[llm-translator] could not open the log file ${o} (${r.message}); logging is off`)}}s(M,"open");function N(n,e,o){if(typeof e!="string"||typeof o!="function")throw new TypeError("events.on needs an event name and a function");return n.listeners.has(e)||n.listeners.set(e,new Set),n.listeners.get(e).add(o),()=>v(n,e,o)}s(N,"on");function v(n,e,o){n.listeners.get(e)?.delete(o)}s(v,"off");function u(n,e,o){const{sink:r}=n.events;if((o===!1?null:o??n.events.logger)?.[e.level]?.({event:e},e.message),r.console&&(e.level==="warn"||e.level==="error")&&!n.warned.has(e.message)&&(n.warned.add(e.message),console[e.level==="error"?"error":"warn"](`[llm-translator] ${e.message}`)),r.file!==null)try{S(r.file,`${JSON.stringify(e)}
2
+ `)}catch(i){const f=r.file;r.file=null,console.warn(`[llm-translator] could not write the log file ${f} (${i.message}); file logging is off`)}}s(u,"write");function g(n,e,o){const r=`Event listener for "${e}" failed: ${o?.message??o}`,l=`listener
3
+ ${r}`;n.warned.has(l)||(n.warned.add(l),u(n,{type:"listener",level:"warn",message:r,time:Date.now(),event:e},!1))}s(g,"failed");function x(n,e,o,r){try{const l=o(r);typeof l?.then=="function"&&l.then(void 0,i=>g(n,e,i))}catch(l){g(n,e,l)}}s(x,"call");function O({config:n,state:e},o){const{type:r,kind:l,level:i="info",message:f,log:p,...w}=o,a={type:r,...l===void 0?{}:{kind:l},level:i,message:f,time:Date.now(),...w};if(n.events!==!1){const t=new Set([r]);i==="warn"&&t.add("warning"),i==="error"&&t.add("error"),t.add("log"),t.add("*");for(const c of t)for(const y of[...e.events.listeners.get(c)??[]])x(e,c,y,a)}return u(e,a,p),a}s(O,"emit");export{J as create,O as emit,v as off,N as on,M as open};
4
+ //# sourceMappingURL=events.mjs.map
@@ -1,2 +1,2 @@
1
- var p=Object.defineProperty;var n=(t,e)=>p(t,"name",{value:e,configurable:!0});const _={abort:{type:"api_error",status:502},aborted:{type:"api_error",status:502},error:{type:"api_error",status:502},insufficient_system_resource:{type:"overloaded_error",status:503}};function u(t){if(typeof t!="string"||!Object.hasOwn(_,t))return null;const{type:e,status:o}=_[t];return{type:e,status:o,code:"upstream_finish_"+t,message:`Upstream ended the response with finish_reason "${t}"`}}n(u,"finishError");function a(t,{hasToolCalls:e,matchedStop:o,argumentsComplete:r=!0}){return e&&(t!=="length"&&t!=="model_length"||r)?{stop_reason:"tool_use",stop_sequence:null}:t==="length"||t==="model_length"?{stop_reason:"max_tokens",stop_sequence:null}:t==="content_filter"?{stop_reason:"refusal",stop_sequence:null}:typeof o=="string"&&o!==""?{stop_reason:"stop_sequence",stop_sequence:o}:{stop_reason:"end_turn",stop_sequence:null}}n(a,"toAnthropicStop");function l(t){switch(t){case"max_tokens":return"length";case"tool_use":return"tool_calls";case"refusal":return"content_filter";default:return"stop"}}n(l,"toOpenAIFinish");function i(t){const e=t?.prompt_tokens??0,o=t?.prompt_tokens_details?.cached_tokens??0;return{input_tokens:Math.max(0,e-o),output_tokens:t?.completion_tokens??0,cache_creation_input_tokens:0,cache_read_input_tokens:o}}n(i,"toAnthropicUsage");function k(t){const e=t?.cache_read_input_tokens??0,o=(t?.input_tokens??0)+e+(t?.cache_creation_input_tokens??0),r=t?.output_tokens??0,s={prompt_tokens:o,completion_tokens:r,total_tokens:o+r};return e>0&&(s.prompt_tokens_details={cached_tokens:e}),s}n(k,"toOpenAIUsage");export{u as finishError,a as toAnthropicStop,i as toAnthropicUsage,l as toOpenAIFinish,k as toOpenAIUsage};
1
+ var _=Object.defineProperty;var r=(t,e)=>_(t,"name",{value:e,configurable:!0});const p={abort:{type:"api_error",status:502},aborted:{type:"api_error",status:502},error:{type:"api_error",status:502},insufficient_system_resource:{type:"overloaded_error",status:503}};function l(t){if(typeof t!="string"||!Object.hasOwn(p,t))return null;const{type:e,status:o}=p[t];return{type:e,status:o,code:"upstream_finish_"+t,message:`Upstream ended the response with finish_reason "${t}"`}}r(l,"finishError");function a(t,{hasToolCalls:e,matchedStop:o,argumentsComplete:s=!0,refusal:n}){return e&&(t!=="length"&&t!=="model_length"||s)?{stop_reason:"tool_use",stop_sequence:null}:t==="length"||t==="model_length"?{stop_reason:"max_tokens",stop_sequence:null}:t==="content_filter"?{stop_reason:"refusal",stop_sequence:null,stop_details:{type:"refusal",category:null,explanation:typeof n=="string"&&n!==""?n:null}}:typeof o=="string"&&o!==""?{stop_reason:"stop_sequence",stop_sequence:o}:{stop_reason:"end_turn",stop_sequence:null}}r(a,"toAnthropicStop");function i(t){switch(t){case"max_tokens":return"length";case"tool_use":return"tool_calls";case"refusal":return"content_filter";default:return"stop"}}r(i,"toOpenAIFinish");function k(t){const e=t?.prompt_tokens??0,o=t?.prompt_tokens_details?.cached_tokens??0;return{input_tokens:Math.max(0,e-o),output_tokens:t?.completion_tokens??0,cache_creation_input_tokens:0,cache_read_input_tokens:o}}r(k,"toAnthropicUsage");function d(t){const e=t?.cache_read_input_tokens??0,o=(t?.input_tokens??0)+e+(t?.cache_creation_input_tokens??0),s=t?.output_tokens??0,n={prompt_tokens:o,completion_tokens:s,total_tokens:o+s};return e>0&&(n.prompt_tokens_details={cached_tokens:e}),n}r(d,"toOpenAIUsage");export{l as finishError,a as toAnthropicStop,k as toAnthropicUsage,i as toOpenAIFinish,d as toOpenAIUsage};
2
2
  //# sourceMappingURL=finish.mjs.map
@@ -0,0 +1,3 @@
1
+ var E=Object.defineProperty;var s=(e,c)=>E(e,"name",{value:c,configurable:!0});import{randomBytes as F}from"node:crypto";import{mkdirSync as O,writeFileSync as T}from"node:fs";import y from"node:path";import{items as v}from"./source.mjs";import{warn as $}from"./warn.mjs";const u=1e6,j=/key|token|secret|auth|cookie|password/i;function m(e){const c={};for(const[r,i]of Object.entries(e??{}))c[r.toLowerCase()]=j.test(r)?"[redacted]":i;return c}s(m,"redact");function L(e){return e===void 0||e===!1||typeof e=="function"||typeof e=="string"&&e!==""}s(L,"valid");const C={raw:s(e=>e,"raw"),events:s(e=>e,"events"),reply(){}};function M({config:e,state:c},r){const i=e.capture;if(!i)return C;const{sent:f}=r,h=F(6).toString("hex"),w=Date.now(),d={time:w,id:h,front:r.front,requested:r.requested,model:f.body?.model??null,endpoint:f.upstream,stream:f.state.stream,client:{body:r.body},upstream:{url:f.url,headers:m(f.headers),body:f.body},response:{}};let a="",g=!1,l=0,p=!1;const S=[],b=s(()=>{try{if(typeof i=="function"){const t=i(d);typeof t?.then=="function"&&t.then(void 0,n=>k(n))}else O(y.resolve(i),{recursive:!0}),T(y.join(y.resolve(i),`${w}-${h}.json`),`${JSON.stringify(d,null,2)}
2
+ `)}catch(t){k(t)}},"emit"),k=s(t=>{$(e,c,`Could not capture the exchange (${t instanceof Error?t.message:String(t)}); the reply is not affected`,{type:"warning",kind:"capture",log:r.log})},"problem");return{raw(t){return(async function*(){const n=new TextDecoder;for await(const o of v(t))g||(a+=typeof o=="string"?o:n.decode(o,{stream:!0}),a.length>u&&(a=a.slice(0,u),g=!0,p=!0)),yield o})()},events(t){return(async function*(){try{for await(const n of v(t)){if(l<=u){const o=JSON.stringify(n).length;l+=o,l>u?p=!0:S.push(n)}yield n}}finally{d.response={status:200,headers:m(r.headers),raw:a,events:S,truncated:p},b()}})()},reply(t,n,o){d.response={status:t,headers:m(n),body:o},b()}}}s(M,"start");export{u as STREAM_LIMIT,m as redact,M as start,L as valid};
3
+ //# sourceMappingURL=record.mjs.map
@@ -1,2 +1,2 @@
1
- var H=Object.defineProperty;var i=(e,n)=>H(e,"name",{value:n,configurable:!0});import{timingSafeEqual as O}from"node:crypto";import{TranslatorError as p}from"./errors.mjs";import{messageId as S}from"./ids.mjs";import{sign as T}from"./thinking.mjs";const j=64*1024*1024,D={"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"},w=Symbol("stalled"),x=Symbol("gone");async function I(e,n){if(!(n>0))return e;let s;const l=new Promise(f=>{s=setTimeout(f,n,w)});try{return await Promise.race([e,l])}finally{clearTimeout(s)}}i(I,"settle");async function*L(e,n,s){let l=!1;try{const f=n.front==="anthropic";f&&(yield{event:"message_start",data:{type:"message_start",message:{id:S(),type:"message",role:"assistant",model:s,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}}},yield{event:"content_block_start",data:{type:"content_block_start",index:0,content_block:{type:"thinking",thinking:"",signature:""}}});const a=await e,m=i(function*(){yield{event:"content_block_delta",data:{type:"content_block_delta",index:0,delta:{type:"signature_delta",signature:T()}}},yield{event:"content_block_stop",data:{type:"content_block_stop",index:0}}},"closeEarly");if(a.stream){l=!0;let d=null;for await(const c of a.stream){if(!f){yield c;continue}if(c.event!=="message_start"){if(d===null&&c.event==="content_block_start"&&c.data.content_block.type==="thinking"){d=0;continue}d===null&&(yield*m(),d=1),yield d>0&&typeof c.data?.index=="number"?{...c,data:{...c.data,index:c.data.index+d}}:c}}return}f&&(yield*m()),yield*v(n,a.body)}finally{l||e.then(f=>f.stream?.return?.(),()=>{})}}i(L,"late");function*v(e,n){if(e.front==="anthropic"){yield{event:"error",data:n};return}yield{data:n},yield{data:"[DONE]"}}i(v,"failure");async function E(e,n,s,l,f,a=200,m=D){e.hijack();const d=e.raw;d.writeHead(a,m);try{await n.write(d,l,{front:n.front,interval:f})}catch(c){if(!s.signal.aborted){const g=c instanceof p;g||e.log.error(c);const{body:_}=n.build(g?c.status:502,g?c.message:"Internal server error",g?{type:c.type,code:c.code}:{});for(const t of v(n,_))d.write(n.encode(t))}}return d.end(),e}i(E,"stream");function z(e,n){const s=Buffer.from(e),l=Buffer.from(n);return s.length===l.length&&O(s,l)}i(z,"same");function B(e){const n=/^Bearer\s+(.+)$/i.exec(e.authorization??"");return e["x-api-key"]||n?.[1]||""}i(B,"keyOf");function C(e){const n={};for(const[s,l]of Object.entries(e))(s==="anthropic-beta"||s==="anthropic-version"||s.startsWith("x-claude-code-"))&&(n[s]=String(l));return n}i(C,"forwardable");function P(e){if(e===!0)return{ok:!0,context:void 0};if(e&&typeof e=="object"&&e.ok===!0)return{ok:!0,context:e.context};const n=e&&typeof e=="object"&&e.ok===!1?e:{};return{ok:!1,status:Number.isInteger(n.status)&&n.status>=400&&n.status<=599?n.status:401,message:typeof n.message=="string"&&n.message!==""?n.message:"unauthorized"}}i(P,"verdictOf");function W(e,n,s){const{front:l,filter:f}=s,a={...s,build:i((t,o,r={})=>s.build(t,o,{...r,front:l}),"build"),send:i((t,o)=>s.send(t,{...o,front:l,filter:f}),"send"),route:i(t=>s.route(t,{front:l}),"route"),count:i((t,o)=>s.count(t,{...o,front:l}),"count"),list:i(t=>s.list({...t,front:l}),"list"),get:i((t,o)=>s.get(t,{...o,front:l}),"get")},m=[n.apiKey??[]].flat().filter(Boolean),d=n.bodyLimit??j,c=new WeakMap,g=i((t,o)=>t.code(o.status).headers(o.headers).send(o.body),"reject");e.setErrorHandler((t,o,r)=>{if(t instanceof p)return g(r,a.build(t.status,t.message,{type:t.type,code:t.code,param:t.param}));const u=t.statusCode??500;return u<500?g(r,a.build(u,t.message)):(o.log.error(t),g(r,a.build(u,"Internal server error")))}),e.addHook("onRequest",async(t,o)=>{if(m.length===0||t.routeOptions.config?.public)return;const r=B(t.headers);if(!(r&&m.some(u=>z(r,u))))return g(o,a.build(401,"invalid x-api-key"))}),typeof n.authorize=="function"&&e.addHook("preHandler",async(t,o)=>{if(t.routeOptions.config?.public)return;let r=null;if(t.body&&typeof t.body=="object"&&!Array.isArray(t.body))try{r=a.route(t.body)}catch{}let u;try{u=P(await n.authorize({method:t.method,url:t.url,headers:t.headers,body:t.body,front:a.front,route:r}))}catch(y){t.log.error(y),u={ok:!1,status:401,message:"unauthorized"}}if(!u.ok)return g(o,a.build(u.status,u.message));c.set(t,u.context)}),e.route({method:["GET","HEAD"],url:"/",config:{public:!0},handler:i(async(t,o)=>o.send({ok:!0}),"handler")}),e.route({method:["GET","HEAD"],url:"/api/hello",config:{public:!0},handler:i(async(t,o)=>o.send({ok:!0}),"handler")}),e.get("/v1/models",async(t,o)=>{const r=new AbortController;return o.raw.on("close",()=>r.abort()),a.list({signal:r.signal})}),e.get("/v1/models/*",async(t,o)=>{const r=new AbortController;return o.raw.on("close",()=>r.abort()),a.get(t.params["*"],{signal:r.signal})});const _=a.front==="anthropic"?"/v1/messages":"/v1/chat/completions";e.post(_,{bodyLimit:d},async(t,o)=>{if(o.raw.destroyed)return o;const r=new AbortController;o.raw.on("close",()=>{o.raw.writableFinished||r.abort()});const u=typeof n.onUsage=="function"?h=>n.onUsage(h,c.get(t)):void 0,y=a.interval(t.body),k=a.send(t.body,{signal:r.signal,clientHeaders:C(t.headers),onUsage:u});k.catch(()=>{});const A=new Promise(h=>r.signal.addEventListener("abort",()=>h(x),{once:!0})),b=await I(Promise.race([k,A]),t.body?.stream===!0?y:0);return b===x?(k.then(h=>h.stream?.return?.(),()=>{}),o):b===w?E(o,a,r,L(k,a,t.body?.model),y):b.stream?E(o,a,r,b.stream,y,b.status,b.headers):g(o,b)}),a.front==="anthropic"&&e.post("/v1/messages/count_tokens",{bodyLimit:d},async(t,o)=>{const r=new AbortController;return o.raw.on("close",()=>r.abort()),a.count(t.body,{signal:r.signal})})}i(W,"register");export{L as late,W as register};
1
+ var S=Object.defineProperty;var c=(e,o)=>S(e,"name",{value:o,configurable:!0});import{timingSafeEqual as H}from"node:crypto";import{TranslatorError as w}from"./errors.mjs";import{messageId as O}from"./ids.mjs";import{sign as T}from"./thinking.mjs";const j=64*1024*1024,C={"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache","x-accel-buffering":"no"},p=Symbol("stalled"),v=Symbol("gone");async function D(e,o){if(!(o>0))return e;let a;const l=new Promise(g=>{a=setTimeout(g,o,p)});try{return await Promise.race([e,l])}finally{clearTimeout(a)}}c(D,"settle");async function*I(e,o,a){let l=!1;try{const g=o.front==="anthropic";g&&(yield{event:"message_start",data:{type:"message_start",message:{id:O(),type:"message",role:"assistant",model:a,content:[],stop_reason:null,stop_sequence:null,usage:{input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0}}}},yield{event:"content_block_start",data:{type:"content_block_start",index:0,content_block:{type:"thinking",thinking:"",signature:""}}});const s=await e,m=c(function*(){yield{event:"content_block_delta",data:{type:"content_block_delta",index:0,delta:{type:"signature_delta",signature:T()}}},yield{event:"content_block_stop",data:{type:"content_block_stop",index:0}}},"closeEarly");if(s.stream){l=!0;let d=null;for await(const i of s.stream){if(!g){yield i;continue}if(i.event!=="message_start"){if(d===null&&i.event==="content_block_start"&&i.data.content_block.type==="thinking"){d=0;continue}d===null&&(yield*m(),d=1),yield d>0&&typeof i.data?.index=="number"?{...i,data:{...i.data,index:i.data.index+d}}:i}}return}g&&(yield*m()),yield*x(o,s.body)}finally{l||e.then(g=>g.stream?.return?.(),()=>{})}}c(I,"late");function*x(e,o){if(e.front==="anthropic"){yield{event:"error",data:o};return}yield{data:o},yield{data:"[DONE]"}}c(x,"failure");async function E(e,o,a,l,g,s=200,m=C){e.hijack();const d=e.raw;d.writeHead(s,m);try{await o.write(d,l,{front:o.front,interval:g})}catch(i){if(!a.signal.aborted){const f=i instanceof w;f||(e.log.error(i),o.emit({type:"error",kind:"route",level:"error",message:String(i?.message??i),log:!1}));const{body:_}=o.build(f?i.status:502,f?i.message:"Internal server error",f?{type:i.type,code:i.code}:{});for(const t of x(o,_))d.write(o.encode(t))}}return d.end(),e}c(E,"stream");function L(e,o){const a=Buffer.from(e),l=Buffer.from(o);return a.length===l.length&&H(a,l)}c(L,"same");function z(e){const o=/^Bearer\s+(.+)$/i.exec(e.authorization??"");return e["x-api-key"]||o?.[1]||""}c(z,"keyOf");function B(e){const o={};for(const[a,l]of Object.entries(e))(a==="anthropic-beta"||a==="anthropic-version"||a.startsWith("x-claude-code-"))&&(o[a]=String(l));return o}c(B,"forwardable");function P(e){if(e===!0)return{ok:!0,context:void 0};if(e&&typeof e=="object"&&e.ok===!0)return{ok:!0,context:e.context};const o=e&&typeof e=="object"&&e.ok===!1?e:{};return{ok:!1,status:Number.isInteger(o.status)&&o.status>=400&&o.status<=599?o.status:401,message:typeof o.message=="string"&&o.message!==""?o.message:"unauthorized"}}c(P,"verdictOf");function R(e,o,a){const{front:l,filter:g}=a,s={...a,build:c((t,n,r={})=>a.build(t,n,{...r,front:l}),"build"),send:c((t,n)=>a.send(t,{...n,front:l,filter:g}),"send"),route:c(t=>a.route(t,{front:l}),"route"),count:c((t,n)=>a.count(t,{...n,front:l}),"count"),embed:c((t,n)=>a.embed(t,n),"embed"),list:c(t=>a.list({...t,front:l}),"list"),get:c((t,n)=>a.get(t,{...n,front:l}),"get")},m=[o.apiKey??[]].flat().filter(Boolean),d=o.bodyLimit??j,i=new WeakMap,f=c((t,n)=>t.code(n.status).headers(n.headers).send(n.body),"reject");e.setErrorHandler((t,n,r)=>{if(t instanceof w)return f(r,s.build(t.status,t.message,{type:t.type,code:t.code,param:t.param}));const u=t.statusCode??500;return u<500?f(r,s.build(u,t.message)):(n.log.error(t),s.emit({type:"error",kind:"route",level:"error",message:String(t.message),status:u,log:!1}),f(r,s.build(u,"Internal server error")))}),e.addHook("onRequest",async(t,n)=>{if(m.length===0||t.routeOptions.config?.public)return;const r=z(t.headers);if(!(r&&m.some(u=>L(r,u))))return f(n,s.build(401,"invalid x-api-key"))}),typeof o.authorize=="function"&&e.addHook("preHandler",async(t,n)=>{if(t.routeOptions.config?.public)return;let r=null;if(t.body&&typeof t.body=="object"&&!Array.isArray(t.body))try{r=s.route(t.body)}catch{}let u;try{u=P(await o.authorize({method:t.method,url:t.url,headers:t.headers,body:t.body,front:s.front,route:r}))}catch(b){t.log.error(b),s.emit({type:"error",kind:"route",level:"error",message:String(b?.message??b),log:!1}),u={ok:!1,status:401,message:"unauthorized"}}if(!u.ok)return f(n,s.build(u.status,u.message));i.set(t,u.context)}),e.route({method:["GET","HEAD"],url:"/",config:{public:!0},handler:c(async(t,n)=>n.send({ok:!0}),"handler")}),e.route({method:["GET","HEAD"],url:"/api/hello",config:{public:!0},handler:c(async(t,n)=>n.send({ok:!0}),"handler")}),e.get("/v1/models",async(t,n)=>{const r=new AbortController;return n.raw.on("close",()=>r.abort()),s.list({signal:r.signal})}),e.get("/v1/models/*",async(t,n)=>{const r=new AbortController;return n.raw.on("close",()=>r.abort()),s.get(t.params["*"],{signal:r.signal})});const _=s.front==="anthropic"?"/v1/messages":"/v1/chat/completions";e.post(_,{bodyLimit:d},async(t,n)=>{if(n.raw.destroyed)return n;const r=new AbortController;n.raw.on("close",()=>{n.raw.writableFinished||r.abort()});const u=typeof o.onUsage=="function"?h=>o.onUsage(h,i.get(t)):void 0,b=s.interval(t.body),k=s.send(t.body,{signal:r.signal,clientHeaders:B(t.headers),onUsage:u,log:t.log});k.catch(()=>{});const A=new Promise(h=>r.signal.addEventListener("abort",()=>h(v),{once:!0})),y=await D(Promise.race([k,A]),t.body?.stream===!0?b:0);return y===v?(k.then(h=>h.stream?.return?.(),()=>{}),n):y===p?E(n,s,r,I(k,s,t.body?.model),b):y.stream?E(n,s,r,y.stream,b,y.status,y.headers):f(n,y)}),s.front==="openai"&&e.post("/v1/embeddings",{bodyLimit:d},async(t,n)=>{const r=new AbortController;return n.raw.on("close",()=>{n.raw.writableFinished||r.abort()}),f(n,await s.embed(t.body,{signal:r.signal,log:t.log}))}),s.front==="anthropic"&&e.post("/v1/messages/count_tokens",{bodyLimit:d},async(t,n)=>{const r=new AbortController;return n.raw.on("close",()=>r.abort()),s.count(t.body,{signal:r.signal})})}c(R,"register");export{I as late,R as register};
2
2
  //# sourceMappingURL=routes.mjs.map
@@ -0,0 +1,2 @@
1
+ var a=Object.defineProperty;var u=(e,i)=>a(e,"name",{value:i,configurable:!0});import{TranslatorError as p}from"./errors.mjs";const f=["seed","frequency_penalty","presence_penalty"];function h(e,i,l,c=[],o=[]){const s={...l.sampling,...i!==null&&typeof i=="object"&&!Array.isArray(i)?i:{}};let r=e;for(const[n,t]of Object.entries(s))if(!(t==null||Object.hasOwn(e,n))){if(!f.includes(n)&&!c.includes(n)){if(l.unknownFields==="error")throw new p(`sampling.${n}: is not accepted by this upstream`,{code:"unsupported_field",param:`sampling.${n}`});o.includes(n)||o.push(n);continue}r===e&&(r={...e}),r[n]=t}return r}u(h,"addSampling");export{h as addSampling};
2
+ //# sourceMappingURL=sampling.mjs.map