@lunora/ai 1.0.0-alpha.130 → 1.0.0-alpha.131
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.
- package/dist/create.d.mts +2 -2
- package/dist/create.d.ts +2 -2
- package/dist/create.mjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.mjs +1 -1
- package/dist/packem_shared/createAi-DHYK5EHD.mjs +1 -0
- package/dist/packem_shared/{defineRag-BOS3IQeP.mjs → defineRag-Dq2bA1Xl.mjs} +1 -1
- package/dist/packem_shared/{types.d-BG8Olmuo.d.mts → types.d-KCPinSfY.d.mts} +5 -1
- package/dist/packem_shared/{types.d-BG8Olmuo.d.ts → types.d-KCPinSfY.d.ts} +5 -1
- package/dist/packem_shared/{usage-C5GJNFt9.mjs → usage-DQdygGEV.mjs} +1 -1
- package/dist/rag/index.d.mts +1 -1
- package/dist/rag/index.d.ts +1 -1
- package/dist/rag/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/packem_shared/createAi-GYEHZ8tt.mjs +0 -1
package/dist/create.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as LunoraAiOptions, L as LunoraAi } from "./packem_shared/types.d-
|
|
2
|
-
export type { A as AiBindingLike, b as AiImage, c as AiImageGenerateInput, d as AiImageGenerateResult, e as AiToMarkdownInput, f as AiToMarkdownOptions, g as AiToMarkdownResult, h as AiWebSearchItem, i as AiWebSearchProvider } from "./packem_shared/types.d-
|
|
1
|
+
import { a as LunoraAiOptions, L as LunoraAi } from "./packem_shared/types.d-KCPinSfY.mjs";
|
|
2
|
+
export type { A as AiBindingLike, b as AiImage, c as AiImageGenerateInput, d as AiImageGenerateResult, e as AiToMarkdownInput, f as AiToMarkdownOptions, g as AiToMarkdownResult, h as AiWebSearchItem, i as AiWebSearchProvider } from "./packem_shared/types.d-KCPinSfY.mjs";
|
|
3
3
|
import 'ai';
|
|
4
4
|
import 'workers-ai-provider';
|
|
5
5
|
/**
|
package/dist/create.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { a as LunoraAiOptions, L as LunoraAi } from "./packem_shared/types.d-
|
|
2
|
-
export type { A as AiBindingLike, b as AiImage, c as AiImageGenerateInput, d as AiImageGenerateResult, e as AiToMarkdownInput, f as AiToMarkdownOptions, g as AiToMarkdownResult, h as AiWebSearchItem, i as AiWebSearchProvider } from "./packem_shared/types.d-
|
|
1
|
+
import { a as LunoraAiOptions, L as LunoraAi } from "./packem_shared/types.d-KCPinSfY.js";
|
|
2
|
+
export type { A as AiBindingLike, b as AiImage, c as AiImageGenerateInput, d as AiImageGenerateResult, e as AiToMarkdownInput, f as AiToMarkdownOptions, g as AiToMarkdownResult, h as AiWebSearchItem, i as AiWebSearchProvider } from "./packem_shared/types.d-KCPinSfY.js";
|
|
3
3
|
import 'ai';
|
|
4
4
|
import 'workers-ai-provider';
|
|
5
5
|
/**
|
package/dist/create.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as o}from"./packem_shared/createAi-
|
|
1
|
+
import{default as o}from"./packem_shared/createAi-DHYK5EHD.mjs";import{estimateImageCost as m,estimateModelCost as r}from"./packem_shared/DEFAULT_MODEL_PRICES-C5oaHRiN.mjs";export{o as createAi,m as estimateImageCost,r as estimateModelCost};
|
package/dist/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { D as DEFAULT_MODEL_PRICES, type M as ModelPrice, type a as ModelUsage, createAi, estimateImageCost, estimateModelCost, l as lookupModelPrice } from "./create.mjs";
|
|
2
|
-
export { j as AI_DEFAULT_EMBEDDING_MODEL_ENV, k as AI_DEFAULT_MODEL_ENV, l as AI_GATEWAY_ACCOUNT_ID_ENV, m as AI_GATEWAY_ID_ENV, n as AI_GATEWAY_METADATA_MAX_KEYS, o as AI_GATEWAY_TAGS_ENV, p as AI_GATEWAY_TOKEN_ENV, q as AI_PROXY_TOKEN_ENV, r as AI_PROXY_URL_ENV, type A as AiBindingLike, type s as AiGatewayMetadata, type t as AiGatewayOptions, type b as AiImage, type c as AiImageGenerateInput, type d as AiImageGenerateResult, type u as AiMarkdownConversionResult, type v as AiMarkdownDocument, type w as AiMetrics, type x as AiModelOptions, type y as AiRunOptions, type z as AiSpan, type B as AiTelemetry, type e as AiToMarkdownInput, type f as AiToMarkdownOptions, type g as AiToMarkdownResult, type C as AiTracer, type h as AiWebSearchItem, type D as AiWebSearchOptions, type i as AiWebSearchProvider, type F as AiWebSearchResult, type E as EmbeddingModelInput, type L as LunoraAi, type a as LunoraAiOptions, type M as ModelInput, type R as ResolvedAiGateway, type W as WorkersAiProviderLike, G as buildAiGatewayMetadataFields, H as readAiGatewayEnvTags, I as resolveAiGateway } from "./packem_shared/types.d-
|
|
2
|
+
export { j as AI_DEFAULT_EMBEDDING_MODEL_ENV, k as AI_DEFAULT_MODEL_ENV, l as AI_GATEWAY_ACCOUNT_ID_ENV, m as AI_GATEWAY_ID_ENV, n as AI_GATEWAY_METADATA_MAX_KEYS, o as AI_GATEWAY_TAGS_ENV, p as AI_GATEWAY_TOKEN_ENV, q as AI_PROXY_TOKEN_ENV, r as AI_PROXY_URL_ENV, type A as AiBindingLike, type s as AiGatewayMetadata, type t as AiGatewayOptions, type b as AiImage, type c as AiImageGenerateInput, type d as AiImageGenerateResult, type u as AiMarkdownConversionResult, type v as AiMarkdownDocument, type w as AiMetrics, type x as AiModelOptions, type y as AiRunOptions, type z as AiSpan, type B as AiTelemetry, type e as AiToMarkdownInput, type f as AiToMarkdownOptions, type g as AiToMarkdownResult, type C as AiTracer, type h as AiWebSearchItem, type D as AiWebSearchOptions, type i as AiWebSearchProvider, type F as AiWebSearchResult, type E as EmbeddingModelInput, type L as LunoraAi, type a as LunoraAiOptions, type M as ModelInput, type R as ResolvedAiGateway, type W as WorkersAiProviderLike, G as buildAiGatewayMetadataFields, H as readAiGatewayEnvTags, I as resolveAiGateway } from "./packem_shared/types.d-KCPinSfY.mjs";
|
|
3
3
|
export { type EmbeddingModel, type LanguageModel, embed, embedMany, generateObject, generateText, hasToolCall, jsonSchema, streamObject, streamText, tool } from 'ai';
|
|
4
4
|
export { createWorkersAI } from 'workers-ai-provider';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
export { D as DEFAULT_MODEL_PRICES, type M as ModelPrice, type a as ModelUsage, createAi, estimateImageCost, estimateModelCost, l as lookupModelPrice } from "./create.js";
|
|
2
|
-
export { j as AI_DEFAULT_EMBEDDING_MODEL_ENV, k as AI_DEFAULT_MODEL_ENV, l as AI_GATEWAY_ACCOUNT_ID_ENV, m as AI_GATEWAY_ID_ENV, n as AI_GATEWAY_METADATA_MAX_KEYS, o as AI_GATEWAY_TAGS_ENV, p as AI_GATEWAY_TOKEN_ENV, q as AI_PROXY_TOKEN_ENV, r as AI_PROXY_URL_ENV, type A as AiBindingLike, type s as AiGatewayMetadata, type t as AiGatewayOptions, type b as AiImage, type c as AiImageGenerateInput, type d as AiImageGenerateResult, type u as AiMarkdownConversionResult, type v as AiMarkdownDocument, type w as AiMetrics, type x as AiModelOptions, type y as AiRunOptions, type z as AiSpan, type B as AiTelemetry, type e as AiToMarkdownInput, type f as AiToMarkdownOptions, type g as AiToMarkdownResult, type C as AiTracer, type h as AiWebSearchItem, type D as AiWebSearchOptions, type i as AiWebSearchProvider, type F as AiWebSearchResult, type E as EmbeddingModelInput, type L as LunoraAi, type a as LunoraAiOptions, type M as ModelInput, type R as ResolvedAiGateway, type W as WorkersAiProviderLike, G as buildAiGatewayMetadataFields, H as readAiGatewayEnvTags, I as resolveAiGateway } from "./packem_shared/types.d-
|
|
2
|
+
export { j as AI_DEFAULT_EMBEDDING_MODEL_ENV, k as AI_DEFAULT_MODEL_ENV, l as AI_GATEWAY_ACCOUNT_ID_ENV, m as AI_GATEWAY_ID_ENV, n as AI_GATEWAY_METADATA_MAX_KEYS, o as AI_GATEWAY_TAGS_ENV, p as AI_GATEWAY_TOKEN_ENV, q as AI_PROXY_TOKEN_ENV, r as AI_PROXY_URL_ENV, type A as AiBindingLike, type s as AiGatewayMetadata, type t as AiGatewayOptions, type b as AiImage, type c as AiImageGenerateInput, type d as AiImageGenerateResult, type u as AiMarkdownConversionResult, type v as AiMarkdownDocument, type w as AiMetrics, type x as AiModelOptions, type y as AiRunOptions, type z as AiSpan, type B as AiTelemetry, type e as AiToMarkdownInput, type f as AiToMarkdownOptions, type g as AiToMarkdownResult, type C as AiTracer, type h as AiWebSearchItem, type D as AiWebSearchOptions, type i as AiWebSearchProvider, type F as AiWebSearchResult, type E as EmbeddingModelInput, type L as LunoraAi, type a as LunoraAiOptions, type M as ModelInput, type R as ResolvedAiGateway, type W as WorkersAiProviderLike, G as buildAiGatewayMetadataFields, H as readAiGatewayEnvTags, I as resolveAiGateway } from "./packem_shared/types.d-KCPinSfY.js";
|
|
3
3
|
export { type EmbeddingModel, type LanguageModel, embed, embedMany, generateObject, generateText, hasToolCall, jsonSchema, streamObject, streamText, tool } from 'ai';
|
|
4
4
|
export { createWorkersAI } from 'workers-ai-provider';
|
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as _}from"./packem_shared/createAi-
|
|
1
|
+
import{default as _}from"./packem_shared/createAi-DHYK5EHD.mjs";import{AI_DEFAULT_EMBEDDING_MODEL_ENV as E,AI_DEFAULT_MODEL_ENV as a,AI_GATEWAY_ACCOUNT_ID_ENV as o,AI_GATEWAY_ID_ENV as r,AI_GATEWAY_METADATA_MAX_KEYS as T,AI_GATEWAY_TAGS_ENV as I,AI_GATEWAY_TOKEN_ENV as m,AI_PROXY_TOKEN_ENV as s,AI_PROXY_URL_ENV as N,buildAiGatewayMetadataFields as l,readAiGatewayEnvTags as D,resolveAiGateway as G}from"./packem_shared/AI_DEFAULT_EMBEDDING_MODEL_ENV-IwcHZiKj.mjs";import{DEFAULT_MODEL_PRICES as O,estimateImageCost as d,estimateModelCost as i,lookupModelPrice as V}from"./packem_shared/DEFAULT_MODEL_PRICES-C5oaHRiN.mjs";import{embed as x,embedMany as L,generateObject as c,generateText as f,hasToolCall as p,jsonSchema as C,streamObject as W,streamText as b,tool as n}from"ai";import{createWorkersAI as g}from"workers-ai-provider";export{E as AI_DEFAULT_EMBEDDING_MODEL_ENV,a as AI_DEFAULT_MODEL_ENV,o as AI_GATEWAY_ACCOUNT_ID_ENV,r as AI_GATEWAY_ID_ENV,T as AI_GATEWAY_METADATA_MAX_KEYS,I as AI_GATEWAY_TAGS_ENV,m as AI_GATEWAY_TOKEN_ENV,s as AI_PROXY_TOKEN_ENV,N as AI_PROXY_URL_ENV,O as DEFAULT_MODEL_PRICES,l as buildAiGatewayMetadataFields,_ as createAi,g as createWorkersAI,x as embed,L as embedMany,d as estimateImageCost,i as estimateModelCost,c as generateObject,f as generateText,p as hasToolCall,C as jsonSchema,V as lookupModelPrice,D as readAiGatewayEnvTags,G as resolveAiGateway,W as streamObject,b as streamText,n as tool};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import"./DEFAULT_MODEL_PRICES-C5oaHRiN.mjs";import{LunoraError as f}from"@lunora/errors";import{buildAiGatewayMetadataFields as te,readEnv as N,AI_DEFAULT_MODEL_ENV as H,AI_DEFAULT_EMBEDDING_MODEL_ENV as z,AI_PROXY_URL_ENV as U,AI_PROXY_TOKEN_ENV as re,readAiGatewayEnvTags as Ie,AI_GATEWAY_ID_ENV as ne,warnIgnoredBindingToken as _e,resolveAiGateway as Te}from"./AI_DEFAULT_EMBEDDING_MODEL_ENV-IwcHZiKj.mjs";import{m as Me,r as K,a as Y}from"./usage-DQdygGEV.mjs";const L=e=>{let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)},Ne=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},Pe=/^\d{1,3}$/u,Le=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,Re=/^::ffff:0:([\da-f]{1,4}):([\da-f]{1,4})$/u,Ue=/^::[\da-f]{1,4}$/u,De=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,Oe=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,ke=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,Se=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,We=/^[\da-f]{1,4}$/u,xe=[[[8193],23],[[16383],20],[[24320],16],[[256,0,0,1],64]],$e=[[[8193,1,0,0,0,0,0,1],128],[[8193,1,0,0,0,0,0,2],128],[[8193,1,0,0,0,0,0,3],128],[[8193,3],32],[[8193,4,274],48],[[8193,5],32],[[8193,32],28],[[8193,48],28]],Be=e=>{const t=e.split("::");if(t.length>2)return;const r=c=>c===void 0||c===""?[]:c.split(":").map(u=>We.test(u)?Number.parseInt(u,16):Number.NaN),n=r(t[0]),a=r(t[1]),d=8-n.length-a.length;if(d<0||t.length===1&&d!==0)return;const i=[...n,...Array.from({length:d},()=>0),...a];return i.some(Number.isNaN)?void 0:i},X=(e,[t,r])=>{for(let n=0;n*16<r;n+=1){const d=65535<<16-Math.min(16,r-n*16)&65535;if(((e[n]??0)&d)!==((t[n]??0)&d))return!1}return!0},Ce=/^\[|\]$/gu,Ge=/\.$/u,B=e=>{const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>Pe.test(n)?Number(n):-1);if(!r.some(n=>n<0||n>255))return[r[0],r[1],r[2],r[3]]},D=([e,t,r])=>e===0||e===10||e===127||e===100&&t>=64&&t<=127||e===169&&t===254||e===172&&t>=16&&t<=31||e===192&&t===0&&(r===0||r===2)||e===192&&t===88&&r===99||e===192&&t===168||e===198&&(t===18||t===19)||e===198&&t===51&&r===100||e===203&&t===0&&r===113||e>=224,S=(e,t)=>{const r=Number.parseInt(e??"",16),n=Number.parseInt(t??"",16);return!Number.isFinite(r)||!Number.isFinite(n)?!0:D([Math.floor(r/256),r%256,Math.floor(n/256),n%256])},Ve=e=>{const t=e.toLowerCase(),r=Le.exec(t);if(r)return S(r[1],r[2]);const n=Re.exec(t);if(n)return S(n[1],n[2]);const a=De.exec(t);if(a){const u=B(a[1]??"");return u===void 0||D(u)}const d=Oe.exec(t);if(d){const u=B(d[1]??"");return u===void 0||D(u)}const i=ke.exec(t);if(i)return S(i[1],i[2]);if(Ue.test(t)||Se.test(t)||t.startsWith("64:ff9b:1:")||t.startsWith("2002:"))return!0;const c=Be(t);return c!==void 0&&xe.some(u=>X(c,u))&&!$e.some(u=>X(c,u))?!0:t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb")||t.startsWith("fec")||t.startsWith("fed")||t.startsWith("fee")||t.startsWith("fef")||t.startsWith("ff")||t.startsWith("2001:db8:")||t.startsWith("100::")},Fe=e=>e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa"),He=e=>e.replaceAll(Ce,"").replace(Ge,"").toLowerCase(),ze=e=>{const t=He(e);if(t.includes(":"))return Ve(t);const r=B(t);return r===void 0?Fe(t):D(r)},Ke={setAttribute:()=>{},setAttributes:()=>{}},oe=async(e,t)=>t(oe,Ke),Ye=(e,{metrics:t,trace:r=oe})=>{const n={"gen_ai.operation.name":"chat","gen_ai.request.model":e};return{wrapGenerate:async({doGenerate:a})=>r("ai.generate",async(d,i)=>{const c=await a();return K(e,c,i,t),c},n),wrapStream:async({doStream:a})=>{const d=(u,v)=>{const y=u.stream.getReader();let A={};return{...u,stream:new ReadableStream({cancel:async E=>{v({outcome:A}),await y.cancel(E)},pull:async E=>{let p;try{p=await y.read()}catch(P){v({error:P,failed:!0,outcome:A}),E.error(P);return}if(p.done){v({outcome:A}),E.close();return}p.value.type==="finish"&&(A={providerMetadata:p.value.providerMetadata,usage:p.value.usage}),E.enqueue(p.value)}})}},i=Promise.withResolvers(),c=Promise.withResolvers();return r("ai.stream",async(u,v)=>{i.resolve(d(await a(),c.resolve));const y=await c.promise;if(K(e,y.outcome,v,t),y.failed===!0)throw y.error},n).catch(i.reject),i.promise}}},j=(e,t,r)=>{if(t===void 0||typeof e=="string")return e;const n=Ye(r??Me(e)??"unknown",t);let a;const d=async()=>(a??=import("ai").then(({wrapLanguageModel:c})=>c({middleware:n,model:e}),c=>{throw a=void 0,c}),a),i=e;return{doGenerate:async c=>d().then(u=>u.doGenerate(c)),doStream:async c=>d().then(u=>u.doStream(c)),modelId:i.modelId,provider:i.provider,specificationVersion:"v4",get supportedUrls(){return d().then(c=>c.supportedUrls)}}};let W;const ae=()=>(W??=Promise.all([import("@ai-sdk/openai"),import("workers-ai-provider/openai"),import("workers-ai-provider/anthropic")]).then(([e,{openai:t},{anthropic:r}])=>({createOpenAI:e.createOpenAI,plugins:[t,r]}),e=>{throw W=void 0,e}),W),se=(e,t,r)=>({doGenerate:async n=>r().then(a=>a.doGenerate(n)),doStream:async n=>r().then(a=>a.doStream(n)),modelId:e,provider:t,specificationVersion:"v4",get supportedUrls(){return r().then(n=>n.supportedUrls)}}),Xe={maxEmbeddingsPerCall:3e3,supportsParallelCalls:!0},ie=(e,t,r,n)=>({doEmbed:async a=>r().then(d=>d.doEmbed(a)),get maxEmbeddingsPerCall(){return n?.maxEmbeddingsPerCall??r().then(a=>a.maxEmbeddingsPerCall)},modelId:e,provider:t,specificationVersion:"v4",get supportsParallelCalls(){return n?.supportsParallelCalls??r().then(a=>a.supportsParallelCalls)}});let x;const Q=()=>(x??=import("workers-ai-provider").catch(e=>{throw x=void 0,e}),x),R=e=>!e.startsWith("@")&&e.includes("/"),je=e=>{const t=(r,n)=>se(r,"workersai.chat",async()=>e(r).then(a=>a(r,n)));return t.textEmbeddingModel=r=>ie(r,"workersai.embedding",async()=>e(r).then(n=>n.textEmbeddingModel?.(r)),R(r)?void 0:Xe),t},_=e=>{throw new f("INTERNAL",`@lunora/ai: ${e} needs the \`AI\` binding (env.AI). In dev, Lunora leaves it out when there is no Cloudflare login: run \`wrangler login\` or set CLOUDFLARE_API_TOKEN. Elsewhere, add an \`ai\` binding to wrangler.jsonc. Or set ${U} to an OpenAI-compatible proxy for "<provider>/<model>" slugs.`)},de=()=>_("this model id");de.textEmbeddingModel=()=>_("this embedding model id");const Qe=3040,qe=/^(?:[A-Z]\w*:\s*)?3040\s*:/iu,Ze=e=>e?.code===Qe||e instanceof Error&&qe.test(e.message),Je="default",et=new Map([[401,"UNAUTHORIZED"],[403,"FORBIDDEN"],[404,"NOT_FOUND"],[408,"SERVICE_UNAVAILABLE"],[429,"RATE_LIMITED"]]),ce=e=>et.get(e)??(e>=400&&e<500?"BAD_REQUEST":"SERVICE_UNAVAILABLE"),le=300,tt=new Set(["127.0.0.1","[::1]","localhost"]),rt=(e,t)=>{const r=URL.canParse(e)?new URL(e):void 0;if(r===void 0)return`${U} is not a valid URL`;if(t!==void 0&&r.protocol!=="https:"&&!tt.has(r.hostname))return`${U} (${r.origin}) is not HTTPS, so ${re} would travel in cleartext — use an https:// URL`},nt=e=>{const t=N(e,U);if(t===void 0)return;const r=N(e,re),n=rt(t,r);if(n!==void 0){const i=()=>{throw new f("INTERNAL",`@lunora/ai: ${n}`)};return{chat:i,embedding:i,image:i}}let a;const d=()=>(a??=ae().then(({createOpenAI:i})=>i({apiKey:r??"",baseURL:t,name:"lunora-proxy"}),i=>{throw a=void 0,i}),a);return{chat:i=>se(i,"lunora-proxy",async()=>d().then(c=>c.chat(i))),embedding:i=>ie(i,"lunora-proxy",async()=>d().then(c=>c.embedding(i))),image:async i=>d().then(c=>c.image(i))}},ot=(e,t)=>{const r=e===void 0?void 0:Ie(e);return r===void 0?t:{...t,tags:{...r,...t?.tags}}},at=(e,t,r)=>{const n=te(r);if(e!==void 0)return n!==void 0&&e.metadata===void 0?{...e,metadata:n}:e;if(t===void 0)return;const a=N(t,ne);if(a!==void 0)return _e(t),n===void 0?{id:a}:{id:a,metadata:n}};let $;const st=()=>($??=Promise.all([import("@ai-sdk/openai"),import("@ai-sdk/google")]).then(([e,t])=>({createGoogle:t.createGoogle,createOpenAI:e.createOpenAI}),e=>{throw $=void 0,e}),$),q=8,it=/^[1-9]\d*x[1-9]\d*$/u,dt=20*1024*1024,Z="unused",J=(e,t)=>{const r=new Headers(t?.headers);return r.delete("authorization"),r.delete("x-goog-api-key"),fetch(e,{...t,headers:r})},ct=e=>{const t=e.pathname.split("/").findLast(r=>r.length>0);return t===void 0||t===""?"document":t},C=(e,t)=>{if(e>t)throw new f("PAYLOAD_TOO_LARGE",`@lunora/ai: toMarkdown document is ${String(e)} bytes, over the ${String(t)}-byte limit — raise \`maxBytes\` to convert it`)},lt=async(e,t)=>{if(e.body===null)return new Uint8Array;let r=0;const n=e.body.pipeThrough(new TransformStream({transform(a,d){if(r+=a.byteLength,r>t){d.error(new f("PAYLOAD_TOO_LARGE",`@lunora/ai: toMarkdown document is over the ${String(t)}-byte limit — raise \`maxBytes\` to convert it`));return}d.enqueue(a)}}));return new Uint8Array(await new Response(n).arrayBuffer())},ut=e=>{if(e.protocol!=="https:"&&e.protocol!=="http:"||ze(e.hostname))throw new f("BAD_REQUEST",`@lunora/ai: toMarkdown will not fetch ${e.href} — only public http(s) hosts; pass its bytes or a Blob instead`)},ft=(e,t,r)=>{if(!(e instanceof ArrayBuffer)&&!(e instanceof Uint8Array))throw new f("BAD_REQUEST","@lunora/ai: toMarkdown input must be a URL, Blob, ArrayBuffer or Uint8Array");const n=e instanceof Uint8Array?e:new Uint8Array(e);C(n.byteLength,r);const a=new Uint8Array(n),d=t?.mimeType;return{blob:new Blob([a],d===void 0?void 0:{type:d}),name:t?.name??"document"}},mt=async(e,t,r)=>{if(e instanceof URL){ut(e);const n=await fetch(e,{redirect:"manual"});if(!n.ok){const c=n.status>=300&&n.status<400?"; redirects are not followed, so pass the final URL":"";throw new f("BAD_REQUEST",`@lunora/ai: toMarkdown could not fetch ${e.href} (HTTP ${String(n.status)})${c}`)}const a=Number(n.headers.get("content-length"));n.headers.has("content-length")&&Number.isFinite(a)&&C(a,r);const d=await lt(n,r),i=n.headers.get("content-type");return{blob:new Blob([d],i===null||i===""?void 0:{type:i}),name:t?.name??ct(e)}}return e instanceof Blob?(C(e.size,r),{blob:e,name:t?.name??"document"}):ft(e,t,r)},ee=e=>{if(e===void 0||e==="")return;const t=Number(e);return Number.isInteger(t)?t:void 0},ht=e=>{if(e===void 0)return{};const[t,r]=e.split("x");return{height:ee(r),width:ee(t)}},T=e=>{const t=(r,n=0)=>r.every((a,d)=>e[n+d]===a);return t([137,80,78,71])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56])?"image/gif":t([82,73,70,70])&&t([87,69,66,80],8)?"image/webp":void 0},gt=e=>{try{return Ne(e.slice(0,16))}catch{return new Uint8Array}},M=(e,t)=>t===void 0?{base64:e}:{base64:e,mimeType:t},ue=async e=>{if(typeof e=="string")return M(e,T(gt(e)));if(e instanceof Uint8Array)return M(L(e),T(e));if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return M(L(t),T(t))}if(e instanceof Response){if(!e.ok){const n=(await e.text().catch(()=>"")).slice(0,le);throw new f(ce(e.status),`@lunora/ai: image generation failed with HTTP ${String(e.status)}${n===""?"":`: ${n}`}`)}const t=new Uint8Array(await e.arrayBuffer());return M(L(t),T(t))}if(e instanceof ReadableStream){const t=new Uint8Array(await new Response(e).arrayBuffer());return M(L(t),T(t))}if(typeof e=="object"&&e!==null&&"image"in e)return ue(e.image)},bt=e=>{const{binding:t,defaultEmbeddingModel:r,defaultModel:n,env:a,gateway:d,metadata:i,provider:c,telemetry:u}=e,v=nt(a),y=ot(a,i),A=at(d,a,y),E=d?.metadata===void 0?te(y):void 0,p=n??N(a,H),P=r??N(a,z);let O;const fe=()=>(O??=Q().then(({createWorkersAI:o})=>o({binding:t,gateway:A})).catch(o=>{throw O=void 0,o}),O);let k;const me=()=>(k??=Promise.all([Q(),ae()]).then(([{createWorkersAI:o},{plugins:l}])=>o({binding:t,gateway:A,providers:l})).catch(o=>{throw k=void 0,o}),k),I=c??(t?je(async o=>R(o)?me():fe()):de),he=(o,l)=>R(o)?v!==void 0?v.chat(o):E===void 0?I(o):I(o,{metadata:E}):l?.rejectIfBusy===void 0?I(o):I(o,{rejectIfBusy:l.rejectIfBusy}),ge=(o,l)=>{const s=o??p;if(s===void 0||s==="")throw new f("INTERNAL",`@lunora/ai: no model supplied and no default configured — pass a model id, or set ${H} in the Worker env (wrangler \`vars\` / \`.dev.vars\`)`);return typeof s=="string"?j(he(s,l),u,s):j(s,u)},we=o=>{if(v!==void 0&&R(o))return v.embedding(o);const l=I.textEmbeddingModel;if(typeof l!="function")throw new f("INTERNAL","@lunora/ai: the Workers AI provider does not expose `textEmbeddingModel`; pass an AI SDK EmbeddingModel (e.g. from @ai-sdk/openai) to embed()");return l.call(I,o)},ve=o=>{if(typeof o=="object")return o;const l=o??P;if(!l)throw new f("INTERNAL",`@lunora/ai: no embedding model supplied and no default configured — pass an embedding model id or an AI SDK EmbeddingModel, or set ${z} in the Worker env (wrangler \`vars\` / \`.dev.vars\`)`);return we(l)},G=async(o,l,s)=>{if(!t)return _("ai.run");const w=A!==void 0&&s?.gateway===void 0?{...s,gateway:A}:s;try{return await t.run(o,l,w)}catch(h){throw Ze(h)?new f("RATE_LIMITED",`@lunora/ai: Workers AI has no free capacity for ${o} (error 3040) — retry later`,{cause:h}):h}},Ae=async(o,l)=>{if(!t)return _("ai.websearch");if(typeof t.websearch!="function")throw new f("NOT_IMPLEMENTED","@lunora/ai: this Workers runtime's `AI` binding has no websearch() — update wrangler / @cloudflare/vite-plugin to a release that ships the Web Search API");const{gatewayId:s,...w}=l??{},h=await t.websearch({...w,gatewayId:s??A?.id??Je,query:o});if(!h.ok){const b=(await h.text().catch(()=>"")).slice(0,le);throw new f(ce(h.status),`@lunora/ai: web search failed with HTTP ${String(h.status)}${b===""?"":`: ${b}`}`)}const g=await h.json().catch(()=>{});if(!Array.isArray(g?.items))throw new f("INTERNAL","@lunora/ai: web search returned a body that is not JSON with an `items` array");return g},ye=async(o,l)=>{if(!t)return _("ai.toMarkdown");if(typeof t.toMarkdown!="function")throw new f("NOT_IMPLEMENTED","@lunora/ai: this Workers runtime's `AI` binding has no toMarkdown() — update wrangler / @cloudflare/vite-plugin to a release that ships the Markdown Conversion API");const s=l?.maxBytes??dt;if(!Number.isFinite(s)||s<=0)throw new f("BAD_REQUEST","@lunora/ai: toMarkdown maxBytes must be a positive number of bytes");const{blob:w,name:h}=await mt(o,l,s),g=await t.toMarkdown({blob:w,name:h},l?.conversionOptions),m=Array.isArray(g)?g[0]:g;if(m===void 0)throw new f("INTERNAL","@lunora/ai: toMarkdown returned no conversion result");if(m.format==="error")throw new f("BAD_REQUEST",`@lunora/ai: toMarkdown could not convert "${h}": ${m.error??"unknown error"}`);if(typeof m.data!="string")throw new f("INTERNAL",`@lunora/ai: toMarkdown returned a "${m.format}" result with no data`);return{markdown:m.data,...m.mimetype===void 0?{}:{mimeType:m.mimetype},...m.pages===void 0?{}:{pages:m.pages},...m.tokens===void 0?{}:{tokens:m.tokens}}},Ee=async o=>{if(!t)return _("ai.images.generate");const{height:l,width:s}=ht(o.size),w=g=>({prompt:o.prompt,...l===void 0?{}:{height:l},...s===void 0?{}:{width:s},...o.seed===void 0?{}:{seed:o.seed+g}}),h=async(g,m)=>{if(g>=(o.count??1))return m;const b=await ue(await G(o.model,w(g)));if(b===void 0||b.base64==="")throw new f("INTERNAL",`@lunora/ai: ${o.model} returned no image data`);return Y(o.model,1,u?.metrics),h(g+1,[...m,b])};return{images:await h(0,[]),model:o.model}},pe=async(o,l,s)=>{const{createGoogle:w,createOpenAI:h}=await st(),g=A===void 0?void 0:Te({...a,[ne]:A.id});let m;o==="openai"?v!==void 0?m=await v.image(s.model):g===void 0?m=h().image(l):m=h({apiKey:Z,baseURL:`${g.baseURL}/openai`,fetch:J,headers:g.headers}).image(l):g===void 0?m=w().image(l):m=w({apiKey:Z,baseURL:`${g.baseURL}/google-ai-studio/v1beta`,fetch:J,headers:g.headers}).image(l);const{generateImage:b}=await import("ai"),V=(await b({model:m,prompt:s.prompt,...s.count===void 0?{}:{n:s.count},...s.seed===void 0?{}:{seed:s.seed},...s.size===void 0?{}:{size:s.size}})).images.map(F=>({base64:F.base64,mimeType:F.mediaType}));return Y(s.model,V.length,u?.metrics),{images:V,model:s.model}},be=async(o,l)=>{if(o.startsWith("@"))return Ee(l);const s=o.indexOf("/"),w=s===-1?"":o.slice(0,s),h=s===-1?"":o.slice(s+1);if((w==="openai"||w==="google")&&h.length>0)return pe(w,h,l);throw new f("AI_UNKNOWN_IMAGE_MODEL",`@lunora/ai: no image provider for "${o}" — pass a Workers AI image id (@cf/…), or an "openai/<model>" or "google/<model>" slug`)};return{embeddingModel:ve,images:{generate:async o=>{const l=o.model,s=o.count??1;if(!Number.isInteger(s)||s<1||s>q)throw new f("BAD_REQUEST",`@lunora/ai: count must be an integer from 1 to ${String(q)}`,{status:400});if(o.size!==void 0&&!it.test(o.size))throw new f("BAD_REQUEST",`@lunora/ai: size must be "<width>x<height>" with positive integers, e.g. "1024x1024" (got "${o.size}")`);return be(l,o)}},model:ge,run:G,toMarkdown:ye,websearch:Ae,workersai:I}};export{bt as default};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{tool as Re,jsonSchema as De}from"@ai-sdk/provider-utils";import{LunoraError as w,isLunoraError as Ce}from"@lunora/errors";import{stableStringify as Be}from"@lunora/wire";import{r as de,m as L}from"./usage-
|
|
1
|
+
import{tool as Re,jsonSchema as De}from"@ai-sdk/provider-utils";import{LunoraError as w,isLunoraError as Ce}from"@lunora/errors";import{stableStringify as Be}from"@lunora/wire";import{r as de,m as L}from"./usage-DQdygGEV.mjs";import $e from"./fixedWindowChunks-C461ahRE.mjs";import{c as Oe,I as Ke}from"./concurrent-C6nqBv41.mjs";import{contentHash as Ue}from"./contentHash-BIn6ECP8.mjs";import{hybridRank as Qe}from"./hybridRank-B4skyCLx.mjs";import{VECTORIZE_CAPABILITIES as le,vectorizeStore as Ve}from"./VECTORIZE_CAPABILITIES-l9ceRO5j.mjs";const Fe=1e3,Le=200,ze=5,ue=1e3,Pe=4,me=le.maxMetadataBytes===!1?Number.POSITIVE_INFINITY:le.maxMetadataBytes,je=2*1024,we="__ragChunk",be="__ragSource",K="__ragText",q="__ragHash",W="__ragChunks",V="__ragImportance",ve="__ragModel",He=new Set([we,W,q,V,ve,be,K]),Ye=async(e,c,u,m)=>{if(c.length===0)return;const h=c.slice(1);if(!e.upsertMany){await Oe(h,Ke,async(E,A)=>{await e.upsert(E,m),u(A+1)}),await e.upsert(c[0],m),u(0);return}for(let E=0;E<h.length;E+=ue){const A=Math.min(E+ue,h.length);await e.upsertMany(h.slice(E,A),m);for(let U=E;U<A;U+=1)u(U+1)}await e.upsertMany([c[0]],m),u(0)},qe=(e,c,u,m)=>{if(m===!1)return;const h=new TextEncoder().encode(JSON.stringify(e)).length;if(h<=m)return;const A=(typeof e[K]=="string"?new TextEncoder().encode(e[K]).length:0)*2>h?"lower `chunkSize` (it counts characters, not bytes — multibyte text costs up to 3 bytes each), or supply `textStore` to move chunk text out of metadata entirely":"attach less per-source `metadata`";throw new w("BAD_REQUEST",`@lunora/ai/rag: chunk ${String(c)} of "${u}" carries ${String(h)} bytes of metadata, over the store's ${String(m)}-byte per-vector ceiling — ${A}`)},We=(e,c,u)=>{if(u===!1)return;const m=new TextEncoder().encode(e).length;if(!(m<=u))throw new w("BAD_REQUEST",`@lunora/ai/rag: chunk id "${e}" for source "${c}" is ${String(m)} bytes, over the store's ${String(u)}-byte per-vector id ceiling — shorten the source id (hash long keys before indexing them) or shorten the \`namespace\`, which is prefixed onto every chunk id`)},Ze=/^[\w.-]{1,40}$/,ye=e=>e===void 0?"":`${encodeURIComponent(e)}#`,O=(e,c,u)=>`${ye(e)}${c}#${String(u)}`,he=(e,c)=>{const u=ye(c),m=u!==""&&e.startsWith(u)?e.slice(u.length):e,h=m.lastIndexOf("#"),E=h===-1?Number.NaN:Number(m.slice(h+1));return h===-1||!Number.isInteger(E)||E<0?{chunkIndex:0,sourceId:m}:{chunkIndex:E,sourceId:m.slice(0,h)}},Xe=async e=>Ue(new TextEncoder().encode(e)),Je=e=>{try{return Be([e.text,e.metadata,e.importance])}catch{return}},Ge=(e,c)=>{const u=[],m=[];for(const h of e)h.score>=c?u.push(h):m.push(h.id);return{kept:u,rejectedIds:m}},et=e=>e!==void 0&&Object.keys(e).length>0,H=e=>{if(!e)return;const c=Object.entries(e).filter(([u])=>!He.has(u));return c.length>0?Object.fromEntries(c):void 0},pe=new Set,tt=e=>{pe.has(e)||(pe.add(e),console.warn(`[@lunora/ai/rag] index "${e}" is used without a namespace — in a multi-tenant/sharded
|
|
2
2
|
app this shares one tenant's chunks (text included) with every other tenant, since
|
|
3
3
|
Vectorize indexes are account-global. Pass \`namespace\` (the shard/tenant key) on both
|
|
4
4
|
index() and retrieve(). Single-tenant apps suppress this via { allowSharedNamespace: true }.`))},nt=e=>e.map(c=>`[source:${c.sourceId}#${String(c.chunkIndex)}]
|
|
@@ -295,7 +295,11 @@ interface AiImageGenerateInput {
|
|
|
295
295
|
*/
|
|
296
296
|
model: string;
|
|
297
297
|
prompt: string;
|
|
298
|
-
/**
|
|
298
|
+
/**
|
|
299
|
+
* Seed for reproducible generation, for providers that support it. A Workers AI
|
|
300
|
+
* `count` batch uses `seed + i` for image `i`, so the images differ; provider
|
|
301
|
+
* models receive the seed as given.
|
|
302
|
+
*/
|
|
299
303
|
seed?: number;
|
|
300
304
|
/** Image size as `"<width>x<height>"`, e.g. `"1024x1024"`. */
|
|
301
305
|
size?: `${number}x${number}`;
|
|
@@ -295,7 +295,11 @@ interface AiImageGenerateInput {
|
|
|
295
295
|
*/
|
|
296
296
|
model: string;
|
|
297
297
|
prompt: string;
|
|
298
|
-
/**
|
|
298
|
+
/**
|
|
299
|
+
* Seed for reproducible generation, for providers that support it. A Workers AI
|
|
300
|
+
* `count` batch uses `seed + i` for image `i`, so the images differ; provider
|
|
301
|
+
* models receive the seed as given.
|
|
302
|
+
*/
|
|
299
303
|
seed?: number;
|
|
300
304
|
/** Image size as `"<width>x<height>"`, e.g. `"1024x1024"`. */
|
|
301
305
|
size?: `${number}x${number}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{estimateModelCost as d,estimateImageCost as f}from"./DEFAULT_MODEL_PRICES-C5oaHRiN.mjs";const g=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0,p=t=>{if(!(typeof t!="object"||t===null)){for(const o of Object.values(t))if(typeof o=="object"&&o!==null){const{cost:e}=o;if(typeof e=="number"&&Number.isFinite(e))return e}}},b=t=>{const o=t.modelId;return typeof o=="string"&&o.length>0?o:void 0},l=(t,o,e,s)=>{const n=g(o.usage?.inputTokens?.total),u=g(o.usage?.outputTokens?.total),c=p(o.providerMetadata),i=c??d(t,{inputTokens:n,outputTokens:u}),a=c===void 0?"estimated":"provider",r={"gen_ai.request.model":t??"unknown"};n!==void 0&&(e?.setAttribute("gen_ai.usage.input_tokens",n),s?.count("gen_ai.usage.input_tokens",n,r)),u!==void 0&&(e?.setAttribute("gen_ai.usage.output_tokens",u),s?.count("gen_ai.usage.output_tokens",u,r)),i!==void 0&&(e?.setAttributes({"gen_ai.usage.cost":i,"lunora.usage.cost.source":a}),s?.count("gen_ai.usage.cost",i,{...r,"lunora.usage.cost.source":a}))},m=(t,o,e)=>{const s=f(t,o);s!==void 0&&e?.count("gen_ai.usage.cost",s,{"gen_ai.request.model":t,"lunora.usage.cost.source":"estimated"})};export{m as a,b as m,l as r};
|
package/dist/rag/index.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Tool } from 'ai';
|
|
2
|
-
import { E as EmbeddingModelInput, L as LunoraAi } from "../packem_shared/types.d-
|
|
2
|
+
import { E as EmbeddingModelInput, L as LunoraAi } from "../packem_shared/types.d-KCPinSfY.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Built-in fixed-window chunker: split into `size`-char windows overlapping by
|
|
5
5
|
* `overlap` chars. Deliberately simple and deterministic — the zero-config
|
package/dist/rag/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Tool } from 'ai';
|
|
2
|
-
import { E as EmbeddingModelInput, L as LunoraAi } from "../packem_shared/types.d-
|
|
2
|
+
import { E as EmbeddingModelInput, L as LunoraAi } from "../packem_shared/types.d-KCPinSfY.js";
|
|
3
3
|
/**
|
|
4
4
|
* Built-in fixed-window chunker: split into `size`-char windows overlapping by
|
|
5
5
|
* `overlap` chars. Deliberately simple and deterministic — the zero-config
|
package/dist/rag/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{default as o}from"../packem_shared/fixedWindowChunks-C461ahRE.mjs";import{markdownChunker as a,sentenceChunker as f,tokenChunker as n}from"../packem_shared/markdownChunker-iW8V4klY.mjs";import{default as x}from"../packem_shared/defineRag-
|
|
1
|
+
import{default as o}from"../packem_shared/fixedWindowChunks-C461ahRE.mjs";import{markdownChunker as a,sentenceChunker as f,tokenChunker as n}from"../packem_shared/markdownChunker-iW8V4klY.mjs";import{default as x}from"../packem_shared/defineRag-Dq2bA1Xl.mjs";import{contentHash as p,guessMimeTypeFromExtension as i}from"../packem_shared/contentHash-BIn6ECP8.mjs";import{hybridRank as d}from"../packem_shared/hybridRank-B4skyCLx.mjs";import{default as k}from"../packem_shared/bm25LexicalStore-DMUzAL0O.mjs";import{default as h}from"../packem_shared/matchesMetadataFilter-BbIOyA5g.mjs";import{batchReranker as g,scoreReranker as C}from"../packem_shared/batchReranker-Bc38FBLH.mjs";import{defineRagSource as E}from"../packem_shared/defineRagSource-Q3f3niU8.mjs";import{sqlLexicalStore as T}from"../packem_shared/sqlLexicalStore-4C_cIwef.mjs";import{sqliteVectorStore as y}from"../packem_shared/sqliteVectorStore-f24ySqtJ.mjs";import{ragSyncTriggers as q}from"../packem_shared/ragSyncTriggers-D933fCwt.mjs";import{VECTORIZE_CAPABILITIES as A,vectorizeStore as F}from"../packem_shared/VECTORIZE_CAPABILITIES-l9ceRO5j.mjs";export{A as VECTORIZE_CAPABILITIES,g as batchReranker,k as bm25LexicalStore,p as contentHash,x as defineRag,E as defineRagSource,o as fixedWindowChunks,i as guessMimeTypeFromExtension,d as hybridRank,a as markdownChunker,h as matchesMetadataFilter,q as ragSyncTriggers,C as scoreReranker,f as sentenceChunker,T as sqlLexicalStore,y as sqliteVectorStore,n as tokenChunker,F as vectorizeStore};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import"./DEFAULT_MODEL_PRICES-C5oaHRiN.mjs";import{LunoraError as m}from"@lunora/errors";import{buildAiGatewayMetadataFields as J,readEnv as N,AI_DEFAULT_MODEL_ENV as F,AI_DEFAULT_EMBEDDING_MODEL_ENV as H,AI_PROXY_URL_ENV as D,AI_PROXY_TOKEN_ENV as ee,readAiGatewayEnvTags as pe,AI_GATEWAY_ID_ENV as te,warnIgnoredBindingToken as be,resolveAiGateway as Ie}from"./AI_DEFAULT_EMBEDDING_MODEL_ENV-IwcHZiKj.mjs";import{m as _e,r as z,a as Te}from"./usage-C5GJNFt9.mjs";const L=e=>{let t="";for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)},Me=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n+=1)r[n]=t.codePointAt(n)??0;return r},Ne=/^\d{1,3}$/u,Pe=/^::ffff:([\da-f]{1,4}):([\da-f]{1,4})$/u,Le=/^::ffff:0:([\da-f]{1,4}):([\da-f]{1,4})$/u,Re=/^::[\da-f]{1,4}$/u,De=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/u,Oe=/^::(\d{1,3}(?:\.\d{1,3}){3})$/u,Ue=/^::([\da-f]{1,4}):([\da-f]{1,4})$/u,ke=/^64:ff9b::[\da-f]{1,4}:[\da-f]{1,4}$/u,Se=/^[\da-f]{1,4}$/u,xe=[[[8193],23],[[16383],20],[[24320],16],[[256,0,0,1],64]],We=[[[8193,1,0,0,0,0,0,1],128],[[8193,1,0,0,0,0,0,2],128],[[8193,1,0,0,0,0,0,3],128],[[8193,3],32],[[8193,4,274],48],[[8193,5],32],[[8193,32],28],[[8193,48],28]],$e=e=>{const t=e.split("::");if(t.length>2)return;const r=l=>l===void 0||l===""?[]:l.split(":").map(u=>Se.test(u)?Number.parseInt(u,16):Number.NaN),n=r(t[0]),a=r(t[1]),s=8-n.length-a.length;if(s<0||t.length===1&&s!==0)return;const d=[...n,...Array.from({length:s},()=>0),...a];return d.some(Number.isNaN)?void 0:d},K=(e,[t,r])=>{for(let n=0;n*16<r;n+=1){const s=65535<<16-Math.min(16,r-n*16)&65535;if(((e[n]??0)&s)!==((t[n]??0)&s))return!1}return!0},Ce=/^\[|\]$/gu,Be=/\.$/u,B=e=>{const t=e.split(".");if(t.length!==4)return;const r=t.map(n=>Ne.test(n)?Number(n):-1);if(!r.some(n=>n<0||n>255))return[r[0],r[1],r[2],r[3]]},O=([e,t,r])=>e===0||e===10||e===127||e===100&&t>=64&&t<=127||e===169&&t===254||e===172&&t>=16&&t<=31||e===192&&t===0&&(r===0||r===2)||e===192&&t===88&&r===99||e===192&&t===168||e===198&&(t===18||t===19)||e===198&&t===51&&r===100||e===203&&t===0&&r===113||e>=224,S=(e,t)=>{const r=Number.parseInt(e??"",16),n=Number.parseInt(t??"",16);return!Number.isFinite(r)||!Number.isFinite(n)?!0:O([Math.floor(r/256),r%256,Math.floor(n/256),n%256])},Ge=e=>{const t=e.toLowerCase(),r=Pe.exec(t);if(r)return S(r[1],r[2]);const n=Le.exec(t);if(n)return S(n[1],n[2]);const a=De.exec(t);if(a){const u=B(a[1]??"");return u===void 0||O(u)}const s=Oe.exec(t);if(s){const u=B(s[1]??"");return u===void 0||O(u)}const d=Ue.exec(t);if(d)return S(d[1],d[2]);if(Re.test(t)||ke.test(t)||t.startsWith("64:ff9b:1:")||t.startsWith("2002:"))return!0;const l=$e(t);return l!==void 0&&xe.some(u=>K(l,u))&&!We.some(u=>K(l,u))?!0:t==="::"||t==="::1"||t.startsWith("fc")||t.startsWith("fd")||t.startsWith("fe8")||t.startsWith("fe9")||t.startsWith("fea")||t.startsWith("feb")||t.startsWith("fec")||t.startsWith("fed")||t.startsWith("fee")||t.startsWith("fef")||t.startsWith("ff")||t.startsWith("2001:db8:")||t.startsWith("100::")},Ve=e=>e==="localhost"||e.endsWith(".localhost")||e.endsWith(".local")||e.endsWith(".internal")||e.endsWith(".home.arpa"),Fe=e=>e.replaceAll(Ce,"").replace(Be,"").toLowerCase(),He=e=>{const t=Fe(e);if(t.includes(":"))return Ge(t);const r=B(t);return r===void 0?Ve(t):O(r)},ze={setAttribute:()=>{},setAttributes:()=>{}},re=async(e,t)=>t(re,ze),Ke=(e,{metrics:t,trace:r=re})=>{const n={"gen_ai.operation.name":"chat","gen_ai.request.model":e};return{wrapGenerate:async({doGenerate:a})=>r("ai.generate",async(s,d)=>{const l=await a();return z(e,l,d,t),l},n),wrapStream:async({doStream:a})=>{const s=(u,v)=>{const y=u.stream.getReader();let A={};return{...u,stream:new ReadableStream({cancel:async E=>{v({outcome:A}),await y.cancel(E)},pull:async E=>{let p;try{p=await y.read()}catch(P){v({error:P,failed:!0,outcome:A}),E.error(P);return}if(p.done){v({outcome:A}),E.close();return}p.value.type==="finish"&&(A={providerMetadata:p.value.providerMetadata,usage:p.value.usage}),E.enqueue(p.value)}})}},d=Promise.withResolvers(),l=Promise.withResolvers();return r("ai.stream",async(u,v)=>{d.resolve(s(await a(),l.resolve));const y=await l.promise;if(z(e,y.outcome,v,t),y.failed===!0)throw y.error},n).catch(d.reject),d.promise}}},Y=(e,t,r)=>{if(t===void 0||typeof e=="string")return e;const n=Ke(r??_e(e)??"unknown",t);let a;const s=async()=>(a??=import("ai").then(({wrapLanguageModel:l})=>l({middleware:n,model:e}),l=>{throw a=void 0,l}),a),d=e;return{doGenerate:async l=>s().then(u=>u.doGenerate(l)),doStream:async l=>s().then(u=>u.doStream(l)),modelId:d.modelId,provider:d.provider,specificationVersion:"v4",get supportedUrls(){return s().then(l=>l.supportedUrls)}}};let x;const ne=()=>(x??=Promise.all([import("@ai-sdk/openai"),import("workers-ai-provider/openai"),import("workers-ai-provider/anthropic")]).then(([e,{openai:t},{anthropic:r}])=>({createOpenAI:e.createOpenAI,plugins:[t,r]}),e=>{throw x=void 0,e}),x),oe=(e,t,r)=>({doGenerate:async n=>r().then(a=>a.doGenerate(n)),doStream:async n=>r().then(a=>a.doStream(n)),modelId:e,provider:t,specificationVersion:"v4",get supportedUrls(){return r().then(n=>n.supportedUrls)}}),Ye={maxEmbeddingsPerCall:3e3,supportsParallelCalls:!0},ae=(e,t,r,n)=>({doEmbed:async a=>r().then(s=>s.doEmbed(a)),get maxEmbeddingsPerCall(){return n?.maxEmbeddingsPerCall??r().then(a=>a.maxEmbeddingsPerCall)},modelId:e,provider:t,specificationVersion:"v4",get supportsParallelCalls(){return n?.supportsParallelCalls??r().then(a=>a.supportsParallelCalls)}});let W;const X=()=>(W??=import("workers-ai-provider").catch(e=>{throw W=void 0,e}),W),R=e=>!e.startsWith("@")&&e.includes("/"),Xe=e=>{const t=(r,n)=>oe(r,"workersai.chat",async()=>e(r).then(a=>a(r,n)));return t.textEmbeddingModel=r=>ae(r,"workersai.embedding",async()=>e(r).then(n=>n.textEmbeddingModel?.(r)),R(r)?void 0:Ye),t},_=e=>{throw new m("INTERNAL",`@lunora/ai: ${e} needs the \`AI\` binding (env.AI). In dev, Lunora leaves it out when there is no Cloudflare login: run \`wrangler login\` or set CLOUDFLARE_API_TOKEN. Elsewhere, add an \`ai\` binding to wrangler.jsonc. Or set ${D} to an OpenAI-compatible proxy for "<provider>/<model>" slugs.`)},se=()=>_("this model id");se.textEmbeddingModel=()=>_("this embedding model id");const je=3040,Qe=/^(?:[A-Z]\w*:\s*)?3040\s*:/iu,qe=e=>e?.code===je||e instanceof Error&&Qe.test(e.message),Ze="default",Je=new Map([[401,"UNAUTHORIZED"],[403,"FORBIDDEN"],[404,"NOT_FOUND"],[408,"SERVICE_UNAVAILABLE"],[429,"RATE_LIMITED"]]),ie=e=>Je.get(e)??(e>=400&&e<500?"BAD_REQUEST":"SERVICE_UNAVAILABLE"),de=300,et=new Set(["127.0.0.1","[::1]","localhost"]),tt=(e,t)=>{const r=URL.canParse(e)?new URL(e):void 0;if(r===void 0)return`${D} is not a valid URL`;if(t!==void 0&&r.protocol!=="https:"&&!et.has(r.hostname))return`${D} (${r.origin}) is not HTTPS, so ${ee} would travel in cleartext — use an https:// URL`},rt=e=>{const t=N(e,D);if(t===void 0)return;const r=N(e,ee),n=tt(t,r);if(n!==void 0){const d=()=>{throw new m("INTERNAL",`@lunora/ai: ${n}`)};return{chat:d,embedding:d,image:d}}let a;const s=()=>(a??=ne().then(({createOpenAI:d})=>d({apiKey:r??"",baseURL:t,name:"lunora-proxy"}),d=>{throw a=void 0,d}),a);return{chat:d=>oe(d,"lunora-proxy",async()=>s().then(l=>l.chat(d))),embedding:d=>ae(d,"lunora-proxy",async()=>s().then(l=>l.embedding(d))),image:async d=>s().then(l=>l.image(d))}},nt=(e,t)=>{const r=e===void 0?void 0:pe(e);return r===void 0?t:{...t,tags:{...r,...t?.tags}}},ot=(e,t,r)=>{const n=J(r);if(e!==void 0)return n!==void 0&&e.metadata===void 0?{...e,metadata:n}:e;if(t===void 0)return;const a=N(t,te);if(a!==void 0)return be(t),n===void 0?{id:a}:{id:a,metadata:n}};let $;const at=()=>($??=Promise.all([import("@ai-sdk/openai"),import("@ai-sdk/google")]).then(([e,t])=>({createGoogle:t.createGoogle,createOpenAI:e.createOpenAI}),e=>{throw $=void 0,e}),$),j=8,st=/^[1-9]\d*x[1-9]\d*$/u,it=20*1024*1024,Q="unused",q=(e,t)=>{const r=new Headers(t?.headers);return r.delete("authorization"),r.delete("x-goog-api-key"),fetch(e,{...t,headers:r})},dt=e=>{const t=e.pathname.split("/").findLast(r=>r.length>0);return t===void 0||t===""?"document":t},C=(e,t)=>{if(e>t)throw new m("PAYLOAD_TOO_LARGE",`@lunora/ai: toMarkdown document is ${String(e)} bytes, over the ${String(t)}-byte limit — raise \`maxBytes\` to convert it`)},ct=async(e,t)=>{if(e.body===null)return new Uint8Array;let r=0;const n=e.body.pipeThrough(new TransformStream({transform(a,s){if(r+=a.byteLength,r>t){s.error(new m("PAYLOAD_TOO_LARGE",`@lunora/ai: toMarkdown document is over the ${String(t)}-byte limit — raise \`maxBytes\` to convert it`));return}s.enqueue(a)}}));return new Uint8Array(await new Response(n).arrayBuffer())},lt=e=>{if(e.protocol!=="https:"&&e.protocol!=="http:"||He(e.hostname))throw new m("BAD_REQUEST",`@lunora/ai: toMarkdown will not fetch ${e.href} — only public http(s) hosts; pass its bytes or a Blob instead`)},ut=async(e,t,r)=>{if(e instanceof URL){lt(e);const s=await fetch(e,{redirect:"manual"});if(!s.ok){const v=s.status>=300&&s.status<400?"; redirects are not followed, so pass the final URL":"";throw new m("BAD_REQUEST",`@lunora/ai: toMarkdown could not fetch ${e.href} (HTTP ${String(s.status)})${v}`)}const d=Number(s.headers.get("content-length"));s.headers.has("content-length")&&Number.isFinite(d)&&C(d,r);const l=await ct(s,r),u=s.headers.get("content-type");return{blob:new Blob([l],u===null||u===""?void 0:{type:u}),name:t?.name??dt(e)}}if(e instanceof Blob)return C(e.size,r),{blob:e,name:t?.name??"document"};const n=e instanceof Uint8Array?Uint8Array.from(e):new Uint8Array(e);C(n.byteLength,r);const a=t?.mimeType;return{blob:new Blob([n],a===void 0?void 0:{type:a}),name:t?.name??"document"}},Z=e=>{if(e===void 0||e==="")return;const t=Number(e);return Number.isInteger(t)?t:void 0},ft=e=>{if(e===void 0)return{};const[t,r]=e.split("x");return{height:Z(r),width:Z(t)}},T=e=>{const t=(r,n=0)=>r.every((a,s)=>e[n+s]===a);return t([137,80,78,71])?"image/png":t([255,216,255])?"image/jpeg":t([71,73,70,56])?"image/gif":t([82,73,70,70])&&t([87,69,66,80],8)?"image/webp":void 0},mt=e=>{try{return Me(e.slice(0,16))}catch{return new Uint8Array}},M=(e,t)=>t===void 0?{base64:e}:{base64:e,mimeType:t},ce=async e=>{if(typeof e=="string")return M(e,T(mt(e)));if(e instanceof Uint8Array)return M(L(e),T(e));if(e instanceof ArrayBuffer){const t=new Uint8Array(e);return M(L(t),T(t))}if(e instanceof Response){if(!e.ok){const n=(await e.text().catch(()=>"")).slice(0,de);throw new m(ie(e.status),`@lunora/ai: image generation failed with HTTP ${String(e.status)}${n===""?"":`: ${n}`}`)}const t=new Uint8Array(await e.arrayBuffer());return M(L(t),T(t))}if(e instanceof ReadableStream){const t=new Uint8Array(await new Response(e).arrayBuffer());return M(L(t),T(t))}if(typeof e=="object"&&e!==null&&"image"in e)return ce(e.image)},pt=e=>{const{binding:t,defaultEmbeddingModel:r,defaultModel:n,env:a,gateway:s,metadata:d,provider:l,telemetry:u}=e,v=rt(a),y=nt(a,d),A=ot(s,a,y),E=s?.metadata===void 0?J(y):void 0,p=n??N(a,F),P=r??N(a,H);let U;const le=()=>(U??=X().then(({createWorkersAI:o})=>o({binding:t,gateway:A})).catch(o=>{throw U=void 0,o}),U);let k;const ue=()=>(k??=Promise.all([X(),ne()]).then(([{createWorkersAI:o},{plugins:c}])=>o({binding:t,gateway:A,providers:c})).catch(o=>{throw k=void 0,o}),k),b=l??(t?Xe(async o=>R(o)?ue():le()):se),fe=(o,c)=>R(o)?v!==void 0?v.chat(o):E===void 0?b(o):b(o,{metadata:E}):c?.rejectIfBusy===void 0?b(o):b(o,{rejectIfBusy:c.rejectIfBusy}),me=(o,c)=>{const i=o??p;if(i===void 0||i==="")throw new m("INTERNAL",`@lunora/ai: no model supplied and no default configured — pass a model id, or set ${F} in the Worker env (wrangler \`vars\` / \`.dev.vars\`)`);return typeof i=="string"?Y(fe(i,c),u,i):Y(i,u)},he=o=>{if(v!==void 0&&R(o))return v.embedding(o);const c=b.textEmbeddingModel;if(typeof c!="function")throw new m("INTERNAL","@lunora/ai: the Workers AI provider does not expose `textEmbeddingModel`; pass an AI SDK EmbeddingModel (e.g. from @ai-sdk/openai) to embed()");return c.call(b,o)},ge=o=>{if(typeof o=="object")return o;const c=o??P;if(!c)throw new m("INTERNAL",`@lunora/ai: no embedding model supplied and no default configured — pass an embedding model id or an AI SDK EmbeddingModel, or set ${H} in the Worker env (wrangler \`vars\` / \`.dev.vars\`)`);return he(c)},G=async(o,c,i)=>{if(!t)return _("ai.run");const g=A!==void 0&&i?.gateway===void 0?{...i,gateway:A}:i;try{return await t.run(o,c,g)}catch(h){throw qe(h)?new m("RATE_LIMITED",`@lunora/ai: Workers AI has no free capacity for ${o} (error 3040) — retry later`,{cause:h}):h}},we=async(o,c)=>{if(!t)return _("ai.websearch");if(typeof t.websearch!="function")throw new m("NOT_IMPLEMENTED","@lunora/ai: this Workers runtime's `AI` binding has no websearch() — update wrangler / @cloudflare/vite-plugin to a release that ships the Web Search API");const{gatewayId:i,...g}=c??{},h=await t.websearch({...g,gatewayId:i??A?.id??Ze,query:o});if(!h.ok){const I=(await h.text().catch(()=>"")).slice(0,de);throw new m(ie(h.status),`@lunora/ai: web search failed with HTTP ${String(h.status)}${I===""?"":`: ${I}`}`)}const w=await h.json().catch(()=>{});if(!Array.isArray(w?.items))throw new m("INTERNAL","@lunora/ai: web search returned a body that is not JSON with an `items` array");return w},ve=async(o,c)=>{if(!t)return _("ai.toMarkdown");if(typeof t.toMarkdown!="function")throw new m("NOT_IMPLEMENTED","@lunora/ai: this Workers runtime's `AI` binding has no toMarkdown() — update wrangler / @cloudflare/vite-plugin to a release that ships the Markdown Conversion API");const i=c?.maxBytes??it;if(!Number.isFinite(i)||i<=0)throw new m("BAD_REQUEST","@lunora/ai: toMarkdown maxBytes must be a positive number of bytes");const{blob:g,name:h}=await ut(o,c,i),w=await t.toMarkdown({blob:g,name:h},c?.conversionOptions),f=Array.isArray(w)?w[0]:w;if(f===void 0)throw new m("INTERNAL","@lunora/ai: toMarkdown returned no conversion result");if(f.format==="error")throw new m("BAD_REQUEST",`@lunora/ai: toMarkdown could not convert "${h}": ${f.error??"unknown error"}`);if(typeof f.data!="string")throw new m("INTERNAL",`@lunora/ai: toMarkdown returned a "${f.format}" result with no data`);return{markdown:f.data,...f.mimetype===void 0?{}:{mimeType:f.mimetype},...f.pages===void 0?{}:{pages:f.pages},...f.tokens===void 0?{}:{tokens:f.tokens}}},Ae=async o=>{if(!t)return _("ai.images.generate");const{height:c,width:i}=ft(o.size),g={prompt:o.prompt,...c===void 0?{}:{height:c},...i===void 0?{}:{width:i},...o.seed===void 0?{}:{seed:o.seed}},h=async(w,f)=>{if(w>=(o.count??1))return f;const I=await ce(await G(o.model,g));if(I===void 0)throw new m("INTERNAL",`@lunora/ai: ${o.model} returned no image data`);return h(w+1,[...f,I])};return{images:await h(0,[]),model:o.model}},ye=async(o,c,i)=>{const{createGoogle:g,createOpenAI:h}=await at(),w=A===void 0?void 0:Ie({...a,[te]:A.id});let f;o==="openai"?v!==void 0?f=await v.image(i.model):w===void 0?f=h().image(c):f=h({apiKey:Q,baseURL:`${w.baseURL}/openai`,fetch:q,headers:w.headers}).image(c):w===void 0?f=g().image(c):f=g({apiKey:Q,baseURL:`${w.baseURL}/google-ai-studio/v1beta`,fetch:q,headers:w.headers}).image(c);const{generateImage:I}=await import("ai");return{images:(await I({model:f,prompt:i.prompt,...i.count===void 0?{}:{n:i.count},...i.seed===void 0?{}:{seed:i.seed},...i.size===void 0?{}:{size:i.size}})).images.map(V=>({base64:V.base64,mimeType:V.mediaType})),model:i.model}},Ee=async(o,c)=>{if(o.startsWith("@"))return Ae(c);const i=o.indexOf("/"),g=i===-1?"":o.slice(0,i),h=i===-1?"":o.slice(i+1);if((g==="openai"||g==="google")&&h.length>0)return ye(g,h,c);throw new m("AI_UNKNOWN_IMAGE_MODEL",`@lunora/ai: no image provider for "${o}" — pass a Workers AI image id (@cf/…), or an "openai/<model>" or "google/<model>" slug`)};return{embeddingModel:ge,images:{generate:async o=>{const c=o.model,i=o.count??1;if(!Number.isInteger(i)||i<1||i>j)throw new m("BAD_REQUEST",`@lunora/ai: count must be an integer from 1 to ${String(j)}`,{status:400});if(o.size!==void 0&&!st.test(o.size))throw new m("BAD_REQUEST",`@lunora/ai: size must be "<width>x<height>" with positive integers, e.g. "1024x1024" (got "${o.size}")`);const g=await Ee(c,o);return Te(c,g.images.length,u?.metrics),g}},model:me,run:G,toMarkdown:ve,websearch:we,workersai:b}};export{pt as default};
|