@ax-llm/ax 14.0.30 → 14.0.32

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/index.js CHANGED
@@ -1,17 +1,17 @@
1
- function ve({model:i,modelInfo:e,models:t}){let n=t?.find(l=>l.key===i),r=n&&"model"in n?n.model:i,o=e.find(l=>l.name===i);if(o)return o;let s=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===s);return a||null}var Ir=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function ge(){return Ir.randomUUID()}async function ya(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Ir.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var br=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return ya(this.data)}};function hn(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new br}function es(){return Ir}var fn=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
1
+ function Me({model:i,modelInfo:e,models:t}){let n=t?.find(l=>l.key===i),r=n&&"model"in n?n.model:i,o=e.find(l=>l.name===i);if(o)return o;let s=r.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===s);return a||null}var Rr=(()=>{if(globalThis.crypto&&typeof globalThis.crypto.randomUUID=="function")return globalThis.crypto;throw new Error("Web Crypto API with randomUUID support not available. Requires Node.js 16+ or modern browser.")})();function he(){return Rr.randomUUID()}async function Oa(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await Rr.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(s=>s.toString(16).padStart(2,"0")).join("")}var Cr=class{data="";update(e){return this.data+=e,this}digest(e){if(e!=="hex")throw new Error("Only hex encoding is supported");let n=new TextEncoder().encode(this.data),r=0;for(let o=0;o<n.length;o++){let s=n[o];r=(r<<5)-r+s,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return Oa(this.data)}};function An(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new Cr}function cs(){return Rr}var xn=class extends TransformStream{buffer="";currentEvent={rawData:""};dataParser;onError;constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)}),this.dataParser=e.dataParser||JSON.parse,this.onError=e.onError||((t,n)=>{console.warn("Failed to parse event data:",t),console.log("Raw data that failed to parse:",n)})}handleChunk(e,t){this.buffer+=e,this.processBuffer(t)}handleFlush(e){this.processBuffer(e),this.currentEvent.rawData&&this.processEvent(e)}processBuffer(e){let n=this.buffer.replace(/\r\n|\r/g,`
2
2
  `).split(`
3
3
  `);this.buffer=n.pop()||"";for(let r of n)r===""?this.processEvent(e):this.parseLine(r)}parseLine(e){if(e.startsWith(":"))return;let t=e.indexOf(":");if(t===-1){this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
4
4
  `)?`
5
5
  `:"")+e.trim();return}let n=e.slice(0,t).trim(),r=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=r;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
6
6
  `)?`
7
- `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var Tr=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},An=class extends TransformStream{constructor(){super(new Tr)}};var ba={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Ia=globalThis.TextDecoderStream??An,Re=class extends Error{constructor(t,n,r,o,s={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=ge(),this.context=s,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},mt=class extends Re{constructor(t,n,r,o,s,a){super(`HTTP ${t} - ${n}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},Ve=class extends Re{constructor(t,n,r,o,s){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},et=class extends Re{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name=this.constructor.name}},Ue=class extends Re{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name=this.constructor.name}},gt=class extends Re{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name=this.constructor.name}},wt=class extends Re{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name=this.constructor.name}},st=class extends Re{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name=this.constructor.name}},ae=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=ge()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Fe=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=ge()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Be=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=ge()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function ts(i){try{return i.headers.get("content-type")?.includes("application/json")?await i.json():await i.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function ns(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Ta(){return{startTime:Date.now(),retryCount:0}}function rs(i){i.retryCount++,i.lastRetryTime=Date.now()}function os(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Ve&&!(i instanceof st)}var ye=async(i,e)=>{if(i.localCall)return await i.localCall(e,i.stream);if(!i.url)throw new Error("API URL is required when localCall is not provided");let t={...ba,...i.retry},n=i.timeout,r=Ta(),o,s=new URL(i.url),a=`${[s.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${s.search}`,l=new URL(a,s);if(i.corsProxy){let u=l.href;l=new URL(`${i.corsProxy}?url=${encodeURIComponent(u)}`)}let c=ge();if(i.validateRequest&&!await i.validateRequest(e))throw new et("Invalid request data",l.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":l.href,"request.id":c,"request.startTime":r.startTime});let p=0;for(;;){let u=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new wt(l.href,i.abortSignal.reason,e,{metrics:r});let d=()=>{u.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",d,{once:!0});let m=u.abort.bind(u);u.abort=g=>{i.abortSignal.removeEventListener("abort",d),m(g)}}n&&(o=setTimeout(()=>{u.abort("Request timeout")},n));try{let d=await(i.fetch??fetch)(l,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...i.headers},body:JSON.stringify(e),signal:u.signal});if(o&&clearTimeout(o),d.status===401||d.status===403){let A=await ts(d);throw new st(l.href,e,A,{metrics:r})}if(d.status>=400&&os(new Error,d.status,p,t)){let A=ns(p,t);p++,rs(r),i.span?.addEvent("retry",{attempt:p,delay:A,status:d.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,A));continue}if(d.status>=400){let A=await ts(d);throw new mt(d.status,d.statusText,l.href,e,A,{metrics:r})}if(!i.stream){let A=await d.json();if(i.validateResponse&&!await i.validateResponse(A))throw new et("Invalid response data",l.href,e,{validation:"response"});return i.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),A}if(!d.body)throw new et("Response body is null",l.href,e,{metrics:r});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(A){let y=d.body.getReader(),I=new TextDecoder,T="";async function b(){try{for(;;){let{done:w,value:v}=await y.read();if(w){x=!0,A.close();break}T+=I.decode(v,{stream:!0});let F=T.split(`
7
+ `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let o=Number.parseInt(r,10);Number.isNaN(o)||(this.currentEvent.retry=o);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var wr=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},yn=class extends TransformStream{constructor(){super(new wr)}};var ka={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Ma=globalThis.TextDecoderStream??yn,Te=class extends Error{constructor(t,n,r,o,s={}){super(t);this.url=n;this.requestBody=r;this.responseBody=o;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=he(),this.context=s,this.stack=this.toString()}timestamp;errorId;context;toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},ht=class extends Te{constructor(t,n,r,o,s,a){super(`HTTP ${t} - ${n}`,r,o,{httpStatus:t,httpStatusText:n,responseBody:s,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},Je=class extends Te{constructor(t,n,r,o,s){super(`Network Error: ${t.message}`,n,r,o,{originalErrorName:t.name,originalErrorStack:t.stack,...s});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},nt=class extends Te{constructor(e,t,n,r){super(e,t,n,void 0,r),this.name=this.constructor.name}},Be=class extends Te{constructor(t,n,r,o){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...o});this.lastChunk=r;this.name=this.constructor.name}},ft=class extends Te{constructor(e,t,n,r){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r}),this.name=this.constructor.name}},vt=class extends Te{constructor(e,t,n,r){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r}),this.name=this.constructor.name}},at=class extends Te{constructor(e,t,n,r){super("Authentication failed",e,t,n,r),this.name=this.constructor.name}},le=class extends Error{constructor(t,n,r){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=r;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=he()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},De=class extends Error{constructor(t,n,r=!1){super(`${t} not supported by ${n}${r?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=r;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=he()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
10
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},qe=class extends Error{constructor(t,n,r){super(`Failed to process ${n} during ${r}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=r;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=he()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
11
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function ps(i){try{return i.headers.get("content-type")?.includes("application/json")?await i.json():await i.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function us(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Ea(){return{startTime:Date.now(),retryCount:0}}function ds(i){i.retryCount++,i.lastRetryTime=Date.now()}function ms(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Je&&!(i instanceof at)}var Ce=async(i,e)=>{if(i.localCall)return await i.localCall(e,i.stream);if(!i.url)throw new Error("API URL is required when localCall is not provided");let t={...ka,...i.retry},n=i.timeout,r=Ea(),o,s=new URL(i.url),a=`${[s.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${s.search}`,l=new URL(a,s);if(i.corsProxy){let u=l.href;l=new URL(`${i.corsProxy}?url=${encodeURIComponent(u)}`)}let c=he();if(i.validateRequest&&!await i.validateRequest(e))throw new nt("Invalid request data",l.href,e,{validation:"request"});i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":l.href,"request.id":c,"request.startTime":r.startTime});let p=0;for(;;){let u=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new vt(l.href,i.abortSignal.reason,e,{metrics:r});let d=()=>{u.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",d,{once:!0});let m=u.abort.bind(u);u.abort=g=>{i.abortSignal.removeEventListener("abort",d),m(g)}}n&&(o=setTimeout(()=>{u.abort("Request timeout")},n));try{let d=await(i.fetch??fetch)(l,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":c,"X-Retry-Count":p.toString(),...i.headers},body:JSON.stringify(e),signal:u.signal});if(o&&clearTimeout(o),d.status===401||d.status===403){let A=await ps(d);throw new at(l.href,e,A,{metrics:r})}if(d.status>=400&&ms(new Error,d.status,p,t)){let A=us(p,t);p++,ds(r),i.span?.addEvent("retry",{attempt:p,delay:A,status:d.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,A));continue}if(d.status>=400){let A=await ps(d);throw new ht(d.status,d.statusText,l.href,e,A,{metrics:r})}if(!i.stream){let A=await d.json();if(i.validateResponse&&!await i.validateResponse(A))throw new nt("Invalid response data",l.href,e,{validation:"response"});return i.span?.setAttributes({"response.time":Date.now()-r.startTime,"response.retries":r.retryCount}),A}if(!d.body)throw new nt("Response body is null",l.href,e,{metrics:r});let m,g=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(A){let y=d.body.getReader(),I=new TextDecoder,T="";async function C(){try{for(;;){let{done:b,value:v}=await y.read();if(b){x=!0,A.close();break}T+=I.decode(v,{stream:!0});let P=T.split(`
12
12
 
13
- `);T=F.pop()||"";for(let K of F){if(!K.trim())continue;let E=K.split(`
14
- `),R="",$="message";for(let C of E)C.startsWith("data: ")?R=C.slice(6):C.startsWith("event: ")&&($=C.slice(7));if(R){if(R==="[DONE]"){A.close();return}try{let C=JSON.parse(R);m=C,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),A.enqueue(C),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":$})}catch(C){i.debug&&console.warn("Skipping non-JSON SSE data:",R,C)}}}}}catch(w){let v=w,F={...r,streamDuration:Date.now()-r.startTime};v.name==="AbortError"||v.message?.includes("aborted")?A.error(new Ue(l.href,e,m,{streamMetrics:F})):A.error(new Ve(v,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:F}))}finally{y.releaseLock()}}b()}});let h=new TransformStream({transform(A,y){m=A,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),y.enqueue(A),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),x=!1;return new ReadableStream({start(A){let y=d.body.pipeThrough(new Ia).pipeThrough(new fn).pipeThrough(h).getReader();async function I(){try{for(;;){let{done:T,value:b}=await y.read();if(T){x||(x=!0,A.close());break}if(x)break;A.enqueue(b)}}catch(T){let b=T,w={...r,streamDuration:Date.now()-r.startTime};throw b.name==="AbortError"||b.message?.includes("aborted")?A.error(new Ue(l.href,e,m,{streamMetrics:w})):b instanceof TypeError&&b.message.includes("cancelled")?A.error(new Ue(l.href,e,m,{streamMetrics:w,cancelReason:"Stream cancelled by client"})):A.error(new Ve(b,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:w})),b}finally{o&&clearTimeout(o),y.releaseLock()}}I()},cancel(){x=!0}})}catch(d){if(d instanceof Error&&d.name==="AbortError")throw i.abortSignal?.aborted?new wt(l.href,i.abortSignal.reason,e,{metrics:r}):new gt(l.href,n||0,e,{metrics:r});if(i.span?.isRecording()&&(i.span.recordException(d),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),d instanceof Ve&&os(d,void 0,p,t)){let m=ns(p,t);p++,rs(r),i.span?.addEvent("retry",{attempt:p,delay:m,error:d.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw d instanceof Re&&(d.context.metrics=r),d}finally{o!==void 0&&clearTimeout(o)}}};import{context as Ls,SpanKind as Gs}from"@opentelemetry/api";var se={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var Ae=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var qc=new Ae,ss=i=>{console.log(i)},is=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
13
+ `);T=P.pop()||"";for(let K of P){if(!K.trim())continue;let O=K.split(`
14
+ `),w="",_="message";for(let R of O)R.startsWith("data: ")?w=R.slice(6):R.startsWith("event: ")&&(_=R.slice(7));if(w){if(w==="[DONE]"){A.close();return}try{let R=JSON.parse(w);m=R,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),A.enqueue(R),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":_})}catch(R){i.debug&&console.warn("Skipping non-JSON SSE data:",w,R)}}}}}catch(b){let v=b,P={...r,streamDuration:Date.now()-r.startTime};v.name==="AbortError"||v.message?.includes("aborted")?A.error(new Be(l.href,e,m,{streamMetrics:P})):A.error(new Je(v,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:P}))}finally{y.releaseLock()}}C()}});let h=new TransformStream({transform(A,y){m=A,g++,r.streamChunks=g,r.lastChunkTime=Date.now(),y.enqueue(A),i.span?.addEvent("stream.chunk",{"stream.chunks":g,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),x=!1;return new ReadableStream({start(A){let y=d.body.pipeThrough(new Ma).pipeThrough(new xn).pipeThrough(h).getReader();async function I(){try{for(;;){let{done:T,value:C}=await y.read();if(T){x||(x=!0,A.close());break}if(x)break;A.enqueue(C)}}catch(T){let C=T,b={...r,streamDuration:Date.now()-r.startTime};throw C.name==="AbortError"||C.message?.includes("aborted")?A.error(new Be(l.href,e,m,{streamMetrics:b})):C instanceof TypeError&&C.message.includes("cancelled")?A.error(new Be(l.href,e,m,{streamMetrics:b,cancelReason:"Stream cancelled by client"})):A.error(new Je(C,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:b})),C}finally{o&&clearTimeout(o),y.releaseLock()}}I()},cancel(){x=!0}})}catch(d){if(d instanceof Error&&d.name==="AbortError")throw i.abortSignal?.aborted?new vt(l.href,i.abortSignal.reason,e,{metrics:r}):new ft(l.href,n||0,e,{metrics:r});if(i.span?.isRecording()&&(i.span.recordException(d),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),d instanceof Je&&ms(d,void 0,p,t)){let m=us(p,t);p++,ds(r),i.span?.addEvent("retry",{attempt:p,delay:m,error:d.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(g=>setTimeout(g,m));continue}throw d instanceof Te&&(d.context.metrics=r),d}finally{o!==void 0&&clearTimeout(o)}}};import{context as Ws,SpanKind as Vs}from"@opentelemetry/api";var ie={signatureStrict:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var be=class{ANSI_WHITE_BRIGHT="\x1B[97m";ANSI_GREEN_BRIGHT="\x1B[92m";ANSI_BLUE_BRIGHT="\x1B[94m";ANSI_RED_BRIGHT="\x1B[91m";ANSI_YELLOW_BRIGHT="\x1B[93m";ANSI_YELLOW="\x1B[93m";ANSI_RED="\x1B[91m";ANSI_RESET="\x1B[0m";ANSI_ORANGE="\x1B[38;5;208m";ANSI_WHITE="\x1B[37m";ANSI_CYAN_BRIGHT="\x1B[96m";ANSI_MAGENTA_BRIGHT="\x1B[95m";ANSI_GRAY="\x1B[90m";ANSI_GREEN="\x1B[32m";ANSI_CYAN="\x1B[36m";ANSI_MAGENTA="\x1B[35m";ANSI_BLUE="\x1B[34m";ANSI_YELLOW_DIM="\x1B[33m";colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};var np=new be,gs=i=>{console.log(i)},hs=(i,e,t)=>{let n=(r,o)=>t&&o&&o in t?t[o](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
15
15
  ${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
16
16
  ${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
17
17
  `;if(typeof i.content=="string")return r+n(i.content,"green");let o=i.content.map(s=>{if(s.type==="text")return n(s.text,"green");if(s.type==="image"){let a=e?"[Image]":`[Image: ${s.image}]`;return n(a,"green")}if(s.type==="audio"){let a=e?"[Audio]":`[Audio: ${s.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+o.join(`
@@ -21,11 +21,11 @@ ${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","gr
21
21
  `,i.functionCalls.forEach((s,a)=>{let l=typeof s.function.params=="string"?s.function.params:JSON.stringify(s.function.params,null,2);o+=n(`${a+1}. ${s.function.name}(${l}) [id: ${s.id}]`,"yellowDim"),a<(i.functionCalls?.length??0)-1&&(o+=`
22
22
  `)}),o+=`
23
23
  `),!i.content&&(!i.functionCalls||i.functionCalls.length===0)&&(o+=n("[No content]","gray")),o}default:return`${n("[ UNKNOWN ]","redBright")}
24
- ${n(JSON.stringify(i),"gray")}`}},as=(i=ss)=>{let e=new Ae,t=e.gray(`${"\u2500".repeat(60)}
24
+ ${n(JSON.stringify(i),"gray")}`}},fs=(i=gs)=>{let e=new be,t=e.gray(`${"\u2500".repeat(60)}
25
25
  `);return n=>{let r=n,o="";switch(r.name){case"ChatRequestChatPrompt":o=`
26
26
  ${e.blueBright(`[ CHAT REQUEST Step ${r.step} ]`)}
27
27
  ${t}
28
- `,r.value.forEach((s,a)=>{o+=is(s,void 0,e),a<r.value.length-1&&(o+=`
28
+ `,r.value.forEach((s,a)=>{o+=hs(s,void 0,e),a<r.value.length-1&&(o+=`
29
29
  ${t}
30
30
  `)}),o+=`
31
31
  ${t}`;break;case"FunctionResults":o=`
@@ -35,9 +35,10 @@ Result: ${s.result}`),a<r.value.length-1&&(o+=`
35
35
  ${t}
36
36
  `)});break;case"ChatResponseResults":o=`
37
37
  ${e.cyanBright("[ CHAT RESPONSE ]")}
38
- `,r.value.forEach((s,a)=>{o+=e.cyan(s.content||"[No content]"),a<r.value.length-1&&(o+=`
38
+ `,r.value.forEach((s,a)=>{let l=[];(s.thoughtBlock?.data||s.thought)&&l.push(e.gray(`[thought${s.thoughtBlock?.encrypted?" (redacted)":""}] `+(s.thoughtBlock?.data??s.thought??""))),s.content&&l.push(e.cyan(s.content)),l.length===0&&l.push(e.gray("[No content]")),o+=l.join(`
39
+ `),a<r.value.length-1&&(o+=`
39
40
  ${t}
40
- `)});break;case"ChatResponseStreamingResult":{let s=r.value.delta||r.value.content||"";o=e.cyanBright(s);return}case"ChatResponseStreamingDoneResult":{o=`
41
+ `)});break;case"ChatResponseStreamingResult":{let s=r.value.thought,a=s||r.value.delta||r.value.content||"";o=s?e.gray(`[thought] ${s}`):e.cyanBright(a);return}case"ChatResponseStreamingDoneResult":{o=`
41
42
  ${e.cyanBright("[ CHAT RESPONSE ]")}
42
43
  ${t}
43
44
  `,r.value.content&&(o+=e.cyanBright(r.value.content)),r.value.functionCalls&&(o+=e.cyanBright(JSON.stringify(r.value.functionCalls,null,2)));break}case"FunctionError":o=`
@@ -80,10 +81,10 @@ ${t}
80
81
  [ CHAT RESPONSE CITATIONS ]`)}
81
82
  `,r.value.forEach(s=>{o+=`${e.white("- ")}${e.cyan(s.title||s.url)}
82
83
  `,s.description&&(o+=` ${e.gray(s.description)}
83
- `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},ls=as(),Ra=(i=ss)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
84
+ `)}),o+=t;break}default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},As=fs(),Pa=(i=gs)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
84
85
  [ CHAT REQUEST Step ${n.step} ]
85
86
  ${e}
86
- `,n.value.forEach((o,s)=>{r+=is(o),s<n.value.length-1&&(r+=`
87
+ `,n.value.forEach((o,s)=>{r+=hs(o),s<n.value.length-1&&(r+=`
87
88
  ${e}
88
89
  `)}),r+=`
89
90
  ${e}`;break;case"FunctionResults":r=`
@@ -140,23 +141,23 @@ ${e}
140
141
  `,n.value.forEach(o=>{r+=`- ${o.title||o.url}
141
142
  `,o.description&&(r+=` ${o.description}
142
143
  `)}),r+=`${e}
143
- `;break}default:r=JSON.stringify(n,null,2)}i(r)}};var U={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},qe={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},cs=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(cs||{}),ps=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ps||{});var Rr=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},xn=class extends TransformStream{constructor(e,t){super(new Rr(e,t))}};function yn(i,e){for(let t of e){let n=i.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var us=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ds=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)},ms=(i,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:i})};function gs(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?yn(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var hs=(i,e)=>{e({name:"FunctionResults",value:i})},Cr=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},fs=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},As=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},xs=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var ys=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},bs=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},Is=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var wr=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},bn,Ts=i=>{if(bn)return bn;if(i)return bn=Ca(i),bn};var Ca=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),Rs=(i,e,t,n,r)=>{try{if(i.latencyHistogram){let o=wr({operation:e,ai_service:n,...r?{model:r}:{}});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Cs=(i,e,t,n,r,o,s)=>{let a={operation:e,ai_service:o,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,a)},ws=(i,e,t,n)=>{try{if(i.errorCounter){let r=wr({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},Ss=(i,e,t,n,r)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},vs=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},St=(i,e,t,n,r)=>{try{let o=wr({ai_service:n,...r?{model:r}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,o),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},Os=(i,e,t,n,r)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Ms=(i,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},Sr=(i,e,t,n,r)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},vr=(i,e,t,n,r)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},ks=(i,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},Or=(i,e,t,n,r)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Es=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Ps=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Fs=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},_s=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ns=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Ds=(i,e,t,n,r)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};function $s(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function _e(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${$s(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${$s(e.item)}`),new Error(t.join(`
144
- `))}function vt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let p=o.fileUri;if(!p||p.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(p)}`)}if(l){let p=o.data;if(!p||p.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(p)}`)}let c="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(s)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof n=="string"&&n.trim()!=="",s=Array.isArray(r)&&r.length>0;if(!o&&!s&&_e("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:r},item:i}),n!==void 0&&typeof n!="string"&&_e("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&_e("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let a=0;a<r.length;a++){let l=r[a];if((!l||typeof l!="object")&&_e("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:i}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&_e("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:i}),(!("type"in l)||l.type!=="function")&&_e("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:i}),!("function"in l)||!l.function)_e("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:i});else{let c=l.function;(!("name"in c)||typeof c.name!="string"||c.name.trim()==="")&&_e("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:c?.name,item:i}),c.params!==void 0&&typeof c.params!="string"&&typeof c.params!="object"&&_e("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:c.params,item:i})}}if(i.name!==void 0){let a=i.name;(typeof a!="string"||a.trim()==="")&&_e("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&_e("Function message isError must be a boolean when provided",{fieldPath:"isError",value:i.isError,item:i});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Mr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var Q=()=>structuredClone({temperature:0}),de=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),pe=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??se.tracer,this.meter=a.meter??se.meter,this.modelInfo=o,this.models=c,this.id=ge();let p=this.getModel(s.model)??s.model,u=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:p,embedModel:u},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&Sa(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=se.logger??ls;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Ts(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??se.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??se.tracer,this.meter=e.meter??se.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??se.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.#e,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,s)=>o+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Rs(r,e,t,this.name,o),Cs(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;vs(r,e,this.name,o),t&&ws(r,e,this.name,o),Ss(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:s}=e.tokens;n&&St(t,"input",n,this.name,e.model),r&&St(t,"output",r,this.name,e.model),o&&St(t,"total",o,this.name,e.model),s&&St(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&Ms(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Fs(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;_s(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;Os(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);Ds(r,l,c,this.name,o);let p=this.calculatePromptLength(e);Es(r,p,this.name,o),ks(r,s?.temperature,s?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Ns(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let u=this.calculateRequestSize(e);if(Sr(r,"chat",u,this.name,o),n&&!a){let d=n,m=this.calculateResponseSize(d);if(vr(r,"chat",m,this.name,o),d.results)for(let h of d.results)h.functionCalls&&this.recordFunctionCallMetrics(h.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&Ps(r,g,this.name,o);let f=this.estimateCost(this.lastUsedChatModel,d.modelUsage);f>0&&Or(r,"chat",f,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);Sr(n,"embed",o,this.name,r);let s=this.calculateResponseSize(t);vr(n,"embed",s,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&Or(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return o=await this._chat1(e,l),o}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat")),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)vt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(c=>c.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Gs.SERVER,attributes:{[U.LLM_SYSTEM]:this.name,[U.LLM_OPERATION_NAME]:"chat",[U.LLM_REQUEST_MODEL]:n,[U.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[U.LLM_REQUEST_TEMPERATURE]:o.temperature,[U.LLM_REQUEST_TOP_P]:o.topP??"Not set",[U.LLM_REQUEST_TOP_K]:o.topK??"Not set",[U.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[U.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[U.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[U.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Ls.active(),async c=>await this._chat2(n,o,e,t,c)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=r?.debug??this.#e,a;n.functions&&n.functions.length>0&&(a=n.functions.map(x=>this.cleanupFunctionSchema(x)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&us(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",d=p==="prompt"||p==="auto"&&!c?{...l,chatPrompt:l.chatPrompt.map(x=>{if(x.role==="assistant"){let{content:A,name:y,cache:I}=x;return{role:"assistant",content:A,name:y,cache:I}}return x.role==="function"?{role:"user",content:x.result}:x}),functions:[]}:l,m=async()=>{let[x,A]=await this.aiImpl.createChatReq(d,r);return o?.isRecording()&&wa(n,o,this.excludeContentFromTrace),await ye({name:x.name,url:this.apiURL,localCall:x.localCall,headers:await this.buildHeaders(x.headers),stream:t.stream,timeout:this.timeout,debug:s,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},A)},g=r?.rateLimiter??this.rt,f=g?await g(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let x=this.aiImpl.createChatStreamResp.bind(this),A=b=>w=>{let v=x(w,b);if(v.sessionId=r?.sessionId,!v.modelUsage){let F=this.aiImpl.getTokenUsage();F&&(v.modelUsage={ai:this.name,model:e,tokens:F})}if(this.modelUsage=v.modelUsage,this.recordTokenUsage(v.modelUsage),o?.isRecording()&&Us(v,o,this.excludeContentFromTrace),s)for(let F of v.results)ms(F,F.index,r?.logger??this.logger);return v},y=async b=>{o?.isRecording()&&o.end(),s&&gs(b,r?.logger??this.logger)};if(typeof window<"u"){let b=f,w={},v=[],F=r?.abortSignal??this.abortSignal;return new ReadableStream({start:K=>{let E=b.getReader(),R=()=>{try{E.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{K.error(new DOMException("Aborted","AbortError"))}catch{K.error(new Error("Aborted"))}};if(F){if(F.aborted){R();return}F.addEventListener("abort",R,{once:!0})}async function $(){try{for(;;){let{done:C,value:S}=await E.read();if(C){y&&await y(v),K.close();break}let _=A(w)(S);_&&(v.push(_),K.enqueue(_))}}catch(C){if(K.error(C),o?.isRecording())try{o.end()}catch{}}finally{if(E.releaseLock(),F)try{F.removeEventListener("abort",R)}catch{}}}$()}})}return f.pipeThrough(new xn(A({}),y))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let h=this.aiImpl.createChatResp(f);if(h.sessionId=r?.sessionId,!h.modelUsage){let x=this.aiImpl.getTokenUsage();x&&(h.modelUsage={ai:this.name,model:e,tokens:x})}return h.modelUsage&&(this.modelUsage=h.modelUsage,this.recordTokenUsage(h.modelUsage)),o?.isRecording()&&(Us(h,o,this.excludeContentFromTrace),o.end()),s&&ds(h,r?.logger??this.logger),h}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Gs.SERVER,attributes:{[U.LLM_SYSTEM]:this.name,[U.LLM_OPERATION_NAME]:"embeddings",[U.LLM_REQUEST_MODEL]:n}},t?.traceContext??Ls.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=n?.debug??this.#e,a={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&ys(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,m]=await o(a);return await ye({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:s,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},c=n?.rateLimiter??this.rt,p=c?await c(l,{modelUsage:this.embedModelUsage}):await l(),u=this.aiImpl.createEmbedResp?.(p);if(u.sessionId=n?.sessionId,!u.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(u.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage),r?.isRecording()&&u.modelUsage?.tokens&&r.addEvent(qe.GEN_AI_USAGE,{[U.LLM_USAGE_INPUT_TOKENS]:u.modelUsage.tokens.promptTokens,[U.LLM_USAGE_OUTPUT_TOKENS]:u.modelUsage.tokens.completionTokens??0,[U.LLM_USAGE_TOTAL_TOKENS]:u.modelUsage.tokens.totalTokens}),s&&bs(u.embeddings,n?.logger??this.logger),r?.end(),u}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function wa(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(qe.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(qe.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(qe.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(qe.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
145
- `)),e.addEvent(qe.GEN_AI_USER_MESSAGE,r)}function Us(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[U.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(qe.GEN_AI_USAGE,{[U.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[U.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[U.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(qe.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Bs(i){let e=0;for(let t of i){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function Sa(i){let e=new Set;for(let t of i){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var In=(u=>(u.Claude41Opus="claude-opus-4-1-20250805",u.Claude4Opus="claude-opus-4-20250514",u.Claude4Sonnet="claude-sonnet-4-20250514",u.Claude37Sonnet="claude-3-7-sonnet-latest",u.Claude35Sonnet="claude-3-5-sonnet-latest",u.Claude35Haiku="claude-3-5-haiku-latest",u.Claude3Opus="claude-3-opus-latest",u.Claude3Sonnet="claude-3-sonnet-20240229",u.Claude3Haiku="claude-3-haiku-20240307",u.Claude21="claude-2.1",u.ClaudeInstant12="claude-instant-1.2",u))(In||{}),kr=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(kr||{});var Tn=[{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var Rn=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Rn(n)]))),e.items&&(e.items=Rn(e.items)),e},zs=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...Q()}),va=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...Q()}),Er=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(b=>b.role==="system").map(b=>({type:"text",text:b.content,...b.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(b=>b.role!=="system"),c=e.functions?.map(b=>({name:b.name,description:b.description,input_schema:b.parameters?Rn(b.parameters):void 0})),u=(this.config.tools??[]).map(b=>b&&typeof b=="object"&&"type"in b?b:{name:b.name,description:b.description,input_schema:b.input_schema?Rn(b.input_schema):void 0,...b.cache_control?{cache_control:b.cache_control}:{}}),d=[...c??[],...u];this.isVertex&&d.length>0&&(d=d.filter(b=>!(b&&typeof b=="object"&&"type"in b))),d.length===0&&(d=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,f=e.modelConfig?.temperature,h=e.modelConfig?.topP,x=e.modelConfig?.topK??this.config.topK,A=e.modelConfig?.n??this.config.n;if(A&&A>1)throw new Error("Anthropic does not support sampling (n > 1)");let y;if(this.config.thinking?.budget_tokens&&(y=this.config.thinking),t?.thinkingTokenBudget){let b=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":y=void 0;break;case"minimal":y={type:"enabled",budget_tokens:b?.minimal??1024};break;case"low":y={type:"enabled",budget_tokens:b?.low??5e3};break;case"medium":y={type:"enabled",budget_tokens:b?.medium??1e4};break;case"high":y={type:"enabled",budget_tokens:b?.high??2e4};break;case"highest":y={type:"enabled",budget_tokens:b?.highest??32e3};break}}if(!y&&t?.thinkingTokenBudget===void 0){let b=this.config.thinkingTokenBudgetLevels}let I=Oa(l,!!y),T={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...f!==void 0&&!y?{temperature:f}:{},...h!==void 0&&(!y||h>=.95)?{top_p:h}:{},...x&&!y?{top_k:x}:{},...s,...d?{tools:d}:{},...r?{stream:!0}:{},...a?{system:a}:{},...y?{thinking:y}:{},messages:I};return[o,T]};createChatResp=e=>{if(e.type==="error")throw new ae(e.error.message,void 0,void 0);let t=qs(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",s=[],a=[];for(let p of e.content)switch(p.type){case"text":if(r+=p.text??"",Array.isArray(p.citations))for(let u of p.citations)u?.url&&a.push({url:String(u.url),title:typeof u.title=="string"?u.title:void 0,snippet:typeof u.cited_text=="string"?u.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=p.thinking??"");break;case"tool_use":s.push({id:p.id,type:"function",function:{name:p.name,params:p.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),o&&(l.thought=o),s.length>0&&(l.functionCalls=s),a.length>0&&(l.citations=a);let c=[l];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:c,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new ae(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,content:""}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:0,completionTokens:s.output_tokens,totalTokens:s.output_tokens},{results:[{index:r,content:"",finishReason:qs(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Ot=class i extends pe{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){let a=t!==void 0&&n!==void 0,l,c;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let p={...zs(),...r},u=new Er(p,a),d=g=>{let f=ve({model:g,modelInfo:Tn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let f=g,h=f?.config;if(!h)return g;let x={};h.maxTokens!==void 0&&(x.maxTokens=h.maxTokens),h.temperature!==void 0&&(x.temperature=h.temperature),h.topP!==void 0&&(x.topP=h.topP),h.topK!==void 0&&(x.topK=h.topK),h.presencePenalty!==void 0&&(x.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(x.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(x.stopSequences=h.stopSequences),h.endSequences!==void 0&&(x.endSequences=h.endSequences),h.stream!==void 0&&(x.stream=h.stream),h.n!==void 0&&(x.n=h.n);let A={...f};Object.keys(x).length>0&&(A.modelConfig={...f.modelConfig??{},...x});let y=h.thinking?.thinkingTokenBudget;if(typeof y=="number"){let I=p.thinkingTokenBudgetLevels,T=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],b="minimal",w=Number.POSITIVE_INFINITY;for(let[v,F]of T){let K=Math.abs(y-F);K<w&&(w=K,b=v)}A.thinkingTokenBudget=b}return h.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!h.thinking.includeThoughts),A});super(u,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Tn,defaults:{model:p.model},options:o,supportFor:d,models:m??s})}};function Oa(i,e){let t=i.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="";return typeof r.content=="string"&&(o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(s=>{let a={};return typeof s.function.params=="string"?a=JSON.parse(s.function.params):typeof s.function.params=="object"&&(a=s.function.params),{type:"tool_use",id:s.id,name:s.function.name,input:a,...r.cache?{cache:{type:"ephemeral"}}:{}}}),e&&Array.isArray(o)&&o.length>0&&o[0]?.type!=="thinking"&&o[0]?.type!=="redacted_thinking"&&(o=[{type:"redacted_thinking",thinking:""},...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Ma(t);return ka(n)}function Ma(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function ka(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function qs(i){if(i)switch(i){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var Cn=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1="o1",T.O1Mini="o1-mini",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(Cn||{}),Mt=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Mt||{});var kt=(w=>(w.GPT4="gpt-4",w.GPT41="gpt-4.1",w.GPT41Mini="gpt-4.1-mini",w.GPT4O="gpt-4o",w.GPT4OMini="gpt-4o-mini",w.GPT4ChatGPT4O="chatgpt-4o-latest",w.GPT4Turbo="gpt-4-turbo",w.GPT35Turbo="gpt-3.5-turbo",w.GPT35TurboInstruct="gpt-3.5-turbo-instruct",w.GPT35TextDavinci002="text-davinci-002",w.GPT3TextBabbage002="text-babbage-002",w.GPT3TextAda001="text-ada-001",w.GPT5="gpt-5",w.GPT5Nano="gpt-5-nano",w.GPT5Mini="gpt-5-mini",w.GPT5Chat="gpt-5-chat",w.O1Pro="o1-pro",w.O1="o1",w.O1Mini="o1-mini",w.O3Pro="o3-pro",w.O3="o3",w.O3Mini="o3-mini",w.O4Mini="o4-mini",w))(kt||{});var Et=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Pr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Ea=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},ht=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Q()}),_r=()=>structuredClone({...ht(),model:"gpt-5"}),Nr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...de()}),Dr=()=>({...ht(),model:"gpt-5-nano"}),Fr=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Pa(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,p=this.config.store,u=Ea(n),d={model:n,messages:a,...this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...u?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...p?{store:p}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new ae(a.message.refusal,e.model,e.id);let l=js(a.finish_reason),c=a.message.tool_calls?.map(({id:p,function:{arguments:u,name:d}})=>({id:p,type:"function",function:{name:d,params:u}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(p=>p?.type==="url_citation"&&p.url_citation).map(p=>({url:p.url_citation?.url,title:p.url_citation?.title,description:p.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:p,refusal:u,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(u)throw new ae(u,void 0,n);let h=js(f),x=d?.map(({id:A,index:y,function:{name:I,arguments:T}})=>{typeof A=="string"&&typeof y=="number"&&!s.indexIdMap[y]&&(s.indexIdMap[y]=A);let b=s.indexIdMap[y];return b?{id:b,type:"function",function:{name:I,params:T}}:null}).filter(A=>A!==null);return{index:l,content:c??void 0,role:p,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,finishReason:h,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},js=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Pa(i){return i.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var ce=class extends pe{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Fr(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},Pt=class extends ce{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Et,...s??[]];let a=c=>{let p=ve({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:p?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let p=c,u=p?.config;if(!u)return c;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty);let m=u.stopSequences??u.stop;m!==void 0&&(d.stopSequences=m),u.n!==void 0&&(d.n=u.n),u.stream!==void 0&&(d.stream=u.stream);let g={...p};Object.keys(d).length>0&&(g.modelConfig={...p.modelConfig??{},...d});let f=u?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[y,I]of h){let T=Math.abs(f-I);T<A&&(A=T,x=y)}g.thinkingTokenBudget=x}return u?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!u.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...ht(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var Hs=ht,Fa=Nr,_a=Dr,Na=_r,Ft=class extends ce{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let c={...Hs(),...o};l=[...Et,...l??[]];let p=d=>{let m=ve({model:d,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:p});let u=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,u).href),super.setHeaders(async()=>({"api-key":e}))}};var $r=class i{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");Da(e),this.services=[...e].sort(t?.comparator??i.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new i(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,r=Date.now()-n,o=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return r>=o}handleFailure(){let t=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Re))throw n;switch(n.constructor){case st:throw n;case mt:break;case Ve:break;case et:break;case Ue:break;case gt:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Da(i){let e=i.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function ft(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let p of i.chatPrompt){if(p.role==="user"&&Array.isArray(p.content))for(let u of p.content)switch(l.add(u.type),u.type){case"image":e=!0,u.cache&&(a=!0),c+=85;break;case"audio":t=!0,u.cache&&(a=!0),c+=u.duration||60;break;case"file":n=!0,u.cache&&(a=!0),c+=Math.ceil((u.extractedText?.length||1e3)/4);break;case"url":r=!0,u.cache&&(a=!0),c+=Math.ceil((u.cachedContent?.length||2e3)/4);break;case"text":u.cache&&(a=!0),c+=Math.ceil(u.text.length/4);break}else"content"in p&&typeof p.content=="string"&&(c+=Math.ceil(p.content.length/4));"cache"in p&&p.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function Ks(i,e){let t=i.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Lr(i,e){return i.map(t=>{let n=t.getFeatures(),r=Ks(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function Gr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=ft(i),r=Lr(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function $a(i,e){let t=ft(i),n=Lr(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function La(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Ga(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var wn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(wn||{}),Sn=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(Sn||{});var Ur=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var Vs=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...Q()}),Ua=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...de()}),Br=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let s=Ba(r),a=e.functions?.map(u=>{let d={};if(u.parameters?.properties)for(let[m,g]of Object.entries(u.parameters.properties))d[m]={description:g.description,type:g.type,required:u.parameters.required?.includes(m)??!1};return{name:u.name,description:u.description,parameter_definitions:d}}),l=e.chatPrompt.filter(u=>u.role==="function").map(u=>{let d=a?.find(m=>m.name===u.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:u.result??""}]}}),c={name:"/chat"},p={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:s,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[c,p]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},_t=class extends pe{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...Vs(),...t},s=new Br(o),a=r?.map(l=>{let c=l,p=c?.config;if(!p)return l;let u={};p.maxTokens!==void 0&&(u.maxTokens=p.maxTokens),p.temperature!==void 0&&(u.temperature=p.temperature),p.topP!==void 0&&(u.topP=p.topP),p.topK!==void 0&&(u.topK=p.topK),p.presencePenalty!==void 0&&(u.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(u.frequencyPenalty=p.frequencyPenalty),p.stopSequences!==void 0&&(u.stopSequences=p.stopSequences),p.endSequences!==void 0&&(u.endSequences=p.endSequences),p.stream!==void 0&&(u.stream=p.stream),p.n!==void 0&&(u.n=p.n);let d={...c};return Object.keys(u).length>0&&(d.modelConfig={...c.modelConfig??{},...u}),d});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ur,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Ba(i){return i.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=Ws(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=Ws(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function Ws(i){return i?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var vn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(vn||{});var qr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Js=()=>structuredClone({model:"deepseek-chat",...Q()}),qa=()=>structuredClone({model:"deepseek-coder",...de()}),Nt=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...Js(),...t};o=[...qr,...o??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var On=(m=>(m.Gemini25Pro="gemini-2.5-pro",m.Gemini25Flash="gemini-2.5-flash",m.Gemini25FlashLite="gemini-2.5-flash-lite",m.Gemini20Flash="gemini-2.0-flash",m.Gemini20FlashLite="gemini-2.0-flash-lite",m.Gemini1Pro="gemini-1.0-pro",m.Gemini15Flash="gemini-1.5-flash",m.Gemini15Flash002="gemini-1.5-flash-002",m.Gemini15Flash8B="gemini-1.5-flash-8b",m.Gemini15Pro="gemini-1.5-pro",m.GeminiFlashLatest="gemini-flash-latest",m.GeminiFlashLiteLatest="gemini-flash-lite-latest",m.GeminiProLatest="gemini-pro-latest",m))(On||{}),zr=(r=>(r.GeminiEmbedding="gemini-embedding-exp",r.TextEmbeddingLarge="text-embedding-large-exp-03-07",r.TextEmbedding004="text-embedding-004",r.TextEmbedding005="text-embedding-005",r))(zr||{}),jr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(jr||{}),Hr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Hr||{}),Qs=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(Qs||{});var Kr=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var Wr=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.maximum,delete e.oneOf,delete e.anyOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Wr(n)]))),e.items&&(e.items=Wr(e.items)),e},Ys=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],Xs=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Ys,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Q()}),za=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Ys,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...de()}),Vr=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let f=r?"&":"?",h=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${f}key=${h}`}let s=e.chatPrompt.filter(f=>f.role==="system").map(f=>f.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(f=>f.role!=="system").map((f,h)=>{switch(f.role){case"user":return{role:"user",parts:Array.isArray(f.content)?f.content.map((A,y)=>{switch(A.type){case"text":return{text:A.text};case"image":return{inlineData:{mimeType:A.mimeType,data:A.image}};case"audio":return{inlineData:{mimeType:`audio/${A.format??"mp3"}`,data:A.data}};case"file":return"fileUri"in A?{fileData:{mimeType:A.mimeType,fileUri:A.fileUri}}:{inlineData:{mimeType:A.mimeType,data:A.data}};default:throw new Error(`Chat prompt content type not supported (index: ${y})`)}}):[{text:f.content}]};case"assistant":{let x=[];if(f.functionCalls){if(x=f.functionCalls.map(A=>{let y=typeof A.function.params=="string"?JSON.parse(A.function.params):A.function.params;return{functionCall:{name:A.function.name,args:y}}}),!x)throw new Error("Function call is empty");return{role:"model",parts:x}}if(!f.content)throw new Error("Assistant content is empty");return x=[{text:f.content}],{role:"model",parts:x}}case"function":{if(!("functionId"in f))throw new Error(`Chat prompt functionId is empty (index: ${h})`);return{role:"user",parts:[{functionResponse:{name:f.functionId,response:{result:f.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(f)} (index: ${h})`)}}),c=[];if(e.functions&&e.functions.length>0){let f=e.functions.map(h=>({...h,parameters:h.parameters?Wr(h.parameters):void 0}));c.push({function_declarations:f})}this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let p;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let f=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...f}}else c&&c.length>0&&(p={function_calling_config:{mode:"AUTO"}});let u={};if(this.config.thinking?.includeThoughts&&(u.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(u.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let f=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":u.thinkingBudget=0,u.includeThoughts=!1;break;case"minimal":u.thinkingBudget=f?.minimal??200;break;case"low":u.thinkingBudget=f?.low??800;break;case"medium":u.thinkingBudget=f?.medium??5e3;break;case"high":u.thinkingBudget=f?.high??1e4;break;case"highest":u.thinkingBudget=f?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(u.includeThoughts=t.showThoughts);let d={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(u).length>0?{thinkingConfig:u}:{}},m=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:d,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t=e.candidates?.map(n=>{let r={index:0};switch(n.finishReason){case"MAX_TOKENS":r.finishReason="length";break;case"STOP":r.finishReason="stop";break;case"SAFETY":throw new ae("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new ae("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new ae("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new ae("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new ae("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new ae("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new ae("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new ae("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new ae("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return r;for(let s of n.content.parts){if("text"in s){"thought"in s&&s.thought?r.thought=s.text:r.content=s.text;continue}"functionCall"in s&&(r.functionCalls=[{id:ge(),type:"function",function:{name:s.functionCall.name,params:s.functionCall.args}}])}let o=n.citationMetadata?.citations;if(Array.isArray(o)&&o.length){let s=a=>a?`${a.year}-${String(a.month).padStart(2,"0")}-${String(a.day).padStart(2,"0")}`:void 0;r.citations=o.filter(a=>typeof a?.uri=="string").map(a=>({url:a.uri,title:a.title,license:a.license,publicationDate:s(a.publicationDate)}))}return r});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Dt=class i extends pe{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,p,u;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;r?h="endpoints":h="publishers/google",p=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,u=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");p="https://generativelanguage.googleapis.com/v1beta",u=async()=>({})}let d={...Xs(),...o},m=new Vr(d,c,r,e,s);l=[...Kr,...l??[]];let g=h=>{let x=ve({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let x=h,A=x?.config;if(!A)return h;let y={};A.maxTokens!==void 0&&(y.maxTokens=A.maxTokens),A.temperature!==void 0&&(y.temperature=A.temperature),A.topP!==void 0&&(y.topP=A.topP),A.topK!==void 0&&(y.topK=A.topK),A.presencePenalty!==void 0&&(y.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(y.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(y.stopSequences=A.stopSequences),A.endSequences!==void 0&&(y.endSequences=A.endSequences),A.stream!==void 0&&(y.stream=A.stream),A.n!==void 0&&(y.n=A.n);let I={...x};Object.keys(y).length>0&&(I.modelConfig={...x.modelConfig??{},...y});let T=A.thinking?.thinkingTokenBudget;if(typeof T=="number"){let b=d.thinkingTokenBudgetLevels,w=[["minimal",b?.minimal??200],["low",b?.low??800],["medium",b?.medium??5e3],["high",b?.high??1e4],["highest",b?.highest??24500]],v="minimal",F=Number.POSITIVE_INFINITY;for(let[K,E]of w){let R=Math.abs(T-E);R<F&&(F=R,v=K)}I.thinkingTokenBudget=v}return A.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!A.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:p,headers:u,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:f??a})}};var ja=new Ae,$t=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(ja.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var Mn=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(Mn||{});var Jr=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var Ha=()=>structuredClone({model:"llama-3.3-70b-versatile",...Q()}),Lt=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...Ha(),...t},a={...n,streamingUsage:!1};o=[...Jr,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new $t(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var Qr=[];var Yr=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Yr||{});var Zs=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Q()}),Ka=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...de()}),Xr=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
144
+ `;break}default:r=JSON.stringify(n,null,2)}i(r)}};var B={LLM_SYSTEM:"gen_ai.system",LLM_OPERATION_NAME:"gen_ai.operation.name",LLM_REQUEST_MODEL:"gen_ai.request.model",LLM_REQUEST_MAX_TOKENS:"gen_ai.request.max_tokens",LLM_REQUEST_TEMPERATURE:"gen_ai.request.temperature",LLM_REQUEST_TOP_K:"gen_ai.request.top_k",LLM_REQUEST_FREQUENCY_PENALTY:"gen_ai.request.frequency_penalty",LLM_REQUEST_PRESENCE_PENALTY:"gen_ai.request.presence_penalty",LLM_REQUEST_STOP_SEQUENCES:"gen_ai.request.stop_sequences",LLM_REQUEST_LLM_IS_STREAMING:"gen_ai.request.llm_is_streaming",LLM_REQUEST_TOP_P:"gen_ai.request.top_p",LLM_USAGE_INPUT_TOKENS:"gen_ai.usage.input_tokens",LLM_USAGE_OUTPUT_TOKENS:"gen_ai.usage.output_tokens",LLM_USAGE_TOTAL_TOKENS:"gen_ai.usage.total_tokens",LLM_USAGE_THOUGHTS_TOKENS:"gen_ai.usage.thoughts_tokens",DB_SYSTEM:"db.system",DB_TABLE:"db.table",DB_NAMESPACE:"db.namespace",DB_ID:"db.id",DB_QUERY_TEXT:"db.query.text",DB_VECTOR:"db.vector",DB_OPERATION_NAME:"db.operation.name",DB_VECTOR_QUERY_TOP_K:"db.vector.query.top_k",DB_QUERY_EMBEDDINGS:"db.query.embeddings",DB_QUERY_RESULT:"db.query.result",DB_QUERY_EMBEDDINGS_VECTOR:"db.query.embeddings.vector",DB_QUERY_RESULT_ID:"db.query.result.id",DB_QUERY_RESULT_SCORE:"db.query.result.score",DB_QUERY_RESULT_DISTANCE:"db.query.result.distance",DB_QUERY_RESULT_METADATA:"db.query.result.metadata",DB_QUERY_RESULT_VECTOR:"db.query.result.vector",DB_QUERY_RESULT_DOCUMENT:"db.query.result.document"},ze={GEN_AI_USER_MESSAGE:"gen_ai.user.message",GEN_AI_SYSTEM_MESSAGE:"gen_ai.system.message",GEN_AI_ASSISTANT_MESSAGE:"gen_ai.assistant.message",GEN_AI_TOOL_MESSAGE:"gen_ai.tool.message",GEN_AI_CHOICE:"gen_ai.choice",GEN_AI_USAGE:"gen_ai.usage"},xs=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(xs||{}),ys=(o=>(o.WORKFLOW="workflow",o.TASK="task",o.AGENT="agent",o.TOOL="tool",o.UNKNOWN="unknown",o))(ys||{});var Sr=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},bn=class extends TransformStream{constructor(e,t){super(new Sr(e,t))}};function In(i,e){for(let t of e){let n=i.find(r=>r.id===t.id);n?(typeof t.function.name=="string"&&t.function.name.length>0&&(n.function.name+=t.function.name),typeof t.function.params=="string"&&t.function.params.length>0&&(n.function.params+=t.function.params),typeof t.function.params=="object"&&(n.function.params=t.function.params)):i.push(t)}}var bs=(i,e,t,n)=>{let r=n?i.filter(s=>s.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var Is=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)},Ts=(i,e,t)=>{t({name:"ChatResponseStreamingResult",index:e,value:i})};function Cs(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let o=t.get(r.index);o?(r.content&&(o.content=(o.content??"")+r.content),r.thought&&(o.thought=(o.thought??"")+r.thought),r.finishReason&&(o.finishReason=r.finishReason),r.functionCalls&&(o.functionCalls?In(o.functionCalls,structuredClone(r.functionCalls)):o.functionCalls=structuredClone(r.functionCalls))):(o=structuredClone(r),t.set(r.index,o))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var Rs=(i,e)=>{e({name:"FunctionResults",value:i})},vr=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},ws=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},Ss=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},vs=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var Os=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},ks=(i,e)=>{let t=i.slice(0,3).map(r=>({length:r.length,sample:r.slice(0,5),truncated:r.length>5})),n={name:"EmbedResponse",totalEmbeddings:i.length,value:t};e(n)},Ms=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var Or=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n);e[t]=r.length>100?r.substring(0,100):r}return e},Tn,Es=i=>{if(Tn)return Tn;if(i)return Tn=Fa(i),Tn};var Fa=i=>({latencyHistogram:i.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:i.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:i.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:i.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:i.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:i.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:i.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:i.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:i.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:i.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:i.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:i.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:i.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:i.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:i.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:i.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:i.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:i.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:i.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:i.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:i.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:i.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:i.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:i.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),Ps=(i,e,t,n,r)=>{try{if(i.latencyHistogram){let o=Or({operation:e,ai_service:n,...r?{model:r}:{}});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},Fs=(i,e,t,n,r,o,s)=>{let a={operation:e,ai_service:o,...s?{model:s}:{}};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,a),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,a),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,a)},_s=(i,e,t,n)=>{try{if(i.errorCounter){let r=Or({operation:e,ai_service:t,...n?{model:n}:{}});i.errorCounter.add(1,r)}}catch(r){console.warn("Failed to record error metric:",r)}},Ns=(i,e,t,n,r)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{}})},Ds=(i,e,t,n)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ot=(i,e,t,n,r)=>{try{let o=Or({ai_service:n,...r?{model:r}:{}});i.tokenCounter&&i.tokenCounter.add(t,{token_type:e,...o}),e==="input"&&i.inputTokenCounter&&i.inputTokenCounter.add(t,o),e==="output"&&i.outputTokenCounter&&i.outputTokenCounter.add(t,o)}catch(o){console.warn("Failed to record token metric:",o)}},$s=(i,e,t,n,r)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{}})},Gs=(i,e,t,n,r)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{}};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},kr=(i,e,t,n,r)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Mr=(i,e,t,n,r)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Ls=(i,e,t,n,r)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{}};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},Er=(i,e,t,n,r)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{}})},Us=(i,e,t,n)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Bs=(i,e,t,n)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},qs=(i,e,t,n)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},zs=(i,e,t,n)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},js=(i,e,t,n)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Hs=(i,e,t,n,r)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{}})};function Ks(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function $e(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Ks(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Ks(e.item)}`),new Error(t.join(`
145
+ `))}function kt(i){let e=n=>JSON.stringify(n,null,2);if(!i)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(i)}`);let t=typeof i=="object"&&i!==null&&"role"in i&&typeof i.role=="string"?i.role:void 0;if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=typeof i=="object"&&i!==null&&"content"in i&&typeof i.content=="string"?i.content:void 0;if(!n||n.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n)}`);break}case"user":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0;if(n===void 0)throw new Error(`User message content cannot be undefined, received: ${e(n)}`);if(typeof n=="string"){if(n.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n)}`)}else if(Array.isArray(n)){if(n.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n)}`);for(let r=0;r<n.length;r++){let o=n[r];if(!o||typeof o!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(o)}`);let s=typeof o=="object"&&o!==null&&"type"in o&&typeof o.type=="string"?o.type:void 0;if(!s)throw new Error(`User message content item at index ${r} must have a type, received: ${e(s)}`);switch(s){case"text":{let a="text"in o&&typeof o.text=="string"?o.text:void 0;if(!a||a.trim()==="")throw new Error(`User message text content at index ${r} cannot be empty or whitespace-only, received: ${e(a)}`);break}case"image":{let a="image"in o&&typeof o.image=="string"?o.image:void 0,l="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:void 0;if(!a||a.trim()==="")throw new Error(`User message image content at index ${r} cannot be empty, received: ${e(a)}`);if(!l||l.trim()==="")throw new Error(`User message image content at index ${r} must have a mimeType, received: ${e(l)}`);break}case"audio":{let a="data"in o&&typeof o.data=="string"?o.data:void 0;if(!a||a.trim()==="")throw new Error(`User message audio content at index ${r} cannot be empty, received: ${e(a)}`);break}case"file":{let a="fileUri"in o&&typeof o.fileUri=="string",l="data"in o&&typeof o.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(o)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(o)}`);if(a){let p=o.fileUri;if(!p||p.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(p)}`)}if(l){let p=o.data;if(!p||p.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(p)}`)}let c="mimeType"in o&&typeof o.mimeType=="string"?o.mimeType:null;if(!c||c.trim()==="")throw new Error(`User message file content at index ${r} must have a mimeType, received: ${e(c)}`);break}case"url":{let a="url"in o&&typeof o.url=="string"?o.url:void 0;if(!a||a.trim()==="")throw new Error(`User message url content at index ${r} cannot be empty, received: ${e(a)}`);break}default:throw new Error(`User message content item at index ${r} has unsupported type: ${e(s)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n)}`);break}case"assistant":{let n=typeof i=="object"&&i!==null&&"content"in i?i.content:void 0,r=typeof i=="object"&&i!==null&&"functionCalls"in i?i.functionCalls:void 0,o=typeof n=="string"&&n.trim()!=="",s=Array.isArray(r)&&r.length>0;if(!o&&!s&&$e("Assistant message must include non-empty content or at least one function call",{fieldPath:"content | functionCalls",value:{content:n,functionCalls:r},item:i}),n!==void 0&&typeof n!="string"&&$e("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&$e("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let a=0;a<r.length;a++){let l=r[a];if((!l||typeof l!="object")&&$e("functionCalls entry must be an object",{fieldPath:`functionCalls[${a}]`,value:l,item:i}),(!("id"in l)||typeof l.id!="string"||l.id.trim()==="")&&$e("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${a}].id`,value:l.id,item:i}),(!("type"in l)||l.type!=="function")&&$e("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${a}].type`,value:l.type,item:i}),!("function"in l)||!l.function)$e("functionCalls entry must include a function object",{fieldPath:`functionCalls[${a}].function`,value:l.function,item:i});else{let c=l.function;(!("name"in c)||typeof c.name!="string"||c.name.trim()==="")&&$e("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${a}].function.name`,value:c?.name,item:i}),c.params!==void 0&&typeof c.params!="string"&&typeof c.params!="object"&&$e("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${a}].function.params`,value:c.params,item:i})}}if(i.name!==void 0){let a=i.name;(typeof a!="string"||a.trim()==="")&&$e("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:a,item:i})}break}case"function":{let n=typeof i=="object"&&i!==null&&"functionId"in i&&typeof i.functionId=="string"?i.functionId:void 0,r=typeof i=="object"&&i!==null&&"result"in i?i.result:void 0;if(!n||n.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n)}`);if(r==null)throw new Error(`Function message must have a result, received: ${e(r)}`);if(typeof r!="string")throw new Error(`Function message result must be a string, received: ${e(r)}`);i.isError!==void 0&&typeof i.isError!="boolean"&&$e("Function message isError must be a boolean when provided",{fieldPath:"isError",value:i.isError,item:i});break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function Pr(i){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(i)?i:[i];if(t.length===0)throw new Error(`Chat response results cannot be empty, received: ${e(t)}`);for(let n=0;n<t.length;n++){let r=t[n];if(!r)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(r)}`);if(typeof r.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(r.index)}`);if(r.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(r.index)}`);if(!r.content&&!r.thought&&!r.thoughtBlock&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,functionCalls:r.functionCalls,finishReason:r.finishReason})}`);if(r.content!==void 0&&typeof r.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(r.content)}`);if(r.thought!==void 0&&typeof r.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(r.thought)}`);if(r.thoughtBlock!==void 0){if(typeof r.thoughtBlock!="object"||r.thoughtBlock===null)throw new Error(`Chat response result thoughtBlock at index ${n} must be an object, received: ${e(r.thoughtBlock)}`);let o=r.thoughtBlock;if(typeof o.data!="string")throw new Error(`Chat response result thoughtBlock.data at index ${n} must be a string, received: ${e(o.data)}`);if(typeof o.encrypted!="boolean")throw new Error(`Chat response result thoughtBlock.encrypted at index ${n} must be a boolean, received: ${e(o.encrypted)}`);if(o.signature!==void 0&&typeof o.signature!="string")throw new Error(`Chat response result thoughtBlock.signature at index ${n} must be a string when provided, received: ${e(o.signature)}`)}if(r.name!==void 0){if(typeof r.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(r.name)}`);if(r.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(r.name)}`)}if(r.annotations!==void 0){if(!Array.isArray(r.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(r.annotations)}`);for(let o=0;o<r.annotations.length;o++){let s=r.annotations[o];if(!s||typeof s!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must be an object, received: ${e(s)}`);if(s.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${o}] must have type 'url_citation', received: ${e(s.type)}`);if(!s.url_citation||typeof s.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${o}] must have a valid url_citation object, received: ${e(s.url_citation)}`);if(typeof s.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${o}] url_citation.url must be a string, received: ${e(s.url_citation.url)}`)}}if(r.id!==void 0){if(typeof r.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(r.id)}`);if(r.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(r.id)}`)}if(r.functionCalls!==void 0){if(!Array.isArray(r.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(r.functionCalls)}`);for(let o=0;o<r.functionCalls.length;o++){let s=r.functionCalls[o];if(!s)throw new Error(`Function call at index ${o} in result ${n} cannot be null or undefined, received: ${e(s)}`);if(!s.id||typeof s.id!="string"||s.id.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty string id, received: ${e(s.id)}`);if(s.type!=="function")throw new Error(`Function call at index ${o} in result ${n} must have type 'function', received: ${e(s.type)}`);if(!s.function)throw new Error(`Function call at index ${o} in result ${n} must have a function object, received: ${e(s.function)}`);if(!s.function.name||typeof s.function.name!="string"||s.function.name.trim()==="")throw new Error(`Function call at index ${o} in result ${n} must have a non-empty function name, received: ${e(s.function.name)}`);if(s.function.params!==void 0&&typeof s.function.params!="string"&&typeof s.function.params!="object")throw new Error(`Function call params at index ${o} in result ${n} must be a string or object, received: ${e(s.function.params)}`)}}if(r.finishReason!==void 0){let o=["stop","length","function_call","content_filter","error"];if(!o.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${o.join(", ")}, received: ${e(r.finishReason)}`)}}}var Q=()=>structuredClone({temperature:0}),me=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),de=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:o,defaults:s,options:a={},supportFor:l,models:c}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=r,this.supportFor=l,this.tracer=a.tracer??ie.tracer,this.meter=a.meter??ie.meter,this.modelInfo=o,this.models=c,this.id=he();let p=this.getModel(s.model)??s.model,u=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:p,embedModel:u},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),c&&Na(c)}#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=ie.logger??As;corsProxy;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getMetricsInstruments(){return Es(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.#e}setOptions(e){this.#e=e.debug??ie.debug??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??ie.tracer,this.meter=e.meter??ie.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??ie.logger??this.logger,this.corsProxy=e.corsProxy}getOptions(){return{debug:this.#e,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger,corsProxy:this.corsProxy}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((o,s)=>o-s),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((o,s)=>o+s,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ps(r,e,t,this.name,o),Fs(r,e,n.mean,n.p95,n.p99,this.name,o)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let r=this.getMetricsInstruments();if(r){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ds(r,e,this.name,o),t&&_s(r,e,this.name,o),Ns(r,e,n.rate,this.name,o)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&e?.tokens){let{promptTokens:n,completionTokens:r,totalTokens:o,thoughtsTokens:s}=e.tokens;n&&Ot(t,"input",n,this.name,e.model),r&&Ot(t,"output",r,this.name,e.model),o&&Ot(t,"total",o,this.name,e.model),s&&Ot(t,"thoughts",s,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let r of e.chatPrompt)if(r.role==="user"&&Array.isArray(r.content))for(let o of r.content)o.type==="image"?t=!0:o.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculatePromptLength(e){let t=0;if(e.chatPrompt&&Array.isArray(e.chatPrompt))for(let n of e.chatPrompt)if(n.role==="system"||n.role==="assistant")n.content&&(t+=n.content.length);else if(n.role==="user"){if(typeof n.content=="string")t+=n.content.length;else if(Array.isArray(n.content))for(let r of n.content)r.type==="text"&&(t+=r.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=this.modelInfo.find(r=>r.name===e);return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:r=0,completionTokens:o=0}=t.tokens,s=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*s/1e6+o*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let r of e)r&&typeof r=="object"&&"function"in r&&r.function&&typeof r.function=="object"&&"name"in r.function&&Gs(n,r.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;qs(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;zs(t,e,this.name,n)}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let o=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=s?.stream??!1;$s(r,"chat",a,this.name,o);let{hasImages:l,hasAudio:c}=this.detectMultimodalContent(e);Hs(r,l,c,this.name,o);let p=this.calculatePromptLength(e);Us(r,p,this.name,o),Ls(r,s?.temperature,s?.maxTokens,this.name,o),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&js(r,this.modelUsage.tokens.thoughtsTokens,this.name,o);let u=this.calculateRequestSize(e);if(kr(r,"chat",u,this.name,o),n&&!a){let d=n,m=this.calculateResponseSize(d);if(Mr(r,"chat",m,this.name,o),d.results)for(let h of d.results)h.functionCalls&&this.recordFunctionCallMetrics(h.functionCalls,this.lastUsedChatModel);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,d.modelUsage);g>0&&Bs(r,g,this.name,o);let f=this.estimateCost(this.lastUsedChatModel,d.modelUsage);f>0&&Er(r,"chat",f,this.name,o)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let r=this.lastUsedEmbedModel,o=this.calculateRequestSize(e);kr(n,"embed",o,this.name,r);let s=this.calculateResponseSize(t);Mr(n,"embed",s,this.name,r);let a=this.estimateCostByName(r,t.modelUsage);a>0&&Er(n,"embed",a,this.name,r)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,l={...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return o=await this._chat1(e,l),o}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat")),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c),this.updateErrorMetrics("chat",r),r||this.recordChatMetrics(e,l,o)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let c of e.chatPrompt)kt(c);let r=this.getModelByKey(e.model),o={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},s=this.modelInfo.find(c=>c.name===n);if(s?.notSupported?.temperature&&"temperature"in o&&delete o.temperature,s?.notSupported?.topP&&"topP"in o&&delete o.topP,t?.thinkingTokenBudget&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(t?.showThoughts&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(this.modelInfo.find(c=>c.name===n)?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=(t?.stream!==void 0?t.stream:o.stream)??!0,this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Vs.SERVER,attributes:{[B.LLM_SYSTEM]:this.name,[B.LLM_OPERATION_NAME]:"chat",[B.LLM_REQUEST_MODEL]:n,[B.LLM_REQUEST_MAX_TOKENS]:o.maxTokens??"Not set",[B.LLM_REQUEST_TEMPERATURE]:o.temperature,[B.LLM_REQUEST_TOP_P]:o.topP??"Not set",[B.LLM_REQUEST_TOP_K]:o.topK??"Not set",[B.LLM_REQUEST_FREQUENCY_PENALTY]:o.frequencyPenalty??"Not set",[B.LLM_REQUEST_PRESENCE_PENALTY]:o.presencePenalty??"Not set",[B.LLM_REQUEST_STOP_SEQUENCES]:o.stopSequences?.join(", ")??"Not set",[B.LLM_REQUEST_LLM_IS_STREAMING]:o.stream??"Not set"}},t?.traceContext??Ws.active(),async c=>await this._chat2(n,o,e,t,c)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,r,o){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=r?.debug??this.#e,a;n.functions&&n.functions.length>0&&(a=n.functions.map(x=>this.cleanupFunctionSchema(x)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&bs(l.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let c=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",d=p==="prompt"||p==="auto"&&!c?{...l,chatPrompt:l.chatPrompt.map(x=>{if(x.role==="assistant"){let{content:A,name:y,cache:I}=x;return{role:"assistant",content:A,name:y,cache:I}}return x.role==="function"?{role:"user",content:x.result}:x}),functions:[]}:l,m=async()=>{let[x,A]=await this.aiImpl.createChatReq(d,r);return o?.isRecording()&&_a(n,o,this.excludeContentFromTrace),await Ce({name:x.name,url:this.apiURL,localCall:x.localCall,headers:await this.buildHeaders(x.headers),stream:t.stream,timeout:this.timeout,debug:s,fetch:this.fetch,span:o,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},A)},g=r?.rateLimiter??this.rt,f=g?await g(m,{modelUsage:this.modelUsage}):await m();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let x=this.aiImpl.createChatStreamResp.bind(this),A=C=>b=>{let v=x(b,C);if(v.sessionId=r?.sessionId,!v.modelUsage){let P=this.aiImpl.getTokenUsage();P&&(v.modelUsage={ai:this.name,model:e,tokens:P})}if(this.modelUsage=v.modelUsage,this.recordTokenUsage(v.modelUsage),o?.isRecording()&&Js(v,o,this.excludeContentFromTrace),s)for(let P of v.results)Ts(P,P.index,r?.logger??this.logger);return v},y=async C=>{o?.isRecording()&&o.end(),s&&Cs(C,r?.logger??this.logger)};if(typeof window<"u"){let C=f,b={},v=[],P=r?.abortSignal??this.abortSignal;return new ReadableStream({start:K=>{let O=C.getReader(),w=()=>{try{O.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat")}catch{}try{o?.isRecording()&&o.end()}catch{}try{K.error(new DOMException("Aborted","AbortError"))}catch{K.error(new Error("Aborted"))}};if(P){if(P.aborted){w();return}P.addEventListener("abort",w,{once:!0})}async function _(){try{for(;;){let{done:R,value:S}=await O.read();if(R){y&&await y(v),K.close();break}let N=A(b)(S);N&&(v.push(N),K.enqueue(N))}}catch(R){if(K.error(R),o?.isRecording())try{o.end()}catch{}}finally{if(O.releaseLock(),P)try{P.removeEventListener("abort",w)}catch{}}}_()}})}return f.pipeThrough(new bn(A({}),y))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let h=this.aiImpl.createChatResp(f);if(h.sessionId=r?.sessionId,!h.modelUsage){let x=this.aiImpl.getTokenUsage();x&&(h.modelUsage={ai:this.name,model:e,tokens:x})}return h.modelUsage&&(this.modelUsage=h.modelUsage,this.recordTokenUsage(h.modelUsage)),o?.isRecording()&&(Js(h,o,this.excludeContentFromTrace),o.end()),s&&Is(h,r?.logger??this.logger),h}async embed(e,t){let n=performance.now(),r=!1,o,s=this.getModelByKey(e.embedModel),a={...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel}:void 0,...t};try{return o=await this._embed1(e,a),o}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed")),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l),this.updateErrorMetrics("embed",r),!r&&o&&this.recordEmbedMetrics(e,o)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");return this.tracer?await this.tracer.startActiveSpan("AI Embed Request",{kind:Vs.SERVER,attributes:{[B.LLM_SYSTEM]:this.name,[B.LLM_OPERATION_NAME]:"embeddings",[B.LLM_REQUEST_MODEL]:n}},t?.traceContext??Ws.active(),async r=>await this._embed2(n,e,t,r)):await this._embed2(n,e,t)}async _embed2(e,t,n,r){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let o=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=n?.debug??this.#e,a={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&Os(a.texts??[],e,n?.logger??this.logger);let l=async()=>{let[d,m]=await o(a);return await Ce({name:d.name,url:this.apiURL,localCall:d.localCall,headers:await this.buildHeaders(d.headers),debug:s,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy},m)},c=n?.rateLimiter??this.rt,p=c?await c(l,{modelUsage:this.embedModelUsage}):await l(),u=this.aiImpl.createEmbedResp?.(p);if(u.sessionId=n?.sessionId,!u.modelUsage){let d=this.aiImpl.getTokenUsage();d&&(u.modelUsage={ai:this.name,model:e,tokens:d})}return this.embedModelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage),r?.isRecording()&&u.modelUsage?.tokens&&r.addEvent(ze.GEN_AI_USAGE,{[B.LLM_USAGE_INPUT_TOKENS]:u.modelUsage.tokens.promptTokens,[B.LLM_USAGE_OUTPUT_TOKENS]:u.modelUsage.tokens.completionTokens??0,[B.LLM_USAGE_TOTAL_TOKENS]:u.modelUsage.tokens.totalTokens}),s&&ks(u.embeddings,n?.logger??this.logger),r?.end(),u}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}};function _a(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let o of i.chatPrompt)switch(o.role){case"system":if(o.content){let s={};t||(s.content=o.content),e.addEvent(ze.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof o.content=="string")n.push(o.content);else if(Array.isArray(o.content))for(let s of o.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&o.content&&(a.content=o.content),e.addEvent(ze.GEN_AI_ASSISTANT_MESSAGE,a)}else if(o.content){let a={};t||(a.content=o.content),e.addEvent(ze.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:o.functionId};t||(s.content=o.result),e.addEvent(ze.GEN_AI_TOOL_MESSAGE,s);break}}let r={};t||(r.content=n.join(`
146
+ `)),e.addEvent(ze.GEN_AI_USER_MESSAGE,r)}function Js(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[B.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(ze.GEN_AI_USAGE,{[B.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[B.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[B.LLM_USAGE_TOTAL_TOKENS]:i.modelUsage.tokens.totalTokens,...n})}if(i.results)for(let n=0;n<i.results.length;n++){let r=i.results[n];if(!r||!r.content&&!r.thought&&!r.functionCalls?.length&&!r.finishReason)continue;let o=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};o&&o.length>0?(t||(s.content=r.content),s.tool_calls=o):t||(s.content=r.content??""),e.addEvent(ze.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Qs(i){let e=0;for(let t of i){if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if(t.role!=="user"&&t.role!=="assistant")throw new Error(`AxMessage array validation failed: Item at index ${e} has invalid role: ${t.role}`);e++}}function Na(i){let e=new Set;for(let t of i){if(e.has(t.key))throw new Error(`Duplicate model key detected: "${t.key}". Each model key must be unique.`);e.add(t.key)}}var Cn=(u=>(u.Claude41Opus="claude-opus-4-1-20250805",u.Claude4Opus="claude-opus-4-20250514",u.Claude4Sonnet="claude-sonnet-4-20250514",u.Claude37Sonnet="claude-3-7-sonnet-latest",u.Claude35Sonnet="claude-3-5-sonnet-latest",u.Claude35Haiku="claude-3-5-haiku-latest",u.Claude3Opus="claude-3-opus-latest",u.Claude3Sonnet="claude-3-sonnet-20240229",u.Claude3Haiku="claude-3-haiku-20240307",u.Claude21="claude-2.1",u.ClaudeInstant12="claude-instant-1.2",u))(Cn||{}),Fr=(s=>(s.Claude37Sonnet="claude-3-7-sonnet",s.Claude35Haiku="claude-3-5-haiku",s.Claude35Sonnet="claude-3-5-sonnet",s.Claude35SonnetV2="claude-3-5-sonnet-v2",s.Claude3Haiku="claude-3-haiku",s.Claude3Opus="claude-3-opus",s))(Fr||{});var Rn=[{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var wn=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.oneOf,delete e.anyOf,delete e.allOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,wn(n)]))),e.items&&(e.items=wn(e.items)),e},Xs=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...Q()}),Da=()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...Q()}),_r=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,r=e.modelConfig?.stream??this.config.stream,o;this.isVertex?o={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:o={name:"/messages"};let s;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":s={tool_choice:{type:"auto"}};break;case"required":s={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)s={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(b=>b.role==="system").map(b=>({type:"text",text:b.content,...b.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(b=>b.role!=="system"),c=e.functions?.map(b=>({name:b.name,description:b.description,input_schema:b.parameters?wn(b.parameters):void 0})),u=(this.config.tools??[]).map(b=>b&&typeof b=="object"&&"type"in b?b:{name:b.name,description:b.description,input_schema:b.input_schema?wn(b.input_schema):void 0,...b.cache_control?{cache_control:b.cache_control}:{}}),d=[...c??[],...u];this.isVertex&&d.length>0&&(d=d.filter(b=>!(b&&typeof b=="object"&&"type"in b))),d.length===0&&(d=void 0);let m=e.modelConfig?.maxTokens??this.config.maxTokens,g=e.modelConfig?.stopSequences??this.config.stopSequences,f=e.modelConfig?.temperature,h=e.modelConfig?.topP,x=e.modelConfig?.topK??this.config.topK,A=e.modelConfig?.n??this.config.n;if(A&&A>1)throw new Error("Anthropic does not support sampling (n > 1)");let y;if(this.config.thinking?.budget_tokens&&(y=this.config.thinking),t?.thinkingTokenBudget){let b=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":y=void 0;break;case"minimal":y={type:"enabled",budget_tokens:b?.minimal??1024};break;case"low":y={type:"enabled",budget_tokens:b?.low??5e3};break;case"medium":y={type:"enabled",budget_tokens:b?.medium??1e4};break;case"high":y={type:"enabled",budget_tokens:b?.high??2e4};break;case"highest":y={type:"enabled",budget_tokens:b?.highest??32e3};break}}if(!y&&t?.thinkingTokenBudget===void 0){let b=this.config.thinkingTokenBudgetLevels}let I=$a(l,!!y);I.some(b=>b.role==="assistant"&&Array.isArray(b.content)&&b.content.length>0&&b.content[0]?.type==="tool_use")&&(y=void 0);let C={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...m?{max_tokens:m}:{},...g&&g.length>0?{stop_sequences:g}:{},...f!==void 0&&!y?{temperature:f}:{},...h!==void 0&&(!y||h>=.95)?{top_p:h}:{},...x&&!y?{top_k:x}:{},...s,...d?{tools:d}:{},...r?{stream:!0}:{},...a?{system:a}:{},...y?{thinking:y}:{},messages:I};return[o,C]};createChatResp=e=>{if(e.type==="error")throw new le(e.error.message,void 0,void 0);let t=Ys(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",o="",s=!1,a,l=[],c=[];for(let d of e.content)switch(d.type){case"text":if(r+=d.text??"",Array.isArray(d.citations))for(let m of d.citations)m?.url&&c.push({url:String(m.url),title:typeof m.title=="string"?m.title:void 0,snippet:typeof m.cited_text=="string"?m.cited_text:void 0});break;case"thinking":case"redacted_thinking":n&&(o+=d.thinking??d.data??""),d.type==="redacted_thinking"&&(s=!0),typeof d.signature=="string"&&(a=d.signature);break;case"tool_use":l.push({id:d.id,type:"function",function:{name:d.name,params:d.input}});break}let p={index:0,id:e.id,finishReason:t};r&&(p.content=r),o&&(p.thought=o,p.thoughtBlock={data:o,encrypted:s,...a?{signature:a}:{}}),l.length>0&&(p.functionCalls=l),c.length>0&&(p.citations=c);let u=[p];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:u,remoteId:e.id}};createChatStreamResp=(e,t)=>{if(!("type"in e))throw new Error("Invalid Anthropic streaming event");let n=t;if(n.indexIdMap||(n.indexIdMap={}),e.type==="error"){let{error:o}=e;throw new le(o.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:o}=e,s=[{index:r,content:"",id:o.id}];return this.tokensUsed={promptTokens:o.usage?.input_tokens??0,completionTokens:o.usage?.output_tokens??0,totalTokens:(o.usage?.input_tokens??0)+(o.usage?.output_tokens??0)},{results:s}}if(e.type==="content_block_start"){let{content_block:o}=e;if(o.type==="text"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="tool_use"&&typeof o.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=o.id;let s=[{id:o.id,type:"function",function:{name:o.name,params:""}}];return{results:[{index:r,functionCalls:s}]}}if(o.type==="web_search_tool_result"||o.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:o}=e;if(o.type==="citations_delta"){let s=o.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(o.type==="text_delta"){let s=[];if(Array.isArray(o.citations))for(let a of o.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:r,content:o.text,...s.length?{citations:s}:{}}]}}if(o.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:o.thinking,thoughtBlock:{data:o.thinking,encrypted:!1}}]}:{results:[{index:r,content:""}]};if(o.type==="signature_delta")return{results:[{index:r,content:""}]};if(o.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:r,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:o.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:o,usage:s}=e;return this.tokensUsed={promptTokens:0,completionTokens:s.output_tokens,totalTokens:s.output_tokens},{results:[{index:r,content:"",finishReason:Ys(o.stop_reason)}]}}return{results:[{index:r,content:""}]}}},Mt=class i extends de{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:o,models:s}){let a=t!==void 0&&n!==void 0,l,c;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",c=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let p={...Xs(),...r},u=new _r(p,a),d=g=>{let f=Me({model:g,modelInfo:Rn,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:f?.supported?.thinkingBudget??!1,hasShowThoughts:f?.supported?.showThoughts??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"]},thinking:f?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let f=g,h=f?.config;if(!h)return g;let x={};h.maxTokens!==void 0&&(x.maxTokens=h.maxTokens),h.temperature!==void 0&&(x.temperature=h.temperature),h.topP!==void 0&&(x.topP=h.topP),h.topK!==void 0&&(x.topK=h.topK),h.presencePenalty!==void 0&&(x.presencePenalty=h.presencePenalty),h.frequencyPenalty!==void 0&&(x.frequencyPenalty=h.frequencyPenalty),h.stopSequences!==void 0&&(x.stopSequences=h.stopSequences),h.endSequences!==void 0&&(x.endSequences=h.endSequences),h.stream!==void 0&&(x.stream=h.stream),h.n!==void 0&&(x.n=h.n);let A={...f};Object.keys(x).length>0&&(A.modelConfig={...f.modelConfig??{},...x});let y=h.thinking?.thinkingTokenBudget;if(typeof y=="number"){let I=p.thinkingTokenBudgetLevels,T=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],C="minimal",b=Number.POSITIVE_INFINITY;for(let[v,P]of T){let K=Math.abs(y-P);K<b&&(b=K,C=v)}A.thinkingTokenBudget=C}return h.thinking?.includeThoughts!==void 0&&(A.showThoughts=!!h.thinking.includeThoughts),A});super(u,{name:"Anthropic",apiURL:l,headers:c,modelInfo:Rn,defaults:{model:p.model},options:o,supportFor:d,models:m??s})}};function $a(i,e){let t=i.map(r=>{switch(r.role){case"function":return{role:"user",content:[{type:"tool_result",content:r.result,tool_use_id:r.functionId,...r.isError?{is_error:!0}:{},...r.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof r.content=="string"?{role:"user",content:r.content}:{role:"user",content:r.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let o="",s=[],a=r.thoughtBlock;return a&&typeof a.data=="string"&&a.data.length>0&&(a.encrypted?s.push(a.signature?{type:"redacted_thinking",data:a.data,signature:a.signature}:{type:"redacted_thinking",data:a.data}):s.push(a.signature?{type:"thinking",thinking:a.data,signature:a.signature}:{type:"thinking",thinking:a.data})),typeof r.content=="string"&&(s.length>0?o=[...s,{type:"text",text:r.content}]:o=r.content),typeof r.functionCalls<"u"&&(o=r.functionCalls.map(l=>{let c={};return typeof l.function.params=="string"?c=JSON.parse(l.function.params):typeof l.function.params=="object"&&(c=l.function.params),{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache:{type:"ephemeral"}}:{}}}),Array.isArray(o)&&s.length>0&&(o=[...s,...o])),{role:"assistant",content:o}}default:throw new Error("Invalid role")}}),n=Ga(t);return La(n)}function Ga(i){let e=[];for(let[t,n]of i.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&i.at(t-1)?.role==="assistant"){let r=e.pop();e.push({...r||{},...n})}else e.push(n)}return e}function La(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Ys(i){if(i)switch(i){case"stop_sequence":return"stop";case"max_tokens":return"length";case"tool_use":return"function_call";case"end_turn":return"stop";default:return"stop"}}var Sn=(T=>(T.GPT4="gpt-4",T.GPT41="gpt-4.1",T.GPT41Mini="gpt-4.1-mini",T.GPT4O="gpt-4o",T.GPT4OMini="gpt-4o-mini",T.GPT4ChatGPT4O="chatgpt-4o-latest",T.GPT4Turbo="gpt-4-turbo",T.GPT35Turbo="gpt-3.5-turbo",T.GPT35TurboInstruct="gpt-3.5-turbo-instruct",T.GPT35TextDavinci002="text-davinci-002",T.GPT3TextBabbage002="text-babbage-002",T.GPT3TextAda001="text-ada-001",T.GPT5="gpt-5",T.GPT5Nano="gpt-5-nano",T.GPT5Mini="gpt-5-mini",T.GPT5Chat="gpt-5-chat",T.O1="o1",T.O1Mini="o1-mini",T.O3="o3",T.O3Mini="o3-mini",T.O4Mini="o4-mini",T))(Sn||{}),Et=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Et||{});var Pt=(b=>(b.GPT4="gpt-4",b.GPT41="gpt-4.1",b.GPT41Mini="gpt-4.1-mini",b.GPT4O="gpt-4o",b.GPT4OMini="gpt-4o-mini",b.GPT4ChatGPT4O="chatgpt-4o-latest",b.GPT4Turbo="gpt-4-turbo",b.GPT35Turbo="gpt-3.5-turbo",b.GPT35TurboInstruct="gpt-3.5-turbo-instruct",b.GPT35TextDavinci002="text-davinci-002",b.GPT3TextBabbage002="text-babbage-002",b.GPT3TextAda001="text-ada-001",b.GPT5="gpt-5",b.GPT5Nano="gpt-5-nano",b.GPT5Mini="gpt-5-mini",b.GPT5Chat="gpt-5-chat",b.O1Pro="o1-pro",b.O1="o1",b.O1Mini="o1-mini",b.O3Pro="o3-pro",b.O3="o3",b.O3Mini="o3-mini",b.O4Mini="o4-mini",b))(Pt||{});var Ft=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Nr=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0}}];var Ua=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},At=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Q()}),$r=()=>structuredClone({...At(),model:"gpt-5"}),Gr=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...me()}),Lr=()=>({...At(),model:"gpt-5-nano"}),Dr=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r={name:"/chat/completions"},o=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),s=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Ba(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,p=this.config.store,u=Ua(n),d={model:n,messages:a,...this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...o?{tools:o}:{},...s?{tool_choice:s}:{},...u?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...l!==void 0?{frequency_penalty:l}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...c&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...p?{store:p}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(d.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(d.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d.reasoning_effort=void 0;break;case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":d.reasoning_effort="high";break;case"high":d.reasoning_effort="high";break;case"highest":d.reasoning_effort="high";break}if(!d.reasoning_effort&&t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"minimal":d.reasoning_effort="minimal";break;case"low":d.reasoning_effort="medium";break;case"medium":case"high":case"highest":d.reasoning_effort="high";break}return this.chatReqUpdater&&(d=this.chatReqUpdater(d)),[r,d]};createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]};createChatResp(e){let{id:t,usage:n,choices:r,error:o}=e;if(o)throw o;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:r.map(a=>{if(a.message.refusal)throw new le(a.message.refusal,e.model,e.id);let l=Zs(a.finish_reason),c=a.message.tool_calls?.map(({id:p,function:{arguments:u,name:d}})=>({id:p,type:"function",function:{name:d,params:u}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(p=>p?.type==="url_citation"&&p.url_citation).map(p=>({url:p.url_citation?.url,title:p.url_citation?.title,description:p.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:o}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let s=t;return s.indexIdMap||(s.indexIdMap={}),{results:o.map(({index:l,delta:{content:c,role:p,refusal:u,tool_calls:d,reasoning_content:m,annotations:g},finish_reason:f})=>{if(u)throw new le(u,void 0,n);let h=Zs(f),x=d?.map(({id:A,index:y,function:{name:I,arguments:T}})=>{typeof A=="string"&&typeof y=="number"&&!s.indexIdMap[y]&&(s.indexIdMap[y]=A);let C=s.indexIdMap[y];return C?{id:C,type:"function",function:{name:I,params:T}}:null}).filter(A=>A!==null);return{index:l,content:c??void 0,role:p,thought:m,citations:g?.filter(A=>A?.type==="url_citation"&&A.url_citation).map(A=>({url:A.url_citation?.url,title:A.url_citation?.title,description:A.url_citation?.description})),functionCalls:x,finishReason:h,id:n}})}}createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{embeddings:t.map(r=>r.embedding)}}},Zs=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Ba(i){return i.chatPrompt.map(t=>{switch(t.role){case"system":return{role:"system",content:t.content};case"user":{let n=Array.isArray(t.content)?t.content.map(r=>{switch(r.type){case"text":return{type:"text",text:r.text};case"image":return{type:"image_url",image_url:{url:`data:${r.mimeType};base64,${r.image}`,details:r.details??"auto"}};case"audio":return{type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=t.functionCalls?.map(r=>({id:r.id,type:"function",function:{name:r.function.name,arguments:typeof r.function.params=="object"?JSON.stringify(r.function.params):r.function.params}}));if(n&&n.length>0)return{role:"assistant",...t.content?{content:t.content}:{},name:t.name,tool_calls:n};if(t.content===void 0)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",content:t.content,...t.name?{name:t.name}:{}}}case"function":return{role:"tool",content:t.result,tool_call_id:t.functionId};default:throw new Error("Invalid role")}})}var ue=class extends de{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o,models:s,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new Dr(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:s})}},_t=class extends ue{constructor({apiKey:e,apiURL:t,config:n,options:r,models:o,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...Ft,...s??[]];let a=c=>{let p=Me({model:c,modelInfo:s,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","ogg"],maxDuration:25*60},files:{supported:!0,formats:["text/plain","application/pdf","image/jpeg","image/png"],maxSize:512*1024*1024,uploadMethod:"upload"},urls:{supported:!1,webSearch:!0,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:p?.supported?.thinkingBudget??!1,multiTurn:!0}},l=o?.map(c=>{let p=c,u=p?.config;if(!u)return c;let d={};u.maxTokens!==void 0&&(d.maxTokens=u.maxTokens),u.temperature!==void 0&&(d.temperature=u.temperature),u.topP!==void 0&&(d.topP=u.topP),u.presencePenalty!==void 0&&(d.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(d.frequencyPenalty=u.frequencyPenalty);let m=u.stopSequences??u.stop;m!==void 0&&(d.stopSequences=m),u.n!==void 0&&(d.n=u.n),u.stream!==void 0&&(d.stream=u.stream);let g={...p};Object.keys(d).length>0&&(g.modelConfig={...p.modelConfig??{},...d});let f=u?.thinking?.thinkingTokenBudget;if(typeof f=="number"){let h=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],x="minimal",A=Number.POSITIVE_INFINITY;for(let[y,I]of h){let T=Math.abs(f-I);T<A&&(A=T,x=y)}g.thinkingTokenBudget=x}return u?.thinking?.includeThoughts!==void 0&&(g.showThoughts=!!u.thinking.includeThoughts),g});super({apiKey:e,apiURL:t,config:{...At(),...n},options:r,modelInfo:s,models:l??o,supportFor:a}),super.setName("OpenAI")}};var ei=At,qa=Gr,za=Lr,ja=$r,Nt=class extends ue{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:o,options:s,models:a,modelInfo:l}){if(!e||e==="")throw new Error("Azure OpenAPI API key not set");if(!t||t==="")throw new Error("Azure OpenAPI resource name not set");if(!n||n==="")throw new Error("Azure OpenAPI deployment id not set");let c={...ei(),...o};l=[...Ft,...l??[]];let p=d=>{let m=Me({model:d,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:m?.supported?.thinkingBudget??!1,hasShowThoughts:m?.supported?.showThoughts??!1,functionCot:!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:m?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:s,models:a,modelInfo:l,supportFor:p});let u=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${r}`,u).href),super.setHeaders(async()=>({"api-key":e}))}};var Ur=class i{services;currentServiceIndex=0;currentService;debug;initialBackoffMs;maxBackoffMs;maxRetries;serviceFailures=new Map;constructor(e,t){if(e.length===0)throw new Error("No AI services provided.");Ha(e),this.services=[...e].sort(t?.comparator??i.metricComparator);let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=t?.debug??!0,this.initialBackoffMs=t?.initialBackoffMs??1e3,this.maxBackoffMs=t?.maxBackoffMs??32e3,this.maxRetries=t?.maxRetries??3}static create(e,t){return new i(e,t)}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static inputOrderComparator=()=>0;static metricComparator=(e,t)=>{let n=e.getMetrics(),r=t.getMetrics();return n.latency.chat.mean-r.latency.chat.mean};getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,r=Date.now()-n,o=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return r>=o}handleFailure(e){let n=(this.serviceFailures.get(this.currentService.getId())?.retries??0)+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:n,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${n}/${this.maxRetries})`,e),n>=this.maxRetries){let r=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`,e),r}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te))throw n;switch(n.constructor){case at:throw n;case ht:break;case Je:break;case nt:break;case Be:break;case ft:break;default:throw n}if(!this.handleFailure(n))throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof Te)||!this.handleFailure(n))throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function Ha(i){let e=i.find(r=>r.getModelList()!==void 0);if(!e)return;let t=e.getModelList();if(!t)throw new Error("No model list found in any service.");let n=new Set(t.map(r=>r.key));for(let r=0;r<i.length;r++){let o=i[r];if(!o)throw new Error(`Service at index ${r} is undefined`);let s=o.getModelList();if(!s)throw new Error(`Service at index ${r} (${o.getName()}) has no model list while another service does.`);let a=new Set(s.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${o.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${o.getName()}) has extra model "${l}"`)}}function xt(i){let e=!1,t=!1,n=!1,r=!1,o=!1,s=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let p of i.chatPrompt){if(p.role==="user"&&Array.isArray(p.content))for(let u of p.content)switch(l.add(u.type),u.type){case"image":e=!0,u.cache&&(a=!0),c+=85;break;case"audio":t=!0,u.cache&&(a=!0),c+=u.duration||60;break;case"file":n=!0,u.cache&&(a=!0),c+=Math.ceil((u.extractedText?.length||1e3)/4);break;case"url":r=!0,u.cache&&(a=!0),c+=Math.ceil((u.cachedContent?.length||2e3)/4);break;case"text":u.cache&&(a=!0),c+=Math.ceil(u.text.length/4);break}else"content"in p&&typeof p.content=="string"&&(c+=Math.ceil(p.content.length/4));"cache"in p&&p.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(o=!0),i.modelConfig?.stream===!0&&(s=!0),i.capabilities&&(i.capabilities.requiresImages&&(e=!0),i.capabilities.requiresAudio&&(t=!0),i.capabilities.requiresFiles&&(n=!0),i.capabilities.requiresWebSearch&&(r=!0)),{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r,requiresFunctions:o,requiresStreaming:s,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function ti(i,e){let t=i.getFeatures(),n=[],r=[],o=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),o.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),o.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),o.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),o.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),o.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),o.push("Repeated content will not be cached")),e.hasImages&&t.media.images.supported){let a=t.media.images.maxSize;a&&a<10*1024*1024&&r.push(`Image size limit is ${Math.round(a/(1024*1024))}MB`)}if(e.hasAudio&&t.media.audio.supported){let a=t.media.audio.maxDuration;a&&a<600&&r.push(`Audio duration limit is ${Math.round(a/60)} minutes`)}return{isSupported:n.length===0,missingCapabilities:n,warnings:r,alternatives:o}}function Br(i,e){return i.map(t=>{let n=t.getFeatures(),r=ti(t,e),o=0,s=[];return o+=10,e.hasImages&&n.media.images.supported&&(o+=25,s.push("Images"),n.media.images.detailLevels?.includes("high")&&(o+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(o+=3)),e.hasAudio&&n.media.audio.supported&&(o+=25,s.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(o+=5)),e.hasFiles&&n.media.files.supported&&(o+=25,s.push("Files"),n.media.files.uploadMethod==="cloud"&&(o+=3)),e.hasUrls&&n.media.urls.supported&&(o+=25,s.push("URLs"),n.media.urls.webSearch&&(o+=5)),e.requiresFunctions&&n.functions&&(o+=15,s.push("Functions"),n.functionCot&&(o+=3)),e.requiresStreaming&&n.streaming&&(o+=10,s.push("Streaming")),e.requiresCaching&&n.caching.supported&&(o+=8,s.push("Caching"),n.caching.types.includes("persistent")&&(o+=3)),n.thinking&&(o+=2),n.multiTurn&&(o+=2),n.hasThinkingBudget&&(o+=1),n.hasShowThoughts&&(o+=1),o-=r.missingCapabilities.length*10,{provider:t,score:o,missingCapabilities:r.missingCapabilities,supportedCapabilities:s}}).sort((t,n)=>n.score-t.score)}function qr(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=xt(i),r=Br(e,n);if(t.requireExactMatch){let o=r.filter(s=>s.missingCapabilities.length===0);if(o.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return o[0].provider}if(!t.allowDegradation){let o=r[0];if(o.missingCapabilities.length>0)throw new Error(`Best available provider (${o.provider.getName()}) is missing: ${o.missingCapabilities.join(", ")}`)}return r[0].provider}function Ka(i,e){let t=xt(i),n=Br(e,t),r=n[0]?.provider||null,o=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,s=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${s}/${o} requirements (${Math.round(s/Math.max(o,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Wa(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Va(i,e){let t={};for(let n of i){let o=n.getFeatures().media[e];if(o.supported)for(let s of o.formats)t[s]||(t[s]=[]),t[s].push(n)}return t}var vn=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(vn||{}),On=(r=>(r.EmbedEnglishV30="embed-english-v3.0",r.EmbedEnglishLightV30="embed-english-light-v3.0",r.EmbedMultiLingualV30="embed-multilingual-v3.0",r.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",r))(On||{});var zr=[{name:"command-r-plus",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"command-r",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"command-light",currency:"usd",promptTokenCostPer1M:.3,completionTokenCostPer1M:.6},{name:"embed-english-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-english-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"embed-multilingual-light-v3.0",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1}];var ri=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...Q()}),Ja=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...me()}),jr=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,frequencyPenalty:e.frequencyPenalty,presencePenalty:e.presencePenalty,endSequences:e.endSequences,stopSequences:e.stopSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),o;n&&n.role==="user"&&typeof n.content=="string"&&(o=n?.content);let s=Qa(r),a=e.functions?.map(u=>{let d={};if(u.parameters?.properties)for(let[m,g]of Object.entries(u.parameters.properties))d[m]={description:g.description,type:g.type,required:u.parameters.required?.includes(m)??!1};return{name:u.name,description:u.description,parameter_definitions:d}}),l=e.chatPrompt.filter(u=>u.role==="function").map(u=>{let d=a?.find(m=>m.name===u.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:u.result??""}]}}),c={name:"/chat"},p={message:o,model:t,tools:a,...l&&!o?{tool_results:l}:{},chat_history:s,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},k:e.modelConfig?.topK??this.config.topK,...e.modelConfig?.topP!==void 0?{p:e.modelConfig.topP}:{},frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,end_sequences:this.config.endSequences,stop_sequences:e.modelConfig?.stopSequences??this.config.stopSequences};return[c,p]}createEmbedReq=e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embed"},r={model:t,texts:e.texts??[],input_type:"classification",truncate:""};return[n,r]};createChatResp=e=>{this.tokensUsed=e.meta.billed_units?{promptTokens:e.meta.billed_units.input_tokens,completionTokens:e.meta.billed_units.output_tokens,totalTokens:e.meta.billed_units.input_tokens+e.meta.billed_units.output_tokens}:void 0;let t;if("finish_reason"in e)switch(e.finish_reason){case"COMPLETE":t="stop";break;case"MAX_TOKENS":t="length";break;case"ERROR":throw new Error("Finish reason: ERROR");case"ERROR_TOXIC":throw new Error("Finish reason: CONTENT_FILTER");default:t="stop";break}let n;return"tool_calls"in e&&(n=e.tool_calls?.map(o=>({id:o.name,type:"function",function:{name:o.name,params:o.parameters}}))),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}};createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:e.meta.billed_units?.output_tokens??0,totalTokens:e.meta.billed_units?.output_tokens??0};let{results:r}=this.createChatResp(e),o=r[0];if(!o)throw new Error("No result");return o.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},Dt=class extends de{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let o={...ri(),...t},s=new jr(o),a=r?.map(l=>{let c=l,p=c?.config;if(!p)return l;let u={};p.maxTokens!==void 0&&(u.maxTokens=p.maxTokens),p.temperature!==void 0&&(u.temperature=p.temperature),p.topP!==void 0&&(u.topP=p.topP),p.topK!==void 0&&(u.topK=p.topK),p.presencePenalty!==void 0&&(u.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(u.frequencyPenalty=p.frequencyPenalty),p.stopSequences!==void 0&&(u.stopSequences=p.stopSequences),p.endSequences!==void 0&&(u.endSequences=p.endSequences),p.stream!==void 0&&(u.stream=p.stream),p.n!==void 0&&(u.n=p.n);let d={...c};return Object.keys(u).length>0&&(d.modelConfig={...c.modelConfig??{},...u}),d});super(s,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:zr,defaults:{model:o.model},supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[],maxSize:0,detailLevels:[]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},options:n,models:a??r})}};function Qa(i){return i.map(e=>{let t="";if(e.role==="system"||e.role==="assistant"||e.role==="user")if(typeof e.content=="string")t=e.content;else throw new Error("Multi-modal content not supported");switch(e.role){case"user":return{role:"USER",message:t};case"system":return{role:"SYSTEM",message:t};case"assistant":{let n=ni(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(s=>{if(s.role==="assistant")return s.functionCalls?.find(a=>a.id===e.functionId)}).filter(s=>s!==void 0),r=ni(n)?.at(0);if(!r)throw new Error("Function call not found");let o=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:o}]}}default:throw new Error("Unknown role")}})}function ni(i){return i?.map(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})}var kn=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(kn||{});var Hr=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var oi=()=>structuredClone({model:"deepseek-chat",...Q()}),Ya=()=>structuredClone({model:"deepseek-coder",...me()}),$t=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("DeepSeek API key not set");let s={...oi(),...t};o=[...Hr,...o??[]],super({apiKey:e,config:s,options:n,apiURL:"https://api.deepseek.com",modelInfo:o,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r}),super.setName("DeepSeek")}};var Mn=(m=>(m.Gemini25Pro="gemini-2.5-pro",m.Gemini25Flash="gemini-2.5-flash",m.Gemini25FlashLite="gemini-2.5-flash-lite",m.Gemini20Flash="gemini-2.0-flash",m.Gemini20FlashLite="gemini-2.0-flash-lite",m.Gemini1Pro="gemini-1.0-pro",m.Gemini15Flash="gemini-1.5-flash",m.Gemini15Flash002="gemini-1.5-flash-002",m.Gemini15Flash8B="gemini-1.5-flash-8b",m.Gemini15Pro="gemini-1.5-pro",m.GeminiFlashLatest="gemini-flash-latest",m.GeminiFlashLiteLatest="gemini-flash-lite-latest",m.GeminiProLatest="gemini-pro-latest",m))(Mn||{}),Kr=(r=>(r.GeminiEmbedding="gemini-embedding-exp",r.TextEmbeddingLarge="text-embedding-large-exp-03-07",r.TextEmbedding004="text-embedding-004",r.TextEmbedding005="text-embedding-005",r))(Kr||{}),Wr=(r=>(r.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",r.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",r.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",r.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",r))(Wr||{}),Vr=(o=>(o.BlockNone="BLOCK_NONE",o.BlockOnlyHigh="BLOCK_ONLY_HIGH",o.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",o.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",o.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",o))(Vr||{}),si=(l=>(l.SemanticSimilarity="SEMANTIC_SIMILARITY",l.Classification="CLASSIFICATION",l.Clustering="CLUSTERING",l.RetrievalDocument="RETRIEVAL_DOCUMENT",l.RetrievalQuery="RETRIEVAL_QUERY",l.QuestionAnswering="QUESTION_ANSWERING",l.FactVerification="FACT_VERIFICATION",l.CodeRetrievalQuery="CODE_RETRIEVAL_QUERY",l))(si||{});var Jr=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0}}];var Qr=i=>{if(!i||typeof i!="object")return i;let e={...i};return delete e.additionalProperties,delete e.default,delete e.optional,delete e.maximum,delete e.oneOf,delete e.anyOf,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,Qr(n)]))),e.items&&(e.items=Qr(e.items)),e},ii=[{category:"HARM_CATEGORY_HARASSMENT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_HATE_SPEECH",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_SEXUALLY_EXPLICIT",threshold:"BLOCK_NONE"},{category:"HARM_CATEGORY_DANGEROUS_CONTENT",threshold:"BLOCK_NONE"}],ai=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:ii,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...Q()}),Xa=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:ii,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...me()}),Yr=class{constructor(e,t,n,r,o){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=o;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq=async(e,t)=>{let n=e.model,r=e.modelConfig?.stream??this.config.stream;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o;if(this.endpointId?o={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:o={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let f=r?"&":"?",h=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;o.name+=`${f}key=${h}`}let s=e.chatPrompt.filter(f=>f.role==="system").map(f=>f.content),a=s.length>0?{role:"user",parts:[{text:s.join(" ")}]}:void 0,l=e.chatPrompt.filter(f=>f.role!=="system").map((f,h)=>{switch(f.role){case"user":return{role:"user",parts:Array.isArray(f.content)?f.content.map((A,y)=>{switch(A.type){case"text":return{text:A.text};case"image":return{inlineData:{mimeType:A.mimeType,data:A.image}};case"audio":return{inlineData:{mimeType:`audio/${A.format??"mp3"}`,data:A.data}};case"file":return"fileUri"in A?{fileData:{mimeType:A.mimeType,fileUri:A.fileUri}}:{inlineData:{mimeType:A.mimeType,data:A.data}};default:throw new Error(`Chat prompt content type not supported (index: ${y})`)}}):[{text:f.content}]};case"assistant":{let x=[];if(f.functionCalls){if(x=f.functionCalls.map(A=>{let y=typeof A.function.params=="string"?JSON.parse(A.function.params):A.function.params;return{functionCall:{name:A.function.name,args:y}}}),!x)throw new Error("Function call is empty");return{role:"model",parts:x}}if(!f.content)throw new Error("Assistant content is empty");return x=[{text:f.content}],{role:"model",parts:x}}case"function":{if(!("functionId"in f))throw new Error(`Chat prompt functionId is empty (index: ${h})`);return{role:"user",parts:[{functionResponse:{name:f.functionId,response:{result:f.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(f)} (index: ${h})`)}}),c=[];if(e.functions&&e.functions.length>0){let f=e.functions.map(h=>({...h,parameters:h.parameters?Qr(h.parameters):void 0}));c.push({function_declarations:f})}this.options?.codeExecution&&c.push({code_execution:{}}),this.options?.googleSearchRetrieval&&c.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&c.push({google_search:{}}),this.options?.urlContext&&c.push({url_context:{}}),c.length===0&&(c=void 0);let p;if(e.functionCall)if(e.functionCall==="none")p={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")p={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")p={function_calling_config:{mode:"ANY"}};else{let f=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...f}}else c&&c.length>0&&(p={function_calling_config:{mode:"AUTO"}});let u={};if(this.config.thinking?.includeThoughts&&(u.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(u.thinkingBudget=this.config.thinking.thinkingTokenBudget),t?.thinkingTokenBudget){let f=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":u.thinkingBudget=0,u.includeThoughts=!1;break;case"minimal":u.thinkingBudget=f?.minimal??200;break;case"low":u.thinkingBudget=f?.low??800;break;case"medium":u.thinkingBudget=f?.medium??5e3;break;case"high":u.thinkingBudget=f?.high??1e4;break;case"highest":u.thinkingBudget=f?.highest??24500;break}}t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(u.includeThoughts=t.showThoughts);let d={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{topP:e.modelConfig.topP}:{},topK:e.modelConfig?.topK??this.config.topK,frequencyPenalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,candidateCount:1,stopSequences:e.modelConfig?.stopSequences??this.config.stopSequences,responseMimeType:"text/plain",...Object.keys(u).length>0?{thinkingConfig:u}:{}},m=this.config.safetySettings;return[o,{contents:l,tools:c,toolConfig:p,systemInstruction:a,generationConfig:d,safetySettings:m}]};createEmbedReq=async e=>{let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n,r;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},r={instances:e.texts.map(o=>({content:o,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let o=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${o}`},r={requests:e.texts.map(s=>({model:`models/${t}`,content:{parts:[{text:s}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t=e.candidates?.map(n=>{let r={index:0};switch(n.finishReason){case"MAX_TOKENS":r.finishReason="length";break;case"STOP":r.finishReason="stop";break;case"SAFETY":throw new le("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new le("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new le("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new le("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new le("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new le("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new le("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new le("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new le("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return r;for(let s of n.content.parts){if("text"in s){"thought"in s&&s.thought?r.thought=s.text:r.content=s.text;continue}"functionCall"in s&&(r.functionCalls=[{id:he(),type:"function",function:{name:s.functionCall.name,params:s.functionCall.args}}])}let o=n.citationMetadata?.citations;if(Array.isArray(o)&&o.length){let s=a=>a?`${a.year}-${String(a.month).padStart(2,"0")}-${String(a.day).padStart(2,"0")}`:void 0;r.citations=o.filter(a=>typeof a?.uri=="string").map(a=>({url:a.uri,title:a.title,license:a.license,publicationDate:s(a.publicationDate)}))}return r});return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}};createChatStreamResp=e=>this.createChatResp(e);createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}},Gt=class i extends de{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:o,options:s,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,p,u;if(c){if(!e)throw new Error("GoogleGemini Vertex API key not set");if(typeof e!="function")throw new Error("GoogleGemini Vertex API key must be a function for token-based authentication");let h;r?h="endpoints":h="publishers/google",p=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${h}`,u=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");p="https://generativelanguage.googleapis.com/v1beta",u=async()=>({})}let d={...ai(),...o},m=new Yr(d,c,r,e,s);l=[...Jr,...l??[]];let g=h=>{let x=Me({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:x?.supported?.thinkingBudget??!1,hasShowThoughts:x?.supported?.showThoughts??!1,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:20*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!0,formats:["wav","mp3","aac","ogg"],maxDuration:9.5*60},files:{supported:!0,formats:["application/pdf","text/plain","text/csv","text/html","text/xml"],maxSize:2*1024*1024*1024,uploadMethod:"cloud"},urls:{supported:!0,webSearch:!0,contextFetching:!0}},caching:{supported:!1,types:[]},thinking:x?.supported?.thinkingBudget??!1,multiTurn:!0}},f=a?.map(h=>{let x=h,A=x?.config;if(!A)return h;let y={};A.maxTokens!==void 0&&(y.maxTokens=A.maxTokens),A.temperature!==void 0&&(y.temperature=A.temperature),A.topP!==void 0&&(y.topP=A.topP),A.topK!==void 0&&(y.topK=A.topK),A.presencePenalty!==void 0&&(y.presencePenalty=A.presencePenalty),A.frequencyPenalty!==void 0&&(y.frequencyPenalty=A.frequencyPenalty),A.stopSequences!==void 0&&(y.stopSequences=A.stopSequences),A.endSequences!==void 0&&(y.endSequences=A.endSequences),A.stream!==void 0&&(y.stream=A.stream),A.n!==void 0&&(y.n=A.n);let I={...x};Object.keys(y).length>0&&(I.modelConfig={...x.modelConfig??{},...y});let T=A.thinking?.thinkingTokenBudget;if(typeof T=="number"){let C=d.thinkingTokenBudgetLevels,b=[["minimal",C?.minimal??200],["low",C?.low??800],["medium",C?.medium??5e3],["high",C?.high??1e4],["highest",C?.highest??24500]],v="minimal",P=Number.POSITIVE_INFINITY;for(let[K,O]of b){let w=Math.abs(T-O);w<P&&(P=w,v=K)}I.thinkingTokenBudget=v}return A.thinking?.includeThoughts!==void 0&&(I.showThoughts=!!A.thinking.includeThoughts),I});super(m,{name:"GoogleGeminiAI",apiURL:p,headers:u,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:s,supportFor:g,models:f??a})}};var Za=new be,Lt=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(Za.red(`Rate limiter: Waiting for ${e-this.currentTokens} tokens`)),await new Promise(t=>setTimeout(t,100)),this.waitUntilTokensAvailable(e)}async acquire(e){await this.waitUntilTokensAvailable(e)}};var En=(r=>(r.Llama3_8B="llama3-8b-8192",r.Llama33_70B="llama-3.3-70b-versatile",r.Mixtral_8x7B="mixtral-8x7b-32768",r.Gemma2_9B="gemma2-9b-it",r))(En||{});var Xr=[{name:"gemma2-9b-it",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.2,completionTokenCostPer1M:.2},{name:"llama-3.3-70b-versatile",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.59,completionTokenCostPer1M:.79},{name:"llama3-8b-8192",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.05,completionTokenCostPer1M:.08},{name:"mixtral-8x7b-32768",currency:"usd",characterIsToken:!0,promptTokenCostPer1M:.24,completionTokenCostPer1M:.24}];var el=()=>structuredClone({model:"llama-3.3-70b-versatile",...Q()}),Ut=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Groq API key not set");let s={...el(),...t},a={...n,streamingUsage:!1};o=[...Xr,...o??[]];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:a,modelInfo:o,apiURL:"https://api.groq.com/openai/v1",models:r,supportFor:l}),super.setName("Groq"),this.setOptions(a)}setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})};newRateLimiter=e=>{if(e?.rateLimiter)return e.rateLimiter;let t=e?.tokensPerMinute??4800,n=new Lt(t,t/60,{debug:e?.debug});return async(o,s)=>{let a=s.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await o()}}};var Zr=[];var eo=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(eo||{});var li=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Q()}),tl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...me()}),to=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,n:e.n,presencePenalty:e.presencePenalty}}createChatReq=e=>{let t=e.model,n=e.functions?`Functions:
146
147
  ${JSON.stringify(e.functions,null,2)}
147
148
  `:"",r=e.chatPrompt?.map(l=>{switch(l.role){case"user":return`User: ${l.content}`;case"system":return`System: ${l.content}`;case"function":return`Function Result: ${l.result}`;case"assistant":{let c=l.functionCalls?.map(p=>{let u=typeof p.function.params=="string"?p.function.params:JSON.stringify(p.function.params);return`${p.function.name}(${u})`}).join(`
148
149
  `);return c?`Assistant: ${l.content}
149
150
  Functions:
150
151
  ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
151
- `),o=`${n} ${r}`.trim(),s={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[s,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Gt=class extends pe{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...Zs(),...t},s=new Xr(o);super(s,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Qr,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var kn=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(kn||{}),ei=(e=>(e.MistralEmbed="mistral-embed",e))(ei||{});var Zr=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var eo=()=>structuredClone({model:"mistral-small-latest",...Q(),topP:1}),Wa=()=>structuredClone({...eo(),model:"mistral-large-latest"}),Ut=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let s={...eo(),...t};o=[...Zr,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=c=>{let{max_completion_tokens:p,messages:u,...d}=c;return{...d,messages:this.updateMessages(u),max_tokens:p}};super({apiKey:e,config:s,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var to=class{constructor(e={}){this.config=e;this.config.id=this.config.id??ge()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let s=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[s]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var no=class i{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:s,isInternal:a}=n;this.services.set(n.key,{service:o,description:s,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let s of o){if(this.services.has(s.key)){let a=this.services.get(s.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${s.key} as service ${a?.getName()}`)}if("model"in s&&typeof s.model)this.services.set(s.key,{description:s.description,service:n,model:s.model});else if("embedModel"in s&&s.embedModel)this.services.set(s.key,{description:s.description,service:n,embedModel:s.embedModel});else throw new Error(`Key ${s.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new i(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...s}=e;return await r.service.chat(s,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...s}=e;return await r.service.embed(s,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var ti=()=>structuredClone({...Q(),model:"nous-hermes2",embedModel:"all-minilm"}),Va=()=>structuredClone({...de(),model:"nous-hermes2",embedModel:"all-minilm"}),Bt=class extends ce{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let s={...ti(),...n};super({apiKey:e,options:r,config:s,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var Ja=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),qt=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let s=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:s,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let s={type:"message",role:"assistant",content:""};if(r.content&&(s.content=o),r.name&&(s.name=r.name),r.content&&n.push(s),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let s=r.role;throw new Error(`Invalid role in chat prompt: ${s}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,s=!1;if(e.chatPrompt){for(let x of e.chatPrompt)if(x.role==="system"&&typeof x.content=="string"){o=x.content,s=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(x=>({type:"function",name:x.name,description:x.description,parameters:x.parameters??{}})),c=[],p=Ja(n),u=this.config.reasoningSummary;t?.showThoughts?u||(u="auto"):u=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...p?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:c.length>0?c:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:u}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,s):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let f=m.reasoning??{};if(this.config.reasoningEffort&&(f={...f,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":f={};break;case"minimal":f={...f,effort:"minimal"};break;case"low":f={...f,effort:"medium"};break;case"medium":case"high":case"highest":f={...f,effort:"high"};break}Object.keys(f).length>0&&f.effort?m.reasoning=f:m.reasoning=void 0;let h=m;return this.responsesReqUpdater&&(h=this.responsesReqUpdater(h)),[r,h]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let s of n??[])switch(s.type){case"message":o.id=s.id,o.content=ro(s.content,t),o.finishReason=s.status==="completed"?"stop":"content_filter",o.citations=En(s.content);break;case"reasoning":o.id=s.id,s.encrypted_content?o.thought=s.encrypted_content:o.thought=s.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
152
- `);break;case"file_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries,results:s.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code,results:s.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name,args:s.args,serverLabel:s.server_label,output:s.output,error:s.error}}}],o.finishReason="function_call";break;case"function_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:s.name,params:s.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=ro(t.item.content,t.item.id),n.citations=En(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(s=>({fileId:s.file_id,filename:s.filename,score:s.score,text:s.text,attributes:s.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=ro([t.part],t.item_id),n.citations=En([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let o=En(t.item.content||[]);o&&(n.citations=o)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},ro=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
153
- `);throw new ae(n,void 0,e)}return i.filter(n=>n.type==="output_text").map(n=>n.text).join(`
154
- `)};function En(i){let e=[];for(let t of i??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var Fn=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Qa=()=>({...Fn(),model:"gpt-4o",temperature:.5}),Ya=()=>({...Fn(),model:"gpt-4o",temperature:.9}),Pn=class extends pe{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:s,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new qt(t,n?.streamingUsage??!0,a),p=s?.map(u=>{let d=u,m=d?.config;if(!m)return u;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let f=m.stopSequences??m.stop;f!==void 0&&(g.stopSequences=f),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let h={...d};Object.keys(g).length>0&&(h.modelConfig={...d.modelConfig??{},...g});let x=m?.thinking?.thinkingTokenBudget;if(typeof x=="number"){let A=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",I=Number.POSITIVE_INFINITY;for(let[T,b]of A){let w=Math.abs(x-b);w<I&&(I=w,y=T)}h.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!m.thinking.includeThoughts),h});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:p??s})}},zt=class extends Pn{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...Pr,...o??[]];let s=a=>{let l=ve({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...Fn(),...t},options:n,modelInfo:o,models:r,supportFor:s})}};var ni=()=>structuredClone({model:"openrouter/auto",...Q()}),jt=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:s,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...ni(),...t},c={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},p=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:p,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let u={Authorization:`Bearer ${e}`};return s&&(u["HTTP-Referer"]=s),a&&(u["X-Title"]=a),u})}};async function oo(i,e,t={}){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return[{type:"text",text:String(i)}];let n=e.getFeatures(),r=[];for(let o of i)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let s=await t.imageToText(o.image);r.push({type:"text",text:s})}catch(s){throw new Be(s,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new Fe("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let s=await t.audioToText(o.data,o.format);r.push({type:"text",text:s})}catch(s){throw new Be(s,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new Fe("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let s=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:s})}catch(s){throw new Be(s,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new Fe("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let s=await t.urlToText(o.url);r.push({type:"text",text:s})}catch(s){throw new Be(s,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new Fe("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(s){throw s instanceof Fe||s instanceof Be?s:new Be(s,o.type||"unknown","content processing")}return r}function Xa(i){let e=!1,t=!1,n=!1,r=!1;for(let o of i)if(o.role==="user"&&Array.isArray(o.content))for(let s of o.content)switch(s.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var _n=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(_n||{});var so=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var Nn=()=>structuredClone({model:"reka-core",...Q()}),Za=()=>structuredClone({...Nn(),model:"reka-core"}),el=()=>structuredClone({model:"reka-core",...de()}),tl=()=>({...Nn(),model:"reka-flash"}),io=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=nl(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,s=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...s?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=ri(s.finish_reason),c;return typeof s.message.content=="string"?c=s.message.content:c=s.message.content.text,{index:a,id:`${t}`,content:c,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=ri(s.finish_reason),c;return typeof s.chunk.content=="string"?c=s.chunk.content:c=s.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},ri=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function nl(i){return i.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var Ht=class extends pe{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=so,models:s}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Nn(),...t},l=new io(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:s})}};var ao=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof Fe&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let s of e.chatPrompt)if(s.role==="user"&&Array.isArray(s.content)){let a=await oo(s.content,t,r);a.every(c=>c.type==="text")&&a.length===1?o.push({...s,content:a[0].text}):o.push({...s,content:a.map(c=>({type:"text",text:c.text}))})}else o.push(s);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=ft(e),r=[],o=[],s=[];try{let a=Gr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&s.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&s.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:s}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},s=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(s,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=ft(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var lo=[];var oi=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...Q()}),Kt=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let s={...oi(),...t};o=[...lo,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var Dn=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(Dn||{});var co=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var si=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Q()}),rl=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...de()}),po=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(p=>p.type==="text").map(p=>p.text).join(`
155
- `));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(p=>({id:p.id,type:"function",function:{name:p.function.name,arguments:typeof p.function.params=="string"?p.function.params:JSON.stringify(p.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let c=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(p){try{for await(let u of c)p.enqueue(u);p.close()}catch(u){p.error(u)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},s={model:t,messages:n,...r?.length?{tools:r}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,s]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:s,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let c=n.toolCalls[l.index];c?l.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:s,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},Wt=class extends pe{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...si(),...t},s=new po(o,e);super(s,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:co,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var $n=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))($n||{}),ii=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(ii||{});var uo=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var mo=()=>structuredClone({model:"grok-3-mini",...Q()}),ol=()=>structuredClone({...mo(),model:"grok-3"}),Vt=class extends ce{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let s={...mo(),...t};o=[...uo,...o??[]];let a=c=>{let p=ve({model:c,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=c=>{if(n?.searchParameters){let p=n.searchParameters;return{...c,search_parameters:{mode:p.mode,return_citations:p.returnCitations,from_date:p.fromDate,to_date:p.toDate,max_search_results:p.maxSearchResults,sources:p.sources?.map(u=>({type:u.type,country:u.country,excluded_websites:u.excludedWebsites,allowed_websites:u.allowedWebsites,safe_search:u.safeSearch,x_handles:u.xHandles,links:u.links}))}}}return c};super({apiKey:e,config:s,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function sl(i){return Ln.create(i)}var Ln=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new Pt(e);break;case"openai-responses":this.ai=new zt(e);break;case"azure-openai":this.ai=new Ft(e);break;case"grok":this.ai=new Vt(e);break;case"huggingface":this.ai=new Gt(e);break;case"groq":this.ai=new Lt(e);break;case"together":this.ai=new Kt(e);break;case"openrouter":this.ai=new jt(e);break;case"cohere":this.ai=new _t(e);break;case"google-gemini":this.ai=new Dt(e);break;case"anthropic":this.ai=new Ot(e);break;case"mistral":this.ai=new Ut(e);break;case"deepseek":this.ai=new Nt(e);break;case"ollama":this.ai=new Bt(e);break;case"reka":this.ai=new Ht(e);break;case"webllm":this.ai=new Wt(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};import{SpanKind as go}from"@opentelemetry/api";var Ne=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:go.SERVER,attributes:{[U.DB_SYSTEM]:this.name,[U.DB_OPERATION_NAME]:"upsert",[U.DB_TABLE]:e.table,[U.DB_NAMESPACE]:e.namespace,[U.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:go.SERVER,attributes:{[U.DB_SYSTEM]:this.name,[U.DB_OPERATION_NAME]:"upsert",[U.DB_TABLE]:e[0].table,[U.DB_NAMESPACE]:e[0].namespace,[U.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:go.SERVER,attributes:{[U.DB_SYSTEM]:this.name,[U.DB_OPERATION_NAME]:"upsert",[U.DB_TABLE]:e.table,[U.DB_NAMESPACE]:e.namespace,[U.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var ho="https://api.cloudflare.com/client/v4/accounts/",Jt=class extends Ne{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await ye({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,ho),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await ye({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,ho),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(s=>({id:s.id,values:s.values,namespace:s.namespace,metadata:s.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:s})=>s).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await ye({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,ho),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,values:a,metadata:l}))}}};var it=class extends Ne{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let s=await this.upsert(o,t);r.push(...s.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,s])=>{if(e.values&&s.values){let a=il(e.values,s.values);r.push({id:o,score:a,metadata:s.metadata})}}),r.sort((o,s)=>o.score-s.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},il=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,s=!0,a=new Float64Array(i),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],r+=l[d]*l[d],a[d]!==0&&(o=!1),l[d]!==0&&(s=!1);if(o||s)return 1;let c=Math.sqrt(n),p=Math.sqrt(r);return 1-t/(c*p)};var al=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),Qt=class extends Ne{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await ye({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:s})=>({id:r,values:o,metadata:s}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await ye({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},al(e))).matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,metadata:l,values:a}))}}};var Yt=class extends Ne{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await ye({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(s=>({id:s.id,class:s.table,tenant:s.namespace,vector:s.values,properties:s.metadata??{}})),o=await ye({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:s})=>s?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:s})=>s?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:s})=>s)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
152
+ `),o=`${n} ${r}`.trim(),s={name:"/models"},a={model:t,inputs:o,parameters:{max_new_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,repetition_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},top_k:e.modelConfig?.topK??this.config.topK,return_full_text:this.config.returnFullText,num_return_sequences:this.config.n,do_sample:this.config.doSample,max_time:this.config.maxTime},options:{use_cache:this.config.useCache,wait_for_model:this.config.waitForModel}};return[s,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},Bt=class extends de{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let o={...li(),...t},s=new to(o);super(s,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Zr,defaults:{model:o.model},options:n,supportFor:{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:r})}};var Pn=(l=>(l.Mistral7B="open-mistral-7b",l.Mistral8x7B="open-mixtral-8x7b",l.MistralSmall="mistral-small-latest",l.MistralNemo="mistral-nemo-latest",l.MistralLarge="mistral-large-latest",l.Codestral="codestral-latest",l.OpenCodestralMamba="open-codestral-mamba",l.OpenMistralNemo="open-mistral-nemo-latest",l))(Pn||{}),ci=(e=>(e.MistralEmbed="mistral-embed",e))(ci||{});var no=[{name:"open-mistral-7b",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mixtral-8x7b",currency:"USD",promptTokenCostPer1M:.7,completionTokenCostPer1M:.7},{name:"mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.15,completionTokenCostPer1M:.15},{name:"mistral-small-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"mistral-large-latest",currency:"USD",promptTokenCostPer1M:2,completionTokenCostPer1M:6},{name:"codestral-latest",currency:"USD",promptTokenCostPer1M:.2,completionTokenCostPer1M:.6},{name:"open-codestral-mamba",currency:"USD",promptTokenCostPer1M:.25,completionTokenCostPer1M:.25},{name:"open-mistral-nemo-latest",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.3}];var ro=()=>structuredClone({model:"mistral-small-latest",...Q(),topP:1}),nl=()=>structuredClone({...ro(),model:"mistral-large-latest"}),qt=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Mistral API key not set");let s={...ro(),...t};o=[...no,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},l=c=>{let{max_completion_tokens:p,messages:u,...d}=c;return{...d,messages:this.updateMessages(u),max_tokens:p}};super({apiKey:e,config:s,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Mistral")}updateMessages(e){let t=[];if(!Array.isArray(e))return e;for(let n of e)if(n.role==="user"&&Array.isArray(n.content)){let r=n.content.map(o=>typeof o=="object"&&o!==null&&"image_url"in o?{type:"image_url",image_url:{url:o.image_url?.url}}:o);t.push({...n,content:r})}else t.push(n);return t}};var oo=class{constructor(e={}){this.config=e;this.config.id=this.config.id??he()}metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getLastUsedChatModel(){return this.config.modelInfo?.name??"mock-model"}getLastUsedEmbedModel(){return this.config.embedModelInfo?.name??"mock-embed-model"}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:this.config.features?.streaming??!1}:void 0}getName(){return this.config.name??"mock-ai-service"}getId(){return this.config.id??"mock-ai-service-id"}getFeatures(e){return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getModelList(){return this.config.models}getMetrics(){return this.metrics}async chat(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock chat error");return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):this.config.chatResponse??{results:[{index:0,content:"Mock response",finishReason:"stop"}],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:10,completionTokens:5,totalTokens:15}}}}async embed(e,t){if(this.config.latencyMs&&await new Promise(n=>setTimeout(n,this.config.latencyMs)),this.config.shouldError)throw new Error(this.config.errorMessage??"Mock embed error");return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):this.config.embedResponse??{embeddings:[[.1,.2,.3]],modelUsage:{ai:this.getName(),model:"mock-model",tokens:{promptTokens:5,completionTokens:0,totalTokens:5}}}}setOptions(e){this.config.options=e}getOptions(){return this.config.options??{}}getLogger(){return this.config.options?.logger??(e=>{console.log(e)})}updateMetrics(e){let t=this.config.latencyMs??0;this.metrics.latency[e].samples.push(t);let n=this.metrics.latency[e].samples;if(this.metrics.latency[e].mean=n.reduce((r,o)=>r+o,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),o=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[o]??t;let s=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[s]??t}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let r=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=r>0?this.metrics.errors[e].count/r:0}}};var so=class i{options;lastUsedService;services=new Map;constructor(e){if(e.length===0)throw new Error("No AI services provided.");for(let[t,n]of e.entries())if("key"in n){if(this.services.has(n.key))throw new Error(`Duplicate model key: ${n.key}`);let{service:o,description:s,isInternal:a}=n;this.services.set(n.key,{service:o,description:s,isInternal:a})}else{let o=n.getModelList();if(!o)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let s of o){if(this.services.has(s.key)){let a=this.services.get(s.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${s.key} as service ${a?.getName()}`)}if("model"in s&&typeof s.model)this.services.set(s.key,{description:s.description,service:n,model:s.model});else if("embedModel"in s&&s.embedModel)this.services.set(s.key,{description:s.description,service:n,embedModel:s.embedModel});else throw new Error(`Key ${s.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}static create(e){return new i(e)}getLastUsedChatModel(){return this.lastUsedService?.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.lastUsedService?.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.lastUsedService?.getLastUsedModelConfig()}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{model:o,...s}=e;return await r.service.chat(s,t)}return await r.service.chat({model:n,...e},t)}async embed(e,t){let n=e.embedModel;if(!n)throw new Error("Embed model key must be specified for multi-service");let r=this.services.get(n);if(!r)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=r.service,!r.model){let{embedModel:o,...s}=e;return await r.service.embed(s,t)}return await r.service.embed({embedModel:n,...e},t)}getId(){return`MultiServiceRouter:${Array.from(this.services.values()).map(e=>e.service.getId()).join(",")}`}getName(){return"MultiServiceRouter"}getModelList(){return Array.from(this.services).filter(([,e])=>!e.isInternal).map(([e,t])=>{if(t.model)return{key:e,description:t.description,model:t.model};if(t.embedModel)return{key:e,description:t.description,embedModel:t.embedModel};throw new Error(`Service ${e} has no model or embedModel`)})}getFeatures(e){if(e){let t=this.services.get(e);if(t)return t.service.getFeatures(e)}return{functions:!1,streaming:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}getMetrics(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e="service"in t?t.service:t)}if(!e)throw new Error("No service available to get metrics.");return e.getMetrics()}setOptions(e){for(let t of this.services.values())t.service.setOptions(e);this.options=e}getOptions(){return this.options??{}}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}if(!e)throw new Error("No service available to get logger.");return e.getLogger()}setServiceEntry(e,t){this.services.set(e,t)}};var pi=()=>structuredClone({...Q(),model:"nous-hermes2",embedModel:"all-minilm"}),rl=()=>structuredClone({...me(),model:"nous-hermes2",embedModel:"all-minilm"}),zt=class extends ue{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:o}){let s={...pi(),...n};super({apiKey:e,options:r,config:s,apiURL:t,models:o,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}),super.setName("Ollama")}};var ol=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),jt=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,stopSequences:e.stopSequences,topP:e.topP,stream:e.stream}}mapInternalContentToResponsesInput(e,t){let n=[];for(let r of e){if(r.type==="text"){t==="assistant"?n.push({type:"output_text",text:r.text}):n.push({type:"input_text",text:r.text});continue}if(t==="assistant")continue;if(r.type==="image"){let s=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:s,details:r.details??"auto"}});continue}if(r.type==="audio"){n.push({type:"input_audio",input_audio:{data:r.data,format:r.format==="wav"?"wav":void 0}});continue}let o=r;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let o;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?o=r.content:r.role==="assistant"?o=[{type:"output_text",text:r.content}]:o=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))o=this.mapInternalContentToResponsesInput(r.content,r.role==="assistant"?"assistant":"user");else{if(!(r.role==="assistant"&&!r.content&&r.functionCalls))throw new Error(`Invalid content type for role ${r.role}`);o=""}else r.role,o="";switch(r.role){case"system":n.push({type:"message",role:"system",content:o});break;case"user":n.push({type:"message",role:"user",content:o,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let s={type:"message",role:"assistant",content:""};if(r.content&&(s.content=o),r.name&&(s.name=r.name),r.content&&n.push(s),r.functionCalls)for(let a of r.functionCalls)n.push({type:"function_call",call_id:a.id,name:a.function.name,arguments:typeof a.function.params=="object"?JSON.stringify(a.function.params):a.function.params||""})}break;case"function":n.push({type:"function_call_output",call_id:r.functionId,output:r.result});break;default:{let s=r.role;throw new Error(`Invalid role in chat prompt: ${s}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},o=null,s=!1;if(e.chatPrompt){for(let x of e.chatPrompt)if(x.role==="system"&&typeof x.content=="string"){o=x.content,s=!0;break}}let a=o??this.config.systemPrompt??null,l=e.functions?.map(x=>({type:"function",name:x.name,description:x.description,parameters:x.parameters??{}})),c=[],p=ol(n),u=this.config.reasoningSummary;t?.showThoughts?u||(u="auto"):u=void 0;let d=this.config.reasoningEffort;if(t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":d=void 0;break;case"minimal":d="minimal";break;case"low":d="medium";break;case"medium":case"high":case"highest":d="high";break}let m={model:n,input:"",instructions:a,tools:l?.length?l:void 0,tool_choice:e.functionCall==="none"||e.functionCall==="auto"||e.functionCall==="required"?e.functionCall:typeof e.functionCall=="object"&&e.functionCall.function?{type:"function",name:e.functionCall.function.name}:void 0,...p?{max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0}:{...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty??void 0,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty??void 0,max_output_tokens:e.modelConfig?.maxTokens??this.config.maxTokens??void 0},stream:e.modelConfig?.stream??this.config.stream??!1,background:void 0,include:c.length>0?c:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...d?{reasoning:{effort:d,summary:u}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let g=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,s):[];if(g.length>0)m.input=g;else if(e.chatPrompt&&e.chatPrompt.length===1&&e.chatPrompt[0]?.role==="user"&&e.chatPrompt[0]?.content&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(g.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let f=m.reasoning??{};if(this.config.reasoningEffort&&(f={...f,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":f={};break;case"minimal":f={...f,effort:"minimal"};break;case"low":f={...f,effort:"medium"};break;case"medium":case"high":case"highest":f={...f,effort:"high"};break}Object.keys(f).length>0&&f.effort?m.reasoning=f:m.reasoning=void 0;let h=m;return this.responsesReqUpdater&&(h=this.responsesReqUpdater(h)),[r,h]}createChatResp(e){let{id:t,output:n,usage:r}=e;r&&(this.tokensUsed={promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens??r.output_tokens??0,totalTokens:r.total_tokens});let o={};for(let s of n??[])switch(s.type){case"message":o.id=s.id,o.content=io(s.content,t),o.finishReason=s.status==="completed"?"stop":"content_filter",o.citations=Fn(s.content);break;case"reasoning":o.id=s.id,s.encrypted_content?o.thought=s.encrypted_content:o.thought=s.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
153
+ `);break;case"file_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries,results:s.results}}}],o.finishReason="function_call";break;case"web_search_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries}}}],o.finishReason="function_call";break;case"computer_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action}}}],o.finishReason="function_call";break;case"code_interpreter_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code,results:s.results}}}],o.finishReason="function_call";break;case"image_generation_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}],o.finishReason="function_call";break;case"local_shell_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action}}}],o.finishReason="function_call";break;case"mcp_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:"mcp",params:{name:s.name,args:s.args,serverLabel:s.server_label,output:s.output,error:s.error}}}],o.finishReason="function_call";break;case"function_call":o.id=s.id,o.functionCalls=[{id:s.id,type:"function",function:{name:s.name,params:s.arguments}}],o.finishReason="function_call";break}return{results:[{...o,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},r;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":r=t.response.id,n.id=`${t.response.id}_res_0`;break;case"response.output_item.added":switch(t.item.type){case"message":n.id=t.item.id,n.content=io(t.item.content,t.item.id),n.citations=Fn(t.item.content);break;case"function_call":n.id=t.item.id,n.functionCalls=[{id:t.item.id,type:"function",function:{name:t.item.name,params:t.item.arguments}}];break;case"file_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries||[],results:o.results?.map(s=>({fileId:s.file_id,filename:s.filename,score:s.score,text:s.text,attributes:s.attributes}))}}}]}break;case"web_search_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries||[]}}}]}break;case"computer_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action||{}}}}]}break;case"code_interpreter_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code||"",results:o.results}}}]}break;case"image_generation_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}]}break;case"local_shell_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action||{}}}}]}break;case"mcp_call":{let o=t.item;n.id=t.item.id,n.functionCalls=[{id:o.id,type:"function",function:{name:"mcp",params:{name:o.name||"",args:o.args||"",serverLabel:o.server_label||"",output:o.output,error:o.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=io([t.part],t.item_id),n.citations=Fn([t.part]);break;case"response.output_text.delta":n.id=t.item_id,n.content=t.delta;break;case"response.output_text.done":break;case"response.function_call_arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.reasoning_summary_text.delta":n.id=t.item_id,n.thought=t.delta;break;case"response.file_search_call.in_progress":case"response.file_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.file_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.in_progress":case"response.web_search_call.searching":n.id=t.item_id,n.finishReason="function_call";break;case"response.web_search_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.in_progress":case"response.image_generation_call.generating":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.completed":n.id=t.item_id,n.finishReason="function_call";break;case"response.image_generation_call.partial_image":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.in_progress":n.id=t.item_id,n.finishReason="function_call";break;case"response.mcp_call.arguments.delta":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.delta}}];break;case"response.mcp_call.arguments.done":n.id=t.item_id,n.functionCalls=[{id:t.item_id,type:"function",function:{name:"",params:t.arguments}}];break;case"response.mcp_call.completed":case"response.mcp_call.failed":n.id="mcp_call_event",n.finishReason="function_call";break;case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":n.id="mcp_list_tools_event",n.finishReason="function_call";break;case"response.output_item.done":switch(t.item.type){case"message":if(n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error",!n.citations||n.citations.length===0){let o=Fn(t.item.content||[]);o&&(n.citations=o)}break;case"function_call":case"file_search_call":case"web_search_call":case"computer_call":case"code_interpreter_call":case"image_generation_call":case"local_shell_call":case"mcp_call":n.id=t.item.id,n.finishReason="function_call";break}break;case"response.completed":t.response.usage&&(this.tokensUsed={promptTokens:t.response.usage.prompt_tokens,completionTokens:t.response.usage.completion_tokens??t.response.usage.output_tokens??0,totalTokens:t.response.usage.total_tokens}),r=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":r=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":r=t.response.id,n.id=`${t.response.id}_incomplete`,n.finishReason="length";break;case"error":n.id="error",n.content=`Error: ${t.message}`,n.finishReason="error";break;default:n.id="unknown";break}return{results:[n],remoteId:r}}createEmbedReq(e){let t=e.embedModel;if(!t)throw new Error("Embed model not set");if(!e.texts||e.texts.length===0)throw new Error("Embed texts is empty");let n={name:"/embeddings"},r={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,r]}},io=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
154
+ `);throw new le(n,void 0,e)}return i.filter(n=>n.type==="output_text").map(n=>n.text).join(`
155
+ `)};function Fn(i){let e=[];for(let t of i??[])if(t?.type==="output_text"&&Array.isArray(t.annotations))for(let n of t.annotations)n&&n.type==="url_citation"&&typeof n.url=="string"&&e.push({url:n.url,title:n.title,description:n.description});return e.length?e:void 0}var Nn=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),sl=()=>({...Nn(),model:"gpt-4o",temperature:.5}),il=()=>({...Nn(),model:"gpt-4o",temperature:.9}),_n=class extends de{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=[],models:s,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new jt(t,n?.streamingUsage??!0,a),p=s?.map(u=>{let d=u,m=d?.config;if(!m)return u;let g={};m.maxTokens!==void 0&&(g.maxTokens=m.maxTokens),m.temperature!==void 0&&(g.temperature=m.temperature),m.topP!==void 0&&(g.topP=m.topP),m.presencePenalty!==void 0&&(g.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(g.frequencyPenalty=m.frequencyPenalty);let f=m.stopSequences??m.stop;f!==void 0&&(g.stopSequences=f),m.n!==void 0&&(g.n=m.n),m.stream!==void 0&&(g.stream=m.stream);let h={...d};Object.keys(g).length>0&&(h.modelConfig={...d.modelConfig??{},...g});let x=m?.thinking?.thinkingTokenBudget;if(typeof x=="number"){let A=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",I=Number.POSITIVE_INFINITY;for(let[T,C]of A){let b=Math.abs(x-C);b<I&&(I=b,y=T)}h.thinkingTokenBudget=y}return m?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!m.thinking.includeThoughts),h});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:o,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:p??s})}},Ht=class extends _n{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...Nr,...o??[]];let s=a=>{let l=Me({model:a,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}};super({apiKey:e,config:{...Nn(),...t},options:n,modelInfo:o,models:r,supportFor:s})}};var ui=()=>structuredClone({model:"openrouter/auto",...Q()}),Kt=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o,referer:s,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...ui(),...t},c={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},p=o??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:p,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let u={Authorization:`Bearer ${e}`};return s&&(u["HTTP-Referer"]=s),a&&(u["X-Title"]=a),u})}};async function ao(i,e,t={}){if(typeof i=="string")return[{type:"text",text:i}];if(!Array.isArray(i))return[{type:"text",text:String(i)}];let n=e.getFeatures(),r=[];for(let o of i)try{switch(o.type){case"text":r.push({type:"text",text:o.text});break;case"image":if(n.media.images.supported)o.altText?r.push({type:"text",text:`[Image: ${o.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(o.altText)r.push({type:"text",text:o.altText});else if(t.imageToText)try{let s=await t.imageToText(o.image);r.push({type:"text",text:s})}catch(s){throw new qe(s,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new De("Images",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:"[Image content not supported by this provider]"})}break;case"audio":if(n.media.audio.supported)o.transcription?r.push({type:"text",text:o.transcription}):r.push({type:"text",text:"[Audio content]"});else if(o.transcription)r.push({type:"text",text:o.transcription});else if(t.audioToText)try{let s=await t.audioToText(o.data,o.format);r.push({type:"text",text:s})}catch(s){throw new qe(s,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new De("Audio",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:"[Audio content not supported by this provider]"})}break;case"file":if(n.media.files.supported)o.extractedText?r.push({type:"text",text:o.extractedText}):r.push({type:"text",text:`[File: ${o.filename}]`});else if(o.extractedText)r.push({type:"text",text:o.extractedText});else if(t.fileToText)try{let s=await t.fileToText(o.data,o.mimeType);r.push({type:"text",text:s})}catch(s){throw new qe(s,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new De("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${o.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)o.cachedContent?r.push({type:"text",text:o.cachedContent}):r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`});else if(o.cachedContent)r.push({type:"text",text:o.cachedContent});else if(t.urlToText)try{let s=await t.urlToText(o.url);r.push({type:"text",text:s})}catch(s){throw new qe(s,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new De("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${o.url}${o.title?` - ${o.title}`:""}]`})}break;default:typeof o=="object"&&o.text?r.push({type:"text",text:o.text}):r.push({type:"text",text:String(o)})}}catch(s){throw s instanceof De||s instanceof qe?s:new qe(s,o.type||"unknown","content processing")}return r}function al(i){let e=!1,t=!1,n=!1,r=!1;for(let o of i)if(o.role==="user"&&Array.isArray(o.content))for(let s of o.content)switch(s.type){case"image":e=!0;break;case"audio":t=!0;break;case"file":n=!0;break;case"url":r=!0;break}return{hasImages:e,hasAudio:t,hasFiles:n,hasUrls:r}}var Dn=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(Dn||{});var lo=[{name:"reka-core",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"reka-flash",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2},{name:"reka-edge",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1}];var $n=()=>structuredClone({model:"reka-core",...Q()}),ll=()=>structuredClone({...$n(),model:"reka-core"}),cl=()=>structuredClone({model:"reka-core",...me()}),pl=()=>({...$n(),model:"reka-flash"}),co=class{constructor(e){this.config=e}tokensUsed;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=e=>{let t=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let n={name:"/chat/completions"},r=ul(e),o=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,s=e.modelConfig?.stream??this.config.stream,a={model:t,messages:r,max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},top_k:e.modelConfig?.n??this.config.n,...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},stop:e.modelConfig?.stopSequences??this.config.stop,presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,...o?{frequency_penalty:o}:{},...s?{stream:!0}:{}};return[n,a]};createChatResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=di(s.finish_reason),c;return typeof s.message.content=="string"?c=s.message.content:c=s.message.content.text,{index:a,id:`${t}`,content:c,finishReason:l}}),remoteId:t}};createChatStreamResp=e=>{let{id:t,usage:n,responses:r}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:r.map((s,a)=>{let l=di(s.finish_reason),c;return typeof s.chunk.content=="string"?c=s.chunk.content:c=s.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},di=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function ul(i){return i.chatPrompt.map(e=>{switch(e.role){case"system":return{role:"user",content:e.content};case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})}:{role:"user",content:e.content};case"assistant":if(Array.isArray(e.content))return{role:"assistant",content:e.content.map(t=>{switch(t.type){case"text":return{type:"text",text:t.text};case"image":throw new Error("Image type not supported");default:throw new Error("Invalid content type")}})};if(!e.content)throw new Error("Assistant content is empty");return{role:"user",content:e.content};default:throw new Error("Invalid role")}})}var Wt=class extends de{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:o=lo,models:s}){if(!e||e==="")throw new Error("Reka API key not set");let a={...$n(),...t},l=new co(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:o,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0},models:s})}};var po=class{providers;processingServices;config;constructor(e){this.providers=[e.providers.primary,...e.providers.alternatives],this.processingServices=e.processing,this.config=e.routing}async chat(e,t={}){let n=await this.selectProviderWithDegradation(e,t.routingOptions||{}),r=await this.preprocessRequest(e,n.provider,t.processingOptions);try{return{response:await n.provider.chat(r,t),routing:n}}catch(o){if(o instanceof De&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw o}}async preprocessRequest(e,t,n){let r={...n,fallbackBehavior:n?.fallbackBehavior||"degrade",imageToText:n?.imageToText||this.processingServices.imageToText,audioToText:n?.audioToText||this.processingServices.audioToText,fileToText:n?.fileToText||this.processingServices.fileToText,urlToText:n?.urlToText||this.processingServices.urlToText},o=[];for(let s of e.chatPrompt)if(s.role==="user"&&Array.isArray(s.content)){let a=await ao(s.content,t,r);a.every(c=>c.type==="text")&&a.length===1?o.push({...s,content:a[0].text}):o.push({...s,content:a.map(c=>({type:"text",text:c.text}))})}else o.push(s);return{...e,chatPrompt:o}}async selectProviderWithDegradation(e,t){let n=xt(e),r=[],o=[],s=[];try{let a=qr(e,this.providers,{requireExactMatch:t.requireExactMatch??this.config.capability.requireExactMatch,allowDegradation:t.allowDegradation??this.config.capability.allowDegradation}),l=a.getFeatures();return n.hasImages&&!l.media.images.supported&&(o.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(o.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(o.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(o.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&s.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&s.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:o,warnings:s}}catch(a){throw new Error(`Provider selection failed: ${a instanceof Error?a.message:"Unknown error"}`)}}async tryFallbackProviders(e,t,n){for(let r of t)try{let o={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},s=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(s,n),routing:o}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=xt(e),n=[],r=[];try{let o=await this.selectProviderWithDegradation(e,{});return o.degradations.length>0&&(n.push(...o.degradations),r.push("Consider using a provider that natively supports all media types")),o.warnings.length>0&&n.push(...o.warnings),t.hasImages&&this.processingServices.imageToText===void 0&&(this.providers.some(a=>a.getFeatures().media.images.supported)||(n.push("No image processing service available and no providers support images"),r.push("Add imageToText processing service or use image-capable provider"))),t.hasAudio&&this.processingServices.audioToText===void 0&&(this.providers.some(a=>a.getFeatures().media.audio.supported)||(n.push("No audio processing service available and no providers support audio"),r.push("Add audioToText processing service or use audio-capable provider"))),{canHandle:n.length===0||o.degradations.length>0,issues:n,recommendations:r}}catch(o){return{canHandle:!1,issues:[`Cannot route request: ${o instanceof Error?o.message:"Unknown error"}`],recommendations:["Add more providers or processing services to handle this request"]}}}getRoutingStats(){let e={};for(let t of this.providers){let n=t.getFeatures(),r=t.getName();n.functions&&(e.Functions=e.Functions||[],e.Functions.push(r)),n.streaming&&(e.Streaming=e.Streaming||[],e.Streaming.push(r)),n.media.images.supported&&(e.Images=e.Images||[],e.Images.push(r)),n.media.audio.supported&&(e.Audio=e.Audio||[],e.Audio.push(r)),n.media.files.supported&&(e.Files=e.Files||[],e.Files.push(r)),n.media.urls.supported&&(e.URLs=e.URLs||[],e.URLs.push(r)),n.caching.supported&&(e.Caching=e.Caching||[],e.Caching.push(r))}return{totalProviders:this.providers.length,capabilityMatrix:e,recommendedProvider:this.providers[0]?.getName()||"None"}}};var uo=[];var mi=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...Q()}),Vt=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Together API key not set");let s={...mi(),...t};o=[...uo,...o??[]];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0};super({apiKey:e,config:s,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:o,models:r,supportFor:a}),super.setName("Together")}};var Gn=(d=>(d.Llama31_8B_Instruct="Llama-3.1-8B-Instruct-q4f32_1-MLC",d.Llama31_70B_Instruct="Llama-3.1-70B-Instruct-q4f16_1-MLC",d.Llama32_1B_Instruct="Llama-3.2-1B-Instruct-q4f32_1-MLC",d.Llama32_3B_Instruct="Llama-3.2-3B-Instruct-q4f32_1-MLC",d.Mistral7B_Instruct="Mistral-7B-Instruct-v0.3-q4f32_1-MLC",d.Phi35_Mini_Instruct="Phi-3.5-mini-instruct-q4f32_1-MLC",d.Gemma2_2B_Instruct="gemma-2-2b-it-q4f32_1-MLC",d.Gemma2_9B_Instruct="gemma-2-9b-it-q4f32_1-MLC",d.Qwen2_5_0_5B_Instruct="Qwen2.5-0.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_1_5B_Instruct="Qwen2.5-1.5B-Instruct-q4f32_1-MLC",d.Qwen2_5_3B_Instruct="Qwen2.5-3B-Instruct-q4f32_1-MLC",d.Qwen2_5_7B_Instruct="Qwen2.5-7B-Instruct-q4f32_1-MLC",d))(Gn||{});var mo=[{name:"Llama-3.1-8B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"Llama-3.1-70B-Instruct-q4f16_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096,isExpensive:!0},{name:"Llama-3.2-1B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Llama-3.2-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:2048},{name:"Mistral-7B-Instruct-v0.3-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096},{name:"Phi-3.5-mini-instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:128e3,maxTokens:4096},{name:"gemma-2-2b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"gemma-2-9b-it-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:8192,maxTokens:2048},{name:"Qwen2.5-0.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-1.5B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-3B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:2048},{name:"Qwen2.5-7B-Instruct-q4f32_1-MLC",currency:"usd",promptTokenCostPer1M:0,completionTokenCostPer1M:0,contextWindow:32768,maxTokens:4096}];var gi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Q()}),dl=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...me()}),go=class{constructor(e,t){this.config=e;this.engine=t}tokensUsed;engine;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens,temperature:e.temperature,topP:e.topP,topK:e.topK,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,stopSequences:e.stopSequences,endSequences:e.endSequences,stream:e.stream,n:e.n}}createChatReq(e){let t=e.model,n=e.chatPrompt.map(a=>{if(a.role==="function")return{role:"function",name:a.functionId,content:typeof a.result=="string"?a.result:JSON.stringify(a.result)};let l="";typeof a.content=="string"?l=a.content:Array.isArray(a.content)&&(l=a.content.filter(p=>p.type==="text").map(p=>p.text).join(`
156
+ `));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(p=>({id:p.id,type:"function",function:{name:p.function.name,arguments:typeof p.function.params=="string"?p.function.params:JSON.stringify(p.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),o={name:"/chat/completions",localCall:async(a,l)=>{try{let c=await this.engine.chat.completions.create({...a,stream:l||!1});return l?new ReadableStream({async start(p){try{for await(let u of c)p.enqueue(u);p.close()}catch(u){p.error(u)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},s={model:t,messages:n,...r?.length?{tools:r}:{},max_tokens:e.modelConfig?.maxTokens??this.config.maxTokens,...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty,frequency_penalty:e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,stop:e.modelConfig?.stopSequences??this.config.stopSequences,stream:e.modelConfig?.stream??this.config.stream,n:e.modelConfig?.n??this.config.n};return[o,s]}createEmbedReq=e=>{throw new Error("WebLLM does not support embeddings")};createChatResp=e=>(this.tokensUsed={promptTokens:e.usage?.prompt_tokens??0,completionTokens:e.usage?.completion_tokens??0,totalTokens:e.usage?.total_tokens??0},{results:e.choices.map((n,r)=>{let o="stop";switch(n.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.message.tool_calls?.map(a=>({id:a.id,type:"function",function:{name:a.function.name,params:a.function.arguments}}));return{index:r,id:e.id,content:n.message.content||"",functionCalls:s,finishReason:o}}),remoteId:e.id});createChatStreamResp=(e,t)=>{let n=t,r=e.choices[0];if(!r)throw new Error("No choice in WebLLM stream response");if(r.delta.content&&(n.content=(n.content||"")+r.delta.content),r.delta.tool_calls){n.toolCalls||(n.toolCalls=[]);for(let l of r.delta.tool_calls){let c=n.toolCalls[l.index];c?l.function?.arguments&&(c.function.arguments=(c.function?.arguments||"")+l.function.arguments):n.toolCalls[l.index]={id:l.id,type:l.type,function:{name:l.function?.name,arguments:l.function?.arguments||""}}}}e.usage&&(this.tokensUsed={promptTokens:e.usage.prompt_tokens,completionTokens:e.usage.completion_tokens,totalTokens:e.usage.total_tokens});let o;if(r.finish_reason)switch(r.finish_reason){case"stop":o="stop";break;case"length":o="length";break;case"tool_calls":o="function_call";break;case"content_filter":o="content_filter";break;default:o="stop";break}let s=n.toolCalls?.map(l=>({id:l.id||"",type:"function",function:{name:l.function?.name||"",params:l.function?.arguments||""}}));return{results:[{index:0,id:e.id,content:n.content||"",functionCalls:s,finishReason:o}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},Jt=class extends de{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let o={...gi(),...t},s=new go(o,e);super(s,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:mo,defaults:{model:o.model},supportFor:a=>({functions:!0,streaming:!0,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}),options:n,models:r})}};var Ln=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(Ln||{}),hi=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(hi||{});var ho=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,supported:{thinkingBudget:!0}},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,supported:{thinkingBudget:!0}}];var fo=()=>structuredClone({model:"grok-3-mini",...Q()}),ml=()=>structuredClone({...fo(),model:"grok-3"}),Qt=class extends ue{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:o}){if(!e||e==="")throw new Error("Grok API key not set");let s={...fo(),...t};o=[...ho,...o??[]];let a=c=>{let p=Me({model:c,modelInfo:o,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:p?.supported?.thinkingBudget??!1,hasShowThoughts:p?.supported?.showThoughts??!1,media:{images:{supported:!1,formats:[]},audio:{supported:!1,formats:[]},files:{supported:!1,formats:[],uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!1,types:[]},thinking:!1,multiTurn:!0}},l=c=>{if(n?.searchParameters){let p=n.searchParameters;return{...c,search_parameters:{mode:p.mode,return_citations:p.returnCitations,from_date:p.fromDate,to_date:p.toDate,max_search_results:p.maxSearchResults,sources:p.sources?.map(u=>({type:u.type,country:u.country,excluded_websites:u.excludedWebsites,allowed_websites:u.allowedWebsites,safe_search:u.safeSearch,x_handles:u.xHandles,links:u.links}))}}}return c};super({apiKey:e,config:s,options:n,apiURL:"https://api.x.ai/v1",modelInfo:o,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function gl(i){return Un.create(i)}var Un=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new _t(e);break;case"openai-responses":this.ai=new Ht(e);break;case"azure-openai":this.ai=new Nt(e);break;case"grok":this.ai=new Qt(e);break;case"huggingface":this.ai=new Bt(e);break;case"groq":this.ai=new Ut(e);break;case"together":this.ai=new Vt(e);break;case"openrouter":this.ai=new Kt(e);break;case"cohere":this.ai=new Dt(e);break;case"google-gemini":this.ai=new Gt(e);break;case"anthropic":this.ai=new Mt(e);break;case"mistral":this.ai=new qt(e);break;case"deepseek":this.ai=new $t(e);break;case"ollama":this.ai=new zt(e);break;case"reka":this.ai=new Wt(e);break;case"webllm":this.ai=new Jt(e);break;default:throw new Error("Unknown AI")}}getName(){return this.ai.getName()}getId(){return this.ai.getId()}getFeatures(e){return this.ai.getFeatures(e)}getModelList(){return this.ai.getModelList()}getLastUsedChatModel(){return this.ai.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.ai.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.ai.getLastUsedModelConfig()}getMetrics(){return this.ai.getMetrics()}async chat(e,t){return await this.ai.chat(e,t)}async embed(e,t){return await this.ai.embed(e,t)}setOptions(e){this.ai.setOptions(e)}getOptions(){return this.ai.getOptions()}getLogger(){return this.ai.getLogger()}};import{SpanKind as Ao}from"@opentelemetry/api";var Ge=class{name;fetch;tracer;_upsert;_batchUpsert;_query;constructor({name:e,fetch:t,tracer:n}){this.name=e,this.fetch=t,this.tracer=n}async upsert(e,t){if(!this._upsert)throw new Error("upsert() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Upsert Request",{kind:Ao.SERVER,attributes:{[B.DB_SYSTEM]:this.name,[B.DB_OPERATION_NAME]:"upsert",[B.DB_TABLE]:e.table,[B.DB_NAMESPACE]:e.namespace,[B.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._upsert(e,t,{span:n})}finally{n.end()}}):await this._upsert(e,t)}async batchUpsert(e,t){if(!this._batchUpsert)throw new Error("batchUpsert() not implemented");if(e.length===0)throw new Error("Batch request is empty");if(!e[0])throw new Error("Batch request is invalid first element is undefined");return this.tracer?await this.tracer.startActiveSpan("DB Batch Upsert Request",{kind:Ao.SERVER,attributes:{[B.DB_SYSTEM]:this.name,[B.DB_OPERATION_NAME]:"upsert",[B.DB_TABLE]:e[0].table,[B.DB_NAMESPACE]:e[0].namespace,[B.DB_OPERATION_NAME]:t?"update":"insert"}},async n=>{try{return await this._batchUpsert(e,t,{span:n})}finally{n.end()}}):await this._batchUpsert(e,t)}async query(e){if(!this._query)throw new Error("query() not implemented");return this.tracer?await this.tracer.startActiveSpan("DB Query Request",{kind:Ao.SERVER,attributes:{[B.DB_SYSTEM]:this.name,[B.DB_OPERATION_NAME]:"upsert",[B.DB_TABLE]:e.table,[B.DB_NAMESPACE]:e.namespace,[B.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var xo="https://api.cloudflare.com/client/v4/accounts/",Yt=class extends Ge{apiKey;accountId;constructor({apiKey:e,accountId:t,fetch:n,tracer:r}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:r}),this.apiKey=e,this.accountId=t}_upsert=async(e,t,n)=>{let r=await Ce({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,xo),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(r.errors)throw new Error(`Cloudflare upsert failed: ${r.errors.map(({message:o})=>o).join(", ")}`);return{ids:r.result.ids}};batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length<1)throw new Error("Batch request is empty");if(!e[0]||!e[0].table)throw new Error("Table name is empty");let r=e[0].table,o=await Ce({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,xo),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(s=>({id:s.id,values:s.values,namespace:s.namespace,metadata:s.metadata})));if(o.errors)throw new Error(`Cloudflare batch upsert failed: ${o.errors.map(({message:s})=>s).join(", ")}`);return{ids:o.result.ids}};query=async(e,t)=>{let n=await Ce({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,xo),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:t?.span},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:o})=>o).join(", ")}`);return{matches:n.result.matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,values:a,metadata:l}))}}};var lt=class extends Ge{state;constructor({tracer:e}={}){super({name:"Memory",tracer:e}),this.state={}}_upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let r=this.state[e.table];if(!r)throw new Error(`Table not found: ${e.table}`);r[e.id]=e}return{ids:[e.id]}};_batchUpsert=async(e,t,n)=>{let r=[];for(let o of e){let s=await this.upsert(o,t);r.push(...s.ids)}return{ids:r}};_query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let r=[];return Object.entries(n).forEach(([o,s])=>{if(e.values&&s.values){let a=hl(e.values,s.values);r.push({id:o,score:a,metadata:s.metadata})}}),r.sort((o,s)=>o.score-s.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},hl=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,o=!0,s=!0,a=new Float64Array(i),l=new Float64Array(e);for(let d=0;d<a.length;d++)t+=a[d]*l[d],n+=a[d]*a[d],r+=l[d]*l[d],a[d]!==0&&(o=!1),l[d]!==0&&(s=!1);if(o||s)return 1;let c=Math.sqrt(n),p=Math.sqrt(r);return 1-t/(c*p)};var fl=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),Xt=class extends Ge{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]});_batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await Ce({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:o=[],metadata:s})=>({id:r,values:o,metadata:s}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await Ce({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},fl(e))).matches.map(({id:o,score:s,values:a,metadata:l})=>({id:o,score:s,metadata:l,values:a}))}}};var Zt=class extends Ge{apiKey;apiURL;constructor({apiKey:e,host:t,fetch:n,tracer:r}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:r}),this.apiKey=e,this.apiURL=t}_upsert=async(e,t,n)=>{let r=await Ce({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:n?.span},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:e.metadata??{}});if(r?.result?.errors)throw new Error(`Weaviate upsert failed: ${r.result.errors.error.map(({message:o})=>o).join(", ")}`);return{ids:[r.id]}};_batchUpsert=async(e,t,n)=>{if(t)throw new Error("Weaviate does not support batch update");if(e.length===0)throw new Error("Batch request is empty");let r=e.map(s=>({id:s.id,class:s.table,tenant:s.namespace,vector:s.values,properties:s.metadata??{}})),o=await Ce({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(o?.some(({result:s})=>s?.errors))throw new Error(`Weaviate batch upsert failed: ${o.map(({result:s})=>s?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:o.map(({id:s})=>s)}};_query=async(e,t)=>{let n="";if(e.columns&&e.columns.length===0)throw new Error("Weaviate requires at least one column");if(e.values)n=`nearVector: {
156
157
  vector: [${e.values.join(",")}],
157
158
  }`;else if(e.text)n=`nearText: {
158
159
  concepts: ['${e.text}'],
159
- }`;else throw new Error("Weaviate requires either text or values");let r=await ye({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
160
+ }`;else throw new Error("Weaviate requires either text or values");let r=await Ce({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:t?.span},{query:`{
160
161
  Get {
161
162
  ${e.table} (
162
163
  limit: ${e.limit||10},
@@ -166,9 +167,9 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
166
167
  `)}
167
168
  }
168
169
  }
169
- }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var fo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Yt(e);break;case"pinecone":this.db=new Qt(e);break;case"cloudflare":this.db=new Jt(e);break;case"memory":this.db=new it(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var Ao="_internal",xo=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
170
+ }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let o=r.data.Get[e.table];return o?{matches:o.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var yo=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Zt(e);break;case"pinecone":this.db=new Xt(e);break;case"cloudflare":this.db=new Yt(e);break;case"memory":this.db=new lt(e);break;default:throw new Error("Unknown DB")}}async upsert(e,t){return await this.db.upsert(e,t)}async batchUpsert(e,t){return await this.db.batchUpsert(e,t)}async query(e){return await this.db.query(e)}};var bo="_internal",Io=class{ai;db;chunker;rewriter;reranker;constructor({ai:e,db:t,config:n}){this.ai=e,this.db=t,this.chunker=n?.chunker??this.defaultChunker,this.reranker=n?.reranker,this.rewriter=n?.rewriter}defaultChunker=e=>e.split(/\n\n+/);insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
170
171
 
171
- `):e,r=this.chunker(n).filter(c=>c.length>0),o=t?.maxWordsPerChunk,s=t?.minWordsPerChunk,a=ll({initialChunks:r,minWordsPerChunk:s,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let p=a.slice(c,c+l),d=(await this.ai.embed({texts:p},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:Ao,values:m,metadata:{text:p[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(d)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,c]of r.entries()){let{rewrittenQuery:p}=await this.rewriter.forward(this.ai,{query:c});r[l]=p}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:Ao,values:c})):o=r.map(l=>this.db.query({table:Ao,values:l}));let s=await Promise.all(o),a=[];for(let{matches:l}of s){let c=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),p=t&&t>1?t/100:t,u=p?cl(c,p):c;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:u.map(g=>g.text)}),m=d.map(g=>u.find(f=>f.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(u)}return a}},ll=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return i.forEach(s=>{let a=s.split(/\s+/),l=a.length;if(o+l<=e)r+=`${s}
172
+ `):e,r=this.chunker(n).filter(c=>c.length>0),o=t?.maxWordsPerChunk,s=t?.minWordsPerChunk,a=Al({initialChunks:r,minWordsPerChunk:s,maxWordsPerChunk:o}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let p=a.slice(c,c+l),d=(await this.ai.embed({texts:p},{abortSignal:t?.abortSignal})).embeddings.map((m,g)=>({id:`chunk_${Date.now()+g}`,table:bo,values:m,metadata:{text:p[g]??""}})).filter(m=>m.metadata?.text&&m.metadata?.text.length>0);await this.db.batchUpsert(d)}}catch(n){throw new Error(`Error processing text: ${n}`)}};query=async(e,{topPercent:t,abortSignal:n}={})=>{let r=Array.isArray(e)?e:[e];if(typeof r[0]=="string"&&this.rewriter)for(let[l,c]of r.entries()){let{rewrittenQuery:p}=await this.rewriter.forward(this.ai,{query:c});r[l]=p}let o;typeof r[0]=="string"?o=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:bo,values:c})):o=r.map(l=>this.db.query({table:bo,values:l}));let s=await Promise.all(o),a=[];for(let{matches:l}of s){let c=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),p=t&&t>1?t/100:t,u=p?xl(c,p):c;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:u.map(g=>g.text)}),m=d.map(g=>u.find(f=>f.text===g)).filter(g=>g!==void 0);a.push(m)}else a.push(u)}return a}},Al=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",o=0;return i.forEach(s=>{let a=s.split(/\s+/),l=a.length;if(o+l<=e)r+=`${s}
172
173
 
173
174
  `,o+=l;else if(o>0&&o+l<=e*1.5)r+=`${s}
174
175
 
@@ -176,59 +177,59 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
176
177
 
177
178
  `,o+=c.length)}else r=`${s}
178
179
 
179
- `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},cl=(i,e=.1)=>{let t=[...i].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as Bl,SpanKind as ql,trace as zl}from"@opentelemetry/api";var Xt=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:r}){let o=this.data.at(-1);if(!o||o.role!=="assistant"||o.role==="assistant"&&!o.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:r,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let s=o.chat.find(a=>a.index===r);if(!s){o.chat.push({index:r,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(s.value.content=e),typeof t=="string"&&t.trim()!==""&&(s.value.name=t),Array.isArray(n)&&n.length>0&&(s.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(s=>s.index===e).map(s=>s.value):o=r.find(s=>s.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(s=>({...s,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},Zt=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new Xt}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Xt),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)vt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Mr(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Xt):this.defaultMemory.reset()}};var Je=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Gn=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new Je({message:o});if(!o)throw r?new Je({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},yo=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(s=>s.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let s of r){let{message:a,fn:l}=s,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new Je({message:c});if(!c&&a)throw new Je({message:a})}}};var ai={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},en,bo=i=>{if(en)return en;let e=i??se.meter;if(e)return en=ul(e),en};var pl=()=>{let i=[];return se.meter||i.push("Global meter not initialized"),!en&&se.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},ul=i=>({generationLatencyHistogram:i.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:i.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:i.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:i.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:i.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:i.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:i.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:i.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:i.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:i.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:i.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:i.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:i.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:i.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:i.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:i.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:i.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:i.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:i.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:i.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:i.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:i.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:i.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:i.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:i.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:i.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:i.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:i.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:i.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:i.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:i.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:i.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:i.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),Un=ai,dl=i=>{Un={...Un,...i}},ml=()=>({...Un}),De=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=Un.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},li=(i,e,t,n,r,o)=>{try{let s=De({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},Bn=(i,e,t,n)=>{try{let r=De({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,r),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,r),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Io=(i,e,t)=>{try{let n=De({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ci=(i,e)=>{try{let t=De({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},To=(i,e,t,n,r)=>{try{let o=De({success:t.toString(),...r?{signature:r}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,o),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,o),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,o),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},pi=(i,e,t,n,r=!1,o)=>{try{let s=De({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},ui=(i,e,t,n)=>{try{let r=De({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,r),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},di=(i,e,t,n,r)=>{try{let o=De({is_streaming:e.toString(),...r?{signature:r}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,o),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,o),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},mi=(i,e,t,n,r)=>{try{let o=De({result_picker_used:t.toString(),...r?{signature:r}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,o),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,o),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},gi=(i,e,t,n,r,o)=>{try{let s=De({...o?{signature:o}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(r,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},qn=(i,e,t,n)=>{try{let r=De({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,r);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,r);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,r);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var At=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e},be=class extends Error{constructor(e){super(e),this.name=this.constructor.name}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},hi=i=>{let t=i.map(n=>`'${n.title}' (${At(n.type)})`).join(", ");return new be(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${i[0]?.title}:") and then provide a valid ${At(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},zn=i=>new be(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${At(i.type)} value directly after.`);var fi=i=>new be(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${At(i.type)}. Do not use null, undefined, or leave it blank.`),Ai=(i,e)=>new be(`Invalid JSON: ${e} in field '${i.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),xi=(i,e)=>new be(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${At(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),yi=(i,e,t)=>new be(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${At(i.type)}. Ensure formatting exactly matches the expected type.`),bi=(i,e,t)=>new be(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Ii=(i,e,t)=>new be(`Invalid date/time for '${i.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`);var Ti=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";fs(i,e,l,n)}return r&&Io(r,"validation",o),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ri=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";As(i,e,l,n)}return r&&Io(r,"assertion",o),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Ci=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{t&&n&&xs(i,e,n),r&&ci(r,o),s&&s.addEvent("refusal.error",{message:i.toString()})};var wi=i=>{let e=[],t=(n,r="")=>{if(!n||typeof n!="object")return;let o=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:r||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((s,a)=>{t(s,`${r}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:r||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((s,a)=>{t(s,`${r}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:r||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((s,a)=>{t(s,`${r}allOf[${a}].`)});return}if(n.type){if(!o.includes(n.type)){e.push({path:r||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${o.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:r||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let s in n.properties){let a=n.properties[s];if(a!=null){if(typeof a!="object"){e.push({path:`${r}${s}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${s}: { type: "string", description: "..." }`});continue}t(a,`${r}${s}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:r||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let s of n.required)typeof s!="string"?e.push({path:`${r}required`,issue:`Required property names must be strings, got ${typeof s}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):s in n.properties||e.push({path:`${r}required`,issue:`Required property '${s}' is not defined in properties`,fix:`Either add '${s}' to properties or remove it from required`,example:`properties: { ${s}: { type: "string" } }`})}}}n.type==="array"&&(n.items?typeof n.items!="object"?e.push({path:`${r}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${r}items.`):e.push({path:r||"root",issue:'Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)',fix:'Add an "items" schema describing the array element type, e.g., items: { type: "string" } or items: { type: "object", properties: { ... } }',example:['type: "array",','description: "List of step strings"','items: { type: "string" }'].join(`
180
+ `,o=l}),(o>t||n.length===0)&&n.push(r.trim()),n},xl=(i,e=.1)=>{let t=[...i].sort((r,o)=>r.score-o.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as Ql,SpanKind as Yl,trace as Xl}from"@opentelemetry/api";var en=class{data=[];seenTags=new Set;addRequest(e,t){this.data.push(...e.map(n=>{let r=structuredClone(n);return{role:n.role,chat:[{index:t,value:r}]}}))}addFunctionResults(e){let t=e.map(({index:r,...o})=>({index:r,value:structuredClone(o)})),n=this.getLast();n?.role==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...r})=>({index:n,value:structuredClone(r)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o,index:s}){let a=this.data.at(-1);if(!a||a.role!=="assistant"||a.role==="assistant"&&!a.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})}]});return}let l=a.chat.find(c=>c.index===s);if(!l){a.chat.push({index:s,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlock:o})});return}if(typeof e=="string"&&e.trim()!==""&&(l.value.content=e),typeof t=="string"&&t.trim()!==""&&(l.value.name=t),Array.isArray(n)&&n.length>0&&(l.value.functionCalls=n),typeof r=="string"&&r.trim()!==""){let c=l.value.thought;l.value.thought=typeof c=="string"?c+r:r}if(o&&typeof o=="object"){let c=l.value.thoughtBlock??{},p={data:(c.data??"")+(o.data??""),encrypted:!!c.encrypted||!!o.encrypted,...o.signature?{signature:o.signature}:{}};l.value.thoughtBlock=p}}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e),this.seenTags.add(e))}rewindToTag(e){let t=this.data.findIndex(n=>n.tags?.includes(e));if(t===-1){if(!this.seenTags.has(e))throw new Error(`Tag "${e}" not found`);return[]}return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,r,o)=>(r.tags?.includes(e)&&n.push(o),n),[]);return t.length===0?[]:t.reverse().map(n=>this.data.splice(n,1).at(0)).filter(n=>n!==void 0).reverse()}history(e){let t=[];for(let{role:n,chat:r}of this.data){let o;n==="function"?o=r.filter(s=>s.index===e).map(s=>s.value):o=r.find(s=>s.index===e)?.value,Array.isArray(o)&&o.length>0?t.push(...o.map(s=>({...s,role:n}))):typeof o=="object"&&o!==null&&t.push({...o,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},tn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new en}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new en),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)kt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){Pr(e),this.getMemory(t).addResponse(e)}addFunctionResults(e,t){this.getMemory(t).addFunctionResults(e)}updateResult(e,t){this.getMemory(t).updateResult(e)}addTag(e,t){this.getMemory(t).addTag(e)}rewindToTag(e,t){return this.getMemory(t).rewindToTag(e)}removeByTag(e,t){return this.getMemory(t).removeByTag(e)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new en):this.defaultMemory.reset()}};var Qe=class extends Error{constructor({message:e}){super(e),this.name=this.constructor.name}getFixingInstructions=()=>{let e=[],t=this.message.trim();return e.push({name:"error",title:"Follow these instructions",description:t+(t.endsWith(".")?"":".")}),e};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Bn=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,o=await n(e);if(o!==void 0){if(typeof o=="string")throw new Qe({message:o});if(!o)throw r?new Qe({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},To=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(s=>s.fieldName===e.currField?.name);if(r.length===0)return;let o=t.substring(e.s);for(let s of r){let{message:a,fn:l}=s,c=await l(o,n);if(c!==void 0){if(typeof c=="string")throw new Qe({message:c});if(!c&&a)throw new Qe({message:a})}}};var fi={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},nn,Co=i=>{if(nn)return nn;let e=i??ie.meter;if(e)return nn=bl(e),nn};var yl=()=>{let i=[];return ie.meter||i.push("Global meter not initialized"),!nn&&ie.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},bl=i=>({generationLatencyHistogram:i.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:i.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:i.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:i.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:i.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:i.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:i.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:i.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:i.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:i.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:i.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:i.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:i.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:i.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:i.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:i.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:i.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:i.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:i.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:i.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:i.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:i.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:i.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:i.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:i.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:i.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:i.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:i.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:i.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:i.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:i.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:i.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:i.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),qn=fi,Il=i=>{qn={...qn,...i}},Tl=()=>({...qn}),Le=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=qn.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},Ai=(i,e,t,n,r,o)=>{try{let s=Le({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...o?{model:o}:{}});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,s),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,s),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,s)}catch(s){console.warn("Failed to record generation metric:",s)}},zn=(i,e,t,n)=>{try{let r=Le({...n?{signature:n}:{}});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,r),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,r),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,r)}catch(r){console.warn("Failed to record multi-step metric:",r)}},Ro=(i,e,t)=>{try{let n=Le({error_type:e,...t?{signature:t}:{}});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},xi=(i,e)=>{try{let t=Le({error_type:"refusal",...e?{signature:e}:{}});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},wo=(i,e,t,n,r)=>{try{let o=Le({success:t.toString(),...r?{signature:r}:{}});i.errorCorrectionAttemptsHistogram&&i.errorCorrectionAttemptsHistogram.record(e,o),t&&i.errorCorrectionSuccessCounter&&i.errorCorrectionSuccessCounter.add(1,o),t||(i.errorCorrectionFailureCounter&&i.errorCorrectionFailureCounter.add(1,o),e>=n&&i.maxRetriesReachedCounter&&i.maxRetriesReachedCounter.add(1,o))}catch(o){console.warn("Failed to record error correction metric:",o)}},yi=(i,e,t,n,r=!1,o)=>{try{let s=Le({functions_enabled:e.toString(),had_function_calls:n.toString(),...o?{signature:o}:{}});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,s),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,s),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,s),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,s)}catch(s){console.warn("Failed to record function calling metric:",s)}},bi=(i,e,t,n)=>{try{let r=Le({...n?{signature:n}:{}});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,r),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,r)}catch(r){console.warn("Failed to record field processing metric:",r)}},Ii=(i,e,t,n,r)=>{try{let o=Le({is_streaming:e.toString(),...r?{signature:r}:{}});e&&i.streamingGenerationsCounter&&i.streamingGenerationsCounter.add(1,o),t>0&&i.streamingDeltasEmittedCounter&&i.streamingDeltasEmittedCounter.add(t,o),n&&i.streamingFinalizationLatencyHistogram&&i.streamingFinalizationLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record streaming metric:",o)}},Ti=(i,e,t,n,r)=>{try{let o=Le({result_picker_used:t.toString(),...r?{signature:r}:{}});i.samplesGeneratedHistogram&&i.samplesGeneratedHistogram.record(e,o),t&&i.resultPickerUsageCounter&&i.resultPickerUsageCounter.add(1,o),n&&i.resultPickerLatencyHistogram&&i.resultPickerLatencyHistogram.record(n,o)}catch(o){console.warn("Failed to record samples metric:",o)}},Ci=(i,e,t,n,r,o)=>{try{let s=Le({...o?{signature:o}:{}});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,s),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,s),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,s),i.demosUsedGauge&&i.demosUsedGauge.record(r,s)}catch(s){console.warn("Failed to record signature complexity metrics:",s)}},jn=(i,e,t,n)=>{try{let r=Le({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,r);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,r);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,r);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,r);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record performance metric:",r)}};var yt=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e},Re=class extends Error{constructor(e){super(e),this.name=this.constructor.name}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field **Only return the invalid, remaining fields**",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Ri=i=>{let t=i.map(n=>`'${n.title}' (${yt(n.type)})`).join(", ");return new Re(`Required field not found: ${t}. Add a line starting with the exact label followed by a colon (e.g., "${i[0]?.title}:") and then provide a valid ${yt(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},Hn=i=>new Re(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${yt(i.type)} value directly after.`);var wi=i=>new Re(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${yt(i.type)}. Do not use null, undefined, or leave it blank.`),Si=(i,e)=>new Re(`Invalid JSON: ${e} in field '${i.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),vi=(i,e)=>new Re(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${yt(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),Oi=(i,e,t)=>new Re(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${yt(i.type)}. Ensure formatting exactly matches the expected type.`),ki=(i,e,t)=>new Re(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),Mi=(i,e,t)=>new Re(`Invalid date/time for '${i.title}': ${t}. Use the format YYYY-MM-DD HH:mm or YYYY-MM-DD HH:mm:ss followed by a valid timezone (e.g., America/New_York). You provided: ${e}.`);var Ei=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";ws(i,e,l,n)}return r&&Ro(r,"validation",o),s&&s.addEvent("validation.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Pi=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{let a=i.getFixingInstructions();if(t&&n){let l=a?.map(c=>c.title).join(", ")??"";Ss(i,e,l,n)}return r&&Ro(r,"assertion",o),s&&s.addEvent("assertion.error",{message:i.toString(),fixing_instructions:a?.map(l=>l.title).join(", ")??""}),a},Fi=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:o,span:s})=>{t&&n&&vs(i,e,n),r&&xi(r,o),s&&s.addEvent("refusal.error",{message:i.toString()})};var _i=i=>{let e=[],t=(n,r="")=>{if(!n||typeof n!="object")return;let o=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:r||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((s,a)=>{t(s,`${r}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:r||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((s,a)=>{t(s,`${r}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:r||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((s,a)=>{t(s,`${r}allOf[${a}].`)});return}if(n.type){if(!o.includes(n.type)){e.push({path:r||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${o.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:r||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let s in n.properties){let a=n.properties[s];if(a!=null){if(typeof a!="object"){e.push({path:`${r}${s}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${s}: { type: "string", description: "..." }`});continue}t(a,`${r}${s}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:r||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let s of n.required)typeof s!="string"?e.push({path:`${r}required`,issue:`Required property names must be strings, got ${typeof s}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):s in n.properties||e.push({path:`${r}required`,issue:`Required property '${s}' is not defined in properties`,fix:`Either add '${s}' to properties or remove it from required`,example:`properties: { ${s}: { type: "string" } }`})}}}n.type==="array"&&(n.items?typeof n.items!="object"?e.push({path:`${r}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${r}items.`):e.push({path:r||"root",issue:'Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)',fix:'Add an "items" schema describing the array element type, e.g., items: { type: "string" } or items: { type: "object", properties: { ... } }',example:['type: "array",','description: "List of step strings"','items: { type: "string" }'].join(`
180
181
  `)}))}};if(t(i),e.length>0){let n=["JSON Schema validation failed:","",...e.map((r,o)=>{let s=[`${o+1}. Path: ${r.path}`,` Issue: ${r.issue}`,` Fix: ${r.fix}`];return r.example&&s.push(` Example: ${r.example}`),s.join(`
181
182
  `)}),"","Please fix these issues and try again."].join(`
182
- `);throw new Error(n)}};var xt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},jn=class extends Error{constructor(t){super();this.fields=t;this.name=this.constructor.name}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
183
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},tn=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
183
+ `);throw new Error(n)}};var bt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Kn=class extends Error{constructor(t){super();this.fields=t;this.name=this.constructor.name}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
184
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},rn=class extends Error{constructor(t,n,r){super();this.fields=t;this.func=n;this.funcId=r}getFunctionId=()=>this.funcId;getFieldDescription(t){if(!this.func.parameters?.properties?.[t])return"";let n=this.func.parameters.properties[t],r=n.description;return n.enum?.length&&(r+=` Allowed values are: ${n.enum.join(", ")}`),r}getFixingInstructions=()=>{let t=this.fields.map(n=>{let r=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${r}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
184
185
  ${t.join(`
185
186
  `)}`};toString(){return[`${this.name}: Function execution error in '${this.func.name}'`,...this.fields.map(t=>{let n=this.getFieldDescription(t.field);return` - ${t.field}: ${t.message}${n?` (${n})`:""}`}),this.funcId?` Function ID: ${this.funcId}`:""].join(`
186
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Hn=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;e.parameters?s=e.func.length===2?await e.func(r,o):await e.func(r):s=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??se.functionResultFormatter)(s);return{formatted:String(l),rawResult:s,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(s=>s.name===e.name);if(o||(o=this.funcList.find(s=>n(s.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(s){throw s instanceof jn?new tn(s.getFields(),o,e.id):s}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Kn=(i,e)=>{if(i.length===0)return[...e??[]];let t=i.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{wi(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
187
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Wn=class{funcList=[];constructor(e){this.funcList=e}executeFunction=async(e,t,n)=>{let r;if(typeof t.args=="string"&&t.args.length>0)try{r=JSON.parse(t.args)}catch(c){throw new Error(`Invalid function arguments: ${t.args}`,{cause:c})}else r=t.args;let o=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,s;e.parameters?s=e.func.length===2?await e.func(r,o):await e.func(r):s=e.func.length===1?await e.func(o):await e.func();let l=(n?.functionResultFormatter??ie.functionResultFormatter)(s);return{formatted:String(l),rawResult:s,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=s=>s.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),o=this.funcList.find(s=>s.name===e.name);if(o||(o=this.funcList.find(s=>n(s.name)===r)),!o)throw new Error(`Function not found: ${e.name}`);if(!o.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(o,e,t)}catch(s){throw s instanceof Kn?new rn(s.getFields(),o,e.id):s}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Vn=(i,e)=>{if(i.length===0)return[...e??[]];let t=i.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(r=>r.parameters))if(n.parameters)try{_i(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
187
188
  ${r.message}
188
- Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Wn=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:p,debug:u,stopFunctionNames:d})=>{let m=new Hn(e),g=new Set,f=[],h=I=>{let T=v=>v.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),b=T(I),w=e.find(v=>v.name===I);return w||(w=e.find(v=>T(v.name)===b)),w},x=t.map(I=>{if(!I.id)throw new Error(`Function ${I.name} did not return an ID`);let T=i.getOptions().tracer??se.tracer;return T?T.startActiveSpan(`Tool: ${I.name}`,async b=>{try{b?.setAttributes?.({"tool.name":I.name,"tool.mode":"native","function.id":I.id,"session.id":r??""});let{formatted:w,rawResult:v,parsedArgs:F}=await m.executeWithDetails(I,{sessionId:r,ai:i,functionResultFormatter:c,traceId:b?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(I.name.toLowerCase()),d?.includes(I.name.toLowerCase())){let K=h(I.name);K&&f.push({func:K,args:F,result:v})}if(a?b.addEvent("gen_ai.tool.message",{name:I.name}):b.addEvent("gen_ai.tool.message",{name:I.name,args:I.args,result:w??""}),s){let K={name:I.name};a||(K.args=I.args,K.result=w??""),s.addEvent("function.call",K)}return{result:w??"",role:"function",functionId:I.id,index:l}}catch(w){if(b?.recordException?.(w),w instanceof tn){let v=w.getFixingInstructions(),F={name:I.name,message:w.toString()};return a||(F.args=I.args,F.fixing_instructions=v),b?.addEvent?.("function.error",F),u&&Cr(w,l,v,p),{functionId:I.id,isError:!0,index:l,result:v,role:"function"}}throw w}finally{b?.end?.()}}):m.executeWithDetails(I,{sessionId:r,ai:i,functionResultFormatter:c,traceId:o,stopFunctionNames:d}).then(({formatted:b,rawResult:w,parsedArgs:v})=>{if(g.add(I.name.toLowerCase()),d?.includes(I.name.toLowerCase())){let F=h(I.name);F&&f.push({func:F,args:v,result:w})}if(s){let F={name:I.name};a||(F.args=I.args,F.result=b??""),s.addEvent("function.call",F)}return{result:b??"",role:"function",functionId:I.id,index:l}}).catch(b=>{if(!(b instanceof tn))throw b;let w=b.getFixingInstructions();if(s){let v={name:I.name,message:b.toString()};a||(v.args=I.args,v.fixing_instructions=w),s.addEvent("function.error",v)}return u&&Cr(b,l,w,p),{functionId:I.id,isError:!0,index:l,result:w,role:"function"}})}),y=(await Promise.all(x)).map(I=>I.result===void 0||I.result===""?{...I,result:"done"}:I);if(n.addFunctionResults(y,r),u){let I=y.filter(T=>!T.isError);I.length>0&&hs(I,p)}if(f.length>0)throw new xt(f);return g};function Ro(i,e,t,n){if(!e||e.length===0)return;if(!i.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function Si(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}import at from"dayjs";import gl from"dayjs/plugin/customParseFormat.js";import hl from"dayjs/plugin/timezone.js";import fl from"dayjs/plugin/utc.js";at.extend(fl);at.extend(hl);at.extend(gl);function vi(i,e,t=!1){try{return Al(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw bi(i,e,r)}}function Al(i){if(!at(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return at.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Oi(i,e,t=!1){try{return xl(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Ii(i,e,r)}}function xl(i){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=i.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=at.tz(n,o,r);if(!s.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return s.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Mi=i=>at(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var _m=new Ae,Vn=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(c,p)=>{switch(c){case"class":return typeof p=="string";case"code":return typeof p=="string";case"string":return typeof p=="string";case"number":return typeof p=="number";case"boolean":return typeof p=="boolean";case"date":return p instanceof Date||typeof p=="string";case"datetime":return p instanceof Date||typeof p=="string";case"json":return typeof p=="object"||typeof p=="string";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(i.type?.name==="image"){let c;if(Array.isArray(e)){for(let p of e)if(!r(p)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let o=c=>!(!c||typeof c!="object"||!("data"in c));if(i.type?.name==="audio"){let c;if(Array.isArray(e)){for(let p of e)if(!o(p)){c="object ({ data: string; format?: string })";break}}else o(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let p="data"in c,u="fileUri"in c;return!(!p&&!u||p&&u)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let p of e)if(!s(p)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(i.type?.name==="url"){let c;if(Array.isArray(e)){for(let p of e)if(!a(p)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let c of e)if(!n(t.name,c)){l=!1;break}}else l=n(t.name,e);if(!l){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function nn(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let s=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(s.push(c),l.add(c.url));r.citations=s}}}return Object.values(e)}var ki=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
189
- `),r=[];for(let o of n){let s=o.trim();if(s){if(s[0]&&e.has(s[0]))r.push(s.slice(1).trim());else if(t.test(s))r.push(s.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function wo(i,e){let{index:t,delta:n,version:r}=e,o=i.find(a=>a.index===t)?.delta;if(!o)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=o[a],c=n[a];l===void 0&&Array.isArray(c)?o[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?o[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?o[a]=`${l??""}${c}`:o[a]=c}let s=i.find(a=>a.index===t);return s&&(s.version=r),i}var Co=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},yl=new Co(500);function Ei(i,e,t=0,n=yl){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let r=i.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let s=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}var vo=(i,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Oo(i,e,a,t,{strictMode:r,skipEarlyFail:s,treatAllFieldsOptional:o}),Mo(i,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},So=(i,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw hi(n)},Oo=(i,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let s=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=s.map((g,f)=>({field:g,index:f})).filter(({index:g})=>!l.has(g)),p,u,d=-1,m=0;for(let{index:g,field:f}of c){let x=`${(t.extractedFields.length===0?"":`
190
- `)+f.title}:`,A=Ei(n,x,t.s);if(A===-2||A===-3)return!0;if(A===-4)return t.inBlock=!0,!0;A>=0&&(d===-1||A<d)&&(d=A,m=x.length,p=g,u=f)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(f=>!f.isOptional);if(g)throw zn(g)}break}if(a&&u&&a.name!==u.name)throw zn(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),f=Jn(t.currField,g);f!==void 0&&(e[t.currField.name]=f),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,u!==void 0&&p!==void 0&&(t.currField=u,t.currFieldIndex=p),u&&!t.extractedFields.includes(u)&&t.extractedFields.push(u),u&&t.streamedIndex[u.name]===void 0&&(t.streamedIndex[u.name]=0)}},Mo=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,p=i.getOutputFields();for(let m of p){if(m.name===t.currField.name)continue;let g=`
191
- ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<c&&(c=f)}let u=n.substring(t.s,c).trim(),d=Jn(t.currField,u);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let u=i.getOutputFields().find(d=>!d.isOptional);if(u)throw zn(u)}if(bl(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?So(t,e,i.getOutputFields()):c||So(t,e,i.getOutputFields())}},bl=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let s=r[0];if(s){let a=`${s.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,p=`
192
- ${s.title}:`,u=t.indexOf(p,c),d=t.substring(c,u===-1?t.length:u).trim();if(d)try{let m=Jn(s,d);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
193
- `);for(let s of r){if(s.name in e)continue;let a=`${s.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let p=c.substring(a.length).trim();if(p)try{let u=Jn(s,p);if(u!==void 0){e[s.name]=u;break}}catch(u){if(!s.isOptional)throw u}break}}}},Pi=(i,e,t=!1)=>{switch(i.type?.name){case"code":return _i(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(i.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(i.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return vi(i,e,t);case"datetime":return Oi(i,e,t);case"class":{let n=e;if(i.type.options&&!i.type.options.includes(n)){if(i.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${i.type.options.join(", ")}`)}return n}default:return e}};function*Fi(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let p=r.streamedIndex[s]??0,u=p===0,d=(t<0?0:t)+p,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let f=u?g.trimStart():g;r.currField?.type?.name==="code"&&(f=f.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),f.length>0&&(yield{index:o,delta:{[s]:f}},r.streamedIndex[s]=p+g.length)}function*ko(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*Fi(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*Fi(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(c=>c.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let c=n.streamedIndex?.[s]??0,p=l.slice(c);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c+p.length);continue}n.streamedIndex[s]||(yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=1)}}function Jn(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw fi(i)}let t;if(i.type?.name==="json")try{let n=_i(e);return t=JSON.parse(n),t}catch(n){throw Ai(i,n.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=ki(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw xi(i,n.message)}try{if(Array.isArray(t)){for(let[n,r]of t.entries())if(r!==void 0){let o=typeof r=="string"?r.trim():r;t[n]=Pi(i,o,!0)}}else t=Pi(i,e)}catch(n){throw yi(i,e,n.message)}if(!(typeof t=="string"&&t===""))return t}var _i=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Eo(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});Ni(r.field,t,s,n)}}async function Po(i,e,t,n,r,o,s=!1){for(let a of i){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let c=a.process,p=await c(l,{sessionId:o,values:r,done:s});Ni(t.currField,n,p,o)}}var Ni=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=Il(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Il(i,e){let t=i.type?.name==="code",n=i.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*Di({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:c,value:p}=await l.read();if(c)break;let u=p;u.modelUsage&&(s=u.modelUsage);for(let d of u.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*Tl({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Rl({...r,state:c,debug:n});if(s){if(a.length){let c=Array.from(new Map(a.filter(p=>p.url).map(p=>[p.url,p])).values());s.citations=c}if(e.push(s),n&&r.logger){let c=structuredClone(s);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*Tl({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:p,asserts:u}){if(i.functionCalls&&i.functionCalls.length>0)yn(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){if(i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,delta:i.content,index:i.index},t),Oo(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;p.length!==0&&await yo(p,s.xstate,s.content),l.length!==0&&await Po(l,s.content,s.xstate,e,s.values,t),yield*ko(a,s.content,s.values,s.xstate,i.index),await Gn(u,s.values)}else i.thought&&i.thought.length>0&&(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}});if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
194
- Content: ${s.content}`)}async function*Rl({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:p,streamingAsserts:u,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:h,logger:x,debug:A,stopFunctionNames:y}){let I=h?void 0:Ro(t,i.functionCalls,i.values,n);if(I){if(!r)throw new Error("Functions are not defined");let T=await Wn({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:p,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...T]),i.functionCalls=[]}else{let T=h!==void 0;if(Mo(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:T,deferRequiredCheckForStreaming:!0,forceFinalize:!0}),h){let b=await h.processResults(i.values);if(b&&b.length>0){if(!r)throw new Error("Functions are not defined");let w=await Wn({ai:t,functionList:r,functionCalls:b,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:p,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...w]),o.updateResult({name:void 0,content:i.content,functionCalls:b.map(v=>({id:v.id,type:"function",function:{name:v.name,params:v.args}})),index:i.index},s);return}}await yo(u,i.xstate,i.content,!0),await Gn(d,i.values),m.length&&await Eo(m,i.values,o,s),g.length!==0&&await Po(g,i.content,i.xstate,o,i.values,s,!0),yield*ko(e,i.content,i.values,i.xstate,i.index)}}async function*$i({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:c,excludeContentFromTrace:p,asserts:u,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:h,debug:x,signatureToolCallingManager:A,stopFunctionNames:y,disableMemoryCleanup:I}){let T=e.results??[],b=A!==void 0;t.addResponse(T,n);let w=[];for(let E of T)if(Array.isArray(E?.citations))for(let R of E.citations)R?.url&&w.push({url:R.url,title:R.title,description:R.description,license:R.license,publicationDate:R.publicationDate,snippet:R.snippet});for(let E of T){let R=l[E.index];if(!R)throw new Error(`No state found for result (index: ${E.index})`);if(e.modelUsage){let $=Array.from(new Map(w.filter(S=>S.url).map(S=>[S.url,S])).values()),C={...e.modelUsage,...$.length?{citations:$}:{}};if(c.push(C),x&&h){let S=structuredClone(C);delete S.citations,h({name:"ChatResponseUsage",value:S}),C.citations&&C.citations.length>0&&h({name:"ChatResponseCitations",value:C.citations})}}if(A&&E.content){E.thought&&E.thought.length>0&&(R.values[m]=E.thought),vo(g,R.values,E.content,{strictMode:a,treatAllFieldsOptional:b});let C=(await A.processResults(R.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));C&&C.length>0&&t.updateResult({name:E.name,content:E.content,functionCalls:C,index:E.index},n)}if(E.functionCalls?.length){let $=Ro(i,E.functionCalls,R.values);if($&&$.length>0){if(!o)throw new Error("Functions are not defined");let C;try{C=await Wn({ai:i,functionList:o,functionCalls:$,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:p,index:E.index,functionResultFormatter:f,logger:h,debug:x,stopFunctionNames:y})}catch(S){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),S}R.functionsExecuted=new Set([...R.functionsExecuted,...C])}}else E.content&&(E.thought&&E.thought.length>0&&(R.values[m]=E.thought),vo(g,R.values,E.content,{strictMode:a,treatAllFieldsOptional:b}));if(await Gn(u,R.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Eo(d,R.values,t,n),E.finishReason==="length")throw new Error(`Max tokens reached before completion
195
- Content: ${E.content}`)}let v=l.map(E=>E.values);for(let E of v)for(let R of g.getOutputFields())R.isInternal&&delete E[R.name];let F=g.getOutputFields(),K=v.map((E,R)=>{let $={};for(let C of F)C.isInternal||($[C.name]=E[C.name]);return E[m]!==void 0&&($[m]=E[m]),{index:R,delta:$}});for(let E of K)yield E}function Li(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[o,s]of t.entries()){let a=e?Array.from(e).some(u=>s.functionsExecuted.has(u)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",p=r.tags?r.tags.some(u=>u==="processor"):!1;if(c&&e&&a||!(c||p))return!1}return!0}var rn=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var L=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Fo=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new L("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new L("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new L('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new L(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof L)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new L(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new L(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new L(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new L(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new L("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new L("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
196
- `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new L(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof L?r:new L(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new L(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof L?r:new L(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new L(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new L(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof L?o:new L(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new L(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new L(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new L(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(s==="audio"&&a)throw new L(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(s==="image")throw new L(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(s==="audio")throw new L(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(s){throw s instanceof L?s:new L(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(se.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let s=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new L(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new L(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new L(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new L(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new L(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new L("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new L(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new L(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(o,Math.min(this.position,o+20));throw new L(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new L(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Gi(i){return new Fo(i).parse()}var Yn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new le(e)}},xe=class i{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new i({...this,isOptional:!0})}array(){return new i({...this,isArray:!0})}internal(){return new i({...this,isInternal:!0})}},on=Object.assign(()=>new Yn,{string:i=>new xe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1}),number:i=>new xe({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1}),boolean:i=>new xe({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1}),json:i=>new xe({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1}),datetime:i=>new xe({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1}),date:i=>new xe({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1}),class:(i,e)=>new xe({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1}),image:i=>new xe({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1}),audio:i=>new xe({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1}),file:i=>new xe({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1}),url:i=>new xe({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1}),code:(i,e)=>new xe({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1})});function Qn(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var D=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},le=class i{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=Gi(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new D(`Invalid Signature: ${n.message}`,void 0,r)}throw new D(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof i)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new D("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new D("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof D?t:new D(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new D("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new i(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new D("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new D("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new D("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);ze(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new D(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new D(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ze(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new D(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new D(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new D("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ze(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new D("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return ze(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof D?t:new D(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new i(this);return n.addInputField({name:e,...Qn(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...Qn(t)},o=n.parseField(r);ze(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new D(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new D(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Qn(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...Qn(t)},o=n.parseField(r);ze(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new D(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new D(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ze(e,"input")}),this.getOutputFields().forEach(e=>{ze(e,"output")}),this.sigHash=hn("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Bi(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof D?e:new D(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ze(e,"input")}),this.getOutputFields().forEach(e=>{ze(e,"output")}),this.validateSignatureConsistency(),this.sigHash=hn("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Bi(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof D?e:new D(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new D(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new D(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new D(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new D("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new D("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function Ui(i){let e=i.name;return i.isOptional&&(e+="?"),i.isInternal&&(e+="!"),i.type&&(e+=`:${i.type.name}`,i.type.isArray&&(e+="[]"),i.type.name==="class"&&i.type.options&&(e+=` "${i.type.options.join(" | ")}"`)),i.description&&i.type?.name!=="class"&&(e+=` "${i.description}"`),e}function Bi(i,e,t){let n=i?`"${i}" `:"",r=e.map(Ui).join(", "),o=t.map(Ui).join(", ");return`${n}${r} -> ${o}`}function Cl(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ze(i,e){if(!i.name||i.name.length===0)throw new D("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Cl(i.name))throw new D(`Invalid field name '${i.name}' - must be camelCase or snake_case`,i.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(se.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(i.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new D(`Field name '${i.name}' is too generic`,i.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(i.name.length<2)throw new D(`Field name '${i.name}' is too short`,i.name,"Field names must be at least 2 characters long");if(i.name.length>50)throw new D(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&wl(i,e)}function wl(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new D(`${t.name} type is not supported in output fields`,i.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new D("Class type is not supported in input fields",i.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new D("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new D("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new D(`Invalid class option "${o}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new D("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new D("Arrays of code are not commonly supported",i.name,"Consider using a single code field or an array of strings instead");if(i.isInternal&&e==="input")throw new D("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields")}var lt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new le(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new rn,this.key={id:this.signature.hash()}}getSignature(){return new le(this.signature)}setSignature(e){this.signature=new le(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of o){let c=s[l.name];c!==void 0&&(Vn(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return nn(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var Sl=`
189
+ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Jn=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:o,span:s,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:p,debug:u,stopFunctionNames:d})=>{let m=new Wn(e),g=new Set,f=[],h=I=>{let T=v=>v.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),C=T(I),b=e.find(v=>v.name===I);return b||(b=e.find(v=>T(v.name)===C)),b},x=t.map(I=>{if(!I.id)throw new Error(`Function ${I.name} did not return an ID`);let T=i.getOptions().tracer??ie.tracer;return T?T.startActiveSpan(`Tool: ${I.name}`,async C=>{try{C?.setAttributes?.({"tool.name":I.name,"tool.mode":"native","function.id":I.id,"session.id":r??""});let{formatted:b,rawResult:v,parsedArgs:P}=await m.executeWithDetails(I,{sessionId:r,ai:i,functionResultFormatter:c,traceId:C?.spanContext?.().traceId??o,stopFunctionNames:d});if(g.add(I.name.toLowerCase()),d?.includes(I.name.toLowerCase())){let K=h(I.name);K&&f.push({func:K,args:P,result:v})}if(a?C.addEvent("gen_ai.tool.message",{name:I.name}):C.addEvent("gen_ai.tool.message",{name:I.name,args:I.args,result:b??""}),s){let K={name:I.name};a||(K.args=I.args,K.result=b??""),s.addEvent("function.call",K)}return{result:b??"",role:"function",functionId:I.id,index:l}}catch(b){if(C?.recordException?.(b),b instanceof rn){let v=b.getFixingInstructions(),P={name:I.name,message:b.toString()};return a||(P.args=I.args,P.fixing_instructions=v),C?.addEvent?.("function.error",P),u&&vr(b,l,v,p),{functionId:I.id,isError:!0,index:l,result:v,role:"function"}}throw b}finally{C?.end?.()}}):m.executeWithDetails(I,{sessionId:r,ai:i,functionResultFormatter:c,traceId:o,stopFunctionNames:d}).then(({formatted:C,rawResult:b,parsedArgs:v})=>{if(g.add(I.name.toLowerCase()),d?.includes(I.name.toLowerCase())){let P=h(I.name);P&&f.push({func:P,args:v,result:b})}if(s){let P={name:I.name};a||(P.args=I.args,P.result=C??""),s.addEvent("function.call",P)}return{result:C??"",role:"function",functionId:I.id,index:l}}).catch(C=>{if(!(C instanceof rn))throw C;let b=C.getFixingInstructions();if(s){let v={name:I.name,message:C.toString()};a||(v.args=I.args,v.fixing_instructions=b),s.addEvent("function.error",v)}return u&&vr(C,l,b,p),{functionId:I.id,isError:!0,index:l,result:b,role:"function"}})}),y=(await Promise.all(x)).map(I=>I.result===void 0||I.result===""?{...I,result:"done"}:I);if(n.addFunctionResults(y,r),u){let I=y.filter(T=>!T.isError);I.length>0&&Rs(I,p)}if(f.length>0)throw new bt(f);return g};function So(i,e,t,n){if(!e||e.length===0)return;if(!i.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(o=>({id:o.id,name:o.function.name,args:o.function.params}))}function Ni(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(s=>"toFunction"in s?s.toFunction():s).flat(),functionCall:r}:{functions:[],functionCall:r}}import ct from"dayjs";import Cl from"dayjs/plugin/customParseFormat.js";import Rl from"dayjs/plugin/timezone.js";import wl from"dayjs/plugin/utc.js";ct.extend(wl);ct.extend(Rl);ct.extend(Cl);function Di(i,e,t=!1){try{return Sl(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw ki(i,e,r)}}function Sl(i){if(!ct(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return ct.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function $i(i,e,t=!1){try{return vl(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw Mi(i,e,r)}}function vl(i){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=i.match(e);if(!t)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');let[,n,r]=t;if(!n||!r)throw new Error('Invalid date and time format. Please provide the date and time in "YYYY-MM-DD HH:mm" or "YYYY-MM-DD HH:mm:ss" format, followed by the timezone.');try{let o=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",s=ct.tz(n,o,r);if(!s.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return s.utc().toDate()}catch{throw new Error(`Unrecognized time zone ${r}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var Gi=i=>ct(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var Vm=new be,Qn=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(c,p)=>{switch(c){case"class":return typeof p=="string";case"code":return typeof p=="string";case"string":return typeof p=="string";case"number":return typeof p=="number";case"boolean":return typeof p=="boolean";case"date":return p instanceof Date||typeof p=="string";case"datetime":return p instanceof Date||typeof p=="string";case"json":return typeof p=="object"||typeof p=="string";default:return!1}},r=c=>!(!c||typeof c!="object"||!("mimeType"in c)||!("data"in c));if(i.type?.name==="image"){let c;if(Array.isArray(e)){for(let p of e)if(!r(p)){c="object ({ mimeType: string; data: string })";break}}else r(e)||(c="object ({ mimeType: string; data: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let o=c=>!(!c||typeof c!="object"||!("data"in c));if(i.type?.name==="audio"){let c;if(Array.isArray(e)){for(let p of e)if(!o(p)){c="object ({ data: string; format?: string })";break}}else o(e)||(c="object ({ data: string; format?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let s=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let p="data"in c,u="fileUri"in c;return!(!p&&!u||p&&u)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let p of e)if(!s(p)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else s(e)||(c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let a=c=>typeof c=="string"?!0:!(!c||typeof c!="object"||!("url"in c));if(i.type?.name==="url"){let c;if(Array.isArray(e)){for(let p of e)if(!a(p)){c="string or object ({ url: string; title?: string; description?: string })";break}}else a(e)||(c="string or object ({ url: string; title?: string; description?: string })");if(c)throw new Error(`Validation failed: Expected '${i.name}' to be type '${c}' instead got '${e}'`);return}let l=!0;if(t.isArray){if(!Array.isArray(e))l=!1;else for(let c of e)if(!n(t.name,c)){l=!1;break}}else l=n(t.name,e);if(!l){let c=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${i.name}' to be a ${i.type?.isArray?"an array of ":""}${t.name} instead got '${c}' (${JSON.stringify(e)})`)}};function on(i){let e={};for(let t of i){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let r=e[n];if(r){let o=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};o.promptTokens+=t?.tokens?.promptTokens??0,o.completionTokens+=t?.tokens?.completionTokens??0,o.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=o;let s=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(s.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(s.push(c),l.add(c.url));r.citations=s}}}return Object.values(e)}var Li=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
190
+ `),r=[];for(let o of n){let s=o.trim();if(s){if(s[0]&&e.has(s[0]))r.push(s.slice(1).trim());else if(t.test(s))r.push(s.replace(t,"").trim());else if(r.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(r.length===0)throw new Error("Could not parse markdown list: no valid list items found");return r};function Oo(i,e){let{index:t,delta:n,version:r}=e,o=i.find(a=>a.index===t)?.delta;if(!o)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=o[a],c=n[a];l===void 0&&Array.isArray(c)?o[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?o[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?o[a]=`${l??""}${c}`:o[a]=c}let s=i.find(a=>a.index===t);return s&&(s.version=r),i}var vo=class{cache=new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let n=this.cache.keys().next().value;n&&this.cache.delete(n)}this.cache.set(e,t)}},Ol=new vo(500);function Ui(i,e,t=0,n=Ol){if(/^```[a-zA-Z]*\s*$/.test(i))return-4;if(/^[\s`]*$/.test(i))return-3;let r=i.indexOf(e,t);if(r!==-1)return r;let o=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,o);let s=-1;for(let a=o.length-1;a>=0;a--){let l=o[a];if(i.endsWith(l)){s=a;break}}return s>=0?-2:-1}var Mo=(i,e,t,n)=>{let r=n?.strictMode??!1,o=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Eo(i,e,a,t,{strictMode:r,skipEarlyFail:s,treatAllFieldsOptional:o}),Po(i,e,a,t,{strictMode:r,treatAllFieldsOptional:o,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},ko=(i,e,t)=>{let n=[];for(let r of t)r&&!r.isOptional&&e[r.name]===void 0&&n.push(r);if(n.length>0)throw Ri(n)},Eo=(i,e,t,n,{strictMode:r,skipEarlyFail:o}={})=>{let s=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=s.map((g,f)=>({field:g,index:f})).filter(({index:g})=>!l.has(g)),p,u,d=-1,m=0;for(let{index:g,field:f}of c){let x=`${(t.extractedFields.length===0?"":`
191
+ `)+f.title}:`,A=Ui(n,x,t.s);if(A===-2||A===-3)return!0;if(A===-4)return t.inBlock=!0,!0;A>=0&&(d===-1||A<d)&&(d=A,m=x.length,p=g,u=f)}if(d===-1){if(o)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(f=>!f.isOptional);if(g)throw Hn(g)}break}if(a&&u&&a.name!==u.name)throw Hn(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,d).trim(),f=Yn(t.currField,g);f!==void 0&&(e[t.currField.name]=f),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:d}):t.prevFields=[{field:t.currField,s:t.s,e:d}]}t.s=d+m,u!==void 0&&p!==void 0&&(t.currField=u,t.currFieldIndex=p),u&&!t.extractedFields.includes(u)&&t.extractedFields.push(u),u&&t.streamedIndex[u.name]===void 0&&(t.streamedIndex[u.name]=0)}},Po=(i,e,t,n,r)=>{let o=r?.strictMode??!1,s=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,p=i.getOutputFields();for(let m of p){if(m.name===t.currField.name)continue;let g=`
192
+ ${m.title}:`,f=n.indexOf(g,t.s);f!==-1&&f<c&&(c=f)}let u=n.substring(t.s,c).trim(),d=Yn(t.currField,u);d!==void 0&&(e[t.currField.name]=d)}if(o&&!t.currField&&t.extractedFields.length===0&&n.trim()){let u=i.getOutputFields().find(d=>!d.isOptional);if(u)throw Hn(u)}if(kl(i,e,n,t),!s){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;o||l?ko(t,e,i.getOutputFields()):c||ko(t,e,i.getOutputFields())}},kl=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let s=r[0];if(s){let a=`${s.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,p=`
193
+ ${s.title}:`,u=t.indexOf(p,c),d=t.substring(c,u===-1?t.length:u).trim();if(d)try{let m=Yn(s,d);if(m!==void 0){e[s.name]=m;return}}catch{}}}}let o=t.split(`
194
+ `);for(let s of r){if(s.name in e)continue;let a=`${s.title}:`;for(let l of o){let c=l.trim();if(c.startsWith(a)){let p=c.substring(a.length).trim();if(p)try{let u=Yn(s,p);if(u!==void 0){e[s.name]=u;break}}catch(u){if(!s.isOptional)throw u}break}}}},Bi=(i,e,t=!1)=>{switch(i.type?.name){case"code":return zi(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(i.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(i.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return Di(i,e,t);case"datetime":return $i(i,e,t);case"class":{let n=e;if(i.type.options&&!i.type.options.includes(n)){if(i.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${i.type.options.join(", ")}`)}return n}default:return e}};function*qi(i,e,t,n,r,o){let{name:s,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let p=r.streamedIndex[s]??0,u=p===0,d=(t<0?0:t)+p,m=i.substring(d,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let f=u?g.trimStart():g;r.currField?.type?.name==="code"&&(f=f.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),f.length>0&&(yield{index:o,delta:{[s]:f}},r.streamedIndex[s]=p+g.length)}function*Fo(i,e,t,n,r){for(let s of n.prevFields??[]){let{field:a,s:l,e:c}=s;yield*qi(e,a,l,c,n,r)}if(n.prevFields=void 0,n.inAssumedField&&!(i.getOutputFields().filter(l=>!l.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*qi(e,n.currField,n.s,e.length,n,r);let o=i.getOutputFields();for(let s of Object.keys(t)){let a=o.find(c=>c.name===s);if(!a||a.isInternal)continue;let l=t[s];if(Array.isArray(l)){let c=n.streamedIndex?.[s]??0,p=l.slice(c);p&&p.length>0&&(yield{index:r,delta:{[s]:p}},n.streamedIndex[s]=c+p.length);continue}n.streamedIndex[s]||(yield{index:r,delta:{[s]:l}},n.streamedIndex[s]=1)}}function Yn(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw wi(i)}let t;if(i.type?.name==="json")try{let n=zi(e);return t=JSON.parse(n),t}catch(n){throw Si(i,n.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=Li(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw vi(i,n.message)}try{if(Array.isArray(t)){for(let[n,r]of t.entries())if(r!==void 0){let o=typeof r=="string"?r.trim():r;t[n]=Bi(i,o,!0)}}else t=Bi(i,e)}catch(n){throw Oi(i,e,n.message)}if(!(typeof t=="string"&&t===""))return t}var zi=i=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function _o(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let o=r.process,s=await o(e[r.field.name],{sessionId:n,values:e,done:!0});ji(r.field,t,s,n)}}async function No(i,e,t,n,r,o,s=!1){for(let a of i){if(t.currField?.name!==a.field.name)continue;let l=e.substring(t.s);t.currField?.type?.name==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let c=a.process,p=await c(l,{sessionId:o,values:r,done:s});ji(t.currField,n,p,o)}}var ji=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(s,a)=>typeof a=="bigint"?Number(a):a,2),o=Ml(i,r);e.addRequest([{role:"user",content:[{type:"text",text:o}]}],n),e.addTag("processor",n)};function Ml(i,e){let t=i.type?.name==="code",n=i.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*Hi({res:i,usage:e,states:t,debug:n,...r}){let o=(r.ai.getFeatures().functionCot??!1)&&r.functions!==void 0&&r.functions.length>0,s,a=[],l=i.getReader();try{for(;;){let{done:c,value:p}=await l.read();if(c)break;let u=p;u.modelUsage&&(s=u.modelUsage);for(let d of u.results){if(Array.isArray(d.citations))for(let g of d.citations)g?.url&&a.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!d.content||d.content==="")&&(!d.thought||d.thought==="")&&(!d.functionCalls||d.functionCalls.length===0))continue;let m=t.find(g=>g.index===d.index);if(!m)throw new Error(`No state found for result (index: ${d.index})`);yield*El({...r,result:d,skipEarlyFail:o,state:m,debug:n})}}}finally{l.releaseLock()}for(let c of t)yield*Pl({...r,state:c,debug:n});if(s){if(a.length){let c=Array.from(new Map(a.filter(p=>p.url).map(p=>[p.url,p])).values());s.citations=c}if(e.push(s),n&&r.logger){let c=structuredClone(s);delete c.citations,r.logger({name:"ChatResponseUsage",value:c}),s.citations&&s.citations.length>0&&r.logger({name:"ChatResponseCitations",value:s.citations})}}}async function*El({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o,state:s,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:p,asserts:u}){if(i.functionCalls&&i.functionCalls.length>0)In(s.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:s.functionCalls,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){if(i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),s.content+=i.content,e.updateResult({name:i.name,content:s.content,delta:i.content,index:i.index},t),Eo(a,s.values,s.xstate,s.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:o}))return;p.length!==0&&await To(p,s.xstate,s.content),l.length!==0&&await No(l,s.content,s.xstate,e,s.values,t),yield*Fo(a,s.content,s.values,s.xstate,i.index),await Bn(u,s.values)}else i.thought&&i.thought.length>0&&(s.values[c]=(s.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}});if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
195
+ Content: ${s.content}`)}async function*Pl({state:i,signature:e,ai:t,model:n,functions:r,mem:o,sessionId:s,traceId:a,span:l,strictMode:c,excludeContentFromTrace:p,streamingAsserts:u,asserts:d,fieldProcessors:m,streamingFieldProcessors:g,functionResultFormatter:f,signatureToolCallingManager:h,logger:x,debug:A,stopFunctionNames:y}){let I=h?void 0:So(t,i.functionCalls,i.values,n);if(I){if(!r)throw new Error("Functions are not defined");let T=await Jn({ai:t,functionList:r,functionCalls:I,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:p,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...T]),i.functionCalls=[]}else{let T=h!==void 0;if(Po(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:T,deferRequiredCheckForStreaming:!0,forceFinalize:!0}),h){let C=await h.processResults(i.values);if(C&&C.length>0){if(!r)throw new Error("Functions are not defined");let b=await Jn({ai:t,functionList:r,functionCalls:C,mem:o,sessionId:s,traceId:a,span:l,index:i.index,excludeContentFromTrace:p,functionResultFormatter:f,logger:x,debug:A,stopFunctionNames:y});i.functionsExecuted=new Set([...i.functionsExecuted,...b]),o.updateResult({name:void 0,content:i.content,functionCalls:C.map(v=>({id:v.id,type:"function",function:{name:v.name,params:v.args}})),index:i.index},s);return}}await To(u,i.xstate,i.content,!0),await Bn(d,i.values),m.length&&await _o(m,i.values,o,s),g.length!==0&&await No(g,i.content,i.xstate,o,i.values,s,!0),yield*Fo(e,i.content,i.values,i.xstate,i.index)}}async function*Ki({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:o,span:s,strictMode:a,states:l,usage:c,excludeContentFromTrace:p,asserts:u,fieldProcessors:d,thoughtFieldName:m,signature:g,functionResultFormatter:f,logger:h,debug:x,signatureToolCallingManager:A,stopFunctionNames:y,disableMemoryCleanup:I}){let T=e.results??[],C=A!==void 0;t.addResponse(T,n);let b=[];for(let O of T)if(Array.isArray(O?.citations))for(let w of O.citations)w?.url&&b.push({url:w.url,title:w.title,description:w.description,license:w.license,publicationDate:w.publicationDate,snippet:w.snippet});for(let O of T){let w=l[O.index];if(!w)throw new Error(`No state found for result (index: ${O.index})`);if(e.modelUsage){let _=Array.from(new Map(b.filter(S=>S.url).map(S=>[S.url,S])).values()),R={...e.modelUsage,..._.length?{citations:_}:{}};if(c.push(R),x&&h){let S=structuredClone(R);delete S.citations,h({name:"ChatResponseUsage",value:S}),R.citations&&R.citations.length>0&&h({name:"ChatResponseCitations",value:R.citations})}}if(A&&O.content){O.thought&&O.thought.length>0&&(w.values[m]=O.thought),Mo(g,w.values,O.content,{strictMode:a,treatAllFieldsOptional:C});let R=(await A.processResults(w.values))?.map(S=>({id:S.id,type:"function",function:{name:S.name,params:S.args}}));R&&R.length>0&&t.updateResult({name:O.name,content:O.content,functionCalls:R,index:O.index},n)}if(O.functionCalls?.length){let _=So(i,O.functionCalls,w.values);if(_&&_.length>0){if(!o)throw new Error("Functions are not defined");let R;try{R=await Jn({ai:i,functionList:o,functionCalls:_,mem:t,sessionId:n,traceId:r,span:s,excludeContentFromTrace:p,index:O.index,functionResultFormatter:f,logger:h,debug:x,stopFunctionNames:y})}catch(S){throw t.addRequest([{role:"user",content:"The previous tool call failed. Fix arguments and try again, ensuring required fields match schema."}],n),t.addTag("correction",n),S}w.functionsExecuted=new Set([...w.functionsExecuted,...R])}}else O.content&&(O.thought&&O.thought.length>0&&(w.values[m]=O.thought),Mo(g,w.values,O.content,{strictMode:a,treatAllFieldsOptional:C}));if(await Bn(u,w.values),I||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await _o(d,w.values,t,n),O.finishReason==="length")throw new Error(`Max tokens reached before completion
196
+ Content: ${O.content}`)}let v=l.map(O=>O.values);for(let O of v)for(let w of g.getOutputFields())w.isInternal&&delete O[w.name];let P=g.getOutputFields(),K=v.map((O,w)=>{let _={};for(let R of P)R.isInternal||(_[R.name]=O[R.name]);return O[m]!==void 0&&(_[m]=O[m]),{index:w,delta:_}});for(let O of K)yield O}function Wi(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[o,s]of t.entries()){let a=e?Array.from(e).some(u=>s.functionsExecuted.has(u)):!1;if(!r.chat[o])throw new Error(`No chat message found for result (index: ${o})`);let c=r.role==="function",p=r.tags?r.tags.some(u=>u==="processor"):!1;if(c&&e&&a||!(c||p))return!1}return!0}var sn=class{reg;constructor(){this.reg=new Set}register(e){this.reg.add(e)}*[Symbol.iterator](){let e=Array.from(this.reg);for(let t=0;t<e.length;t++)yield e[t]}};var L=class extends Error{constructor(t,n,r,o){super(t);this.position=n;this.context=r;this.suggestion=o;this.name="SignatureValidationError"}},Do=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new L("Empty signature provided",0,"",'A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"')}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection="inputs";let t=this.parseFieldList(this.parseInputField.bind(this),"input");if(this.skipWhitespace(),this.position>=this.input.length)throw new L("Incomplete signature: Missing output section",this.position,this.getErrorContext(),'Add "->" followed by output fields. Example: "-> responseText:string"');if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new L('Incomplete signature: No output fields specified after "->"',this.position,this.getErrorContext(),'Add at least one output field. Example: "-> responseText:string"');this.currentSection="outputs";let n=this.parseFieldList(this.parseOutputField.bind(this),"output");if(this.skipWhitespace(),this.position<this.input.length){let r=this.input.slice(this.position);throw new L(`Unexpected content after signature: "${r}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){if(e instanceof L)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new L(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new L(`Duplicate input field name: "${r.name}"`,0,"","Each field name must be unique within the signature");t.add(r.name)}let n=new Set;for(let r of e.outputs){if(n.has(r.name))throw new L(`Duplicate output field name: "${r.name}"`,0,"","Each field name must be unique within the signature");n.add(r.name)}for(let r of e.outputs)if(t.has(r.name))throw new L(`Field name "${r.name}" appears in both inputs and outputs`,0,"","Use different names for input and output fields to avoid confusion");if(e.inputs.length===0)throw new L("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new L("Signature must have at least one output field",0,"",'Add an output field after "->". Example: "... -> responseText:string"')}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),o=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${o}`].join(`
197
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new L(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t==="input"?"userInput:string":"responseText:string"}`);try{n.push(e())}catch(r){throw r instanceof L?r:new L(`Invalid first ${t} field: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]==="-"&&this.position+1<this.input.length&&this.input[this.position+1]===">");)if(this.match(",")){if(this.skipWhitespace(),this.position>=this.input.length)throw new L(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(r){throw r instanceof L?r:new L(`Invalid ${t} field after comma: ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace()}else break;return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"input");let t;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!"))throw new L(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),"Internal markers (!) are only allowed on output fields");break}let n;if(this.skipWhitespace(),this.match(":")){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new L(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),'Class types are only allowed on output fields. Use "string" type for input classifications');try{let o=this.parseTypeNotClass(),s=this.match("[]");n={name:o,isArray:s}}catch(o){throw o instanceof L?o:new L(`Input field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:r?.trim(),type:n,isOptional:t}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,"output");let t=!1,n=!1;for(;;){if(this.match("?")){t=!0;continue}if(this.match("!")){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let s=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new L(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),'Add class names in quotes. Example: class "positive, negative, neutral"');let l=a.split(/[,|]/).map(c=>c.trim()).filter(c=>c.length>0);if(l.length===0)throw new L(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:s,options:l}}else try{let s=this.parseTypeNotClass(),a=this.match("[]");if(r={name:s,isArray:a},s==="image"&&a)throw new L(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(s==="audio"&&a)throw new L(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(s==="image")throw new L(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),"Image types can only be used in input fields");if(s==="audio")throw new L(`Output field "${e}": Audio type is not supported in output fields`,this.position,this.getErrorContext(),"Audio types can only be used in input fields")}catch(s){throw s instanceof L?s:new L(`Output field "${e}": ${s instanceof Error?s.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:o?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(ie.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(e.toLowerCase())){let s=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new L(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${s.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new L(`Invalid field name "${e}"`,this.position,this.getErrorContext(),'Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(e.length<2)throw new L(`Field name "${e}" is too short`,this.position,this.getErrorContext(),"Field names must be at least 2 characters long");if(e.length>50)throw new L(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),"Field names should be 50 characters or less")}parseTypeNotClass(){let e=["string","number","boolean","json","image","audio","file","url","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),o=`Invalid type "${n||"empty"}"`,s=r?`. Did you mean "${r}"?`:"",a=`${o}${s}`;throw new L(a,this.position,this.getErrorContext(),`Expected one of: ${e.join(", ")}`)}return t}suggestType(e){return{str:"string",text:"string",int:"number",integer:"number",float:"number",double:"number",bool:"boolean",object:"json",dict:"json",timestamp:"datetime",time:"datetime",img:"image",picture:"image",sound:"audio",voice:"audio",classification:"class",category:"class"}[e.toLowerCase()]||null}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:"";throw n===""?new L("Expected field name but found end of input",this.position,this.getErrorContext(),"Add a field name. Field names must start with a letter or underscore"):/^\d/.test(n)?new L(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),'Field names must start with a letter or underscore. Example: "userInput" or "_internal"'):new L(`Invalid field name "${n}"`,this.position,this.getErrorContext(),"Field names must start with a letter or underscore and contain only letters, numbers, or underscores")}parseParsedString(){let e=["'",'"'];for(let t of e)if(this.match(t)){let n="",r=!1,o=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,r)n+=a,r=!1;else if(a==="\\")r=!0;else{if(a===t)return n;n+=a}}let s=this.input.slice(o,Math.min(this.position,o+20));throw new L(`Unterminated string starting at position ${o}`,o,this.getErrorContext(),`Add closing ${t} to complete the string: ${s}${t}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e=="string"){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match("->")){let e=this.input.slice(this.position,this.position+10),t=e.includes(">")?'Use "->" (dash followed by greater-than)':e.includes("-")?'Add ">" after the dash':'Add "->" to separate input and output fields';throw new L(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Vi(i){return new Do(i).parse()}var Zn=class{inputFields=[];outputFields=[];desc;input(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n=!1){let r={name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0};return n?this.outputFields.unshift(r):this.outputFields.push(r),this}description(e){return this.desc=e,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields};return new pe(e)}},Ie=class i{type;isArray;options;description;isOptional;isInternal;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.isOptional=e.isOptional,this.isInternal=e.isInternal}optional(){return new i({...this,isOptional:!0})}array(){return new i({...this,isArray:!0})}internal(){return new i({...this,isInternal:!0})}},re=Object.assign(()=>new Zn,{string:i=>new Ie({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1}),number:i=>new Ie({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1}),boolean:i=>new Ie({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1}),json:i=>new Ie({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1}),datetime:i=>new Ie({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1}),date:i=>new Ie({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1}),class:(i,e)=>new Ie({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1}),image:i=>new Ie({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1}),audio:i=>new Ie({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1}),file:i=>new Ie({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1}),url:i=>new Ie({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1}),code:(i,e)=>new Ie({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1})});function Xn(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var $=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},pe=class i{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(e){if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=Vi(e)}catch(n){if(n instanceof Error){let r="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new $(`Invalid Signature: ${n.message}`,void 0,r)}throw new $(`Invalid Signature: ${e}`,void 0,'Please check the signature format. Example: "userInput:string -> responseText:string"')}this.description=t.desc,this.inputFields=t.inputs.map(n=>this.parseParsedField(n)),this.outputFields=t.outputs.map(n=>this.parseParsedField(n)),[this.sigHash,this.sigString]=this.updateHash()}else if(e instanceof i)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new $("Invalid signature object: missing inputs or outputs",void 0,'Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }');if(!Array.isArray(e.inputs)||!Array.isArray(e.outputs))throw new $("Invalid signature object: inputs and outputs must be arrays",void 0,'Both "inputs" and "outputs" must be arrays of AxField objects');try{this.description=e.description,this.inputFields=e.inputs.map(t=>this.parseField(t)),this.outputFields=e.outputs.map(t=>this.parseField(t)),[this.sigHash,this.sigString]=this.updateHash()}catch(t){throw t instanceof $?t:new $(`Failed to create signature from object: ${t instanceof Error?t.message:"Unknown error"}`,void 0,"Check that all fields in inputs and outputs arrays are valid AxField objects")}}else throw new $("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}static create(e){return new i(e)}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new $("Field name is required",e.name,'Every field must have a descriptive name. Example: "userInput", "responseText"');let t=this.toTitle(e.name);return{name:e.name,title:t,description:"desc"in e?e.desc:void 0,type:e.type??{name:"string",isArray:!1},..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new $("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, datetime, class, code");return{...e,title:t}};setDescription=e=>{if(typeof e!="string")throw new $("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);je(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new $(`Duplicate input field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.outputFields)if(n.name===t.name)throw new $(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof $?t:new $(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);je(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new $(`Duplicate output field name: "${t.name}"`,t.name,"Each field name must be unique within the signature");for(let n of this.inputFields)if(n.name===t.name)throw new $(`Field name "${t.name}" appears in both inputs and outputs`,t.name,"Use different names for input and output fields to avoid confusion");this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof $?t:new $(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new $("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return je(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof $?t:new $(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new $("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let r=this.parseField(n);return je(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof $?t:new $(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(e,t)=>{let n=new i(this);return n.addInputField({name:e,...Xn(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...Xn(t)},o=n.parseField(r);je(o,"input");for(let s of n.inputFields)if(s.name===o.name)throw new $(`Duplicate input field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.outputFields)if(s.name===o.name)throw new $(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Xn(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...Xn(t)},o=n.parseField(r);je(o,"output");for(let s of n.outputFields)if(s.name===o.name)throw new $(`Duplicate output field name: "${o.name}"`,o.name,"Each field name must be unique within the signature");for(let s of n.inputFields)if(s.name===o.name)throw new $(`Field name "${o.name}" appears in both inputs and outputs`,o.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(o),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0};toTitle=e=>{let t=e.replace(/_/g," ");return t=t.replace(/([A-Z]|[0-9]+)/g," $1").trim(),t.charAt(0).toUpperCase()+t.slice(1)};toJSONSchema=()=>{let e={},t=[];for(let r of this.inputFields){let o=r.type?r.type.name:"string";r.type?.isArray?e[r.name]={description:r.description,type:"array",items:{type:o,description:r.description}}:e[r.name]={description:r.description,type:o},r.isOptional||t.push(r.name)}return{type:"object",properties:e,required:t}};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{je(e,"input")}),this.getOutputFields().forEach(e=>{je(e,"output")}),this.sigHash=An("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Qi(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof $?e:new $(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{je(e,"input")}),this.getOutputFields().forEach(e=>{je(e,"output")}),this.validateSignatureConsistency(),this.sigHash=An("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Qi(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof $?e:new $(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};validateSignatureConsistency(){let e=new Set;for(let n of this.inputFields){if(e.has(n.name))throw new $(`Duplicate input field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");e.add(n.name)}let t=new Set;for(let n of this.outputFields){if(t.has(n.name))throw new $(`Duplicate output field name: "${n.name}"`,n.name,"Each field name must be unique within the signature");t.add(n.name)}for(let n of this.outputFields)if(e.has(n.name))throw new $(`Field name "${n.name}" appears in both inputs and outputs`,n.name,"Use different names for input and output fields to avoid confusion");if(this.inputFields.length===0)throw new $("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new $("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})};function Ji(i){let e=i.name;return i.isOptional&&(e+="?"),i.isInternal&&(e+="!"),i.type&&(e+=`:${i.type.name}`,i.type.isArray&&(e+="[]"),i.type.name==="class"&&i.type.options&&(e+=` "${i.type.options.join(" | ")}"`)),i.description&&i.type?.name!=="class"&&(e+=` "${i.description}"`),e}function Qi(i,e,t){let n=i?`"${i}" `:"",r=e.map(Ji).join(", "),o=t.map(Ji).join(", ");return`${n}${r} -> ${o}`}function Fl(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function je(i,e){if(!i.name||i.name.length===0)throw new $("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Fl(i.name))throw new $(`Invalid field name '${i.name}' - must be camelCase or snake_case`,i.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(ie.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(i.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new $(`Field name '${i.name}' is too generic`,i.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(i.name.length<2)throw new $(`Field name '${i.name}' is too short`,i.name,"Field names must be at least 2 characters long");if(i.name.length>50)throw new $(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&_l(i,e)}function _l(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file"||t.name==="url")&&e==="output")throw new $(`${t.name} type is not supported in output fields`,i.name,`${t.name} types can only be used in input fields`);if(t.name==="class"){if(e==="input")throw new $("Class type is not supported in input fields",i.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new $("Class type requires options",i.name,'Provide class options. Example: class "positive, negative, neutral"');for(let r of t.options){if(!r||r.trim().length===0)throw new $("Empty class option found",i.name,"All class options must be non-empty strings");let o=r.trim();if(o.includes(",")||o.includes("|"))throw new $(`Invalid class option "${o}"`,i.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(r=>r.trim().toLowerCase())).size!==t.options.length)throw new $("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new $("Arrays of code are not commonly supported",i.name,"Consider using a single code field or an array of strings instead");if(i.isInternal&&e==="input")throw new $("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields")}var pt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new pe(e),t?.description&&this.signature.setDescription(t.description),t?.traceLabel&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=this.signature?.hash(),this.children=new sn,this.key={id:this.signature.hash()}}getSignature(){return new pe(this.signature)}setSignature(e){this.signature=new pe(e),e&&this.signature.validate(),this.updateSignatureHash()}setDescription(e){this.signature.setDescription(e),this.updateSignatureHash()}updateSignatureHash(){this.sigHash=this.signature.hash(),this.key={id:this.signature.hash()}}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))t?.setParentId(e)}setParentId(e){this.key.custom||(this.key.id=[e,this.key.id].join("/"))}setExamples(e,t){if(this._setExamples(e,t),"programId"in e)for(let n of Array.from(this.children))n?.setExamples(e,t)}_setExamples(e,t){let n=[];if("programId"in e&&e.programId===this.key.id&&(n=e.traces),Array.isArray(e)&&(n=e),n){this.examplesOptions=t;let r=this.signature,o=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(s=>{let a={};for(let l of o){let c=s[l.name];c!==void 0&&(Qn(l,c),a[l.name]=c)}return a})}}getTraces(){let e=[];this.trace&&e.push({trace:this.trace,programId:this.key.id});for(let t of Array.from(this.children)){let n=t?.getTraces();e=[...e,...n??[]]}return e}getUsage(){let e=[...this.usage??[]];for(let t of Array.from(this.children)){let n=t?.getUsage();e=[...e,...n??[]]}return on(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))e?.resetUsage()}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(r=>r.programId===this.key.id);if(t&&!n)throw new Error(`Program with id '${this.key.id}' has children but no matching programId found in demos`);this.demos=e.filter(r=>r.programId===this.key.id).map(r=>r.traces).flat();for(let r of Array.from(this.children))r?.setDemos(e)}applyOptimization(e){e.applyTo(this);for(let t of Array.from(this.children))t&&"applyOptimization"in t&&typeof t.applyOptimization=="function"&&t.applyOptimization(e)}};var Nl=`
197
198
  ## Function Call Instructions
198
- - Complete the task, using the functions defined earlier in this prompt.
199
+ - Complete the task, using the functions defined earlier in this prompt.
199
200
  - Output fields should only be generated after all functions have been called.
200
- - Use the function results to generate the output fields.`,vl=`
201
+ - Use the function results to generate the output fields.`,Dl=`
201
202
  ## Strict Output Formatting Rules
202
203
  - No formatting rules should override these **Strict Output Formatting Rules**
203
204
  - Output must strictly follow the defined plain-text \`field name: value\` field format.
204
205
  - Output field, values must strictly adhere to the specified output field formatting rules.
205
206
  - Do not include fields with empty, unknown, or placeholder values.
206
207
  - Do not add any text before or after the output fields, just the field name and value.
207
- - Do not use code blocks.`,yt=class{sig;fieldTemplates;task;thoughtFieldName;functions;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions;let r=[],o=qi(this.sig.getInputFields()),s=qi(this.sig.getOutputFields());r.push(`You will be provided with the following fields: ${o}. Your task is to generate new fields: ${s}.`);let l=this.functions?.map(d=>"toFunction"in d?d.toFunction():d)?.flat()?.map(d=>`- \`${d.name}\`: ${Xn(d.description)}`).join(`
208
+ - Do not use code blocks.`,It=class{sig;fieldTemplates;task;thoughtFieldName;functions;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions;let r=[],o=Yi(this.sig.getInputFields()),s=Yi(this.sig.getOutputFields());r.push(`You will be provided with the following fields: ${o}. Your task is to generate new fields: ${s}.`);let l=this.functions?.map(d=>"toFunction"in d?d.toFunction():d)?.flat()?.map(d=>`- \`${d.name}\`: ${er(d.description)}`).join(`
208
209
  `);l&&l.length>0&&r.push(`## Available Functions
209
- ${l}`);let c=Ol(this.sig.getInputFields());r.push(`## Input Fields
210
- ${c}`);let p=Ml(this.sig.getOutputFields());r.push(`## Output Fields
211
- ${p}`),l&&l.length>0&&r.push(Sl.trim()),r.push(vl.trim());let u=this.sig.getDescription();if(u){let d=Xn(u);r.push(d)}this.task={type:"text",text:r.join(`
210
+ ${l}`);let c=$l(this.sig.getInputFields());r.push(`## Input Fields
211
+ ${c}`);let p=Gl(this.sig.getOutputFields());r.push(`## Output Fields
212
+ ${p}`),l&&l.length>0&&r.push(Nl.trim()),r.push(Dl.trim());let u=this.sig.getDescription();if(u){let d=er(u);r.push(d)}this.task={type:"text",text:r.join(`
212
213
 
213
214
  `)}}renderSingleValueUserContent=(e,t,n,r)=>{let o=this.renderInputFields(e),a=(r?o:[...t,...n,...o]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
214
- `):a.reduce(zi(`
215
+ `):a.reduce(Xi(`
215
216
  `),[])};render=(e,{examples:t,demos:n})=>{let r=t?[{type:"text",text:`
216
217
 
217
218
  ## Examples
218
- `},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],s=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=s&&a,c=this.task.text;if(l){let d=[{type:"text",text:c},...r,...o];d.reduce(zi(""),[]),d?.[0]&&(c=d[0].text)}let p={role:"system",content:c};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let f of m){let h;if(g?(h=this.renderSingleValueUserContent(f.values,r,o,l),g=!1):h=this.renderSingleValueUserContent(f.values,[],[],!1),f.role==="user"){d.push({role:"user",content:h});continue}if(f.role!=="assistant")throw new Error("Invalid message role");if(typeof h!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:h})}return[p,...d]}let u=this.renderSingleValueUserContent(e,r,o,l);return[p,{role:"user",content:u}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,s)=>{let a=s.title;return o[a]||(o[a]=[]),o[a].push(s),o},{});return Object.entries(n).map(([o,s])=>{if(s.length===1){let a=s[0];return{title:o,name:a.name,description:a.description}}if(s.length>1){let a=s.map(l=>`- ${l.description}`).join(`
219
+ `},...this.renderExamples(t)]:[],o=n?this.renderDemos(n):[],s=r.every(d=>d.type==="text"),a=o.every(d=>d.type==="text"),l=s&&a,c=this.task.text;if(l){let d=[{type:"text",text:c},...r,...o];d.reduce(Xi(""),[]),d?.[0]&&(c=d[0].text)}let p={role:"system",content:c};if(Array.isArray(e)){let d=[],m=e,g=!0;for(let f of m){let h;if(g?(h=this.renderSingleValueUserContent(f.values,r,o,l),g=!1):h=this.renderSingleValueUserContent(f.values,[],[],!1),f.role==="user"){d.push({role:"user",content:h});continue}if(f.role!=="assistant")throw new Error("Invalid message role");if(typeof h!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:h})}return[p,...d]}let u=this.renderSingleValueUserContent(e,r,o,l);return[p,{role:"user",content:u}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,s)=>{let a=s.title;return o[a]||(o[a]=[]),o[a].push(s),o},{});return Object.entries(n).map(([o,s])=>{if(s.length===1){let a=s[0];return{title:o,name:a.name,description:a.description}}if(s.length>1){let a=s.map(l=>`- ${l.description}`).join(`
219
220
  `);return{title:o,name:s[0].name,description:a}}}).filter(Boolean).forEach(o=>{let s=this.fieldTemplates?.[o.name]??this.defaultRenderInField;t.push(...s(o,o.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0};for(let[r,o]of e.entries()){let s=this.sig.getInputFields().map(c=>this.renderInField(c,o,{...n,isInputField:!0})).filter(c=>c!==void 0).flat(),a=this.sig.getOutputFields().map(c=>this.renderInField(c,o,{...n,isInputField:!1})).filter(c=>c!==void 0).flat(),l=[...s,...a];r>0&&l.length>0&&l[0]?.type==="text"&&t.push({type:"text",text:`---
220
221
 
221
222
  `}),l.forEach(c=>{"text"in c&&(c.text=`${c.text}
222
223
  `),t.push(c)})}return t};renderDemos=e=>{let t=[],n=this.sig.getInputFields(),r=this.sig.getOutputFields(),o={isExample:!0};for(let s of e){let a=n.map(p=>this.renderInField(p,s,{...o,isInputField:!0})).filter(p=>p!==void 0).flat(),l=r.map(p=>this.renderInField(p,s,{...o,isInputField:!1})).filter(p=>p!==void 0).flat();[...a,...l].slice(0,-1).forEach(p=>{"text"in p&&(p.text=`${p.text}
223
224
  `),t.push(p)})}return t};renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
224
- `}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(El(e,r,n))return;e.type&&Vn(e,r);let o=kl(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=s=>{if(!s)throw new Error("Image field value is required.");if(typeof s!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in s))throw new Error("Image field must have mimeType");if(!("data"in s))throw new Error("Image field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let s=r(t);o.push({type:"image",mimeType:s.mimeType,image:s.data})}return o}if(e.type?.name==="audio"){let r=s=>{if(!s)throw new Error("Audio field value is required.");if(typeof s!="object")throw new Error("Audio field value must be an object.");if(!("data"in s))throw new Error("Audio field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let s=r(t);o.push({type:"audio",format:s.format??"wav",data:s.data})}return o}if(e.type?.name==="file"){let r=s=>{if(!s)throw new Error("File field value is required.");if(typeof s!="object")throw new Error("File field value must be an object.");if(!("mimeType"in s))throw new Error("File field must have mimeType");let a="data"in s,l="fileUri"in s;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let s=r(t);o.push("fileUri"in s?{type:"file",mimeType:s.mimeType,fileUri:s.fileUri}:{type:"file",mimeType:s.mimeType,data:s.data})}return o}if(e.type?.name==="url"){let r=s=>{if(!s)throw new Error("URL field value is required.");if(typeof s=="string")return{url:s};if(typeof s!="object")throw new Error("URL field value must be a string or object.");if(!("url"in s))throw new Error("URL field must have url property");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let s=r(t);o.push({type:"url",url:s.url,...s.title?{title:s.title}:{},...s.description?{description:s.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
225
+ `}),t};renderInField=(e,t,n)=>{let r=t[e.name];if(Ul(e,r,n))return;e.type&&Qn(e,r);let o=Ll(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,o)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=s=>{if(!s)throw new Error("Image field value is required.");if(typeof s!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in s))throw new Error("Image field must have mimeType");if(!("data"in s))throw new Error("Image field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let s=r(t);o.push({type:"image",mimeType:s.mimeType,image:s.data})}return o}if(e.type?.name==="audio"){let r=s=>{if(!s)throw new Error("Audio field value is required.");if(typeof s!="object")throw new Error("Audio field value must be an object.");if(!("data"in s))throw new Error("Audio field must have data");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let s=r(t);o.push({type:"audio",format:s.format??"wav",data:s.data})}return o}if(e.type?.name==="file"){let r=s=>{if(!s)throw new Error("File field value is required.");if(typeof s!="object")throw new Error("File field value must be an object.");if(!("mimeType"in s))throw new Error("File field must have mimeType");let a="data"in s,l="fileUri"in s;if(!a&&!l)throw new Error("File field must have either data or fileUri");if(a&&l)throw new Error("File field cannot have both data and fileUri");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let s=r(t);o.push("fileUri"in s?{type:"file",mimeType:s.mimeType,fileUri:s.fileUri}:{type:"file",mimeType:s.mimeType,data:s.data})}return o}if(e.type?.name==="url"){let r=s=>{if(!s)throw new Error("URL field value is required.");if(typeof s=="string")return{url:s};if(typeof s!="object")throw new Error("URL field value must be a string or object.");if(!("url"in s))throw new Error("URL field must have url property");return s},o=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");o=o.concat(t.map(s=>{let a=r(s);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let s=r(t);o.push({type:"url",url:s.url,...s.title?{title:s.title}:{},...s.description?{description:s.description}:{}})}return o}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
225
226
  `),n.push(t.map(r=>`- ${r}`).join(`
226
- `))):n.push(t),[{type:"text",text:n.join("")}]}},qi=i=>i.map(e=>`\`${e.title}\``).join(", "),Ol=i=>i.map(t=>{let n=t.title,r=t.type?.name?ji(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,s=t.description?` ${Xn(t.description)}`:"";return`${n}: (${o})${s}`.trim()}).join(`
227
- `),Ml=i=>i.map(t=>{let n=t.title,r=t.type?.name?ji(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:Xn(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${s}`.trim()}).join(`
228
- `),kl=(i,e)=>{if(i.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return i.type?.name==="datetime"&&e instanceof Date?Mi(e):i.type?.name==="image"&&typeof e=="object"||i.type?.name==="audio"&&typeof e=="object"||i.type?.name==="file"&&typeof e=="object"||i.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},ji=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function zi(i){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=i+t.text:e.push(t)}else e.push(t);return e}}var El=(i,e,t)=>{if(typeof e=="boolean")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function Xn(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Pl(i,e){let t=i.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function Fl(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=o.find(c=>"functionId"in c&&c.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function Zn(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Pl(t,n):!1)&&t){let l=Fl(t,n),c=await r({type:"function",results:l});if(c<0||c>=l.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${l.length-1}`);return c}let s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function Hi(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await Zn(r,t,i,e)}var er=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=_l(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,s=new Map;for(let[a,l]of this.tools.entries())s.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,p]of this.tools.entries()){let u=s.get(c);if(!u)continue;let d=u.get(a);if(!d)continue;let m=o.get(p.name)??{};this.setNested(m,d,l),o.set(p.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let u=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(u.length>0)throw new be(`Missing required arguments for tool '${l.name}': ${u.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[s,a]of Object.entries(r)){let l=[...o,s];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,p=this.sanitizeFieldName(c);t.set(p,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function _l(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,p]of Object.entries(s)){let u=a?`${a}.${c}`:c,d=`${i.name}.${u}`;if(p.type==="object"&&p.properties)o(p.properties,u,p.required||[]);else{let m=Nl(p);e.push({name:$l(d),title:Dl(i.name,u),type:m,description:p.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Nl(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Dl(i,e){return`${i} ${e.replace(/\./g," ")}`}function $l(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Vi(i,e,t){let n=new le(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=_o(o.name),l=Wi(o.parameters);n.getOutputFields().some(p=>p.name===a)||n.addOutputField({name:a,title:Ki(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=Ll(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(p=>p.name===l.name)||n.addOutputField(l)}else{let s=_o(o.name),a=Wi(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:Ki(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Ll(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,p]of Object.entries(s)){let u=a?`${a}.${c}`:c,d=`${i.name}.${u}`;if(p.type==="object"&&p.properties)o(p.properties,u,p.required||[]);else{let m=Gl(p),g={name:_o(d),title:Ul(i.name,u),type:m,description:p.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Gl(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Ul(i,e){return`${i} ${e.replace(/\./g," ")}`}function _o(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ki(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Wi(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var sn=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new er(e)}processSignature(e){let{signature:t}=Vi(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var Ce=class extends lt{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??yt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Kn(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return bo()}updateMeter(e){bo(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:p,stream:u,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await Hi(t,l,{resultPicker:n?.resultPicker}),f=t?.history(g,l)??[];if(f.length===0)throw new Error("No chat prompt found");let h={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},x=this.isDebug(e,n),A=a===0,y=this.getLogger(e,n);return o=this.signatureToolCallingManager?[]:o,await e.chat({chatPrompt:f,functions:o,functionCall:s,modelConfig:h,model:c},{sessionId:l,rateLimiter:p,stream:u,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:p}=n??{},u=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,h=this.usage,x=r===0,A=this.isDebug(e,n),y=this.getLogger(e,n),{functions:I,functionCall:T}=Si(p,d,x,n),b=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:I,functionCall:T,stepIndex:r});b instanceof ReadableStream?yield*Di({ai:e,model:f,res:b,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:g,span:o,states:a,usage:h,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:u,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*$i({ai:e,model:f,res:b,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:g,states:a,usage:h,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:u,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(F=>F.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,p=r.maxSteps??this.options?.maxSteps??10,u=r.mem??this.options?.mem??new Zt,d=[...this.functions,...r.functions?Kn(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new sn(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new sn(d));let f,h,x=this.options?.promptTemplate??yt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new x(this.signature,A);let y,I=performance.now();Array.isArray(t)?(Bs(t),y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-I,b=this.getMetricsInstruments();b&&qn(b,"prompt_render",T,this.getSignatureName());let w=performance.now();u.addRequest(y,r.sessionId);let v=performance.now()-w;b&&qn(b,"memory_update",v,this.getSignatureName());e:for(let F=0;F<p;F++){for(let E=0;E<c;E++)try{let R=this.forwardCore({options:r,ai:e,mem:u,stepIndex:F,span:o,traceContext:s,states:n,stopFunctionNames:l});for await(let S of R)S!==void 0&&(yield{version:E,index:S.index,delta:S.delta});if(Li(u,l,n,r?.sessionId)){let S=this.getMetricsInstruments();S&&Bn(S,F+1,p,this.getSignatureName());continue e}r?.disableMemoryCleanup||(u.removeByTag("invalid-assistant",r.sessionId),u.removeByTag("correction",r.sessionId),u.removeByTag("error",r.sessionId));let C=this.getMetricsInstruments();if(C){Bn(C,F+1,p,this.getSignatureName());let S=new Set;n.forEach(_=>{_.functionsExecuted.forEach(B=>S.add(B))}),S.size>0&&pi(C,!0,S.size,!0,!1,this.getSignatureName()),ui(C,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(R){h=R;let $,C=this.isDebug(e,r),S=this.getLogger(e,r),_=this.getMetricsInstruments(),B=this.getSignatureName(),ee={error:R,errCount:E,logger:S,metricsInstruments:_,signatureName:B,span:o,debug:C};if(o?.recordException(R),R instanceof be)$=Ti(ee),f=R;else if(R instanceof Je)$=Ri(ee),f=R;else if(R instanceof ae)Ci(ee);else{if(R instanceof xt)throw R;if(!(R instanceof Ue))throw No(R,e,this.signature)}$&&(u.addTag("error",r.sessionId),u.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields($)}],r.sessionId),u.addTag("correction",r.sessionId))}let K=this.getMetricsInstruments();throw K&&To(K,c,!1,c,this.getSignatureName()),No(new Error(`Unable to fix validation error: ${(f??h)?.message??(f??h)?.toString()??"unknown error"}`),e,this.signature)}throw b&&Bn(b,p,p,this.getSignatureName()),No(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments();a&&qn(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=Kn(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let p=c?.map(x=>x.name).join(","),u={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...p?{provided_functions:p}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:ql.SERVER,attributes:u}),f=Bl.active(),h=zl.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},g,h),!this.excludeContentFromTrace){let x=o.map(y=>y.values),A=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=performance.now(),o=this.getSignatureName(),s=n?.stream??!1,a=!1,l=0,c=!1;try{let p=this.getMetricsInstruments();p&&gi(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,o);let u=this._forward1(e,t,n??{}),d=[],m=0,g=0;for await(let T of u)T.version!==m&&(d=[]),m=T.version,d=wo(d,T),g++;l=m;let f=performance.now();c=!!n?.resultPicker;let h=await Zn(d,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),x=performance.now()-f,y=d[h]?.delta??{},I=Array.isArray(t)?{}:t??{};if(this.trace={...I,...y},c&&this.isDebug(e,n)){let T=this.getLogger(e,n);Is(d.length,h,x,T)}return a=!0,p&&(mi(p,d.length,c,c?x:void 0,o),di(p,s,g,void 0,o)),y}catch(p){throw a=!1,p}finally{let p=performance.now()-r,u=this.getMetricsInstruments();u&&(li(u,p,a,o,e.getName(),n?.model?String(n.model):void 0),l>0&&To(u,l,a,n?.maxRetries??10,o))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let r=this._forward1(e,t,{...n,stream:!0}),o=[],s=0;for await(let c of r)c.version!==s&&(o=[]),s=c.version,o=wo(o,c);let a=await Zn(o,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=o[a];l&&(yield{version:s,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??se.logger??e.getLogger()}},tr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function No(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=e.getLastUsedChatModel(),o=e.getLastUsedModelConfig(),s={model:r,maxTokens:o?.maxTokens,streaming:o?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new tr("Generate failed",s,{cause:n})}var jl=i=>i.replace(/^\W+|\W+$/g,""),Hl=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},Kl=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Wl=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},Vl=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Jl=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},Do={trimNonAlphaNum:jl,splitIntoTwo:Hl,dedup:Kl,extractIdAndText:Wl,extractIndexPrefixedText:Vl,batchArray:Jl};var $o=class extends Ce{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
229
- query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=Do.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=o[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Lo=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var Gg=new Ae,Go=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Uo=class{ai;db;debug;constructor(e){this.db=new it,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}let s=o.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var Ji=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function Qi(i,e){return i.filter(t=>!e.has(t))}function Yi(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function ct(i){let e=i.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function Ql(i,e){return ct(i)===ct(e)?1:0}function Yl(i,e){let t=ct(i).split(" "),n=ct(e).split(" "),r=Yi(t),o=Yi(n),s=0;for(let c in r){let p=r[c]??0,u=o[c]??0;s+=Math.min(p,u)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function Xl(i,e,t,n=!1){let r=ct(i).split(" "),o=ct(e).split(" "),s=ct(t).split(" "),a=new Set([...Ji,...r]);o=Qi(o,a),s=Qi(s,a);let l=0,c=l/o.length,p=l/s.length,u=2*c*p/(c+p);return n?p:u}var Zl={emScore:Ql,f1Score:Yl,novelF1ScoreOptimized:Xl};var Bo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let s=0;s<n;s++){let a=this.examples[s];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),c=await e({prediction:l,example:a});r+=c}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
227
+ `))):n.push(t),[{type:"text",text:n.join("")}]}},Yi=i=>i.map(e=>`\`${e.title}\``).join(", "),$l=i=>i.map(t=>{let n=t.title,r=t.type?.name?Zi(t.type):"string",o=t.isOptional?`This optional ${r} field may be omitted`:`A ${r} field`,s=t.description?` ${er(t.description)}`:"";return`${n}: (${o})${s}`.trim()}).join(`
228
+ `),Gl=i=>i.map(t=>{let n=t.title,r=t.type?.name?Zi(t.type):"string",o=t.isOptional?`Only include this ${r} field if its value is available`:`This ${r} field must be included`,s="";return t.description&&t.description.length>0&&(s=` ${t.type?.name==="class"?t.description:er(t.description)}`),t.type?.options&&t.type.options.length>0&&(s.length>0&&(s+=". "),s+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${o})${s}`.trim()}).join(`
229
+ `),Ll=(i,e)=>{if(i.type?.name==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return i.type?.name==="datetime"&&e instanceof Date?Gi(e):i.type?.name==="image"&&typeof e=="object"||i.type?.name==="audio"&&typeof e=="object"||i.type?.name==="file"&&typeof e=="object"||i.type?.name==="url"&&(typeof e=="string"||typeof e=="object")||typeof e=="string"?e:JSON.stringify(e,null,2)},Zi=i=>{let e=(()=>{switch(i?.name){case"string":return"string";case"number":return"number";case"boolean":return"boolean (true or false)";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";case"file":return"file (with filename, mimeType, and data)";case"url":return"URL (string or object with url, title, description)";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Xi(i){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=i+t.text:e.push(t)}else e.push(t);return e}}var Ul=(i,e,t)=>{if(typeof e=="boolean"||i?.type?.name==="number"&&typeof e=="number")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(t?.isExample||i.isOptional||i.isInternal)return!0;let n=t?.isInputField!==!1?"input":"output";throw new Error(`Value for ${n} field '${i.name}' is required.`)}return!1};function er(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Bl(i,e){let t=i.history(0,e),n=t.some(o=>o.role==="function");return t.some(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0)&&n}function ql(i,e){let t=i.history(0,e),n=[],r=t.filter(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0),o=t.filter(s=>s.role==="function");for(let s of r)if("functionCalls"in s&&s.functionCalls)for(let a of s.functionCalls){let l=o.find(c=>"functionId"in c&&c.functionId===a.id);l&&"result"in l&&"functionId"in l&&n.push({index:n.length,functionName:a.function.name,functionId:a.id,args:a.function.params||"",result:String(l.result),isError:"isError"in l?!!l.isError:!1})}return n}async function tr(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Bl(t,n):!1)&&t){let l=ql(t,n),c=await r({type:"function",results:l});if(c<0||c>=l.length)throw new Error(`Result picker returned invalid index: ${c}. Must be between 0 and ${l.length-1}`);return c}let s=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:s});if(a<0||a>=i.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${i.length-1}`);return a}async function ea(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(s=>({version:0,index:s.index,delta:s.value}));return await tr(r,t,i,e)}var nr=class{tools;logger;constructor(e,t){this.tools=new Map(e.map(n=>[n.name,n])),this.logger=t}getToolParamFieldMap(){let e=new Map;for(let[,t]of this.tools.entries())if(t.parameters?.properties&&Object.keys(t.parameters.properties).length>0){let{paramFieldMap:n}=zl(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},o=new Map,s=new Map;for(let[a,l]of this.tools.entries())s.set(a,this.buildSanitizedFieldMap(l));for(let[a,l]of Object.entries(e)){let c=this.tools.get(this.normalizeToolName(a));if(c){l!=null&&typeof l=="object"&&o.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,p]of this.tools.entries()){let u=s.get(c);if(!u)continue;let d=u.get(a);if(!d)continue;let m=o.get(p.name)??{};this.setNested(m,d,l),o.set(p.name,m)}for(let[a,l]of this.tools.entries()){let c=o.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let u=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(u.length>0)throw new Re(`Missing required arguments for tool '${l.name}': ${u.join(", ")}`)}n.push({id:l.name,name:l.name,args:JSON.stringify(c)})}}return{functionCalls:n,remainingFields:r}}normalizeToolName(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}sanitizeFieldName(e){return e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}buildSanitizedFieldMap(e){let t=new Map;if(!e.parameters||!("properties"in e.parameters))return t;let n=(r,o)=>{for(let[s,a]of Object.entries(r)){let l=[...o,s];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,p=this.sanitizeFieldName(c);t.set(p,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let o=0;o<t.length-1;o++){let s=t[o],a=r[s];(typeof a!="object"||a===null)&&(r[s]={}),r=r[s]}r[t[t.length-1]]=n}isToolField(e){return this.tools.has(this.normalizeToolName(e))}getToolFieldNames(){return Array.from(this.tools.keys()).map(e=>e.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_/,""))}};function zl(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,p]of Object.entries(s)){let u=a?`${a}.${c}`:c,d=`${i.name}.${u}`;if(p.type==="object"&&p.properties)o(p.properties,u,p.required||[]);else{let m=jl(p);e.push({name:Kl(d),title:Hl(i.name,u),type:m,description:p.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function jl(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Hl(i,e){return`${i} ${e.replace(/\./g," ")}`}function Kl(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function ra(i,e,t){let n=new pe(e);if(t){let r=t.getToolParamFieldMap();for(let o of i){let s=r.get(o.name);if(s&&s.size>0)for(let a of s.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=$o(o.name),l=na(o.parameters);n.getOutputFields().some(p=>p.name===a)||n.addOutputField({name:a,title:ta(o.name),type:l,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let o of i)if(o.parameters?.properties&&Object.keys(o.parameters.properties).length>0){let{fields:s,paramFieldMap:a}=Wl(o);r.set(o.name,a);for(let l of s)n.getOutputFields().some(p=>p.name===l.name)||n.addOutputField(l)}else{let s=$o(o.name),a=na(o.parameters);n.getOutputFields().some(c=>c.name===s)||n.addOutputField({name:s,title:ta(o.name),type:a,description:o.description||`Parameters for ${o.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Wl(i){let e=[],t=new Map;if(!i.parameters||!i.parameters.properties)return{fields:e,paramFieldMap:t};let n=i.parameters.properties,r=i.parameters.required||[],o=(s,a,l)=>{for(let[c,p]of Object.entries(s)){let u=a?`${a}.${c}`:c,d=`${i.name}.${u}`;if(p.type==="object"&&p.properties)o(p.properties,u,p.required||[]);else{let m=Vl(p),g={name:$o(d),title:Jl(i.name,u),type:m,description:p.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(g),t.set(d,g)}}};return o(n,"",r),{fields:e,paramFieldMap:t}}function Vl(i){switch(i.type){case"string":return{name:"string",isArray:!1};case"number":case"integer":return{name:"number",isArray:!1};case"boolean":return{name:"boolean",isArray:!1};case"array":{let e=i.items;if(e?.type)switch(e.type){case"string":return{name:"string",isArray:!0};case"number":case"integer":return{name:"number",isArray:!0};case"boolean":return{name:"boolean",isArray:!0};default:return{name:"json",isArray:!0}}return{name:"json",isArray:!0}}case"object":return{name:"json",isArray:!1};default:return{name:"string",isArray:!1}}}function Jl(i,e){return`${i} ${e.replace(/\./g," ")}`}function $o(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function ta(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function na(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var an=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new nr(e)}processSignature(e){let{signature:t}=ra(this.tools,e),n=new Set(t.getOutputFields().map(o=>o.name)),r=new Set(e.getOutputFields().map(o=>o.name));return this.injectedToolFieldNames=new Set([...n].filter(o=>!r.has(o))),t}async processResults(e,t){let{functionCalls:n}=await this.router.route(e,t);return n.length>0?n:void 0}getInjectedToolFieldNames(){return Array.from(this.injectedToolFieldNames)}getRouter(){return this.router}};var ve=class extends pt{promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;constructor(e,t){super(e,{description:t?.description,traceLabel:t?.traceLabel}),this.options=t,this.thoughtFieldName=t?.thoughtFieldName??"thought";let n={functions:t?.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(t?.promptTemplate??It)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Vn(t.functions):[],this.usage=[]}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return Co()}updateMeter(e){Co(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})};addStreamingAssert=(e,t,n)=>{let r=this.signature.getOutputFields().find(a=>a.name===e);if(!r)throw new Error(`addStreamingAssert: field ${String(e)} not found in output signature`);let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addStreamingAssert: field ${String(e)} must be a string field for streaming assertions`);this.streamingAsserts.push({fieldName:String(e),fn:t,message:n})};addFieldProcessorInternal=(e,t,n=!1)=>{let r=this.signature.getOutputFields().find(o=>o.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let o=r.type?.name;if(!(!o||o==="string"||o==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:r,process:t})}else this.fieldProcessors.push({field:r,process:t})};addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!0)};addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(String(e),t,!1)};async forwardSendRequest({ai:e,mem:t,options:n,traceContext:r,functions:o,functionCall:s,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:p,stream:u,thinkingTokenBudget:d,showThoughts:m}=n??{},g=await ea(t,l,{resultPicker:n?.resultPicker}),f=t?.history(g,l)??[];if(f.length===0)throw new Error("No chat prompt found");let h={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},x=this.isDebug(e,n),A=a===0,y=this.getLogger(e,n);return o=this.signatureToolCallingManager?[]:o,await e.chat({chatPrompt:f,functions:o,functionCall:s,modelConfig:h,model:c},{sessionId:l,rateLimiter:p,stream:u,debug:x,debugHideSystemPrompt:!A,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal,stepIndex:a,logger:y,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto"})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:o,traceContext:s,states:a,stopFunctionNames:l}){let{sessionId:c,functions:p}=n??{},u=n?.functionResultFormatter??this.options?.functionResultFormatter,d=n?.functionCall??this.options?.functionCall,m=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,h=this.usage,x=r===0,A=this.isDebug(e,n),y=this.getLogger(e,n),{functions:I,functionCall:T}=Ni(p,d,x,n),C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:s,functions:I,functionCall:T,stepIndex:r});C instanceof ReadableStream?yield*Hi({ai:e,model:f,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,strictMode:g,span:o,states:a,usage:h,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:u,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup}):yield*Ki({ai:e,model:f,res:C,mem:t,sessionId:c,traceId:o?o.spanContext?.().traceId:void 0,functions:I,span:o,strictMode:g,states:a,usage:h,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:y,debug:A,functionResultFormatter:u,signatureToolCallingManager:m,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup})}async*_forward2(e,t,n,r,o,s){let a=r?.stopFunction??this.options?.stopFunction,l=Array.isArray(a)?a.map(P=>P.toLowerCase()):a?[a.toLowerCase()]:void 0,c=r.maxRetries??this.options?.maxRetries??10,p=r.maxSteps??this.options?.maxSteps??10,u=r.mem??this.options?.mem??new tn,d=[...this.functions,...r.functions?Vn(r.functions):[]],m=d&&d.length>0,g=r.functionCallMode??this.options?.functionCallMode??"auto";m&&g==="prompt"&&(this.signatureToolCallingManager=new an(d)),m&&g==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new an(d));let f,h,x=this.options?.promptTemplate??It;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new x(this.signature,A);let y,I=performance.now();Array.isArray(t)?(Qs(t),y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):y=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let T=performance.now()-I,C=this.getMetricsInstruments();C&&jn(C,"prompt_render",T,this.getSignatureName());let b=performance.now();u.addRequest(y,r.sessionId);let v=performance.now()-b;C&&jn(C,"memory_update",v,this.getSignatureName());e:for(let P=0;P<p;P++){for(let O=0;O<c;O++)try{let w=this.forwardCore({options:r,ai:e,mem:u,stepIndex:P,span:o,traceContext:s,states:n,stopFunctionNames:l});for await(let S of w)S!==void 0&&(yield{version:O,index:S.index,delta:S.delta});if(Wi(u,l,n,r?.sessionId)){let S=this.getMetricsInstruments();S&&zn(S,P+1,p,this.getSignatureName());continue e}r?.disableMemoryCleanup||(u.removeByTag("invalid-assistant",r.sessionId),u.removeByTag("correction",r.sessionId),u.removeByTag("error",r.sessionId));let R=this.getMetricsInstruments();if(R){zn(R,P+1,p,this.getSignatureName());let S=new Set;n.forEach(N=>{N.functionsExecuted.forEach(G=>S.add(G))}),S.size>0&&yi(R,!0,S.size,!0,!1,this.getSignatureName()),bi(R,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(w){h=w;let _,R=this.isDebug(e,r),S=this.getLogger(e,r),N=this.getMetricsInstruments(),G=this.getSignatureName(),Y={error:w,errCount:O,logger:S,metricsInstruments:N,signatureName:G,span:o,debug:R};if(o?.recordException(w),w instanceof Re)_=Ei(Y),f=w;else if(w instanceof Qe)_=Pi(Y),f=w;else if(w instanceof le)Fi(Y);else{if(w instanceof bt)throw w;if(!(w instanceof Be))throw Go(w,e,this.signature)}_&&(u.addTag("error",r.sessionId),u.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(_)}],r.sessionId),u.addTag("correction",r.sessionId))}let K=this.getMetricsInstruments();throw K&&wo(K,c,!1,c,this.getSignatureName()),Go(new Error(`Unable to fix validation error: ${(f??h)?.message??(f??h)?.toString()??"unknown error"}`),e,this.signature)}throw C&&zn(C,p,p,this.getSignatureName()),Go(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let r=performance.now(),o=this.createStates(n.sampleCount??1),s=performance.now()-r,a=this.getMetricsInstruments();a&&jn(a,"state_creation",s,this.getSignatureName());let l=n?.tracer??this.options?.tracer??e.getOptions().tracer,c=this.functions;if(n?.functions&&(c=Vn(n.functions,this.functions)),!l){yield*this._forward2(e,t,o,{...n,functions:c});return}let p=c?.map(x=>x.name).join(","),u={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...p?{provided_functions:p}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},d=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,m=d?`AxGen > ${d}`:"AxGen",g=l.startSpan(m,{kind:Yl.SERVER,attributes:u}),f=Ql.active(),h=Xl.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,o,{...n,functions:c},g,h),!this.excludeContentFromTrace){let x=o.map(y=>y.values),A=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(A,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=performance.now(),o=this.getSignatureName(),s=n?.stream??!1,a=!1,l=0,c=!1;try{let p=this.getMetricsInstruments();p&&Ci(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,o);let u=this._forward1(e,t,n??{}),d=[],m=0,g=0;for await(let T of u)T.version!==m&&(d=[]),m=T.version,d=Oo(d,T),g++;l=m;let f=performance.now();c=!!n?.resultPicker;let h=await tr(d,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),x=performance.now()-f,y=d[h]?.delta??{},I=Array.isArray(t)?{}:t??{};if(this.trace={...I,...y},c&&this.isDebug(e,n)){let T=this.getLogger(e,n);Ms(d.length,h,x,T)}return a=!0,p&&(Ti(p,d.length,c,c?x:void 0,o),Ii(p,s,g,void 0,o)),y}catch(p){throw a=!1,p}finally{let p=performance.now()-r,u=this.getMetricsInstruments();u&&(Ai(u,p,a,o,e.getName(),n?.model?String(n.model):void 0),l>0&&wo(u,l,a,n?.maxRetries??10,o))}}async*streamingForward(e,t,n){if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let r=this._forward1(e,t,{...n,stream:!0}),o=[],s=0;for await(let c of r)c.version!==s&&(o=[]),s=c.version,o=Oo(o,c);let a=await tr(o,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),l=o[a];l&&(yield{version:s,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??ie.logger??e.getLogger()}},rr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}};function Go(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=e.getLastUsedChatModel(),o=e.getLastUsedModelConfig(),s={model:r,maxTokens:o?.maxTokens,streaming:o?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new rr("Generate failed",s,{cause:n})}var Zl=i=>i.replace(/^\W+|\W+$/g,""),ec=(i,e)=>{let t=i.search(e);if(t===-1)return[i];let n=i.match(e);if(!n)throw new Error("Match failed unexpectedly.");let r=i.substring(0,t),o=i.substring(t+n[0].length);return[r,o]},tc=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},nc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);if(!e||e.length<3)throw new Error('line must start with a number, a dot and then text. e.g. "1. hello"');let t=Number.parseInt(e[1],10),n=e[2].trim();return{id:t,text:n}},rc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},oc=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},Lo={trimNonAlphaNum:Zl,splitIntoTwo:ec,dedup:tc,extractIdAndText:nc,extractIndexPrefixedText:rc,batchArray:oc};var Uo=class extends ve{constructor(e){super(`"You are a re-ranker assistant tasked with evaluating a set of content items in relation to a specific question. Your role involves critically analyzing each content item to determine its relevance to the question and re-ranking them accordingly. This process includes assigning a relevance score from 0 to 10 to each content item based on how well it answers the question, its coverage of the topic, and the reliability of its information. This re-ranked list should start with the content item that is most relevant to the question and end with the least relevant. Output only the list."
230
+ query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e)}forward=async(e,t,n)=>{let{rankedItems:r}=await super.forward(e,t,n),o=r.map(a=>{let{id:l}=Lo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=o[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Bo=class{tikaUrl;fetch;constructor(e){let t=e??{url:"http://localhost:9998/"};this.tikaUrl=new URL("/tika",t.url),this.fetch=t.fetch}async _convert(e,t){if(!e)throw new Error("Failed to read file data");let n=t?.format==="html"?"text/html":"text/plain";try{let r={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(r.duplex="half");let o=await(this.fetch??fetch)(this.tikaUrl,r);if(!o.ok)throw new Error(`Failed to upload file: ${o.statusText}`);return await o.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let o=0;o<e.length;o+=r){let a=e.slice(o,o+r).map(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var Zg=new be,qo=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},zo=class{ai;db;debug;constructor(e){this.db=new lt,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}setClasses=async(e,t)=>{for(let n of e){let r=await this.ai.embed({texts:n.getContext()},{abortSignal:t?.abortSignal});await this.db.upsert({id:n.getName(),table:"classes",values:r.embeddings[0]})}};async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:t?.abortSignal}),o=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;o=o.filter(l=>l.score<=a)}let s=o.at(0);return s?s.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var oa=new Set(["0o","0s","3a","3b","3d","6b","6o","a","a1","a2","a3","a4","ab","able","about","above","abst","ac","accordance","according","accordingly","across","act","actually","ad","added","adj","ae","af","affected","affecting","affects","after","afterwards","ag","again","against","ah","ain","ain't","aj","al","all","allow","allows","almost","alone","along","already","also","although","always","am","among","amongst","amoungst","amount","an","and","announce","another","any","anybody","anyhow","anymore","anyone","anything","anyway","anyways","anywhere","ao","ap","apart","apparently","appear","appreciate","appropriate","approximately","ar","are","aren","arent","aren't","arise","around","as","a's","aside","ask","asking","associated","at","au","auth","av","available","aw","away","awfully","ax","ay","az","b","b1","b2","b3","ba","back","bc","bd","be","became","because","become","becomes","becoming","been","before","beforehand","begin","beginning","beginnings","begins","behind","being","believe","below","beside","besides","best","better","between","beyond","bi","bill","biol","bj","bk","bl","bn","both","bottom","bp","br","brief","briefly","bs","bt","bu","but","bx","by","c","c1","c2","c3","ca","call","came","can","cannot","cant","can't","cause","causes","cc","cd","ce","certain","certainly","cf","cg","ch","changes","ci","cit","cj","cl","clearly","cm","c'mon","cn","co","com","come","comes","con","concerning","consequently","consider","considering","contain","containing","contains","corresponding","could","couldn","couldnt","couldn't","course","cp","cq","cr","cry","cs","c's","ct","cu","currently","cv","cx","cy","cz","d","d2","da","date","dc","dd","de","definitely","describe","described","despite","detail","df","di","did","didn","didn't","different","dj","dk","dl","do","does","doesn","doesn't","doing","don","done","don't","down","downwards","dp","dr","ds","dt","du","due","during","dx","dy","e","e2","e3","ea","each","ec","ed","edu","ee","ef","effect","eg","ei","eight","eighty","either","ej","el","eleven","else","elsewhere","em","empty","en","end","ending","enough","entirely","eo","ep","eq","er","es","especially","est","et","et-al","etc","eu","ev","even","ever","every","everybody","everyone","everything","everywhere","ex","exactly","example","except","ey","f","f2","fa","far","fc","few","ff","fi","fifteen","fifth","fify","fill","find","fire","first","five","fix","fj","fl","fn","fo","followed","following","follows","for","former","formerly","forth","forty","found","four","fr","from","front","ft","fu","full","further","furthermore","fy","g","ga","gave","ge","get","gets","getting","gi","give","given","gives","giving","gj","gl","go","goes","going","gone","got","gotten","gr","greetings","gs","gy","h","h2","h3","had","hadn","hadn't","happens","hardly","has","hasn","hasnt","hasn't","have","haven","haven't","having","he","hed","he'd","he'll","hello","help","hence","her","here","hereafter","hereby","herein","heres","here's","hereupon","hers","herself","hes","he's","hh","hi","hid","him","himself","his","hither","hj","ho","home","hopefully","how","howbeit","however","how's","hr","hs","http","hu","hundred","hy","i","i2","i3","i4","i6","i7","i8","ia","ib","ibid","ic","id","i'd","ie","if","ig","ignored","ih","ii","ij","il","i'll","im","i'm","immediate","immediately","importance","important","in","inasmuch","inc","indeed","index","indicate","indicated","indicates","information","inner","insofar","instead","interest","into","invention","inward","io","ip","iq","ir","is","isn","isn't","it","itd","it'd","it'll","its","it's","itself","iv","i've","ix","iy","iz","j","jj","jr","js","jt","ju","just","k","ke","keep","keeps","kept","kg","kj","km","know","known","knows","ko","l","l2","la","largely","last","lately","later","latter","latterly","lb","lc","le","least","les","less","lest","let","lets","let's","lf","like","liked","likely","line","little","lj","ll","ll","ln","lo","look","looking","looks","los","lr","ls","lt","ltd","m","m2","ma","made","mainly","make","makes","many","may","maybe","me","mean","means","meantime","meanwhile","merely","mg","might","mightn","mightn't","mill","million","mine","miss","ml","mn","mo","more","moreover","most","mostly","move","mr","mrs","ms","mt","mu","much","mug","must","mustn","mustn't","my","myself","model","n","n2","na","name","namely","nay","nc","nd","ne","near","nearly","necessarily","necessary","need","needn","needn't","needs","neither","never","nevertheless","new","next","ng","ni","nine","ninety","nj","nl","nn","no","nobody","non","none","nonetheless","noone","nor","normally","nos","not","noted","nothing","novel","now","nowhere","nr","ns","nt","ny","o","oa","ob","obtain","obtained","obviously","oc","od","of","off","often","og","oh","oi","oj","ok","okay","ol","old","om","omitted","on","once","one","ones","only","onto","oo","op","oq","or","ord","os","ot","other","others","otherwise","ou","ought","our","ours","ourselves","out","outside","over","overall","ow","owing","own","ox","oz","p","p1","p2","p3","page","pagecount","pages","par","part","particular","particularly","pas","past","pc","pd","pe","per","perhaps","pf","ph","pi","pj","pk","pl","placed","please","plus","pm","pn","po","poorly","possible","possibly","potentially","pp","pq","pr","predominantly","present","presumably","previously","primarily","probably","promptly","proud","provides","ps","pt","pu","put","py","q","qj","qu","que","quickly","quite","qv","r","r2","ra","ran","rather","rc","rd","re","readily","really","reasonably","recent","recently","ref","refs","regarding","regardless","regards","related","relatively","research","research-articl","respectively","resulted","resulting","results","rf","rh","ri","right","rj","rl","rm","rn","ro","rq","rr","rs","rt","ru","run","rv","ry","s","s2","sa","said","same","saw","say","saying","says","sc","sd","se","sec","second","secondly","section","see","seeing","seem","seemed","seeming","seems","seen","self","selves","sensible","sent","serious","seriously","seven","several","sf","shall","shan","shan't","she","shed","she'd","she'll","shes","she's","should","shouldn","shouldn't","should've","show","showed","shown","showns","shows","si","side","significant","significantly","similar","similarly","since","sincere","six","sixty","sj","sl","slightly","sm","sn","so","some","somebody","somehow","someone","somethan","something","sometime","sometimes","somewhat","somewhere","soon","sorry","sp","specifically","specified","specify","specifying","sq","sr","ss","st","still","stop","strongly","sub","substantially","successfully","such","sufficiently","suggest","sup","sure","sy","system","sz","t","t1","t2","t3","take","taken","taking","tb","tc","td","te","tell","ten","tends","tf","th","than","thank","thanks","thanx","that","that'll","thats","that's","that've","the","their","theirs","them","themselves","then","thence","there","thereafter","thereby","thered","therefore","therein","there'll","thereof","therere","theres","there's","thereto","thereupon","there've","these","they","theyd","they'd","they'll","theyre","they're","they've","thickv","thin","think","third","this","thorough","thoroughly","those","thou","though","thoughh","thousand","three","throug","through","throughout","thru","thus","ti","til","tip","tj","tl","tm","tn","to","together","too","took","top","toward","towards","tp","tq","tr","tried","tries","truly","try","trying","ts","t's","tt","tv","twelve","twenty","twice","two","tx","u","u201d","ue","ui","uj","uk","um","un","under","unfortunately","unless","unlike","unlikely","until","unto","uo","up","upon","ups","ur","us","use","used","useful","usefully","usefulness","uses","using","usually","ut","v","va","value","various","vd","ve","ve","very","via","viz","vj","vo","vol","vols","volumtype","vq","vs","vt","vu","w","wa","want","wants","was","wasn","wasnt","wasn't","way","we","wed","we'd","welcome","well","we'll","well-b","went","were","we're","weren","werent","weren't","we've","what","whatever","what'll","whats","what's","when","whence","whenever","when's","where","whereafter","whereas","whereby","wherein","wheres","where's","whereupon","wherever","whether","which","while","whim","whither","who","whod","whoever","whole","who'll","whom","whomever","whos","who's","whose","why","why's","wi","widely","will","willing","wish","with","within","without","wo","won","wonder","wont","won't","words","world","would","wouldn","wouldnt","wouldn't","www","x","x1","x2","x3","xf","xi","xj","xk","xl","xn","xo","xs","xt","xv","xx","y","y2","yes","yet","yj","yl","you","youd","you'd","you'll","your","youre","you're","yours","yourself","yourselves","you've","yr","ys","yt","z","zero","zi","zz","task"]);function sa(i,e){return i.filter(t=>!e.has(t))}function ia(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function ut(i){let e=i.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function sc(i,e){return ut(i)===ut(e)?1:0}function ic(i,e){let t=ut(i).split(" "),n=ut(e).split(" "),r=ia(t),o=ia(n),s=0;for(let c in r){let p=r[c]??0,u=o[c]??0;s+=Math.min(p,u)}if(s===0)return 0;let a=s/t.length,l=s/n.length;return 2*a*l/(a+l)}function ac(i,e,t,n=!1){let r=ut(i).split(" "),o=ut(e).split(" "),s=ut(t).split(" "),a=new Set([...oa,...r]);o=sa(o,a),s=sa(s,a);let l=0,c=l/o.length,p=l/s.length,u=2*c*p/(c+p);return n?p:u}var lc={emScore:sc,f1Score:ic,novelF1ScoreOptimized:ac};var jo=class{ai;program;examples;constructor({ai:e,program:t,examples:n=[]}){if(n.length===0)throw new Error("No examples found");this.ai=e,this.program=t,this.examples=n}async run(e){let t=Date.now(),n=this.examples.length,r=0;for(let s=0;s<n;s++){let a=this.examples[s];if(!a)throw new Error("Invalid example");try{let l=await this.program.forward(this.ai,a,{maxRetries:1}),c=await e({prediction:l,example:a});r+=c}catch(l){console.warn(`Program evaluation failed for example ${s}: ${l instanceof Error?l.message:"Unknown error"}`)}}let o=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
230
231
  Performance: `,r,"/",n,"Average Score: ",o,`
231
- `)}};var qo=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let s={};return t.forEach(a=>{let l=a.split("."),c=o.row;for(let u of l)Object.hasOwn(c,u)&&(c=c[u]);if(!c)return;let p=n&&a in n?n[a]:a;if(!p)throw new Error(`Invalid field name: ${a}`);s[p]=c}),s}).filter(o=>Object.keys(o).length!==0)}};var Xi=i=>{console.log(i)},Zi=(i=Xi)=>{let e=new Ae,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
232
+ `)}};var Ho=class{rows=[];baseUrl;dataset;split;config;options;constructor({dataset:e,split:t,config:n,options:r}){this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=r}async fetchDataFromAPI(e){try{let t=await fetch(e);if(!t.ok)throw new Error(`Error fetching data: ${t.statusText}`);let n=await t.json();if(!n?.rows)throw new Error("Invalid data format");return n.rows}catch(t){throw console.error("Error fetching data from API:",t),t}}async loadData(){let e=this.options?.offset??0,t=this.options?.length??100,n=encodeURIComponent(this.dataset),r=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return this.rows=await this.fetchDataFromAPI(r),this.rows}setData(e){this.rows=e}getData(){return this.rows}async getRows({count:e,fields:t,renameMap:n}){if(this.rows.length===0)throw new Error("No data loaded, call loadData or setData first.");return this.rows.slice(0,e).map(o=>{let s={};return t.forEach(a=>{let l=a.split("."),c=o.row;for(let u of l)Object.hasOwn(c,u)&&(c=c[u]);if(!c)return;let p=n&&a in n?n[a]:a;if(!p)throw new Error(`Invalid field name: ${a}`);s[p]=c}),s}).filter(o=>Object.keys(o).length!==0)}};var aa=i=>{console.log(i)},la=(i=aa)=>{let e=new be,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let o="";switch(r.name){case"OptimizationStart":o=`
232
233
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
233
234
  ${t}
234
235
  ${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
@@ -271,7 +272,7 @@ ${t}
271
272
  ${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
272
273
  `;break;default:o=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
273
274
  ${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
274
- `}i(o)}},ec=(i=Xi)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
275
+ `}i(o)}},cc=(i=aa)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
275
276
  ${e}
276
277
  Config: ${JSON.stringify(t.value.config,null,2)}
277
278
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -297,15 +298,28 @@ Score: ${t.value.score.toFixed(3)}
297
298
  Config: ${JSON.stringify(t.value.config)}
298
299
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
299
300
  ${JSON.stringify(t)}
300
- ${e}`}i(n)}},nr=Zi();var ea={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},rr,tc=i=>{if(rr)return rr;if(i)return rr=oc(i),rr};var or=ea,nc=i=>{or={...or,...i}},rc=()=>({...or}),oc=i=>({optimizationLatencyHistogram:i.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:i.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:i.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:i.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:i.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:i.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:i.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:i.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:i.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:i.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:i.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:i.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:i.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:i.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:i.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:i.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:i.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:i.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:i.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:i.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:i.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:i.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:i.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:i.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:i.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:i.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:i.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:i.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:i.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:i.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:i.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),Le=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=or.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},sc=(i,e,t,n,r)=>{try{let o=Le({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,o),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,o),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},ic=(i,e,t,n,r,o)=>{try{let s=Le({optimizer_type:o});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,s),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,s),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,s),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,s)}catch(s){console.warn("Failed to record convergence metric:",s)}},ac=(i,e,t)=>{try{let n=Le({reason:e,optimizer_type:t});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},lc=(i,e,t,n,r)=>{try{let o=Le({optimizer_type:n});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,o),i.costUsageCounter&&i.costUsageCounter.add(t,o),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},cc=(i,e,t)=>{try{let n=Le({optimizer_type:t});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},pc=(i,e,t,n)=>{try{let r=Le({optimizer_type:n});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,r),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,r),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},uc=(i,e,t,n,r)=>{try{let o=Le({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,o),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,o)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,o),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},dc=(i,e,t,n,r)=>{try{let o=Le({optimizer_type:n});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,o),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,o),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,o),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},mc=(i,e,t,n,r,o)=>{try{let s=Le({optimizer_type:o});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,s),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,s),i.examplesCountGauge&&i.examplesCountGauge.record(n,s),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,s)}catch(s){console.warn("Failed to record program complexity metric:",s)}},gc=(i,e,t,n)=>{try{let r=Le({metric_type:e,optimizer_type:n});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},hc=(i,e,t,n)=>{try{let r=Le({optimizer_type:e});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,r),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,r),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},pt=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},sr=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},$e=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new sr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=tc(se.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?nr:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a);let l,c=(g,f,h,x,A,y,I,T={},b)=>{this.getOptimizerLogger(b)?.({name:"RoundProgress",value:{round:g,totalRounds:b?.maxIterations??0,currentScore:f,bestScore:y,configuration:h}}),this.updateOptimizationProgress(g,f,h,x,A,y,I,T,b)},p=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},u=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:u,overrideOnEarlyStop:p}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,s,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],p=this.findParetoFrontier(c),u=this.calculateHypervolume(p);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(p.length,c.length,"base_optimizer",u);let d=p.length>0?Math.max(...p.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:p.length>0?[...p[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:p,hypervolume:u,paretoFrontSize:p.length,finalConfiguration:{paretoFrontSize:p.length,hypervolume:u,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l),p=this.generateWeightCombinations(c);for(let u=0;u<p.length;u++){let d=p[u],m=async({prediction:g,example:f})=>{let h=await n({prediction:g,example:f}),x=0;for(let[A,y]of Object.entries(h))x+=y*(d[A]||0);return x};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let p of c){let u=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[p]||0,h=0;for(let[x,A]of Object.entries(g))x!==p&&A<.3&&(h+=(.3-A)*2);return f-h};try{let d=await this.compile(e,t,u,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:p,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let s of e)o[s]=s===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new Ce(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},p=l;for(let d of p)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,h]of Object.entries(g))c[f]||(c[f]=[]),c[f].push(h)}catch{}let u={};for(let[d,m]of Object.entries(c))u[d]=m.length>0?m.reduce((g,f)=>g+f,0)/m.length:0;return u}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,s=0,a=[...e].sort((c,p)=>(p.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let p=c.scores[r]||0,u=c.scores[o]||0;s+=p*(u-l),l=Math.max(l,u)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,p;try{let u={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};p=await a(u),c=!0}catch(u){throw c=!1,u}finally{let u=Date.now()-l;this.recordCheckpointMetrics("save",u,c,e)}return p}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return s}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;mc(this.metricsInstruments,n,r,0,0,e)}hc(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;sc(this.metricsInstruments,e,t,n,r),cc(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,s=this.costTracker?.getTotalTokens()??0;lc(this.metricsInstruments,s,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&ic(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&ac(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&pc(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&uc(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&dc(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&gc(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??se.optimizerLogger??nr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let p=t.bootstrappedDemos;typeof p=="number"&&p===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let s=this.getOptimizerLogger(r);s&&s(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};var an=class extends $e{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Ac([...t],this.maxExamples),p=this.traces.length;for(let u=0;u<c.length;u+=this.batchSize){u>0&&(l.modelConfig.temperature=.7+.001*u);let d=c.slice(u,u+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(x=>x!==m);e.setExamples(g);let f=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{let x={...l,maxRetries:1};h=await e.forward(f,m,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(h).length/4),await r({prediction:h,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),h={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-p;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let s=fc(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function fc(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var Ac=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};function xc(i){return le.create(i)}function we(i,e){let t=typeof i=="string"?le.create(i):i;return new Ce(t,e)}function ta(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function je(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(ta(i[s].scores,i[n].scores,e)){o=!0;break}ta(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Oe(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,p=Math.max(c-s,0);o+=l*p,s=Math.max(s,c)}return o}function ut(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function ir(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function ln(i,e){let t=new Set;for(let p of i)for(let u of p)t.add(u);let r=[...Array.from(t)].sort((p,u)=>(e[p]??0)-(e[u]??0)),o=new Set,s=(p,u)=>{for(let d of i){if(!d.has(p))continue;let m=!1;for(let g of u)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let p of r){if(o.has(p))continue;let u=new Set(r.filter(d=>d!==p&&!o.has(d)));if(s(p,u)){o.add(p),a=!0;break}}}let l=r.filter(p=>!o.has(p)),c=new Set(l);return i.map(p=>{let u=new Set;for(let d of p)c.has(d)&&u.add(d);return u})}function cn(i,e,t){let n=ln(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let p=Number(l);for(let u=0;u<c;u++)o.push(p)}if(o.length===0)return 0;let s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var zo=class extends $e{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??0)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,p=async(C,S)=>{try{e.setInstruction?.(C);let _=await e.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:_,example:S})||{}}catch{return{}}},u=async(C,S)=>{let _=[];for(let B of S)_.push(await p(C,B));return ir(_)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await u(d,l)}],g=C=>{let S=r?.paretoMetricKey,_=r?.paretoScalarize;if(typeof _=="function")return _(C);if(S)return Number.isFinite(C[S])?C[S]:0;let B=Object.values(C);return B.length?B.reduce((ee,re)=>ee+re,0)/B.length:0},f=[],h=async(C,S)=>{let _=[];for(let B of S){let ee=await p(C,B);_.push(g(ee))}return _};f.push(await h(d,l));let x=()=>{let C=f[0]?.length??0,S=[];for(let B=0;B<C;B++){let ee=Number.NEGATIVE_INFINITY,re=new Set;for(let Ge=0;Ge<f.length;Ge++){let ue=f[Ge][B];ue>ee+this.tieEpsilon?(ee=ue,re.clear(),re.add(Ge)):Math.abs(ue-ee)<=this.tieEpsilon&&re.add(Ge)}S.push(re)}let _=f.map(B=>ut(B));return cn(S,_)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let y=0,I=je(m.map((C,S)=>({idx:S,scores:C.scores})),this.tieEpsilon).map(C=>C.idx),T,b=r?.maxMetricCalls;if(!Number.isFinite(b)||b<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let w=Math.floor(b);for(let C=0;C<this.numTrials&&!(w!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(w)));C++){let S=f[0]?.length??0,_=[];for(let O=0;O<S;O++){let N=Number.NEGATIVE_INFINITY,q=new Set;for(let z=0;z<f.length;z++){let j=f[z][O];j>N+this.tieEpsilon?(N=j,q.clear(),q.add(z)):Math.abs(j-N)<=this.tieEpsilon&&q.add(z)}_.push(q)}let B=f.map(O=>ut(O));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let O=k=>{let M=[],P=k;for(;P!==void 0;)M.push(P),P=m[P]?.parent;return M},N=k=>k.length?k[Math.floor(this.rand()*k.length)]:void 0,q=ln(_,B),z=new Set;for(let k of q)for(let M of k)z.add(M);let j=Array.from(z),X;for(let k=0;k<10&&!X&&!(j.length<2);k++){let M=N(j),P=N(j);if(M===P)continue;P<M&&([M,P]=[P,M]);let J=new Set(O(M)),ie=new Set(O(P));if(J.has(P)||ie.has(M))continue;let Y=[...J].filter(oe=>ie.has(oe));if(Y.length===0)continue;let H=Y.map(oe=>Math.max(1e-9,B[oe])),W=this.rand()*H.reduce((oe,ke)=>oe+ke,0),V=Y[Y.length-1];for(let oe=0;oe<Y.length;oe++){if(W<H[oe]){V=Y[oe];break}W-=H[oe]}X={i:M,j:P,a:V}}if(this.lastIterFoundNewProgram=!1,X){let{i:k,j:M,a:P}=X,J=B[P],ie=B[k],Y=B[M],H=m[P].instruction,W=m[k].instruction,V=m[M].instruction,oe=W===H&&V!==W||V===H&&W!==V,ke=J<=Math.min(ie,Y)&&oe,Ie="",Te="i",Ye=!1;if(ke){let He=`${k}|${M}|${P}`;if(this.mergeAttemptKeys.has(He))ke=!1;else{W===H&&V!==W?(Ie=V,Te="j"):V===H&&W!==V?(Ie=W,Te="i"):W!==H&&V!==H&&W!==V?ie>Y||ie===Y&&this.rand()<.5?(Ie=W,Te="i"):(Ie=V,Te="j"):(Ie=W,Te="i");let ne=`${Math.min(k,M)}|${Math.max(k,M)}|${Te}`;if(this.mergeCompositionKeys.has(ne))ke=!1;else{this.mergeAttemptKeys.add(He),this.mergeCompositionKeys.add(ne);let Ee=f[k],Ke=f[M],Se=Array.from({length:Ee.length},(Z,fe)=>fe),Xe=Se.filter(Z=>(Ee[Z]??0)>(Ke[Z]??0)),dt=Se.filter(Z=>(Ke[Z]??0)>(Ee[Z]??0)),nt=Se.filter(Z=>!(Xe.includes(Z)||dt.includes(Z))),We=5,Ze=Math.ceil(We/3),G=(Z,fe)=>{if(fe<=0||Z.length===0)return[];if(Z.length<=fe)return[...Z];let Ct=[],gn=new Set;for(;Ct.length<fe;){let Pe=Math.floor(this.rand()*Z.length);gn.has(Pe)||(gn.add(Pe),Ct.push(Z[Pe]))}return Ct},te=[];te.push(...G(Xe,Math.min(Ze,Xe.length))),te.push(...G(dt,Math.min(Ze,dt.length)));let rt=We-te.length;te.push(...G(nt,Math.max(0,rt)));let ot=We-te.length;if(ot>0){let Z=Se.filter(fe=>!te.includes(fe));te.push(...G(Z,Math.min(ot,Z.length)))}let he=te.slice(0,Math.min(We,Se.length)),yr=he.map(Z=>l[Z]);Ye=!0;let ha=(await h(Ie,yr)).reduce((Z,fe)=>Z+fe,0),fa=he.reduce((Z,fe)=>Z+(Ee[fe]??0),0),Aa=he.reduce((Z,fe)=>Z+(Ke[fe]??0),0);if(ha>=Math.max(fa,Aa)+this.tieEpsilon){let Z=await u(Ie,l);m.push({instruction:Ie,parent:P,scores:Z}),f.push(await h(Ie,l));let fe=I.length,Ct=Oe(I.map(Pe=>m[Pe].scores))??0;I=je(m.map((Pe,xa)=>({idx:xa,scores:Pe.scores})),this.tieEpsilon).map(Pe=>Pe.idx);let gn=Oe(I.map(Pe=>m[Pe].scores))??0;(I.length>fe||gn>Ct+1e-6)&&(y=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(Ye)continue}}let ee=cn(_,B,()=>this.rand()),re=this.minibatch?this.nextMinibatchIndices(c.length,C).map(O=>c[O]):c;if(r?.skipPerfectScore??!0){let O=Number(r?.perfectScore??1),N=await h(m[ee].instruction,re);if(N.length>0&&N.every(q=>q>=O))continue}let Ge=!1,ue=m[ee].instruction,me="reflective_mutation",Me,Qe;if(Ge){let O=(ee+1)%m.length;ue=await this.mergeInstructions(m[ee].instruction,m[O].instruction,r),me="merge",this.mergesUsed+=1}else{let O=r?.gepaAdapter;if(O){try{let N={instruction:m[ee].instruction},q=await O.evaluate(re,N,!0);Me=Array.isArray(q?.scores)?q.scores.reduce((k,M)=>k+(Number(M)||0),0):void 0;let z=O.make_reflective_dataset(N,q,["instruction"]),j=await O.propose_new_texts?.(N,z,["instruction"]),X=j?.instruction??(j?Object.values(j)[0]:void 0);typeof X=="string"&&X.length>0?ue=X:ue=await this.reflectInstruction(m[ee].instruction,e,re,async({prediction:k,example:M})=>{let P=await n({prediction:k,example:M}),J=Object.values(P||{});return J.length?J.reduce((ie,Y)=>ie+Y,0)/J.length:0},r)}catch{ue=await this.reflectInstruction(m[ee].instruction,e,re,async({prediction:N,example:q})=>{let z=await n({prediction:N,example:q}),j=Object.values(z||{});return j.length?j.reduce((X,k)=>X+k,0)/j.length:0},r)}if(Me!==void 0)try{let N=await O.evaluate(re,{instruction:ue},!1);Qe=Array.isArray(N?.scores)?N.scores.reduce((q,z)=>q+(Number(z)||0),0):void 0}catch{}}else ue=await this.reflectInstruction(m[ee].instruction,e,re,async({prediction:N,example:q})=>{let z=await n({prediction:N,example:q}),j=Object.values(z||{});return j.length?j.reduce((X,k)=>X+k,0)/j.length:0},r)}let dr=await h(m[ee].instruction,re),mr=await h(ue,re),gr=dr.reduce((O,N)=>O+N,0),tt=mr.reduce((O,N)=>O+N,0);if(this.currentRound=C+1,await this.updateOptimizationProgress(this.currentRound,tt,{instructionLen:ue.length,parent:ee,totalRounds:this.numTrials},"GEPA",{strategy:me,paretoSetSize:l.length},tt,{instructionLen:m[ee].instruction.length,idx:ee},{...r??{},maxIterations:this.numTrials}),!(tt>gr+this.tieEpsilon&&(Me===void 0||Qe===void 0||Qe>Me+this.tieEpsilon))){if(++y>=this.earlyStoppingTrials)break;continue}let hr=await u(ue,l);m.push({instruction:ue,parent:ee,scores:hr}),f.push(await h(ue,l));let fr=I.length,Ar=Oe(I.map(O=>m[O].scores))??0;I=je(m.map((O,N)=>({idx:N,scores:O.scores})),this.tieEpsilon).map(O=>O.idx);let xr=Oe(I.map(O=>m[O].scores))??0;if(I.length>fr||xr>Ar+1e-6)y=0;else if(y++,y>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let v=je(m.map((C,S)=>({idx:S,scores:C.scores})),this.tieEpsilon),F=v.length>0?Math.max(...v.map(C=>g(C.scores))):0,K;if(v.length>0){let C=Number.NEGATIVE_INFINITY;for(let S of v){let _=g(S.scores);_>C&&(C=_,K=S.idx)}}let E=Oe(v.map(C=>C.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(v.length,m.length,"GEPA",E);let R=Date.now()-o,$=typeof K=="number"?new pt({bestScore:F,stats:this.stats,instruction:m[K].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:R,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(v,E,F),{demos:[],stats:this.stats,bestScore:F,paretoFront:v.map(C=>({demos:[],scores:C.scores,configuration:{candidate:C.idx},dominatedSolutions:C.dominated})),paretoFrontSize:v.length,hypervolume:E,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:$}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){try{let t=e.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?ut(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o){let s=[];for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let f=await r({prediction:g,example:m});s.push({input:m,prediction:g,score:typeof f=="number"?f:0})}catch{s.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=we('minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback per case if available" -> feedbackSummary:string "Concise feedback: common errors, missing constraints, desired changes"'),c=[],p=o?.feedbackFn;if(typeof p=="function")for(let m=0;m<s.length;m++)try{let g=p({prediction:s[m].prediction,example:s[m].input});g&&(Array.isArray(g)?c.push(...g):c.push(g))}catch{}let u="";try{u=(await l.forward(a,{minibatch:s,evalFeedback:c}))?.feedbackSummary?.trim()||"",u&&(this.feedbackMemory.unshift(u),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop())}catch{}let d=we('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let g=(await d.forward(a,{currentInstruction:e,feedbackSummary:u,recentFeedback:this.feedbackMemory,minibatch:s}))?.newInstruction?.trim();if(g&&g.length>16)return g}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){console.log(`
301
+ ${e}`}i(n)}},or=la();var ca={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},sr,pc=i=>{if(sr)return sr;if(i)return sr=mc(i),sr};var ir=ca,uc=i=>{ir={...ir,...i}},dc=()=>({...ir}),mc=i=>({optimizationLatencyHistogram:i.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:i.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:i.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:i.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:i.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:i.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:i.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:i.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:i.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:i.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:i.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:i.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:i.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:i.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:i.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:i.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:i.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:i.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:i.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:i.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:i.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:i.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:i.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:i.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:i.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:i.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:i.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:i.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:i.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:i.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:i.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:i.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),Ue=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),o=ir.maxLabelLength;e[t]=r.length>o?r.substring(0,o):r}return e},gc=(i,e,t,n,r)=>{try{let o=Ue({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{}});i.optimizationLatencyHistogram&&i.optimizationLatencyHistogram.record(e,o),i.optimizationRequestsCounter&&i.optimizationRequestsCounter.add(1,o),!t&&i.optimizationErrorsCounter&&i.optimizationErrorsCounter.add(1,o)}catch(o){console.warn("Failed to record optimization metric:",o)}},hc=(i,e,t,n,r,o)=>{try{let s=Ue({optimizer_type:o});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,s),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,s),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,s),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,s)}catch(s){console.warn("Failed to record convergence metric:",s)}},fc=(i,e,t)=>{try{let n=Ue({reason:e,optimizer_type:t});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Ac=(i,e,t,n,r)=>{try{let o=Ue({optimizer_type:n});i.tokenUsageCounter&&i.tokenUsageCounter.add(e,o),i.costUsageCounter&&i.costUsageCounter.add(t,o),r!==void 0&&i.memoryUsageGauge&&i.memoryUsageGauge.record(r,o)}catch(o){console.warn("Failed to record resource usage metric:",o)}},xc=(i,e,t)=>{try{let n=Ue({optimizer_type:t});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},yc=(i,e,t,n)=>{try{let r=Ue({optimizer_type:n});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,r),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,r),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,r)}catch(r){console.warn("Failed to record teacher-student metric:",r)}},bc=(i,e,t,n,r)=>{try{let o=Ue({operation:e,success:n.toString(),optimizer_type:r});e==="save"?(i.checkpointSaveCounter&&i.checkpointSaveCounter.add(1,o),i.checkpointSaveLatencyHistogram&&i.checkpointSaveLatencyHistogram.record(t,o)):(i.checkpointLoadCounter&&i.checkpointLoadCounter.add(1,o),i.checkpointLoadLatencyHistogram&&i.checkpointLoadLatencyHistogram.record(t,o))}catch(o){console.warn("Failed to record checkpoint metric:",o)}},Ic=(i,e,t,n,r)=>{try{let o=Ue({optimizer_type:n});i.paretoOptimizationsCounter&&i.paretoOptimizationsCounter.add(1,o),i.paretoFrontSizeHistogram&&i.paretoFrontSizeHistogram.record(e,o),r!==void 0&&i.paretoHypervolumeGauge&&i.paretoHypervolumeGauge.record(r,o),i.paretoSolutionsGeneratedHistogram&&i.paretoSolutionsGeneratedHistogram.record(t,o)}catch(o){console.warn("Failed to record Pareto metric:",o)}},Tc=(i,e,t,n,r,o)=>{try{let s=Ue({optimizer_type:o});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,s),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,s),i.examplesCountGauge&&i.examplesCountGauge.record(n,s),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,s)}catch(s){console.warn("Failed to record program complexity metric:",s)}},Cc=(i,e,t,n)=>{try{let r=Ue({metric_type:e,optimizer_type:n});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,r);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,r);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,r);break}}catch(r){console.warn("Failed to record optimizer performance metric:",r)}},Rc=(i,e,t,n)=>{try{let r=Ue({optimizer_type:e});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,r),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,r),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,r)}catch(r){console.warn("Failed to record optimizer configuration metric:",r)}},Ye=class{bestScore;stats;instruction;demos;examples;modelConfig;optimizerType;optimizationTime;totalRounds;converged;scoreHistory;configurationHistory;constructor(e){this.bestScore=e.bestScore,this.stats=e.stats,this.instruction=e.instruction,this.demos=e.demos,this.examples=e.examples,this.modelConfig=e.modelConfig,this.optimizerType=e.optimizerType,this.optimizationTime=e.optimizationTime,this.totalRounds=e.totalRounds,this.converged=e.converged,this.scoreHistory=e.scoreHistory,this.configurationHistory=e.configurationHistory}applyTo(e){this.demos&&this.demos.length>0&&e.setDemos(this.demos),this.examples&&this.examples.length>0&&e.setExamples(this.examples),this.instruction&&(e._optimizedInstruction=this.instruction),this.modelConfig&&(e._optimizedModelConfig=this.modelConfig)}},ar=class{tokenUsage={};totalTokens=0;costPerModel;maxCost;maxTokens;constructor(e){this.costPerModel=e?.costPerModel??{},this.maxCost=e?.maxCost,this.maxTokens=e?.maxTokens}trackTokens(e,t){this.tokenUsage[t]=(this.tokenUsage[t]||0)+e,this.totalTokens+=e}getCurrentCost(){let e=0;for(let[t,n]of Object.entries(this.tokenUsage)){let r=this.costPerModel[t]||.001;e+=n/1e3*r}return e}getTokenUsage(){return{...this.tokenUsage}}getTotalTokens(){return this.totalTokens}isLimitReached(){return this.maxTokens!==void 0&&this.totalTokens>=this.maxTokens||this.maxCost!==void 0&&this.getCurrentCost()>=this.maxCost}reset(){this.tokenUsage={},this.totalTokens=0}},Oe=class{studentAI;teacherAI;targetScore;minSuccessRate;onProgress;onEarlyStop;costTracker;seed;checkpointSave;checkpointLoad;checkpointInterval;resumeFromCheckpoint;logger;verbose;debugOptimizer;optimizerLogger;currentRound=0;scoreHistory=[];configurationHistory=[];stats;metricsInstruments;resultExplainer;constructor(e){this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.targetScore=e.targetScore,this.minSuccessRate=e.minSuccessRate,this.onProgress=e.onProgress,this.onEarlyStop=e.onEarlyStop,this.seed=e.seed,this.checkpointSave=e.checkpointSave,this.checkpointLoad=e.checkpointLoad,this.checkpointInterval=e.checkpointInterval??10,this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new ar({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=pc(ie.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?or:void 0),this.initializeResultExplainer()}initializeResultExplainer(){this.resultExplainer=void 0}initializeStats(){return{totalCalls:0,successfulDemos:0,estimatedTokenUsage:0,earlyStopped:!1,resourceUsage:{totalTokens:0,totalTime:0,avgLatencyPerEval:0,costByModel:{}},convergenceInfo:{converged:!1,finalImprovement:0,stagnationRounds:0,convergenceThreshold:.01},bestScore:0,bestConfiguration:{}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return this.costTracker?.isLimitReached()??!1}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:e,finalScore:this.stats.bestScore??0,round:t}})}validateExamples(e,t=!0){if(!e||e.length===0)throw new Error("At least 1 example is required for optimization");if(t&&e.length<2)throw new Error("At least 2 examples are required for optimization with auto-splitting. Provide more examples to enable proper train/validation split.");let n=t?10:5;e.length<n&&this.verbose&&console.warn(`[Ax Optimizer] Warning: Only ${e.length} examples provided. Consider providing more examples (${n}+ recommended) for better optimization results.`)}getAIService(e=!1,t){return e&&t?.overrideTeacherAI?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return e?.overrideTeacherAI!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return e?.overrideTeacherAI||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let r=this.getAIService(t,n);return await e(r)}async*compileStream(e,t,n,r){let o=Date.now(),s=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(s,a);let l,c=(g,f,h,x,A,y,I,T={},C)=>{this.getOptimizerLogger(C)?.({name:"RoundProgress",value:{round:g,totalRounds:C?.maxIterations??0,currentScore:f,bestScore:y,configuration:h}}),this.updateOptimizationProgress(g,f,h,x,A,y,I,T,C)},p=(g,f)=>{l=g,this.triggerEarlyStopping(g,this.currentRound)},u=g=>{this.onProgress?.(g),c(g.round,g.currentScore,g.currentConfiguration||{},s,{},g.bestScore,g.bestConfiguration,g.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:u,overrideOnEarlyStop:p}),m=Date.now()-o;return this.recordOptimizationComplete(m,!0,s,a),l&&this.getLogger(r)?.({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${l}`}),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n,r){let o=this.constructor.name,s=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],p=this.findParetoFrontier(c),u=this.calculateHypervolume(p);this.updateResourceUsage(s),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(p.length,c.length,"base_optimizer",u);let d=p.length>0?Math.max(...p.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:p.length>0?[...p[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:p,hypervolume:u,paretoFrontSize:p.length,finalConfiguration:{paretoFrontSize:p.length,hypervolume:u,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l),p=this.generateWeightCombinations(c);for(let u=0;u<p.length;u++){let d=p[u],m=async({prediction:g,example:f})=>{let h=await n({prediction:g,example:f}),x=0;for(let[A,y]of Object.entries(h))x+=y*(d[A]||0);return x};try{let g=await this.compile(e,t,m,{...r,verbose:!1}),f=await this.evaluateWithMultiObjective(e,g,n,t);o.push({scores:f,demos:g.demos,configuration:{...g.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return o}async generateConstraintSolutions(e,t,n,r){let o=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let s=t[0],a=await e.forward(this.getAIService(!1,r),s),l=await n({prediction:a,example:s}),c=Object.keys(l);for(let p of c){let u=async({prediction:d,example:m})=>{let g=await n({prediction:d,example:m}),f=g[p]||0,h=0;for(let[x,A]of Object.entries(g))x!==p&&A<.3&&(h+=(.3-A)*2);return f-h};try{let d=await this.compile(e,t,u,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);o.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:p,strategy:"constraint_based"}})}catch{}}return o}generateWeightCombinations(e){let t=[];for(let r of e){let o={};for(let s of e)o[s]=s===r?1:0;t.push(o)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,o]=e;for(let s=.1;s<=.9;s+=.2){let a=1-s;t.push({[r]:s,[o]:a})}}if(e.length===3){let[r,o,s]=e;t.push({[r]:.5,[o]:.3,[s]:.2},{[r]:.3,[o]:.5,[s]:.2},{[r]:.2,[o]:.3,[s]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let o=new ve(e.getSignature());t.demos&&o.setDemos(t.demos);let s=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},p=l;for(let d of p)try{let m=await o.forward(this.studentAI,d),g=await n({prediction:m,example:d});for(let[f,h]of Object.entries(g))c[f]||(c[f]=[]),c[f].push(h)}catch{}let u={};for(let[d,m]of Object.entries(c))u[d]=m.length>0?m.reduce((g,f)=>g+f,0)/m.length:0;return u}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],o=!1,s=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){o=!0;break}this.dominates(r.scores,l.scores)&&s++}o||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:s})}return t}dominates(e,t){let n=Object.keys(e),r=!0,o=!1;for(let s of n){let a=e[s]||0,l=t[s]||0;if(a<l){r=!1;break}a>l&&(o=!0)}return r&&o}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,o]=n,s=0,a=[...e].sort((c,p)=>(p.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let p=c.scores[r]||0,u=c.scores[o]||0;s+=p*(u-l),l=Math.max(l,u)}return s}}async saveCheckpoint(e,t,n,r,o={},s){let a=s?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,p;try{let u={version:"1.0.0",timestamp:Date.now(),optimizerType:e,optimizerConfig:t,currentRound:this.currentRound,totalRounds:this.stats.resourceUsage.totalTime>0?this.currentRound:0,bestScore:n,bestConfiguration:r,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:o,examples:[]};p=await a(u),c=!0}catch(u){throw c=!1,u}finally{let u=Date.now()-l;this.recordCheckpointMetrics("save",u,c,e)}return p}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),o=!1,s=null;try{s=await n(e),o=s!==null}catch(a){throw o=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,o,"unknown")}return s}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=t?.overrideCheckpointInterval||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,r,o,s,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,o,s,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:s,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,o={},s){s?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...o,final:!0},s)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return e?.verbose!==void 0?e.verbose:this.verbose??!0}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,r=(t.match(/output:/g)||[]).length;Tc(this.metricsInstruments,n,r,0,0,e)}Rc(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,r){if(!this.metricsInstruments)return;gc(this.metricsInstruments,e,t,n,r),xc(this.metricsInstruments,e,n);let o=this.costTracker?.getCurrentCost()??0,s=this.costTracker?.getTotalTokens()??0;Ac(this.metricsInstruments,s,o,n)}recordConvergenceMetrics(e,t,n,r,o){this.metricsInstruments&&hc(this.metricsInstruments,e,t,n,r,o)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&fc(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&yc(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,r){this.metricsInstruments&&bc(this.metricsInstruments,e,t,n,r)}recordParetoMetrics(e,t,n,r){this.metricsInstruments&&Ic(this.metricsInstruments,e,t,n,r)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&Cc(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??ie.optimizerLogger??or}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,o=this.stats.totalCalls,s=o>0?this.stats.successfulDemos/o*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${s.toFixed(1)}%.`,l=[];if(r||l.push("Increase numTrials or relax earlyStoppingTrials to allow further improvement."),typeof this.targetScore=="number"&&e<this.targetScore&&l.push("Tighten the metric or supply more/better-labeled examples to reach targetScore."),t&&"bootstrappedDemos"in t){let p=t.bootstrappedDemos;typeof p=="number"&&p===0&&l.push("Consider allowing a small number of bootstrapped demos to boost performance.")}l.length===0&&l.push("Re-run with more trials or different acquisition settings to explore more of the space.");let c=`Tokens used: ${this.stats.resourceUsage.totalTokens}, rounds: ${this.currentRound}, stagnationRounds: ${this.stats.convergenceInfo.stagnationRounds}.`;return{humanExplanation:a,recommendations:l,performanceAssessment:c}}async logOptimizationComplete(e,t,n,r,o){let s=this.getOptimizerLogger(r);s&&s(o?{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",explanation:o.humanExplanation,recommendations:o.recommendations,performanceAssessment:o.performanceAssessment,stats:this.stats}}:{name:"OptimizationComplete",value:{optimizerType:e,bestScore:t,bestConfiguration:n||{},totalCalls:this.stats.totalCalls,successRate:this.stats.totalCalls>0?`${(this.stats.successfulDemos/this.stats.totalCalls*100).toFixed(1)}%`:"N/A",stats:this.stats}})}reset(){this.stats=this.initializeStats(),this.costTracker?.reset(),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}};function wc(i){return pe.create(i)}function fe(i,e){let t=typeof i=="string"?pe.create(i):i;return new ve(t,e)}import Sc from"crypto";function Ko(i){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:i}}function dt(i){return JSON.parse(JSON.stringify(i))}function vc(i){return Math.ceil(i.length/4)}function Wo(i,e,t){let n=[],r=[],{maxSectionSize:o=Number.POSITIVE_INFINITY,allowDynamicSections:s=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),p=l??new Set;for(let u of e){if(!u.section)continue;if(!i.sections[u.section]){if(!s)continue;i.sections[u.section]=[]}let d=i.sections[u.section];switch(u.type){case"ADD":{if(d.length>=o){if(!a)continue;let f=kc(d,p);if(!f)continue;n.push(f.id),r.push({type:"REMOVE",section:u.section,bulletId:f.id,metadata:{...f.metadata??{},autoPruned:!0,removedAt:c}})}let m=u.bulletId??Oc(u.section),g={id:m,section:u.section,content:u.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:u.metadata?{...u.metadata}:void 0};d.push(g),n.push(m);break}case"UPDATE":{let m=d.find(g=>g.id===u.bulletId);if(!m)continue;typeof u.content=="string"&&(m.content=u.content),m.updatedAt=c,u.metadata&&(m.metadata={...m.metadata??{},...u.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(g=>g.id===u.bulletId);if(m>=0){let[g]=d.splice(m,1);g&&n.push(g.id)}break}}}return Qo(i),i.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function Vo(i,e,t){for(let n of Object.values(i.sections)){let r=n.find(o=>o.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),Qo(i);return}}}function ln(i){let e=i.description?`## Context Playbook
302
+ ${i.description.trim()}
303
+ `:`## Context Playbook
304
+ `,t=Object.entries(i.sections).map(([n,r])=>{let o=r.map(s=>`- [${s.id}] ${s.content}`).join(`
305
+ `);return o?`### ${n}
306
+ ${o}`:`### ${n}
307
+ _(empty)_`}).join(`
308
+
309
+ `);return`${e}
310
+ ${t}`.trim()}function Oc(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Sc.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function kc(i,e){let t=-1,n;for(let o=0;o<i.length;o+=1){let s=i[o];if(e.has(s.id))continue;let a=s.helpfulCount??0,l=s.harmfulCount??0,c=a-l*2,p=Date.parse(s.updatedAt??s.createdAt),u=[c,a,Number.isFinite(p)?p:Number.POSITIVE_INFINITY];if(!n){t=o,n=u;continue}let d=i[t],m=d.helpfulCount??0,g=d.harmfulCount??0,f=m-g*2,h=Date.parse(d.updatedAt??d.createdAt),x=[f,m,Number.isFinite(h)?h:Number.POSITIVE_INFINITY];(u[0]<x[0]||u[0]===x[0]&&u[1]<x[1]||u[0]===x[0]&&u[1]===x[1]&&u[2]<x[2])&&(t=o,n=u)}if(t===-1)return;let[r]=i.splice(t,1);return r}function Jo(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,o=[];for(let s of n){let a=s.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=s.helpfulCount,l.harmfulCount+=s.harmfulCount,l.updatedAt=s.updatedAt):(r.set(a,s),o.push(s))}i.sections[t]=o}Qo(i)}function Qo(i){let e=0,t=0,n=0,r=0;for(let o of Object.values(i.sections))for(let s of o)e+=1,t+=s.helpfulCount,n+=s.harmfulCount,r+=vc(s.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Mc={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},lr=class extends Ye{playbook;artifact;baseInstruction;constructor(e){super({bestScore:e.bestScore,stats:e.stats,instruction:e.instruction,demos:e.demos,examples:e.examples,modelConfig:e.modelConfig,optimizerType:e.optimizerType,optimizationTime:e.optimizationTime,totalRounds:e.totalRounds,converged:e.converged,scoreHistory:e.scoreHistory,configurationHistory:e.configurationHistory}),this.playbook=dt(e.playbook),this.artifact=e.artifact,this.baseInstruction=e.baseInstruction}applyTo(e){super.applyTo(e);let t=e.getSignature(),r=[(this.baseInstruction??t.getDescription()??"").trim(),"",ln(this.playbook)].filter(o=>o&&o.trim().length>0).join(`
311
+
312
+ `);e.setDescription(r)}},Yo=class extends Oe{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;constructor(e,t){super(e),this.aceConfig={...Mc,...t},this.playbook=t?.initialPlaybook!==void 0?dt(t.initialPlaybook):Ko()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?dt(this.aceConfig.initialPlaybook):Ko(),this.generatorHistory=[],this.deltaHistory=[]}configureAuto(e){switch(e){case"light":this.aceConfig.maxEpochs=1,this.aceConfig.maxReflectorRounds=1;break;case"medium":this.aceConfig.maxEpochs=2,this.aceConfig.maxReflectorRounds=2;break;case"heavy":this.aceConfig.maxEpochs=3,this.aceConfig.maxReflectorRounds=3;break}}async compile(e,t,n,r){let o=r?.aceOptions;o&&(Object.assign(this.aceConfig,{maxEpochs:o.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:o.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:o.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:o.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:o.allowDynamicSections??this.aceConfig.allowDynamicSections}),o.initialPlaybook&&(this.playbook=dt(o.initialPlaybook)));let s=Date.now();this.validateExamples(t);let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,p=0,u=Math.max(this.aceConfig.maxEpochs,1),d=u*t.length;try{for(let x=0;x<u;x++)for(let A=0;A<t.length;A++){let y=t[A],I=this.composeInstruction(a??l,this.playbook);e.setDescription?.(I);let T=await e.forward(this.studentAI,y);this.stats.totalCalls+=1;let C=await n({prediction:T,example:y});typeof C=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,C),c=Math.max(c,C));let b=T?.severity,v=y?.severity,P=this.createGeneratorOutput(T,y),K=v&&b&&v!==b,O=await this.runReflectionRounds({example:y,generatorOutput:P,feedback:v&&b&&v!==b?`Expected severity "${v}" but model predicted "${b}".`:void 0}),w=await this.runCurator({example:y,reflection:O,playbook:this.playbook}),_=this.normalizeCuratorOperations(w?.operations);_.length===0&&K&&(_=this.inferOperationsFromReflection(O)),_=this.resolveCuratorOperationTargets(_,this.playbook,O,P);let R=w||_.length>0?{...w??{},operations:_}:void 0,S=[];if(_.length>0){let Ae=this.collectProtectedBulletIds(_),ce=Wo(this.playbook,_,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:Ae});S=ce.updatedBulletIds,ce.autoRemoved.length>0&&(_.push(...ce.autoRemoved),R&&(R.operations=_))}if(O?.bulletTags)for(let Ae of O.bulletTags)Vo(this.playbook,Ae.id,Ae.tag);_.length>0&&S.length>0&&Jo(this.playbook,this.aceConfig.similarityThreshold);let N={example:y,prediction:T,score:typeof C=="number"?C:0,generatorOutput:P,reflection:O,curator:R,timestamp:new Date().toISOString()};this.generatorHistory.push(N),S.length>0&&R?.operations?.length&&this.deltaHistory.push({epoch:x,exampleIndex:A,operations:R.operations}),p+=1,this.currentRound=p;let G=typeof C=="number"&&Number.isFinite(C)?C:0,Y=Number.isFinite(c)?c:G,te={...r??{},maxIterations:d};await this.updateOptimizationProgress(p,G,{epoch:x,exampleIndex:A,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:u,totalRounds:d},Y,{playbookBullets:this.playbook.stats.bulletCount},void 0,te),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,G)}}finally{e.setDescription?.(l)}let m=Date.now()-s;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let g={playbook:dt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},f=new lr({baseInstruction:a??l,playbook:this.playbook,artifact:g,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:p,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:u},optimizedProgram:f,playbook:dt(this.playbook),artifact:g}}async applyOnlineUpdate(e){let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,o=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),s=await this.runCurator({example:e.example,reflection:o,playbook:this.playbook}),a=this.normalizeCuratorOperations(s?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(o)),a=this.resolveCuratorOperationTargets(a,this.playbook,o,t);let c=s||a.length>0?{...s??{},operations:a}:void 0;if(o?.bulletTags)for(let u of o.bulletTags)Vo(this.playbook,u.id,u.tag);if(a.length>0){let u=this.collectProtectedBulletIds(a),d=Wo(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:u});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Jo(this.playbook,this.aceConfig.similarityThreshold)}let p={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:o,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(p),c}composeInstruction(e,t){return[e.trim(),"",ln(t)].filter(r=>r.trim().length>0).join(`
313
+
314
+ `)}async extractProgramInstruction(e){try{return e.getSignature().getDescription()??void 0}catch{return}}createGeneratorOutput(e,t){let n=e?.thought?.toString()??"",r=Array.isArray(e?.bullet_ids)?e?.bullet_ids:[];return{reasoning:n,answer:e,bulletIds:r,trajectory:JSON.stringify({example:t,prediction:e}),metadata:{predictedSeverity:e?.severity,expectedSeverity:t?.severity}}}resolveCuratorOperationTargets(e,t,n,r){if(!e.length)return e;let o=[],s=new Set(e.map(p=>p.bulletId).filter(p=>typeof p=="string")),a=new Map,l=(p,u)=>{if(s.has(p))return;let d=this.locateBullet(t,p);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[u].push(d.id),a.set(d.section,m)};for(let p of n?.bulletTags??[]){let u=p.tag==="harmful"?"harmful":"primary";l(p.id,u)}if(r?.bulletIds)for(let p of r.bulletIds)l(p,"generator");let c=p=>{let u=a.get(p);if(!u)return this.locateFallbackBullet(t,p,s);let d=g=>{for(;g.length>0;){let f=g.shift();if(!s.has(f))return f}},m=d(u.harmful)??d(u.primary)??d(u.generator);return m||this.locateFallbackBullet(t,p,s)};for(let p of e){if((p.type==="UPDATE"||p.type==="REMOVE")&&!p.bulletId){let u=c(p.section);u&&(p.bulletId=u,s.add(u))}(p.type==="UPDATE"||p.type==="REMOVE")&&!p.bulletId||o.push(p)}return o}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(o=>o.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let o of r)if(!n.has(o.id))return o.id}collectProtectedBulletIds(e){let t=new Set;for(let n of e)n.type==="UPDATE"&&n.bulletId&&t.add(n.bulletId);return t}normalizeCuratorOperations(e){if(!e)return[];if(Array.isArray(e)){let t=[],n=new Set;for(let r of e){if(!r||typeof r!="object")continue;let o=r.type??"ADD",s=typeof o=="string"?o.toUpperCase():"ADD",a=s==="UPDATE"?"UPDATE":s==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",p=r.content??"",u=typeof p=="string"?p.trim():"";if(a!=="REMOVE"&&u.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,f=[a,c,u,m??""].join(":");if(n.has(f))continue;n.add(f);let h={type:a,section:c};a!=="REMOVE"&&(h.content=u),m&&(h.bulletId=m);let x=r.metadata;x&&typeof x=="object"&&(h.metadata={...x}),t.push(h)}return t}if(typeof e=="string")try{let t=JSON.parse(e);return this.normalizeCuratorOperations(t)}catch{return[]}if(typeof e=="object"){let t=e;if(t&&Array.isArray(t.operations))return this.normalizeCuratorOperations(t.operations);if(t&&typeof t.operations=="string")try{let n=JSON.parse(t.operations);return this.normalizeCuratorOperations(n)}catch{return[]}return[]}return[]}inferOperationsFromReflection(e){if(!e)return[];let t=[],n=new Set,r=(o,s)=>{if(!s)return;let a=s.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${o}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:o,content:a}))};return r("Guidelines",e.keyInsight),r("Response Strategies",e.correctApproach),r("Common Pitfalls",e.errorIdentification),r("Root Cause Notes",e.rootCauseAnalysis),t}async runReflectionRounds({example:e,generatorOutput:t,feedback:n}){let r=Math.max(this.aceConfig.maxReflectorRounds,1),o;for(let s=0;s<r;s++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:o});if(!a)break;o=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return o}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let o=this.getOrCreateReflectorProgram(),s=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint};return await o.forward(s,{question:JSON.stringify(e),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:ln(this.playbook),structured:this.playbook}),expected_answer:a.severity||a.policyHint?JSON.stringify(a):void 0,feedback:n,previous_reflection:r?JSON.stringify(r):void 0})}catch(a){this.verbose&&console.warn("[AxACE] Reflector error:",a instanceof Error?a.message:a);return}}async runCurator({example:e,reflection:t,playbook:n}){if(!t)return;let r=this.getOrCreateCuratorProgram(),o=this.teacherAI??this.studentAI;try{return await r.forward(o,{playbook:JSON.stringify({markdown:ln(n),structured:n}),reflection:JSON.stringify(t),question_context:JSON.stringify(e),token_budget:1024})}catch(s){this.verbose&&console.warn("[AxACE] Curator error:",s instanceof Error?s.message:s);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=re().input("question",re.string("Original task input serialized as JSON")).input("generator_answer",re.string("Generator output serialized as JSON")).input("generator_reasoning",re.string("Generator reasoning trace").optional()).input("playbook",re.string("Current context playbook rendered as markdown")).input("expected_answer",re.string("Expected output when ground truth is available").optional()).input("feedback",re.string("External feedback or reward signal").optional()).input("previous_reflection",re.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",re.string("Step-by-step analysis of generator performance")).output("errorIdentification",re.string("Specific mistakes detected")).output("rootCauseAnalysis",re.string("Underlying cause of the error")).output("correctApproach",re.string("What the generator should do differently")).output("keyInsight",re.string("Reusable insight to remember")).output("bulletTags",re.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=fe(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=re().input("playbook",re.string("Current playbook serialized as JSON")).input("reflection",re.string("Latest reflection output serialized as JSON")).input("question_context",re.string("Original task input serialized as JSON")).input("token_budget",re.number("Approximate token budget for curator response").optional()).output("reasoning",re.string("Justification for the proposed updates")).output("operations",re.json("List of operations with type/section/content fields")).build();this.curatorProgram=fe(e)}return this.curatorProgram}};var cn=class extends Oe{maxRounds;maxDemos;maxExamples;batchSize;earlyStoppingPatience;costMonitoring;maxTokensPerGeneration;verboseMode;debugMode;traces=[];constructor(e){super(e);let t=e.options||{};this.maxRounds=t.maxRounds??3,this.maxDemos=t.maxDemos??4,this.maxExamples=t.maxExamples??16,this.batchSize=t.batchSize??1,this.earlyStoppingPatience=t.earlyStoppingPatience??0,this.costMonitoring=t.costMonitoring??!1,this.maxTokensPerGeneration=t.maxTokensPerGeneration??0,this.verboseMode=t.verboseMode??!0,this.debugMode=t.debugMode??!1}async compileRound(e,t,n,r,o){let s=Date.now(),a=o?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Pc([...t],this.maxExamples),p=this.traces.length;for(let u=0;u<c.length;u+=this.batchSize){u>0&&(l.modelConfig.temperature=.7+.001*u);let d=c.slice(u,u+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let g=t.filter(x=>x!==m);e.setExamples(g);let f=this.getTeacherOrStudentAI();this.stats.totalCalls++;let h;try{let x={...l,maxRetries:1};h=await e.forward(f,m,x),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(h).length/4),await r({prediction:h,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(x){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${x instanceof Error?x.message:"Unknown error"}`),h={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-p;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?n:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=n;else if(n-this.stats.earlyStopping.bestScoreRound>=this.earlyStoppingPatience){this.stats.earlyStopping.patienceExhausted=!0,this.stats.earlyStopped=!0,this.stats.earlyStopping.reason=`No improvement for ${this.earlyStoppingPatience} rounds`;return}}}async compile(e,t,n,r){this.validateExamples(t,!1);let o=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<o&&(await this.compileRound(e,t,l,n,r),!this.stats.earlyStopped);l++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let s=Ec(this.traces),a=0;return this.traces.length>0&&(a=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),await this.logOptimizationComplete("BootstrapFewShot",a,{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a,demosGenerated:s.length,tracesCollected:this.traces.length},r),{demos:s,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Ec(i){let e=new Map;for(let n of i)if(e.has(n.programId)){let r=e.get(n.programId);r&&r.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,r)=>{t.push({traces:n,programId:r})}),t}var Pc=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),o=t[n],s=t[r];if(!o||!s)throw new Error("Invalid array elements");[t[n],t[r]]=[s,o]}return t.slice(0,e)};function pa(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,o=!1;for(let s of n){let a=i[s]??0,l=e[s]??0;if(a+t<l){r=!1;break}a>l+t&&(o=!0)}return r&&o}function He(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,o=!1;for(let s=0;s<i.length;s++)if(n!==s){if(pa(i[s].scores,i[n].scores,e)){o=!0;break}pa(i[n].scores,i[s].scores,e)&&r++}o||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Ee(i){if(i.length===0)return;let e=Object.keys(i[0]??{});if(e.length!==2)return;let[t,n]=e,r=[...i].sort((a,l)=>(l[t]??0)-(a[t]??0)),o=0,s=0;for(let a of r){let l=a[t]??0,c=a[n]??0,p=Math.max(c-s,0);o+=l*p,s=Math.max(s,c)}return o}function mt(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function cr(i){let e={},t={};for(let r of i)for(let[o,s]of Object.entries(r))e[o]=(e[o]||0)+(typeof s=="number"?s:0),t[o]=(t[o]||0)+1;let n={};for(let[r,o]of Object.entries(e))n[r]=o/Math.max(t[r]||1,1);return n}function pn(i,e){let t=new Set;for(let p of i)for(let u of p)t.add(u);let r=[...Array.from(t)].sort((p,u)=>(e[p]??0)-(e[u]??0)),o=new Set,s=(p,u)=>{for(let d of i){if(!d.has(p))continue;let m=!1;for(let g of u)if(d.has(g)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let p of r){if(o.has(p))continue;let u=new Set(r.filter(d=>d!==p&&!o.has(d)));if(s(p,u)){o.add(p),a=!0;break}}}let l=r.filter(p=>!o.has(p)),c=new Set(l);return i.map(p=>{let u=new Set;for(let d of p)c.has(d)&&u.add(d);return u})}function un(i,e,t){let n=pn(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let o=[];for(let[l,c]of Object.entries(r)){let p=Number(l);for(let u=0;u<c;u++)o.push(p)}if(o.length===0)return 0;let s=typeof t=="function"?t():Math.random(),a=Math.floor(s*o.length);return o[a]}var Xo=class extends Oe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;paretoSetSize;crossoverEvery;tieEpsilon;feedbackMemorySize;feedbackMemory=[];mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;rngState=123456789;samplerState={epoch:-1,shuffled:[],freq:new Map};localScoreHistory=[];localConfigurationHistory=[];constructor(e){super(e);let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??20,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(o??Math.max(3,Math.floor(this.numTrials/4))));let s=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(s)?s:0;let a=e?.feedbackMemorySize;this.feedbackMemorySize=Math.max(0,Math.floor(a??4));let l=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(l??0)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.localScoreHistory=[],this.localConfigurationHistory=[],this.feedbackMemory=[],this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}async compile(e,t,n,r){let o=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let s=r?.validationExamples,a=r?.feedbackExamples,l=(s&&s.length>0?s:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,p=async(R,S)=>{try{e.setInstruction?.(R);let N=await e.forward(this.studentAI,S,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:N,example:S})||{}}catch{return{}}},u=async(R,S)=>{let N=[];for(let G of S)N.push(await p(R,G));return cr(N)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await u(d,l)}],g=R=>{let S=r?.paretoMetricKey,N=r?.paretoScalarize;if(typeof N=="function")return N(R);if(S)return Number.isFinite(R[S])?R[S]:0;let G=Object.values(R);return G.length?G.reduce((Y,te)=>Y+te,0)/G.length:0},f=[],h=async(R,S)=>{let N=[];for(let G of S){let Y=await p(R,G);N.push(g(Y))}return N};f.push(await h(d,l));let x=()=>{let R=f[0]?.length??0,S=[];for(let G=0;G<R;G++){let Y=Number.NEGATIVE_INFINITY,te=new Set;for(let Ae=0;Ae<f.length;Ae++){let ce=f[Ae][G];ce>Y+this.tieEpsilon?(Y=ce,te.clear(),te.add(Ae)):Math.abs(ce-Y)<=this.tieEpsilon&&te.add(Ae)}S.push(te)}let N=f.map(G=>mt(G));return un(S,N)};this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let y=0,I=He(m.map((R,S)=>({idx:S,scores:R.scores})),this.tieEpsilon).map(R=>R.idx),T,C=r?.maxMetricCalls;if(!Number.isFinite(C)||C<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let b=Math.floor(C);for(let R=0;R<this.numTrials&&!(b!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(b)));R++){let S=f[0]?.length??0,N=[];for(let k=0;k<S;k++){let D=Number.NEGATIVE_INFINITY,q=new Set;for(let z=0;z<f.length;z++){let j=f[z][k];j>D+this.tieEpsilon?(D=j,q.clear(),q.add(z)):Math.abs(j-D)<=this.tieEpsilon&&q.add(z)}N.push(q)}let G=f.map(k=>mt(k));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let k=E=>{let M=[],F=E;for(;F!==void 0;)M.push(F),F=m[F]?.parent;return M},D=E=>E.length?E[Math.floor(this.rand()*E.length)]:void 0,q=pn(N,G),z=new Set;for(let E of q)for(let M of E)z.add(M);let j=Array.from(z),Z;for(let E=0;E<10&&!Z&&!(j.length<2);E++){let M=D(j),F=D(j);if(M===F)continue;F<M&&([M,F]=[F,M]);let J=new Set(k(M)),ae=new Set(k(F));if(J.has(F)||ae.has(M))continue;let X=[...J].filter(se=>ae.has(se));if(X.length===0)continue;let H=X.map(se=>Math.max(1e-9,G[se])),W=this.rand()*H.reduce((se,Fe)=>se+Fe,0),V=X[X.length-1];for(let se=0;se<X.length;se++){if(W<H[se]){V=X[se];break}W-=H[se]}Z={i:M,j:F,a:V}}if(this.lastIterFoundNewProgram=!1,Z){let{i:E,j:M,a:F}=Z,J=G[F],ae=G[E],X=G[M],H=m[F].instruction,W=m[E].instruction,V=m[M].instruction,se=W===H&&V!==W||V===H&&W!==V,Fe=J<=Math.min(ae,X)&&se,we="",Se="i",Ze=!1;if(Fe){let Ke=`${E}|${M}|${F}`;if(this.mergeAttemptKeys.has(Ke))Fe=!1;else{W===H&&V!==W?(we=V,Se="j"):V===H&&W!==V?(we=W,Se="i"):W!==H&&V!==H&&W!==V?ae>X||ae===X&&this.rand()<.5?(we=W,Se="i"):(we=V,Se="j"):(we=W,Se="i");let oe=`${Math.min(E,M)}|${Math.max(E,M)}|${Se}`;if(this.mergeCompositionKeys.has(oe))Fe=!1;else{this.mergeAttemptKeys.add(Ke),this.mergeCompositionKeys.add(oe);let _e=f[E],We=f[M],ke=Array.from({length:_e.length},(ee,ye)=>ye),et=ke.filter(ee=>(_e[ee]??0)>(We[ee]??0)),gt=ke.filter(ee=>(We[ee]??0)>(_e[ee]??0)),ot=ke.filter(ee=>!(et.includes(ee)||gt.includes(ee))),Ve=5,tt=Math.ceil(Ve/3),U=(ee,ye)=>{if(ye<=0||ee.length===0)return[];if(ee.length<=ye)return[...ee];let St=[],fn=new Set;for(;St.length<ye;){let Ne=Math.floor(this.rand()*ee.length);fn.has(Ne)||(fn.add(Ne),St.push(ee[Ne]))}return St},ne=[];ne.push(...U(et,Math.min(tt,et.length))),ne.push(...U(gt,Math.min(tt,gt.length)));let st=Ve-ne.length;ne.push(...U(ot,Math.max(0,st)));let it=Ve-ne.length;if(it>0){let ee=ke.filter(ye=>!ne.includes(ye));ne.push(...U(ee,Math.min(it,ee.length)))}let xe=ne.slice(0,Math.min(Ve,ke.length)),Tr=xe.map(ee=>l[ee]);Ze=!0;let Ra=(await h(we,Tr)).reduce((ee,ye)=>ee+ye,0),wa=xe.reduce((ee,ye)=>ee+(_e[ye]??0),0),Sa=xe.reduce((ee,ye)=>ee+(We[ye]??0),0);if(Ra>=Math.max(wa,Sa)+this.tieEpsilon){let ee=await u(we,l);m.push({instruction:we,parent:F,scores:ee}),f.push(await h(we,l));let ye=I.length,St=Ee(I.map(Ne=>m[Ne].scores))??0;I=He(m.map((Ne,va)=>({idx:va,scores:Ne.scores})),this.tieEpsilon).map(Ne=>Ne.idx);let fn=Ee(I.map(Ne=>m[Ne].scores))??0;(I.length>ye||fn>St+1e-6)&&(y=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(Ze)continue}}let Y=un(N,G,()=>this.rand()),te=this.minibatch?this.nextMinibatchIndices(c.length,R).map(k=>c[k]):c;if(r?.skipPerfectScore??!0){let k=Number(r?.perfectScore??1),D=await h(m[Y].instruction,te);if(D.length>0&&D.every(q=>q>=k))continue}let Ae=!1,ce=m[Y].instruction,ge="reflective_mutation",Pe,Xe;if(Ae){let k=(Y+1)%m.length;ce=await this.mergeInstructions(m[Y].instruction,m[k].instruction,r),ge="merge",this.mergesUsed+=1}else{let k=r?.gepaAdapter;if(k){try{let D={instruction:m[Y].instruction},q=await k.evaluate(te,D,!0);Pe=Array.isArray(q?.scores)?q.scores.reduce((E,M)=>E+(Number(M)||0),0):void 0;let z=k.make_reflective_dataset(D,q,["instruction"]),j=await k.propose_new_texts?.(D,z,["instruction"]),Z=j?.instruction??(j?Object.values(j)[0]:void 0);typeof Z=="string"&&Z.length>0?ce=Z:ce=await this.reflectInstruction(m[Y].instruction,e,te,async({prediction:E,example:M})=>{let F=await n({prediction:E,example:M}),J=Object.values(F||{});return J.length?J.reduce((ae,X)=>ae+X,0)/J.length:0},r)}catch{ce=await this.reflectInstruction(m[Y].instruction,e,te,async({prediction:D,example:q})=>{let z=await n({prediction:D,example:q}),j=Object.values(z||{});return j.length?j.reduce((Z,E)=>Z+E,0)/j.length:0},r)}if(Pe!==void 0)try{let D=await k.evaluate(te,{instruction:ce},!1);Xe=Array.isArray(D?.scores)?D.scores.reduce((q,z)=>q+(Number(z)||0),0):void 0}catch{}}else ce=await this.reflectInstruction(m[Y].instruction,e,te,async({prediction:D,example:q})=>{let z=await n({prediction:D,example:q}),j=Object.values(z||{});return j.length?j.reduce((Z,E)=>Z+E,0)/j.length:0},r)}let hr=await h(m[Y].instruction,te),fr=await h(ce,te),Ar=hr.reduce((k,D)=>k+D,0),rt=fr.reduce((k,D)=>k+D,0);if(this.currentRound=R+1,await this.updateOptimizationProgress(this.currentRound,rt,{instructionLen:ce.length,parent:Y,totalRounds:this.numTrials},"GEPA",{strategy:ge,paretoSetSize:l.length},rt,{instructionLen:m[Y].instruction.length,idx:Y},{...r??{},maxIterations:this.numTrials}),!(rt>Ar+this.tieEpsilon&&(Pe===void 0||Xe===void 0||Xe>Pe+this.tieEpsilon))){if(++y>=this.earlyStoppingTrials)break;continue}let xr=await u(ce,l);m.push({instruction:ce,parent:Y,scores:xr}),f.push(await h(ce,l));let yr=I.length,br=Ee(I.map(k=>m[k].scores))??0;I=He(m.map((k,D)=>({idx:D,scores:k.scores})),this.tieEpsilon).map(k=>k.idx);let Ir=Ee(I.map(k=>m[k].scores))??0;if(I.length>yr||Ir>br+1e-6)y=0;else if(y++,y>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let v=He(m.map((R,S)=>({idx:S,scores:R.scores})),this.tieEpsilon),P=v.length>0?Math.max(...v.map(R=>g(R.scores))):0,K;if(v.length>0){let R=Number.NEGATIVE_INFINITY;for(let S of v){let N=g(S.scores);N>R&&(R=N,K=S.idx)}}let O=Ee(v.map(R=>R.scores));this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(v.length,m.length,"GEPA",O);let w=Date.now()-o,_=typeof K=="number"?new Ye({bestScore:P,stats:this.stats,instruction:m[K].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:w,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0;return this.generateOptimizationReport(v,O,P),{demos:[],stats:this.stats,bestScore:P,paretoFront:v.map(R=>({demos:[],scores:R.scores,configuration:{candidate:R.idx},dominatedSolutions:R.dominated})),paretoFrontSize:v.length,hypervolume:O,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:_}}configureAuto(e){switch(e){case"light":this.numTrials=10,this.minibatch=!0,this.minibatchSize=15;break;case"medium":this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numTrials=35,this.minibatch=!0,this.minibatchSize=35;break}}async getBaseInstruction(e){try{let t=e.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?mt(o):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});if(typeof s=="number"&&!Number.isNaN(s)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return s>=a&&(this.stats.successfulDemos+=1),s}return 0}catch(o){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(o)}),0}}async reflectInstruction(e,t,n,r,o){let s=[];for(let m of n)try{t.setInstruction?.(e);let g=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let f=await r({prediction:g,example:m});s.push({input:m,prediction:g,score:typeof f=="number"?f:0})}catch{s.push({input:m,prediction:{},score:0})}let a=o?.overrideTeacherAI??this.teacherAI??this.studentAI,l=fe('minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback per case if available" -> feedbackSummary:string "Concise feedback: common errors, missing constraints, desired changes"'),c=[],p=o?.feedbackFn;if(typeof p=="function")for(let m=0;m<s.length;m++)try{let g=p({prediction:s[m].prediction,example:s[m].input});g&&(Array.isArray(g)?c.push(...g):c.push(g))}catch{}let u="";try{u=(await l.forward(a,{minibatch:s,evalFeedback:c}))?.feedbackSummary?.trim()||"",u&&(this.feedbackMemory.unshift(u),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop())}catch{}let d=fe('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let g=(await d.forward(a,{currentInstruction:e,feedbackSummary:u,recentFeedback:this.feedbackMemory,minibatch:s}))?.newInstruction?.trim();if(g&&g.length>16)return g}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}generateOptimizationReport(e,t,n){console.log(`
301
315
  \u{1F389} GEPA Multi-Objective Optimization Complete!
302
316
  `),console.log("\u2705 Improvements:"),e.length>1?console.log("\u2022 Successfully found multiple Pareto-optimal solutions"):console.log("\u2022 Found at least one optimal solution"),t!==void 0&&t>0&&console.log(`\u2022 Hypervolume improvement: ${(t*100).toFixed(1)}%`),n!==void 0&&console.log(`\u2022 Best score achieved: ${n.toFixed(3)}`),console.log(`\u2022 Multi-objective approach balances competing goals
303
317
  `),console.log("\u26A0\uFE0F Limitations:"),e.length===1&&console.log("\u2022 Limited diversity in Pareto frontier"),this.stats.totalCalls<100&&console.log("\u2022 Relatively few optimization trials performed"),console.log("\u2022 Results depend on training data quality and size"),console.log(`\u2022 Optimization time scales with problem complexity
304
318
  `),console.log("\u{1F50D} Key Issues:"),e.length<3&&console.log("\u2022 Few distinct trade-off points found"),this.stats.convergenceInfo?.converged===!1&&console.log("\u2022 Optimization may not have fully converged"),console.log("\u2022 Evaluation metrics may need domain-specific tuning"),console.log(`\u2022 Model selection impacts optimization effectiveness
305
- `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 GEPA framework successfully demonstrates multi-objective optimization"),console.log("\u2022 Pareto frontier reveals real trade-offs between objectives"),console.log("\u2022 Users can select solutions based on their specific priorities"),console.log("\u2022 More training data and trials would likely improve results")}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,o=we(`instructionA:string "Parent A instruction",
319
+ `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 GEPA framework successfully demonstrates multi-objective optimization"),console.log("\u2022 Pareto frontier reveals real trade-offs between objectives"),console.log("\u2022 Users can select solutions based on their specific priorities"),console.log("\u2022 More training data and trials would likely improve results")}async mergeInstructions(e,t,n){let r=n?.overrideTeacherAI??this.teacherAI??this.studentAI,o=fe(`instructionA:string "Parent A instruction",
306
320
  instructionB:string "Parent B instruction",
307
321
  recentFeedback?:string[] "Past feedback memory"
308
- -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};var jo=class extends $e{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,p=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),u=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:p.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(R,$)=>{try{s.setAllNodeInstructions?.(R);let C=await s.forward(this.studentAI,$,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:C,example:$})||{}}catch{return{}}},g=async(R,$)=>{let C=[];for(let S of $)C.push(await m(R,S));return ir(C)},f={};for(let R of a)f[R.name]=await this.getBaseInstruction(R.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,p)}],x=R=>{let $=r?.paretoMetricKey,C=r?.paretoScalarize;if(typeof C=="function")return C(R);if($)return Number.isFinite(R[$])?R[$]:0;let S=Object.values(R);return S.length?S.reduce((_,B)=>_+B,0)/S.length:0},A=[],y=async(R,$)=>{let C=[];for(let S of $){let _=await m(R,S);C.push(x(_))}return C};A.push(await y(f,p));let I=je(h.map((R,$)=>({idx:$,scores:R.scores})),this.tieEpsilon).map(R=>R.idx),T=0,b=new Set,w=r?.maxMetricCalls;if(!Number.isFinite(w)||w<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let v=Math.floor(w);for(let R=0;R<this.numTrials&&!(v!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(v)));R++){let $=A[0]?.length??0,C=[];for(let O=0;O<$;O++){let N=Number.NEGATIVE_INFINITY,q=new Set;for(let z=0;z<A.length;z++){let j=A[z][O];j>N+this.tieEpsilon?(N=j,q.clear(),q.add(z)):Math.abs(j-N)<=this.tieEpsilon&&q.add(z)}C.push(q)}let S=A.map(O=>ut(O));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let O=ln(C,S),N=new Set;for(let k of O)for(let M of k)N.add(M);let q=Array.from(N),z=k=>{let M=[],P=k;for(;P!==void 0;)M.push(P),P=h[P]?.parent;return M},j=k=>k.length?k[Math.floor(this.rand()*k.length)]:void 0,X;for(let k=0;k<10&&!X&&!(q.length<2);k++){let M=j(q),P=j(q);if(M===P)continue;P<M&&([M,P]=[P,M]);let J=new Set(z(M)),ie=new Set(z(P));if(J.has(P)||ie.has(M))continue;let Y=[...J].filter(ne=>ie.has(ne));if(Y.length===0)continue;let H=[];for(let ne of Y){let Ee=h[ne].cfg,Ke=h[M].cfg,Se=h[P].cfg,Xe=!1,dt=new Set([...Object.keys(Ee),...Object.keys(Ke),...Object.keys(Se)]);for(let nt of dt){let We=Ee[nt],Ze=Ke[nt],G=Se[nt];if(Ze===We&&G!==Ze||G===We&&Ze!==G){Xe=!0;break}}Xe&&H.push(ne)}if(H.length===0)continue;let W=H.map(ne=>Math.max(1e-9,S[ne])),V=this.rand()*W.reduce((ne,Ee)=>ne+Ee,0),oe=H[H.length-1];for(let ne=0;ne<H.length;ne++){if(V<W[ne]){oe=H[ne];break}V-=W[ne]}let ke=S[oe],Ie=S[M],Te=S[P];if(ke>Math.min(Ie,Te))continue;let Ye=`${M}|${P}|${oe}`;if(this.mergeAttemptKeys.has(Ye))continue;this.mergeAttemptKeys.add(Ye);let He=`${M}|${P}|${oe}`;b.has(He)||(X={i:M,j:P,a:oe})}if(this.lastIterFoundNewProgram=!1,X){let{i:k,j:M,a:P}=X,{cfg:J,descSig:ie}=this.systemAwareMergeWithSig(h,k,M,(G,te)=>S[G]>=S[te]?G:te),Y=`${Math.min(k,M)}|${Math.max(k,M)}|${ie}`;if(this.mergeCompositionKeys.has(Y))continue;this.mergeCompositionKeys.add(Y);let H=A[k],W=A[M],V=Array.from({length:H.length},(G,te)=>te),oe=V.filter(G=>(H[G]??0)>(W[G]??0)),ke=V.filter(G=>(W[G]??0)>(H[G]??0)),Ie=V.filter(G=>!(oe.includes(G)||ke.includes(G))),Te=5,Ye=Math.ceil(Te/3),He=(G,te)=>{if(te<=0||G.length===0)return[];if(G.length<=te)return[...G];let rt=[],ot=new Set;for(;rt.length<te;){let he=Math.floor(this.rand()*G.length);ot.has(he)||(ot.add(he),rt.push(G[he]))}return rt},ne=[];ne.push(...He(oe,Math.min(Ye,oe.length))),ne.push(...He(ke,Math.min(Ye,ke.length)));let Ee=Te-ne.length;ne.push(...He(Ie,Math.max(0,Ee)));let Ke=Te-ne.length;if(Ke>0){let G=V.filter(te=>!ne.includes(te));ne.push(...He(G,Math.min(Ke,G.length)))}let Se=ne.slice(0,Math.min(Te,V.length)),Xe=Se.map(G=>p[G]),nt=(await y(J,Xe)).reduce((G,te)=>G+te,0),We=Se.reduce((G,te)=>G+(H[te]??0),0),Ze=Se.reduce((G,te)=>G+(W[te]??0),0);if(nt>=Math.max(We,Ze)+this.tieEpsilon){let G=await g(J,p);h.push({cfg:J,parent:P,scores:G}),A.push(await y(J,p));let te=I.length,rt=Oe(I.map(he=>h[he].scores))??0;I=je(h.map((he,yr)=>({idx:yr,scores:he.scores})),this.tieEpsilon).map(he=>he.idx);let ot=Oe(I.map(he=>h[he].scores))??0;(I.length>te||ot>rt+1e-6)&&(T=0),this.mergesDue-=1,this.totalMergesTested+=1,b.add(`${Math.min(k,M)}|${Math.max(k,M)}|${P}`)}continue}}let _=cn(C,S,()=>this.rand());this.lastIterFoundNewProgram=!1;let B=this.minibatch?this.nextMinibatchIndices(u.length,R).map(O=>u[O]):u;if(r?.skipPerfectScore??!0){let O=Number(r?.perfectScore??1),N=await y(h[_].cfg,B);if(N.length>0&&N.every(q=>q>=O))continue}let ee=!1,re={...h[_].cfg},Ge="reflective_mutation",ue=R%a.length,me=a[ue],Me,Qe;if(ee&&this.mergesUsed<this.mergeMax){let O=(_+1)%h.length,N=k=>{let M=[],P=k;for(;P!==void 0;)M.push(P),P=h[P]?.parent;return M},q=N(_),z=N(O),j=q.find(k=>z.includes(k)),X=!0;if(j||(X=!1),(z.includes(_)||q.includes(O))&&(X=!1),X){let k=h[j].cfg,M=h[_].cfg,P=h[O].cfg,J=!1,ie=new Set([...Object.keys(k),...Object.keys(M),...Object.keys(P)]);for(let Y of ie){let H=k[Y],W=M[Y],V=P[Y];if(W===H&&V!==W||V===H&&W!==V){J=!0;break}}J||(X=!1)}if(X){let k=Math.min(_,O),M=Math.max(_,O),P=`${k}|${M}|${j}`;if(!b.has(P)){let J=x(h[j].scores),ie=x(h[_].scores),Y=x(h[O].scores);J<=Math.min(ie,Y)&&(re=this.systemAwareMerge(h,_,O,(H,W)=>{let V=x(h[H].scores),oe=x(h[W].scores);return V>=oe?H:W}),Ge="system_merge",this.mergesUsed+=1,b.add(P))}}else{let k=h[_].cfg[me.name],M=r?.gepaAdapter,P;if(M)try{let J=await M.evaluate(B,{...h[_].cfg},!0);Me=Array.isArray(J?.scores)?J.scores.reduce((W,V)=>W+(Number(V)||0),0):void 0;let ie=M.make_reflective_dataset({...h[_].cfg},J,[me.name]),H=(await M.propose_new_texts?.({...h[_].cfg},ie,[me.name]))?.[me.name];typeof H=="string"&&H.length>0&&(P=H)}catch{}if(P||(P=await this.reflectModuleInstruction(me.name,k,s,a,{...h[_].cfg},B,async({prediction:J,example:ie})=>{let Y=await n({prediction:J,example:ie}),H=Object.values(Y||{});return H.length?H.reduce((W,V)=>W+V,0)/H.length:0},r)),re[me.name]=P,M&&Me!==void 0)try{let J=await M.evaluate(B,re,!1);Qe=Array.isArray(J?.scores)?J.scores.reduce((ie,Y)=>ie+(Number(Y)||0),0):void 0}catch{}}}else{let O=h[_].cfg[me.name],N=r?.gepaAdapter,q;if(N)try{let z=await N.evaluate(B,{...h[_].cfg},!0);Me=Array.isArray(z?.scores)?z.scores.reduce((M,P)=>M+(Number(P)||0),0):void 0;let j=N.make_reflective_dataset({...h[_].cfg},z,[me.name]),k=(await N.propose_new_texts?.({...h[_].cfg},j,[me.name]))?.[me.name];typeof k=="string"&&k.length>0&&(q=k)}catch{}if(q||(q=await this.reflectModuleInstruction(me.name,O,s,a,{...h[_].cfg},B,async({prediction:z,example:j})=>{let X=await n({prediction:z,example:j}),k=Object.values(X||{});return k.length?k.reduce((M,P)=>M+P,0)/k.length:0},r)),re[me.name]=q,N&&Me!==void 0)try{let z=await N.evaluate(B,re,!1);Qe=Array.isArray(z?.scores)?z.scores.reduce((j,X)=>j+(Number(X)||0),0):void 0}catch{}}let dr=await y(h[_].cfg,B),mr=await y(re,B),gr=dr.reduce((O,N)=>O+N,0),tt=mr.reduce((O,N)=>O+N,0);if(this.currentRound=R+1,await this.updateOptimizationProgress(this.currentRound,tt,{modules:a.length,mutatedModule:me.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:Ge,paretoSetSize:p.length},tt,{idx:_},{...r??{},maxIterations:this.numTrials}),!(tt>gr+this.tieEpsilon&&(Me===void 0||Qe===void 0||Qe>Me+this.tieEpsilon))){if(++T>=this.earlyStoppingTrials)break;continue}let hr=await g(re,p);h.push({cfg:re,parent:_,scores:hr}),A.push(await y(re,p));let fr=I.length,Ar=Oe(I.map(O=>h[O].scores))??0;I=je(h.map((O,N)=>({idx:N,scores:O.scores})),this.tieEpsilon).map(O=>O.idx);let xr=Oe(I.map(O=>h[O].scores))??0;if(I.length>fr||xr>Ar+1e-6)T=0;else if(T++,T>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let F=je(h.map((R,$)=>({idx:$,scores:R.scores})),this.tieEpsilon),K=F.length>0?Math.max(...F.map(R=>x(R.scores))):0,E=Oe(F.map(R=>R.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(F.length,h.length,"GEPA-Flow",E),{demos:[],stats:this.stats,bestScore:K,paretoFront:F.map(R=>({demos:[],scores:R.scores,configuration:{candidate:R.idx},dominatedSolutions:R.dominated})),paretoFrontSize:F.length,hypervolume:E,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:h.length}}}async getBaseInstruction(e){try{let t=e?.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?ut(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],p=[];for(let x of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:A,example:x});p.push({input:x,prediction:A,score:typeof y=="number"?y:0})}catch{p.push({input:x,prediction:{},score:0})}let u=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=we('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let x of p){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let f="";try{f=(await d.forward(u,{moduleName:e,minibatch:p,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=we('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let A=(await h.forward(u,{moduleName:e,currentInstruction:t,feedbackSummary:f,minibatch:p}))?.newInstruction?.trim();if(A&&A.length>16)return A}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=h=>{let x=[],A=h;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??t,p=e[c].cfg,u=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(p),...Object.keys(u),...Object.keys(d)])).sort();for(let h of f){let x=p[h],A=u[h],y=d[h];if(A===x&&y!==A)m[h]=y,g.push("j");else if(y===x&&A!==y)m[h]=A,g.push("i");else if(A!==y&&A!==x&&y!==x){let I=r(t,n);m[h]=I===t?A:y,g.push(I===t?"i":"j")}else m[h]=A??y??x,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=f=>{let h=[],x=f;for(;x!==void 0;)h.push(x),x=e[x]?.parent;return h},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,p=e[c].cfg,u=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(p),...Object.keys(u),...Object.keys(d)]);for(let f of g){let h=p[f],x=u[f],A=d[f];if(x===h&&A!==x)m[f]=A;else if(A===h&&x!==A)m[f]=x;else if(x!==A&&x!==h&&A!==h){let y=r(t,n);m[f]=y===t?x:A}else m[f]=x??A??h}return m}};var ar=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Ho=class extends $e{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;constructor(e){if(super(e),this.numCandidates=e.numCandidates??5,this.initTemperature=e.initTemperature??.7,this.maxBootstrappedDemos=e.maxBootstrappedDemos??3,this.maxLabeledDemos=e.maxLabeledDemos??4,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??25,this.minibatchFullEvalSteps=e.minibatchFullEvalSteps??10,this.programAwareProposer=e.programAwareProposer??!0,this.dataAwareProposer=e.dataAwareProposer??!0,this.viewDataBatchSize=e.viewDataBatchSize??10,this.tipAwareProposer=e.tipAwareProposer??!0,this.fewshotAwareProposer=e.fewshotAwareProposer??!0,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??.01,this.bayesianOptimization=e.bayesianOptimization??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,e.optimizerEndpoint){let t={endpoint:e.optimizerEndpoint,timeout:e.optimizerTimeout??3e4,retryAttempts:e.optimizerRetries??3,logger:n=>{this.logger?.({name:"Notification",id:"python_client",value:typeof n=="string"?n:JSON.stringify(n)})}};this.pythonClient=new ar(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
322
+ -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await o.forward(r,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};var Zo=class extends Oe{numTrials;minibatch;minibatchSize;earlyStoppingTrials;minImprovementThreshold;sampleCount;crossoverEvery;tieEpsilon;paretoSetSize;mergeMax;mergesUsed=0;mergesDue=0;totalMergesTested=0;lastIterFoundNewProgram=!1;rngState;mergeAttemptKeys=new Set;mergeCompositionKeys=new Set;samplerState={epoch:-1,shuffled:[],freq:new Map};constructor(e){super(e),this.numTrials=e.numTrials??24,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??8,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??0,this.sampleCount=e.sampleCount??1,this.crossoverEvery=Math.max(0,Math.floor(e?.crossoverEvery??Math.max(3,Math.floor(this.numTrials/3)))),this.tieEpsilon=Number.isFinite(e?.tieEpsilon)?Number(e?.tieEpsilon):0;let t=e?.seed,n=Number.isFinite(t)?Math.floor(Number(t)):0;this.rngState=n&&n!==0?n:123456789;let r=e?.paretoSetSize;this.paretoSetSize=r&&r>0?Math.min(1e3,Math.max(5,Math.floor(r))):Math.max(10,Math.min(200,this.minibatchSize*3));let o=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(o??5)),this.mergesUsed=0,this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold,this.mergesUsed=0,this.mergesDue=0,this.totalMergesTested=0,this.lastIterFoundNewProgram=!1,this.mergeAttemptKeys.clear(),this.mergeCompositionKeys.clear(),this.samplerState.epoch=-1,this.samplerState.shuffled=[],this.samplerState.freq.clear()}configureAuto(e){switch(e){case"light":this.numTrials=8,this.minibatch=!0,this.minibatchSize=6;break;case"medium":this.numTrials=16,this.minibatch=!0,this.minibatchSize=10;break;case"heavy":this.numTrials=28,this.minibatch=!0,this.minibatchSize=14;break}}async compile(e,t,n,r){let o=Date.now(),s=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=s.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,p=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),u=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:p.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(w,_)=>{try{s.setAllNodeInstructions?.(w);let R=await s.forward(this.studentAI,_,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:R,example:_})||{}}catch{return{}}},g=async(w,_)=>{let R=[];for(let S of _)R.push(await m(w,S));return cr(R)},f={};for(let w of a)f[w.name]=await this.getBaseInstruction(w.program);let h=[{cfg:{...f},parent:void 0,scores:await g(f,p)}],x=w=>{let _=r?.paretoMetricKey,R=r?.paretoScalarize;if(typeof R=="function")return R(w);if(_)return Number.isFinite(w[_])?w[_]:0;let S=Object.values(w);return S.length?S.reduce((N,G)=>N+G,0)/S.length:0},A=[],y=async(w,_)=>{let R=[];for(let S of _){let N=await m(w,S);R.push(x(N))}return R};A.push(await y(f,p));let I=He(h.map((w,_)=>({idx:_,scores:w.scores})),this.tieEpsilon).map(w=>w.idx),T=0,C=new Set,b=r?.maxMetricCalls;if(!Number.isFinite(b)||b<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let v=Math.floor(b);for(let w=0;w<this.numTrials&&!(v!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(v)));w++){let _=A[0]?.length??0,R=[];for(let k=0;k<_;k++){let D=Number.NEGATIVE_INFINITY,q=new Set;for(let z=0;z<A.length;z++){let j=A[z][k];j>D+this.tieEpsilon?(D=j,q.clear(),q.add(z)):Math.abs(j-D)<=this.tieEpsilon&&q.add(z)}R.push(q)}let S=A.map(k=>mt(k));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let k=pn(R,S),D=new Set;for(let E of k)for(let M of E)D.add(M);let q=Array.from(D),z=E=>{let M=[],F=E;for(;F!==void 0;)M.push(F),F=h[F]?.parent;return M},j=E=>E.length?E[Math.floor(this.rand()*E.length)]:void 0,Z;for(let E=0;E<10&&!Z&&!(q.length<2);E++){let M=j(q),F=j(q);if(M===F)continue;F<M&&([M,F]=[F,M]);let J=new Set(z(M)),ae=new Set(z(F));if(J.has(F)||ae.has(M))continue;let X=[...J].filter(oe=>ae.has(oe));if(X.length===0)continue;let H=[];for(let oe of X){let _e=h[oe].cfg,We=h[M].cfg,ke=h[F].cfg,et=!1,gt=new Set([...Object.keys(_e),...Object.keys(We),...Object.keys(ke)]);for(let ot of gt){let Ve=_e[ot],tt=We[ot],U=ke[ot];if(tt===Ve&&U!==tt||U===Ve&&tt!==U){et=!0;break}}et&&H.push(oe)}if(H.length===0)continue;let W=H.map(oe=>Math.max(1e-9,S[oe])),V=this.rand()*W.reduce((oe,_e)=>oe+_e,0),se=H[H.length-1];for(let oe=0;oe<H.length;oe++){if(V<W[oe]){se=H[oe];break}V-=W[oe]}let Fe=S[se],we=S[M],Se=S[F];if(Fe>Math.min(we,Se))continue;let Ze=`${M}|${F}|${se}`;if(this.mergeAttemptKeys.has(Ze))continue;this.mergeAttemptKeys.add(Ze);let Ke=`${M}|${F}|${se}`;C.has(Ke)||(Z={i:M,j:F,a:se})}if(this.lastIterFoundNewProgram=!1,Z){let{i:E,j:M,a:F}=Z,{cfg:J,descSig:ae}=this.systemAwareMergeWithSig(h,E,M,(U,ne)=>S[U]>=S[ne]?U:ne),X=`${Math.min(E,M)}|${Math.max(E,M)}|${ae}`;if(this.mergeCompositionKeys.has(X))continue;this.mergeCompositionKeys.add(X);let H=A[E],W=A[M],V=Array.from({length:H.length},(U,ne)=>ne),se=V.filter(U=>(H[U]??0)>(W[U]??0)),Fe=V.filter(U=>(W[U]??0)>(H[U]??0)),we=V.filter(U=>!(se.includes(U)||Fe.includes(U))),Se=5,Ze=Math.ceil(Se/3),Ke=(U,ne)=>{if(ne<=0||U.length===0)return[];if(U.length<=ne)return[...U];let st=[],it=new Set;for(;st.length<ne;){let xe=Math.floor(this.rand()*U.length);it.has(xe)||(it.add(xe),st.push(U[xe]))}return st},oe=[];oe.push(...Ke(se,Math.min(Ze,se.length))),oe.push(...Ke(Fe,Math.min(Ze,Fe.length)));let _e=Se-oe.length;oe.push(...Ke(we,Math.max(0,_e)));let We=Se-oe.length;if(We>0){let U=V.filter(ne=>!oe.includes(ne));oe.push(...Ke(U,Math.min(We,U.length)))}let ke=oe.slice(0,Math.min(Se,V.length)),et=ke.map(U=>p[U]),ot=(await y(J,et)).reduce((U,ne)=>U+ne,0),Ve=ke.reduce((U,ne)=>U+(H[ne]??0),0),tt=ke.reduce((U,ne)=>U+(W[ne]??0),0);if(ot>=Math.max(Ve,tt)+this.tieEpsilon){let U=await g(J,p);h.push({cfg:J,parent:F,scores:U}),A.push(await y(J,p));let ne=I.length,st=Ee(I.map(xe=>h[xe].scores))??0;I=He(h.map((xe,Tr)=>({idx:Tr,scores:xe.scores})),this.tieEpsilon).map(xe=>xe.idx);let it=Ee(I.map(xe=>h[xe].scores))??0;(I.length>ne||it>st+1e-6)&&(T=0),this.mergesDue-=1,this.totalMergesTested+=1,C.add(`${Math.min(E,M)}|${Math.max(E,M)}|${F}`)}continue}}let N=un(R,S,()=>this.rand());this.lastIterFoundNewProgram=!1;let G=this.minibatch?this.nextMinibatchIndices(u.length,w).map(k=>u[k]):u;if(r?.skipPerfectScore??!0){let k=Number(r?.perfectScore??1),D=await y(h[N].cfg,G);if(D.length>0&&D.every(q=>q>=k))continue}let Y=!1,te={...h[N].cfg},Ae="reflective_mutation",ce=w%a.length,ge=a[ce],Pe,Xe;if(Y&&this.mergesUsed<this.mergeMax){let k=(N+1)%h.length,D=E=>{let M=[],F=E;for(;F!==void 0;)M.push(F),F=h[F]?.parent;return M},q=D(N),z=D(k),j=q.find(E=>z.includes(E)),Z=!0;if(j||(Z=!1),(z.includes(N)||q.includes(k))&&(Z=!1),Z){let E=h[j].cfg,M=h[N].cfg,F=h[k].cfg,J=!1,ae=new Set([...Object.keys(E),...Object.keys(M),...Object.keys(F)]);for(let X of ae){let H=E[X],W=M[X],V=F[X];if(W===H&&V!==W||V===H&&W!==V){J=!0;break}}J||(Z=!1)}if(Z){let E=Math.min(N,k),M=Math.max(N,k),F=`${E}|${M}|${j}`;if(!C.has(F)){let J=x(h[j].scores),ae=x(h[N].scores),X=x(h[k].scores);J<=Math.min(ae,X)&&(te=this.systemAwareMerge(h,N,k,(H,W)=>{let V=x(h[H].scores),se=x(h[W].scores);return V>=se?H:W}),Ae="system_merge",this.mergesUsed+=1,C.add(F))}}else{let E=h[N].cfg[ge.name],M=r?.gepaAdapter,F;if(M)try{let J=await M.evaluate(G,{...h[N].cfg},!0);Pe=Array.isArray(J?.scores)?J.scores.reduce((W,V)=>W+(Number(V)||0),0):void 0;let ae=M.make_reflective_dataset({...h[N].cfg},J,[ge.name]),H=(await M.propose_new_texts?.({...h[N].cfg},ae,[ge.name]))?.[ge.name];typeof H=="string"&&H.length>0&&(F=H)}catch{}if(F||(F=await this.reflectModuleInstruction(ge.name,E,s,a,{...h[N].cfg},G,async({prediction:J,example:ae})=>{let X=await n({prediction:J,example:ae}),H=Object.values(X||{});return H.length?H.reduce((W,V)=>W+V,0)/H.length:0},r)),te[ge.name]=F,M&&Pe!==void 0)try{let J=await M.evaluate(G,te,!1);Xe=Array.isArray(J?.scores)?J.scores.reduce((ae,X)=>ae+(Number(X)||0),0):void 0}catch{}}}else{let k=h[N].cfg[ge.name],D=r?.gepaAdapter,q;if(D)try{let z=await D.evaluate(G,{...h[N].cfg},!0);Pe=Array.isArray(z?.scores)?z.scores.reduce((M,F)=>M+(Number(F)||0),0):void 0;let j=D.make_reflective_dataset({...h[N].cfg},z,[ge.name]),E=(await D.propose_new_texts?.({...h[N].cfg},j,[ge.name]))?.[ge.name];typeof E=="string"&&E.length>0&&(q=E)}catch{}if(q||(q=await this.reflectModuleInstruction(ge.name,k,s,a,{...h[N].cfg},G,async({prediction:z,example:j})=>{let Z=await n({prediction:z,example:j}),E=Object.values(Z||{});return E.length?E.reduce((M,F)=>M+F,0)/E.length:0},r)),te[ge.name]=q,D&&Pe!==void 0)try{let z=await D.evaluate(G,te,!1);Xe=Array.isArray(z?.scores)?z.scores.reduce((j,Z)=>j+(Number(Z)||0),0):void 0}catch{}}let hr=await y(h[N].cfg,G),fr=await y(te,G),Ar=hr.reduce((k,D)=>k+D,0),rt=fr.reduce((k,D)=>k+D,0);if(this.currentRound=w+1,await this.updateOptimizationProgress(this.currentRound,rt,{modules:a.length,mutatedModule:ge.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:Ae,paretoSetSize:p.length},rt,{idx:N},{...r??{},maxIterations:this.numTrials}),!(rt>Ar+this.tieEpsilon&&(Pe===void 0||Xe===void 0||Xe>Pe+this.tieEpsilon))){if(++T>=this.earlyStoppingTrials)break;continue}let xr=await g(te,p);h.push({cfg:te,parent:N,scores:xr}),A.push(await y(te,p));let yr=I.length,br=Ee(I.map(k=>h[k].scores))??0;I=He(h.map((k,D)=>({idx:D,scores:k.scores})),this.tieEpsilon).map(k=>k.idx);let Ir=Ee(I.map(k=>h[k].scores))??0;if(I.length>yr||Ir>br+1e-6)T=0;else if(T++,T>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let P=He(h.map((w,_)=>({idx:_,scores:w.scores})),this.tieEpsilon),K=P.length>0?Math.max(...P.map(w=>x(w.scores))):0,O=Ee(P.map(w=>w.scores));return this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(P.length,h.length,"GEPA-Flow",O),{demos:[],stats:this.stats,bestScore:K,paretoFront:P.map(w=>({demos:[],scores:w.scores,configuration:{candidate:w.idx},dominatedSolutions:w.dominated})),paretoFrontSize:P.length,hypervolume:O,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:h.length}}}async getBaseInstruction(e){try{let t=e?.getSignature?.();if(t&&typeof t.instruction=="string"&&t.instruction.length>0)return t.instruction}catch{}return"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let o=[];for(let s of n){let a=await this.evaluateOne(e,t,s,r);o.push(a)}return o}async evaluateAvg(e,t,n,r){let o=await this.evaluateOnSet(e,t,n,r);return o.length>0?mt(o):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let o=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let s=await r({prediction:o,example:n});return typeof s=="number"&&!Number.isNaN(s)?((typeof this.targetScore=="number"?s>=this.targetScore:s>=.5)&&(this.stats.successfulDemos+=1),s):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,o,s,a,l){let c=[],p=[];for(let x of s)try{o[e]=t,n.setAllNodeInstructions?.(o);let A=await n.forward(this.studentAI,x,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let y=await a({prediction:A,example:x});p.push({input:x,prediction:A,score:typeof y=="number"?y:0})}catch{p.push({input:x,prediction:{},score:0})}let u=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=fe('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],g=l?.feedbackFn;if(typeof g=="function")for(let x of p){let A=g({prediction:x.prediction,example:x.input});A&&(Array.isArray(A)?m.push(...A):m.push(A))}let f="";try{f=(await d.forward(u,{moduleName:e,minibatch:p,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let h=fe('moduleName:string "Target module", currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction (1-6 sentences) for the module"');try{let A=(await h.forward(u,{moduleName:e,currentInstruction:t,feedbackSummary:f,minibatch:p}))?.newInstruction?.trim();if(A&&A.length>16)return A}catch{}return`${t.trim()} Focus on step-by-step, module-specific reasoning and factual grounding.`.slice(0,2e3)}updateSamplerShuffled(e){let t=Array.from({length:e},(l,c)=>c);for(let l=t.length-1;l>0;l--){let c=Math.floor(this.rand()*(l+1));[t[l],t[c]]=[t[c],t[l]]}for(let l of t)this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1);let n=this.minibatchSize,r=e%n,o=r===0?0:n-r,s=Array.from({length:e},(l,c)=>c).sort((l,c)=>(this.samplerState.freq.get(l)??0)-(this.samplerState.freq.get(c)??0)),a=[...t];for(let l=0;l<o;l++){let c=s[l%s.length];a.push(c),this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,r=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),o=Math.floor(t/r);for(;o>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}systemAwareMergeWithSig(e,t,n,r){let o=h=>{let x=[],A=h;for(;A!==void 0;)x.push(A),A=e[A]?.parent;return x},s=o(t),a=o(n),c=s.find(h=>a.includes(h))??t,p=e[c].cfg,u=e[t].cfg,d=e[n].cfg,m={},g=[],f=Array.from(new Set([...Object.keys(p),...Object.keys(u),...Object.keys(d)])).sort();for(let h of f){let x=p[h],A=u[h],y=d[h];if(A===x&&y!==A)m[h]=y,g.push("j");else if(y===x&&A!==y)m[h]=A,g.push("i");else if(A!==y&&A!==x&&y!==x){let I=r(t,n);m[h]=I===t?A:y,g.push(I===t?"i":"j")}else m[h]=A??y??x,g.push("i")}return{cfg:m,descSig:g.join("|")}}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMerge(e,t,n,r){let o=f=>{let h=[],x=f;for(;x!==void 0;)h.push(x),x=e[x]?.parent;return h},s=o(t),a=o(n),c=s.find(f=>a.includes(f))??t,p=e[c].cfg,u=e[t].cfg,d=e[n].cfg,m={},g=new Set([...Object.keys(p),...Object.keys(u),...Object.keys(d)]);for(let f of g){let h=p[f],x=u[f],A=d[f];if(x===h&&A!==x)m[f]=A;else if(A===h&&x!==A)m[f]=x;else if(x!==A&&x!==h&&A!==h){let y=r(t,n);m[f]=y===t?x:A}else m[f]=x??A??h}return m}};var pr=class{endpoint;timeout;retryAttempts;retryDelay;logger;constructor(e){this.endpoint=e.endpoint.replace(/\/$/,""),this.timeout=e.timeout??3e4,this.retryAttempts=e.retryAttempts??3,this.retryDelay=e.retryDelay??1e3,this.logger=e.logger}async healthCheck(){try{return(await this.fetchWithRetry("/health",{method:"GET"})).ok}catch(e){return this.logger?.({name:"Notification",id:"health_check_failed",value:`Health check failed: ${e}`}),!1}}async createOptimizationJob(e){let t=await this.fetchWithRetry("/optimize",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to create optimization job: ${n}`)}return t.json()}async getJobStatus(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get job status: ${n}`)}return t.json()}async cancelJob(e){let t=await this.fetchWithRetry(`/jobs/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to cancel job: ${n}`)}}async suggestParameters(e){let t=await this.fetchWithRetry(`/studies/${e}/suggest`,{method:"POST",headers:{"Content-Type":"application/json"}});if(!t.ok){let n=await t.text();throw new Error(`Failed to suggest parameters: ${n}`)}return t.json()}async evaluateTrial(e){let t=await this.fetchWithRetry(`/studies/${e.study_name}/evaluate`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Failed to evaluate trial: ${n}`)}}async getStudyResults(e){let t=await this.fetchWithRetry(`/studies/${e}/results`,{method:"GET"});if(!t.ok){let n=await t.text();throw new Error(`Failed to get study results: ${n}`)}return t.json()}async deleteStudy(e){let t=await this.fetchWithRetry(`/studies/${e}`,{method:"DELETE"});if(!t.ok){let n=await t.text();throw new Error(`Failed to delete study: ${n}`)}}async listStudies(){let e=await this.fetchWithRetry("/studies",{method:"GET"});if(!e.ok){let t=await e.text();throw new Error(`Failed to list studies: ${t}`)}return e.json()}async waitForJobCompletion(e,t=2e3,n=3e5){let r=Date.now();for(;Date.now()-r<n;){let o=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(o.status))return o;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${o.status}, waiting...`}),await this.sleep(t)}throw new Error(`Job ${e} did not complete within ${n}ms`)}async fetchWithRetry(e,t){let n=`${this.endpoint}${e}`,r=null;for(let o=0;o<this.retryAttempts;o++)try{let s=new AbortController,a=setTimeout(()=>s.abort(),this.timeout),l=await fetch(n,{...t,signal:s.signal});return clearTimeout(a),l}catch(s){r=s,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${o+1} failed: ${s}`}),o<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,o))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var es=class extends Oe{maxBootstrappedDemos;maxLabeledDemos;numCandidates;initTemperature;numTrials;minibatch;minibatchSize;minibatchFullEvalSteps;programAwareProposer;dataAwareProposer;viewDataBatchSize;tipAwareProposer;fewshotAwareProposer;earlyStoppingTrials;minImprovementThreshold;bayesianOptimization;acquisitionFunction;explorationWeight;optimizeTopP;sampleCount;pythonClient;localScoreHistory=[];localConfigurationHistory=[];customResultPicker;constructor(e){if(super(e),this.numCandidates=e.numCandidates??5,this.initTemperature=e.initTemperature??.7,this.maxBootstrappedDemos=e.maxBootstrappedDemos??3,this.maxLabeledDemos=e.maxLabeledDemos??4,this.numTrials=e.numTrials??30,this.minibatch=e.minibatch??!0,this.minibatchSize=e.minibatchSize??25,this.minibatchFullEvalSteps=e.minibatchFullEvalSteps??10,this.programAwareProposer=e.programAwareProposer??!0,this.dataAwareProposer=e.dataAwareProposer??!0,this.viewDataBatchSize=e.viewDataBatchSize??10,this.tipAwareProposer=e.tipAwareProposer??!0,this.fewshotAwareProposer=e.fewshotAwareProposer??!0,this.earlyStoppingTrials=e.earlyStoppingTrials??5,this.minImprovementThreshold=e.minImprovementThreshold??.01,this.bayesianOptimization=e.bayesianOptimization??!0,this.acquisitionFunction=e.acquisitionFunction??"expected_improvement",this.explorationWeight=e.explorationWeight??.1,this.optimizeTopP=e.optimizeTopP??!1,this.sampleCount=e.sampleCount??1,this.customResultPicker=e.resultPicker,e.optimizerEndpoint){let t={endpoint:e.optimizerEndpoint,timeout:e.optimizerTimeout??3e4,retryAttempts:e.optimizerRetries??3,logger:n=>{this.logger?.({name:"Notification",id:"python_client",value:typeof n=="string"?n:JSON.stringify(n)})}};this.pythonClient=new pr(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let o=e.results.findIndex(s=>!s.isError);return o>=0?o:0}let t=new Map;for(let o of e.results){let s=JSON.stringify(o.sample??{}),a=t.get(s);a?a.count+=1:t.set(s,{count:1,firstIndex:o.index})}let n="",r={count:-1,firstIndex:0};for(let[o,s]of t.entries())s.count>r.count&&(r=s,n=o);return t.get(n)?.firstIndex??0};configureAuto(e){switch(e){case"light":this.numCandidates=3,this.numTrials=10,this.minibatch=!0,this.minibatchSize=20;break;case"medium":this.numCandidates=5,this.numTrials=20,this.minibatch=!0,this.minibatchSize=25;break;case"heavy":this.numCandidates=7,this.numTrials=30,this.minibatch=!0,this.minibatchSize=30;break}}generateTips(){return["Be very specific and detailed in your instructions.","Focus on step-by-step reasoning in your instructions.","Provide clear constraints and guidelines in your instructions.","Keep your instructions concise and to the point.","Emphasize accuracy and precision in your instructions.","Include examples of good outputs in your instructions.","Focus on handling edge cases in your instructions.","Explicitly outline the reasoning process in your instructions."]}async generateProgramSummary(e,t){let r=`
309
323
  Analyze this language model program and provide a concise summary of its purpose and structure.
310
324
 
311
325
  Program Signature: ${e.getSignature()}
@@ -345,12 +359,12 @@ Requirements:
345
359
  5. Keep it concise but comprehensive
346
360
 
347
361
  Generate a single, well-crafted instruction:
348
- Instruction:`;try{let m=(await we('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],p=c[t%c.length]||c[0];return e&&(p=`${p} ${e}`),p}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),s,a;this.programAwareProposer&&(s=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let p=l.length>0?c%l.length:-1,u=p>=0?l[p]:void 0,d=await this.generateInstruction({tip:u,candidateIndex:c,ai:o,programSummary:s,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new an({studentAI:this.studentAI,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.verbose??!1}}).compile(e,n,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(e){let t=[],n=new Set;for(;n.size<this.maxLabeledDemos&&n.size<e.length;){let r=Math.floor(Math.random()*e.length);if(!n.has(r)){n.add(r);let o=e[r];o&&t.push(o)}}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n,r){let o=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),r?.auto&&this.configureAuto(r.auto),!this.pythonClient)throw new Error("AxMiPRO v2 requires the Python optimizer service. Please configure optimizerEndpoint.");if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return await this.compilePython(e,t,n,r)}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,r){if(!this.pythonClient)throw new Error("Python client not initialized");let o=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let s=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={study_name:s,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},l=await this.pythonClient.createOptimizationJob(a);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:l.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,u,d=0,m=0;for(let I=0;I<this.numTrials;I++)try{let T=await this.pythonClient.suggestParameters(s),b=T.params.temperature,w=T.params.bootstrappedDemos,v=this.optimizeTopP?T.params.topP:void 0;if(b===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(T)}`);if(w===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(T)}`);let K=!this.minibatch||this.minibatchFullEvalSteps>0&&I%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let $=Math.min(this.minibatchSize,t.length),C=new Set;for(;C.size<$;)C.add(Math.floor(Math.random()*t.length));return Array.from(C).map(S=>t[S])})(),E=await this.evaluateConfiguration(e,n,{temperature:b,bootstrappedDemos:w,topP:v},K);d++,await this.pythonClient.evaluateTrial({study_name:s,trial_number:T.trial_number,value:E}),E>p+this.minImprovementThreshold?(p=E,u={temperature:b,bootstrappedDemos:w,...v!==void 0?{topP:v}:{},trialNumber:T.trial_number},m=0):m+=1,this.currentRound=I+1;let R={temperature:b,bootstrappedDemos:w,...v!==void 0?{topP:v}:{},trialNumber:T.trial_number};if(this.localScoreHistory.push(E),this.localConfigurationHistory.push(R),await this.updateOptimizationProgress(this.currentRound,E,R,"MiPRO (Python)",{sampler:"TPESampler"},p,u),this.onProgress?.({round:I+1,totalRounds:this.numTrials,currentScore:E,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:d,totalExamples:t.length}),this.earlyStoppingTrials>0&&m>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:p,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let g=p,f={},h=[];try{let I=await this.pythonClient.getStudyResults(s);if(g=I.best_value||p,f=I.best_params||{},f&&Object.keys(f).length>0){let T=f.bootstrappedDemos||0;T>0&&(h=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),h=h.slice(0,T))}}catch{}let x;try{let T=await we('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:g,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:f||{}});x={humanExplanation:T.humanExplanation??"",recommendations:T.recommendations??[],performanceAssessment:T.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,f,r,x);try{await this.pythonClient.deleteStudy(s)}catch{}this.stats.bestScore=g;let A=new Ce(e.getSignature());h.length>0&&A.setDemos(h),f.temperature&&(A._optimizedModelConfig={temperature:f.temperature});let y=new pt({bestScore:g,stats:this.stats,instruction:void 0,demos:h,examples:[],modelConfig:{temperature:f.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-o,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(g,h.length),{bestScore:g,demos:h,stats:this.stats,optimizedGen:A,optimizedProgram:y,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
362
+ Instruction:`;try{let m=(await fe('programSummary?:string "Program context" , datasetSummary?:string "Dataset context" , tip?:string "Generation tip" -> instructionText:string "Well-crafted instruction for the program"').forward(n,{programSummary:r??"",datasetSummary:o??"",tip:e??""})).instructionText;if(m&&m.trim().length>10)return m.trim()}catch{}let c=["Analyze the input systematically and provide a precise, well-reasoned response.","Think through this step-by-step, considering all relevant factors before responding.","Examine the input carefully and generate an accurate, detailed answer.","Process the information methodically and deliver a clear, comprehensive response.","Consider the context thoroughly and provide a thoughtful, accurate answer."],p=c[t%c.length]||c[0];return e&&(p=`${p} ${e}`),p}async proposeInstructionCandidates(e,t,n=[]){let r=[],o=this.getTeacherOrStudentAI(t),s,a;this.programAwareProposer&&(s=await this.generateProgramSummary(e,o)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],o));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let p=l.length>0?c%l.length:-1,u=p>=0?l[p]:void 0,d=await this.generateInstruction({tip:u,candidateIndex:c,ai:o,programSummary:s,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new cn({studentAI:this.studentAI,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.verbose??!1}}).compile(e,n,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(e){let t=[],n=new Set;for(;n.size<this.maxLabeledDemos&&n.size<e.length;){let r=Math.floor(Math.random()*e.length);if(!n.has(r)){n.add(r);let o=e[r];o&&t.push(o)}}return t}applyConfigToProgram(e,t,n,r){e.setInstruction&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples&&e.setExamples(r.slice(0,t.labeledExamples))}async compile(e,t,n,r){let o=Date.now();if(this.validateExamples(t),this.setupRandomSeed(),r?.auto&&this.configureAuto(r.auto),!this.pythonClient)throw new Error("AxMiPRO v2 requires the Python optimizer service. Please configure optimizerEndpoint.");if(!await this.pythonClient.healthCheck())throw new Error("Python optimizer service is not available or unhealthy");return await this.compilePython(e,t,n,r)}applyConfigToAxGen(e,t,n,r){"setInstruction"in e&&typeof e.setInstruction=="function"&&e.setInstruction(t.instruction),t.bootstrappedDemos>0&&e.setDemos(n.slice(0,t.bootstrappedDemos)),t.labeledExamples>0&&e.setExamples(r.slice(0,t.labeledExamples))}getConfiguration(){return{numCandidates:this.numCandidates,initTemperature:this.initTemperature,maxBootstrappedDemos:this.maxBootstrappedDemos,maxLabeledDemos:this.maxLabeledDemos,numTrials:this.numTrials,minibatch:this.minibatch,minibatchSize:this.minibatchSize,minibatchFullEvalSteps:this.minibatchFullEvalSteps,programAwareProposer:this.programAwareProposer,dataAwareProposer:this.dataAwareProposer,tipAwareProposer:this.tipAwareProposer,fewshotAwareProposer:this.fewshotAwareProposer,earlyStoppingTrials:this.earlyStoppingTrials,minImprovementThreshold:this.minImprovementThreshold,bayesianOptimization:this.bayesianOptimization,acquisitionFunction:this.acquisitionFunction,explorationWeight:this.explorationWeight,sampleCount:this.sampleCount}}updateConfiguration(e){e.numCandidates!==void 0&&(this.numCandidates=e.numCandidates),e.initTemperature!==void 0&&(this.initTemperature=e.initTemperature),e.maxBootstrappedDemos!==void 0&&(this.maxBootstrappedDemos=e.maxBootstrappedDemos),e.maxLabeledDemos!==void 0&&(this.maxLabeledDemos=e.maxLabeledDemos),e.numTrials!==void 0&&(this.numTrials=e.numTrials),e.minibatch!==void 0&&(this.minibatch=e.minibatch),e.minibatchSize!==void 0&&(this.minibatchSize=e.minibatchSize),e.earlyStoppingTrials!==void 0&&(this.earlyStoppingTrials=e.earlyStoppingTrials),e.minImprovementThreshold!==void 0&&(this.minImprovementThreshold=e.minImprovementThreshold),e.sampleCount!==void 0&&(this.sampleCount=e.sampleCount)}reset(){super.reset(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return{isValid:t.length===0,issues:t,suggestions:n}}async compilePython(e,t,n,r){if(!this.pythonClient)throw new Error("Python client not initialized");let o=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let s=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,a={study_name:s,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},...this.optimizeTopP?[{name:"topP",type:"float",low:.7,high:1}]:[]],objective:{name:"score",direction:"maximize"},n_trials:this.numTrials,sampler:"TPESampler",pruner:this.minibatch?"MedianPruner":void 0},l=await this.pythonClient.createOptimizationJob(a);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:l.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,u,d=0,m=0;for(let I=0;I<this.numTrials;I++)try{let T=await this.pythonClient.suggestParameters(s),C=T.params.temperature,b=T.params.bootstrappedDemos,v=this.optimizeTopP?T.params.topP:void 0;if(C===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(T)}`);if(b===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(T)}`);let K=!this.minibatch||this.minibatchFullEvalSteps>0&&I%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let _=Math.min(this.minibatchSize,t.length),R=new Set;for(;R.size<_;)R.add(Math.floor(Math.random()*t.length));return Array.from(R).map(S=>t[S])})(),O=await this.evaluateConfiguration(e,n,{temperature:C,bootstrappedDemos:b,topP:v},K);d++,await this.pythonClient.evaluateTrial({study_name:s,trial_number:T.trial_number,value:O}),O>p+this.minImprovementThreshold?(p=O,u={temperature:C,bootstrappedDemos:b,...v!==void 0?{topP:v}:{},trialNumber:T.trial_number},m=0):m+=1,this.currentRound=I+1;let w={temperature:C,bootstrappedDemos:b,...v!==void 0?{topP:v}:{},trialNumber:T.trial_number};if(this.localScoreHistory.push(O),this.localConfigurationHistory.push(w),await this.updateOptimizationProgress(this.currentRound,O,w,"MiPRO (Python)",{sampler:"TPESampler"},p,u),this.onProgress?.({round:I+1,totalRounds:this.numTrials,currentScore:O,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-o,successfulExamples:d,totalExamples:t.length}),this.earlyStoppingTrials>0&&m>=this.earlyStoppingTrials){this.getOptimizerLogger()?.({name:"EarlyStopping",value:{reason:`No improvement \u2265 ${this.minImprovementThreshold} for ${this.earlyStoppingTrials} trials`,finalScore:p,round:this.currentRound}}),this.onEarlyStop?.(`No improvement for ${this.earlyStoppingTrials} trials`,this.stats);break}}catch{}let g=p,f={},h=[];try{let I=await this.pythonClient.getStudyResults(s);if(g=I.best_value||p,f=I.best_params||{},f&&Object.keys(f).length>0){let T=f.bootstrappedDemos||0;T>0&&(h=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),h=h.slice(0,T))}}catch{}let x;try{let T=await fe('optimizerType:string "Optimizer name" , bestScore:number "Final best score" , totalCalls:number "Total eval calls" , successfulDemos:number "Successful evals" , bestConfig:json "Best configuration" -> humanExplanation:string "Readable summary", recommendations:string[] "Next steps", performanceAssessment:string "Performance notes"').forward(this.studentAI,{optimizerType:"MiPRO (Python)",bestScore:g,totalCalls:this.stats.totalCalls,successfulDemos:this.stats.successfulDemos,bestConfig:f||{}});x={humanExplanation:T.humanExplanation??"",recommendations:T.recommendations??[],performanceAssessment:T.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,f,r,x);try{await this.pythonClient.deleteStudy(s)}catch{}this.stats.bestScore=g;let A=new ve(e.getSignature());h.length>0&&A.setDemos(h),f.temperature&&(A._optimizedModelConfig={temperature:f.temperature});let y=new Ye({bestScore:g,stats:this.stats,instruction:void 0,demos:h,examples:[],modelConfig:{temperature:f.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-o,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(g,h.length),{bestScore:g,demos:h,stats:this.stats,optimizedGen:A,optimizedProgram:y,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
349
363
  \u{1F389} MiPRO Optimization Complete!
350
364
  `),console.log("\u2705 Improvements:"),e!==void 0&&e>0&&console.log(`\u2022 Best score achieved: ${e.toFixed(3)}`),t>0&&console.log(`\u2022 Generated ${t} optimized demonstrations`),console.log("\u2022 Systematic prompt and example optimization"),console.log(`\u2022 Automated instruction refinement process
351
365
  `),console.log("\u26A0\uFE0F Limitations:"),this.stats.totalCalls<50&&console.log("\u2022 Relatively few optimization trials performed"),t<5&&console.log("\u2022 Limited number of demonstrations generated"),console.log("\u2022 Results depend on teacher model quality"),console.log(`\u2022 Optimization time increases with example complexity
352
366
  `),console.log("\u{1F50D} Key Issues:"),e!==void 0&&e<.7&&console.log("\u2022 Final performance may still have room for improvement"),this.stats.convergenceInfo?.converged===!1&&console.log("\u2022 Optimization may not have fully converged"),console.log("\u2022 Evaluation metrics may need domain-specific tuning"),console.log(`\u2022 Bootstrap quality depends on initial examples
353
- `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,s=0,a=0,l=r,c=[];if(n.bootstrappedDemos>0)try{c=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{c=[]}for(let p of l)try{c.length>0&&e.setDemos?.(c);let u=await e.forward(this.studentAI,p,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let d=await t({prediction:u,example:p});if(typeof d=="number"&&!Number.isNaN(d)){o+=d,s++;let m=typeof this.targetScore=="number"?this.targetScore:.5;d>=m&&a++}}catch(u){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof u=="string"?u:String(u)})}return this.stats.successfulDemos+=a,s>0?o/s:0}};var pn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let s of o)s[1]&&!n.includes(s[1])&&n.push(s[1]);if(n.length===0)try{let s=this.createDependencyTracker(n);e(s)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let s=r[o];return s&&typeof s=="object"?n.createTrackingProxy(s,t):s},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let s of n)s[1]&&!t.includes(s[1])&&t.push(s[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let s of r)s[1]&&!t.includes(s[1])&&t.push(s[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let s of o)for(let a=1;a<s.length;a++)s[a]&&!t.includes(s[a])&&t.push(s[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function bt(i,e,t){if(!t||t<=0||t>=i.length){let r=i.map((o,s)=>e(o,s));return Promise.all(r)}let n=new Array(i.length);for(let r=0;r<i.length;r+=t){let s=i.slice(r,r+t).map((l,c)=>{let p=r+c;return e(l,p).then(u=>({result:u,originalIndex:p}))}),a=await Promise.all(s);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var un=class{steps=[];parallelGroups=[];analyzer=new pn;initialFields=new Set;addExecutionStep(e,t,n,r,o,s,a){let l=[],c=[],p=r||"map";if(t&&n)p="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(p==="map"&&o)c=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(p==="parallel-map"){if(Array.isArray(o)){let d=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(f=>d.add(f));c=Array.from(d)}else o?c=this.analyzeMapTransformation(o):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(p==="merge"){if(s?.resultKey)c=[s.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(p==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(p==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...d].filter((m,g,f)=>f.indexOf(m)===g)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(p="map",l=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],l=this.getAllProducedFields());for(let d of l)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let u={type:p,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(u)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(s=>{let a=s.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(s=>{let a=s.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(s=>t.add(s));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(s=>!e.has(s.stepIndex));if(o.length>0){let s=o[0];e.add(s.stepIndex),s.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[s]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,s)=>{let a=await bt(n.steps,async p=>await p.stepFunction(o,s),e);if(a.some(p=>p&&typeof p=="object"&&"_parallelResults"in p)){let p=a.find(u=>u&&typeof u=="object"&&"_parallelResults"in u);return p||o}let c=o;for(let p of a)c={...c,...p};return c};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};import{context as Ic,SpanKind as Tc,trace as Rc}from"@opentelemetry/api";var na=i=>{console.log(i)},It=(i,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(i))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},Tt=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,lr=(i=na)=>{let e=new Ae,t=e.gray(`${"\u2501".repeat(80)}
367
+ `),console.log("\u{1F4A1} What This Means:"),console.log("\u2022 MiPRO successfully automated prompt engineering"),console.log("\u2022 Optimized instructions and examples improve model performance"),console.log("\u2022 Framework reduces manual prompt engineering effort"),console.log("\u2022 More training data and iterations would likely improve results")}async evaluateConfiguration(e,t,n,r){let o=0,s=0,a=0,l=r,c=[];if(n.bootstrappedDemos>0)try{c=(await this.bootstrapFewShotExamples(e,t,l)).slice(0,n.bootstrappedDemos)}catch{c=[]}for(let p of l)try{c.length>0&&e.setDemos?.(c);let u=await e.forward(this.studentAI,p,{modelConfig:{temperature:n.temperature,...n.topP!==void 0?{topP:n.topP}:{}},sampleCount:this.sampleCount,resultPicker:this.sampleCount>1?this.customResultPicker??this.defaultResultPicker:void 0});this.stats.totalCalls+=1;let d=await t({prediction:u,example:p});if(typeof d=="number"&&!Number.isNaN(d)){o+=d,s++;let m=typeof this.targetScore=="number"?this.targetScore:.5;d>=m&&a++}}catch(u){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof u=="string"?u:String(u)})}return this.stats.successfulDemos+=a,s>0?o/s:0}};var dn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),o=Array.from(r.matchAll(/state\.(\w+)/g));for(let s of o)s[1]&&!n.includes(s[1])&&n.push(s[1]);if(n.length===0)try{let s=this.createDependencyTracker(n);e(s)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,o){typeof o=="string"&&!t.includes(o)&&t.push(o);let s=r[o];return s&&typeof s=="object"?n.createTrackingProxy(s,t):s},has(r,o){return typeof o=="string"&&!t.includes(o)&&t.push(o),o in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let s of n)s[1]&&!t.includes(s[1])&&t.push(s[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let s of r)s[1]&&!t.includes(s[1])&&t.push(s[1]);let o=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let s of o)for(let a=1;a<s.length;a++)s[a]&&!t.includes(s[a])&&t.push(s[a])}catch(n){console.debug("Static dependency parsing failed:",n)}return t}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}};async function Tt(i,e,t){if(!t||t<=0||t>=i.length){let r=i.map((o,s)=>e(o,s));return Promise.all(r)}let n=new Array(i.length);for(let r=0;r<i.length;r+=t){let s=i.slice(r,r+t).map((l,c)=>{let p=r+c;return e(l,p).then(u=>({result:u,originalIndex:p}))}),a=await Promise.all(s);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var mn=class{steps=[];parallelGroups=[];analyzer=new dn;initialFields=new Set;addExecutionStep(e,t,n,r,o,s,a){let l=[],c=[],p=r||"map";if(t&&n)p="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(p==="map"&&o)c=this.analyzeMapTransformation(o),l=this.getAllProducedFields();else if(p==="parallel-map"){if(Array.isArray(o)){let d=new Set;for(let m of o)this.analyzeMapTransformation(m).forEach(f=>d.add(f));c=Array.from(d)}else o?c=this.analyzeMapTransformation(o):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(p==="merge"){if(s?.resultKey)c=[s.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(p==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(p==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=o?this.analyzer.analyzeMappingDependencies(o,"derive"):[];l=[a.inputFieldName,...d].filter((m,g,f)=>f.indexOf(m)===g)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(p="map",l=this.getAllProducedFields(),c=["_mapResult"]):e.toString().includes("_parallelResults")&&(c=["_parallelResults"],l=this.getAllProducedFields());for(let d of l)this.getAllProducedFields().includes(d)||this.initialFields.add(d);let u={type:p,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(u)}analyzeStepFunctionProduction(e){try{let t=this.analyzeStepFunctionSource(e);if(t.length>0&&!t.includes("_stepResult"))return t}catch(t){console.debug("Step function source analysis failed:",t)}try{let t=this.createMockState(),n=Object.keys(t),o=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(o&&typeof o=="object"&&"then"in o)return this.analyzeStepFunctionSource(e);if(o&&typeof o=="object"&&!Array.isArray(o)){let a=Object.keys(o).filter(l=>!n.includes(l));if(a.length>0)return a}}catch(t){console.debug("Step function dynamic analysis failed:",t)}return this.analyzeStepFunctionSource(e)}analyzeStepFunctionSource(e){try{let t=e.toString(),n=t.match(/\{\s*\.\.\.state\s*,\s*(\w+)\s*:/g);if(n){let o=n.map(s=>{let a=s.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}let r=t.match(/state\.(\w+)\s*=/g);if(r){let o=r.map(s=>{let a=s.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(o.length>0)return o}}catch(t){console.debug("Step function source analysis failed:",t)}return["_stepResult"]}analyzeMapTransformation(e){try{let n=e.toString().split(/\{[\s\S]*?\}/).flatMap(()=>[])}catch{}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue",responseText:"mockResponseText",inputText:"mockInputText"}:e[n]=this.createMockValue(n);return e}createMockValue(e){return e.includes("List")||e.includes("Array")||e.endsWith("s")?["mockItem1","mockItem2"]:e.includes("count")||e.includes("Count")||e.includes("index")||e.includes("Index")?0:e.includes("is")||e.includes("has")||e.includes("can")?!1:"mockValue"}analyzeBranchMergeFields(){let e=this.steps.slice(-5).filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces);return e.length>0?e:this.steps.filter(t=>t.type==="execute"&&t.nodeName).flatMap(t=>t.produces)}setInitialFields(e){this.initialFields=new Set(e),this.rebuildParallelGroups()}rebuildParallelGroups(){this.parallelGroups=[];let e=new Set,t=new Set(this.initialFields),n=0;for(;e.size<this.steps.length;){let r=[];for(let o of this.steps){if(e.has(o.stepIndex))continue;if(o.dependencies.length===0||o.dependencies.every(a=>t.has(a))){if(o.type==="merge"&&r.length>0)continue;if(r.push(o),e.add(o.stepIndex),o.type==="merge")break}}if(r.length>0){for(let o of r)o.produces.forEach(s=>t.add(s));this.parallelGroups.push({level:n,steps:r}),n++}else{let o=this.steps.filter(s=>!e.has(s.stepIndex));if(o.length>0){let s=o[0];e.add(s.stepIndex),s.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[s]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(e){let t=[];for(let n of this.parallelGroups)if(n.steps.length===1){let r=n.steps[0];r&&t.push(r.stepFunction)}else if(n.steps.length>1){let r=async(o,s)=>{let a=await Tt(n.steps,async p=>await p.stepFunction(o,s),e);if(a.some(p=>p&&typeof p=="object"&&"_parallelResults"in p)){let p=a.find(u=>u&&typeof u=="object"&&"_parallelResults"in u);return p||o}let c=o;for(let p of a)c={...c,...p};return c};t.push(r)}return t}getOptimizedExecutionSteps(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),this.createOptimizedExecution()}getExecutionPlan(){return this.parallelGroups.length===0&&this.steps.length>0&&this.rebuildParallelGroups(),{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:this.steps.length===0?1:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}};import{context as Nc,SpanKind as Dc,trace as $c}from"@opentelemetry/api";var ua=i=>{console.log(i)},Ct=(i,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,r]of Object.entries(i))if(typeof r=="string"&&r.length>100)t[n]=`${r.substring(0,100)}...`;else if(Array.isArray(r)&&r.length>3)t[n]=[...r.slice(0,3),`... (${r.length-3} more)`];else if(typeof r=="object"&&r!==null){let o=JSON.stringify(r);o.length>200?t[n]=`${o.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},Rt=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,ur=(i=ua)=>{let e=new be,t=e.gray(`${"\u2501".repeat(80)}
354
368
  `),n=e.gray(`${"\u2500".repeat(40)}
355
369
  `);return r=>{let o="";switch(r.name){case"FlowStart":o=`
356
370
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -362,13 +376,13 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
362
376
  `,o+=t;break;case"StepStart":{let s=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";o=`${e.greenBright(`${s} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=`
363
377
  `,r.dependencies.length>0&&(o+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
364
378
  `),r.produces.length>0&&(o+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
365
- `),o+=`${e.white("State:")} ${e.gray(It(r.state,!0))}
366
- `,o+=n;break}case"StepComplete":{let s=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${s} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${Tt(r.executionTime)}`)}
379
+ `),o+=`${e.white("State:")} ${e.gray(Ct(r.state,!0))}
380
+ `,o+=n;break}case"StepComplete":{let s=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");o=`${e.greenBright(`${s} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(o+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),o+=` ${e.magenta(`in ${Rt(r.executionTime)}`)}
367
381
  `,r.newFields&&r.newFields.length>0&&(o+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
368
382
  `),r.result&&r.nodeName&&(o+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
369
383
  `),o+=n;break}case"ParallelGroupStart":o=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
370
384
  `,o+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
371
- `,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${Tt(r.executionTime)}`)}
385
+ `,o+=n;break;case"ParallelGroupComplete":o=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,o+=` ${e.magenta(`in ${Rt(r.executionTime)}`)}
372
386
  `,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
373
387
  `,o+=n;break;case"BranchEvaluation":o=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
374
388
  `,o+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
@@ -376,16 +390,16 @@ ${t}`,o+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
376
390
  `,r.hasMatchingBranch&&(o+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
377
391
  `),o+=n;break;case"FlowComplete":o=`
378
392
  ${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
379
- ${t}`,o+=`${e.white("Total Time:")} ${e.magenta(Tt(r.totalExecutionTime))}
393
+ ${t}`,o+=`${e.white("Total Time:")} ${e.magenta(Rt(r.totalExecutionTime))}
380
394
  `,o+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
381
395
  `,o+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
382
- `,o+=`${e.white("Final State:")} ${e.gray(It(r.finalState,!0))}
396
+ `,o+=`${e.white("Final State:")} ${e.gray(Ct(r.finalState,!0))}
383
397
  `,o+=t;break;case"FlowError":o=`
384
398
  ${e.redBright("\u274C [ AXFLOW ERROR ]")}
385
399
  ${t}`,r.stepIndex!==void 0&&(o+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(o+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(o+=` ${e.cyan(`Node: ${r.nodeName}`)}`),o+=`
386
400
  `),o+=`${e.white("Error:")} ${e.red(r.error)}
387
- `,r.state&&(o+=`${e.white("State:")} ${e.gray(It(r.state,!0))}
388
- `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},yc=(i=na)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
401
+ `,r.state&&(o+=`${e.white("State:")} ${e.gray(Ct(r.state,!0))}
402
+ `),o+=t;break;default:o=e.gray(JSON.stringify(r,null,2))}i(o)}},Fc=(i=ua)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
389
403
  [ AXFLOW START ]
390
404
  ${e}
391
405
  `,r+=`Input Fields: ${n.inputFields.join(", ")}
@@ -397,16 +411,16 @@ ${e}
397
411
  `;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
398
412
  `,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
399
413
  `),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
400
- `),r+=`State: ${It(n.state,!0)}
414
+ `),r+=`State: ${Ct(n.state,!0)}
401
415
  `,r+=`${t}
402
- `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Tt(n.executionTime)}
416
+ `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Rt(n.executionTime)}
403
417
  `,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
404
418
  `),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
405
419
  `),r+=`${t}
406
420
  `;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
407
421
  `,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
408
422
  `,r+=`${t}
409
- `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Tt(n.executionTime)}
423
+ `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Rt(n.executionTime)}
410
424
  `,r+=`Steps Executed: ${n.stepsCount}
411
425
  `,r+=`${t}
412
426
  `;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
@@ -417,22 +431,22 @@ ${e}
417
431
  `;break;case"FlowComplete":r=`
418
432
  [ AXFLOW COMPLETE ]
419
433
  ${e}
420
- `,r+=`Total Time: ${Tt(n.totalExecutionTime)}
434
+ `,r+=`Total Time: ${Rt(n.totalExecutionTime)}
421
435
  `,r+=`Steps Executed: ${n.stepsExecuted}
422
436
  `,r+=`Output Fields: ${n.outputFields.join(", ")}
423
- `,r+=`Final State: ${It(n.finalState,!0)}
437
+ `,r+=`Final State: ${Ct(n.finalState,!0)}
424
438
  `,r+=`${e}
425
439
  `;break;case"FlowError":r=`
426
440
  [ AXFLOW ERROR ]
427
441
  ${e}
428
442
  `,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
429
443
  `),r+=`Error: ${n.error}
430
- `,n.state&&(r+=`State: ${It(n.state,!0)}
444
+ `,n.state&&(r+=`State: ${Ct(n.state,!0)}
431
445
  `),r+=`${e}
432
- `;break;default:r=JSON.stringify(n,null,2)}i(r)}},bc=lr(),ra=i=>{let e=new Map;return{logger:i,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var dn=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,u;if("forward"in r&&typeof r.forward=="function")u=await r.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:u}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},Ko=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,u;if("forward"in r&&typeof r.forward=="function")u=await r.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:u}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var cr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new un;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),p=this.getStepMetadata(l,a),u=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,h=Object.keys(o).filter(A=>!u.includes(A)),x;if(c==="execute"&&p.nodeName&&h.length>0){let A=`${p.nodeName}Result`;x=o[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,executionTime:g,state:{...o},newFields:h,result:x})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:c,nodeName:p.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:s}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return on().input("userInput",on.string("User input to the flow")).output("flowOutput",on.string("Output from the flow")).build();let t=new Set,n=new Set;for(let p of e.steps)p.produces.forEach(u=>t.add(u)),p.dependencies.forEach(u=>n.add(u));let r=new Set;for(let p of Array.from(n))t.has(p)||r.add(p);let o=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(p=>{p.startsWith("_")||o.add(p)}),s.type==="merge"&&s.produces.includes("_mergedResult"))for(let p of e.steps)p.type==="execute"&&p.produces.length>0&&p.produces.forEach(u=>o.add(u))}else for(let p of Array.from(t)){let u=!1;for(let d of e.steps)if(d.dependencies.includes(p)){u=!0;break}if(!u)if(p.endsWith("Result")){let d=p.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let h of f)o.add(h.name)}else o.add(p)}else o.add(p)}if(r.size===0&&o.size===0){let p=[],u=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let h of f.getInputFields()){let x=this.toCamelCase(`${m}_${h.name}`);p.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let x=this.toCamelCase(`${m}_${h.name}`);u.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let d=new le;return p.length>0?d.setInputFields(p):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),u.length>0?d.setOutputFields(u):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new le,l=[];for(let p of Array.from(r))l.push({name:p,type:{name:"string"},description:`Input field: ${p}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let p of Array.from(o))p.startsWith("_")||c.push({name:p,type:{name:"string"},description:`Output field: ${p}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){i._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),i._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=lr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?ra(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new i(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new lt(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return nn(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=nn(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let r=Date.now();this.timingLogger?.startTiming("flow-execution");let o={};try{this.resetUsage(),this.resetTraces();let s;if(Array.isArray(t)){let g=t.filter(f=>f.role==="user").pop();if(!g)throw new Error("No user message found in values array");s=g.values}else s=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),o={...s},this.flowLogger){let g=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:r,inputFields:Object.keys(s),totalSteps:g.totalSteps,parallelGroups:g.parallelGroups,maxParallelism:g.maxParallelism,autoParallelEnabled:g.autoParallelEnabled})}let a=n?.tracer??this.defaultAIOptions?.tracer,l=n?.traceContext,c,p=l;if(a){let g=this.getExecutionPlan(),f=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";c=a.startSpan(f,{kind:Tc.INTERNAL,attributes:{total_steps:g.totalSteps,parallel_groups:g.parallelGroups,max_parallelism:g.maxParallelism,auto_parallel_enabled:g.autoParallelEnabled}});let h=l??Ic.active();p=Rc.setSpan(h,c)}let u={mainAi:e,mainOptions:(()=>{let g={...this.defaultAIOptions??{},...n};return n?.model&&(g.model=String(n.model)),a&&(g.tracer=a),p&&(g.traceContext=p),Object.keys(g).length>0?g:void 0})()},d=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,m=0;if(d){this.executionPlanner.setInitialFields(Object.keys(s));let g=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),f=await this.executeStepsWithLogging(g,o,u,!0);o=f.finalState,m=f.stepsExecuted}else{let g=await this.executeStepsWithLogging(this.flowDefinition,o,u,!1);o=g.finalState,m=g.stepsExecuted}if(this.flowLogger){let g=this.timingLogger?.endTiming("flow-execution")??Date.now()-r;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:g,finalState:o,outputFields:Object.keys(o),stepsExecuted:m})}return c&&c.end(),o}catch(s){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:s instanceof Error?s.message:String(s),state:o}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),s}}node(e,t){if(typeof t=="string"||t instanceof le){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=we(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await bt(n,async(l,c)=>{let p=l(o);return Promise.resolve(p)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(s,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},p=t(s),u=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,p,{...c,traceLabel:u}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),s=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await bt(e,async(s,a)=>{let l=new dn(this.nodeGenerators);return await s(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...s};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,c=1,p=`_feedback_${t}_iterations`;for(typeof l[p]!="number"&&(l={...l,[p]:1});e(l)&&c<n;){c++,l={...l,[p]:c};for(let u=r;u<o;u++){let d=this.flowDefinition[u];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,c=0;for(;n(l)&&c<r;){c++;for(let p of o)l=await p(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async s=>{let a=s[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;l=await bt(a,async(p,u)=>n(p,u,s),c)}else l=a.map((c,p)=>n(c,p,s));else l=n(a,void 0,s);return{...s,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?le.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)o=o.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)o=o.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)o=o.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)o=o.appendOutputField(s.name,s.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function Wo(i){return cr.create(i)}var Vo=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(s.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),c=s[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),s=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of s){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var Jo=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var Qo=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return s}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((s,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=ge(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let p=c;l(new Error(`RPC Error ${p.error.code}: ${p.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:s}=await o;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function oa(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function sa(i){let t=new TextEncoder().encode(i),n=await es().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Yo(){return oa(await sa(ge()+Math.random().toString(36)))}async function ia(i){return oa(await sa(i))}async function pr(i,e){let t=await fetch(i,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${i}: ${t.statusText}`);return await t.json()}function aa(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function mn(i){return i.endsWith("/")?i.slice(0,-1):i}function Cc(i){if(!i)return null;let e=i.match(/resource_metadata\s*=\s*"([^"]+)"/i)||i.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function la(i,e){let t=Cc(e);if(t){let a=await pr(t),l=mn(new URL(i).toString().split("?")[0]),c=mn(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let p=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:p}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let s;for(let a of o)try{let l=await pr(a.url),c=mn(l.resource??""),p=mn(a.expected);if(!c||c!==p)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${p} but got ${c}`);let u=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:p,issuers:u}}catch(l){s=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(s)}`)}async function ca(i){let e=new URL(i),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let s=await pr(o);if(!s.authorization_endpoint||!s.token_endpoint)throw new Error("AS metadata missing endpoints");let a=s.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return s}catch(s){r=s}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Rt=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await ca(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await la(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),s=e.currentToken??await this.getStoredToken(t,r);if(s?.accessToken&&!this.isExpired(s.expiresAt))return{token:s,issuer:r,asMeta:o,resource:t};if(s?.refreshToken)try{let A=await this.refreshToken(s.refreshToken,t,r,o);return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await Yo(),p=await ia(c),u=await Yo(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${aa({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:u,code_challenge:p,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:f}=await this.oauth.onAuthCode(m),h=f??a,x=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw new Error("Dynamic client registration did not return client_id");return s}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let s=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);let a=await s.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var Xo=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Rt(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let s=JSON.parse(o.data);this.messageHandler&&this.messageHandler(s)}catch(s){console.error("Failed to parse SSE message:",s)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
446
+ `;break;default:r=JSON.stringify(n,null,2)}i(r)}},_c=ur(),da=i=>{let e=new Map;return{logger:i,startTiming:t=>{e.set(t,Date.now())},endTiming:t=>{let n=e.get(t);if(!n)return 0;let r=Date.now()-n;return e.delete(t),r},getCurrentTime:()=>Date.now()}};var gn=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,u;if("forward"in r&&typeof r.forward=="function")u=await r.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:u}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}},ts=class{constructor(e){this.nodeGenerators=e}steps=[];execute(e,t,n){let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(o,s)=>{let a=n?.ai??s.mainAi,l=n?.options??s.mainOptions,c=t(o),p=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,u;if("forward"in r&&typeof r.forward=="function")u=await r.forward(a,c,{...l,traceLabel:p});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:u}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let r of this.steps)n=await r(n,t);return n}};var dr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new mn;program;nodeUsage=new Map;nodeTraces=new Map;flowLogger;timingLogger;defaultAIOptions;toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}async executeStepsWithLogging(e,t,n,r){let o={...t},s=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),p=this.getStepMetadata(l,a),u=Object.keys(o);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,dependencies:p.dependencies,produces:p.produces,state:{...o}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{o=await l(o,n),s++;let g=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,h=Object.keys(o).filter(A=>!u.includes(A)),x;if(c==="execute"&&p.nodeName&&h.length>0){let A=`${p.nodeName}Result`;x=o[A]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:p.nodeName,executionTime:g,state:{...o},newFields:h,result:x})}catch(m){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:m instanceof Error?m.message:String(m),stepIndex:a,stepType:c,nodeName:p.nodeName,state:{...o}}),m}}return{finalState:o,stepsExecuted:s}}getStepType(e,t){let n=e.toString();return n.includes("nodeName")||n.includes("nodeProgram")?"execute":n.includes("_parallelResults")||n.includes("processBatches")?"parallel":n.includes("branchValue")||n.includes("branches.get")||n.includes("mergeFunction")?"merge":n.includes("transform(")||n.includes("...state,")?"map":n.includes("inputValue")&&n.includes("transformFn")?"derive":n.includes("condition(")&&n.includes("iterations")?n.includes("while")?"while":"feedback":n.includes("branchSteps")||n.includes("currentState")?"branch":"other"}getStepMetadata(e,t){let r=this.executionPlanner.getExecutionPlan().steps.find(a=>a.stepIndex===t);if(r)return{nodeName:r.nodeName,dependencies:r.dependencies,produces:r.produces};let o=e.toString();return{nodeName:this.extractNodeNameFromSource(o),dependencies:[],produces:[]}}extractNodeNameFromSource(e){let t=e.match(/nodeName['"]?\s*[=:]\s*['"](\w+)['"]/);if(t)return t[1];let n=e.match(/nodeProgram\.get\(['"](\w+)['"]\)/);if(n)return n[1]}inferSignatureFromFlow(){let e=this.executionPlanner.getExecutionPlan();if(this.nodeGenerators.size===0&&e.steps.length===0)return re().input("userInput",re.string("User input to the flow")).output("flowOutput",re.string("Output from the flow")).build();let t=new Set,n=new Set;for(let p of e.steps)p.produces.forEach(u=>t.add(u)),p.dependencies.forEach(u=>n.add(u));let r=new Set;for(let p of Array.from(n))t.has(p)||r.add(p);let o=new Set,s=e.steps[e.steps.length-1];if(s&&(s.type==="map"||s.type==="merge")){if(s.produces.forEach(p=>{p.startsWith("_")||o.add(p)}),s.type==="merge"&&s.produces.includes("_mergedResult"))for(let p of e.steps)p.type==="execute"&&p.produces.length>0&&p.produces.forEach(u=>o.add(u))}else for(let p of Array.from(t)){let u=!1;for(let d of e.steps)if(d.dependencies.includes(p)){u=!0;break}if(!u)if(p.endsWith("Result")){let d=p.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let f=m.getSignature().getOutputFields();for(let h of f)o.add(h.name)}else o.add(p)}else o.add(p)}if(r.size===0&&o.size===0){let p=[],u=[];for(let[m,g]of Array.from(this.nodeGenerators)){let f=g.getSignature();for(let h of f.getInputFields()){let x=this.toCamelCase(`${m}_${h.name}`);p.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let x=this.toCamelCase(`${m}_${h.name}`);u.push({name:x,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let d=new pe;return p.length>0?d.setInputFields(p):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),u.length>0?d.setOutputFields(u):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new pe,l=[];for(let p of Array.from(r))l.push({name:p,type:{name:"string"},description:`Input field: ${p}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let p of Array.from(o))p.startsWith("_")||c.push({name:p,type:{name:"string"},description:`Output field: ${p}`});return c.length===0&&c.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(c),a}constructor(e){i._ctorWarned||(console.warn("[AxFlow] new AxFlow() is deprecated. Use flow() factory instead."),i._ctorWarned=!0),this.autoParallelConfig={enabled:e?.autoParallel!==!1,batchSize:e?.batchSize||10},e?.logger?this.flowLogger=e.logger:e?.debug===!0?this.flowLogger=ur():this.flowLogger=void 0,this.timingLogger=this.flowLogger?da(this.flowLogger):void 0,(e?.tracer||e?.meter)&&(this.defaultAIOptions={tracer:e.tracer,meter:e.meter})}static create(e){return new i(e)}ensureProgram(){let e=this.inferSignatureFromFlow();if(!this.program){this.program=new pt(e);for(let[t,n]of Array.from(this.nodeGenerators))this.program.register(n);return}this.program.setSignature(e)}setExamples(e,t){this.ensureProgram(),this.program.setExamples(e,t)}setId(e){this.ensureProgram(),this.program.setId(e)}setParentId(e){this.ensureProgram(),this.program.setParentId(e)}getTraces(){let e=[];for(let[t,n]of Array.from(this.nodeTraces))e.push(...n);return e}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return on(e)}resetUsage(){this.nodeUsage.clear();for(let[e,t]of Array.from(this.nodeGenerators))t&&"resetUsage"in t&&t.resetUsage()}resetTraces(){this.nodeTraces.clear()}getUsageReport(){let e={};for(let[t,n]of Array.from(this.nodeUsage))e[t]=on(n);return e}getNodePrograms(){return Array.from(this.nodeGenerators).map(([e,t])=>({name:e,program:t}))}setNodeInstruction(e,t){let n=this.nodeGenerators.get(e);if(!n)return!1;let r=n;if(typeof r.setInstruction=="function")try{return r.setInstruction(t),!0}catch{return!1}return!1}setAllNodeInstructions(e){for(let[t,n]of Object.entries(e))this.setNodeInstruction(t,n)}getTracesReport(){let e={};for(let[t,n]of Array.from(this.nodeTraces))e[t]=n;return e}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let r=Date.now();this.timingLogger?.startTiming("flow-execution");let o={};try{this.resetUsage(),this.resetTraces();let s;if(Array.isArray(t)){let g=t.filter(f=>f.role==="user").pop();if(!g)throw new Error("No user message found in values array");s=g.values}else s=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),o={...s},this.flowLogger){let g=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:r,inputFields:Object.keys(s),totalSteps:g.totalSteps,parallelGroups:g.parallelGroups,maxParallelism:g.maxParallelism,autoParallelEnabled:g.autoParallelEnabled})}let a=n?.tracer??this.defaultAIOptions?.tracer,l=n?.traceContext,c,p=l;if(a){let g=this.getExecutionPlan(),f=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";c=a.startSpan(f,{kind:Dc.INTERNAL,attributes:{total_steps:g.totalSteps,parallel_groups:g.parallelGroups,max_parallelism:g.maxParallelism,auto_parallel_enabled:g.autoParallelEnabled}});let h=l??Nc.active();p=$c.setSpan(h,c)}let u={mainAi:e,mainOptions:(()=>{let g={...this.defaultAIOptions??{},...n};return n?.model&&(g.model=String(n.model)),a&&(g.tracer=a),p&&(g.traceContext=p),Object.keys(g).length>0?g:void 0})()},d=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,m=0;if(d){this.executionPlanner.setInitialFields(Object.keys(s));let g=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),f=await this.executeStepsWithLogging(g,o,u,!0);o=f.finalState,m=f.stepsExecuted}else{let g=await this.executeStepsWithLogging(this.flowDefinition,o,u,!1);o=g.finalState,m=g.stepsExecuted}if(this.flowLogger){let g=this.timingLogger?.endTiming("flow-execution")??Date.now()-r;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:g,finalState:o,outputFields:Object.keys(o),stepsExecuted:m})}return c&&c.end(),o}catch(s){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:s instanceof Error?s.message:String(s),state:o}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),s}}node(e,t){if(typeof t=="string"||t instanceof pe){let n=t;if(!n)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}});let r=fe(n);this.nodeGenerators.set(e,r),this.ensureProgram(),this.program.register(r)}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let n=new t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else if(t&&typeof t=="object"&&"forward"in t){this.nodes.set(e,{inputs:{},outputs:{}});let n=t;this.nodeGenerators.set(e,n),this.ensureProgram(),this.program.register(n)}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this}n(e,t){return this.node(e,t)}map(e,t){if(t?.parallel){let n=Array.isArray(e)?e:[e],r=async o=>(await Tt(n,async(l,c)=>{let p=l(o);return Promise.resolve(p)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),o);if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"parallel-map",n)}else{let n=async r=>{if(Array.isArray(e))throw new Error("Array of transforms requires parallel: true option");let o=e(r);return Promise.resolve(o)};if(this.branchContext?.currentBranchValue!==void 0){let r=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];r.push(n),this.branchContext.branches.set(this.branchContext.currentBranchValue,r)}else this.flowDefinition.push(n),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(n,void 0,void 0,"map",e)}return this.nodeGenerators.size>0&&this.ensureProgram(),this}m(e,t){return this.map(e,t)}returns(e){let t=async n=>{let r=e(n);return Promise.resolve(r)};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}r(e){return this.returns(e)}label(e){if(this.branchContext?.currentBranchValue!==void 0)throw new Error("Cannot create labels inside branch blocks");return this.stepLabels.set(e,this.flowDefinition.length),this}l(e){return this.label(e)}execute(e,t,n){if(!this.nodes.has(e))throw new Error(`Node '${e}' not found. Make sure to define it with .node() first.`);let r=this.nodeGenerators.get(e);if(!r)throw new Error(`Node program for '${e}' not found.`);let o=async(s,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},p=t(s),u=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,p,{...c,traceLabel:u}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let g=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...g,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let g=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...g,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,e,t);return this.ensureProgram(),this}applyOptimization(e){this.program&&"applyOptimization"in this.program&&this.program.applyOptimization(e);for(let[t,n]of Array.from(this.nodeGenerators))n&&"applyOptimization"in n&&typeof n.applyOptimization=="function"&&n.applyOptimization(e)}e(e,t,n){return this.execute(e,t,n)}branch(e){if(this.branchContext)throw new Error("Nested branches are not supported");return this.branchContext={predicate:t=>e(t),branches:new Map,currentBranchValue:void 0},this}b(e){return this.branch(e)}when(e){if(!this.branchContext)throw new Error("when() called without matching branch()");return this.branchContext.currentBranchValue=e,this.branchContext.branches.set(e,[]),this}w(e){return this.when(e)}merge(){if(!this.branchContext)throw new Error("merge() called without matching branch()");let e=this.branchContext;this.branchContext=null;let t=async(n,r)=>{let o=e.predicate(n),s=e.branches.get(o);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:o,hasMatchingBranch:!!s,branchStepsCount:s?.length??0}),!s)return n;let a=n;for(let l of s)a=await l(a,r);return a};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"merge"),this.ensureProgram(),this}mg(){return this.merge()}parallel(e){let t=async(n,r)=>{let o=await Tt(e,async(s,a)=>{let l=new gn(this.nodeGenerators);return await s(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:o}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"parallel",void 0,void 0),this.ensureProgram(),{merge:(n,r)=>{let o=s=>{let a=s._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...s};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:r}),this.ensureProgram(),this}}}p(e){return this.parallel(e)}feedback(e,t,n=10){if(!this.stepLabels.has(t))throw new Error(`Label '${t}' not found. Make sure to define it with .label() before the feedback point.`);let r=this.stepLabels.get(t),o=this.flowDefinition.length;return this.flowDefinition.push(async(s,a)=>{let l=s,c=1,p=`_feedback_${t}_iterations`;for(typeof l[p]!="number"&&(l={...l,[p]:1});e(l)&&c<n;){c++,l={...l,[p]:c};for(let u=r;u<o;u++){let d=this.flowDefinition[u];d&&(l=await d(l,a))}}return l}),this.nodeGenerators.size>0&&this.ensureProgram(),this}fb(e,t,n=10){return this.feedback(e,t,n)}while(e,t=100){let n=this.flowDefinition.length;this.loopStack.push(n);let r=Object.assign(o=>o,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(r),this.nodeGenerators.size>0&&this.ensureProgram(),this}wh(e,t=100){return this.while(e,t)}endWhile(){if(this.loopStack.length===0)throw new Error("endWhile() called without matching while()");let e=this.loopStack.pop(),t=this.flowDefinition[e];if(!t||!("_isLoopStart"in t))throw new Error("Loop start step not found or invalid");let n=t._condition,r=t._maxIterations,o=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(s,a)=>{let l=s,c=0;for(;n(l)&&c<r;){c++;for(let p of o)l=await p(l,a)}if(c>=r&&n(l))throw new Error(`While loop exceeded maximum iterations (${r}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}derive(e,t,n,r){let o=async s=>{let a=s[t];if(a===void 0)throw new Error(`Input field '${t}' not found in state`);let l;if(Array.isArray(a))if(this.autoParallelConfig.enabled){let c=r?.batchSize||this.autoParallelConfig.batchSize;l=await Tt(a,async(p,u)=>n(p,u,s),c)}else l=a.map((c,p)=>n(c,p,s));else l=n(a,void 0,s);return{...s,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(o),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}else this.flowDefinition.push(o),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(o,void 0,void 0,"derive",n,void 0,{inputFieldName:t,outputFieldName:e,batchSize:r?.batchSize});return this.ensureProgram(),this}getExecutionPlan(){let e=this.executionPlanner.getExecutionPlan();return{totalSteps:e.totalSteps,parallelGroups:e.parallelGroups,maxParallelism:e.maxParallelism,autoParallelEnabled:this.autoParallelConfig.enabled,steps:e.steps,groups:e.groups}}getSignature(){return this.ensureProgram(),this.program.getSignature()}nodeExtended(e,t,n){let o=typeof t=="string"?pe.create(t):t;if(n.prependInputs)for(let s of n.prependInputs)o=o.prependInputField(s.name,s.type);if(n.appendInputs)for(let s of n.appendInputs)o=o.appendInputField(s.name,s.type);if(n.prependOutputs)for(let s of n.prependOutputs)o=o.prependOutputField(s.name,s.type);if(n.appendOutputs)for(let s of n.appendOutputs)o=o.appendOutputField(s.name,s.type);return this.node(e,o)}nx(e,t,n){return this.nodeExtended(e,t,n)}mapOutput(e){let t=async n=>{let r=e(n);return{...n,...r}};if(this.branchContext?.currentBranchValue!==void 0){let n=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];n.push(t),this.branchContext.branches.set(this.branchContext.currentBranchValue,n)}else this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"map",e);return this.nodeGenerators.size>0&&this.ensureProgram(),this}mo(e){return this.mapOutput(e)}};function ns(i){return dr.create(i)}var rs=class{apiUrl;containerId=null;constructor(e="http://localhost:2375"){this.apiUrl=e}async pullImage(e){let t=await this.fetchDockerAPI(`/images/create?fromImage=${encodeURIComponent(e)}`,{method:"POST"});if(!t.ok)throw new Error(`Failed to pull image: ${t.statusText}`);await t.text()}async createContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let o=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let s={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:o},Labels:{}};r&&(s.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!a.ok)throw new Error(`Failed to create container: ${a.statusText}`);let l=await a.json();return this.containerId=l.Id,l}async findOrCreateContainer({imageName:e,volumes:t=[],doNotPullImage:n,tag:r}){let s=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(s&&s.length>0){let l=Math.floor(Math.random()*s.length),c=s[l];if(c)return await this.connectToContainer(c.Id),{Id:c.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:r})).Id,isNew:!0}}async startContainer(){if(!this.containerId)throw new Error("No container created or connected");let e=await this.fetchDockerAPI(`/containers/${this.containerId}/start`,{method:"POST"});if(!e.ok)throw new Error(`Failed to start container: ${e.statusText}`)}async connectToContainer(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to connect to container: ${t.statusText}`);this.containerId=e}async stopContainers({tag:e,remove:t,timeout:n=10}){let r=[],o=await this.listContainers(!0),s=e?o.filter(a=>a.Labels["com.example.tag"]===e):o;for(let a of s){if(a.State.Status==="running"){let l=await this.fetchDockerAPI(`/containers/${a.Id}/stop?t=${n}`,{method:"POST"});if(!l.ok){console.warn(`Failed to stop container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"stopped"})}if(t){let l=await this.fetchDockerAPI(`/containers/${a.Id}`,{method:"DELETE"});if(!l.ok){console.warn(`Failed to remove container ${a.Id}: ${l.statusText}`);continue}r.push({Id:a.Id,Action:"removed"})}}return r}async listContainers(e=!1){return(await this.fetchDockerAPI(`/containers/json?all=${e}`,{method:"GET"})).json()}async getContainerLogs(){if(!this.containerId)throw new Error("No container created or connected");return(await this.fetchDockerAPI(`/containers/${this.containerId}/logs?stdout=true&stderr=true`,{method:"GET"})).text()}async executeCommand(e){if(!this.containerId)throw new Error("No container created or connected");(await this.getContainerInfo(this.containerId)).State.Status!=="running"&&(await this.startContainer(),await this.waitForContainerToBeRunning(this.containerId));let n=await this.fetchDockerAPI(`/containers/${this.containerId}/exec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Cmd:["sh","-c",e],AttachStdout:!0,AttachStderr:!0})});if(!n.ok)throw new Error(`Failed to create exec instance: ${n.statusText}`);let r=await n.json(),o=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!o.ok)throw new Error(`Failed to start exec instance: ${o.statusText}`);return await o.text()}async getContainerInfo(e){let t=await this.fetchDockerAPI(`/containers/${e}/json`);if(!t.ok)throw new Error(`Failed to get container info: ${t.statusText}`);return t.json()}async waitForContainerToBeRunning(e,t=3e4){let n=Date.now();for(;Date.now()-n<t;){if((await this.getContainerInfo(e)).State.Status==="running")return;await new Promise(o=>setTimeout(o,1e3))}throw new Error("Timeout waiting for container to start")}async fetchDockerAPI(e,t){let n=new URL(e,this.apiUrl).toString();return await fetch(n,t)}toFunction(){return{name:"commandExecution",description:"Use this function to execute shell commands, scripts, and programs. This function enables interaction with the file system, running system utilities, and performing tasks that require a shell interface.",parameters:{type:"object",properties:{command:{type:"string",description:'Shell command to execute. eg. `ls -l` or `echo "Hello, World!"`.'}},required:["command"]},func:async({command:e})=>await this.executeCommand(e)}}};var os=class{aiService;info;func;constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let r=(await this.aiService.embed({texts:[e]},{sessionId:t?.sessionId,abortSignal:t?.abortSignal})).embeddings.at(0);if(!r)throw new Error("Failed to embed text");return this.func.length===2?this.func(r,t):this.func(r)}toFunction(){return{name:this.info.name,description:this.info.description,parameters:{type:"object",properties:{text:{type:"string",description:this.info.argumentDescription}},required:["text"]},func:({text:e},t)=>this.embedAdapter(e,t)}}};var ss=class{constructor(e,t={}){this.transport=e;this.options=t;this.logger=t.logger??(n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})}functions=[];activeRequests=new Map;capabilities={};logger;async init(){"connect"in this.transport&&await this.transport.connect?.();let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(o=>o.name===t.name),r=t.inputSchema.properties?{properties:t.inputSchema.properties,required:t.inputSchema.required??[],type:t.inputSchema.type}:void 0;return{name:n?.updates.name??t.name,description:n?.updates.description??t.description,parameters:r,func:async o=>{let{result:s}=await this.sendRequest("tools/call",{name:t.name,arguments:o});return s}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((s,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:o}=r;if(typeof o!="object"||o===null||Object.keys(o).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(o)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=he(),r={jsonrpc:"2.0",id:n,method:e,params:t},o=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(r).then(c=>{if(this.activeRequests.delete(n),c!==null&&typeof c=="object"&&"error"in c){let p=c;l(new Error(`RPC Error ${p.error.code}: ${p.error.message}`))}else c!==null&&typeof c=="object"&&"result"in c?a({result:c.result}):l(new Error("Invalid response no result or error"))}).catch(c=>{this.activeRequests.delete(n),l(c)})}),{result:s}=await o;return{id:n,result:s}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let o={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(o)}await this.transport.sendNotification(n)}};function ma(i){if(typeof Buffer<"u")return Buffer.from(i).toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"");let e="";for(let n=0;n<i.length;n++)e+=String.fromCharCode(i[n]);return(typeof btoa=="function"?btoa(e):"").replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ga(i){let t=new TextEncoder().encode(i),n=await cs().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function is(){return ma(await ga(he()+Math.random().toString(36)))}async function ha(i){return ma(await ga(i))}async function mr(i,e){let t=await fetch(i,{headers:e});if(!t.ok)throw new Error(`HTTP ${t.status} fetching ${i}: ${t.statusText}`);return await t.json()}function fa(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function hn(i){return i.endsWith("/")?i.slice(0,-1):i}function Gc(i){if(!i)return null;let e=i.match(/resource_metadata\s*=\s*"([^"]+)"/i)||i.match(/resource_metadata\s*=\s*([^,\s]+)/i);return e?e[1]:null}async function Aa(i,e){let t=Gc(e);if(t){let a=await mr(t),l=hn(new URL(i).toString().split("?")[0]),c=hn(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let p=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:p}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),o=[];r&&r!=="/"&&o.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),o.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let s;for(let a of o)try{let l=await mr(a.url),c=hn(l.resource??""),p=hn(a.expected);if(!c||c!==p)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${p} but got ${c}`);let u=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:p,issuers:u}}catch(l){s=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(s)}`)}async function xa(i){let e=new URL(i),t=e.pathname.replace(/^\/+/,""),n=[];t?(n.push(`${e.origin}/.well-known/oauth-authorization-server/${t}`),n.push(`${e.origin}/.well-known/openid-configuration/${t}`),n.push(`${e.origin}/${t.replace(/\/+$/,"")}/.well-known/openid-configuration`)):(n.push(`${e.origin}/.well-known/oauth-authorization-server`),n.push(`${e.origin}/.well-known/openid-configuration`));let r;for(let o of n)try{let s=await mr(o);if(!s.authorization_endpoint||!s.token_endpoint)throw new Error("AS metadata missing endpoints");let a=s.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return s}catch(s){r=s}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var wt=class{constructor(e){this.oauth=e}tokenCache=new Map;asMetaCache=new Map;key(e,t){return`${e}::${t}`}async getStoredToken(e,t){let n=this.key(e,t);if(this.tokenCache.has(n))return this.tokenCache.get(n);let r=await this.oauth?.tokenStore?.getToken?.(n);return r&&this.tokenCache.set(n,r),r??null}async setStoredToken(e,t,n){let r=this.key(e,t);this.tokenCache.set(r,n),await this.oauth?.tokenStore?.setToken?.(r,n)}async clearStoredToken(e,t){let n=this.key(e,t);this.tokenCache.delete(n),await this.oauth?.tokenStore?.clearToken?.(n)}isExpired(e){return e?Date.now()>e-6e4:!1}async getASMeta(e){if(this.asMetaCache.has(e))return this.asMetaCache.get(e);let t=await xa(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await Aa(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],o=await this.getASMeta(r),s=e.currentToken??await this.getStoredToken(t,r);if(s?.accessToken&&!this.isExpired(s.expiresAt))return{token:s,issuer:r,asMeta:o,resource:t};if(s?.refreshToken)try{let A=await this.refreshToken(s.refreshToken,t,r,o);return await this.setStoredToken(t,r,A),{token:A,issuer:r,asMeta:o,resource:t}}catch{await this.clearStoredToken(t,r)}let a=this.oauth.redirectUri??"http://localhost:8787/callback",l=this.oauth.clientId?{client_id:this.oauth.clientId,client_secret:this.oauth.clientSecret}:await this.dynamicClientRegistration(o,a),c=await is(),p=await ha(c),u=await is(),d=this.oauth.scopes?.join(" "),m=`${o.authorization_endpoint}?${fa({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:u,code_challenge:p,code_challenge_method:"S256",resource:t})}`;if(!this.oauth.onAuthCode)throw new Error(`Authorization required. Provide oauth.onAuthCode to complete the flow. Navigate to: ${m}`);let{code:g,redirectUri:f}=await this.oauth.onAuthCode(m),h=f??a,x=await this.exchangeCodeForToken({asMeta:o,code:g,codeVerifier:c,client:l,redirectUri:h,resource:t});return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:o,resource:t}}async dynamicClientRegistration(e,t){if(!e.registration_endpoint)throw new Error("Authorization server does not support dynamic client registration and no clientId was provided.");let r={application_type:t.startsWith("http://localhost")?"native":"web",client_name:"Ax MCP Client",redirect_uris:[t],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"},o=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!o.ok)throw new Error(`Dynamic client registration failed: ${o.status} ${o.statusText}`);let s=await o.json();if(!s.client_id)throw new Error("Dynamic client registration did not return client_id");return s}async exchangeCodeForToken(e){let t=new URLSearchParams;t.set("grant_type","authorization_code"),t.set("code",e.code),t.set("redirect_uri",e.redirectUri),t.set("client_id",e.client.client_id),t.set("code_verifier",e.codeVerifier),t.set("resource",e.resource),e.client.client_secret&&t.set("client_secret",e.client.client_secret);let n=await fetch(e.asMeta.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status} ${n.statusText}`);let r=await n.json();if(!r.access_token)throw new Error("No access_token in token response");let o=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:o}}async refreshToken(e,t,n,r){let o=new URLSearchParams;o.set("grant_type","refresh_token"),o.set("refresh_token",e),o.set("resource",t),this.oauth?.clientId&&o.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&o.set("client_secret",this.oauth.clientSecret);let s=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString()});if(!s.ok)throw new Error(`Token refresh failed: ${s.status} ${s.statusText}`);let a=await s.json();if(!a.access_token)throw new Error("No access_token in refresh response");let l=a.expires_in?Date.now()+a.expires_in*1e3:void 0;return{accessToken:a.access_token,refreshToken:a.refresh_token??e,expiresAt:l}}};var as=class{mcpEndpoint;sessionId;eventSource;pendingRequests=new Map;messageHandler;customHeaders;oauthHelper;currentToken;currentIssuer;constructor(e,t){this.mcpEndpoint=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new wt(t?.oauth)}setHeaders(e){this.customHeaders={...e}}setAuthorization(e){this.customHeaders.Authorization=e}getHeaders(){return{...this.customHeaders}}buildHeaders(e){let t={...this.customHeaders,...e};return this.sessionId&&(t["Mcp-Session-Id"]=this.sessionId),t}setMessageHandler(e){this.messageHandler=e}async connect(){return Promise.resolve()}async openListeningStream(){return new Promise((e,t)=>{let n=this.buildHeaders({Accept:"text/event-stream"}),r=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(r.toString()),this.eventSource.onopen=()=>e(),this.eventSource.onmessage=o=>{try{let s=JSON.parse(o.data);this.messageHandler&&this.messageHandler(s)}catch(s){console.error("Failed to parse SSE message:",s)}},this.eventSource.onerror=()=>t(new Error("Failed to establish SSE connection"))})}async openListeningStreamWithFetch(e){let t=await fetch(this.mcpEndpoint,{method:"GET",headers:e});if(t.status===401){let a=t.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,this.openListeningStreamWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!t.ok)throw new Error(`Failed to open SSE stream: ${t.status} ${t.statusText}`);if(!t.body)throw new Error("No response body available for SSE stream");let n=t.body.getReader(),r=new TextDecoder,o="",s=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}o+=r.decode(l,{stream:!0});let c=o.split(`
433
447
  `);o=c.pop()||"";for(let p of c)if(p.startsWith("data: ")){let u=p.slice(6);if(u==="[DONE]")return;try{let d=JSON.parse(u);this.messageHandler&&this.messageHandler(d)}catch(d){console.error("Failed to parse SSE data:",d)}}await s()}catch(a){throw n.releaseLock(),a}};await s()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let a=r.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);let o=r.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let s=r.headers.get("Content-Type");if(s?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(s?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${s}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let o=e.body?.getReader();if(!o){r(new Error("No response body reader available"));return}let s=new TextDecoder,a="",l=async()=>{try{let{done:c,value:p}=await o.read();if(c){o.releaseLock();return}a+=s.decode(p,{stream:!0});let u=a.split(`
434
- `);a=u.pop()||"";for(let d of u)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(c){o.releaseLock(),r(c)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var Zo=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new Rt(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:s,value:a}=await t.read();if(s)break;r+=n.decode(a,{stream:!0});let l=r.split(`
435
- `);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))o=c.slice(7).trim();else if(c.startsWith("data: ")){let p=c.slice(6);if(o==="endpoint"){let u=p.trim(),d;try{let m=JSON.parse(u);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=u}if(!d)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(d)||(d=new URL(this.sseUrl).origin+(d.startsWith("/")?d:`/${d}`)),this.endpoint=d,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let u=p.trim();try{let d=JSON.parse(u);if(d&&typeof d=="object"&&"id"in d){let m=d.id,g=this.pendingRequests.get(m);g?(g.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else c.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function wc(i,e,t,n,r){let o={...i};if(o.parameters){let s=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(c=>s.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){o.parameters=vc(o.parameters,l);let c=o.func;o.func=async(p,u)=>{let d={};if(Array.isArray(e)){let g=e.filter(f=>f.role==="user").pop();g&&(d=da(g.values,l))}else d=da(e,l);let m={...p,...d};return await c(m,u)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=ma(o.parameters,n)),o}var pa=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),ua=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),ur=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:s,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:p,debug:u}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=p??[],this.debug=u,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw pa;if(r&&r.length<100)throw ua;this.program=new Ce(o,{...l,description:r??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:Sc(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=ma(this.func.parameters,d))}static create(e,t){let n=le.create(e),{ai:r,name:o,description:s,definition:a,agents:l,functions:c,...p}=t;return new i({ai:r,name:o,description:s,definition:a,signature:n,agents:l,functions:c},p)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...s}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...r,model:o}),p=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=p.find(g=>g.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
436
- `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(u=>u.name),l=this.getDebug(r,n),c=this.agents?.map(u=>{let d=u.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return wc(u.getFunction(),t,a,o,m)}),p=[...n?.functions??this.functions??[],...c??[]];return{ai:r,functions:p,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return await this.program.forward(r,t,a)}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return yield*this.program.streamingForward(r,t,a)}setDescription(e){if(!e||e.length<20)throw pa;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw ua;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function Sc(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function ma(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(s=>s.key),description:`The AI model to use for this function call. Available options: ${e.map(s=>`\`${s.key}\` ${s.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function vc(i,e){let t=structuredClone(i);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function da(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Oc(i,e){let t=typeof i=="string"?le.create(i):i,{ai:n,name:r,description:o,definition:s,agents:a,functions:l,...c}=e;return new ur({ai:n,name:r,description:o,definition:s,signature:t,agents:a,functions:l},c)}var Mc=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return Wo({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,c=await i(l);return{...a,retrievalResult:{retrievedDocument:c,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],c=l.length>0?await Promise.all(l.filter(Boolean).map(p=>i(p))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let l=[...a.allEvidence||[],...a.retrievalResults||[]].filter(Boolean);return{collectedEvidence:l.length>0?l:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...a.allEvidence,...a.retrievalResults],evidenceSources:[...a.evidenceSources,`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:a.accumulatedContext||a.synthesizedEvidence||a.allEvidence.join(`
437
- `),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],c=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,p=await i(c);return{...a,healingResult:{healingDocument:p}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};export{Ln as AxAI,Ot as AxAIAnthropic,In as AxAIAnthropicModel,kr as AxAIAnthropicVertexModel,Ft as AxAIAzureOpenAI,_t as AxAICohere,Sn as AxAICohereEmbedModel,wn as AxAICohereModel,Nt as AxAIDeepSeek,vn as AxAIDeepSeekModel,Dt as AxAIGoogleGemini,zr as AxAIGoogleGeminiEmbedModel,Qs as AxAIGoogleGeminiEmbedTypes,On as AxAIGoogleGeminiModel,jr as AxAIGoogleGeminiSafetyCategory,Hr as AxAIGoogleGeminiSafetyThreshold,Vt as AxAIGrok,ii as AxAIGrokEmbedModels,$n as AxAIGrokModel,Lt as AxAIGroq,Mn as AxAIGroqModel,Gt as AxAIHuggingFace,Yr as AxAIHuggingFaceModel,Ut as AxAIMistral,ei as AxAIMistralEmbedModels,kn as AxAIMistralModel,Bt as AxAIOllama,Pt as AxAIOpenAI,ce as AxAIOpenAIBase,Mt as AxAIOpenAIEmbedModel,Cn as AxAIOpenAIModel,zt as AxAIOpenAIResponses,Pn as AxAIOpenAIResponsesBase,qt as AxAIOpenAIResponsesImpl,kt as AxAIOpenAIResponsesModel,jt as AxAIOpenRouter,ae as AxAIRefusalError,Ht as AxAIReka,_n as AxAIRekaModel,wt as AxAIServiceAbortedError,st as AxAIServiceAuthenticationError,Re as AxAIServiceError,Ve as AxAIServiceNetworkError,et as AxAIServiceResponseError,mt as AxAIServiceStatusError,Ue as AxAIServiceStreamTerminatedError,gt as AxAIServiceTimeoutError,Kt as AxAITogether,Wt as AxAIWebLLM,Dn as AxAIWebLLMModel,ur as AxAgent,Lo as AxApacheTika,Je as AxAssertionError,$r as AxBalancer,pe as AxBaseAI,$e as AxBaseOptimizer,an as AxBootstrapFewShot,Be as AxContentProcessingError,fo as AxDB,Ne as AxDBBase,Jt as AxDBCloudflare,xo as AxDBManager,it as AxDBMemory,Qt as AxDBPinecone,Yt as AxDBWeaviate,sr as AxDefaultCostTracker,$o as AxDefaultResultReranker,Vo as AxDockerSession,Jo as AxEmbeddingAdapter,Zl as AxEvalUtil,cr as AxFlow,pn as AxFlowDependencyAnalyzer,un as AxFlowExecutionPlanner,dn as AxFlowSubContextImpl,Ko as AxFlowTypedSubContextImpl,xe as AxFluentFieldType,jn as AxFunctionError,Hn as AxFunctionProcessor,zo as AxGEPA,jo as AxGEPAFlow,Ce as AxGen,tr as AxGenerateError,qo as AxHFDataLoader,rn as AxInstanceRegistry,cs as AxLLMRequestTypeValues,Qo as AxMCPClient,Zo as AxMCPHTTPSSETransport,Xo as AxMCPStreambleHTTPTransport,Fe as AxMediaNotSupportedError,Zt as AxMemory,Ho as AxMiPRO,to as AxMockAIService,no as AxMultiServiceRouter,pt as AxOptimizedProgramImpl,lt as AxProgram,yt as AxPromptTemplate,ao as AxProviderRouter,$t as AxRateLimiterTokenUsage,le as AxSignature,Yn as AxSignatureBuilder,Uo as AxSimpleClassifier,Go as AxSimpleClassifierClass,ps as AxSpanKindValues,xt as AxStopFunctionCallException,Do as AxStringUtil,Bo as AxTestPrompt,Oc as agent,sl as ai,we as ax,zs as axAIAnthropicDefaultConfig,va as axAIAnthropicVertexDefaultConfig,Na as axAIAzureOpenAIBestConfig,Fa as axAIAzureOpenAICreativeConfig,Hs as axAIAzureOpenAIDefaultConfig,_a as axAIAzureOpenAIFastConfig,Ua as axAICohereCreativeConfig,Vs as axAICohereDefaultConfig,qa as axAIDeepSeekCodeConfig,Js as axAIDeepSeekDefaultConfig,Xs as axAIGoogleGeminiDefaultConfig,za as axAIGoogleGeminiDefaultCreativeConfig,ol as axAIGrokBestConfig,mo as axAIGrokDefaultConfig,Ka as axAIHuggingFaceCreativeConfig,Zs as axAIHuggingFaceDefaultConfig,Wa as axAIMistralBestConfig,eo as axAIMistralDefaultConfig,ti as axAIOllamaDefaultConfig,Va as axAIOllamaDefaultCreativeConfig,_r as axAIOpenAIBestConfig,Nr as axAIOpenAICreativeConfig,ht as axAIOpenAIDefaultConfig,Dr as axAIOpenAIFastConfig,Qa as axAIOpenAIResponsesBestConfig,Ya as axAIOpenAIResponsesCreativeConfig,Fn as axAIOpenAIResponsesDefaultConfig,ni as axAIOpenRouterDefaultConfig,Za as axAIRekaBestConfig,el as axAIRekaCreativeConfig,Nn as axAIRekaDefaultConfig,tl as axAIRekaFastConfig,oi as axAITogetherDefaultConfig,rl as axAIWebLLMCreativeConfig,si as axAIWebLLMDefaultConfig,Xa as axAnalyzeChatPromptRequirements,ft as axAnalyzeRequestRequirements,Q as axBaseAIDefaultConfig,de as axBaseAIDefaultCreativeConfig,pl as axCheckMetricsHealth,as as axCreateDefaultColorLogger,Zi as axCreateDefaultOptimizerColorLogger,ec as axCreateDefaultOptimizerTextLogger,Ra as axCreateDefaultTextLogger,lr as axCreateFlowColorLogger,yc as axCreateFlowTextLogger,bc as axDefaultFlowLogger,ai as axDefaultMetricsConfig,nr as axDefaultOptimizerLogger,ea as axDefaultOptimizerMetricsConfig,$a as axGetCompatibilityReport,Ga as axGetFormatCompatibility,ml as axGetMetricsConfig,rc as axGetOptimizerMetricsConfig,La as axGetProvidersWithMediaSupport,se as axGlobals,Tn as axModelInfoAnthropic,Ur as axModelInfoCohere,qr as axModelInfoDeepSeek,Kr as axModelInfoGoogleGemini,uo as axModelInfoGrok,Jr as axModelInfoGroq,Qr as axModelInfoHuggingFace,Zr as axModelInfoMistral,Et as axModelInfoOpenAI,Pr as axModelInfoOpenAIResponses,so as axModelInfoReka,lo as axModelInfoTogether,co as axModelInfoWebLLM,oo as axProcessContentForProvider,Mc as axRAG,Lr as axScoreProvidersForRequest,Gr as axSelectOptimalProvider,U as axSpanAttributes,qe as axSpanEvents,dl as axUpdateMetricsConfig,nc as axUpdateOptimizerMetricsConfig,vt as axValidateChatRequestMessage,Mr as axValidateChatResponseResult,Ks as axValidateProviderCapabilities,on as f,Wo as flow,xc as s};
448
+ `);a=u.pop()||"";for(let d of u)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let g=JSON.parse(m);if("id"in g&&g.id===t){n(g);return}this.messageHandler&&this.messageHandler(g)}catch(g){console.error("Failed to parse SSE data:",g)}}await l()}catch(c){o.releaseLock(),r(c)}};l().catch(r)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=JSON.stringify(e),r=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.mcpEndpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:n})}if(!r.ok)throw r.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}async terminateSession(){if(this.sessionId)try{let e=this.buildHeaders({});(await fetch(this.mcpEndpoint,{method:"DELETE",headers:e})).status===405&&console.info("Server does not support explicit session termination")}catch(e){console.error("Failed to terminate session:",e)}finally{this.sessionId=void 0}}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0)}};var ls=class{endpoint=null;sseUrl;eventSource;customHeaders={};oauthHelper;currentToken;currentIssuer;sseAbort;pendingRequests=new Map;messageHandler;endpointReady;constructor(e,t){this.sseUrl=e,this.customHeaders={...t?.headers??{}},t?.authorization&&(this.customHeaders.Authorization=t.authorization),this.oauthHelper=new wt(t?.oauth)}buildHeaders(e){return{...this.customHeaders,...e}}async openSSEWithFetch(e){let t=new AbortController;this.sseAbort=t;let n=await fetch(this.sseUrl,{method:"GET",headers:e,signal:t.signal});if(n.status===401){let o=n.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,this.openSSEWithFetch(this.buildHeaders({Accept:"text/event-stream"}))}if(!n.ok)throw new Error("Failed to establish SSE connection");let r=this.createEndpointReady();this.consumeSSEStream(n),await r}createEndpointReady(){if(!this.endpointReady){let e,t=new Promise(n=>{e=n});this.endpointReady={resolve:e,promise:t}}return this.endpointReady.promise}async consumeSSEStream(e){if(!e.body)throw new Error("No response body available for SSE stream");let t=e.body.getReader(),n=new TextDecoder,r="",o=null;for(;;){let{done:s,value:a}=await t.read();if(s)break;r+=n.decode(a,{stream:!0});let l=r.split(`
449
+ `);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))o=c.slice(7).trim();else if(c.startsWith("data: ")){let p=c.slice(6);if(o==="endpoint"){let u=p.trim(),d;try{let m=JSON.parse(u);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=u}if(!d)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(d)||(d=new URL(this.sseUrl).origin+(d.startsWith("/")?d:`/${d}`)),this.endpoint=d,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let u=p.trim();try{let d=JSON.parse(u);if(d&&typeof d=="object"&&"id"in d){let m=d.id,g=this.pendingRequests.get(m);g?(g.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else c.trim()===""&&(o=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=new Promise((a,l)=>{this.pendingRequests.set(e.id,{resolve:a,reject:l})}),o=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let a=o.headers.get("WWW-Authenticate"),l=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!l)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${l.token.accessToken}`,o=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${o.status}: ${o.statusText}`);if(o.headers.get("Content-Type")?.includes("application/json")){let a=await o.json();return this.pendingRequests.delete(e.id),a}return r}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),r=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(r.status===401){let o=r.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:o,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${s.token.accessToken}`,r=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!r.ok)throw new Error(`HTTP error ${r.status}: ${r.statusText}`);r.status!==202&&console.warn(`Unexpected status for notification: ${r.status}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};function Lc(i,e,t,n,r){let o={...i};if(o.parameters){let s=o.parameters.properties?Object.keys(o.parameters.properties):[],l=t.filter(c=>s.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){o.parameters=Bc(o.parameters,l);let c=o.func;o.func=async(p,u)=>{let d={};if(Array.isArray(e)){let g=e.filter(f=>f.role==="user").pop();g&&(d=Ia(g.values,l))}else d=Ia(e,l);let m={...p,...d};return await c(m,u)}}return o}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(o.parameters=Ta(o.parameters,n)),o}var ya=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),ba=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),gr=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:o,agents:s,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:p,debug:u}=l??{};if(this.ai=e,this.agents=s,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=p??[],this.debug=u,this.options=l,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw ya;if(r&&r.length<100)throw ba;this.program=new ve(o,{...l,description:r??n});for(let m of s??[])this.program.register(m);this.name=t,this.func={name:Uc(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();d&&!this.disableSmartModelRouting&&(this.func.parameters=Ta(this.func.parameters,d))}static create(e,t){let n=pe.create(e),{ai:r,name:o,description:s,definition:a,agents:l,functions:c,...p}=t;return new i({ai:r,name:o,description:s,definition:a,signature:n,agents:l,functions:c},p)}setExamples(e,t){this.program.setExamples(e,t)}setId(e){this.program.setId(e)}setParentId(e){this.program.setParentId(e)}getTraces(){return this.program.getTraces()}setDemos(e){this.program.setDemos(e)}getUsage(){return this.program.getUsage()}resetUsage(){this.program.resetUsage()}getFunction(){let e=this.forward.bind(this),t=async(n,r)=>{let{model:o,...s}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,s,{...r,model:o}),p=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=p.find(g=>g.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
450
+ `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,o=r?.getModelList(),a=this.program.getSignature().getInputFields().map(u=>u.name),l=this.getDebug(r,n),c=this.agents?.map(u=>{let d=u.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return Lc(u.getFunction(),t,a,o,m)}),p=[...n?.functions??this.functions??[],...c??[]];return{ai:r,functions:p,debug:l}}async forward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return await this.program.forward(r,t,a)}async*streamingForward(e,t,n){let{ai:r,functions:o,debug:s}=this.init(e,t,n),a={...this.options,...n,debug:s,functions:o};return yield*this.program.streamingForward(r,t,a)}setDescription(e){if(!e||e.length<20)throw ya;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw ba;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}applyOptimization(e){this.program.applyOptimization?.(e)}getDebug(e,t){return t?.debug??this.debug??e?.getOptions()?.debug??!1}};function Uc(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let o=n.toLowerCase();return r>0&&o&&o[0]?o[0].toUpperCase()+o.slice(1):o}).join("")}function Ta(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(s=>s.key),description:`The AI model to use for this function call. Available options: ${e.map(s=>`\`${s.key}\` ${s.description}`).join(", ")}`},r={...t.properties??{},model:n},o=[...t.required??[],"model"];return{...t,properties:r,required:o}}function Bc(i,e){let t=structuredClone(i);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(r=>!e.includes(r));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Ia(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function qc(i,e){let t=typeof i=="string"?pe.create(i):i,{ai:n,name:r,description:o,definition:s,agents:a,functions:l,...c}=e;return new gr({ai:n,name:r,description:o,definition:s,signature:t,agents:a,functions:l},c)}var zc=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,o=e?.qualityTarget??.85,s=e?.disableQualityHealing??!1;return ns({logger:e?.logger,debug:e?.debug}).node("queryGenerator","originalQuestion:string, previousContext?:string -> searchQuery:string, queryReasoning:string").node("contextualizer","retrievedDocument:string, accumulatedContext?:string -> enhancedContext:string").node("qualityAssessor","currentContext:string, originalQuestion:string -> completenessScore:number, missingAspects:string[]").node("questionDecomposer","complexQuestion:string -> subQuestions:string[], decompositionReason:string").node("evidenceSynthesizer","collectedEvidence:string[], originalQuestion:string -> synthesizedEvidence:string, evidenceGaps:string[]").node("gapAnalyzer","synthesizedEvidence:string, evidenceGaps:string[], originalQuestion:string -> needsMoreInfo:boolean, focusedQueries:string[]").node("answerGenerator","finalContext:string, originalQuestion:string -> comprehensiveAnswer:string, confidenceLevel:number").node("queryRefiner","originalQuestion:string, currentContext:string, missingAspects:string[] -> refinedQuery:string").node("qualityValidator","generatedAnswer:string, userQuery:string -> qualityScore:number, issues:string[]").node("answerHealer","originalAnswer:string, healingDocument:string, issues?:string[] -> healedAnswer:string").map(a=>({...a,maxHops:t,qualityThreshold:n,maxIterations:r,qualityTarget:o,disableQualityHealing:s,currentHop:0,accumulatedContext:"",retrievedContexts:[],completenessScore:0,searchQuery:a.originalQuestion,shouldContinue:!0,iteration:0,allEvidence:[],evidenceSources:[],needsMoreInfo:!0,healingAttempts:0,currentQuality:0,shouldContinueHealing:!0,currentAnswer:"",currentIssues:[]})).while(a=>a.currentHop<a.maxHops&&a.completenessScore<a.qualityThreshold&&a.shouldContinue).map(a=>({...a,currentHop:a.currentHop+1})).execute("queryGenerator",a=>({originalQuestion:a.originalQuestion,previousContext:a.accumulatedContext||void 0})).map(async a=>{let l=a.queryGeneratorResult?.searchQuery||a.searchQuery||a.originalQuestion,c=await i(l);return{...a,retrievalResult:{retrievedDocument:c,retrievalConfidence:.9}}}).execute("contextualizer",a=>({retrievedDocument:a.retrievalResult.retrievedDocument,accumulatedContext:a.accumulatedContext||void 0})).execute("qualityAssessor",a=>({currentContext:a.contextualizerResult.enhancedContext,originalQuestion:a.originalQuestion})).map(a=>({...a,accumulatedContext:a.contextualizerResult.enhancedContext,retrievedContexts:[...a.retrievedContexts,a.retrievalResult.retrievedDocument],completenessScore:a.qualityAssessorResult.completenessScore,searchQuery:a.queryGeneratorResult.searchQuery,shouldContinue:a.qualityAssessorResult.completenessScore<a.qualityThreshold})).branch(a=>a.shouldContinue&&a.currentHop<a.maxHops).when(!0).execute("queryRefiner",a=>({originalQuestion:a.originalQuestion,currentContext:a.accumulatedContext,missingAspects:a.qualityAssessorResult.missingAspects})).map(a=>({...a,searchQuery:a.queryRefinerResult?.refinedQuery||a.searchQuery})).when(!1).map(a=>a).merge().endWhile().map(a=>({...a,allEvidence:a.retrievedContexts.length>0?a.retrievedContexts:[]})).while(a=>a.iteration<a.maxIterations&&a.needsMoreInfo).map(a=>({...a,iteration:a.iteration+1})).branch(a=>a.iteration===1).when(!0).execute("questionDecomposer",a=>({complexQuestion:a.originalQuestion})).map(a=>({...a,currentQueries:a.questionDecomposerResult.subQuestions})).when(!1).map(a=>({...a,currentQueries:a.gapAnalyzerResult?.focusedQueries||[]})).merge().map(async a=>{let l=a.currentQueries||[],c=l.length>0?await Promise.all(l.filter(Boolean).map(p=>i(p))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],p=[...l,...c].filter(Boolean);return{collectedEvidence:p.length>0?p:["No evidence collected yet"],originalQuestion:a.originalQuestion}}).execute("gapAnalyzer",a=>({synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence,evidenceGaps:a.evidenceSynthesizerResult.evidenceGaps,originalQuestion:a.originalQuestion})).map(a=>({...a,allEvidence:[...Array.isArray(a.allEvidence)?a.allEvidence:[],...Array.isArray(a.retrievalResults)?a.retrievalResults:[]],evidenceSources:[...Array.isArray(a.evidenceSources)?a.evidenceSources:[],`Iteration ${a.iteration} sources`],needsMoreInfo:a.gapAnalyzerResult.needsMoreInfo,synthesizedEvidence:a.evidenceSynthesizerResult.synthesizedEvidence})).endWhile().execute("answerGenerator",a=>({finalContext:(()=>{let l=(a.accumulatedContext||"").toString().trim();if(l.length>0)return l;let c=(a.synthesizedEvidence||"").toString().trim();if(c.length>0)return c;let u=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
451
+ `):"").toString().trim();return u.length>0?u:"No context available."})(),originalQuestion:a.originalQuestion})).branch(a=>!a.disableQualityHealing).when(!0).execute("qualityValidator",a=>({generatedAnswer:a.answerGeneratorResult.comprehensiveAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).while(a=>a.healingAttempts<3&&a.shouldContinueHealing).map(a=>({...a,healingAttempts:a.healingAttempts+1})).map(async a=>{let l=a.currentIssues||[],c=l.length>0?`${a.originalQuestion} addressing issues: ${l.join(", ")}`:`${a.originalQuestion} quality improvement`,p=await i(c);return{...a,healingResult:{healingDocument:p}}}).execute("answerHealer",a=>({originalAnswer:a.currentAnswer,healingDocument:a.healingResult.healingDocument,issues:a.currentIssues})).execute("qualityValidator",a=>({generatedAnswer:a.answerHealerResult.healedAnswer,userQuery:a.originalQuestion})).map(a=>({...a,currentAnswer:a.answerHealerResult.healedAnswer,currentQuality:a.qualityValidatorResult.qualityScore,currentIssues:a.qualityValidatorResult.issues,shouldContinueHealing:a.qualityValidatorResult.qualityScore<a.qualityTarget})).endWhile().when(!1).map(a=>({...a,currentAnswer:a.answerGeneratorResult.comprehensiveAnswer,currentQuality:1,currentIssues:[],shouldContinueHealing:!1})).merge().returns(a=>({finalAnswer:a.currentAnswer,totalHops:a.currentHop,retrievedContexts:a.retrievedContexts,iterationCount:a.iteration,healingAttempts:a.healingAttempts,qualityAchieved:a.currentQuality}))};export{Yo as AxACE,lr as AxACEOptimizedProgram,Un as AxAI,Mt as AxAIAnthropic,Cn as AxAIAnthropicModel,Fr as AxAIAnthropicVertexModel,Nt as AxAIAzureOpenAI,Dt as AxAICohere,On as AxAICohereEmbedModel,vn as AxAICohereModel,$t as AxAIDeepSeek,kn as AxAIDeepSeekModel,Gt as AxAIGoogleGemini,Kr as AxAIGoogleGeminiEmbedModel,si as AxAIGoogleGeminiEmbedTypes,Mn as AxAIGoogleGeminiModel,Wr as AxAIGoogleGeminiSafetyCategory,Vr as AxAIGoogleGeminiSafetyThreshold,Qt as AxAIGrok,hi as AxAIGrokEmbedModels,Ln as AxAIGrokModel,Ut as AxAIGroq,En as AxAIGroqModel,Bt as AxAIHuggingFace,eo as AxAIHuggingFaceModel,qt as AxAIMistral,ci as AxAIMistralEmbedModels,Pn as AxAIMistralModel,zt as AxAIOllama,_t as AxAIOpenAI,ue as AxAIOpenAIBase,Et as AxAIOpenAIEmbedModel,Sn as AxAIOpenAIModel,Ht as AxAIOpenAIResponses,_n as AxAIOpenAIResponsesBase,jt as AxAIOpenAIResponsesImpl,Pt as AxAIOpenAIResponsesModel,Kt as AxAIOpenRouter,le as AxAIRefusalError,Wt as AxAIReka,Dn as AxAIRekaModel,vt as AxAIServiceAbortedError,at as AxAIServiceAuthenticationError,Te as AxAIServiceError,Je as AxAIServiceNetworkError,nt as AxAIServiceResponseError,ht as AxAIServiceStatusError,Be as AxAIServiceStreamTerminatedError,ft as AxAIServiceTimeoutError,Vt as AxAITogether,Jt as AxAIWebLLM,Gn as AxAIWebLLMModel,gr as AxAgent,Bo as AxApacheTika,Qe as AxAssertionError,Ur as AxBalancer,de as AxBaseAI,Oe as AxBaseOptimizer,cn as AxBootstrapFewShot,qe as AxContentProcessingError,yo as AxDB,Ge as AxDBBase,Yt as AxDBCloudflare,Io as AxDBManager,lt as AxDBMemory,Xt as AxDBPinecone,Zt as AxDBWeaviate,ar as AxDefaultCostTracker,Uo as AxDefaultResultReranker,rs as AxDockerSession,os as AxEmbeddingAdapter,lc as AxEvalUtil,dr as AxFlow,dn as AxFlowDependencyAnalyzer,mn as AxFlowExecutionPlanner,gn as AxFlowSubContextImpl,ts as AxFlowTypedSubContextImpl,Ie as AxFluentFieldType,Kn as AxFunctionError,Wn as AxFunctionProcessor,Xo as AxGEPA,Zo as AxGEPAFlow,ve as AxGen,rr as AxGenerateError,Ho as AxHFDataLoader,sn as AxInstanceRegistry,xs as AxLLMRequestTypeValues,ss as AxMCPClient,ls as AxMCPHTTPSSETransport,as as AxMCPStreambleHTTPTransport,De as AxMediaNotSupportedError,tn as AxMemory,es as AxMiPRO,oo as AxMockAIService,so as AxMultiServiceRouter,Ye as AxOptimizedProgramImpl,pt as AxProgram,It as AxPromptTemplate,po as AxProviderRouter,Lt as AxRateLimiterTokenUsage,pe as AxSignature,Zn as AxSignatureBuilder,zo as AxSimpleClassifier,qo as AxSimpleClassifierClass,ys as AxSpanKindValues,bt as AxStopFunctionCallException,Lo as AxStringUtil,jo as AxTestPrompt,qc as agent,gl as ai,fe as ax,Xs as axAIAnthropicDefaultConfig,Da as axAIAnthropicVertexDefaultConfig,ja as axAIAzureOpenAIBestConfig,qa as axAIAzureOpenAICreativeConfig,ei as axAIAzureOpenAIDefaultConfig,za as axAIAzureOpenAIFastConfig,Ja as axAICohereCreativeConfig,ri as axAICohereDefaultConfig,Ya as axAIDeepSeekCodeConfig,oi as axAIDeepSeekDefaultConfig,ai as axAIGoogleGeminiDefaultConfig,Xa as axAIGoogleGeminiDefaultCreativeConfig,ml as axAIGrokBestConfig,fo as axAIGrokDefaultConfig,tl as axAIHuggingFaceCreativeConfig,li as axAIHuggingFaceDefaultConfig,nl as axAIMistralBestConfig,ro as axAIMistralDefaultConfig,pi as axAIOllamaDefaultConfig,rl as axAIOllamaDefaultCreativeConfig,$r as axAIOpenAIBestConfig,Gr as axAIOpenAICreativeConfig,At as axAIOpenAIDefaultConfig,Lr as axAIOpenAIFastConfig,sl as axAIOpenAIResponsesBestConfig,il as axAIOpenAIResponsesCreativeConfig,Nn as axAIOpenAIResponsesDefaultConfig,ui as axAIOpenRouterDefaultConfig,ll as axAIRekaBestConfig,cl as axAIRekaCreativeConfig,$n as axAIRekaDefaultConfig,pl as axAIRekaFastConfig,mi as axAITogetherDefaultConfig,dl as axAIWebLLMCreativeConfig,gi as axAIWebLLMDefaultConfig,al as axAnalyzeChatPromptRequirements,xt as axAnalyzeRequestRequirements,Q as axBaseAIDefaultConfig,me as axBaseAIDefaultCreativeConfig,yl as axCheckMetricsHealth,fs as axCreateDefaultColorLogger,la as axCreateDefaultOptimizerColorLogger,cc as axCreateDefaultOptimizerTextLogger,Pa as axCreateDefaultTextLogger,ur as axCreateFlowColorLogger,Fc as axCreateFlowTextLogger,_c as axDefaultFlowLogger,fi as axDefaultMetricsConfig,or as axDefaultOptimizerLogger,ca as axDefaultOptimizerMetricsConfig,Ka as axGetCompatibilityReport,Va as axGetFormatCompatibility,Tl as axGetMetricsConfig,dc as axGetOptimizerMetricsConfig,Wa as axGetProvidersWithMediaSupport,ie as axGlobals,Rn as axModelInfoAnthropic,zr as axModelInfoCohere,Hr as axModelInfoDeepSeek,Jr as axModelInfoGoogleGemini,ho as axModelInfoGrok,Xr as axModelInfoGroq,Zr as axModelInfoHuggingFace,no as axModelInfoMistral,Ft as axModelInfoOpenAI,Nr as axModelInfoOpenAIResponses,lo as axModelInfoReka,uo as axModelInfoTogether,mo as axModelInfoWebLLM,ao as axProcessContentForProvider,zc as axRAG,Br as axScoreProvidersForRequest,qr as axSelectOptimalProvider,B as axSpanAttributes,ze as axSpanEvents,Il as axUpdateMetricsConfig,uc as axUpdateOptimizerMetricsConfig,kt as axValidateChatRequestMessage,Pr as axValidateChatResponseResult,ti as axValidateProviderCapabilities,re as f,ns as flow,wc as s};
438
452
  //# sourceMappingURL=index.js.map