@ax-llm/ax 16.1.7 → 16.1.8

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,21 +1,21 @@
1
- function Ke({model:i,modelInfo:e,models:t}){let n=t?.find(c=>c.key===i),r=n&&"model"in n?n.model:i,s=e.find(c=>c.name===i);if(s)return s;let o=e.find(c=>c.name===r);if(o)return o;let a=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+$/,""),l=e.find(c=>c.name===a);return l||null}var ns=(()=>{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 Me(){return ns.randomUUID()}async function hl(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await ns.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}var ts=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 s=0;s<n.length;s++){let o=n[s];r=(r<<5)-r+o,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return hl(this.data)}};function Ne(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new ts}function Ho(){return ns}var Jn=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 Ke({model:i,modelInfo:e,models:t}){let n=t?.find(c=>c.key===i),r=n&&"model"in n?n.model:i,s=e.find(c=>c.name===i);if(s)return s;let o=e.find(c=>c.name===r);if(o)return o;let a=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+$/,""),l=e.find(c=>c.name===a);return l||null}var rs=(()=>{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 Me(){return rs.randomUUID()}async function hl(i){let e=new TextEncoder,t=typeof i=="string"?e.encode(i):i,n=await rs.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(o=>o.toString(16).padStart(2,"0")).join("")}var ns=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 s=0;s<n.length;s++){let o=n[s];r=(r<<5)-r+o,r=r&r}return Math.abs(r).toString(16).padStart(8,"0")}async digestAsync(){return hl(this.data)}};function Ne(i){if(i!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new ns}function Ko(){return rs}var Qn=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 s=Number.parseInt(r,10);Number.isNaN(s)||(this.currentEvent.retry=s);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 rs=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)}},Qn=class extends TransformStream{constructor(){super(new rs)}};var fl={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},xl=globalThis.TextDecoderStream??Qn,Le=class extends Error{constructor(t,n,r,s,o={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=s;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Me(),this.context=o,this.includeRequestBodyInErrors=a,this.stack=this.toString()}timestamp;errorId;context;includeRequestBodyInErrors;toString(){let t=[`${this.name}: ${this.message}`,`URL: ${this.url}`];return this.includeRequestBodyInErrors&&t.push(`Request Body: ${JSON.stringify(this.requestBody,null,2)}`),t.push(`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`),t.join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Ue=class extends Le{constructor(t,n,r,s,o,a,l,c=!0){let u=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${u}`,r,s,{httpStatus:t,httpStatusText:n,responseBody:o,...a},{},c);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Pe=class extends Le{constructor(t,n,r,s,o,a=!0){super(`Network Error: ${t.message}`,n,r,s,{originalErrorName:t.name,originalErrorStack:t.stack,...o},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},bt=class extends Le{constructor(e,t,n,r,s=!0){super(e,t,n,void 0,r,s),this.name="AxAIServiceResponseError"}},Ze=class extends Le{constructor(t,n,r,s,o=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...s},o);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},We=class extends Le{constructor(e,t,n,r,s=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},s),this.name="AxAIServiceTimeoutError"}},Yn=class extends Ue{constructor(e,t,n,r,s,o,a=!0){super(e,t,n,r,s,o,void 0,a),this.name="AxTokenLimitError"}},Yt=class extends Le{constructor(e,t,n,r,s=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},s),this.name="AxAIServiceAbortedError"}},It=class extends Le{constructor(e,t,n,r,s=!0){super("Authentication failed",e,t,n,r,s),this.name="AxAIServiceAuthenticationError"}},ge=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=Me()}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(`
7
+ `:"")+r;break;case"id":this.currentEvent.id=r;break;case"retry":{let s=Number.parseInt(r,10);Number.isNaN(s)||(this.currentEvent.retry=s);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 ss=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 ss)}};var fl={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},xl=globalThis.TextDecoderStream??Yn,Le=class extends Error{constructor(t,n,r,s,o={},a=!0){super(t);this.url=n;this.requestBody=r;this.responseBody=s;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=Me(),this.context=o,this.includeRequestBodyInErrors=a,this.stack=this.toString()}timestamp;errorId;context;includeRequestBodyInErrors;toString(){let t=[`${this.name}: ${this.message}`,`URL: ${this.url}`];return this.includeRequestBodyInErrors&&t.push(`Request Body: ${JSON.stringify(this.requestBody,null,2)}`),t.push(`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`),t.join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Ue=class extends Le{constructor(t,n,r,s,o,a,l,c=!0){let u=l?` (after ${l} retries)`:"";super(`HTTP ${t} - ${n}${u}`,r,s,{httpStatus:t,httpStatusText:n,responseBody:o,...a},{},c);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},Pe=class extends Le{constructor(t,n,r,s,o,a=!0){super(`Network Error: ${t.message}`,n,r,s,{originalErrorName:t.name,originalErrorStack:t.stack,...o},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},bt=class extends Le{constructor(e,t,n,r,s=!0){super(e,t,n,void 0,r,s),this.name="AxAIServiceResponseError"}},Ze=class extends Le{constructor(t,n,r,s,o=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:r,...s},o);this.lastChunk=r;this.name="AxAIServiceStreamTerminatedError"}},We=class extends Le{constructor(e,t,n,r,s=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...r},s),this.name="AxAIServiceTimeoutError"}},Xn=class extends Ue{constructor(e,t,n,r,s,o,a=!0){super(e,t,n,r,s,o,void 0,a),this.name="AxTokenLimitError"}},Xt=class extends Le{constructor(e,t,n,r,s=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...r},s),this.name="AxAIServiceAbortedError"}},It=class extends Le{constructor(e,t,n,r,s=!0){super("Authentication failed",e,t,n,r,s),this.name="AxAIServiceAuthenticationError"}},ge=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=Me()}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
9
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},et=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=Me()}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
10
  `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},at=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=Me()}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 ss(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 Ko(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Al(i){if(!i)return;let e=Number(i);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(i);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function yl(){return{startTime:Date.now(),retryCount:0}}function Wo(i){i.retryCount++,i.lastRetryTime=Date.now()}function Vo(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Pe&&!(i instanceof It)}var Ee=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={...fl,...i.retry},n=i.timeout,r=yl(),s=i.verbose??!1,o=i.includeRequestBodyInErrors??!0,a,l=new URL(i.url),c=`${[l.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,u=new URL(c,l);if(i.corsProxy){let m=u.href;u=new URL(`${i.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Me();if(i.validateRequest&&!await i.validateRequest(e))throw new bt("Invalid request data",u.href,e,{validation:"request"},o);i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":u.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Yt(u.href,i.abortSignal.reason,e,{metrics:r},o);let h=()=>{m.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",h,{once:!0});let g=m.abort.bind(m);m.abort=f=>{i.abortSignal.removeEventListener("abort",h),g(f)}}n&&(a=setTimeout(()=>{m.abort("Request timeout")},n));try{s&&console.log(`
11
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function os(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 Wo(i,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**i)*(.75+Math.random()*.5)}function Al(i){if(!i)return;let e=Number(i);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(i);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function yl(){return{startTime:Date.now(),retryCount:0}}function Vo(i){i.retryCount++,i.lastRetryTime=Date.now()}function Jo(i,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:i instanceof Pe&&!(i instanceof It)}var Ee=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={...fl,...i.retry},n=i.timeout,r=yl(),s=i.verbose??!1,o=i.includeRequestBodyInErrors??!0,a,l=new URL(i.url),c=`${[l.pathname,i.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,u=new URL(c,l);if(i.corsProxy){let m=u.href;u=new URL(`${i.corsProxy}?url=${encodeURIComponent(m)}`)}let p=Me();if(i.validateRequest&&!await i.validateRequest(e))throw new bt("Invalid request data",u.href,e,{validation:"request"},o);i.span?.setAttributes({"http.request.method":i.put?"PUT":"POST","url.full":u.href,"request.id":p,"request.startTime":r.startTime});let d=0;for(;;){let m=new AbortController;if(i.abortSignal){if(i.abortSignal.aborted)throw new Xt(u.href,i.abortSignal.reason,e,{metrics:r},o);let h=()=>{m.abort(i.abortSignal.reason||"User aborted request")};i.abortSignal.addEventListener("abort",h,{once:!0});let g=m.abort.bind(m);m.abort=f=>{i.abortSignal.removeEventListener("abort",h),g(f)}}n&&(a=setTimeout(()=>{m.abort("Request timeout")},n));try{s&&console.log(`
12
12
  --- [AxAI API Request] ---
13
13
  `,`URL: ${u.href}
14
14
  `,`Method: ${i.put?"PUT":"POST"}
15
15
  `,"Headers:",JSON.stringify({"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...i.headers},null,2),`
16
16
  Body:`,JSON.stringify(e,null,2),`
17
17
  ------------------------
18
- `);let h=await(i.fetch??fetch)(u,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...i.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),h.status===401||h.status===403){let T=await ss(h);throw new It(u.href,e,T,{metrics:r},o)}if(h.status===400){let T=await ss(h),A=T,I=!1;if(A?.error?.code==="context_length_exceeded")I=!0;else if(A?.type==="invalid_request_error"&&(A?.error?.message?.includes("prompt is too long")||A?.error?.message?.includes("max_tokens")||A?.error?.message?.includes("token limit")))I=!0;else if(A?.error?.code===400&&A?.error?.status==="INVALID_ARGUMENT"&&(A?.error?.message?.includes("token")||A?.error?.message?.includes("limit")))I=!0;else{let C=JSON.stringify(T).toLowerCase();(C.includes("token")&&C.includes("limit")||C.includes("context length")||C.includes("prompt is too long"))&&(I=!0)}if(I)throw new Yn(h.status,h.statusText,u.href,e,T,{metrics:r},o)}if(h.status>=400&&Vo(new Error,h.status,d,t)){let T=Ko(d,t),A=Al(h.headers.get("Retry-After"));A!==void 0&&A<=t.maxDelayMs&&(T=A,s&&console.log(`[AxAI] Respecting Retry-After header: ${T}ms`)),d++,Wo(r),i.span?.addEvent("retry",{attempt:d,delay:T,status:h.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(I=>setTimeout(I,T));continue}if(h.status>=400){let T=await ss(h);throw new Ue(h.status,h.statusText,u.href,e,T,{metrics:r},d>0?d:void 0,o)}if(!i.stream){let T=await h.json();if(s&&console.log(`
18
+ `);let h=await(i.fetch??fetch)(u,{method:i.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":d.toString(),...i.headers},body:JSON.stringify(e),signal:m.signal});if(a&&clearTimeout(a),h.status===401||h.status===403){let T=await os(h);throw new It(u.href,e,T,{metrics:r},o)}if(h.status===400){let T=await os(h),A=T,I=!1;if(A?.error?.code==="context_length_exceeded")I=!0;else if(A?.type==="invalid_request_error"&&(A?.error?.message?.includes("prompt is too long")||A?.error?.message?.includes("max_tokens")||A?.error?.message?.includes("token limit")))I=!0;else if(A?.error?.code===400&&A?.error?.status==="INVALID_ARGUMENT"&&(A?.error?.message?.includes("token")||A?.error?.message?.includes("limit")))I=!0;else{let C=JSON.stringify(T).toLowerCase();(C.includes("token")&&C.includes("limit")||C.includes("context length")||C.includes("prompt is too long"))&&(I=!0)}if(I)throw new Xn(h.status,h.statusText,u.href,e,T,{metrics:r},o)}if(h.status>=400&&Jo(new Error,h.status,d,t)){let T=Wo(d,t),A=Al(h.headers.get("Retry-After"));A!==void 0&&A<=t.maxDelayMs&&(T=A,s&&console.log(`[AxAI] Respecting Retry-After header: ${T}ms`)),d++,Vo(r),i.span?.addEvent("retry",{attempt:d,delay:T,status:h.status,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(I=>setTimeout(I,T));continue}if(h.status>=400){let T=await os(h);throw new Ue(h.status,h.statusText,u.href,e,T,{metrics:r},d>0?d:void 0,o)}if(!i.stream){let T=await h.json();if(s&&console.log(`
19
19
  --- [AxAI API Response] ---
20
20
  `,`Status: ${h.status} ${h.statusText}
21
21
  `,"Body:",JSON.stringify(T,null,2),`
@@ -28,7 +28,7 @@ Body:`,JSON.stringify(e,null,2),`
28
28
  `),!h.body)throw new bt("Response body is null",u.href,e,{metrics:r},o);let g,f=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(T){let A=h.body.getReader(),I=new TextDecoder,C="";async function S(){try{for(;;){let{done:R,value:P}=await A.read();if(R){b=!0,T.close();break}C+=I.decode(P,{stream:!0});let E=C.split(`
29
29
 
30
30
  `);C=E.pop()||"";for(let w of E){if(!w.trim())continue;let v=w.split(`
31
- `),k="",O="message";for(let N of v)N.startsWith("data: ")?k=N.slice(6):N.startsWith("event: ")&&(O=N.slice(7));if(k){if(k==="[DONE]"){T.close();return}try{let N=JSON.parse(k);g=N,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),T.enqueue(N),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":O})}catch(N){s&&console.warn("Skipping non-JSON SSE data:",k,N)}}}}}catch(R){let P=R,E={...r,streamDuration:Date.now()-r.startTime};P.name==="AbortError"||P.message?.includes("aborted")?T.error(new Ze(u.href,e,g,{streamMetrics:E},o)):T.error(new Pe(P,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:E},o))}finally{A.releaseLock()}}S()}});let x=new TransformStream({transform(T,A){g=T,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),A.enqueue(T),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),b=!1;return new ReadableStream({start(T){let A=h.body.pipeThrough(new xl).pipeThrough(new Jn).pipeThrough(x).getReader();async function I(){try{for(;;){let{done:C,value:S}=await A.read();if(C){b||(b=!0,T.close());break}if(b)break;T.enqueue(S)}}catch(C){let S=C,R={...r,streamDuration:Date.now()-r.startTime};throw S.name==="AbortError"||S.message?.includes("aborted")?T.error(new Ze(u.href,e,g,{streamMetrics:R},o)):S instanceof TypeError&&S.message.includes("cancelled")?T.error(new Ze(u.href,e,g,{streamMetrics:R,cancelReason:"Stream cancelled by client"},o)):T.error(new Pe(S,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:R},o)),S}finally{a&&clearTimeout(a),A.releaseLock()}}I()},cancel(){b=!0}})}catch(h){if(h instanceof Error&&h.name==="AbortError")throw i.abortSignal?.aborted?new Yt(u.href,i.abortSignal.reason,e,{metrics:r},o):new We(u.href,n||0,e,{metrics:r},o);let g=h;if(!(h instanceof Le)&&h instanceof Error&&(g=new Pe(h,u.href,e,void 0,{metrics:r},o)),i.span?.isRecording()&&(i.span.recordException(g),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),g instanceof Pe&&Vo(g,void 0,d,t)){let f=Ko(d,t);d++,Wo(r),i.span?.addEvent("retry",{attempt:d,delay:f,error:g.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,f));continue}throw g instanceof Le&&(g.context.metrics=r),g}finally{a!==void 0&&clearTimeout(a)}}};import{context as Si,SpanKind as ki}from"@opentelemetry/api";var Z={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var $e=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 ep=new $e,Jo=i=>{console.log(i)},Qo=(i,e,t)=>{let n=(r,s)=>t&&s&&s in t?t[s](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
31
+ `),k="",O="message";for(let N of v)N.startsWith("data: ")?k=N.slice(6):N.startsWith("event: ")&&(O=N.slice(7));if(k){if(k==="[DONE]"){T.close();return}try{let N=JSON.parse(k);g=N,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),T.enqueue(N),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount,"sse.event.type":O})}catch(N){s&&console.warn("Skipping non-JSON SSE data:",k,N)}}}}}catch(R){let P=R,E={...r,streamDuration:Date.now()-r.startTime};P.name==="AbortError"||P.message?.includes("aborted")?T.error(new Ze(u.href,e,g,{streamMetrics:E},o)):T.error(new Pe(P,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:E},o))}finally{A.releaseLock()}}S()}});let x=new TransformStream({transform(T,A){g=T,f++,r.streamChunks=f,r.lastChunkTime=Date.now(),A.enqueue(T),i.span?.addEvent("stream.chunk",{"stream.chunks":f,"stream.duration":Date.now()-r.startTime,"response.retries":r.retryCount})}}),b=!1;return new ReadableStream({start(T){let A=h.body.pipeThrough(new xl).pipeThrough(new Qn).pipeThrough(x).getReader();async function I(){try{for(;;){let{done:C,value:S}=await A.read();if(C){b||(b=!0,T.close());break}if(b)break;T.enqueue(S)}}catch(C){let S=C,R={...r,streamDuration:Date.now()-r.startTime};throw S.name==="AbortError"||S.message?.includes("aborted")?T.error(new Ze(u.href,e,g,{streamMetrics:R},o)):S instanceof TypeError&&S.message.includes("cancelled")?T.error(new Ze(u.href,e,g,{streamMetrics:R,cancelReason:"Stream cancelled by client"},o)):T.error(new Pe(S,u.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:R},o)),S}finally{a&&clearTimeout(a),A.releaseLock()}}I()},cancel(){b=!0}})}catch(h){if(h instanceof Error&&h.name==="AbortError")throw i.abortSignal?.aborted?new Xt(u.href,i.abortSignal.reason,e,{metrics:r},o):new We(u.href,n||0,e,{metrics:r},o);let g=h;if(!(h instanceof Le)&&h instanceof Error&&(g=new Pe(h,u.href,e,void 0,{metrics:r},o)),i.span?.isRecording()&&(i.span.recordException(g),i.span.setAttributes({"error.time":Date.now()-r.startTime,"error.retries":r.retryCount})),g instanceof Pe&&Jo(g,void 0,d,t)){let f=Wo(d,t);d++,Vo(r),i.span?.addEvent("retry",{attempt:d,delay:f,error:g.message,"metrics.startTime":r.startTime,"metrics.retryCount":r.retryCount,"metrics.lastRetryTime":r.lastRetryTime}),await new Promise(y=>setTimeout(y,f));continue}throw g instanceof Le&&(g.context.metrics=r),g}finally{a!==void 0&&clearTimeout(a)}}};import{context as ki,SpanKind as Oi}from"@opentelemetry/api";var Z={signatureStrict:!0,useStructuredPrompt:!0,tracer:void 0,meter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,cachingFunction:void 0,functionResultFormatter:i=>typeof i=="string"?i:i==null?"":JSON.stringify(i,null,2)};var $e=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 tp=new $e,Qo=i=>{console.log(i)},Yo=(i,e,t)=>{let n=(r,s)=>t&&s&&s in t?t[s](r):r;switch(i.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
32
32
  ${n(i.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
33
33
  ${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","greenBright")}
34
34
  `;if(typeof i.content=="string")return r+n(i.content,"green");let s=i.content.map(o=>{if(o.type==="text")return n(o.text,"green");if(o.type==="image"){let a=e?"[Image]":`[Image: ${o.image}]`;return n(a,"green")}if(o.type==="audio"){let a=e?"[Audio]":`[Audio: ${o.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return r+s.join(`
@@ -38,11 +38,11 @@ ${n(i.result??"[No result]","yellowDim")}`;case"user":{let r=`${n("[ USER ]","gr
38
38
  `,i.functionCalls.forEach((o,a)=>{let l=typeof o.function.params=="string"?o.function.params:JSON.stringify(o.function.params,null,2);s+=n(`${a+1}. ${o.function.name}(${l}) [id: ${o.id}]`,"yellowDim"),a<(i.functionCalls?.length??0)-1&&(s+=`
39
39
  `)}),s+=`
40
40
  `),!i.content&&(!i.functionCalls||i.functionCalls.length===0)&&(s+=n("[No content]","gray")),s}default:return`${n("[ UNKNOWN ]","redBright")}
41
- ${n(JSON.stringify(i),"gray")}`}},Yo=(i=Jo)=>{let e=new $e,t=e.gray(`${"\u2500".repeat(60)}
41
+ ${n(JSON.stringify(i),"gray")}`}},Xo=(i=Qo)=>{let e=new $e,t=e.gray(`${"\u2500".repeat(60)}
42
42
  `);return n=>{let r=n,s="";switch(r.name){case"ChatRequestChatPrompt":s=`
43
43
  ${e.blueBright(`[ CHAT REQUEST Step ${r.step} ]`)}
44
44
  ${t}
45
- `,r.value.forEach((o,a)=>{s+=Qo(o,void 0,e),a<r.value.length-1&&(s+=`
45
+ `,r.value.forEach((o,a)=>{s+=Yo(o,void 0,e),a<r.value.length-1&&(s+=`
46
46
  ${t}
47
47
  `)}),s+=`
48
48
  ${t}`;break;case"FunctionResults":s=`
@@ -102,10 +102,10 @@ ${t}
102
102
  [ CHAT RESPONSE CITATIONS ]`)}
103
103
  `,r.value.forEach(o=>{s+=`${e.white("- ")}${e.cyan(o.title||o.url)}
104
104
  `,o.description&&(s+=` ${e.gray(o.description)}
105
- `)}),s+=t;break}default:s=e.gray(JSON.stringify(r,null,2))}i(s)}},Xo=Yo(),bl=(i=Jo)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
105
+ `)}),s+=t;break}default:s=e.gray(JSON.stringify(r,null,2))}i(s)}},Zo=Xo(),bl=(i=Qo)=>{let e="\u2500".repeat(60);return t=>{let n=t,r="";switch(n.name){case"ChatRequestChatPrompt":r=`
106
106
  [ CHAT REQUEST Step ${n.step} ]
107
107
  ${e}
108
- `,n.value.forEach((s,o)=>{r+=Qo(s),o<n.value.length-1&&(r+=`
108
+ `,n.value.forEach((s,o)=>{r+=Yo(s),o<n.value.length-1&&(r+=`
109
109
  ${e}
110
110
  `)}),r+=`
111
111
  ${e}`;break;case"FunctionResults":r=`
@@ -164,19 +164,19 @@ ${e}
164
164
  `,n.value.forEach(s=>{r+=`- ${s.title||s.url}
165
165
  `,s.description&&(r+=` ${s.description}
166
166
  `)}),r+=`${e}
167
- `;break}default:r=JSON.stringify(n,null,2)}i(r)}};var Q={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"},lt={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"},Zo=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(Zo||{}),ei=(s=>(s.WORKFLOW="workflow",s.TASK="task",s.AGENT="agent",s.TOOL="tool",s.UNKNOWN="unknown",s))(ei||{});var os=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 os(e,t))}};function Zn(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 ti=(i,e,t,n)=>{let r=n?i.filter(o=>o.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ni=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function ri(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let s=t.get(r.index);s?(r.content&&(s.content=(s.content??"")+r.content),r.thought&&(s.thought=(s.thought??"")+r.thought),r.finishReason&&(s.finishReason=r.finishReason),r.functionCalls&&(s.functionCalls?Zn(s.functionCalls,structuredClone(r.functionCalls)):s.functionCalls=structuredClone(r.functionCalls))):(s=structuredClone(r),t.set(r.index,s))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var si=(i,e)=>{e({name:"FunctionResults",value:i})},is=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},oi=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},ii=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},ai=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var li=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},ci=(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)},ui=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var tr=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},wt=(...i)=>{let e={};for(let t of i)t&&Object.assign(e,t);return e},er,pi=i=>{if(er)return er;if(i)return er=Il(i),er};var Il=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)"}),cacheReadTokensCounter:i.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:i.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),di=(i,e,t,n,r,s)=>{try{if(i.latencyHistogram){let o=tr({operation:e,ai_service:n,...r?{model:r}:{},...s});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},mi=(i,e,t,n,r,s,o,a)=>{let l={operation:e,ai_service:s,...o?{model:o}:{},...a};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,l),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,l),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,l)},gi=(i,e,t,n,r)=>{try{if(i.errorCounter){let s=tr({operation:e,ai_service:t,...n?{model:n}:{},...r});i.errorCounter.add(1,s)}}catch(s){console.warn("Failed to record error metric:",s)}},hi=(i,e,t,n,r,s)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...s})},fi=(i,e,t,n,r)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Xt=(i,e,t,n,r,s)=>{try{let o=tr({ai_service:n,...r?{model:r}:{},...s});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)}},xi=(i,e,t,n,r,s)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...s})},Ai=(i,e,t,n,r,s)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...s};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},as=(i,e,t,n,r,s)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},ls=(i,e,t,n,r,s)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},yi=(i,e,t,n,r,s)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{},...s};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},cs=(i,e,t,n,r,s)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},bi=(i,e,t,n,r)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ii=(i,e,t,n,r)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ti=(i,e,t,n,r)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Ci=(i,e,t,n,r)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Ri=(i,e,t,n,r)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},wi=(i,e,t,n,r,s)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...s})},us=(i,e,t,n,r,s)=>{try{if(t<=0)return;let o=tr({ai_service:n,...r?{model:r}:{},...s});e==="read"&&i.cacheReadTokensCounter&&i.cacheReadTokensCounter.add(t,o),e==="write"&&i.cacheWriteTokensCounter&&i.cacheWriteTokensCounter.add(t,o)}catch(o){console.warn("Failed to record cache token metric:",o)}};function vi(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function tt(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${vi(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${vi(e.item)}`),new Error(t.join(`
168
- `))}function Zt(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 s=n[r];if(!s||typeof s!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(s)}`);let o=typeof s=="object"&&s!==null&&"type"in s&&typeof s.type=="string"?s.type:void 0;if(!o)throw new Error(`User message content item at index ${r} must have a type, received: ${e(o)}`);switch(o){case"text":{let a="text"in s&&typeof s.text=="string"?s.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 s&&typeof s.image=="string"?s.image:void 0,l="mimeType"in s&&typeof s.mimeType=="string"?s.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 s&&typeof s.data=="string"?s.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 s&&typeof s.fileUri=="string",l="data"in s&&typeof s.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(s)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(s)}`);if(a){let u=s.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=s.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(u)}`)}let c="mimeType"in s&&typeof s.mimeType=="string"?s.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 s&&typeof s.url=="string"?s.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(o)}`)}}}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,s=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,o=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(s)&&s.length>0;if(!o&&!a&&!l&&tt("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:s},item:i}),n!==void 0&&typeof n!="string"&&tt("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&tt("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&&tt("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&&tt("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&&tt("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)tt("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&tt("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&tt("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&&tt("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,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"&&tt("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 ps(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.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,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.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let s=0;s<r.thoughtBlocks.length;s++){let o=r.thoughtBlocks[s];if(typeof o!="object"||o===null)throw new Error(`Chat response result thoughtBlocks[${s}] at index ${n} must be an object, received: ${e(o)}`);if(typeof o.data!="string")throw new Error(`Chat response result thoughtBlocks[${s}].data at index ${n} must be a string, received: ${e(o.data)}`);if(typeof o.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${s}].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 thoughtBlocks[${s}].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 s=0;s<r.annotations.length;s++){let o=r.annotations[s];if(!o||typeof o!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must be an object, received: ${e(o)}`);if(o.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${s}] must have type 'url_citation', received: ${e(o.type)}`);if(!o.url_citation||typeof o.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must have a valid url_citation object, received: ${e(o.url_citation)}`);if(typeof o.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${s}] url_citation.url must be a string, received: ${e(o.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 s=0;s<r.functionCalls.length;s++){let o=r.functionCalls[s];if(!o)throw new Error(`Function call at index ${s} in result ${n} cannot be null or undefined, received: ${e(o)}`);if(!o.id||typeof o.id!="string"||o.id.trim()==="")throw new Error(`Function call at index ${s} in result ${n} must have a non-empty string id, received: ${e(o.id)}`);if(o.type!=="function")throw new Error(`Function call at index ${s} in result ${n} must have type 'function', received: ${e(o.type)}`);if(!o.function)throw new Error(`Function call at index ${s} in result ${n} must have a function object, received: ${e(o.function)}`);if(!o.function.name||typeof o.function.name!="string"||o.function.name.trim()==="")throw new Error(`Function call at index ${s} in result ${n} must have a non-empty function name, received: ${e(o.function.name)}`);if(o.function.params!==void 0&&typeof o.function.params!="string"&&typeof o.function.params!="object")throw new Error(`Function call params at index ${s} in result ${n} must be a string or object, received: ${e(o.function.params)}`)}}if(r.finishReason!==void 0){let s=["stop","length","function_call","content_filter","error"];if(!s.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${s.join(", ")}, received: ${e(r.finishReason)}`)}}}var ds=new Map;function Tl(i){return`${i.providerName}:${i.contentHash}`}function Cl(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Rl(i){let e=Ne("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let s of r.content)Cl(e,s)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var ie=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Ce=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:s,defaults:o,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??Z.tracer,this.meter=a.meter??Z.meter,this.modelInfo=s,this.models=c,this.id=Me();let u=this.getModel(o.model)??o.model,p=this.getEmbedModel(o.embedModel)??o.embedModel;if(this.defaults={model:u,embedModel:p},!o.model||typeof o.model!="string"||o.model==="")throw new Error("No model defined");this.setOptions(a),c&&wl(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=Z.logger??Xo;corsProxy;retry;customLabels;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 pi(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??Z.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??Z.tracer,this.meter=e.meter??Z.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??Z.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,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,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return wt(Z.customLabels,this.customLabels,e)}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((s,o)=>s-o),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((o,a)=>o+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let s=this.getMetricsInstruments();if(s){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);di(s,e,t,this.name,o,a),mi(s,e,r.mean,r.p95,r.p99,this.name,o,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let s=this.getMetricsInstruments();if(s){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);fi(s,e,this.name,o,a),t&&gi(s,e,this.name,o,a),hi(s,e,r.rate,this.name,o,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:s,totalTokens:o,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:c}=e.tokens,u=this.getMergedCustomLabels(t);r&&Xt(n,"input",r,this.name,e.model,u),s&&Xt(n,"output",s,this.name,e.model,u),o&&Xt(n,"total",o,this.name,e.model,u),a&&Xt(n,"thoughts",a,this.name,e.model,u),l&&us(n,"read",l,this.name,e.model,u),c&&us(n,"write",c,this.name,e.model,u)}}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 s of r.content)s.type==="image"?t=!0:s.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:s=0}=t.tokens,o=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*o/1e6+s*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:s=0}=t.tokens,o=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*o/1e6+s*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let s of e)s&&typeof s=="object"&&"function"in s&&s.function&&typeof s.function=="object"&&"name"in s.function&&Ai(r,s.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ti(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ci(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedChatModel,o=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=o?.stream??!1;xi(r,"chat",l,this.name,s,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);wi(r,c,u,this.name,s,a);let p=this.calculatePromptLength(e);bi(r,p,this.name,s,a),yi(r,o?.temperature,o?.maxTokens,this.name,s,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&Ri(r,this.modelUsage.tokens.thoughtsTokens,this.name,s,a);let d=this.calculateRequestSize(e);if(as(r,"chat",d,this.name,s,a),n&&!l){let m=n,h=this.calculateResponseSize(m);if(ls(r,"chat",h,this.name,s,a),m.results)for(let y of m.results)y.functionCalls&&this.recordFunctionCallMetrics(y.functionCalls,this.lastUsedChatModel,a);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);g>0&&Ii(r,g,this.name,s,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&cs(r,"chat",f,this.name,s,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedEmbedModel,o=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);as(r,"embed",a,this.name,s,o);let l=this.calculateResponseSize(t);ls(r,"embed",l,this.name,s,o);let c=this.estimateCostByName(s,t.modelUsage);c>0&&cs(r,"embed",c,this.name,s,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,s,o=this.getModelByKey(e.model),a=o?o.thinkingTokenBudget:void 0,l={...o?{thinkingTokenBudget:a,showThoughts:o.showThoughts,stream:o.stream,debug:o.debug,useExpensiveModel:o.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return s=await this._chat1(e,l),s}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat",l?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),r||this.recordChatMetrics(e,l,s)}}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)Zt(c);let r=this.getModelByKey(e.model),s={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},o=this.modelInfo.find(c=>c.name===n);if(o?.notSupported?.temperature&&"temperature"in s&&delete s.temperature,o?.notSupported?.topP&&"topP"in s&&delete s.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 s.stream=(t?.stream!==void 0?t.stream:s.stream)??!0,this.getFeatures(n).streaming||(s.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:ki.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"chat",[Q.LLM_REQUEST_MODEL]:n,[Q.LLM_REQUEST_MAX_TOKENS]:s.maxTokens??"Not set",[Q.LLM_REQUEST_TEMPERATURE]:s.temperature,[Q.LLM_REQUEST_TOP_P]:s.topP??"Not set",[Q.LLM_REQUEST_TOP_K]:s.topK??"Not set",[Q.LLM_REQUEST_FREQUENCY_PENALTY]:s.frequencyPenalty??"Not set",[Q.LLM_REQUEST_PRESENCE_PENALTY]:s.presencePenalty??"Not set",[Q.LLM_REQUEST_STOP_SEQUENCES]:s.stopSequences?.join(", ")??"Not set",[Q.LLM_REQUEST_LLM_IS_STREAMING]:s.stream??"Not set"}},t?.traceContext??Si.active(),async c=>await this._chat2(n,s,e,t,c)):await this._chat2(n,s,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,s){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let o=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(b=>this.cleanupFunctionSchema(b)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,o&&ti(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(b=>{if(b.role==="assistant"){let{content:T,name:A,cache:I}=b;return{role:"assistant",content:T,name:A,cache:I}}return b.role==="function"?{role:"user",content:b.result}:b}),functions:[]}:c,h=await this.handleContextCaching(e,m,r,s),g=async()=>{if(h?.preparedRequest){let{apiConfig:I,request:C}=h.preparedRequest;return s?.isRecording()&&Oi(n,s,this.excludeContentFromTrace),await Ee({name:I.name,url:this.apiURL,localCall:I.localCall,headers:await this.buildHeaders(I.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},C)}let[b,T]=await this.aiImpl.createChatReq(m,r);return s?.isRecording()&&Oi(n,s,this.excludeContentFromTrace),await Ee({name:b.name,url:this.apiURL,localCall:b.localCall,headers:await this.buildHeaders(b.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},T)},f=r?.rateLimiter??this.rt,y=f?await f(g,{modelUsage:this.modelUsage}):await g();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let b=this.aiImpl.createChatStreamResp.bind(this),T=S=>R=>{let P=b(R,S);if(P.sessionId=r?.sessionId,!P.modelUsage){let E=this.aiImpl.getTokenUsage();E&&(P.modelUsage={ai:this.name,model:e,tokens:E})}return this.modelUsage=P.modelUsage,this.recordTokenUsage(P.modelUsage,r?.customLabels),s?.isRecording()&&Mi(P,s,this.excludeContentFromTrace),P},A=async S=>{s?.isRecording()&&s.end(),o&&ri(S,r?.logger??this.logger)};if(typeof window<"u"){let S=y,R={},P=[],E=r?.abortSignal??this.abortSignal;return new ReadableStream({start:w=>{let v=S.getReader(),k=()=>{try{v.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{s?.isRecording()&&s.end()}catch{}try{w.error(new DOMException("Aborted","AbortError"))}catch{w.error(new Error("Aborted"))}};if(E){if(E.aborted){k();return}E.addEventListener("abort",k,{once:!0})}async function O(){try{for(;;){let{done:N,value:M}=await v.read();if(N){A&&await A(P),w.close();break}let D=T(R)(M);D&&(P.push(D),w.enqueue(D))}}catch(N){if(w.error(N),s?.isRecording())try{s.end()}catch{}}finally{if(v.releaseLock(),E)try{E.removeEventListener("abort",k)}catch{}}}O()}})}return y.pipeThrough(new Xn(T({}),A))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(y);if(x.sessionId=r?.sessionId,!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage,r?.customLabels)),s?.isRecording()&&(Mi(x,s,this.excludeContentFromTrace),s.end()),o&&ni(x,r?.logger??this.logger),x}async embed(e,t){let n=performance.now(),r=!1,s,o=this.getModelByKey(e.embedModel),a={...o?{thinkingTokenBudget:o.thinkingTokenBudget,showThoughts:o.showThoughts,stream:o.stream,debug:o.debug,useExpensiveModel:o.useExpensiveModel}:void 0,...t};try{return s=await this._embed1(e,a),s}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&s&&this.recordEmbedMetrics(e,s,a)}}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:ki.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"embeddings",[Q.LLM_REQUEST_MODEL]:n}},t?.traceContext??Si.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 s=this.aiImpl.createEmbedReq.bind(this.aiImpl),o=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,o&&li(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,h]=await s(l);return await Ee({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},h)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(lt.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),o&&ci(d.embeddings,n?.logger??this.logger),r?.end(),d}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}async handleContextCaching(e,t,n,r){let s=n?.contextCache;if(!s)return null;let o=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!o&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!o)return null;let l=s.ttlSeconds??3600,c=s.refreshWindowSeconds??300,u=s.minTokens??2048;if(s.name)return this.useCacheByName(e,t,s.name,n,r);let p=Rl(t.chatPrompt);if(!p||p===Ne("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=Tl(d),h=Date.now(),g=s.registry,f=g?await g.get(m):ds.get(m);if(f&&f.expiresAt>h){if(f.expiresAt-h<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let T={cacheName:f.cacheName,expiresAt:h+l*1e3,tokenCount:f.tokenCount};g?await g.set(m,T):ds.set(m,{...T,contentHash:p,lastTouchedAt:h})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let b=await this.executeCacheOperation(x,n,r);if(b){let T={cacheName:b.name,expiresAt:new Date(b.expiresAt).getTime(),tokenCount:b.tokenCount};return g?await g.set(m,T):ds.set(m,{...T,contentHash:p,lastTouchedAt:h}),this.useCacheByName(e,t,b.name,n,r)}}return null}async useCacheByName(e,t,n,r,s){if(this.aiImpl.prepareCachedChatReq){let o=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:o.apiConfig,request:o.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let s=await Ee({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(s)}catch(s){n?.addEvent("context_cache.error",{type:e.type,error:s instanceof Error?s.message:String(s)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)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)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Oi(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let s of i.chatPrompt)switch(s.role){case"system":if(s.content){let o={};t||(o.content=s.content),e.addEvent(lt.GEN_AI_SYSTEM_MESSAGE,o)}break;case"user":if(typeof s.content=="string")n.push(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"&&n.push(o.text);break;case"assistant":{let o=s.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(o&&o.length>0){let a={function_calls:JSON.stringify(o,null,2)};!t&&s.content&&(a.content=s.content),e.addEvent(lt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(s.content){let a={};t||(a.content=s.content),e.addEvent(lt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let o={id:s.functionId};t||(o.content=s.result),e.addEvent(lt.GEN_AI_TOOL_MESSAGE,o);break}}let r={};t||(r.content=n.join(`
169
- `)),e.addEvent(lt.GEN_AI_USER_MESSAGE,r)}function Mi(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[Q.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(lt.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[Q.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 s=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),o={};s&&s.length>0?(t||(o.content=r.content),o.tool_calls=s):t||(o.content=r.content??""),e.addEvent(lt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(o,null,2)})}}function Pi(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 wl(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 nr=(g=>(g.Claude46Opus="claude-opus-4-6",g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(nr||{}),rr=(m=>(m.Claude46Opus="claude-opus-4-6@20260205",m.Claude45Opus="claude-opus-4-5@20251101",m.Claude41Opus="claude-opus-4-1@20250805",m.Claude4Opus="claude-opus-4@20250514",m.Claude45Sonnet="claude-sonnet-4-5@20250929",m.Claude4Sonnet="claude-sonnet-4@20250514",m.Claude37Sonnet="claude-3-7-sonnet@20250219",m.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",m.Claude45Haiku="claude-haiku-4-5@20251001",m.Claude35Haiku="claude-3-5-haiku@20241022",m.Claude35Sonnet="claude-3-5-sonnet@20240620",m.Claude3Opus="claude-3-opus@20240229",m.Claude3Haiku="claude-3-haiku@20240307",m))(rr||{});var sr=[{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6@20260205",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,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 Tt=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Tt(r)]))),e.items&&(e.items=Tt(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Tt(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Tt(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Tt(n))),e},Fi=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...ie()}),vl=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...ie()}),ms=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;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,s;this.isVertex?s={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={name:"/messages"};let o;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":o={tool_choice:{type:"auto"}};break;case"required":o={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)o={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.some(O=>"cache"in O&&O.cache)||e.functions?.some(O=>O.cache),l=e.chatPrompt.filter(O=>O.role==="system"),c=l.map((O,N)=>({type:"text",text:O.content,...O.cache||a&&N===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(O=>O.role!=="system"),p=e.functions?.map((O,N,M)=>{let D={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=O.parameters?Tt(O.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...D}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:O.name,description:O.description,input_schema:F,...O.cache||a&&N===M.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(O=>O&&typeof O=="object"&&"type"in O?O:{name:O.name,description:O.description,input_schema:O.input_schema?Tt(O.input_schema):void 0,...O.cache_control?{cache_control:O.cache_control}:{}}),h=[...p??[],...m];h.length===0&&(h=void 0);let g=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,y=e.modelConfig?.temperature,x=e.modelConfig?.topP,b=e.modelConfig?.topK??this.config.topK,T=e.modelConfig?.n??this.config.n;if(T&&T>1)throw new Error("Anthropic does not support sampling (n > 1)");let A=O=>O.includes("claude-opus-4-6"),I=O=>O.includes("claude-opus-4-5"),C,S,R=n;if(t?.thinkingTokenBudget){let O=this.config.thinkingTokenBudgetLevels,N=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")C=void 0,S=void 0;else{let M=t.thinkingTokenBudget;if(A(R))C={type:"adaptive"},S={effort:N?.[M]??"medium"};else if(I(R)){C={type:"enabled",budget_tokens:O?.[M]??1e4};let F=N?.[M]??"medium";F==="max"&&(F="high"),S={effort:F}}else C={type:"enabled",budget_tokens:O?.[M]??1e4}}}let E=Sl(u,!!C);E.some(O=>O.role==="assistant"&&Array.isArray(O.content)&&O.content.length>0&&O.content[0]?.type==="tool_use")&&(C=void 0,S=void 0);let v;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let O=e.responseFormat.schema.schema||e.responseFormat.schema;v={type:"json_schema",schema:Tt(O)},this.usedStructuredOutput=!0}let k={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...g?{max_tokens:g}:{},...f&&f.length>0?{stop_sequences:f}:{},...y!==void 0&&!C?{temperature:y}:{},...x!==void 0&&(!C||x>=.95)?{top_p:x}:{},...b&&!C?{top_k:b}:{},...o,...h?{tools:h}:{},...r?{stream:!0}:{},...c?{system:c}:{},...C?{thinking:C}:{},...S?{output_config:S}:{},...v?{output_format:v}:{},messages:E};return[s,k]};createChatResp=e=>{if(e.type==="error")throw new ge(e.error.message,void 0,void 0);let t=Ei(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",s=[],o=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;o.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;o.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":s.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),o.length>0&&(l.thoughtBlocks=o,l.thought=o.map(u=>u.data).join("")),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+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_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:s}=e;throw new ge(s.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:s}=e,o=[{index:r,content:"",id:s.id}];return this.tokensUsed={promptTokens:s.usage?.input_tokens??0,completionTokens:s.usage?.output_tokens??0,totalTokens:(s.usage?.input_tokens??0)+(s.usage?.output_tokens??0)+(s.usage?.cache_creation_input_tokens??0)+(s.usage?.cache_read_input_tokens??0),cacheCreationTokens:s.usage?.cache_creation_input_tokens,cacheReadTokens:s.usage?.cache_read_input_tokens},{results:o}}if(e.type==="content_block_start"){let{content_block:s}=e;if(s.type==="text"){let o=[];if(Array.isArray(s.citations))for(let a of s.citations)a?.url&&o.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:s.text,...o.length?{citations:o}:{}}]}}if(s.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="tool_use"&&typeof s.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=s.id;let o=[{id:s.id,type:"function",function:{name:s.name,params:""}}];return{results:[{index:r,functionCalls:o}]}}if(s.type==="web_search_tool_result"||s.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:s}=e;if(s.type==="citations_delta"){let o=s.citation;if(o&&typeof o.url=="string"&&o.url.length>0){let a=[{url:String(o.url),title:typeof o.title=="string"?o.title:void 0,snippet:typeof o.cited_text=="string"?o.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(s.type==="text_delta"){let o=[];if(Array.isArray(s.citations))for(let a of s.citations)a?.url&&o.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:s.text,...o.length?{citations:o}:{}}]}}if(s.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:s.signature}]}]};if(s.type==="input_json_delta"){let o=n.indexIdMap[e.index];if(!o)return{results:[{index:r,content:""}]};let a=[{id:o,type:"function",function:{name:"",params:s.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:s,usage:o}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:o.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+o.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Ei(s.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},en=class i extends Ce{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:s,models:o}){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==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}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":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={...Fi(),...r},p=new ms(u,a),d=h=>{let g=Ke({model:h,modelInfo:sr,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,structuredOutputs:g?.supported?.structuredOutputs??!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"],cacheBreakpoints:!1},thinking:g?.supported?.thinkingBudget??!1,multiTurn:!0}},m=o?.map(h=>{let g=h,f=g?.config;if(!f)return h;let y={};f.maxTokens!==void 0&&(y.maxTokens=f.maxTokens),f.temperature!==void 0&&(y.temperature=f.temperature),f.topP!==void 0&&(y.topP=f.topP),f.topK!==void 0&&(y.topK=f.topK),f.presencePenalty!==void 0&&(y.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(y.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(y.stopSequences=f.stopSequences),f.endSequences!==void 0&&(y.endSequences=f.endSequences),f.stream!==void 0&&(y.stream=f.stream),f.n!==void 0&&(y.n=f.n);let x={...g};Object.keys(y).length>0&&(x.modelConfig={...g.modelConfig??{},...y});let b=f.thinking?.thinkingTokenBudget;if(typeof b=="number"){let T=u.thinkingTokenBudgetLevels,A=[["minimal",T?.minimal??1024],["low",T?.low??5e3],["medium",T?.medium??1e4],["high",T?.high??2e4],["highest",T?.highest??32e3]],I="minimal",C=Number.POSITIVE_INFINITY;for(let[S,R]of A){let P=Math.abs(b-R);P<C&&(C=P,I=S)}x.thinkingTokenBudget=I}return f.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!f.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:sr,defaults:{model:u.model},options:s,supportFor:d,models:m??o})}};function Sl(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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let s="",o=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?o.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):o.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(o.length>0?s=[...o,{type:"text",text:r.content}]:s=r.content),typeof r.functionCalls<"u"&&(s=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(s)&&o.length>0&&(s=[...o,...s])),r.cache){if(typeof s=="string")s=[{type:"text",text:s,cache_control:{type:"ephemeral"}}];else if(Array.isArray(s)&&s.length>0){let l=s.length-1,c=s[l];c&&c.type==="text"&&(s[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:s}}default:throw new Error("Invalid role")}}),n=kl(t);return Ol(n)}function kl(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 Ol(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Ei(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 or=(w=>(w.GPT4="gpt-4",w.GPT41="gpt-4.1",w.GPT41Mini="gpt-4.1-mini",w.GPT41Nano="gpt-4.1-nano",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.GPT5Pro="gpt-5-pro",w.GPT51="gpt-5.1",w.GPT51ChatLatest="gpt-5.1-chat-latest",w.GPT52="gpt-5.2",w.GPT52ChatLatest="gpt-5.2-chat-latest",w.GPT52Pro="gpt-5.2-pro",w.O1="o1",w.O1Mini="o1-mini",w.O3="o3",w.O3Mini="o3-mini",w.O4Mini="o4-mini",w))(or||{}),tn=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(tn||{});var nn=(k=>(k.GPT4="gpt-4",k.GPT41="gpt-4.1",k.GPT41Mini="gpt-4.1-mini",k.GPT41Nano="gpt-4.1-nano",k.GPT4O="gpt-4o",k.GPT4OMini="gpt-4o-mini",k.GPT4ChatGPT4O="chatgpt-4o-latest",k.GPT4Turbo="gpt-4-turbo",k.GPT35Turbo="gpt-3.5-turbo",k.GPT35TurboInstruct="gpt-3.5-turbo-instruct",k.GPT35TextDavinci002="text-davinci-002",k.GPT3TextBabbage002="text-babbage-002",k.GPT3TextAda001="text-ada-001",k.GPT5="gpt-5",k.GPT5Nano="gpt-5-nano",k.GPT5Mini="gpt-5-mini",k.GPT5Chat="gpt-5-chat",k.GPT5Pro="gpt-5-pro",k.GPT51="gpt-5.1",k.GPT51ChatLatest="gpt-5.1-chat-latest",k.GPT52="gpt-5.2",k.GPT52ChatLatest="gpt-5.2-chat-latest",k.GPT52Pro="gpt-5.2-pro",k.O1Pro="o1-pro",k.O1="o1",k.O1Mini="o1-mini",k.O3Pro="o3-pro",k.O3="o3",k.O3Mini="o3-mini",k.O4Mini="o4-mini",k))(nn||{});var rn=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{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}],gs=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Ml=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},Nt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ie()}),fs=()=>structuredClone({...Nt(),model:"gpt-5"}),xs=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),As=()=>({...Nt(),model:"gpt-5-nano"}),hs=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"},s=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),o=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Pl(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=Ml(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...s?{tools:s}:{},...o?{tool_choice:o}:{},...p?{}:{...(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}}:{},...u?{store:u}:{},...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:s}=e;if(s)throw s;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 ge(a.message.refusal,e.model,e.id);let l=_i(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:p,name:d}})=>({id:u,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:s}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let o=t;return o.indexIdMap||(o.indexIdMap={}),{results:s.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:h},finish_reason:g})=>{if(p)throw new ge(p,void 0,n);let f=_i(g),y=d?.map(({id:x,index:b,function:{name:T,arguments:A}})=>{typeof x=="string"&&typeof b=="number"&&!o.indexIdMap[b]&&(o.indexIdMap[b]=x);let I=o.indexIdMap[b];return I?{id:I,type:"function",function:{name:T,params:A}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:y,finishReason:f,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)}}},_i=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Pl(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 Ie=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s,models:o,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new hs(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:o})}},sn=class extends Ie{constructor({apiKey:e,apiURL:t,config:n,options:r,models:s,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...rn,...o??[]];let a=c=>{let u=Ke({model:c,modelInfo:o,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!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:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=s?.map(c=>{let u=c,p=u?.config;if(!p)return c;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let h={...u};Object.keys(d).length>0&&(h.modelConfig={...u.modelConfig??{},...d});let g=p?.thinking?.thinkingTokenBudget;if(typeof g=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",x=Number.POSITIVE_INFINITY;for(let[b,T]of f){let A=Math.abs(g-T);A<x&&(x=A,y=b)}h.thinkingTokenBudget=y}return p?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!p.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...Nt(),...n},options:r,modelInfo:o,models:l??s,supportFor:a}),super.setName("OpenAI")}};var El=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},Fl=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Ni=Nt,_l=xs,Nl=As,Ll=fs,on=class extends Ie{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:s,options:o,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={...Ni(),...s},u=El(r),p=Fl(u);l=[...rn,...l??[]];let d=h=>{let g=Ke({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,structuredOutputs:p&&(g?.supported?.structuredOutputs??!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:g?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:o,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var ys=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.");$l(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(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}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){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!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:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={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}}},t=0,n=0,r=0,s=0;for(let o of this.services){let a=o.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,s+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),s>0&&(e.latency.embed.mean=r/s);for(let o of this.services){let a=o.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,s=Date.now()-r,o=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return s>=o}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,s=r?.requiresImages,o=r?.requiresAudio,a=this.services,l=e.model;if((n||s||o)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||s&&!d.media.images.supported||o&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),s&&p.push("images"),o&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Le))throw p;switch(p.constructor){case It:throw p;case Ue:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Pe:break;case bt:break;case Ze:break;case We:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Le)||r instanceof Ue&&![408,429,500,502,503,504].includes(r.status)||r instanceof It)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let o=this.getNextService(this.services,n);if(!o.service)throw r;this.currentService=o.service,n=o.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function $l(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 s=i[r];if(!s)throw new Error(`Service at index ${r} is undefined`);let o=s.getModelList();if(!o)throw new Error(`Service at index ${r} (${s.getName()}) has no model list while another service does.`);let a=new Set(o.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${s.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${s.getName()}) has extra model "${l}"`)}}function Lt(i){let e=!1,t=!1,n=!1,r=!1,s=!1,o=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let p of u.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(s=!0),i.modelConfig?.stream===!0&&(o=!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:s,requiresStreaming:o,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function Li(i,e){let t=i.getFeatures(),n=[],r=[],s=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),s.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),s.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),s.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),s.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),s.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),s.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:s}}function bs(i,e){return i.map(t=>{let n=t.getFeatures(),r=Li(t,e),s=0,o=[];return s+=10,e.hasImages&&n.media.images.supported&&(s+=25,o.push("Images"),n.media.images.detailLevels?.includes("high")&&(s+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(s+=3)),e.hasAudio&&n.media.audio.supported&&(s+=25,o.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(s+=5)),e.hasFiles&&n.media.files.supported&&(s+=25,o.push("Files"),n.media.files.uploadMethod==="cloud"&&(s+=3)),e.hasUrls&&n.media.urls.supported&&(s+=25,o.push("URLs"),n.media.urls.webSearch&&(s+=5)),e.requiresFunctions&&n.functions&&(s+=15,o.push("Functions"),n.functionCot&&(s+=3)),e.requiresStreaming&&n.streaming&&(s+=10,o.push("Streaming")),e.requiresCaching&&n.caching.supported&&(s+=8,o.push("Caching"),n.caching.types.includes("persistent")&&(s+=3)),n.thinking&&(s+=2),n.multiTurn&&(s+=2),n.hasThinkingBudget&&(s+=1),n.hasShowThoughts&&(s+=1),s-=r.missingCapabilities.length*10,{provider:t,score:s,missingCapabilities:r.missingCapabilities,supportedCapabilities:o}}).sort((t,n)=>n.score-t.score)}function Is(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=Lt(i),r=bs(e,n);if(t.requireExactMatch){let s=r.filter(o=>o.missingCapabilities.length===0);if(s.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return s[0].provider}if(!t.allowDegradation){let s=r[0];if(s.missingCapabilities.length>0)throw new Error(`Best available provider (${s.provider.getName()}) is missing: ${s.missingCapabilities.join(", ")}`)}return r[0].provider}function Gl(i,e){let t=Lt(i),n=bs(e,t),r=n[0]?.provider||null,s=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,o=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${o}/${s} requirements (${Math.round(o/Math.max(s,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Dl(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Ul(i,e){let t={};for(let n of i){let s=n.getFeatures().media[e];if(s.supported)for(let o of s.formats)t[o]||(t[o]=[]),t[o].push(n)}return t}var ir=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(ir||{}),ar=(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))(ar||{});var Ts=[{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 Gi=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ie()}),Bl=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),Cs=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),s;n&&n.role==="user"&&typeof n.content=="string"&&(s=n?.content);let o=jl(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,h]of Object.entries(p.parameters.properties))d[m]={description:h.description,type:h.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),c={name:"/chat"},u={message:s,model:t,tools:a,...l&&!s?{tool_results:l}:{},chat_history:o,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,u]}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(s=>({id:s.name,type:"function",function:{name:s.name,params:s.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),s=r[0];if(!s)throw new Error("No result");return s.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},an=class extends Ce{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let s={...Gi(),...t},o=new Cs(s),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let p={};u.maxTokens!==void 0&&(p.maxTokens=u.maxTokens),u.temperature!==void 0&&(p.temperature=u.temperature),u.topP!==void 0&&(p.topP=u.topP),u.topK!==void 0&&(p.topK=u.topK),u.presencePenalty!==void 0&&(p.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(p.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(p.stopSequences=u.stopSequences),u.endSequences!==void 0&&(p.endSequences=u.endSequences),u.stream!==void 0&&(p.stream=u.stream),u.n!==void 0&&(p.n=u.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(o,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ts,defaults:{model:s.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 jl(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=$i(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(o=>{if(o.role==="assistant")return o.functionCalls?.find(a=>a.id===e.functionId)}).filter(o=>o!==void 0),r=$i(n)?.at(0);if(!r)throw new Error("Function call not found");let s=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:s}]}}default:throw new Error("Unknown role")}})}function $i(i){return i?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var lr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(lr||{});var Rs=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Di=()=>structuredClone({model:"deepseek-chat",...ie()}),ql=()=>structuredClone({model:"deepseek-coder",...Se()}),ln=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("DeepSeek API key not set");let o={...Di(),...t};s=[...Rs,...s??[]],super({apiKey:e,config:o,options:n,apiURL:"https://api.deepseek.com",modelInfo:s,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 cr=(x=>(x.Gemini3Flash="gemini-3-flash-preview",x.Gemini3Pro="gemini-3-pro-preview",x.Gemini3ProImage="gemini-3-pro-image-preview",x.Gemini25Pro="gemini-2.5-pro",x.Gemini25Flash="gemini-2.5-flash",x.Gemini25FlashLite="gemini-2.5-flash-lite",x.Gemini20Flash="gemini-2.0-flash",x.Gemini20FlashLite="gemini-2.0-flash-lite",x.Gemini20ProExp="gemini-2.0-pro-exp-02-05",x.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",x.Gemini1Pro="gemini-1.0-pro",x.Gemini15Flash="gemini-1.5-flash",x.Gemini15Flash002="gemini-1.5-flash-002",x.Gemini15Flash8B="gemini-1.5-flash-8b",x.Gemini15Pro="gemini-1.5-pro",x.GeminiFlashLatest="gemini-flash-latest",x.GeminiFlashLiteLatest="gemini-flash-lite-latest",x.GeminiProLatest="gemini-pro-latest",x))(cr||{}),ws=(s=>(s.GeminiEmbedding001="gemini-embedding-001",s.GeminiEmbedding="gemini-embedding-exp",s.TextEmbeddingLarge="text-embedding-large-exp-03-07",s.TextEmbedding004="text-embedding-004",s.TextEmbedding005="text-embedding-005",s))(ws||{}),vs=(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))(vs||{}),Ss=(s=>(s.BlockNone="BLOCK_NONE",s.BlockOnlyHigh="BLOCK_ONLY_HIGH",s.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",s.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",s.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",s))(Ss||{}),Ui=(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))(Ui||{}),Bi=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var ks=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var vt=i=>i.includes("gemini-3"),ji=i=>i.includes("gemini-3")&&i.includes("pro"),ur=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,Array.isArray(e.type)&&(e.type=e.type.includes("object")?"object":e.type[0]??"string"),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,ur(n)]))),e.items&&(e.items=ur(e.items)),e},qi=[{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"}],zi=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:qi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...ie()}),zl=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:qi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...Se()}),Os=class{constructor(e,t,n,r,s){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=s;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini");let o=this.config.model;if(vt(o)){if(this.config.thinking?.thinkingTokenBudget!==void 0&&typeof this.config.thinking.thinkingTokenBudget=="number")throw new Error(`Gemini 3 models (${o}) do not support numeric thinkingTokenBudget. Use thinkingLevel ('low', 'medium', 'high') instead, or pass thinkingTokenBudget as a string level via options.`);if(ji(o)&&this.config.thinking?.thinkingLevel){let a=this.config.thinking.thinkingLevel;if(a!=="low"&&a!=="high")throw new Error(`Gemini 3 Pro (${o}) only supports thinkingLevel 'low' or 'high', got '${a}'. Use 'low' for less thinking or 'high' for more thinking.`)}}}tokensUsed;models;setModels(e){this.models=e}getEffectiveMappings(e){let t=this.models?.find(n=>n.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}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 s;if(this.endpointId?s={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:s={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let x=r?"&":"?",b=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;s.name+=`${x}key=${b}`}let o=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=o.length>0?{role:"user",parts:[{text:o.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<c.length;x++){let b=c[x];switch(b.role){case"user":{let T=Array.isArray(b.content)?b.content.map((A,I)=>{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: ${I})`)}}):[{text:b.content}];l.push({role:"user",parts:T});break}case"assistant":{let T=[],A=b.thoughtBlocks,I=b.functionCalls&&b.functionCalls.length>0,C=A?.[0],S=A?.map(P=>P.data).join("")??"",R=C?.signature;if(S&&T.push({...I?{}:{thought:!0},text:S,...R&&!I?{thought_signature:R}:{}}),b.functionCalls){let P=b.functionCalls.map((E,w)=>{let v;if(typeof E.function.params=="string"){let O=E.function.params;if(O.trim().length===0)v={};else try{v=JSON.parse(O)}catch{throw new Error(`Failed to parse function params JSON: ${O}`)}}else v=E.function.params;let k={functionCall:{name:E.function.name,args:v}};return R&&w===0&&(k.thought_signature=R),k});T.push(...P)}if(b.content&&T.push({text:b.content}),T.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:T});break}case"function":{let T=[],A=b,I=x;for(;;){if(!("functionId"in A))throw new Error(`Chat prompt functionId is empty (index: ${I})`);if(T.push({functionResponse:{name:A.functionId,response:{result:A.result}}}),I+1<c.length&&c[I+1].role==="function")I++,A=c[I];else break}x=I,l.push({role:"user",parts:T});break}default:throw new Error(`Invalid role: ${JSON.stringify(b)} (index: ${x})`)}}let u=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(b=>{let T={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},A=b.parameters?ur(b.parameters):void 0;return A===void 0||A&&typeof A=="object"&&Object.keys(A).length===0?A={...T}:A&&typeof A=="object"&&A.type==="object"&&(!("properties"in A)||!A.properties||Object.keys(A.properties).length===0)&&(A={...A,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:b.name,description:b.description,parameters:A}});u.push({function_declarations:x})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,b=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};u.push({google_maps:b})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;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 x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&vt(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.getEffectiveMappings(n),b=x.thinkingTokenBudgetLevels;if(vt(n)){let A=ji(n),I=x.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=I?.minimal??"minimal";else{let C=t.thinkingTokenBudget,S=I?.[C];S||(S=C==="highest"?"high":C),m.thinkingLevel=S}if(A&&m.thinkingLevel){let C=m.thinkingLevel;C!=="low"&&C!=="high"&&(m.thinkingLevel=C==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=b?.minimal??200;break;case"low":m.thinkingBudget=b?.low??800;break;case"medium":m.thinkingBudget=b?.medium??5e3;break;case"high":m.thinkingBudget=b?.high??1e4;break;case"highest":m.thinkingBudget=b?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,vt(n)||delete m.thinkingLevel,vt(n)&&delete m.thinkingBudget;let h=e.modelConfig?.maxTokens??this.config.maxTokens;if(m.thinkingLevel&&h!==void 0)throw new Error("Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.");t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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(m).length>0?{thinkingConfig:m}:{}};if(vt(n)&&(g.temperature===void 0||g.temperature<1)&&(g.temperature=1),e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=ur(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let f=this.config.safetySettings;return[s,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:f}]};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(s=>({content:s,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let s=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${s}`},r={requests:e.texts.map(o=>({model:`models/${t}`,content:{parts:[{text:o}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(s=>{let o={index:0};switch(s.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new ge("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new ge("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new ge("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new ge("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new ge("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new ge("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new ge("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new ge("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new ge("Other finish reason",void 0,void 0)}if(!s.content||!s.content.parts)return o;for(let c of s.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){o.thought=c.text;let u=c.thoughtSignature||c.thought_signature;o.thoughtBlocks||(o.thoughtBlocks=[]),o.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else o.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!o.thoughtBlocks||o.thoughtBlocks.length===0)o.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=o.thoughtBlocks[o.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}o.functionCalls=[...o.functionCalls??[],{id:Me(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=s.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;o.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=s.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(o.citations=[...o.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return o});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};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}};supportsContextCache=e=>{let t=e;return Bi.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:s,contents:o}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!o||o.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(a.systemInstruction=s),o&&o.length>0&&(a.contents=o);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let s=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${s}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:s=>{let o=s;if(o?.name)return{name:o.name,expiresAt:o.expireTime,tokenCount:o.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,s=e.modelConfig?.stream??this.config.stream,{dynamicContents:o,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:s?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:s?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=s?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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"};vt(r)&&(c.temperature===void 0||c.temperature<1)&&(c.temperature=1);let u=this.config.safetySettings,p={contents:o,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if("cache"in o&&o.cache){r=s;break}}for(let s=0;s<e.length;s++){let o=e[s];if(o.role==="system"){t={role:"user",parts:[{text:o.content}]};continue}if(r>=0&&s<=r)if(o.role==="user"){let a=[];if(typeof o.content=="string")a.push({text:o.content});else if(Array.isArray(o.content))for(let l of o.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else o.role==="assistant"&&o.content&&n.push({role:"model",parts:[{text:o.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let s=[];if(typeof r.content=="string")s.push({text:r.content});else if(Array.isArray(r.content)){for(let o of r.content)if(!("cache"in o&&o.cache))switch(o.type){case"text":s.push({text:o.text});break;case"image":s.push({inlineData:{mimeType:o.mimeType,data:o.image}});break;case"audio":s.push({inlineData:{mimeType:`audio/${o.format??"mp3"}`,data:o.data}});break;case"file":"fileUri"in o?s.push({fileData:{mimeType:o.mimeType,fileUri:o.fileUri}}):s.push({inlineData:{mimeType:o.mimeType,data:o.data}});break}}s.length>0&&n.push({role:"user",parts:s})}else if(r.role==="assistant"){let s=[];if(r.content&&s.push({text:r.content}),r.functionCalls)for(let o of r.functionCalls){let a;if(typeof o.function.params=="string")try{a=JSON.parse(o.function.params)}catch{a={}}else a=o.function.params??{};s.push({functionCall:{name:o.function.name,args:a}})}s.length>0&&n.push({role:"model",parts:s})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},cn=class i extends Ce{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:s,options:o,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,u,p;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 f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...zi(),...s},m=new Os(d,c,r,e,o);l=[...ks,...l??[]];let h=f=>{let y=Ke({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:y?.supported?.thinkingBudget??!1,hasShowThoughts:y?.supported?.showThoughts??!1,structuredOutputs:y?.supported?.structuredOutputs??!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:m.supportsContextCache(f),types:["persistent"]},thinking:y?.supported?.thinkingBudget??!1,multiTurn:!0}},g=a?.map(f=>{let y=f,x=y?.config;if(!x)return f;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let T={...y};Object.keys(b).length>0&&(T.modelConfig={...y.modelConfig??{},...b});let A=x.thinking?.thinkingTokenBudget;if(typeof A=="number"){let I=d.thinkingTokenBudgetLevels,C=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],S="minimal",R=Number.POSITIVE_INFINITY;for(let[P,E]of C){let w=Math.abs(A-E);w<R&&(R=w,S=P)}T.thinkingTokenBudget=S}return x.thinking?.includeThoughts!==void 0&&(T.showThoughts=!!x.thinking.includeThoughts),x.thinkingLevelMapping&&(T.thinkingLevelMapping=x.thinkingLevelMapping),x.thinkingTokenBudgetLevels&&(T.thinkingTokenBudgetLevels=x.thinkingTokenBudgetLevels),T});g?m.setModels(g):a&&m.setModels(a),super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:o,supportFor:h,models:g??a})}};var Hl=new $e,un=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(Hl.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 pr=(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))(pr||{});var Ms=[{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 Kl=()=>structuredClone({model:"llama-3.3-70b-versatile",...ie()}),pn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Groq API key not set");let o={...Kl(),...t},a={...n,streamingUsage:!1};s=[...Ms,...s??[]];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:o,options:a,modelInfo:s,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 un(t,t/60,{debug:e?.debug});return async(s,o)=>{let a=o.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await s()}}};var Ps=[];var Es=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Es||{});var Hi=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ie()}),Wl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),Fs=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:
167
+ `;break}default:r=JSON.stringify(n,null,2)}i(r)}};var Q={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"},lt={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"},ei=(r=>(r.COMPLETION="completion",r.CHAT="chat",r.RERANK="rerank",r.UNKNOWN="unknown",r))(ei||{}),ti=(s=>(s.WORKFLOW="workflow",s.TASK="task",s.AGENT="agent",s.TOOL="tool",s.UNKNOWN="unknown",s))(ti||{});var is=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()}},Zn=class extends TransformStream{constructor(e,t){super(new is(e,t))}};function er(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 ni=(i,e,t,n)=>{let r=n?i.filter(o=>o.role!=="system"):[...i];t({name:"ChatRequestChatPrompt",step:e,value:r})};var ri=(i,e)=>{if(!i.results)return;let t={name:"ChatResponseResults",value:i.results};e(t)};function si(i,e){let t=new Map;for(let n of i)for(let r of n.results){if(!r)continue;let s=t.get(r.index);s?(r.content&&(s.content=(s.content??"")+r.content),r.thought&&(s.thought=(s.thought??"")+r.thought),r.finishReason&&(s.finishReason=r.finishReason),r.functionCalls&&(s.functionCalls?er(s.functionCalls,structuredClone(r.functionCalls)):s.functionCalls=structuredClone(r.functionCalls))):(s=structuredClone(r),t.set(r.index,s))}for(let n of t.values()){let r={name:"ChatResponseStreamingDoneResult",index:n.index,value:n};e(r)}}var oi=(i,e)=>{e({name:"FunctionResults",value:i})},as=(i,e,t,n)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:i})},ii=(i,e,t,n)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:i})},ai=(i,e,t,n)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:i})},li=(i,e,t)=>{t({name:"RefusalError",index:e,error:i})};var ci=(i,e,t)=>{t({name:"EmbedRequest",embedModel:e,value:i})},ui=(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)},pi=(i,e,t,n)=>{n({name:"ResultPickerUsed",sampleCount:i,selectedIndex:e,latency:t})};var nr=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},wt=(...i)=>{let e={};for(let t of i)t&&Object.assign(e,t);return e},tr,di=i=>{if(tr)return tr;if(i)return tr=Il(i),tr};var Il=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)"}),cacheReadTokensCounter:i.createCounter("ax_llm_cache_read_tokens_total",{description:"Total number of tokens read from cache (prompt caching)"}),cacheWriteTokensCounter:i.createCounter("ax_llm_cache_write_tokens_total",{description:"Total number of tokens written to cache (prompt caching)"})}),mi=(i,e,t,n,r,s)=>{try{if(i.latencyHistogram){let o=nr({operation:e,ai_service:n,...r?{model:r}:{},...s});i.latencyHistogram.record(t,o)}}catch(o){console.warn("Failed to record latency metric:",o)}},gi=(i,e,t,n,r,s,o,a)=>{let l={operation:e,ai_service:s,...o?{model:o}:{},...a};i.meanLatencyGauge&&i.meanLatencyGauge.record(t,l),i.p95LatencyGauge&&i.p95LatencyGauge.record(n,l),i.p99LatencyGauge&&i.p99LatencyGauge.record(r,l)},hi=(i,e,t,n,r)=>{try{if(i.errorCounter){let s=nr({operation:e,ai_service:t,...n?{model:n}:{},...r});i.errorCounter.add(1,s)}}catch(s){console.warn("Failed to record error metric:",s)}},fi=(i,e,t,n,r,s)=>{i.errorRateGauge&&i.errorRateGauge.record(t*100,{operation:e,ai_service:n,...r?{model:r}:{},...s})},xi=(i,e,t,n,r)=>{i.requestCounter&&i.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Zt=(i,e,t,n,r,s)=>{try{let o=nr({ai_service:n,...r?{model:r}:{},...s});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)}},Ai=(i,e,t,n,r,s)=>{t&&i.streamingRequestsCounter&&i.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...r?{model:r}:{},...s})},yi=(i,e,t,n,r,s)=>{let o={function_name:e,...n?{ai_service:n}:{},...r?{model:r}:{},...s};i.functionCallsCounter&&i.functionCallsCounter.add(1,o),t&&i.functionCallLatencyHistogram&&i.functionCallLatencyHistogram.record(t,o)},ls=(i,e,t,n,r,s)=>{i.requestSizeHistogram&&i.requestSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},cs=(i,e,t,n,r,s)=>{i.responseSizeHistogram&&i.responseSizeHistogram.record(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},bi=(i,e,t,n,r,s)=>{let o={...n?{ai_service:n}:{},...r?{model:r}:{},...s};e!==void 0&&i.temperatureGauge&&i.temperatureGauge.record(e,o),t!==void 0&&i.maxTokensGauge&&i.maxTokensGauge.record(t,o)},us=(i,e,t,n,r,s)=>{i.estimatedCostCounter&&i.estimatedCostCounter.add(t,{operation:e,ai_service:n,...r?{model:r}:{},...s})},Ii=(i,e,t,n,r)=>{i.promptLengthHistogram&&i.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ti=(i,e,t,n,r)=>{i.contextWindowUsageGauge&&i.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{},...r})},Ci=(i,e,t,n,r)=>{i.timeoutsCounter&&i.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},Ri=(i,e,t,n,r)=>{i.abortsCounter&&i.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{},...r})},wi=(i,e,t,n,r)=>{i.thinkingBudgetUsageCounter&&i.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{},...r})},vi=(i,e,t,n,r,s)=>{(e||t)&&i.multimodalRequestsCounter&&i.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...r?{model:r}:{},...s})},ps=(i,e,t,n,r,s)=>{try{if(t<=0)return;let o=nr({ai_service:n,...r?{model:r}:{},...s});e==="read"&&i.cacheReadTokensCounter&&i.cacheReadTokensCounter.add(t,o),e==="write"&&i.cacheWriteTokensCounter&&i.cacheWriteTokensCounter.add(t,o)}catch(o){console.warn("Failed to record cache token metric:",o)}};function Si(i){try{return JSON.stringify(i,null,2)}catch{return String(i)}}function tt(i,e={}){let t=[i];throw e.fieldPath!==void 0&&t.push(`Field: ${e.fieldPath}`),e.value!==void 0&&t.push(`Value: ${Si(e.value)}`),e.note&&t.push(`Note: ${e.note}`),e.item!==void 0&&t.push(`Chat item: ${Si(e.item)}`),new Error(t.join(`
168
+ `))}function en(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 s=n[r];if(!s||typeof s!="object")throw new Error(`User message content item at index ${r} must be an object, received: ${e(s)}`);let o=typeof s=="object"&&s!==null&&"type"in s&&typeof s.type=="string"?s.type:void 0;if(!o)throw new Error(`User message content item at index ${r} must have a type, received: ${e(o)}`);switch(o){case"text":{let a="text"in s&&typeof s.text=="string"?s.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 s&&typeof s.image=="string"?s.image:void 0,l="mimeType"in s&&typeof s.mimeType=="string"?s.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 s&&typeof s.data=="string"?s.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 s&&typeof s.fileUri=="string",l="data"in s&&typeof s.data=="string";if(!a&&!l)throw new Error(`User message file content at index ${r} must have either 'data' or 'fileUri', received: ${e(s)}`);if(a&&l)throw new Error(`User message file content at index ${r} cannot have both 'data' and 'fileUri', received: ${e(s)}`);if(a){let u=s.fileUri;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} fileUri cannot be empty, received: ${e(u)}`)}if(l){let u=s.data;if(!u||u.trim()==="")throw new Error(`User message file content at index ${r} data cannot be empty, received: ${e(u)}`)}let c="mimeType"in s&&typeof s.mimeType=="string"?s.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 s&&typeof s.url=="string"?s.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(o)}`)}}}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,s=typeof i=="object"&&i!==null&&"thoughtBlocks"in i?i.thoughtBlocks:void 0,o=typeof n=="string"&&n.trim()!=="",a=Array.isArray(r)&&r.length>0,l=Array.isArray(s)&&s.length>0;if(!o&&!a&&!l&&tt("Assistant message must include non-empty content, at least one function call, or thought blocks",{fieldPath:"content | functionCalls | thoughtBlocks",value:{content:n,functionCalls:r,thoughtBlocks:s},item:i}),n!==void 0&&typeof n!="string"&&tt("Assistant message content must be a string",{fieldPath:"content",value:n,item:i}),r!==void 0&&!Array.isArray(r)&&tt("Assistant message functionCalls must be an array when provided",{fieldPath:"functionCalls",value:r,item:i}),Array.isArray(r))for(let c=0;c<r.length;c++){let u=r[c];if((!u||typeof u!="object")&&tt("functionCalls entry must be an object",{fieldPath:`functionCalls[${c}]`,value:u,item:i}),(!("id"in u)||typeof u.id!="string"||u.id.trim()==="")&&tt("functionCalls entry must include a non-empty string id",{fieldPath:`functionCalls[${c}].id`,value:u.id,item:i}),(!("type"in u)||u.type!=="function")&&tt("functionCalls entry must have type 'function'",{fieldPath:`functionCalls[${c}].type`,value:u.type,item:i}),!("function"in u)||!u.function)tt("functionCalls entry must include a function object",{fieldPath:`functionCalls[${c}].function`,value:u.function,item:i});else{let p=u.function;(!("name"in p)||typeof p.name!="string"||p.name.trim()==="")&&tt("functionCalls entry must include a non-empty function name",{fieldPath:`functionCalls[${c}].function.name`,value:p?.name,item:i}),p.params!==void 0&&typeof p.params!="string"&&typeof p.params!="object"&&tt("functionCalls entry params must be a string or object when provided",{fieldPath:`functionCalls[${c}].function.params`,value:p.params,item:i})}}if(i.name!==void 0){let c=i.name;(typeof c!="string"||c.trim()==="")&&tt("Assistant message name must be a non-empty string when provided",{fieldPath:"name",value:c,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"&&tt("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 ds(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.thoughtBlocks||r.thoughtBlocks.length===0)&&!r.functionCalls&&!r.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, thoughtBlocks, functionCalls, or finishReason, received: ${e({content:r.content,thought:r.thought,thoughtBlocks:r.thoughtBlocks,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.thoughtBlocks!==void 0){if(!Array.isArray(r.thoughtBlocks))throw new Error(`Chat response result thoughtBlocks at index ${n} must be an array, received: ${e(r.thoughtBlocks)}`);for(let s=0;s<r.thoughtBlocks.length;s++){let o=r.thoughtBlocks[s];if(typeof o!="object"||o===null)throw new Error(`Chat response result thoughtBlocks[${s}] at index ${n} must be an object, received: ${e(o)}`);if(typeof o.data!="string")throw new Error(`Chat response result thoughtBlocks[${s}].data at index ${n} must be a string, received: ${e(o.data)}`);if(typeof o.encrypted!="boolean")throw new Error(`Chat response result thoughtBlocks[${s}].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 thoughtBlocks[${s}].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 s=0;s<r.annotations.length;s++){let o=r.annotations[s];if(!o||typeof o!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must be an object, received: ${e(o)}`);if(o.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${s}] must have type 'url_citation', received: ${e(o.type)}`);if(!o.url_citation||typeof o.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${s}] must have a valid url_citation object, received: ${e(o.url_citation)}`);if(typeof o.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${s}] url_citation.url must be a string, received: ${e(o.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 s=0;s<r.functionCalls.length;s++){let o=r.functionCalls[s];if(!o)throw new Error(`Function call at index ${s} in result ${n} cannot be null or undefined, received: ${e(o)}`);if(!o.id||typeof o.id!="string"||o.id.trim()==="")throw new Error(`Function call at index ${s} in result ${n} must have a non-empty string id, received: ${e(o.id)}`);if(o.type!=="function")throw new Error(`Function call at index ${s} in result ${n} must have type 'function', received: ${e(o.type)}`);if(!o.function)throw new Error(`Function call at index ${s} in result ${n} must have a function object, received: ${e(o.function)}`);if(!o.function.name||typeof o.function.name!="string"||o.function.name.trim()==="")throw new Error(`Function call at index ${s} in result ${n} must have a non-empty function name, received: ${e(o.function.name)}`);if(o.function.params!==void 0&&typeof o.function.params!="string"&&typeof o.function.params!="object")throw new Error(`Function call params at index ${s} in result ${n} must be a string or object, received: ${e(o.function.params)}`)}}if(r.finishReason!==void 0){let s=["stop","length","function_call","content_filter","error"];if(!s.includes(r.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${s.join(", ")}, received: ${e(r.finishReason)}`)}}}var ms=new Map;function Tl(i){return`${i.providerName}:${i.contentHash}`}function Cl(i,e){e.type==="text"?i.update(`text:${e.text}`):e.type==="image"?i.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?i.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?i.update(`file:${e.mimeType}:${e.fileUri}`):i.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Rl(i){let e=Ne("sha256"),t=-1;for(let n=i.length-1;n>=0;n--){let r=i[n];if("cache"in r&&r.cache){t=n;break}}for(let n=0;n<i.length;n++){let r=i[n];if(r.role==="system"){e.update(`system:${r.content}`);continue}if(t>=0&&n<=t)if(r.role==="user"){if(typeof r.content=="string")e.update(`user:${r.content}`);else if(Array.isArray(r.content))for(let s of r.content)Cl(e,s)}else r.role==="assistant"&&r.content&&e.update(`assistant:${r.content}`)}return e.digest("hex")}var ie=()=>structuredClone({temperature:0}),Se=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Ce=class{constructor(e,{name:t,apiURL:n,headers:r,modelInfo:s,defaults:o,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??Z.tracer,this.meter=a.meter??Z.meter,this.modelInfo=s,this.models=c,this.id=Me();let u=this.getModel(o.model)??o.model,p=this.getEmbedModel(o.embedModel)??o.embedModel;if(this.defaults={model:u,embedModel:p},!o.model||typeof o.model!="string"||o.model==="")throw new Error("No model defined");this.setOptions(a),c&&wl(c)}#e=!1;#t=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger=Z.logger??Zo;corsProxy;retry;customLabels;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 di(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??Z.debug??!1,this.#t=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer??Z.tracer,this.meter=e.meter??Z.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger??Z.logger??this.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels}getOptions(){return{debug:this.#e,verbose:this.#t,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,retry:this.retry,customLabels:this.customLabels}}getLogger(){return this.logger}getMergedCustomLabels(e){return wt(Z.customLabels,this.customLabels,e)}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((s,o)=>s-o),r=Math.ceil(t/100*n.length)-1;return n[r]??0}updateLatencyMetrics(e,t,n){let r=this.metrics.latency[e];r.samples.push(t),r.samples.length>1e3&&r.samples.shift(),r.mean=r.samples.reduce((o,a)=>o+a,0)/r.samples.length,r.p95=this.calculatePercentile(r.samples,95),r.p99=this.calculatePercentile(r.samples,99);let s=this.getMetricsInstruments();if(s){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);mi(s,e,t,this.name,o,a),gi(s,e,r.mean,r.p95,r.p99,this.name,o,a)}}updateErrorMetrics(e,t,n){let r=this.metrics.errors[e];r.total++,t&&r.count++,r.rate=r.count/r.total;let s=this.getMetricsInstruments();if(s){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n);xi(s,e,this.name,o,a),t&&hi(s,e,this.name,o,a),fi(s,e,r.rate,this.name,o,a)}}recordTokenUsage(e,t){let n=this.getMetricsInstruments();if(n&&e?.tokens){let{promptTokens:r,completionTokens:s,totalTokens:o,thoughtsTokens:a,cacheReadTokens:l,cacheCreationTokens:c}=e.tokens,u=this.getMergedCustomLabels(t);r&&Zt(n,"input",r,this.name,e.model,u),s&&Zt(n,"output",s,this.name,e.model,u),o&&Zt(n,"total",o,this.name,e.model,u),a&&Zt(n,"thoughts",a,this.name,e.model,u),l&&ps(n,"read",l,this.name,e.model,u),c&&ps(n,"write",c,this.name,e.model,u)}}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 s of r.content)s.type==="image"?t=!0:s.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:s=0}=t.tokens,o=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*o/1e6+s*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:s=0}=t.tokens,o=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return r*o/1e6+s*a/1e6}recordFunctionCallMetrics(e,t,n){let r=this.getMetricsInstruments();if(!(!r||!e))for(let s of e)s&&typeof s=="object"&&"function"in s&&s.function&&typeof s.function=="object"&&"name"in s.function&&yi(r,s.function.name,void 0,this.name,t,this.getMergedCustomLabels(n))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ci(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments();if(n){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Ri(n,e,this.name,r,this.getMergedCustomLabels(t))}}recordChatMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedChatModel,o=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),l=o?.stream??!1;Ai(r,"chat",l,this.name,s,a);let{hasImages:c,hasAudio:u}=this.detectMultimodalContent(e);vi(r,c,u,this.name,s,a);let p=this.calculatePromptLength(e);Ii(r,p,this.name,s,a),bi(r,o?.temperature,o?.maxTokens,this.name,s,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&wi(r,this.modelUsage.tokens.thoughtsTokens,this.name,s,a);let d=this.calculateRequestSize(e);if(ls(r,"chat",d,this.name,s,a),n&&!l){let m=n,h=this.calculateResponseSize(m);if(cs(r,"chat",h,this.name,s,a),m.results)for(let y of m.results)y.functionCalls&&this.recordFunctionCallMetrics(y.functionCalls,this.lastUsedChatModel,a);let g=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);g>0&&Ti(r,g,this.name,s,a);let f=this.estimateCost(this.lastUsedChatModel,m.modelUsage);f>0&&us(r,"chat",f,this.name,s,a)}}recordEmbedMetrics(e,t,n){let r=this.getMetricsInstruments();if(!r)return;let s=this.lastUsedEmbedModel,o=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);ls(r,"embed",a,this.name,s,o);let l=this.calculateResponseSize(t);cs(r,"embed",l,this.name,s,o);let c=this.estimateCostByName(s,t.modelUsage);c>0&&us(r,"embed",c,this.name,s,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),r=!1,s,o=this.getModelByKey(e.model),a=o?o.thinkingTokenBudget:void 0,l={...o?{thinkingTokenBudget:a,showThoughts:o.showThoughts,stream:o.stream,debug:o.debug,useExpensiveModel:o.useExpensiveModel}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,c])=>c!==void 0))};try{return s=await this._chat1(e,l),s}catch(c){throw r=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("chat",l?.customLabels):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("chat",l?.customLabels)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("chat",c,l?.customLabels),this.updateErrorMetrics("chat",r,l?.customLabels),r||this.recordChatMetrics(e,l,s)}}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)en(c);let r=this.getModelByKey(e.model),s={...this.aiImpl.getModelConfig(),...r?r.modelConfig:void 0,...e.modelConfig},o=this.modelInfo.find(c=>c.name===n);if(o?.notSupported?.temperature&&"temperature"in s&&delete s.temperature,o?.notSupported?.topP&&"topP"in s&&delete s.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 s.stream=(t?.stream!==void 0?t.stream:s.stream)??!0,this.getFeatures(n).streaming||(s.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:Oi.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"chat",[Q.LLM_REQUEST_MODEL]:n,[Q.LLM_REQUEST_MAX_TOKENS]:s.maxTokens??"Not set",[Q.LLM_REQUEST_TEMPERATURE]:s.temperature,[Q.LLM_REQUEST_TOP_P]:s.topP??"Not set",[Q.LLM_REQUEST_TOP_K]:s.topK??"Not set",[Q.LLM_REQUEST_FREQUENCY_PENALTY]:s.frequencyPenalty??"Not set",[Q.LLM_REQUEST_PRESENCE_PENALTY]:s.presencePenalty??"Not set",[Q.LLM_REQUEST_STOP_SEQUENCES]:s.stopSequences?.join(", ")??"Not set",[Q.LLM_REQUEST_LLM_IS_STREAMING]:s.stream??"Not set"}},t?.traceContext??ki.active(),async c=>await this._chat2(n,s,e,t,c)):await this._chat2(n,s,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,s){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let o=r?.debug??this.#e,a=r?.verbose??this.#t,l;n.functions&&n.functions.length>0&&(l=n.functions.map(b=>this.cleanupFunctionSchema(b)));let c={...n,model:e,functions:l,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,o&&ni(c.chatPrompt,r?.stepIndex??0,r?.logger??this.logger,r?.debugHideSystemPrompt);let u=this.getFeatures(e).functions,p=r?.functionCallMode??"auto",m=p==="prompt"||p==="auto"&&!u?{...c,chatPrompt:c.chatPrompt.map(b=>{if(b.role==="assistant"){let{content:T,name:A,cache:I}=b;return{role:"assistant",content:T,name:A,cache:I}}return b.role==="function"?{role:"user",content:b.result}:b}),functions:[]}:c,h=await this.handleContextCaching(e,m,r,s),g=async()=>{if(h?.preparedRequest){let{apiConfig:I,request:C}=h.preparedRequest;return s?.isRecording()&&Mi(n,s,this.excludeContentFromTrace),await Ee({name:I.name,url:this.apiURL,localCall:I.localCall,headers:await this.buildHeaders(I.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},C)}let[b,T]=await this.aiImpl.createChatReq(m,r);return s?.isRecording()&&Mi(n,s,this.excludeContentFromTrace),await Ee({name:b.name,url:this.apiURL,localCall:b.localCall,headers:await this.buildHeaders(b.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:s,abortSignal:r?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:r?.retry??this.retry},T)},f=r?.rateLimiter??this.rt,y=f?await f(g,{modelUsage:this.modelUsage}):await g();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let b=this.aiImpl.createChatStreamResp.bind(this),T=S=>R=>{let P=b(R,S);if(P.sessionId=r?.sessionId,!P.modelUsage){let E=this.aiImpl.getTokenUsage();E&&(P.modelUsage={ai:this.name,model:e,tokens:E})}return this.modelUsage=P.modelUsage,this.recordTokenUsage(P.modelUsage,r?.customLabels),s?.isRecording()&&Pi(P,s,this.excludeContentFromTrace),P},A=async S=>{s?.isRecording()&&s.end(),o&&si(S,r?.logger??this.logger)};if(typeof window<"u"){let S=y,R={},P=[],E=r?.abortSignal??this.abortSignal;return new ReadableStream({start:w=>{let v=S.getReader(),k=()=>{try{v.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",r?.customLabels)}catch{}try{s?.isRecording()&&s.end()}catch{}try{w.error(new DOMException("Aborted","AbortError"))}catch{w.error(new Error("Aborted"))}};if(E){if(E.aborted){k();return}E.addEventListener("abort",k,{once:!0})}async function O(){try{for(;;){let{done:N,value:M}=await v.read();if(N){A&&await A(P),w.close();break}let D=T(R)(M);D&&(P.push(D),w.enqueue(D))}}catch(N){if(w.error(N),s?.isRecording())try{s.end()}catch{}}finally{if(v.releaseLock(),E)try{E.removeEventListener("abort",k)}catch{}}}O()}})}return y.pipeThrough(new Zn(T({}),A))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");let x=this.aiImpl.createChatResp(y);if(x.sessionId=r?.sessionId,!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}return x.modelUsage&&(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage,r?.customLabels)),s?.isRecording()&&(Pi(x,s,this.excludeContentFromTrace),s.end()),o&&ri(x,r?.logger??this.logger),x}async embed(e,t){let n=performance.now(),r=!1,s,o=this.getModelByKey(e.embedModel),a={...o?{thinkingTokenBudget:o.thinkingTokenBudget,showThoughts:o.showThoughts,stream:o.stream,debug:o.debug,useExpensiveModel:o.useExpensiveModel}:void 0,...t};try{return s=await this._embed1(e,a),s}catch(l){throw r=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("embed",a?.customLabels):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("embed",a?.customLabels)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("embed",l,a?.customLabels),this.updateErrorMetrics("embed",r,a?.customLabels),!r&&s&&this.recordEmbedMetrics(e,s,a)}}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:Oi.SERVER,attributes:{[Q.LLM_SYSTEM]:this.name,[Q.LLM_OPERATION_NAME]:"embeddings",[Q.LLM_REQUEST_MODEL]:n}},t?.traceContext??ki.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 s=this.aiImpl.createEmbedReq.bind(this.aiImpl),o=n?.debug??this.#e,a=n?.verbose??this.#t,l={...t,embedModel:e};this.lastUsedEmbedModel=e,o&&ci(l.texts??[],e,n?.logger??this.logger);let c=async()=>{let[m,h]=await s(l);return await Ee({name:m.name,url:this.apiURL,localCall:m.localCall,headers:await this.buildHeaders(m.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:r,abortSignal:n?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:n?.retry??this.retry},h)},u=n?.rateLimiter??this.rt,p=u?await u(c,{modelUsage:this.embedModelUsage}):await c(),d=this.aiImpl.createEmbedResp?.(p);if(d.sessionId=n?.sessionId,!d.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(d.modelUsage={ai:this.name,model:e,tokens:m})}return this.embedModelUsage=d.modelUsage,this.recordTokenUsage(d.modelUsage,n?.customLabels),r?.isRecording()&&d.modelUsage?.tokens&&r.addEvent(lt.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:d.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:d.modelUsage.tokens.completionTokens??0,[Q.LLM_USAGE_TOTAL_TOKENS]:d.modelUsage.tokens.totalTokens}),o&&ui(d.embeddings,n?.logger??this.logger),r?.end(),d}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}async handleContextCaching(e,t,n,r){let s=n?.contextCache;if(!s)return null;let o=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!o&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!o)return null;let l=s.ttlSeconds??3600,c=s.refreshWindowSeconds??300,u=s.minTokens??2048;if(s.name)return this.useCacheByName(e,t,s.name,n,r);let p=Rl(t.chatPrompt);if(!p||p===Ne("sha256").digest("hex"))return null;let d={providerName:this.getName(),contentHash:p},m=Tl(d),h=Date.now(),g=s.registry,f=g?await g.get(m):ms.get(m);if(f&&f.expiresAt>h){if(f.expiresAt-h<c*1e3&&this.aiImpl.buildCacheUpdateTTLOp){await this.executeCacheOperation(this.aiImpl.buildCacheUpdateTTLOp(f.cacheName,l),n,r);let T={cacheName:f.cacheName,expiresAt:h+l*1e3,tokenCount:f.tokenCount};g?await g.set(m,T):ms.set(m,{...T,contentHash:p,lastTouchedAt:h})}return this.useCacheByName(e,t,f.cacheName,n,r)}if(this.estimateCacheableTokens(t.chatPrompt)<u)return null;let x=this.aiImpl.buildCacheCreateOp?.(t,n);if(x){let b=await this.executeCacheOperation(x,n,r);if(b){let T={cacheName:b.name,expiresAt:new Date(b.expiresAt).getTime(),tokenCount:b.tokenCount};return g?await g.set(m,T):ms.set(m,{...T,contentHash:p,lastTouchedAt:h}),this.useCacheByName(e,t,b.name,n,r)}}return null}async useCacheByName(e,t,n,r,s){if(this.aiImpl.prepareCachedChatReq){let o=await this.aiImpl.prepareCachedChatReq(t,r??{},n);return{preparedRequest:{apiConfig:o.apiConfig,request:o.request}}}return null}async executeCacheOperation(e,t,n){let r=t?.verbose??this.#t;try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let s=await Ee({name:e.apiConfig.name,url:this.apiURL,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:r,fetch:this.fetch,span:n,abortSignal:t?.abortSignal??this.abortSignal,corsProxy:this.corsProxy,retry:t?.retry??this.retry},e.request);return e.parseResponse(s)}catch(s){n?.addEvent("context_cache.error",{type:e.type,error:s instanceof Error?s.message:String(s)});return}}estimateCacheableTokens(e){let t=0;for(let n of e){if(n.role==="system"){t+=n.content.length;continue}if("cache"in n&&n.cache)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)"cache"in r&&r.cache&&(r.type==="text"?t+=r.text.length:r.type==="image"?t+=1e3:r.type==="audio"?t+=2e3:r.type==="file"&&(t+=500))}else n.role==="assistant"&&n.content&&(t+=n.content.length)}return Math.ceil(t/4)}};function Mi(i,e,t){let n=[];if(i.chatPrompt&&Array.isArray(i.chatPrompt)&&i.chatPrompt.length>0)for(let s of i.chatPrompt)switch(s.role){case"system":if(s.content){let o={};t||(o.content=s.content),e.addEvent(lt.GEN_AI_SYSTEM_MESSAGE,o)}break;case"user":if(typeof s.content=="string")n.push(s.content);else if(Array.isArray(s.content))for(let o of s.content)o.type==="text"&&n.push(o.text);break;case"assistant":{let o=s.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(o&&o.length>0){let a={function_calls:JSON.stringify(o,null,2)};!t&&s.content&&(a.content=s.content),e.addEvent(lt.GEN_AI_ASSISTANT_MESSAGE,a)}else if(s.content){let a={};t||(a.content=s.content),e.addEvent(lt.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let o={id:s.functionId};t||(o.content=s.result),e.addEvent(lt.GEN_AI_TOOL_MESSAGE,o);break}}let r={};t||(r.content=n.join(`
169
+ `)),e.addEvent(lt.GEN_AI_USER_MESSAGE,r)}function Pi(i,e,t){if(i.modelUsage?.tokens){let n=i.modelUsage.tokens.thoughtsTokens?{[Q.LLM_USAGE_THOUGHTS_TOKENS]:i.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(lt.GEN_AI_USAGE,{[Q.LLM_USAGE_INPUT_TOKENS]:i.modelUsage.tokens.promptTokens,[Q.LLM_USAGE_OUTPUT_TOKENS]:i.modelUsage.tokens.completionTokens??0,[Q.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 s=r.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),o={};s&&s.length>0?(t||(o.content=r.content),o.tool_calls=s):t||(o.content=r.content??""),e.addEvent(lt.GEN_AI_CHOICE,{finish_reason:r.finishReason,index:n,message:JSON.stringify(o,null,2)})}}function Ei(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 wl(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 rr=(g=>(g.Claude46Opus="claude-opus-4-6",g.Claude45Opus="claude-opus-4-5-20251101",g.Claude41Opus="claude-opus-4-1-20250805",g.Claude4Opus="claude-opus-4-20250514",g.Claude4Sonnet="claude-sonnet-4-20250514",g.Claude45Sonnet="claude-sonnet-4-5-20250929",g.Claude45Haiku="claude-haiku-4-5",g.Claude37Sonnet="claude-3-7-sonnet-latest",g.Claude35Sonnet="claude-3-5-sonnet-latest",g.Claude35Haiku="claude-3-5-haiku-latest",g.Claude3Opus="claude-3-opus-latest",g.Claude3Sonnet="claude-3-sonnet-20240229",g.Claude3Haiku="claude-3-haiku-20240307",g.Claude21="claude-2.1",g.ClaudeInstant12="claude-instant-1.2",g))(rr||{}),sr=(m=>(m.Claude46Opus="claude-opus-4-6@20260205",m.Claude45Opus="claude-opus-4-5@20251101",m.Claude41Opus="claude-opus-4-1@20250805",m.Claude4Opus="claude-opus-4@20250514",m.Claude45Sonnet="claude-sonnet-4-5@20250929",m.Claude4Sonnet="claude-sonnet-4@20250514",m.Claude37Sonnet="claude-3-7-sonnet@20250219",m.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",m.Claude45Haiku="claude-haiku-4-5@20251001",m.Claude35Haiku="claude-3-5-haiku@20241022",m.Claude35Sonnet="claude-3-5-sonnet@20240620",m.Claude3Opus="claude-3-opus@20240229",m.Claude3Haiku="claude-3-haiku@20240307",m))(sr||{});var or=[{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6@20260205",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:128e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,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 Tt=i=>{if(!i||typeof i!="object")return i;let e={...i};if(e.type==="object"||Array.isArray(e.type)&&e.type.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)throw new Error("Anthropic models do not support arbitrary JSON objects (e.g. f.json() or f.object() with no properties) in structured outputs. Please use f.string() and instruct the model to return a JSON string, or define the expected structure with f.object({ ... })");e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([n,r])=>[n,Tt(r)]))),e.items&&(e.items=Tt(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(n=>Tt(n))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(n=>Tt(n))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(n=>Tt(n))),e},_i=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...ie()}),vl=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...ie()}),gs=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;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,s;this.isVertex?s={name:r?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={name:"/messages"};let o;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":o={tool_choice:{type:"auto"}};break;case"required":o={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)o={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.some(O=>"cache"in O&&O.cache)||e.functions?.some(O=>O.cache),l=e.chatPrompt.filter(O=>O.role==="system"),c=l.map((O,N)=>({type:"text",text:O.content,...O.cache||a&&N===l.length-1?{cache_control:{type:"ephemeral"}}:{}})),u=e.chatPrompt.filter(O=>O.role!=="system"),p=e.functions?.map((O,N,M)=>{let D={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},F=O.parameters?Tt(O.parameters):void 0;return F===void 0||F&&typeof F=="object"&&Object.keys(F).length===0?F={...D}:F&&typeof F=="object"&&F.type==="object"&&(!("properties"in F)||!F.properties||Object.keys(F.properties).length===0)&&(F={...F,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:O.name,description:O.description,input_schema:F,...O.cache||a&&N===M.length-1?{cache_control:{type:"ephemeral"}}:{}}}),m=(this.config.tools??[]).map(O=>O&&typeof O=="object"&&"type"in O?O:{name:O.name,description:O.description,input_schema:O.input_schema?Tt(O.input_schema):void 0,...O.cache_control?{cache_control:O.cache_control}:{}}),h=[...p??[],...m];h.length===0&&(h=void 0);let g=e.modelConfig?.maxTokens??this.config.maxTokens,f=e.modelConfig?.stopSequences??this.config.stopSequences,y=e.modelConfig?.temperature,x=e.modelConfig?.topP,b=e.modelConfig?.topK??this.config.topK,T=e.modelConfig?.n??this.config.n;if(T&&T>1)throw new Error("Anthropic does not support sampling (n > 1)");let A=O=>O.includes("claude-opus-4-6"),I=O=>O.includes("claude-opus-4-5"),C,S,R=n;if(t?.thinkingTokenBudget){let O=this.config.thinkingTokenBudgetLevels,N=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")C=void 0,S=void 0;else{let M=t.thinkingTokenBudget;if(A(R))C={type:"adaptive"},S={effort:N?.[M]??"medium"};else if(I(R)){C={type:"enabled",budget_tokens:O?.[M]??1e4};let F=N?.[M]??"medium";F==="max"&&(F="high"),S={effort:F}}else C={type:"enabled",budget_tokens:O?.[M]??1e4}}}let E=Sl(u,!!C);E.some(O=>O.role==="assistant"&&Array.isArray(O.content)&&O.content.length>0&&O.content[0]?.type==="tool_use")&&(C=void 0,S=void 0);let v;if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let O=e.responseFormat.schema.schema||e.responseFormat.schema;v={type:"json_schema",schema:Tt(O)},this.usedStructuredOutput=!0}let k={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...g?{max_tokens:g}:{},...f&&f.length>0?{stop_sequences:f}:{},...y!==void 0&&!C?{temperature:y}:{},...x!==void 0&&(!C||x>=.95)?{top_p:x}:{},...b&&!C?{top_k:b}:{},...o,...h?{tools:h}:{},...r?{stream:!0}:{},...c?{system:c}:{},...C?{thinking:C}:{},...S?{output_config:S}:{},...v?{output_format:v}:{},messages:E};return[s,k]};createChatResp=e=>{if(e.type==="error")throw new ge(e.error.message,void 0,void 0);let t=Fi(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,r="",s=[],o=[],a=[];for(let u of e.content)switch(u.type){case"text":if(r+=u.text??"",Array.isArray(u.citations))for(let p of u.citations)p?.url&&a.push({url:String(p.url),title:typeof p.title=="string"?p.title:void 0,snippet:typeof p.cited_text=="string"?p.cited_text:void 0});break;case"thinking":if(n){let p=u.thinking??"",d=u.signature;o.push({data:p,encrypted:!1,...typeof d=="string"?{signature:d}:{}})}break;case"redacted_thinking":if(n){let p=u.data??"",d=u.signature;o.push({data:p,encrypted:!0,...typeof d=="string"?{signature:d}:{}})}break;case"tool_use":s.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let l={index:0,id:e.id,finishReason:t};r&&(l.content=r),o.length>0&&(l.thoughtBlocks=o,l.thought=o.map(u=>u.data).join("")),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+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_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:s}=e;throw new ge(s.message,void 0,void 0)}let r=0;if(e.type==="message_start"){let{message:s}=e,o=[{index:r,content:"",id:s.id}];return this.tokensUsed={promptTokens:s.usage?.input_tokens??0,completionTokens:s.usage?.output_tokens??0,totalTokens:(s.usage?.input_tokens??0)+(s.usage?.output_tokens??0)+(s.usage?.cache_creation_input_tokens??0)+(s.usage?.cache_read_input_tokens??0),cacheCreationTokens:s.usage?.cache_creation_input_tokens,cacheReadTokens:s.usage?.cache_read_input_tokens},{results:o}}if(e.type==="content_block_start"){let{content_block:s}=e;if(s.type==="text"){let o=[];if(Array.isArray(s.citations))for(let a of s.citations)a?.url&&o.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:s.text,...o.length?{citations:o}:{}}]}}if(s.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="tool_use"&&typeof s.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=s.id;let o=[{id:s.id,type:"function",function:{name:s.name,params:""}}];return{results:[{index:r,functionCalls:o}]}}if(s.type==="web_search_tool_result"||s.type==="server_tool_use")return{results:[{index:r,content:""}]}}if(e.type==="content_block_delta"){let{delta:s}=e;if(s.type==="citations_delta"){let o=s.citation;if(o&&typeof o.url=="string"&&o.url.length>0){let a=[{url:String(o.url),title:typeof o.title=="string"?o.title:void 0,snippet:typeof o.cited_text=="string"?o.cited_text:void 0}];return{results:[{index:r,content:"",citations:a}]}}return{results:[{index:r,content:""}]}}if(s.type==="text_delta"){let o=[];if(Array.isArray(s.citations))for(let a of s.citations)a?.url&&o.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:s.text,...o.length?{citations:o}:{}}]}}if(s.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:r,thought:s.thinking,thoughtBlocks:[{data:s.thinking,encrypted:!1}]}]}:{results:[{index:r,content:""}]};if(s.type==="signature_delta")return{results:[{index:r,thoughtBlocks:[{data:"",encrypted:!1,signature:s.signature}]}]};if(s.type==="input_json_delta"){let o=n.indexIdMap[e.index];if(!o)return{results:[{index:r,content:""}]};let a=[{id:o,type:"function",function:{name:"",params:s.partial_json}}];return{results:[{index:r,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:s,usage:o}=e;return this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:o.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+o.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens},{results:[{index:r,content:"",finishReason:Fi(s.stop_reason)}]}}return{results:[{index:r,content:""}]}};supportsImplicitCaching=()=>!0},tn=class i extends Ce{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,config:r,options:s,models:o}){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==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,c=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}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":"structured-outputs-2025-11-13, web-search-2025-03-05","x-api-key":typeof e=="function"?await e():e})}let u={..._i(),...r},p=new gs(u,a),d=h=>{let g=Ke({model:h,modelInfo:or,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,structuredOutputs:g?.supported?.structuredOutputs??!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"],cacheBreakpoints:!1},thinking:g?.supported?.thinkingBudget??!1,multiTurn:!0}},m=o?.map(h=>{let g=h,f=g?.config;if(!f)return h;let y={};f.maxTokens!==void 0&&(y.maxTokens=f.maxTokens),f.temperature!==void 0&&(y.temperature=f.temperature),f.topP!==void 0&&(y.topP=f.topP),f.topK!==void 0&&(y.topK=f.topK),f.presencePenalty!==void 0&&(y.presencePenalty=f.presencePenalty),f.frequencyPenalty!==void 0&&(y.frequencyPenalty=f.frequencyPenalty),f.stopSequences!==void 0&&(y.stopSequences=f.stopSequences),f.endSequences!==void 0&&(y.endSequences=f.endSequences),f.stream!==void 0&&(y.stream=f.stream),f.n!==void 0&&(y.n=f.n);let x={...g};Object.keys(y).length>0&&(x.modelConfig={...g.modelConfig??{},...y});let b=f.thinking?.thinkingTokenBudget;if(typeof b=="number"){let T=u.thinkingTokenBudgetLevels,A=[["minimal",T?.minimal??1024],["low",T?.low??5e3],["medium",T?.medium??1e4],["high",T?.high??2e4],["highest",T?.highest??32e3]],I="minimal",C=Number.POSITIVE_INFINITY;for(let[S,R]of A){let P=Math.abs(b-R);P<C&&(C=P,I=S)}x.thinkingTokenBudget=I}return f.thinking?.includeThoughts!==void 0&&(x.showThoughts=!!f.thinking.includeThoughts),x});super(p,{name:"Anthropic",apiURL:l,headers:c,modelInfo:or,defaults:{model:u.model},options:s,supportFor:d,models:m??o})}};function Sl(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,...r.cache?{cache_control:{type:"ephemeral"}}:{}}:{role:"user",content:r.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let s="",o=[],a=r.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let l of a)l.encrypted?o.push(l.signature?{type:"redacted_thinking",data:l.data,signature:l.signature}:{type:"redacted_thinking",data:l.data}):o.push(l.signature?{type:"thinking",thinking:l.data,signature:l.signature}:{type:"thinking",thinking:l.data});if(typeof r.content=="string"&&(o.length>0?s=[...o,{type:"text",text:r.content}]:s=r.content),typeof r.functionCalls<"u"&&(s=r.functionCalls.map(l=>{let c={};if(typeof l.function.params=="string"){let u=l.function.params;if(u.trim().length===0)c={};else try{c=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof l.function.params=="object"&&(c=l.function.params);return{type:"tool_use",id:l.id,name:l.function.name,input:c,...r.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(s)&&o.length>0&&(s=[...o,...s])),r.cache){if(typeof s=="string")s=[{type:"text",text:s,cache_control:{type:"ephemeral"}}];else if(Array.isArray(s)&&s.length>0){let l=s.length-1,c=s[l];c&&c.type==="text"&&(s[l]={...c,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:s}}default:throw new Error("Invalid role")}}),n=kl(t);return Ol(n)}function kl(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 Ol(i){return i.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function Fi(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 ir=(w=>(w.GPT4="gpt-4",w.GPT41="gpt-4.1",w.GPT41Mini="gpt-4.1-mini",w.GPT41Nano="gpt-4.1-nano",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.GPT5Pro="gpt-5-pro",w.GPT51="gpt-5.1",w.GPT51ChatLatest="gpt-5.1-chat-latest",w.GPT52="gpt-5.2",w.GPT52ChatLatest="gpt-5.2-chat-latest",w.GPT52Pro="gpt-5.2-pro",w.O1="o1",w.O1Mini="o1-mini",w.O3="o3",w.O3Mini="o3-mini",w.O4Mini="o4-mini",w))(ir||{}),nn=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(nn||{});var rn=(k=>(k.GPT4="gpt-4",k.GPT41="gpt-4.1",k.GPT41Mini="gpt-4.1-mini",k.GPT41Nano="gpt-4.1-nano",k.GPT4O="gpt-4o",k.GPT4OMini="gpt-4o-mini",k.GPT4ChatGPT4O="chatgpt-4o-latest",k.GPT4Turbo="gpt-4-turbo",k.GPT35Turbo="gpt-3.5-turbo",k.GPT35TurboInstruct="gpt-3.5-turbo-instruct",k.GPT35TextDavinci002="text-davinci-002",k.GPT3TextBabbage002="text-babbage-002",k.GPT3TextAda001="text-ada-001",k.GPT5="gpt-5",k.GPT5Nano="gpt-5-nano",k.GPT5Mini="gpt-5-mini",k.GPT5Chat="gpt-5-chat",k.GPT5Pro="gpt-5-pro",k.GPT51="gpt-5.1",k.GPT51ChatLatest="gpt-5.1-chat-latest",k.GPT52="gpt-5.2",k.GPT52ChatLatest="gpt-5.2-chat-latest",k.GPT52Pro="gpt-5.2-pro",k.O1Pro="o1-pro",k.O1="o1",k.O1Mini="o1-mini",k.O3Pro="o3-pro",k.O3="o3",k.O3Mini="o3-mini",k.O4Mini="o4-mini",k))(rn||{});var sn=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{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}],hs=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{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,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:12,completionTokenCostPer1M:36,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:60,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Ml=i=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(i)||e.includes(i)},Lt=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...ie()}),xs=()=>structuredClone({...Lt(),model:"gpt-5"}),As=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Se()}),ys=()=>({...Lt(),model:"gpt-5-nano"}),fs=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"},s=e.functions?.map(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}})),o=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=Pl(e),l=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,c=e.modelConfig?.stream??this.config.stream,u=this.config.store,p=Ml(n),d={model:n,messages:a,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...s?{tools:s}:{},...o?{tool_choice:o}:{},...p?{}:{...(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}}:{},...u?{store:u}:{},...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:s}=e;if(s)throw s;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 ge(a.message.refusal,e.model,e.id);let l=Ni(a.finish_reason),c=a.message.tool_calls?.map(({id:u,function:{arguments:p,name:d}})=>({id:u,type:"function",function:{name:d,params:p}}));return{index:a.index,id:`${a.index}`,content:a.message.content??void 0,thought:a.message.reasoning_content,citations:a.message.annotations?.filter(u=>u?.type==="url_citation"&&u.url_citation).map(u=>({url:u.url_citation?.url,title:u.url_citation?.title,description:u.url_citation?.description})),functionCalls:c,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:r,choices:s}=e;this.tokensUsed=r?{promptTokens:r.prompt_tokens,completionTokens:r.completion_tokens,totalTokens:r.total_tokens}:void 0;let o=t;return o.indexIdMap||(o.indexIdMap={}),{results:s.map(({index:l,delta:{content:c,role:u,refusal:p,tool_calls:d,reasoning_content:m,annotations:h},finish_reason:g})=>{if(p)throw new ge(p,void 0,n);let f=Ni(g),y=d?.map(({id:x,index:b,function:{name:T,arguments:A}})=>{typeof x=="string"&&typeof b=="number"&&!o.indexIdMap[b]&&(o.indexIdMap[b]=x);let I=o.indexIdMap[b];return I?{id:I,type:"function",function:{name:T,params:A}}:null}).filter(x=>x!==null);return{index:l,content:c??void 0,role:u,thought:m,citations:h?.filter(x=>x?.type==="url_citation"&&x.url_citation).map(x=>({url:x.url_citation?.url,title:x.url_citation?.title,description:x.url_citation?.description})),functionCalls:y,finishReason:f,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)}}},Ni=i=>{switch(i){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function Pl(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 Ie=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s,models:o,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let c=new fs(t,n?.streamingUsage??!0,a);super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:o})}},on=class extends Ie{constructor({apiKey:e,apiURL:t,config:n,options:r,models:s,modelInfo:o}){if(!e||e==="")throw new Error("OpenAI API key not set");o=[...sn,...o??[]];let a=c=>{let u=Ke({model:c,modelInfo:o,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.supported?.showThoughts??!1,structuredOutputs:u?.supported?.structuredOutputs??!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:u?.supported?.thinkingBudget??!1,multiTurn:!0}},l=s?.map(c=>{let u=c,p=u?.config;if(!p)return c;let d={};p.maxTokens!==void 0&&(d.maxTokens=p.maxTokens),p.temperature!==void 0&&(d.temperature=p.temperature),p.topP!==void 0&&(d.topP=p.topP),p.presencePenalty!==void 0&&(d.presencePenalty=p.presencePenalty),p.frequencyPenalty!==void 0&&(d.frequencyPenalty=p.frequencyPenalty);let m=p.stopSequences??p.stop;m!==void 0&&(d.stopSequences=m),p.n!==void 0&&(d.n=p.n),p.stream!==void 0&&(d.stream=p.stream);let h={...u};Object.keys(d).length>0&&(h.modelConfig={...u.modelConfig??{},...d});let g=p?.thinking?.thinkingTokenBudget;if(typeof g=="number"){let f=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],y="minimal",x=Number.POSITIVE_INFINITY;for(let[b,T]of f){let A=Math.abs(g-T);A<x&&(x=A,y=b)}h.thinkingTokenBudget=y}return p?.thinking?.includeThoughts!==void 0&&(h.showThoughts=!!p.thinking.includeThoughts),h});super({apiKey:e,apiURL:t,config:{...Lt(),...n},options:r,modelInfo:o,models:l??s,supportFor:a}),super.setName("OpenAI")}};var El=i=>{let e=i.trim();if(!e)return e;if(e.includes("api-version=")){let t=e.indexOf("api-version="),n=e.slice(t);return new URLSearchParams(n).get("api-version")??e}return e},Fl=i=>{let e=i.match(/^(\d{4}-\d{2}-\d{2})/);return e?e[1]>="2024-08-01":!1},Li=Lt,_l=As,Nl=ys,Ll=xs,an=class extends Ie{constructor({apiKey:e,resourceName:t,deploymentName:n,version:r="api-version=2024-02-15-preview",config:s,options:o,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={...Li(),...s},u=El(r),p=Fl(u);l=[...sn,...l??[]];let d=h=>{let g=Ke({model:h,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:g?.supported?.thinkingBudget??!1,hasShowThoughts:g?.supported?.showThoughts??!1,structuredOutputs:p&&(g?.supported?.structuredOutputs??!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:g?.supported?.thinkingBudget??!1,multiTurn:!0}};super({apiKey:e,config:c,options:o,models:a,modelInfo:l,supportFor:d});let m=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${u}`,m).href),super.setHeaders(async()=>({"api-key":e}))}};var bs=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.");$l(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(){for(let e of this.services){let t=e.getModelList();if(t)return t}}getNextService(e,t){let n=t+1,r=e[n];return r===void 0?{service:void 0,index:n}:{service:r,index:n}}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){let t={functions:!1,streaming:!1,thinking:!1,multiTurn:!1,structuredOutputs:!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:[]}};for(let n of this.services){let r=n.getFeatures(e);r.functions&&(t.functions=!0),r.streaming&&(t.streaming=!0),r.thinking&&(t.thinking=!0),r.multiTurn&&(t.multiTurn=!0),r.structuredOutputs&&(t.structuredOutputs=!0),r.functionCot&&(t.functionCot=!0),r.hasThinkingBudget&&(t.hasThinkingBudget=!0),r.hasShowThoughts&&(t.hasShowThoughts=!0),r.media.images.supported&&(t.media.images.supported=!0),t.media.images.formats=Array.from(new Set([...t.media.images.formats,...r.media.images.formats])),r.media.audio.supported&&(t.media.audio.supported=!0),t.media.audio.formats=Array.from(new Set([...t.media.audio.formats,...r.media.audio.formats])),r.media.files.supported&&(t.media.files.supported=!0),t.media.files.formats=Array.from(new Set([...t.media.files.formats,...r.media.files.formats])),r.media.files.uploadMethod!=="none"&&(t.media.files.uploadMethod=r.media.files.uploadMethod),r.media.urls.supported&&(t.media.urls.supported=!0),r.media.urls.webSearch&&(t.media.urls.webSearch=!0),r.media.urls.contextFetching&&(t.media.urls.contextFetching=!0),r.caching.supported&&(t.caching.supported=!0),t.caching.types=Array.from(new Set([...t.caching.types,...r.caching.types]))}return t}getMetrics(){let e={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}}},t=0,n=0,r=0,s=0;for(let o of this.services){let a=o.getMetrics();e.errors.chat.count+=a.errors.chat.count,e.errors.chat.total+=a.errors.chat.total,e.errors.embed.count+=a.errors.embed.count,e.errors.embed.total+=a.errors.embed.total;let l=a.latency.chat.samples.length;l>0&&(t+=a.latency.chat.mean*l,n+=l);let c=a.latency.embed.samples.length;c>0&&(r+=a.latency.embed.mean*c,s+=c)}e.errors.chat.total>0&&(e.errors.chat.rate=e.errors.chat.count/e.errors.chat.total),e.errors.embed.total>0&&(e.errors.embed.rate=e.errors.embed.count/e.errors.embed.total),n>0&&(e.latency.chat.mean=t/n),s>0&&(e.latency.embed.mean=r/s);for(let o of this.services){let a=o.getMetrics();e.latency.chat.p95=Math.max(e.latency.chat.p95,a.latency.chat.p95),e.latency.chat.p99=Math.max(e.latency.chat.p99,a.latency.chat.p99),e.latency.embed.p95=Math.max(e.latency.embed.p95,a.latency.embed.p95),e.latency.embed.p99=Math.max(e.latency.embed.p99,a.latency.embed.p99)}return e}canRetryService(e){let t=this.serviceFailures.get(e.getId());if(!t)return!0;let{retries:n,lastFailureTime:r}=t,s=Date.now()-r,o=Math.min(this.initialBackoffMs*2**n,this.maxBackoffMs);return s>=o}handleFailure(e,t){let r=(this.serviceFailures.get(e.getId())?.retries??0)+1;this.serviceFailures.set(e.getId(),{retries:r,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${e.getName()} failed (retry ${r}/${this.maxRetries})`,t)}handleSuccess(e){this.serviceFailures.delete(e.getId())}async chat(e,t){let n=e.responseFormat?.type==="json_schema",r=e.capabilities,s=r?.requiresImages,o=r?.requiresAudio,a=this.services,l=e.model;if((n||s||o)&&(a=this.services.filter(p=>{let d=p.getFeatures(l);return!(n&&!d.structuredOutputs||s&&!d.media.images.supported||o&&!d.media.audio.supported)}),a.length===0)){let p=[];throw n&&p.push("structured outputs"),s&&p.push("images"),o&&p.push("audio"),new Error(`No services available that support required capabilities: ${p.join(", ")}.`)}let c=0,u=a[c];if(!u)throw new Error("No matching AI services available for request.");for(this.currentService=u;;){if(!this.canRetryService(u)){let p=this.getNextService(a,c);if(!p.service)throw new Error(`All candidate services exhausted (tried ${a.length} service(s))`);u=p.service,c=p.index,this.currentService=u;continue}try{let p=await u.chat(e,t);return this.handleSuccess(u),p}catch(p){if(!(p instanceof Le))throw p;switch(p.constructor){case It:throw p;case Ue:{if(![408,429,500,502,503,504].includes(p.status))throw p;break}case Pe:break;case bt:break;case Ze:break;case We:break;default:throw p}if(this.handleFailure(u,p),(this.serviceFailures.get(u.getId())?.retries??0)>=this.maxRetries){let m=this.getNextService(a,c);if(this.debug&&console.warn(`AxBalancer: Switching to service ${m.service?.getName()??"none"}`,p),!m.service)throw p;u=m.service,c=m.index,this.currentService=u}}}}async embed(e,t){this.reset();let n=this.currentServiceIndex;for(;;){if(!this.canRetryService(this.currentService)){let r=this.getNextService(this.services,n);if(!r.service)throw new Error(`All services exhausted (tried ${this.services.length} service(s))`);this.currentService=r.service,n=r.index,this.currentServiceIndex=n;continue}try{let r=await this.currentService.embed(e,t);return this.handleSuccess(this.currentService),r}catch(r){if(!(r instanceof Le)||r instanceof Ue&&![408,429,500,502,503,504].includes(r.status)||r instanceof It)throw r;if(this.handleFailure(this.currentService,r),(this.serviceFailures.get(this.currentService.getId())?.retries??0)>=this.maxRetries){let o=this.getNextService(this.services,n);if(!o.service)throw r;this.currentService=o.service,n=o.index,this.currentServiceIndex=n}}}}setOptions(e){for(let t of this.services)t.setOptions(e);this.currentService.setOptions(e),this.debug=e.debug??this.debug}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}};function $l(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 s=i[r];if(!s)throw new Error(`Service at index ${r} is undefined`);let o=s.getModelList();if(!o)throw new Error(`Service at index ${r} (${s.getName()}) has no model list while another service does.`);let a=new Set(o.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${r} (${s.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${r} (${s.getName()}) has extra model "${l}"`)}}function $t(i){let e=!1,t=!1,n=!1,r=!1,s=!1,o=!1,a=!1,l=new Set,c=0;if(i.chatPrompt&&Array.isArray(i.chatPrompt))for(let u of i.chatPrompt){if(u.role==="user"&&Array.isArray(u.content))for(let p of u.content)switch(l.add(p.type),p.type){case"image":e=!0,p.cache&&(a=!0),c+=85;break;case"audio":t=!0,p.cache&&(a=!0),c+=p.duration||60;break;case"file":n=!0,p.cache&&(a=!0),c+=Math.ceil((p.extractedText?.length||1e3)/4);break;case"url":r=!0,p.cache&&(a=!0),c+=Math.ceil((p.cachedContent?.length||2e3)/4);break;case"text":p.cache&&(a=!0),c+=Math.ceil(p.text.length/4);break}else"content"in u&&typeof u.content=="string"&&(c+=Math.ceil(u.content.length/4));"cache"in u&&u.cache&&(a=!0)}return i.functions&&i.functions.length>0&&(s=!0),i.modelConfig?.stream===!0&&(o=!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:s,requiresStreaming:o,requiresCaching:a,contentTypes:l,estimatedTokens:c}}function $i(i,e){let t=i.getFeatures(),n=[],r=[],s=[];if(e.hasImages&&!t.media.images.supported&&(n.push("Image support"),s.push("Use altText for images or imageToText service")),e.hasAudio&&!t.media.audio.supported&&(n.push("Audio support"),s.push("Pre-transcribe audio or use transcription field")),e.hasFiles&&!t.media.files.supported&&(n.push("File support"),s.push("Pre-extract text content or use extractedText field")),e.hasUrls&&!t.media.urls.supported&&(n.push("URL/Web search support"),s.push("Pre-fetch content or use cachedContent field")),e.requiresFunctions&&!t.functions&&n.push("Function calling"),e.requiresStreaming&&!t.streaming&&(n.push("Streaming responses"),s.push("Use non-streaming mode")),e.requiresCaching&&!t.caching.supported&&(n.push("Content caching"),s.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:s}}function Is(i,e){return i.map(t=>{let n=t.getFeatures(),r=$i(t,e),s=0,o=[];return s+=10,e.hasImages&&n.media.images.supported&&(s+=25,o.push("Images"),n.media.images.detailLevels?.includes("high")&&(s+=5),n.media.images.maxSize&&n.media.images.maxSize>10*1024*1024&&(s+=3)),e.hasAudio&&n.media.audio.supported&&(s+=25,o.push("Audio"),n.media.audio.maxDuration&&n.media.audio.maxDuration>600&&(s+=5)),e.hasFiles&&n.media.files.supported&&(s+=25,o.push("Files"),n.media.files.uploadMethod==="cloud"&&(s+=3)),e.hasUrls&&n.media.urls.supported&&(s+=25,o.push("URLs"),n.media.urls.webSearch&&(s+=5)),e.requiresFunctions&&n.functions&&(s+=15,o.push("Functions"),n.functionCot&&(s+=3)),e.requiresStreaming&&n.streaming&&(s+=10,o.push("Streaming")),e.requiresCaching&&n.caching.supported&&(s+=8,o.push("Caching"),n.caching.types.includes("persistent")&&(s+=3)),n.thinking&&(s+=2),n.multiTurn&&(s+=2),n.hasThinkingBudget&&(s+=1),n.hasShowThoughts&&(s+=1),s-=r.missingCapabilities.length*10,{provider:t,score:s,missingCapabilities:r.missingCapabilities,supportedCapabilities:o}}).sort((t,n)=>n.score-t.score)}function Ts(i,e,t={}){if(e.length===0)throw new Error("No providers available");let n=$t(i),r=Is(e,n);if(t.requireExactMatch){let s=r.filter(o=>o.missingCapabilities.length===0);if(s.length===0)throw new Error(`No providers fully support the request requirements: ${r[0]?.missingCapabilities.join(", ")||"unknown requirements"}`);return s[0].provider}if(!t.allowDegradation){let s=r[0];if(s.missingCapabilities.length>0)throw new Error(`Best available provider (${s.provider.getName()}) is missing: ${s.missingCapabilities.join(", ")}`)}return r[0].provider}function Gl(i,e){let t=$t(i),n=Is(e,t),r=n[0]?.provider||null,s=[t.hasImages&&"images",t.hasAudio&&"audio",t.hasFiles&&"files",t.hasUrls&&"URLs",t.requiresFunctions&&"functions",t.requiresStreaming&&"streaming",t.requiresCaching&&"caching"].filter(Boolean).length,o=r?n[0].supportedCapabilities.length:0,a=r?`${r.getName()} supports ${o}/${s} requirements (${Math.round(o/Math.max(s,1)*100)}% compatibility)`:"No suitable providers found";return{requirements:t,providerScores:n,recommendedProvider:r,summary:a}}function Dl(i,e){return i.filter(t=>t.getFeatures().media[e].supported)}function Ul(i,e){let t={};for(let n of i){let s=n.getFeatures().media[e];if(s.supported)for(let o of s.formats)t[o]||(t[o]=[]),t[o].push(n)}return t}var ar=(r=>(r.CommandRPlus="command-r-plus",r.CommandR="command-r",r.Command="command",r.CommandLight="command-light",r))(ar||{}),lr=(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))(lr||{});var Cs=[{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 Di=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...ie()}),Bl=()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...Se()}),Rs=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),s;n&&n.role==="user"&&typeof n.content=="string"&&(s=n?.content);let o=jl(r),a=e.functions?.map(p=>{let d={};if(p.parameters?.properties)for(let[m,h]of Object.entries(p.parameters.properties))d[m]={description:h.description,type:h.type,required:p.parameters.required?.includes(m)??!1};return{name:p.name,description:p.description,parameter_definitions:d}}),l=e.chatPrompt.filter(p=>p.role==="function").map(p=>{let d=a?.find(m=>m.name===p.functionId);if(!d)throw new Error("Function not found");return{call:{name:d.name,parameters:d.parameter_definitions},outputs:[{result:p.result??""}]}}),c={name:"/chat"},u={message:s,model:t,tools:a,...l&&!s?{tool_results:l}:{},chat_history:o,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,u]}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(s=>({id:s.name,type:"function",function:{name:s.name,params:s.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),s=r[0];if(!s)throw new Error("No result");return s.id=n.generation_id??"",{results:r}};createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}},ln=class extends Ce{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("Cohere API key not set");let s={...Di(),...t},o=new Rs(s),a=r?.map(l=>{let c=l,u=c?.config;if(!u)return l;let p={};u.maxTokens!==void 0&&(p.maxTokens=u.maxTokens),u.temperature!==void 0&&(p.temperature=u.temperature),u.topP!==void 0&&(p.topP=u.topP),u.topK!==void 0&&(p.topK=u.topK),u.presencePenalty!==void 0&&(p.presencePenalty=u.presencePenalty),u.frequencyPenalty!==void 0&&(p.frequencyPenalty=u.frequencyPenalty),u.stopSequences!==void 0&&(p.stopSequences=u.stopSequences),u.endSequences!==void 0&&(p.endSequences=u.endSequences),u.stream!==void 0&&(p.stream=u.stream),u.n!==void 0&&(p.n=u.n);let d={...c};return Object.keys(p).length>0&&(d.modelConfig={...c.modelConfig??{},...p}),d});super(o,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Cs,defaults:{model:s.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 jl(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=Gi(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=i.map(o=>{if(o.role==="assistant")return o.functionCalls?.find(a=>a.id===e.functionId)}).filter(o=>o!==void 0),r=Gi(n)?.at(0);if(!r)throw new Error("Function call not found");let s=[{result:e.result}];return{role:"TOOL",tool_results:[{call:r,outputs:s}]}}default:throw new Error("Unknown role")}})}function Gi(i){return i?.map(e=>{let t;if(typeof e.function.params=="string"){let n=e.function.params;if(n.trim().length===0)t={};else try{t=JSON.parse(n)}catch{throw new Error(`Failed to parse function params JSON: ${n}`)}}else t=e.function.params;return{name:e.function.name,parameters:t}})}var cr=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(cr||{});var ws=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Ui=()=>structuredClone({model:"deepseek-chat",...ie()}),ql=()=>structuredClone({model:"deepseek-coder",...Se()}),cn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("DeepSeek API key not set");let o={...Ui(),...t};s=[...ws,...s??[]],super({apiKey:e,config:o,options:n,apiURL:"https://api.deepseek.com",modelInfo:s,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 ur=(x=>(x.Gemini3Flash="gemini-3-flash-preview",x.Gemini3Pro="gemini-3-pro-preview",x.Gemini3ProImage="gemini-3-pro-image-preview",x.Gemini25Pro="gemini-2.5-pro",x.Gemini25Flash="gemini-2.5-flash",x.Gemini25FlashLite="gemini-2.5-flash-lite",x.Gemini20Flash="gemini-2.0-flash",x.Gemini20FlashLite="gemini-2.0-flash-lite",x.Gemini20ProExp="gemini-2.0-pro-exp-02-05",x.Gemini20FlashThinkingExp="gemini-2.0-flash-thinking-exp-01-21",x.Gemini1Pro="gemini-1.0-pro",x.Gemini15Flash="gemini-1.5-flash",x.Gemini15Flash002="gemini-1.5-flash-002",x.Gemini15Flash8B="gemini-1.5-flash-8b",x.Gemini15Pro="gemini-1.5-pro",x.GeminiFlashLatest="gemini-flash-latest",x.GeminiFlashLiteLatest="gemini-flash-lite-latest",x.GeminiProLatest="gemini-pro-latest",x))(ur||{}),vs=(s=>(s.GeminiEmbedding001="gemini-embedding-001",s.GeminiEmbedding="gemini-embedding-exp",s.TextEmbeddingLarge="text-embedding-large-exp-03-07",s.TextEmbedding004="text-embedding-004",s.TextEmbedding005="text-embedding-005",s))(vs||{}),Ss=(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))(Ss||{}),ks=(s=>(s.BlockNone="BLOCK_NONE",s.BlockOnlyHigh="BLOCK_ONLY_HIGH",s.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",s.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",s.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",s))(ks||{}),Bi=(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))(Bi||{}),ji=["gemini-3-flash-preview","gemini-3-pro-preview","gemini-2.5-pro","gemini-2.5-flash","gemini-2.5-flash-lite","gemini-2.0-flash","gemini-2.0-flash-lite","gemini-flash-latest","gemini-flash-lite-latest"];var Os=[{name:"gemini-3-flash-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:12,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-3-pro-image-preview",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2,completionTokenCostPer1M:.134,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-pro-exp-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash-thinking-exp-01-21",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.5-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gemini-2.0-flash-lite",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{structuredOutputs:!0}},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15,supported:{structuredOutputs:!0}},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{structuredOutputs:!0}},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5,supported:{structuredOutputs:!0}},{name:"gemini-flash-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-flash-lite-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gemini-pro-latest",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var vt=i=>i.includes("gemini-3"),qi=i=>i.includes("gemini-3")&&i.includes("pro"),pr=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,Array.isArray(e.type)&&(e.type=e.type.includes("object")?"object":e.type[0]??"string"),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([t,n])=>[t,pr(n)]))),e.items&&(e.items=pr(e.items)),e},zi=[{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"}],Hi=()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:zi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...ie()}),zl=()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:zi,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},thinkingLevelMapping:{minimal:"minimal",low:"low",medium:"medium",high:"high",highest:"high"},...Se()}),Ms=class{constructor(e,t,n,r,s){this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=r;this.options=s;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini");let o=this.config.model;if(vt(o)){if(this.config.thinking?.thinkingTokenBudget!==void 0&&typeof this.config.thinking.thinkingTokenBudget=="number")throw new Error(`Gemini 3 models (${o}) do not support numeric thinkingTokenBudget. Use thinkingLevel ('low', 'medium', 'high') instead, or pass thinkingTokenBudget as a string level via options.`);if(qi(o)&&this.config.thinking?.thinkingLevel){let a=this.config.thinking.thinkingLevel;if(a!=="low"&&a!=="high")throw new Error(`Gemini 3 Pro (${o}) only supports thinkingLevel 'low' or 'high', got '${a}'. Use 'low' for less thinking or 'high' for more thinking.`)}}}tokensUsed;models;setModels(e){this.models=e}getEffectiveMappings(e){let t=this.models?.find(n=>n.model===e);return{thinkingLevelMapping:{...this.config.thinkingLevelMapping,...t?.thinkingLevelMapping??{}},thinkingTokenBudgetLevels:{...this.config.thinkingTokenBudgetLevels,...t?.thinkingTokenBudgetLevels??{}}}}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 s;if(this.endpointId?s={name:r?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:s={name:r?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let x=r?"&":"?",b=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;s.name+=`${x}key=${b}`}let o=e.chatPrompt.filter(x=>x.role==="system").map(x=>x.content),a=o.length>0?{role:"user",parts:[{text:o.join(" ")}]}:void 0,l=[],c=e.chatPrompt.filter(x=>x.role!=="system");for(let x=0;x<c.length;x++){let b=c[x];switch(b.role){case"user":{let T=Array.isArray(b.content)?b.content.map((A,I)=>{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: ${I})`)}}):[{text:b.content}];l.push({role:"user",parts:T});break}case"assistant":{let T=[],A=b.thoughtBlocks,I=b.functionCalls&&b.functionCalls.length>0,C=A?.[0],S=A?.map(P=>P.data).join("")??"",R=C?.signature;if(S&&T.push({...I?{}:{thought:!0},text:S,...R&&!I?{thought_signature:R}:{}}),b.functionCalls){let P=b.functionCalls.map((E,w)=>{let v;if(typeof E.function.params=="string"){let O=E.function.params;if(O.trim().length===0)v={};else try{v=JSON.parse(O)}catch{throw new Error(`Failed to parse function params JSON: ${O}`)}}else v=E.function.params;let k={functionCall:{name:E.function.name,args:v}};return R&&w===0&&(k.thought_signature=R),k});T.push(...P)}if(b.content&&T.push({text:b.content}),T.length===0)throw new Error("Assistant content is empty");l.push({role:"model",parts:T});break}case"function":{let T=[],A=b,I=x;for(;;){if(!("functionId"in A))throw new Error(`Chat prompt functionId is empty (index: ${I})`);if(T.push({functionResponse:{name:A.functionId,response:{result:A.result}}}),I+1<c.length&&c[I+1].role==="function")I++,A=c[I];else break}x=I,l.push({role:"user",parts:T});break}default:throw new Error(`Invalid role: ${JSON.stringify(b)} (index: ${x})`)}}let u=[];if(e.functions&&e.functions.length>0){let x=e.functions.map(b=>{let T={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},A=b.parameters?pr(b.parameters):void 0;return A===void 0||A&&typeof A=="object"&&Object.keys(A).length===0?A={...T}:A&&typeof A=="object"&&A.type==="object"&&(!("properties"in A)||!A.properties||Object.keys(A.properties).length===0)&&(A={...A,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:b.name,description:b.description,parameters:A}});u.push({function_declarations:x})}if(this.options?.codeExecution&&u.push({code_execution:{}}),this.options?.googleSearchRetrieval&&u.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),this.options?.googleSearch&&u.push({google_search:{}}),this.options?.googleMaps){let x=this.options.googleMaps,b=x?.enableWidget!==void 0?{enableWidget:x.enableWidget}:{};u.push({google_maps:b})}this.options?.urlContext&&u.push({url_context:{}}),u.length===0&&(u=void 0);let p,d=Array.isArray(u)?u.some(x=>x&&Array.isArray(x.function_declarations)&&x.function_declarations.length>0):!1;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 x=e.functionCall.function?.name?{allowedFunctionNames:[e.functionCall.function.name]}:{};p={function_calling_config:{mode:"ANY"},...x}}else d&&(p={function_calling_config:{mode:"AUTO"}});this.options?.retrievalConfig&&(p={...p??{},retrievalConfig:{...this.options.retrievalConfig.latLng?{latLng:this.options.retrievalConfig.latLng}:{}}});let m={};if(this.config.thinking?.includeThoughts&&(m.includeThoughts=!0),this.config.thinking?.thinkingTokenBudget&&(m.thinkingBudget=this.config.thinking.thinkingTokenBudget),this.config.thinking?.thinkingLevel&&vt(n)&&(m.thinkingLevel=this.config.thinking.thinkingLevel),t?.thinkingTokenBudget){let x=this.getEffectiveMappings(n),b=x.thinkingTokenBudgetLevels;if(vt(n)){let A=qi(n),I=x.thinkingLevelMapping;if(t.thinkingTokenBudget==="none")m.thinkingLevel=I?.minimal??"minimal";else{let C=t.thinkingTokenBudget,S=I?.[C];S||(S=C==="highest"?"high":C),m.thinkingLevel=S}if(A&&m.thinkingLevel){let C=m.thinkingLevel;C!=="low"&&C!=="high"&&(m.thinkingLevel=C==="minimal"?"low":"high")}}else switch(t.thinkingTokenBudget){case"none":m.thinkingBudget=0,m.includeThoughts=!1,delete m.thinkingLevel;break;case"minimal":m.thinkingBudget=b?.minimal??200;break;case"low":m.thinkingBudget=b?.low??800;break;case"medium":m.thinkingBudget=b?.medium??5e3;break;case"high":m.thinkingBudget=b?.high??1e4;break;case"highest":m.thinkingBudget=b?.highest??24500;break}}m.thinkingLevel&&delete m.thinkingBudget,vt(n)||delete m.thinkingLevel,vt(n)&&delete m.thinkingBudget;let h=e.modelConfig?.maxTokens??this.config.maxTokens;if(m.thinkingLevel&&h!==void 0)throw new Error("Cannot set maxTokens when using thinkingLevel with Gemini models. When thinking is enabled, the model manages output tokens automatically. Remove the maxTokens setting or disable thinking.");t?.showThoughts!==void 0&&t?.thinkingTokenBudget!=="none"&&(m.includeThoughts=t.showThoughts);let g={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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(m).length>0?{thinkingConfig:m}:{}};if(vt(n)&&(g.temperature===void 0||g.temperature<1)&&(g.temperature=1),e.responseFormat){if(g.responseMimeType="application/json",e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let x=e.responseFormat.schema.schema||e.responseFormat.schema;g.responseSchema=pr(x)}}else this.config.responseFormat&&this.config.responseFormat==="json_object"&&(g.responseMimeType="application/json");let f=this.config.safetySettings;return[s,{contents:l,tools:u,toolConfig:p,systemInstruction:a,generationConfig:g,safetySettings:f}]};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(s=>({content:s,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let s=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${s}`},r={requests:e.texts.map(o=>({model:`models/${t}`,content:{parts:[{text:o}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,r]};createChatResp=e=>{let t,n=e.candidates?.map(s=>{let o={index:0};switch(s.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new ge("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new ge("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new ge("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new ge("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new ge("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new ge("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new ge("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new ge("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new ge("Other finish reason",void 0,void 0)}if(!s.content||!s.content.parts)return o;for(let c of s.content.parts){if("text"in c){if("thought"in c&&c.thought||c.thought===!0){o.thought=c.text;let u=c.thoughtSignature||c.thought_signature;o.thoughtBlocks||(o.thoughtBlocks=[]),o.thoughtBlocks.push({data:c.text,encrypted:!1,...u?{signature:u}:{}})}else o.content=c.text;continue}if("functionCall"in c){let u=c.thoughtSignature||c.thought_signature;if(u)if(!o.thoughtBlocks||o.thoughtBlocks.length===0)o.thoughtBlocks=[{data:"",encrypted:!1,signature:u}];else{let p=o.thoughtBlocks[o.thoughtBlocks.length-1];p&&!p.signature&&(p.signature=u)}o.functionCalls=[...o.functionCalls??[],{id:Me(),type:"function",function:{name:c.functionCall.name,params:c.functionCall.args}}]}}let a=s.citationMetadata?.citations;if(Array.isArray(a)&&a.length){let c=u=>u?`${u.year}-${String(u.month).padStart(2,"0")}-${String(u.day).padStart(2,"0")}`:void 0;o.citations=a.filter(u=>typeof u?.uri=="string").map(u=>({url:u.uri,title:u.title,license:u.license,publicationDate:c(u.publicationDate)}))}let l=s.groundingMetadata;if(l){if(Array.isArray(l.groundingChunks)){let c=l.groundingChunks.map(u=>u?.maps).filter(u=>u&&typeof u.uri=="string").map(u=>({url:u.uri,title:u.title}));c.length&&(o.citations=[...o.citations??[],...c])}typeof l.googleMapsWidgetContextToken=="string"&&(t=l.googleMapsWidgetContextToken)}return o});e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount,...e.usageMetadata.cachedContentTokenCount!==void 0?{cacheReadTokens:e.usageMetadata.cachedContentTokenCount}:{}});let r={results:n};return t&&(r.providerMetadata={...r.providerMetadata,google:{...r.providerMetadata?.google??{},mapsWidgetContextToken:t}}),r};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}};supportsContextCache=e=>{let t=e;return ji.some(n=>t.includes(n)||n.includes(t))};buildCacheCreateOp=(e,t)=>{let n=e.model,r=t.contextCache?.ttlSeconds??3600,{systemInstruction:s,contents:o}=this.extractCacheableContent(e.chatPrompt);if(!s&&(!o||o.length===0))return;let a={model:this.isVertex?n:`models/${n}`,ttl:`${r}s`,displayName:`ax-cache-${Date.now()}`};s&&(a.systemInstruction=s),o&&o.length>0&&(a.contents=o);let l;if(this.isVertex)l="/cachedContents";else{l="/cachedContents";let c=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;l+=`?key=${c}`}return{type:"create",apiConfig:{name:l},request:a,parseResponse:c=>{let u=c;if(u?.name)return{name:u.name,expiresAt:u.expireTime,tokenCount:u.usageMetadata?.totalTokenCount}}}};buildCacheUpdateTTLOp=(e,t)=>{let n={ttl:`${t}s`},r=`/${e}`;if(!this.isVertex&&this.apiKey){let s=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;r+=`?key=${s}`}return{type:"update",apiConfig:{name:r,headers:{"Content-Type":"application/json"}},request:n,parseResponse:s=>{let o=s;if(o?.name)return{name:o.name,expiresAt:o.expireTime,tokenCount:o.usageMetadata?.totalTokenCount}}}};buildCacheDeleteOp=e=>{let t=`/${e}`;if(!this.isVertex&&this.apiKey){let n=typeof this.apiKey=="function"?"ASYNC_KEY":this.apiKey;t+=`?key=${n}`}return{type:"delete",apiConfig:{name:t,headers:{"Content-Type":"application/json"}},request:{},parseResponse:()=>{}}};prepareCachedChatReq=async(e,t,n)=>{let r=e.model,s=e.modelConfig?.stream??this.config.stream,{dynamicContents:o,dynamicSystemInstruction:a}=this.extractDynamicContent(e.chatPrompt),l;if(this.endpointId?l={name:s?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:l={name:s?`/models/${r}:streamGenerateContent?alt=sse`:`/models/${r}:generateContent`},!this.isVertex){let d=s?"&":"?",m=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;l.name+=`${d}key=${m}`}let c={maxOutputTokens:e.modelConfig?.maxTokens??this.config.maxTokens,temperature:e.modelConfig?.temperature??this.config.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"};vt(r)&&(c.temperature===void 0||c.temperature<1)&&(c.temperature=1);let u=this.config.safetySettings,p={contents:o,cachedContent:n,generationConfig:c,safetySettings:u};return a&&(p.systemInstruction=a),{apiConfig:l,request:p}};extractCacheableContent(e){let t,n=[],r=-1;for(let s=e.length-1;s>=0;s--){let o=e[s];if("cache"in o&&o.cache){r=s;break}}for(let s=0;s<e.length;s++){let o=e[s];if(o.role==="system"){t={role:"user",parts:[{text:o.content}]};continue}if(r>=0&&s<=r)if(o.role==="user"){let a=[];if(typeof o.content=="string")a.push({text:o.content});else if(Array.isArray(o.content))for(let l of o.content)switch(l.type){case"text":a.push({text:l.text});break;case"image":a.push({inlineData:{mimeType:l.mimeType,data:l.image}});break;case"audio":a.push({inlineData:{mimeType:`audio/${l.format??"mp3"}`,data:l.data}});break;case"file":"fileUri"in l?a.push({fileData:{mimeType:l.mimeType,fileUri:l.fileUri}}):a.push({inlineData:{mimeType:l.mimeType,data:l.data}});break}a.length>0&&n.push({role:"user",parts:a})}else o.role==="assistant"&&o.content&&n.push({role:"model",parts:[{text:o.content}]})}return{systemInstruction:t,contents:n}}extractDynamicContent(e){let n=[];for(let r of e)if(r.role!=="system"&&!("cache"in r&&r.cache))if(r.role==="user"){let s=[];if(typeof r.content=="string")s.push({text:r.content});else if(Array.isArray(r.content)){for(let o of r.content)if(!("cache"in o&&o.cache))switch(o.type){case"text":s.push({text:o.text});break;case"image":s.push({inlineData:{mimeType:o.mimeType,data:o.image}});break;case"audio":s.push({inlineData:{mimeType:`audio/${o.format??"mp3"}`,data:o.data}});break;case"file":"fileUri"in o?s.push({fileData:{mimeType:o.mimeType,fileUri:o.fileUri}}):s.push({inlineData:{mimeType:o.mimeType,data:o.data}});break}}s.length>0&&n.push({role:"user",parts:s})}else if(r.role==="assistant"){let s=[];if(r.content&&s.push({text:r.content}),r.functionCalls)for(let o of r.functionCalls){let a;if(typeof o.function.params=="string")try{a=JSON.parse(o.function.params)}catch{a={}}else a=o.function.params??{};s.push({functionCall:{name:o.function.name,args:a}})}s.length>0&&n.push({role:"model",parts:s})}else r.role==="function"&&n.push({role:"user",parts:[{functionResponse:{name:r.functionId,response:{result:r.result}}}]});return{dynamicContents:n,dynamicSystemInstruction:void 0}}},un=class i extends Ce{static create(e){return new i(e)}constructor({apiKey:e,projectId:t,region:n,endpointId:r,config:s,options:o,models:a,modelInfo:l}){let c=t!==void 0&&n!==void 0,u,p;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 f;r?f="endpoints":f="publishers/google",u=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${f}`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");u="https://generativelanguage.googleapis.com/v1beta",p=async()=>({})}let d={...Hi(),...s},m=new Ms(d,c,r,e,o);l=[...Os,...l??[]];let h=f=>{let y=Ke({model:f,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:y?.supported?.thinkingBudget??!1,hasShowThoughts:y?.supported?.showThoughts??!1,structuredOutputs:y?.supported?.structuredOutputs??!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:m.supportsContextCache(f),types:["persistent"]},thinking:y?.supported?.thinkingBudget??!1,multiTurn:!0}},g=a?.map(f=>{let y=f,x=y?.config;if(!x)return f;let b={};x.maxTokens!==void 0&&(b.maxTokens=x.maxTokens),x.temperature!==void 0&&(b.temperature=x.temperature),x.topP!==void 0&&(b.topP=x.topP),x.topK!==void 0&&(b.topK=x.topK),x.presencePenalty!==void 0&&(b.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(b.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(b.stopSequences=x.stopSequences),x.endSequences!==void 0&&(b.endSequences=x.endSequences),x.stream!==void 0&&(b.stream=x.stream),x.n!==void 0&&(b.n=x.n);let T={...y};Object.keys(b).length>0&&(T.modelConfig={...y.modelConfig??{},...b});let A=x.thinking?.thinkingTokenBudget;if(typeof A=="number"){let I=d.thinkingTokenBudgetLevels,C=[["minimal",I?.minimal??200],["low",I?.low??800],["medium",I?.medium??5e3],["high",I?.high??1e4],["highest",I?.highest??24500]],S="minimal",R=Number.POSITIVE_INFINITY;for(let[P,E]of C){let w=Math.abs(A-E);w<R&&(R=w,S=P)}T.thinkingTokenBudget=S}return x.thinking?.includeThoughts!==void 0&&(T.showThoughts=!!x.thinking.includeThoughts),x.thinkingLevelMapping&&(T.thinkingLevelMapping=x.thinkingLevelMapping),x.thinkingTokenBudgetLevels&&(T.thinkingTokenBudgetLevels=x.thinkingTokenBudgetLevels),T});g?m.setModels(g):a&&m.setModels(a),super(m,{name:"GoogleGeminiAI",apiURL:u,headers:p,modelInfo:l,defaults:{model:d.model,embedModel:d.embedModel},options:o,supportFor:h,models:g??a})}};var Hl=new $e,pn=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(Hl.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 dr=(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))(dr||{});var Ps=[{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 Kl=()=>structuredClone({model:"llama-3.3-70b-versatile",...ie()}),dn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Groq API key not set");let o={...Kl(),...t},a={...n,streamingUsage:!1};s=[...Ps,...s??[]];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:o,options:a,modelInfo:s,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 pn(t,t/60,{debug:e?.debug});return async(s,o)=>{let a=o.modelUsage?.tokens?.totalTokens||0;return await n.acquire(a),await s()}}};var Es=[];var Fs=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Fs||{});var Ki=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...ie()}),Wl=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...Se()}),_s=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:
170
170
  ${JSON.stringify(e.functions,null,2)}
171
171
  `:"",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(u=>{let p=typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params);return`${u.function.name}(${p})`}).join(`
172
172
  `);return c?`Assistant: ${l.content}
173
173
  Functions:
174
174
  ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(`
175
- `),s=`${n} ${r}`.trim(),o={name:"/models"},a={model:t,inputs:s,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[o,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},dn=class extends Ce{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let s={...Hi(),...t},o=new Fs(s);super(o,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ps,defaults:{model:s.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 dr=(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))(dr||{}),Ki=(e=>(e.MistralEmbed="mistral-embed",e))(Ki||{});var _s=[{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 Ns=()=>structuredClone({model:"mistral-small-latest",...ie(),topP:1}),Vl=()=>structuredClone({...Ns(),model:"mistral-large-latest"}),mn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Mistral API key not set");let o={...Ns(),...t};s=[..._s,...s??[]];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:u,messages:p,...d}=c;return{...d,messages:this.updateMessages(p),max_tokens:u}};super({apiKey:e,config:o,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:s,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(s=>typeof s=="object"&&s!==null&&"image_url"in s?{type:"image_url",image_url:{url:s.image_url?.url}}:s);t.push({...n,content:r})}else t.push(n);return t}};var Ls=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Me()}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){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs??!1,media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??"none"},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.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,s)=>r+s,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),s=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[s]??t;let o=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[o]??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 $s=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:s,description:o,isInternal:a}=n;this.services.set(n.key,{service:s,description:o,isInternal:a})}else{let s=n.getModelList();if(!s)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let o of s){if(this.services.has(o.key)){let a=this.services.get(o.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${o.key} as service ${a?.getName()}`)}if("model"in o&&typeof o.model)this.services.set(o.key,{description:o.description,service:n,model:o.model});else if("embedModel"in o&&o.embedModel)this.services.set(o.key,{description:o.description,service:n,embedModel:o.embedModel});else throw new Error(`Key ${o.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:s,...o}=e;return await r.service.chat(o,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:s,...o}=e;return await r.service.embed(o,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 Wi=()=>structuredClone({...ie(),model:"nous-hermes2",embedModel:"all-minilm"}),Jl=()=>structuredClone({...Se(),model:"nous-hermes2",embedModel:"all-minilm"}),gn=class extends Ie{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:s}){let o={...Wi(),...n};super({apiKey:e,options:r,config:o,apiURL:t,models:s,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 Ql=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),hn=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 o=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:o,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 s=r;throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let s;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?s=r.content:r.role==="assistant"?s=[{type:"output_text",text:r.content}]:s=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))s=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}`);s=""}else r.role,s="";switch(r.role){case"system":n.push({type:"message",role:"system",content:s});break;case"user":n.push({type:"message",role:"user",content:s,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let o={type:"message",role:"assistant",content:""};if(r.content&&(o.content=s),r.name&&(o.name=r.name),r.content&&n.push(o),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 o=r.role;throw new Error(`Invalid role in chat prompt: ${o}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},s=null,o=!1;if(e.chatPrompt){for(let y of e.chatPrompt)if(y.role==="system"&&typeof y.content=="string"){s=y.content,o=!0;break}}let a=s??this.config.systemPrompt??null,l=e.functions?.map(y=>({type:"function",name:y.name,description:y.description,parameters:y.parameters??{}})),c=[],u=Ql(n),p=this.config.reasoningSummary;t?.showThoughts?p||(p="auto"):p=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,...u?{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:p}}:{},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),e.responseFormat?m.text={format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:{type:e.responseFormat.type}}:this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let h=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,o):[];if(h.length>0)m.input=h;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(h.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let g=m.reasoning??{};if(this.config.reasoningEffort&&(g={...g,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":g={};break;case"minimal":g={...g,effort:"minimal"};break;case"low":g={...g,effort:"medium"};break;case"medium":case"high":case"highest":g={...g,effort:"high"};break}Object.keys(g).length>0&&g.effort?m.reasoning=g:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[r,f]}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 s={};for(let o of n??[])switch(o.type){case"message":s.id=o.id,s.content=Gs(o.content,t),s.finishReason=o.status==="completed"?"stop":"content_filter",s.citations=mr(o.content);break;case"reasoning":s.id=o.id,o.encrypted_content?s.thought=o.encrypted_content:s.thought=o.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
- `);break;case"file_search_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries,results:o.results}}}],s.finishReason="function_call";break;case"web_search_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries}}}],s.finishReason="function_call";break;case"computer_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action}}}],s.finishReason="function_call";break;case"code_interpreter_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code,results:o.results}}}],s.finishReason="function_call";break;case"image_generation_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}],s.finishReason="function_call";break;case"local_shell_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action}}}],s.finishReason="function_call";break;case"mcp_call":s.id=o.id,s.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}}}],s.finishReason="function_call";break;case"function_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:o.name,params:o.arguments}}],s.finishReason="function_call";break}return{results:[{...s,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=Gs(t.item.content,t.item.id),n.citations=mr(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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries||[],results:s.results?.map(o=>({fileId:o.file_id,filename:o.filename,score:o.score,text:o.text,attributes:o.attributes}))}}}]}break;case"web_search_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries||[]}}}]}break;case"computer_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action||{}}}}]}break;case"code_interpreter_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code||"",results:s.results}}}]}break;case"image_generation_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}]}break;case"local_shell_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action||{}}}}]}break;case"mcp_call":{let s=t.item;n.id=t.item.id,n.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}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Gs([t.part],t.item_id),n.citations=mr([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 s=mr(t.item.content||[]);s&&(n.citations=s)}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]}},Gs=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
175
+ `),s=`${n} ${r}`.trim(),o={name:"/models"},a={model:t,inputs:s,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[o,a]};createChatResp=e=>({results:[{index:0,content:e.generated_text}]})},mn=class extends Ce{constructor({apiKey:e,config:t,options:n,models:r}){if(!e||e==="")throw new Error("HuggingFace API key not set");let s={...Ki(),...t},o=new _s(s);super(o,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Es,defaults:{model:s.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 mr=(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))(mr||{}),Wi=(e=>(e.MistralEmbed="mistral-embed",e))(Wi||{});var Ns=[{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 Ls=()=>structuredClone({model:"mistral-small-latest",...ie(),topP:1}),Vl=()=>structuredClone({...Ls(),model:"mistral-large-latest"}),gn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Mistral API key not set");let o={...Ls(),...t};s=[...Ns,...s??[]];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:u,messages:p,...d}=c;return{...d,messages:this.updateMessages(p),max_tokens:u}};super({apiKey:e,config:o,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:s,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(s=>typeof s=="object"&&s!==null&&"image_url"in s?{type:"image_url",image_url:{url:s.image_url?.url}}:s);t.push({...n,content:r})}else t.push(n);return t}};var $s=class{constructor(e={}){this.config=e;this.config.id=this.config.id??Me()}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){let t=this.config.features?.media;return{functions:this.config.features?.functions??!1,streaming:this.config.features?.streaming??!1,structuredOutputs:this.config.features?.structuredOutputs??!1,media:{images:{supported:t?.images?.supported??!1,formats:t?.images?.formats??[]},audio:{supported:t?.audio?.supported??!1,formats:t?.audio?.formats??[]},files:{supported:t?.files?.supported??!1,formats:t?.files?.formats??[],uploadMethod:t?.files?.uploadMethod??"none"},urls:{supported:t?.urls?.supported??!1,webSearch:t?.urls?.webSearch??!1,contextFetching:t?.urls?.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,s)=>r+s,0)/n.length,n.length>0){let r=[...n].sort((a,l)=>a-l),s=Math.max(0,Math.floor(r.length*.95)-1);this.metrics.latency[e].p95=r[s]??t;let o=Math.max(0,Math.floor(r.length*.99)-1);this.metrics.latency[e].p99=r[o]??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 Gs=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:s,description:o,isInternal:a}=n;this.services.set(n.key,{service:s,description:o,isInternal:a})}else{let s=n.getModelList();if(!s)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let o of s){if(this.services.has(o.key)){let a=this.services.get(o.key)?.service;throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${o.key} as service ${a?.getName()}`)}if("model"in o&&typeof o.model)this.services.set(o.key,{description:o.description,service:n,model:o.model});else if("embedModel"in o&&o.embedModel)this.services.set(o.key,{description:o.description,service:n,embedModel:o.embedModel});else throw new Error(`Key ${o.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:s,...o}=e;return await r.service.chat(o,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:s,...o}=e;return await r.service.embed(o,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 Vi=()=>structuredClone({...ie(),model:"nous-hermes2",embedModel:"all-minilm"}),Jl=()=>structuredClone({...Se(),model:"nous-hermes2",embedModel:"all-minilm"}),hn=class extends Ie{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:r,models:s}){let o={...Vi(),...n};super({apiKey:e,options:r,config:o,apiURL:t,models:s,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 Ql=i=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(i),fn=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 o=`data:${r.mimeType};base64,${r.image}`;n.push({type:"input_image",image_url:{url:o,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 s=r;throw new Error(`Unsupported content part: ${JSON.stringify(s)}`)}return n}createResponsesReqInternalInput(e,t=!1){let n=[];for(let r of e){if(t&&r.role==="system")continue;let s;if(r.role==="system"||r.role==="user"||r.role==="assistant"&&r.content)if(typeof r.content=="string")r.role==="system"?s=r.content:r.role==="assistant"?s=[{type:"output_text",text:r.content}]:s=[{type:"input_text",text:r.content}];else if(Array.isArray(r.content))s=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}`);s=""}else r.role,s="";switch(r.role){case"system":n.push({type:"message",role:"system",content:s});break;case"user":n.push({type:"message",role:"user",content:s,name:r.name});break;case"assistant":if(r.content||r.functionCalls){let o={type:"message",role:"assistant",content:""};if(r.content&&(o.content=s),r.name&&(o.name=r.name),r.content&&n.push(o),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 o=r.role;throw new Error(`Invalid role in chat prompt: ${o}`)}}}return n}createChatReq(e,t){let n=e.model,r={name:"/responses"},s=null,o=!1;if(e.chatPrompt){for(let y of e.chatPrompt)if(y.role==="system"&&typeof y.content=="string"){s=y.content,o=!0;break}}let a=s??this.config.systemPrompt??null,l=e.functions?.map(y=>({type:"function",name:y.name,description:y.description,parameters:y.parameters??{}})),c=[],u=Ql(n),p=this.config.reasoningSummary;t?.showThoughts?p||(p="auto"):p=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,...u?{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:p}}:{},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),e.responseFormat?m.text={format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:{type:e.responseFormat.type}}:this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let h=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,o):[];if(h.length>0)m.input=h;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(h.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let g=m.reasoning??{};if(this.config.reasoningEffort&&(g={...g,effort:this.config.reasoningEffort}),t?.thinkingTokenBudget)switch(t.thinkingTokenBudget){case"none":g={};break;case"minimal":g={...g,effort:"minimal"};break;case"low":g={...g,effort:"medium"};break;case"medium":case"high":case"highest":g={...g,effort:"high"};break}Object.keys(g).length>0&&g.effort?m.reasoning=g:m.reasoning=void 0;let f=m;return this.responsesReqUpdater&&(f=this.responsesReqUpdater(f)),[r,f]}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 s={};for(let o of n??[])switch(o.type){case"message":s.id=o.id,s.content=Ds(o.content,t),s.finishReason=o.status==="completed"?"stop":"content_filter",s.citations=gr(o.content);break;case"reasoning":s.id=o.id,o.encrypted_content?s.thought=o.encrypted_content:s.thought=o.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
176
+ `);break;case"file_search_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"file_search",params:{queries:o.queries,results:o.results}}}],s.finishReason="function_call";break;case"web_search_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"web_search",params:{queries:o.queries}}}],s.finishReason="function_call";break;case"computer_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"computer_use",params:{action:o.action}}}],s.finishReason="function_call";break;case"code_interpreter_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"code_interpreter",params:{code:o.code,results:o.results}}}],s.finishReason="function_call";break;case"image_generation_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"image_generation",params:{result:o.result}}}],s.finishReason="function_call";break;case"local_shell_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:"local_shell",params:{action:o.action}}}],s.finishReason="function_call";break;case"mcp_call":s.id=o.id,s.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}}}],s.finishReason="function_call";break;case"function_call":s.id=o.id,s.functionCalls=[{id:o.id,type:"function",function:{name:o.name,params:o.arguments}}],s.finishReason="function_call";break}return{results:[{...s,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=Ds(t.item.content,t.item.id),n.citations=gr(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 s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"file_search",params:{queries:s.queries||[],results:s.results?.map(o=>({fileId:o.file_id,filename:o.filename,score:o.score,text:o.text,attributes:o.attributes}))}}}]}break;case"web_search_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"web_search",params:{queries:s.queries||[]}}}]}break;case"computer_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"computer_use",params:{action:s.action||{}}}}]}break;case"code_interpreter_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"code_interpreter",params:{code:s.code||"",results:s.results}}}]}break;case"image_generation_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"image_generation",params:{result:s.result}}}]}break;case"local_shell_call":{let s=t.item;n.id=t.item.id,n.functionCalls=[{id:s.id,type:"function",function:{name:"local_shell",params:{action:s.action||{}}}}]}break;case"mcp_call":{let s=t.item;n.id=t.item.id,n.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}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=Ds([t.part],t.item_id),n.citations=gr([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 s=gr(t.item.content||[]);s&&(n.citations=s)}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]}},Ds=(i,e)=>{let t=i.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(r=>r.refusal).join(`
177
177
  `);throw new ge(n,void 0,e)}return i.filter(n=>n.type==="output_text").map(n=>n.text).join(`
178
- `)};function mr(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 hr=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Yl=()=>({...hr(),model:"gpt-4o",temperature:.5}),Xl=()=>({...hr(),model:"gpt-4o",temperature:.9}),gr=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=[],models:o,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 hn(t,n?.streamingUsage??!0,a),u=o?.map(p=>{let d=p,m=d?.config;if(!m)return p;let h={};m.maxTokens!==void 0&&(h.maxTokens=m.maxTokens),m.temperature!==void 0&&(h.temperature=m.temperature),m.topP!==void 0&&(h.topP=m.topP),m.presencePenalty!==void 0&&(h.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(h.frequencyPenalty=m.frequencyPenalty);let g=m.stopSequences??m.stop;g!==void 0&&(h.stopSequences=g),m.n!==void 0&&(h.n=m.n),m.stream!==void 0&&(h.stream=m.stream);let f={...d};Object.keys(h).length>0&&(f.modelConfig={...d.modelConfig??{},...h});let y=m?.thinking?.thinkingTokenBudget;if(typeof y=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],b="minimal",T=Number.POSITIVE_INFINITY;for(let[A,I]of x){let C=Math.abs(y-I);C<T&&(T=C,b=A)}f.thinkingTokenBudget=b}return m?.thinking?.includeThoughts!==void 0&&(f.showThoughts=!!m.thinking.includeThoughts),f});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:u??o})}},fn=class extends gr{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...gs,...s??[]];let o=a=>{let l=Ke({model:a,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.supported?.structuredOutputs??!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:{...hr(),...t},options:n,modelInfo:s,models:r,supportFor:o})}};var Vi=()=>structuredClone({model:"openrouter/auto",...ie()}),xn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s,referer:o,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Vi(),...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},u=s??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let p={Authorization:`Bearer ${e}`};return o&&(p["HTTP-Referer"]=o),a&&(p["X-Title"]=a),p})}};async function Ds(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 s of i)try{switch(s.type){case"text":r.push({type:"text",text:s.text});break;case"image":if(n.media.images.supported)s.altText?r.push({type:"text",text:`[Image: ${s.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(s.altText)r.push({type:"text",text:s.altText});else if(t.imageToText)try{let o=await t.imageToText(s.image);r.push({type:"text",text:o})}catch(o){throw new at(o,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new et("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)s.transcription?r.push({type:"text",text:s.transcription}):r.push({type:"text",text:"[Audio content]"});else if(s.transcription)r.push({type:"text",text:s.transcription});else if(t.audioToText)try{let o=await t.audioToText(s.data,s.format);r.push({type:"text",text:o})}catch(o){throw new at(o,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new et("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)s.extractedText?r.push({type:"text",text:s.extractedText}):r.push({type:"text",text:`[File: ${s.filename}]`});else if(s.extractedText)r.push({type:"text",text:s.extractedText});else if(t.fileToText)try{let o=await t.fileToText(s.data,s.mimeType);r.push({type:"text",text:o})}catch(o){throw new at(o,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new et("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${s.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)s.cachedContent?r.push({type:"text",text:s.cachedContent}):r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`});else if(s.cachedContent)r.push({type:"text",text:s.cachedContent});else if(t.urlToText)try{let o=await t.urlToText(s.url);r.push({type:"text",text:o})}catch(o){throw new at(o,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new et("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`})}break;default:typeof s=="object"&&s.text?r.push({type:"text",text:s.text}):r.push({type:"text",text:String(s)})}}catch(o){throw o instanceof et||o instanceof at?o:new at(o,s.type||"unknown","content processing")}return r}function Zl(i){let e=!1,t=!1,n=!1,r=!1;for(let s of i)if(s.role==="user"&&Array.isArray(s.content))for(let o of s.content)switch(o.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 fr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(fr||{});var Us=[{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 xr=()=>structuredClone({model:"reka-core",...ie()}),ec=()=>structuredClone({...xr(),model:"reka-core"}),tc=()=>structuredClone({model:"reka-core",...Se()}),nc=()=>({...xr(),model:"reka-flash"}),Bs=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=rc(e),s=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,o=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,...s?{frequency_penalty:s}:{},...o?{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((o,a)=>{let l=Ji(o.finish_reason),c;return typeof o.message.content=="string"?c=o.message.content:c=o.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((o,a)=>{let l=Ji(o.finish_reason),c;return typeof o.chunk.content=="string"?c=o.chunk.content:c=o.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},Ji=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function rc(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 An=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=Us,models:o}){if(!e||e==="")throw new Error("Reka API key not set");let a={...xr(),...t},l=new Bs(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:s,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:o})}};var js=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(s){if(s instanceof et&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw s}}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},s=[];for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content)){let a=await Ds(o.content,t,r);a.every(c=>c.type==="text")&&a.length===1?s.push({...o,content:a[0].text}):s.push({...o,content:a.map(c=>({type:"text",text:c.text}))})}else s.push(o);return{...e,chatPrompt:s}}async selectProviderWithDegradation(e,t){let n=Lt(e),r=[],s=[],o=[];try{let a=Is(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&&(s.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(s.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(s.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(s.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&o.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&o.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:s,warnings:o}}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 s={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},o=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(o,n),routing:s}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=Lt(e),n=[],r=[];try{let s=await this.selectProviderWithDegradation(e,{});return s.degradations.length>0&&(n.push(...s.degradations),r.push("Consider using a provider that natively supports all media types")),s.warnings.length>0&&n.push(...s.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||s.degradations.length>0,issues:n,recommendations:r}}catch(s){return{canHandle:!1,issues:[`Cannot route request: ${s instanceof Error?s.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 qs=[];var Qi=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...ie()}),yn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Together API key not set");let o={...Qi(),...t};s=[...qs,...s??[]];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:o,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:s,models:r,supportFor:a}),super.setName("Together")}};var Ar=(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))(Ar||{});var zs=[{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 Yi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...ie()}),sc=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Se()}),Hs=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(u=>u.type==="text").map(u=>u.text).join(`
179
- `));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),s={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(u){try{for await(let p of c)u.enqueue(p);u.close()}catch(p){u.error(p)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},o={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[s,o]}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 s="stop";switch(n.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let o=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:o,finishReason:s}}),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 s;if(r.finish_reason)switch(r.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let o=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:o,finishReason:s}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},bn=class extends Ce{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let s={...Yi(),...t},o=new Hs(s,e);super(o,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:zs,defaults:{model:s.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 yr=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(yr||{}),Xi=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Xi||{});var Ks=[{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 Ws=()=>structuredClone({model:"grok-3-mini",...ie()}),oc=()=>structuredClone({...Ws(),model:"grok-3"}),In=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Grok API key not set");let o={...Ws(),...t};s=[...Ks,...s??[]];let a=c=>{let u=Ke({model:c,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.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 u=n.searchParameters;return{...c,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(p=>({type:p.type,country:p.country,excluded_websites:p.excludedWebsites,allowed_websites:p.allowedWebsites,safe_search:p.safeSearch,x_handles:p.xHandles,links:p.links}))}}}return c};super({apiKey:e,config:o,options:n,apiURL:"https://api.x.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function ic(i){return br.create(i)}var br=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new sn(e);break;case"openai-responses":this.ai=new fn(e);break;case"azure-openai":this.ai=new on(e);break;case"grok":this.ai=new In(e);break;case"huggingface":this.ai=new dn(e);break;case"groq":this.ai=new pn(e);break;case"together":this.ai=new yn(e);break;case"openrouter":this.ai=new xn(e);break;case"cohere":this.ai=new an(e);break;case"google-gemini":this.ai=new cn(e);break;case"anthropic":this.ai=new en(e);break;case"mistral":this.ai=new mn(e);break;case"deepseek":this.ai=new ln(e);break;case"ollama":this.ai=new gn(e);break;case"reka":this.ai=new An(e);break;case"webllm":this.ai=new bn(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 Vs}from"@opentelemetry/api";var nt=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:Vs.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e.table,[Q.DB_NAMESPACE]:e.namespace,[Q.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:Vs.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e[0].table,[Q.DB_NAMESPACE]:e[0].namespace,[Q.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:Vs.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e.table,[Q.DB_NAMESPACE]:e.namespace,[Q.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Js="https://api.cloudflare.com/client/v4/accounts/",Tn=class extends nt{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 Ee({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Js),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:s})=>s).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,s=await Ee({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Js),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(o=>({id:o.id,values:o.values,namespace:o.namespace,metadata:o.metadata})));if(s.errors)throw new Error(`Cloudflare batch upsert failed: ${s.errors.map(({message:o})=>o).join(", ")}`);return{ids:s.result.ids}};query=async(e,t)=>{let n=await Ee({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Js),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:s})=>s).join(", ")}`);return{matches:n.result.matches.map(({id:s,score:o,values:a,metadata:l})=>({id:s,score:o,values:a,metadata:l}))}}};var St=class extends nt{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 s of e){let o=await this.upsert(s,t);r.push(...o.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(([s,o])=>{if(e.values&&o.values){let a=ac(e.values,o.values);r.push({id:s,score:a,metadata:o.metadata})}}),r.sort((s,o)=>s.score-o.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},ac=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,s=!0,o=!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&&(s=!1),l[d]!==0&&(o=!1);if(s||o)return 1;let c=Math.sqrt(n),u=Math.sqrt(r);return 1-t/(c*u)};var lc=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),Cn=class extends nt{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 Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:s=[],metadata:o})=>({id:r,values:s,metadata:o}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},lc(e))).matches.map(({id:s,score:o,values:a,metadata:l})=>({id:s,score:o,metadata:l,values:a}))}}};var Rn=class extends nt{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 Ee({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:s})=>s).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(o=>({id:o.id,class:o.table,tenant:o.namespace,vector:o.values,properties:o.metadata??{}})),s=await Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(s?.some(({result:o})=>o?.errors))throw new Error(`Weaviate batch upsert failed: ${s.map(({result:o})=>o?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:s.map(({id:o})=>o)}};_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: {
178
+ `)};function gr(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 fr=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Yl=()=>({...fr(),model:"gpt-4o",temperature:.5}),Xl=()=>({...fr(),model:"gpt-4o",temperature:.9}),hr=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=[],models:o,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 fn(t,n?.streamingUsage??!0,a),u=o?.map(p=>{let d=p,m=d?.config;if(!m)return p;let h={};m.maxTokens!==void 0&&(h.maxTokens=m.maxTokens),m.temperature!==void 0&&(h.temperature=m.temperature),m.topP!==void 0&&(h.topP=m.topP),m.presencePenalty!==void 0&&(h.presencePenalty=m.presencePenalty),m.frequencyPenalty!==void 0&&(h.frequencyPenalty=m.frequencyPenalty);let g=m.stopSequences??m.stop;g!==void 0&&(h.stopSequences=g),m.n!==void 0&&(h.n=m.n),m.stream!==void 0&&(h.stream=m.stream);let f={...d};Object.keys(h).length>0&&(f.modelConfig={...d.modelConfig??{},...h});let y=m?.thinking?.thinkingTokenBudget;if(typeof y=="number"){let x=[["minimal",200],["low",800],["medium",5e3],["high",1e4],["highest",24500]],b="minimal",T=Number.POSITIVE_INFINITY;for(let[A,I]of x){let C=Math.abs(y-I);C<T&&(T=C,b=A)}f.thinkingTokenBudget=b}return m?.thinking?.includeThoughts!==void 0&&(f.showThoughts=!!m.thinking.includeThoughts),f});super(c,{name:"OpenAI",apiURL:r||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:s,defaults:{model:t.model??"gpt-4o",embedModel:t.embedModel??"text-embedding-ada-002"},options:n,supportFor:l,models:u??o})}},xn=class extends hr{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("OpenAI API key not set");s=[...hs,...s??[]];let o=a=>{let l=Ke({model:a,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:l?.supported?.thinkingBudget??!1,hasShowThoughts:l?.supported?.showThoughts??!1,structuredOutputs:l?.supported?.structuredOutputs??!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:{...fr(),...t},options:n,modelInfo:s,models:r,supportFor:o})}};var Ji=()=>structuredClone({model:"openrouter/auto",...ie()}),An=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s,referer:o,title:a}){if(!e||e==="")throw new Error("OpenRouter API key not set");let l={...Ji(),...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},u=s??[];super({apiKey:e,config:l,options:n,apiURL:"https://openrouter.ai/api/v1",modelInfo:u,models:r,supportFor:c}),super.setName("OpenRouter"),super.setHeaders(async()=>{let p={Authorization:`Bearer ${e}`};return o&&(p["HTTP-Referer"]=o),a&&(p["X-Title"]=a),p})}};async function Us(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 s of i)try{switch(s.type){case"text":r.push({type:"text",text:s.text});break;case"image":if(n.media.images.supported)s.altText?r.push({type:"text",text:`[Image: ${s.altText}]`}):r.push({type:"text",text:"[Image content]"});else if(s.altText)r.push({type:"text",text:s.altText});else if(t.imageToText)try{let o=await t.imageToText(s.image);r.push({type:"text",text:o})}catch(o){throw new at(o,"image","vision analysis")}else switch(t.fallbackBehavior){case"error":throw new et("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)s.transcription?r.push({type:"text",text:s.transcription}):r.push({type:"text",text:"[Audio content]"});else if(s.transcription)r.push({type:"text",text:s.transcription});else if(t.audioToText)try{let o=await t.audioToText(s.data,s.format);r.push({type:"text",text:o})}catch(o){throw new at(o,"audio","transcription")}else switch(t.fallbackBehavior){case"error":throw new et("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)s.extractedText?r.push({type:"text",text:s.extractedText}):r.push({type:"text",text:`[File: ${s.filename}]`});else if(s.extractedText)r.push({type:"text",text:s.extractedText});else if(t.fileToText)try{let o=await t.fileToText(s.data,s.mimeType);r.push({type:"text",text:o})}catch(o){throw new at(o,"file","text extraction")}else switch(t.fallbackBehavior){case"error":throw new et("Files",e.getName(),!1);case"skip":continue;default:r.push({type:"text",text:`[File: ${s.filename} - content not accessible by this provider]`})}break;case"url":if(n.media.urls.supported)s.cachedContent?r.push({type:"text",text:s.cachedContent}):r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`});else if(s.cachedContent)r.push({type:"text",text:s.cachedContent});else if(t.urlToText)try{let o=await t.urlToText(s.url);r.push({type:"text",text:o})}catch(o){throw new at(o,"url","content fetching")}else switch(t.fallbackBehavior){case"error":throw new et("URLs",e.getName(),!1);case"skip":continue;case"degrade":r.push({type:"text",text:`[Link: ${s.url}${s.title?` - ${s.title}`:""}]`})}break;default:typeof s=="object"&&s.text?r.push({type:"text",text:s.text}):r.push({type:"text",text:String(s)})}}catch(o){throw o instanceof et||o instanceof at?o:new at(o,s.type||"unknown","content processing")}return r}function Zl(i){let e=!1,t=!1,n=!1,r=!1;for(let s of i)if(s.role==="user"&&Array.isArray(s.content))for(let o of s.content)switch(o.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 xr=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(xr||{});var Bs=[{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 Ar=()=>structuredClone({model:"reka-core",...ie()}),ec=()=>structuredClone({...Ar(),model:"reka-core"}),tc=()=>structuredClone({model:"reka-core",...Se()}),nc=()=>({...Ar(),model:"reka-flash"}),js=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=rc(e),s=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,o=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,...s?{frequency_penalty:s}:{},...o?{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((o,a)=>{let l=Qi(o.finish_reason),c;return typeof o.message.content=="string"?c=o.message.content:c=o.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((o,a)=>{let l=Qi(o.finish_reason),c;return typeof o.chunk.content=="string"?c=o.chunk.content:c=o.chunk.content.text,{index:a,id:`${t}`,content:c,finishReason:l}})}}},Qi=i=>{switch(i){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function rc(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 yn=class extends Ce{constructor({apiKey:e,config:t,options:n,apiURL:r,modelInfo:s=Bs,models:o}){if(!e||e==="")throw new Error("Reka API key not set");let a={...Ar(),...t},l=new js(a);super(l,{name:"Reka",apiURL:r||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:s,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:o})}};var qs=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(s){if(s instanceof et&&t.fallbackProviders?.length)return await this.tryFallbackProviders(e,t.fallbackProviders,t);throw s}}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},s=[];for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content)){let a=await Us(o.content,t,r);a.every(c=>c.type==="text")&&a.length===1?s.push({...o,content:a[0].text}):s.push({...o,content:a.map(c=>({type:"text",text:c.text}))})}else s.push(o);return{...e,chatPrompt:s}}async selectProviderWithDegradation(e,t){let n=$t(e),r=[],s=[],o=[];try{let a=Ts(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&&(s.push("Images will be converted to text descriptions"),r.push("Image-to-text conversion")),n.hasAudio&&!l.media.audio.supported&&(s.push("Audio will be transcribed to text"),r.push("Audio-to-text transcription")),n.hasFiles&&!l.media.files.supported&&(s.push("File content will be extracted to text"),r.push("File-to-text extraction")),n.hasUrls&&!l.media.urls.supported&&(s.push("URL content will be pre-fetched"),r.push("URL content fetching")),n.requiresStreaming&&!l.streaming&&o.push("Streaming not supported - will use non-streaming mode"),n.requiresCaching&&!l.caching.supported&&o.push("Content caching not supported"),{provider:a,processingApplied:r,degradations:s,warnings:o}}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 s={provider:r,processingApplied:["Fallback provider selection"],degradations:["Using fallback provider due to primary provider failure"],warnings:[]},o=await this.preprocessRequest(e,r,{fallbackBehavior:"degrade"});return{response:await r.chat(o,n),routing:s}}catch{}throw new Error("All fallback providers failed")}async getRoutingRecommendation(e){return await this.selectProviderWithDegradation(e,{})}async validateRequest(e){let t=$t(e),n=[],r=[];try{let s=await this.selectProviderWithDegradation(e,{});return s.degradations.length>0&&(n.push(...s.degradations),r.push("Consider using a provider that natively supports all media types")),s.warnings.length>0&&n.push(...s.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||s.degradations.length>0,issues:n,recommendations:r}}catch(s){return{canHandle:!1,issues:[`Cannot route request: ${s instanceof Error?s.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 zs=[];var Yi=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...ie()}),bn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Together API key not set");let o={...Yi(),...t};s=[...zs,...s??[]];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:o,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:s,models:r,supportFor:a}),super.setName("Together")}};var yr=(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))(yr||{});var Hs=[{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 Xi=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...ie()}),sc=()=>structuredClone({model:"Llama-3.2-3B-Instruct-q4f32_1-MLC",...Se()}),Ks=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(u=>u.type==="text").map(u=>u.text).join(`
179
+ `));let c={role:a.role,content:l};return a.role==="assistant"&&a.functionCalls?.length?{...c,tool_calls:a.functionCalls.map(u=>({id:u.id,type:"function",function:{name:u.function.name,arguments:typeof u.function.params=="string"?u.function.params:JSON.stringify(u.function.params||{})}}))}:c}),r=e.functions?.map(a=>({type:"function",function:{name:a.name,description:a.description,parameters:a.parameters||{type:"object",properties:{}}}})),s={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(u){try{for await(let p of c)u.enqueue(p);u.close()}catch(p){u.error(p)}}}):c}catch(c){throw new Error(`WebLLM API error: ${c}`)}}},o={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[s,o]}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 s="stop";switch(n.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let o=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:o,finishReason:s}}),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 s;if(r.finish_reason)switch(r.finish_reason){case"stop":s="stop";break;case"length":s="length";break;case"tool_calls":s="function_call";break;case"content_filter":s="content_filter";break;default:s="stop";break}let o=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:o,finishReason:s}],remoteId:e.id}};createEmbedResp(e){throw new Error("WebLLM does not support embeddings")}},In=class extends Ce{constructor({engine:e,config:t,options:n,models:r}){if(!e)throw new Error("WebLLM engine instance is required");let s={...Xi(),...t},o=new Ks(s,e);super(o,{name:"WebLLM",apiURL:void 0,headers:async()=>({}),modelInfo:Hs,defaults:{model:s.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 br=(r=>(r.Grok3="grok-3",r.Grok3Mini="grok-3-mini",r.Grok3Fast="grok-3-fast",r.Grok3MiniFast="grok-3-mini-fast",r))(br||{}),Zi=(e=>(e.GrokEmbedSmall="grok-embed-small",e))(Zi||{});var Ws=[{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 Vs=()=>structuredClone({model:"grok-3-mini",...ie()}),oc=()=>structuredClone({...Vs(),model:"grok-3"}),Tn=class extends Ie{constructor({apiKey:e,config:t,options:n,models:r,modelInfo:s}){if(!e||e==="")throw new Error("Grok API key not set");let o={...Vs(),...t};s=[...Ws,...s??[]];let a=c=>{let u=Ke({model:c,modelInfo:s,models:r});return{functions:!0,streaming:!0,hasThinkingBudget:u?.supported?.thinkingBudget??!1,hasShowThoughts:u?.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 u=n.searchParameters;return{...c,search_parameters:{mode:u.mode,return_citations:u.returnCitations,from_date:u.fromDate,to_date:u.toDate,max_search_results:u.maxSearchResults,sources:u.sources?.map(p=>({type:p.type,country:p.country,excluded_websites:p.excludedWebsites,allowed_websites:p.allowedWebsites,safe_search:p.safeSearch,x_handles:p.xHandles,links:p.links}))}}}return c};super({apiKey:e,config:o,options:n,apiURL:"https://api.x.ai/v1",modelInfo:s,models:r,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};function ic(i){return Ir.create(i)}var Ir=class i{ai;static create(e){return new i(e)}constructor(e){switch(e.name){case"openai":this.ai=new on(e);break;case"openai-responses":this.ai=new xn(e);break;case"azure-openai":this.ai=new an(e);break;case"grok":this.ai=new Tn(e);break;case"huggingface":this.ai=new mn(e);break;case"groq":this.ai=new dn(e);break;case"together":this.ai=new bn(e);break;case"openrouter":this.ai=new An(e);break;case"cohere":this.ai=new ln(e);break;case"google-gemini":this.ai=new un(e);break;case"anthropic":this.ai=new tn(e);break;case"mistral":this.ai=new gn(e);break;case"deepseek":this.ai=new cn(e);break;case"ollama":this.ai=new hn(e);break;case"reka":this.ai=new yn(e);break;case"webllm":this.ai=new In(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 Js}from"@opentelemetry/api";var nt=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:Js.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e.table,[Q.DB_NAMESPACE]:e.namespace,[Q.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:Js.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e[0].table,[Q.DB_NAMESPACE]:e[0].namespace,[Q.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:Js.SERVER,attributes:{[Q.DB_SYSTEM]:this.name,[Q.DB_OPERATION_NAME]:"upsert",[Q.DB_TABLE]:e.table,[Q.DB_NAMESPACE]:e.namespace,[Q.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var Qs="https://api.cloudflare.com/client/v4/accounts/",Cn=class extends nt{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 Ee({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,Qs),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:s})=>s).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,s=await Ee({url:new URL(`${this.accountId}/vectorize/indexes/${r}/upsert`,Qs),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:n?.span},e.map(o=>({id:o.id,values:o.values,namespace:o.namespace,metadata:o.metadata})));if(s.errors)throw new Error(`Cloudflare batch upsert failed: ${s.errors.map(({message:o})=>o).join(", ")}`);return{ids:s.result.ids}};query=async(e,t)=>{let n=await Ee({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,Qs),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:s})=>s).join(", ")}`);return{matches:n.result.matches.map(({id:s,score:o,values:a,metadata:l})=>({id:s,score:o,values:a,metadata:l}))}}};var St=class extends nt{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 s of e){let o=await this.upsert(s,t);r.push(...o.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(([s,o])=>{if(e.values&&o.values){let a=ac(e.values,o.values);r.push({id:s,score:a,metadata:o.metadata})}}),r.sort((s,o)=>s.score-o.score),e.limit&&(r.length=e.limit),{matches:r}};getDB=()=>structuredClone(this.state);setDB=e=>{this.state=structuredClone(e)};clearDB=()=>{this.state={}}},ac=(i,e)=>{if(i.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,r=0,s=!0,o=!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&&(s=!1),l[d]!==0&&(o=!1);if(s||o)return 1;let c=Math.sqrt(n),u=Math.sqrt(r);return 1-t/(c*u)};var lc=i=>({namespace:i.namespace,topK:i.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:i.values??[],id:i.id}),Rn=class extends nt{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 Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:n?.span},e.map(({id:r,values:s=[],metadata:o})=>({id:r,values:s,metadata:o}))),{ids:e.map(({id:r})=>r)}};query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:t?.span},lc(e))).matches.map(({id:s,score:o,values:a,metadata:l})=>({id:s,score:o,metadata:l,values:a}))}}};var wn=class extends nt{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 Ee({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:s})=>s).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(o=>({id:o.id,class:o.table,tenant:o.namespace,vector:o.values,properties:o.metadata??{}})),s=await Ee({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:n?.span},{objects:r});if(s?.some(({result:o})=>o?.errors))throw new Error(`Weaviate batch upsert failed: ${s.map(({result:o})=>o?.errors?.error.map(({message:a})=>a).join(", ")).join(", ")}`);return{ids:s.map(({id:o})=>o)}};_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: {
180
180
  vector: [${e.values.join(",")}],
181
181
  }`;else if(e.text)n=`nearText: {
182
182
  concepts: ['${e.text}'],
@@ -190,9 +190,9 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
190
190
  `)}
191
191
  }
192
192
  }
193
- }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let s=r.data.Get[e.table];return s?{matches:s.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var Qs=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new Rn(e);break;case"pinecone":this.db=new Cn(e);break;case"cloudflare":this.db=new Tn(e);break;case"memory":this.db=new St(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 Ys="_internal",Xs=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(`
193
+ }`});if(r.errors)throw new Error(`Weaviate query failed: ${r.errors.map(({message:a})=>a).join(", ")}`);let s=r.data.Get[e.table];return s?{matches:s.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}};var Ys=class{db;constructor(e){switch(e.name){case"weaviate":this.db=new wn(e);break;case"pinecone":this.db=new Rn(e);break;case"cloudflare":this.db=new Cn(e);break;case"memory":this.db=new St(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 Xs="_internal",Zs=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(`
194
194
 
195
- `):e,r=this.chunker(n).filter(c=>c.length>0),s=t?.maxWordsPerChunk,o=t?.minWordsPerChunk,a=cc({initialChunks:r,minWordsPerChunk:o,maxWordsPerChunk:s}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let u=a.slice(c,c+l),d=(await this.ai.embed({texts:u},{abortSignal:t?.abortSignal})).embeddings.map((m,h)=>({id:`chunk_${Date.now()+h}`,table:Ys,values:m,metadata:{text:u[h]??""}})).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:u}=await this.rewriter.forward(this.ai,{query:c});r[l]=u}let s;typeof r[0]=="string"?s=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:Ys,values:c})):s=r.map(l=>this.db.query({table:Ys,values:l}));let o=await Promise.all(s),a=[];for(let{matches:l}of o){let c=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),u=t&&t>1?t/100:t,p=u?uc(c,u):c;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:p.map(h=>h.text)}),m=d.map(h=>p.find(g=>g.text===h)).filter(h=>h!==void 0);a.push(m)}else a.push(p)}return a}},cc=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",s=0;return i.forEach(o=>{let a=o.split(/\s+/),l=a.length;if(s+l<=e)r+=`${o}
195
+ `):e,r=this.chunker(n).filter(c=>c.length>0),s=t?.maxWordsPerChunk,o=t?.minWordsPerChunk,a=cc({initialChunks:r,minWordsPerChunk:o,maxWordsPerChunk:s}),l=t?.batchSize??10;for(let c=0;c<a.length;c+=l){let u=a.slice(c,c+l),d=(await this.ai.embed({texts:u},{abortSignal:t?.abortSignal})).embeddings.map((m,h)=>({id:`chunk_${Date.now()+h}`,table:Xs,values:m,metadata:{text:u[h]??""}})).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:u}=await this.rewriter.forward(this.ai,{query:c});r[l]=u}let s;typeof r[0]=="string"?s=(await this.ai.embed({texts:r},{abortSignal:n})).embeddings.map(c=>this.db.query({table:Xs,values:c})):s=r.map(l=>this.db.query({table:Xs,values:l}));let o=await Promise.all(s),a=[];for(let{matches:l}of o){let c=l.filter(d=>d.metadata?.text&&d.metadata?.text.length>0).map(({score:d,metadata:m})=>({score:d,text:m?.text??""})),u=t&&t>1?t/100:t,p=u?uc(c,u):c;if(this.reranker){let{rankedItems:d}=await this.reranker.forward(this.ai,{query:r[0],items:p.map(h=>h.text)}),m=d.map(h=>p.find(g=>g.text===h)).filter(h=>h!==void 0);a.push(m)}else a.push(p)}return a}},cc=({initialChunks:i,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],r="",s=0;return i.forEach(o=>{let a=o.split(/\s+/),l=a.length;if(s+l<=e)r+=`${o}
196
196
 
197
197
  `,s+=l;else if(s>0&&s+l<=e*1.5)r+=`${o}
198
198
 
@@ -200,21 +200,21 @@ ${c}`:`Assistant: ${l.content}`}default:throw new Error("Unknown role")}}).join(
200
200
 
201
201
  `,s+=c.length)}else r=`${o}
202
202
 
203
- `,s=l}),(s>t||n.length===0)&&n.push(r.trim()),n},uc=(i,e=.1)=>{let t=[...i].sort((r,s)=>r.score-s.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as zc,SpanKind as Hc,trace as Kc}from"@opentelemetry/api";var wn=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,...s})=>({index:r,value:structuredClone(s)})),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,thoughtBlocks:s,index:o}){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:o,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})}]});return}let l=a.chat.find(c=>c.index===o);if(!l){a.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})});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(Array.isArray(s)&&s.length>0){let c=l.value.thoughtBlocks??[];for(let u of s){let p=c.length>0?c[c.length-1]:void 0;!u.signature&&u.data?p&&!p.signature?(p.data=(p.data??"")+u.data,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):u.signature?p&&!p.signature?(p.data=(p.data??"")+u.data,p.signature=u.signature,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):c.length===0&&c.push(structuredClone(u))}l.value.thoughtBlocks=c,c.length>0&&(l.value.thought=c.map(u=>u.data).join(""))}}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,s)=>(r.tags?.includes(e)&&n.push(s),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 s;n==="function"?s=r.filter(o=>o.index===e).map(o=>o.value):s=r.find(o=>o.index===e)?.value,Array.isArray(s)&&s.length>0?t.push(...s.map(o=>({...o,role:n}))):typeof s=="object"&&s!==null&&t.push({...s,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},vn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new wn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new wn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)Zt(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){ps(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 wn):this.defaultMemory.reset()}};var mt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}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()}},$t=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,s=await n(e);if(s!==void 0){if(typeof s=="string")throw new mt({message:s});if(!s)throw r?new mt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},Zs=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(o=>o.fieldName===e.currField?.name);if(r.length===0)return;let s=t.substring(e.s);for(let o of r){let{message:a,fn:l}=o,c=await l(s,n);if(c!==void 0){if(typeof c=="string")throw new mt({message:c});if(!c&&a)throw new mt({message:a})}}};var Zi={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Sn,eo=i=>{if(Sn)return Sn;let e=i??Z.meter;if(e)return Sn=dc(e),Sn};var pc=()=>{let i=[];return Z.meter||i.push("Global meter not initialized"),!Sn&&Z.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},dc=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"})}),Ir=Zi,mc=i=>{Ir={...Ir,...i}},gc=()=>({...Ir}),rt=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),s=Ir.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e};var ea=(i,e,t,n,r,s,o)=>{try{let a=rt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...s?{model:s}:{},...o});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,a),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,a),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},Tr=(i,e,t,n,r)=>{try{let s=rt({...n?{signature:n}:{},...r});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,s),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,s),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,s)}catch(s){console.warn("Failed to record multi-step metric:",s)}},to=(i,e,t,n)=>{try{let r=rt({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,r),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},ta=(i,e,t)=>{try{let n=rt({error_type:"refusal",...e?{signature:e}:{},...t});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},no=(i,e,t,n,r,s)=>{try{let o=rt({success:t.toString(),...r?{signature:r}:{},...s});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)}},na=(i,e,t,n,r=!1,s,o)=>{try{let a=rt({functions_enabled:e.toString(),had_function_calls:n.toString(),...s?{signature:s}:{},...o});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,a),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,a),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,a),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},ra=(i,e,t,n,r)=>{try{let s=rt({...n?{signature:n}:{},...r});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,s),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,s)}catch(s){console.warn("Failed to record field processing metric:",s)}},sa=(i,e,t,n,r,s)=>{try{let o=rt({is_streaming:e.toString(),...r?{signature:r}:{},...s});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)}},oa=(i,e,t,n,r,s)=>{try{let o=rt({result_picker_used:t.toString(),...r?{signature:r}:{},...s});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)}},ia=(i,e,t,n,r,s,o)=>{try{let a=rt({...s?{signature:s}:{},...o});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,a),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,a),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,a),i.demosUsedGauge&&i.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},Cr=(i,e,t,n,r)=>{try{let s=rt({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,s);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,s);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,s);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,s);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record performance metric:",s)}};var Gt=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";case"object":return"object";default:return"string"}})();return i?.isArray?`array of ${e}s`:e},ke=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},aa=i=>{let t=i.map(n=>`'${n.title}' (${Gt(n.type)})`).join(", ");return new ke(`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 ${Gt(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},Rr=i=>new ke(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${Gt(i.type)} value directly after.`);var wr=i=>new ke(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${Gt(i.type)}. Do not use null, undefined, or leave it blank.`),la=(i,e)=>new ke(`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.`),ca=(i,e)=>new ke(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${Gt(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),ua=(i,e,t)=>new ke(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${Gt(i.type)}. Ensure formatting exactly matches the expected type.`),pa=(i,e,t)=>new ke(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),da=(i,e,t)=>new ke(`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}.`),ro=(i,e,t)=>new ke(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),Dt=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new ke(r)},so=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new ke(r)};var ma=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";oi(i,e,c,n)}return r&&to(r,"validation",s,a),o&&o.addEvent("validation.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},ga=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";ii(i,e,c,n)}return r&&to(r,"assertion",s,a),o&&o.addEvent("assertion.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},ha=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{t&&n&&ai(i,e,n),r&&ta(r,s,a),o&&o.addEvent("refusal.error",{message:i.toString()})};import kt from"dayjs";import hc from"dayjs/plugin/customParseFormat.js";import fc from"dayjs/plugin/timezone.js";import xc from"dayjs/plugin/utc.js";kt.extend(xc);kt.extend(fc);kt.extend(hc);function fa(i,e,t=!1){try{return Ac(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw pa(i,e,r)}}function Ac(i){if(!kt(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return kt.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function xa(i,e,t=!1){try{return yc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw da(i,e,r)}}function yc(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 s=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",o=kt.tz(n,s,r);if(!o.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return o.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 Aa=i=>kt(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var jg=new $e,vr=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(c,u)=>{switch(c){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";case"object":return typeof u=="object";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 u of e)if(!r(u)){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 s=c=>!(!c||typeof c!="object"||!("data"in c));if(i.type?.name==="audio"){let c;if(Array.isArray(e)){for(let u of e)if(!s(u)){c="object ({ data: string; format?: string })";break}}else s(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 o=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let u="data"in c,p="fileUri"in c;return!(!u&&!p||u&&p)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let u of e)if(!o(u)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else o(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 u of e)if(!a(u)){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 kn(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 s=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};s.promptTokens+=t?.tokens?.promptTokens??0,s.completionTokens+=t?.tokens?.completionTokens??0,s.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=s;let o=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(o.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(o.push(c),l.add(c.url));r.citations=o}}}return Object.values(e)}var ya=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
204
- `),r=[];for(let s of n){let o=s.trim();if(o){if(o[0]&&e.has(o[0]))r.push(o.slice(1).trim());else if(t.test(o))r.push(o.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 io(i,e){let{index:t,delta:n,version:r}=e,s=i.find(a=>a.index===t)?.delta;if(!s)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=s[a],c=n[a];l===void 0&&Array.isArray(c)?s[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?s[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?s[a]=`${l??""}${c}`:s[a]=c}let o=i.find(a=>a.index===t);return o&&(o.version=r),i}var oo=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)}},bc=new oo(500);function ba(i,e,t=0,n=bc){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 s=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,s);let o=-1;for(let a=s.length-1;a>=0;a--){let l=s[a];if(i.endsWith(l)){o=a;break}}return o>=0?-2:-1}function Ct(i,e){if(typeof i!="string")throw ro(e,String(i),"URL must be a string");try{new URL(i)}catch{throw ro(e,i,"Invalid URL format. Expected a valid URL like https://example.com")}}function Ve(i,e){if(typeof i!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&i.length<t.minLength)throw Dt(e,i,"minLength",t.minLength);if(t.maxLength!==void 0&&i.length>t.maxLength)throw Dt(e,i,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(i))throw Dt(e,i,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw Dt(e,i,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(i)}catch{throw Dt(e,i,"format","valid URL")}}}function Je(i,e){if(typeof i!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&i<t.minimum)throw so(e,i,"minimum",t.minimum);if(t.maximum!==void 0&&i>t.maximum)throw so(e,i,"maximum",t.maximum)}}var Or=(i,e,t,n)=>{let r=n?.strictMode??!1,s=n?.treatAllFieldsOptional??!1,o=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};co(i,e,a,t,{strictMode:r,skipEarlyFail:o,treatAllFieldsOptional:s}),uo(i,e,a,t,{strictMode:r,treatAllFieldsOptional:s,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},ao=(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 aa(n)},co=(i,e,t,n,{strictMode:r,skipEarlyFail:s}={})=>{let o=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=o.map((h,g)=>({field:h,index:g})).filter(({index:h})=>!l.has(h)),u,p,d=-1,m=0;for(let{index:h,field:g}of c){let y=`${(t.extractedFields.length===0?"":`
205
- `)+g.title}:`,x=ba(n,y,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=y.length,u=h,p=g)}if(d===-1){if(s)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&o.length===1){t.inAssumedField=!0,t.currField=o[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(o[0])||t.extractedFields.push(o[0]),t.streamedIndex[o[0].name]===void 0&&(t.streamedIndex[o[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let h=o.find(g=>!g.isOptional);if(h)throw Rr(h)}break}if(a&&p&&a.name!==p.name)throw Rr(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let h=n.substring(t.s,d).trim(),g=Sr(t.currField,h);g!==void 0&&(e[t.currField.name]=g),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,p!==void 0&&u!==void 0&&(t.currField=p,t.currFieldIndex=u),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},uo=(i,e,t,n,r)=>{let s=r?.strictMode??!1,o=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=i.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let h=`
206
- ${m.title}:`,g=n.indexOf(h,t.s);g!==-1&&g<c&&(c=g)}let p=n.substring(t.s,c).trim(),d=Sr(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(s&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw Rr(p)}if(Ic(i,e,n,t),!o){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;s||l?ao(t,e,i.getOutputFields()):c||ao(t,e,i.getOutputFields())}},Ic=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let o=r[0];if(o){let a=`${o.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
207
- ${o.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=Sr(o,d);if(m!==void 0){e[o.name]=m;return}}catch{}}}}let s=t.split(`
208
- `);for(let o of r){if(o.name in e)continue;let a=`${o.title}:`;for(let l of s){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let p=Sr(o,u);if(p!==void 0){e[o.name]=p;break}}catch(p){if(!o.isOptional)throw p}break}}}},Ia=(i,e,t=!1)=>{switch(i.type?.name){case"code":return lo(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 fa(i,e,t);case"datetime":return xa(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*Ta(i,e,t,n,r,s){let{name:o,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[o]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let g=p?h.trimStart():h;r.currField?.type?.name==="code"&&(g=g.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),g.length>0&&(yield{index:s,delta:{[o]:g}},r.streamedIndex[o]=u+h.length)}function*po(i,e,t,n,r){for(let o of n.prevFields??[]){let{field:a,s:l,e:c}=o;yield*Ta(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*Ta(e,n.currField,n.s,e.length,n,r);let s=i.getOutputFields();for(let o of Object.keys(t)){let a=s.find(u=>u.name===o);if(!a||a.isInternal)continue;let l=t[o];if(Array.isArray(l)){let u=n.streamedIndex?.[o]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[o]:p}},n.streamedIndex[o]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[o])yield{index:r,delta:{[o]:l}},n.streamedIndex[o]=c?c.length:1;else if(c){let u=n.streamedIndex[o];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[o]:p}},n.streamedIndex[o]=c.length}}}}function Sr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw wr(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=lo(e);return t=JSON.parse(r),t}catch(r){throw la(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=ya(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ca(i,r.message)}try{if(Array.isArray(t)){for(let[r,s]of t.entries())if(s!==void 0){let o=typeof s=="string"?s.trim():s;if(typeof o=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=lo(o);o=JSON.parse(a)}catch{}t[r]=Ia(i,o,!0)}}else t=Ia(i,e)}catch(r){throw ua(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&Ct(t,i),(n.name==="string"||n.name==="code")&&Ve(t,i),n.name==="number"&&Je(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Ve(r,i):n.name==="number"&&Je(r,i));return t}function Ut(i,e,t){let n=i.getOutputFields();for(let r of n){let s=e[r.name];if(s==null){if(!r.isOptional&&!t?.allowMissingRequired)throw wr(r);continue}let o=r.type;if(o){if(o.name==="url"&&Ct(s,r),(o.name==="string"||o.name==="code")&&Ve(s,r),o.name==="number"&&Je(s,r),o.isArray&&Array.isArray(s))for(let a of s)a!=null&&(o.name==="url"?Ct(a,r):o.name==="string"||o.name==="code"?Ve(a,r):o.name==="number"&&Je(a,r));if(o.name==="object"&&o.fields&&typeof s=="object"&&!Array.isArray(s)&&kr(r,s,t),o.isArray&&o.fields&&Array.isArray(s)&&o.name==="object")for(let a of s)a&&typeof a=="object"&&kr(r,a,t)}}}function kr(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,s]of Object.entries(n)){let o={name:r,title:r,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional??!1,isInternal:s.isInternal??!1},a=e[o.name];if(a==null){if(!o.isOptional&&!t?.allowMissingRequired)throw wr(o);continue}let l=o.type;if(l){if(l.name==="url"&&Ct(a,o),(l.name==="string"||l.name==="code")&&Ve(a,o),l.name==="number"&&Je(a,o),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?Ct(c,o):l.name==="string"||l.name==="code"?Ve(c,o):l.name==="number"&&Je(c,o));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&kr(o,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&kr(o,c,t)}}}var lo=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function On(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let s=r.process,o=await s(e[r.field.name],{sessionId:n,values:e,done:!0});Ca(r.field,t,o,n)}}async function mo(i,e,t,n,r,s,o=!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,u=await c(l,{sessionId:s,values:r,done:o});Ca(t.currField,n,u,s)}}var Ca=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(o,a)=>typeof a=="bigint"?Number(a):a,2),s=Tc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:s}]}],n),e.addTag("processor",n)};function Tc(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}`}function Ra(i,e){if(!e)return i;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return i;let n=t.join(". ");return!i||i.trim().length===0?n:`${i.trim().endsWith(".")?i.trim():`${i.trim()}.`} ${n}`}function Mn(i,e="Schema"){if("name"in i&&"type"in i)return Mr(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let s=Mr(r);t[r.name]=s,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Mr(i,e=!1){let t=i.type,n=Ra(i.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${i.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[s,o]of Object.entries(t.fields)){let a={name:s,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional,isInternal:o.isInternal};r.items.properties[s]=Mr(a,!0),o.isOptional||r.items.required.push(s)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let s=Ra(t.description||i.description,t);r.items={type:wa(t.name)},s&&(r.items.description=s),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[s,o]of Object.entries(t.fields)){let a={name:s,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional,isInternal:o.isInternal};r.properties[s]=Mr(a,!0),o.isOptional||r.required.push(s)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=wa(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function wa(i){switch(i){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function Pr(i){if(!i||typeof i!="object")throw new Error("Schema must be an object");if(i.type==="array"){if(!i.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');Pr(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))Pr(e)}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}},Er=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
209
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Pn=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}'
203
+ `,s=l}),(s>t||n.length===0)&&n.push(r.trim()),n},uc=(i,e=.1)=>{let t=[...i].sort((r,s)=>r.score-s.score),n=Math.ceil(t.length*e);return t.slice(0,n)};import{context as Hc,SpanKind as Kc,trace as Wc}from"@opentelemetry/api";var vn=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,...s})=>({index:r,value:structuredClone(s)})),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,thoughtBlocks:s,index:o}){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:o,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})}]});return}let l=a.chat.find(c=>c.index===o);if(!l){a.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n,thought:r,thoughtBlocks:s})});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(Array.isArray(s)&&s.length>0){let c=l.value.thoughtBlocks??[];for(let u of s){let p=c.length>0?c[c.length-1]:void 0;!u.signature&&u.data?p&&!p.signature?(p.data=(p.data??"")+u.data,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):u.signature?p&&!p.signature?(p.data=(p.data??"")+u.data,p.signature=u.signature,u.encrypted&&(p.encrypted=!0)):c.push(structuredClone(u)):c.length===0&&c.push(structuredClone(u))}l.value.thoughtBlocks=c,c.length>0&&(l.value.thought=c.map(u=>u.data).join(""))}}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,s)=>(r.tags?.includes(e)&&n.push(s),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 s;n==="function"?s=r.filter(o=>o.index===e).map(o=>o.value):s=r.find(o=>o.index===e)?.value,Array.isArray(s)&&s.length>0?t.push(...s.map(o=>({...o,role:n}))):typeof s=="object"&&s!==null&&t.push({...s,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[],this.seenTags=new Set}},Sn=class{memories=new Map;defaultMemory;constructor(){this.defaultMemory=new vn}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new vn),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)en(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){ds(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 vn):this.defaultMemory.reset()}};var mt=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}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()}},Gt=async(i,e)=>{for(let t of i){let{fn:n,message:r}=t,s=await n(e);if(s!==void 0){if(typeof s=="string")throw new mt({message:s});if(!s)throw r?new mt({message:r}):new Error("Assertion Failed: No message provided for assertion")}}},eo=async(i,e,t,n=!1)=>{if(!e.currField||e.s===-1||!i||i.length===0)return;let r=i.filter(o=>o.fieldName===e.currField?.name);if(r.length===0)return;let s=t.substring(e.s);for(let o of r){let{message:a,fn:l}=o,c=await l(s,n);if(c!==void 0){if(typeof c=="string")throw new mt({message:c});if(!c&&a)throw new mt({message:a})}}};var ea={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},kn,to=i=>{if(kn)return kn;let e=i??Z.meter;if(e)return kn=dc(e),kn};var pc=()=>{let i=[];return Z.meter||i.push("Global meter not initialized"),!kn&&Z.meter&&i.push("Metrics instruments not created despite available meter"),{healthy:i.length===0,issues:i}},dc=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"})}),Tr=ea,mc=i=>{Tr={...Tr,...i}},gc=()=>({...Tr}),rt=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),s=Tr.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e};var ta=(i,e,t,n,r,s,o)=>{try{let a=rt({success:t.toString(),...n?{signature:n}:{},...r?{ai_service:r}:{},...s?{model:s}:{},...o});i.generationLatencyHistogram&&i.generationLatencyHistogram.record(e,a),i.generationRequestsCounter&&i.generationRequestsCounter.add(1,a),!t&&i.generationErrorsCounter&&i.generationErrorsCounter.add(1,a)}catch(a){console.warn("Failed to record generation metric:",a)}},Cr=(i,e,t,n,r)=>{try{let s=rt({...n?{signature:n}:{},...r});e>1&&i.multiStepGenerationsCounter&&i.multiStepGenerationsCounter.add(1,s),i.stepsPerGenerationHistogram&&i.stepsPerGenerationHistogram.record(e,s),e>=t&&i.maxStepsReachedCounter&&i.maxStepsReachedCounter.add(1,s)}catch(s){console.warn("Failed to record multi-step metric:",s)}},no=(i,e,t,n)=>{try{let r=rt({error_type:e,...t?{signature:t}:{},...n});e==="validation"&&i.validationErrorsCounter&&i.validationErrorsCounter.add(1,r),e==="assertion"&&i.assertionErrorsCounter&&i.assertionErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record validation error metric:",r)}},na=(i,e,t)=>{try{let n=rt({error_type:"refusal",...e?{signature:e}:{},...t});i.validationErrorsCounter&&i.validationErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record refusal error metric:",n)}},ro=(i,e,t,n,r,s)=>{try{let o=rt({success:t.toString(),...r?{signature:r}:{},...s});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)}},ra=(i,e,t,n,r=!1,s,o)=>{try{let a=rt({functions_enabled:e.toString(),had_function_calls:n.toString(),...s?{signature:s}:{},...o});e&&i.functionsEnabledGenerationsCounter&&i.functionsEnabledGenerationsCounter.add(1,a),n&&i.functionCallStepsCounter&&i.functionCallStepsCounter.add(1,a),t>0&&i.functionsExecutedPerGenerationHistogram&&i.functionsExecutedPerGenerationHistogram.record(t,a),r&&i.functionErrorCorrectionCounter&&i.functionErrorCorrectionCounter.add(1,a)}catch(a){console.warn("Failed to record function calling metric:",a)}},sa=(i,e,t,n,r)=>{try{let s=rt({...n?{signature:n}:{},...r});e>0&&i.fieldProcessorsExecutedCounter&&i.fieldProcessorsExecutedCounter.add(e,s),t>0&&i.streamingFieldProcessorsExecutedCounter&&i.streamingFieldProcessorsExecutedCounter.add(t,s)}catch(s){console.warn("Failed to record field processing metric:",s)}},oa=(i,e,t,n,r,s)=>{try{let o=rt({is_streaming:e.toString(),...r?{signature:r}:{},...s});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)}},ia=(i,e,t,n,r,s)=>{try{let o=rt({result_picker_used:t.toString(),...r?{signature:r}:{},...s});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)}},aa=(i,e,t,n,r,s,o)=>{try{let a=rt({...s?{signature:s}:{},...o});i.inputFieldsGauge&&i.inputFieldsGauge.record(e,a),i.outputFieldsGauge&&i.outputFieldsGauge.record(t,a),i.examplesUsedGauge&&i.examplesUsedGauge.record(n,a),i.demosUsedGauge&&i.demosUsedGauge.record(r,a)}catch(a){console.warn("Failed to record signature complexity metrics:",a)}},Rr=(i,e,t,n,r)=>{try{let s=rt({metric_type:e,...n?{signature:n}:{},...r});switch(e){case"prompt_render":i.promptRenderLatencyHistogram&&i.promptRenderLatencyHistogram.record(t,s);break;case"extraction":i.extractionLatencyHistogram&&i.extractionLatencyHistogram.record(t,s);break;case"assertion":i.assertionLatencyHistogram&&i.assertionLatencyHistogram.record(t,s);break;case"state_creation":i.stateCreationLatencyHistogram&&i.stateCreationLatencyHistogram.record(t,s);break;case"memory_update":i.memoryUpdateLatencyHistogram&&i.memoryUpdateLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record performance metric:",s)}};var Dt=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";case"object":return"object";default:return"string"}})();return i?.isArray?`array of ${e}s`:e},ke=class extends Error{constructor(e){super(e),this.name="ValidationError"}getFixingInstructions=()=>[{name:"outputError",title:"Invalid Field",description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},la=i=>{let t=i.map(n=>`'${n.title}' (${Dt(n.type)})`).join(", ");return new ke(`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 ${Dt(i[0]?.type)} value. Keep the output concise and avoid unrelated text.`)},wr=i=>new ke(`Expected (Required) field not found: '${i.title}'. Begin a new section with "${i.title}:" and then provide a valid ${Dt(i.type)} value directly after.`);var vr=i=>new ke(`Required field is missing: '${i.title}'. After the "${i.title}:" label, provide a non-empty ${Dt(i.type)}. Do not use null, undefined, or leave it blank.`),ca=(i,e)=>new ke(`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.`),ua=(i,e)=>new ke(`Invalid Array: ${e} for '${i.title}'. Provide a JSON array of ${Dt(i.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),pa=(i,e,t)=>new ke(`Field '${i.title}' has an invalid value '${e}': ${t}. Provide a ${Dt(i.type)}. Ensure formatting exactly matches the expected type.`),da=(i,e,t)=>new ke(`Invalid date for '${i.title}': ${t}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${e}.`),ma=(i,e,t)=>new ke(`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}.`),so=(i,e,t)=>new ke(`Invalid URL for '${i.title}': ${t}. Use a valid URL format (e.g., https://example.com). You provided: ${e}.`),Ut=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minLength"?r+=`String must be at least ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="maxLength"?r+=`String must be at most ${n} characters long. You provided: "${e}" (${e.length} characters).`:t==="pattern"?r+=`String must match pattern /${n}/. You provided: "${e}".`:t==="format"&&(r+=`String must be a ${n}. You provided: "${e}".`),new ke(r)},oo=(i,e,t,n)=>{let r=`Field '${i.title}' failed validation: `;return t==="minimum"?r+=`Number must be at least ${n}. You provided: ${e}.`:t==="maximum"&&(r+=`Number must be at most ${n}. You provided: ${e}.`),new ke(r)};var ga=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";ii(i,e,c,n)}return r&&no(r,"validation",s,a),o&&o.addEvent("validation.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},ha=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{let l=i.getFixingInstructions();if(t&&n){let c=l?.map(u=>u.title).join(", ")??"";ai(i,e,c,n)}return r&&no(r,"assertion",s,a),o&&o.addEvent("assertion.error",{message:i.toString(),fixing_instructions:l?.map(c=>c.title).join(", ")??""}),l},fa=({error:i,errCount:e,debug:t,logger:n,metricsInstruments:r,signatureName:s,span:o,customLabels:a})=>{t&&n&&li(i,e,n),r&&na(r,s,a),o&&o.addEvent("refusal.error",{message:i.toString()})};import kt from"dayjs";import hc from"dayjs/plugin/customParseFormat.js";import fc from"dayjs/plugin/timezone.js";import xc from"dayjs/plugin/utc.js";kt.extend(xc);kt.extend(fc);kt.extend(hc);function xa(i,e,t=!1){try{return Ac(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw da(i,e,r)}}function Ac(i){if(!kt(i,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return kt.utc(i,"YYYY-MM-DD").startOf("day").toDate()}function Aa(i,e,t=!1){try{return yc(e)}catch(n){if(i.isOptional&&!t)return;let r=n.message;throw ma(i,e,r)}}function yc(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 s=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",o=kt.tz(n,s,r);if(!o.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return o.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 ya=i=>kt(i).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var qg=new $e,Sr=(i,e)=>{let t=i.type??{name:"string",isArray:!1},n=(c,u)=>{switch(c){case"class":return typeof u=="string";case"code":return typeof u=="string";case"string":return typeof u=="string";case"number":return typeof u=="number";case"boolean":return typeof u=="boolean";case"date":return u instanceof Date||typeof u=="string";case"datetime":return u instanceof Date||typeof u=="string";case"json":return typeof u=="object"||typeof u=="string";case"object":return typeof u=="object";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 u of e)if(!r(u)){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 s=c=>!(!c||typeof c!="object"||!("data"in c));if(i.type?.name==="audio"){let c;if(Array.isArray(e)){for(let u of e)if(!s(u)){c="object ({ data: string; format?: string })";break}}else s(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 o=c=>{if(!c||typeof c!="object"||!("mimeType"in c))return!1;let u="data"in c,p="fileUri"in c;return!(!u&&!p||u&&p)};if(i.type?.name==="file"){let c;if(Array.isArray(e)){for(let u of e)if(!o(u)){c="object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })";break}}else o(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 u of e)if(!a(u)){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 s=r.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};s.promptTokens+=t?.tokens?.promptTokens??0,s.completionTokens+=t?.tokens?.completionTokens??0,s.totalTokens+=t?.tokens?.totalTokens??0,r.tokens=s;let o=r.citations??[],a=t.citations??[];if(a.length){let l=new Set(o.map(c=>c.url));for(let c of a)c?.url&&!l.has(c.url)&&(o.push(c),l.add(c.url));r.citations=o}}}return Object.values(e)}var ba=i=>{if(!i.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=i.split(`
204
+ `),r=[];for(let s of n){let o=s.trim();if(o){if(o[0]&&e.has(o[0]))r.push(o.slice(1).trim());else if(t.test(o))r.push(o.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 ao(i,e){let{index:t,delta:n,version:r}=e,s=i.find(a=>a.index===t)?.delta;if(!s)return i.push({index:t,delta:n,version:r}),i;for(let a of Object.keys(n)){let l=s[a],c=n[a];l===void 0&&Array.isArray(c)?s[a]=[...c]:Array.isArray(l)&&Array.isArray(c)?s[a]=[...l,...c]:(l===void 0||typeof l=="string")&&typeof c=="string"?s[a]=`${l??""}${c}`:s[a]=c}let o=i.find(a=>a.index===t);return o&&(o.version=r),i}var io=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)}},bc=new io(500);function Ia(i,e,t=0,n=bc){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 s=n.get(e)??Array.from({length:e.length},(a,l)=>e.slice(0,l+1));n.get(e)||n.set(e,s);let o=-1;for(let a=s.length-1;a>=0;a--){let l=s[a];if(i.endsWith(l)){o=a;break}}return o>=0?-2:-1}function Ct(i,e){if(typeof i!="string")throw so(e,String(i),"URL must be a string");try{new URL(i)}catch{throw so(e,i,"Invalid URL format. Expected a valid URL like https://example.com")}}function Ve(i,e){if(typeof i!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&i.length<t.minLength)throw Ut(e,i,"minLength",t.minLength);if(t.maxLength!==void 0&&i.length>t.maxLength)throw Ut(e,i,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(i))throw Ut(e,i,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i))throw Ut(e,i,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(i)}catch{throw Ut(e,i,"format","valid URL")}}}function Je(i,e){if(typeof i!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&i<t.minimum)throw oo(e,i,"minimum",t.minimum);if(t.maximum!==void 0&&i>t.maximum)throw oo(e,i,"maximum",t.maximum)}}var Mr=(i,e,t,n)=>{let r=n?.strictMode??!1,s=n?.treatAllFieldsOptional??!1,o=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};uo(i,e,a,t,{strictMode:r,skipEarlyFail:o,treatAllFieldsOptional:s}),po(i,e,a,t,{strictMode:r,treatAllFieldsOptional:s,forceFinalize:!0});for(let l of i.getOutputFields())l.isInternal&&delete e[l.name]},lo=(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 la(n)},uo=(i,e,t,n,{strictMode:r,skipEarlyFail:s}={})=>{let o=i.getOutputFields(),a;for(;;){let l=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&l.add(t.currFieldIndex);let c=o.map((h,g)=>({field:h,index:g})).filter(({index:h})=>!l.has(h)),u,p,d=-1,m=0;for(let{index:h,field:g}of c){let y=`${(t.extractedFields.length===0?"":`
205
+ `)+g.title}:`,x=Ia(n,y,t.s);if(x===-2||x===-3)return!0;if(x===-4)return t.inBlock=!0,!0;x>=0&&(d===-1||x<d)&&(d=x,m=y.length,u=h,p=g)}if(d===-1){if(s)return;if(!r&&t.currField===void 0&&t.extractedFields.length===0&&o.length===1){t.inAssumedField=!0,t.currField=o[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(o[0])||t.extractedFields.push(o[0]),t.streamedIndex[o[0].name]===void 0&&(t.streamedIndex[o[0].name]=0);return}if(r&&t.currField===void 0&&t.extractedFields.length===0){let h=o.find(g=>!g.isOptional);if(h)throw wr(h)}break}if(a&&p&&a.name!==p.name)throw wr(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let h=n.substring(t.s,d).trim(),g=kr(t.currField,h);g!==void 0&&(e[t.currField.name]=g),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,p!==void 0&&u!==void 0&&(t.currField=p,t.currFieldIndex=u),p&&!t.extractedFields.includes(p)&&t.extractedFields.push(p),p&&t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},po=(i,e,t,n,r)=>{let s=r?.strictMode??!1,o=r?.treatAllFieldsOptional??!1,a=r?.deferRequiredCheckForStreaming??!1,l=r?.forceFinalize??!1;if(t.currField){let c=n.length,u=i.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let h=`
206
+ ${m.title}:`,g=n.indexOf(h,t.s);g!==-1&&g<c&&(c=g)}let p=n.substring(t.s,c).trim(),d=kr(t.currField,p);d!==void 0&&(e[t.currField.name]=d)}if(s&&!t.currField&&t.extractedFields.length===0&&n.trim()){let p=i.getOutputFields().find(d=>!d.isOptional);if(p)throw wr(p)}if(Ic(i,e,n,t),!o){let c=t.currField!==void 0||(t.extractedFields?.length??0)>0;s||l?lo(t,e,i.getOutputFields()):c||lo(t,e,i.getOutputFields())}},Ic=(i,e,t,n)=>{let r=i.getOutputFields();if(r.length===1){let o=r[0];if(o){let a=`${o.title}:`,l=t.indexOf(a);if(l!==-1){let c=l+a.length,u=`
207
+ ${o.title}:`,p=t.indexOf(u,c),d=t.substring(c,p===-1?t.length:p).trim();if(d)try{let m=kr(o,d);if(m!==void 0){e[o.name]=m;return}}catch{}}}}let s=t.split(`
208
+ `);for(let o of r){if(o.name in e)continue;let a=`${o.title}:`;for(let l of s){let c=l.trim();if(c.startsWith(a)){let u=c.substring(a.length).trim();if(u)try{let p=kr(o,u);if(p!==void 0){e[o.name]=p;break}}catch(p){if(!o.isOptional)throw p}break}}}},Ta=(i,e,t=!1)=>{switch(i.type?.name){case"code":return co(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 xa(i,e,t);case"datetime":return Aa(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*Ca(i,e,t,n,r,s){let{name:o,isInternal:a}=e,{isArray:l,name:c}=e.type??{};if(a||l||c&&c!=="string"&&c!=="code")return;let u=r.streamedIndex[o]??0,p=u===0,d=(t<0?0:t)+u,m=i.substring(d,n);if(m.length===0)return;let h=m.replace(/\s+$/,"");r.currField?.type?.name==="code"&&(h=h.replace(/\s*```\s*$/,""));let g=p?h.trimStart():h;r.currField?.type?.name==="code"&&(g=g.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),g.length>0&&(yield{index:s,delta:{[o]:g}},r.streamedIndex[o]=u+h.length)}function*mo(i,e,t,n,r){for(let o of n.prevFields??[]){let{field:a,s:l,e:c}=o;yield*Ca(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*Ca(e,n.currField,n.s,e.length,n,r);let s=i.getOutputFields();for(let o of Object.keys(t)){let a=s.find(u=>u.name===o);if(!a||a.isInternal)continue;let l=t[o];if(Array.isArray(l)){let u=n.streamedIndex?.[o]??0,p=l.slice(u);p&&p.length>0&&(yield{index:r,delta:{[o]:p}},n.streamedIndex[o]=u+p.length);continue}let c=typeof l=="string"?l:void 0;if(!n.streamedIndex[o])yield{index:r,delta:{[o]:l}},n.streamedIndex[o]=c?c.length:1;else if(c){let u=n.streamedIndex[o];if(c.length>u){let p=c.substring(u);yield{index:r,delta:{[o]:p}},n.streamedIndex[o]=c.length}}}}function kr(i,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(i.isOptional)return;throw vr(i)}let t;if(i.type?.name==="json"&&!i.type?.isArray)try{let r=co(e);return t=JSON.parse(r),t}catch(r){throw ca(i,r.message)}if(i.type?.isArray)try{try{t=JSON.parse(e)}catch{t=ba(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(r){throw ua(i,r.message)}try{if(Array.isArray(t)){for(let[r,s]of t.entries())if(s!==void 0){let o=typeof s=="string"?s.trim():s;if(typeof o=="string"&&(i.type?.name==="object"||i.type?.name==="json"))try{let a=co(o);o=JSON.parse(a)}catch{}t[r]=Ta(i,o,!0)}}else t=Ta(i,e)}catch(r){throw pa(i,e,r.message)}if(typeof t=="string"&&t==="")return;let n=i.type;if(n&&t!==void 0&&(n.name==="url"&&Ct(t,i),(n.name==="string"||n.name==="code")&&Ve(t,i),n.name==="number"&&Je(t,i),n.isArray&&Array.isArray(t)))for(let r of t)r!==void 0&&(n.name==="string"||n.name==="code"?Ve(r,i):n.name==="number"&&Je(r,i));return t}function Bt(i,e,t){let n=i.getOutputFields();for(let r of n){let s=e[r.name];if(s==null){if(!r.isOptional&&!t?.allowMissingRequired)throw vr(r);continue}let o=r.type;if(o){if(o.name==="url"&&Ct(s,r),(o.name==="string"||o.name==="code")&&Ve(s,r),o.name==="number"&&Je(s,r),o.isArray&&Array.isArray(s))for(let a of s)a!=null&&(o.name==="url"?Ct(a,r):o.name==="string"||o.name==="code"?Ve(a,r):o.name==="number"&&Je(a,r));if(o.name==="object"&&o.fields&&typeof s=="object"&&!Array.isArray(s)&&Or(r,s,t),o.isArray&&o.fields&&Array.isArray(s)&&o.name==="object")for(let a of s)a&&typeof a=="object"&&Or(r,a,t)}}}function Or(i,e,t){let n=i.type?.fields;if(!(!n||typeof n!="object"))for(let[r,s]of Object.entries(n)){let o={name:r,title:r,description:s.description,type:{name:s.type,isArray:s.isArray,options:s.options,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,patternDescription:s.patternDescription,format:s.format},isOptional:s.isOptional??!1,isInternal:s.isInternal??!1},a=e[o.name];if(a==null){if(!o.isOptional&&!t?.allowMissingRequired)throw vr(o);continue}let l=o.type;if(l){if(l.name==="url"&&Ct(a,o),(l.name==="string"||l.name==="code")&&Ve(a,o),l.name==="number"&&Je(a,o),l.isArray&&Array.isArray(a))for(let c of a)c!=null&&(l.name==="url"?Ct(c,o):l.name==="string"||l.name==="code"?Ve(c,o):l.name==="number"&&Je(c,o));if(l.name==="object"&&l.fields&&typeof a=="object"&&!Array.isArray(a)&&Or(o,a,t),l.isArray&&l.fields&&Array.isArray(a)&&l.name==="object")for(let c of a)c&&typeof c=="object"&&Or(o,c,t)}}}var co=i=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(i);return t?t.length===3?t[2]:t.length===2?t[1]:i:i};async function Mn(i,e,t,n){for(let r of i){if(e[r.field.name]===void 0)continue;let s=r.process,o=await s(e[r.field.name],{sessionId:n,values:e,done:!0});Ra(r.field,t,o,n)}}async function go(i,e,t,n,r,s,o=!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,u=await c(l,{sessionId:s,values:r,done:o});Ra(t.currField,n,u,s)}}var Ra=(i,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let r=JSON.stringify(t,(o,a)=>typeof a=="bigint"?Number(a):a,2),s=Tc(i,r);e.addRequest([{role:"user",content:[{type:"text",text:s}]}],n),e.addTag("processor",n)};function Tc(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}`}function wa(i,e){if(!e)return i;let t=[];if(e.format==="email"&&t.push("Must be a valid email address format"),(e.format==="uri"||e.format==="url"||e.name==="url")&&t.push("Must be a valid URL format"),(e.name==="string"||e.name==="code"||e.name==="url"||e.name==="date"||e.name==="datetime")&&(e.minLength!==void 0&&e.maxLength!==void 0?t.push(`Minimum length: ${e.minLength} characters, maximum length: ${e.maxLength} characters`):e.minLength!==void 0?t.push(`Minimum length: ${e.minLength} characters`):e.maxLength!==void 0&&t.push(`Maximum length: ${e.maxLength} characters`)),e.name==="number"&&(e.minimum!==void 0&&e.maximum!==void 0?t.push(`Minimum value: ${e.minimum}, maximum value: ${e.maximum}`):e.minimum!==void 0?t.push(`Minimum value: ${e.minimum}`):e.maximum!==void 0&&t.push(`Maximum value: ${e.maximum}`)),e.pattern!==void 0){if(!e.patternDescription)throw new Error(`Field with pattern '${e.pattern}' must include a patternDescription to explain the pattern to the LLM`);t.push(e.patternDescription)}if(e.name==="date"&&t.push("Format: YYYY-MM-DD"),e.name==="datetime"&&t.push("Format: ISO 8601 date-time"),t.length===0)return i;let n=t.join(". ");return!i||i.trim().length===0?n:`${i.trim().endsWith(".")?i.trim():`${i.trim()}.`} ${n}`}function Pn(i,e="Schema"){if("name"in i&&"type"in i)return Pr(i);let t={},n=[];for(let r of i){if(r.isInternal)continue;let s=Pr(r);t[r.name]=s,r.isOptional||n.push(r.name)}return{type:"object",title:e,properties:t,required:n,additionalProperties:!1}}function Pr(i,e=!1){let t=i.type,n=wa(i.description,t);if(e&&t?.name&&(t.name==="image"||t.name==="audio"||t.name==="file"))throw new Error(`Media type '${t.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level input fields. Field: ${i.name}`);let r={};if(n&&(r.description=n),t?.isArray)if(r.type="array",t.fields){r.items={type:"object",properties:{},required:[],additionalProperties:!1},t.description&&(r.items.description=t.description);for(let[s,o]of Object.entries(t.fields)){let a={name:s,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional,isInternal:o.isInternal};r.items.properties[s]=Pr(a,!0),o.isOptional||r.items.required.push(s)}}else if(t.name==="class"&&t.options)r.items={type:"string",enum:t.options};else{let s=wa(t.description||i.description,t);r.items={type:va(t.name)},s&&(r.items.description=s),t.name==="string"||t.name==="code"||t.name==="url"||t.name==="date"||t.name==="datetime"?(t.minLength!==void 0&&(r.items.minLength=t.minLength),t.maxLength!==void 0&&(r.items.maxLength=t.maxLength),t.pattern!==void 0&&(r.items.pattern=t.pattern),t.format!==void 0&&(r.items.format=t.format)):t.name==="number"&&(t.minimum!==void 0&&(r.items.minimum=t.minimum),t.maximum!==void 0&&(r.items.maximum=t.maximum))}else if(t?.name==="object"&&t.fields){r.type="object",r.properties={},r.required=[],r.additionalProperties=!1;for(let[s,o]of Object.entries(t.fields)){let a={name:s,description:o.description,type:{name:o.type,isArray:o.isArray,options:o.options?[...o.options]:void 0,fields:o.fields,minLength:o.minLength,maxLength:o.maxLength,minimum:o.minimum,maximum:o.maximum,pattern:o.pattern,patternDescription:o.patternDescription,format:o.format},isOptional:o.isOptional,isInternal:o.isInternal};r.properties[s]=Pr(a,!0),o.isOptional||r.required.push(s)}}else t?.name==="class"&&t.options?(r.type="string",r.enum=t.options):(r.type=va(t?.name??"string"),t?.name==="string"||t?.name==="code"||t?.name==="url"||t?.name==="date"||t?.name==="datetime"?(t.minLength!==void 0&&(r.minLength=t.minLength),t.maxLength!==void 0&&(r.maxLength=t.maxLength),t.pattern!==void 0&&(r.pattern=t.pattern),t.format!==void 0&&(r.format=t.format),t.name==="url"&&!t.format&&(r.format="uri"),t.name==="date"&&!t.format&&(r.format="date"),t.name==="datetime"&&!t.format&&(r.format="date-time")):t?.name==="number"&&(t.minimum!==void 0&&(r.minimum=t.minimum),t.maximum!==void 0&&(r.maximum=t.maximum)));return r}function va(i){switch(i){case"string":case"code":case"url":case"date":case"datetime":case"image":case"audio":case"file":return"string";case"number":return"number";case"boolean":return"boolean";case"json":case"object":return["object","array","string","number","boolean","null"];default:return"string"}}function Er(i){if(!i||typeof i!="object")throw new Error("Schema must be an object");if(i.type==="array"){if(!i.items)throw new Error('Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)');Er(i.items)}else if(i.type==="object"&&i.properties)for(let e of Object.values(i.properties))Er(e)}var jt=class extends Error{calls;constructor(e){super(`Stop function executed: ${e.map(t=>t.func.name).join(", ")}`),this.name="AxStopFunctionCallException",this.calls=e}},Fr=class extends Error{constructor(t){super();this.fields=t;this.name="AxFunctionError"}getFields=()=>this.fields;toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
209
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},En=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}'
210
210
  ${t.join(`
211
211
  `)}`};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(`
212
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Fr=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 s=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai,step:n.step}:void 0,o;e.parameters?o=e.func.length===2?await e.func(r,s):await e.func(r):o=e.func.length===1?await e.func(s):await e.func();let l=(n?.functionResultFormatter??Z.functionResultFormatter)(o);return{formatted:String(l),rawResult:o,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=o=>o.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),s=this.funcList.find(o=>o.name===e.name);if(s||(s=this.funcList.find(o=>n(o.name)===r)),!s)throw new Error(`Function not found: ${e.name}`);if(!s.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(s,e,t)}catch(o){throw o instanceof Er?new Pn(o.getFields(),s,e.id):o}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Ot=(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{Pr(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
212
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},_r=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 s=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai,step:n.step}:void 0,o;e.parameters?o=e.func.length===2?await e.func(r,s):await e.func(r):o=e.func.length===1?await e.func(s):await e.func();let l=(n?.functionResultFormatter??Z.functionResultFormatter)(o);return{formatted:String(l),rawResult:o,parsedArgs:r}};executeWithDetails=async(e,t)=>{let n=o=>o.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),r=n(e.name),s=this.funcList.find(o=>o.name===e.name);if(s||(s=this.funcList.find(o=>n(o.name)===r)),!s)throw new Error(`Function not found: ${e.name}`);if(!s.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(s,e,t)}catch(o){throw o instanceof Fr?new En(o.getFields(),s,e.id):o}};execute=async(e,t)=>(await this.executeWithDetails(e,t)).formatted},Ot=(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{Er(n.parameters)}catch(r){throw r instanceof Error?new Error(`Function '${n.name}' parameters schema is invalid.
213
213
  ${r.message}
214
- Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},_r=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:s,span:o,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d,step:m})=>{let h=new Fr(e),g=new Set,f=[],y=A=>{let I=R=>R.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),C=I(A),S=e.find(R=>R.name===A);return S||(S=e.find(R=>I(R.name)===C)),S},x=t.map(A=>{if(!A.id)throw new Error(`Function ${A.name} did not return an ID`);let I=i.getOptions().tracer??Z.tracer;return I?I.startActiveSpan(`Tool: ${A.name}`,async C=>{try{C?.setAttributes?.({"tool.name":A.name,"tool.mode":"native","function.id":A.id,"session.id":r??""});let{formatted:S,rawResult:R,parsedArgs:P}=await h.executeWithDetails(A,{sessionId:r,ai:i,functionResultFormatter:c,traceId:C?.spanContext?.().traceId??s,stopFunctionNames:d,step:m});if(g.add(A.name.toLowerCase()),m?._recordFunctionCall(A.name,P,R),d?.includes(A.name.toLowerCase())){let E=y(A.name);E&&f.push({func:E,args:P,result:R})}if(a?C.addEvent("gen_ai.tool.message",{name:A.name}):C.addEvent("gen_ai.tool.message",{name:A.name,args:A.args,result:S??""}),o){let E={name:A.name};a||(E.args=A.args,E.result=S??""),o.addEvent("function.call",E)}return{result:S??"",role:"function",functionId:A.id,index:l}}catch(S){if(C?.recordException?.(S),S instanceof Pn){let R=S.getFixingInstructions(),P={name:A.name,message:S.toString()};return a||(P.args=A.args,P.fixing_instructions=R),C?.addEvent?.("function.error",P),p&&is(S,l,R,u),{functionId:A.id,isError:!0,index:l,result:R,role:"function"}}throw S}finally{C?.end?.()}}):h.executeWithDetails(A,{sessionId:r,ai:i,functionResultFormatter:c,traceId:s,stopFunctionNames:d,step:m}).then(({formatted:C,rawResult:S,parsedArgs:R})=>{if(g.add(A.name.toLowerCase()),m?._recordFunctionCall(A.name,R,S),d?.includes(A.name.toLowerCase())){let P=y(A.name);P&&f.push({func:P,args:R,result:S})}if(o){let P={name:A.name};a||(P.args=A.args,P.result=C??""),o.addEvent("function.call",P)}return{result:C??"",role:"function",functionId:A.id,index:l}}).catch(C=>{if(!(C instanceof Pn))throw C;let S=C.getFixingInstructions();if(o){let R={name:A.name,message:C.toString()};a||(R.args=A.args,R.fixing_instructions=S),o.addEvent("function.error",R)}return p&&is(C,l,S,u),{functionId:A.id,isError:!0,index:l,result:S,role:"function"}})}),T=(await Promise.all(x)).map(A=>A.result===void 0||A.result===""?{...A,result:"done"}:A);if(n.addFunctionResults(T,r),p){let A=T.filter(I=>!I.isError);A.length>0&&si(A,u)}if(f.length>0)throw new Bt(f);return g};function go(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(s=>({id:s.id,name:s.function.name,args:s.function.params}))}function va(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(o=>"toFunction"in o?o.toFunction():o).flat(),functionCall:r}:{functions:[],functionCall:r}}function Cc(i){let e=0,t=!1,n=!1,r=!1,s=!1,o=[];for(let a=0;a<i.length;a++){let l=i[a];if(n){n=!1;continue}if(l==="\\"){n=!0;continue}if(l==='"'){t=!t;continue}t||(l==="{"?(o.push("{"),e++):l==="["?(o.push("["),e++):l==="}"?o.length>0&&o[o.length-1]==="{"&&(o.pop(),e--):l==="]"&&o.length>0&&o[o.length-1]==="["&&(o.pop(),e--))}if(o.length>0){let a=o[o.length-1];r=a==="[",s=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:s}}function Sa(i){if(!i.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(i),partialMarker:null}}catch{}let e=Cc(i),t=Rc(i);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Rc(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1)),e.match(/,\s*"[^"]*"\s*:\s*$/)?e=e.replace(/,\s*"[^"]*"\s*:\s*$/,""):e.match(/\{\s*"[^"]*"\s*:\s*$/)&&(e=e.replace(/"[^"]*"\s*:\s*$/,""));e.match(/[0-9][eE.+-]$/)||e.match(/[eE][+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r){r=!1;continue}if(o==="\\"){r=!0;continue}if(o==='"'){n=!n;continue}n||(o==="{"?t.push("}"):o==="["?t.push("]"):o==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():o==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}async function*ka({res:i,usage:e,states:t,debug:n,stepContext:r,...s}){let o=(s.ai.getFeatures().functionCot??!1)&&s.functions!==void 0&&s.functions.length>0,a,l=[],c=i.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;let d=p;d.modelUsage&&(a=d.modelUsage);for(let m of d.results){if(Array.isArray(m.citations))for(let g of m.citations)g?.url&&l.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!m.content||m.content==="")&&(!m.thought||m.thought==="")&&(!m.thoughtBlocks||m.thoughtBlocks.length===0)&&(!m.functionCalls||m.functionCalls.length===0))continue;let h=t.find(g=>g.index===m.index);if(!h)throw new Error(`No state found for result (index: ${m.index})`);yield*wc({...s,result:m,skipEarlyFail:o,state:h,debug:n})}}}finally{c.releaseLock()}for(let u of t)yield*vc({...s,state:u,debug:n,stepContext:r});if(a){if(l.length){let u=Array.from(new Map(l.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=u}if(e.push(a),n&&s.logger){let u=structuredClone(a);delete u.citations,s.logger({name:"ChatResponseUsage",value:u}),a.citations&&a.citations.length>0&&s.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*wc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s,state:o,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)Zn(o.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:o.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),o.content+=i.content,e.updateResult({name:i.name,content:o.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:g,partialMarker:f}=Sa(o.content);if(g&&typeof g=="object"){let y={},x={};for(let b of Object.keys(g))if(d.some(T=>T.name===b)){let T=g[b],A=o.values[b];if(Array.isArray(T)&&T.length>0&&Sc(T,f)&&(T=T.slice(0,-1)),x[b]=T,typeof T=="string"&&typeof A=="string"&&T.startsWith(A)){let I=T.slice(A.length);I&&(y[b]=I)}else Array.isArray(T)&&Array.isArray(A)?T.length>A.length&&(y[b]=T.slice(A.length)):JSON.stringify(T)!==JSON.stringify(A)&&(Array.isArray(T)||(y[b]=T))}try{Ut(a,x,{allowMissingRequired:!0})}catch{}Object.assign(o.values,x),Object.keys(y).length>0&&(yield{index:i.index,delta:y});return}}if(co(a,o.values,o.xstate,o.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s}))return;u.length!==0&&await Zs(u,o.xstate,o.content),l.length!==0&&await mo(l,o.content,o.xstate,e,o.values,t),yield*po(a,o.content,o.values,o.xstate,i.index),await $t(p,o.values)}else i.thought&&i.thought.length>0?(o.values[c]=(o.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:o.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:o.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
215
- Content: ${o.content}`)}async function*vc({state:i,signature:e,ai:t,model:n,functions:r,mem:s,sessionId:o,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:h,functionResultFormatter:g,signatureToolCallingManager:f,logger:y,debug:x,stopFunctionNames:b,stepContext:T}){let A=f?void 0:go(t,i.functionCalls,i.values,n);if(A){if(!r)throw new Error("Functions are not defined");let I=await _r({ai:t,functionList:r,functionCalls:A,mem:s,sessionId:o,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:g,logger:y,debug:x,stopFunctionNames:b,step:T});i.functionsExecuted=new Set([...i.functionsExecuted,...I]),i.functionCalls=[]}else{let I=e.getOutputFields(),C=e.hasComplexFields(),S=!1;if(C)try{let R=JSON.parse(i.content),P={};for(let E of Object.keys(R))if(I.some(w=>w.name===E)){let w=R[E],v=i.values[E];if(typeof w=="string"&&typeof v=="string"&&w.startsWith(v)){let k=w.slice(v.length);k&&(P[E]=k)}else Array.isArray(w)&&Array.isArray(v)?w.length>v.length&&(P[E]=w.slice(v.length)):JSON.stringify(w)!==JSON.stringify(v)&&(Array.isArray(w)||(P[E]=w))}try{Ut(e,P,{allowMissingRequired:!0})}catch(E){let w=(E.message||"").toLowerCase();if(w.includes("at least")||w.includes("at most")||w.includes("must match pattern")||w.includes("invalid url")||w.includes("required")||w.includes("missing")||w.includes("valid email")||w.includes("number must be"))throw E}for(let E of Object.keys(R))I.some(w=>w.name===E)&&(i.values[E]=R[E]);yield{index:i.index,delta:P},S=!0}catch(R){let P=(R.message||"").toLowerCase();if(P.includes("at least")||P.includes("at most")||P.includes("must match pattern")||P.includes("invalid url")||P.includes("required")||P.includes("missing")||P.includes("valid email")||P.includes("number must be"))throw R}if(!S){let R=f!==void 0;uo(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:R,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(f){let R=await f.processResults(i.values);if(R&&R.length>0){if(!r)throw new Error("Functions are not defined");let P=await _r({ai:t,functionList:r,functionCalls:R,mem:s,sessionId:o,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:g,logger:y,debug:x,stopFunctionNames:b,step:T});i.functionsExecuted=new Set([...i.functionsExecuted,...P]),s.updateResult({name:void 0,content:i.content,functionCalls:R.map(E=>({id:E.id,type:"function",function:{name:E.name,params:E.args}})),index:i.index},o);return}}await Zs(p,i.xstate,i.content,!0),await $t(d,i.values),m.length&&await On(m,i.values,s,o),h.length!==0&&await mo(h,i.content,i.xstate,s,i.values,o,!0),yield*po(e,i.content,i.values,i.xstate,i.index)}}async function*Oa({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:s,span:o,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:h,functionResultFormatter:g,logger:f,debug:y,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:T,stepContext:A}){let I=e.results??[],C=x!==void 0;t.addResponse(I,n);let S=[];for(let w of I)if(Array.isArray(w?.citations))for(let v of w.citations)v?.url&&S.push({url:v.url,title:v.title,description:v.description,license:v.license,publicationDate:v.publicationDate,snippet:v.snippet});for(let w of I){let v=l[w.index];if(!v)throw new Error(`No state found for result (index: ${w.index})`);if(e.modelUsage){let k=Array.from(new Map(S.filter(N=>N.url).map(N=>[N.url,N])).values()),O={...e.modelUsage,...k.length?{citations:k}:{}};if(c.push(O),y&&f){let N=structuredClone(O);delete N.citations,f({name:"ChatResponseUsage",value:N}),O.citations&&O.citations.length>0&&f({name:"ChatResponseCitations",value:O.citations})}}if(x&&w.content){w.thought&&w.thought.length>0&&(v.values[m]=w.thought),Or(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C});let O=(await x.processResults(v.values))?.map(N=>({id:N.id,type:"function",function:{name:N.name,params:N.args}}));O&&O.length>0&&t.updateResult({name:w.name,content:w.content,functionCalls:O,index:w.index},n)}if(w.functionCalls?.length){let k=go(i,w.functionCalls,v.values);if(k&&k.length>0){if(!s)throw new Error("Functions are not defined");let O;try{O=await _r({ai:i,functionList:s,functionCalls:k,mem:t,sessionId:n,traceId:r,span:o,excludeContentFromTrace:u,index:w.index,functionResultFormatter:g,logger:f,debug:y,stopFunctionNames:b,step:A})}catch(N){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),N}v.functionsExecuted=new Set([...v.functionsExecuted,...O])}}else if(w.content){w.thought&&w.thought.length>0&&(v.values[m]=w.thought);let k=h.getOutputFields();if(h.hasComplexFields())try{let N=JSON.parse(w.content),M={};for(let D of Object.keys(N))k.some(F=>F.name===D)&&(M[D]=N[D]);Ut(h,M),Object.assign(v.values,M)}catch(N){let M=N instanceof SyntaxError;if((N.name?.includes("ValidationError")||N.name?.includes("Error"))&&!M){let F=(N.message||"").toLowerCase();if(F.includes("at least")||F.includes("at most")||F.includes("must match pattern")||F.includes("invalid url")||F.includes("required")||F.includes("missing")||F.includes("valid email")||F.includes("number must be"))throw N}if(M)Or(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C});else throw N}else Or(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C})}if(await $t(p,v.values),T||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await On(d,v.values,t,n),w.finishReason==="length")throw new Error(`Max tokens reached before completion
216
- Content: ${w.content}`)}let R=l.map(w=>w.values);for(let w of R)for(let v of h.getOutputFields())v.isInternal&&delete w[v.name];let P=h.getOutputFields(),E=R.map((w,v)=>{let k={};for(let O of P)O.isInternal||(k[O.name]=w[O.name]);return w[m]!==void 0&&(k[m]=w[m]),{index:v,delta:k}});for(let w of E)yield w}function Sc(i,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function Ma(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[s,o]of t.entries()){let a=e?Array.from(e).some(p=>o.functionsExecuted.has(p)):!1;if(!r.chat[s])throw new Error(`No chat message found for result (index: ${s})`);let c=r.role==="function",u=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var kc=["none","minimal","low","medium","high","highest"];function Pa(i,e){let t={};if(e.model!==!1){let o=i.getModelList();if(o&&o.length>0){let a=o.filter(l=>"model"in l);if(a.length>0){let l=a.map(u=>u.key),c=a.map(u=>`${u.key} (${u.description})`);t.model={type:"string",enum:l,description:`Switch model for the next step. Prefer faster/cheaper models for simple tasks; use more capable models for complex reasoning, math, or multi-step analysis. Available: ${c.join(", ")}`}}}}e.thinkingBudget!==!1&&(t.thinkingBudget={type:"string",enum:[...kc],description:"Reasoning depth for the next step. none/minimal: simple lookups or reformatting. low/medium: moderate analysis, summarization. high/highest: math, logic, code analysis, or multi-step reasoning. Higher budgets use more tokens."}),e.temperature&&(t.temperature={type:"number",description:"Sampling temperature for the next step. Lower values (0\u20130.3) for deterministic tasks like math or code; higher values (0.7\u20131.0) for creative or exploratory tasks."});let n;if(e.functions&&e.functions.length>0){n=Ot(e.functions);let o=n.map(l=>l.name),a=n.map(l=>`${l.name} (${l.description})`);t.addFunctions={type:"array",items:{type:"string",enum:o},description:`Activate tools you need for the current sub-task. Only add what you will use immediately \u2014 fewer active tools means less noise. Available: ${a.join(", ")}`},t.removeFunctions={type:"array",items:{type:"string",enum:o},description:"Remove tools you are done with to reduce context size and maintain focus on remaining work."}}let r=n;return{name:"adjustGeneration",description:"Adjust model, reasoning depth, or active tools for the next step. Call when task complexity changes \u2014 upgrade for hard reasoning or analysis, downgrade for simple follow-ups. Only call when there is a clear reason to change.",parameters:Object.keys(t).length>0?{type:"object",properties:t}:void 0,func:(o,a)=>{let l=a?.step;if(!l)return"Generation parameters adjusted for next response.";if(o?.model&&l.setModel(o.model),o?.thinkingBudget&&l.setThinkingBudget(o.thinkingBudget),o?.temperature!==void 0&&l.setTemperature(o.temperature),o?.addFunctions?.length&&r){let c=r.filter(u=>o.addFunctions.includes(u.name));c.length>0&&l.addFunctions(c)}return o?.removeFunctions?.length&&l.removeFunctions(...o.removeFunctions),"Generation parameters adjusted for next response."}}}var En=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 V=class extends Error{constructor(t,n,r,s){super(t);this.position=n;this.context=r;this.suggestion=s;this.name="SignatureValidationError"}},ho=class{input;position;currentFieldName=null;currentSection="description";constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new V("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 V("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 V('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 V(`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 V)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new V(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new V(`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 V(`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 V(`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 V("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new V("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),s=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${s}`].join(`
217
- `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new V(`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 V?r:new V(`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 V(`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 V?r:new V(`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 V(`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 V(`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 s=this.parseTypeNotClass(),o=this.match("[]");n={name:s,isArray:o}}catch(s){throw s instanceof V?s:new V(`Input field "${e}": ${s instanceof Error?s.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 o=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new V(`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 V(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:o,options:l}}else try{let o=this.parseTypeNotClass(),a=this.match("[]");if(r={name:o,isArray:a},o==="image"&&a)throw new V(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(o==="audio"&&a)throw new V(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(o==="image")throw new V(`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(o==="audio")throw new V(`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(o){throw o instanceof V?o:new V(`Output field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let s=this.parseParsedString();return{name:e,desc:s?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(Z.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 o=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new V(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${o.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new V(`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 V(`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 V(`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","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),s=`Invalid type "${n||"empty"}"`,o=r?`. Did you mean "${r}"?`:"",a=`${s}${o}`;throw new V(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 V("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 V(`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 V(`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,s=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 o=this.input.slice(s,Math.min(this.position,s+20));throw new V(`Unterminated string starting at position ${s}`,s,this.getErrorContext(),`Add closing ${t} to complete the string: ${o}${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 V(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Ea(i){return new ho(i).parse()}var Lr=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,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([s,o])=>[s,fo(o)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||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,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([s,o])=>[s,fo(o)])):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}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new fe(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Oe=class i{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}cache(){return new i({...this,isCached:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},ue=Object.assign(()=>new Lr,{string:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),number:i=>new Oe({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),boolean:i=>new Oe({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),json:i=>new Oe({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),datetime:i=>new Oe({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),date:i=>new Oe({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),class:(i,e)=>new Oe({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:i=>new Oe({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),audio:i=>new Oe({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),file:i=>new Oe({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),url:i=>new Oe({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),email:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(i,e)=>new Oe({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1,isCached:!1}),object:(i,e)=>new Oe({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function fo(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,fo(t)])):void 0}}function Nr(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var j=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},fe=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=Ea(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 j(`Invalid Signature: ${n.message}`,void 0,r)}throw new j(`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),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new j("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 j("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 j?t:new j(`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 j("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 j("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 j("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 j("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);ct(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new j(`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 j(`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 j?t:new j(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ct(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new j(`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 j(`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 j?t:new j(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new j("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 ct(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new j("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 ct(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`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,...Nr(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...Nr(t)},s=n.parseField(r);ct(s,"input");for(let o of n.inputFields)if(o.name===s.name)throw new j(`Duplicate input field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let o of n.outputFields)if(o.name===s.name)throw new j(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Nr(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...Nr(t)},s=n.parseField(r);ct(s,"output");for(let o of n.outputFields)if(o.name===s.name)throw new j(`Duplicate output field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let o of n.inputFields)if(o.name===s.name)throw new j(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=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)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ct(e,"input")}),this.getOutputFields().forEach(e=>{ct(e,"output")}),this.sigHash=Ne("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=_a(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ct(e,"input")}),this.getOutputFields().forEach(e=>{ct(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Ne("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=_a(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`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 j(`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 j(`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 j(`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 j("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new j("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);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});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return Mn(e,this.description??"Schema")}};function Fa(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 _a(i,e,t){let n=i?`"${i}" `:"",r=e.map(Fa).join(", "),s=t.map(Fa).join(", ");return`${n}${r} -> ${s}`}function Oc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ct(i,e){if(!i.name||i.name.length===0)throw new j("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Oc(i.name))throw new j(`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(Z.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 j(`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 j(`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 j(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Mc(i,e)}function Mc(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new j(`${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 j("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 j("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 j("Empty class option found",i.name,"All class options must be non-empty strings");let s=r.trim();if(s.includes(",")||s.includes("|"))throw new j(`Invalid class option "${s}"`,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 j("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new j("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 j("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&xo(t.fields,i.name,e)}function xo(i,e,t,n=1){for(let[r,s]of Object.entries(i)){let o=`${e}.${r}`;if(s.type==="image"||s.type==="audio"||s.type==="file")throw new j(`${s.type} type is not allowed in nested object fields`,o,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);s.type==="object"&&s.fields&&xo(s.fields,o,t,n+1),s.isArray&&s.fields&&xo(s.fields,`${o}[]`,t,n+1)}}var Mt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new fe(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 En,this.key={id:this.signature.hash()}}getSignature(){return new fe(this.signature)}setSignature(e){this.signature=new fe(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,s=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(o=>{let a={};for(let l of s){let c=o[l.name];c!==void 0&&(vr(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 kn(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 Na=`
214
+ Tip: Arrays must include an "items" schema (e.g., { items: { type: "string" } } or items: { type: "object", properties: { ... } }).`,{cause:r}):r}return[...e??[],...t]},Nr=async({ai:i,functionList:e,functionCalls:t,mem:n,sessionId:r,traceId:s,span:o,excludeContentFromTrace:a,index:l,functionResultFormatter:c,logger:u,debug:p,stopFunctionNames:d,step:m})=>{let h=new _r(e),g=new Set,f=[],y=A=>{let I=R=>R.replace(/[^a-zA-Z0-9]/g,"").toLowerCase(),C=I(A),S=e.find(R=>R.name===A);return S||(S=e.find(R=>I(R.name)===C)),S},x=t.map(A=>{if(!A.id)throw new Error(`Function ${A.name} did not return an ID`);let I=i.getOptions().tracer??Z.tracer;return I?I.startActiveSpan(`Tool: ${A.name}`,async C=>{try{C?.setAttributes?.({"tool.name":A.name,"tool.mode":"native","function.id":A.id,"session.id":r??""});let{formatted:S,rawResult:R,parsedArgs:P}=await h.executeWithDetails(A,{sessionId:r,ai:i,functionResultFormatter:c,traceId:C?.spanContext?.().traceId??s,stopFunctionNames:d,step:m});if(g.add(A.name.toLowerCase()),m?._recordFunctionCall(A.name,P,R),d?.includes(A.name.toLowerCase())){let E=y(A.name);E&&f.push({func:E,args:P,result:R})}if(a?C.addEvent("gen_ai.tool.message",{name:A.name}):C.addEvent("gen_ai.tool.message",{name:A.name,args:A.args,result:S??""}),o){let E={name:A.name};a||(E.args=A.args,E.result=S??""),o.addEvent("function.call",E)}return{result:S??"",role:"function",functionId:A.id,index:l}}catch(S){if(C?.recordException?.(S),S instanceof En){let R=S.getFixingInstructions(),P={name:A.name,message:S.toString()};return a||(P.args=A.args,P.fixing_instructions=R),C?.addEvent?.("function.error",P),p&&as(S,l,R,u),{functionId:A.id,isError:!0,index:l,result:R,role:"function"}}throw S}finally{C?.end?.()}}):h.executeWithDetails(A,{sessionId:r,ai:i,functionResultFormatter:c,traceId:s,stopFunctionNames:d,step:m}).then(({formatted:C,rawResult:S,parsedArgs:R})=>{if(g.add(A.name.toLowerCase()),m?._recordFunctionCall(A.name,R,S),d?.includes(A.name.toLowerCase())){let P=y(A.name);P&&f.push({func:P,args:R,result:S})}if(o){let P={name:A.name};a||(P.args=A.args,P.result=C??""),o.addEvent("function.call",P)}return{result:C??"",role:"function",functionId:A.id,index:l}}).catch(C=>{if(!(C instanceof En))throw C;let S=C.getFixingInstructions();if(o){let R={name:A.name,message:C.toString()};a||(R.args=A.args,R.fixing_instructions=S),o.addEvent("function.error",R)}return p&&as(C,l,S,u),{functionId:A.id,isError:!0,index:l,result:S,role:"function"}})}),T=(await Promise.all(x)).map(A=>A.result===void 0||A.result===""?{...A,result:"done"}:A);if(n.addFunctionResults(T,r),p){let A=T.filter(I=>!I.isError);A.length>0&&oi(A,u)}if(f.length>0)throw new jt(f);return g};function ho(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(s=>({id:s.id,name:s.function.name,args:s.function.params}))}function Sa(i,e,t,n){let r=e;return!t&&(r==="required"||typeof r=="function")?{functions:[],functionCall:void 0}:i?{functions:i.map(o=>"toFunction"in o?o.toFunction():o).flat(),functionCall:r}:{functions:[],functionCall:r}}function Cc(i){let e=0,t=!1,n=!1,r=!1,s=!1,o=[];for(let a=0;a<i.length;a++){let l=i[a];if(n){n=!1;continue}if(l==="\\"){n=!0;continue}if(l==='"'){t=!t;continue}t||(l==="{"?(o.push("{"),e++):l==="["?(o.push("["),e++):l==="}"?o.length>0&&o[o.length-1]==="{"&&(o.pop(),e--):l==="]"&&o.length>0&&o[o.length-1]==="["&&(o.pop(),e--))}if(o.length>0){let a=o[o.length-1];r=a==="[",s=a==="{"}return{nestingLevel:e,inString:t,inArray:r,inObject:s}}function ka(i){if(!i.trim())return{parsed:null,partialMarker:null};try{return{parsed:JSON.parse(i),partialMarker:null}}catch{}let e=Cc(i),t=Rc(i);try{return{parsed:JSON.parse(t),partialMarker:e}}catch{return{parsed:null,partialMarker:e}}}function Rc(i){let e=i.trim();for(e.endsWith(",")&&(e=e.slice(0,-1)),e.match(/,\s*"[^"]*"\s*:\s*$/)?e=e.replace(/,\s*"[^"]*"\s*:\s*$/,""):e.match(/\{\s*"[^"]*"\s*:\s*$/)&&(e=e.replace(/"[^"]*"\s*:\s*$/,""));e.match(/[0-9][eE.+-]$/)||e.match(/[eE][+-]$/);)e=e.slice(0,-1);e=e.replace(/,(\s*[}\]])/g,"$1"),e.match(/t(r(u(e)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("true")&&e.match(/[:[,]\s*t(r(u(e)?)?)?$/)&&(e=e.replace(/t(r(u(e)?)?)?$/,"true")),e.match(/f(a(l(s(e)?)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("false")&&e.match(/[:[,]\s*f(a(l(s(e)?)?)?)?$/)&&(e=e.replace(/f(a(l(s(e)?)?)?)?$/,"false")),e.match(/n(u(l(l)?)?)?$/)&&!e.endsWith('"')&&!e.endsWith("null")&&e.match(/[:[,]\s*n(u(l(l)?)?)?$/)&&(e=e.replace(/n(u(l(l)?)?)?$/,"null"));let t=[],n=!1,r=!1;for(let s=0;s<e.length;s++){let o=e[s];if(r){r=!1;continue}if(o==="\\"){r=!0;continue}if(o==='"'){n=!n;continue}n||(o==="{"?t.push("}"):o==="["?t.push("]"):o==="}"?t.length>0&&t[t.length-1]==="}"&&t.pop():o==="]"&&t.length>0&&t[t.length-1]==="]"&&t.pop())}for(r&&(e=e.slice(0,-1)),n&&(e+='"'),t.length>0&&t[t.length-1]==="}"&&e.match(/,\s*"[^"]*"\s*$/)&&(e=e.replace(/,\s*"[^"]*"\s*$/,""));t.length>0;)e+=t.pop();return e}async function*Oa({res:i,usage:e,states:t,debug:n,stepContext:r,...s}){let o=(s.ai.getFeatures().functionCot??!1)&&s.functions!==void 0&&s.functions.length>0,a,l=[],c=i.getReader();try{for(;;){let{done:u,value:p}=await c.read();if(u)break;let d=p;d.modelUsage&&(a=d.modelUsage);for(let m of d.results){if(Array.isArray(m.citations))for(let g of m.citations)g?.url&&l.push({url:g.url,title:g.title,description:g.description,license:g.license,publicationDate:g.publicationDate,snippet:g.snippet});if((!m.content||m.content==="")&&(!m.thought||m.thought==="")&&(!m.thoughtBlocks||m.thoughtBlocks.length===0)&&(!m.functionCalls||m.functionCalls.length===0))continue;let h=t.find(g=>g.index===m.index);if(!h)throw new Error(`No state found for result (index: ${m.index})`);yield*wc({...s,result:m,skipEarlyFail:o,state:h,debug:n})}}}finally{c.releaseLock()}for(let u of t)yield*vc({...s,state:u,debug:n,stepContext:r});if(a){if(l.length){let u=Array.from(new Map(l.filter(p=>p.url).map(p=>[p.url,p])).values());a.citations=u}if(e.push(a),n&&s.logger){let u=structuredClone(a);delete u.citations,s.logger({name:"ChatResponseUsage",value:u}),a.citations&&a.citations.length>0&&s.logger({name:"ChatResponseCitations",value:a.citations})}}}async function*wc({result:i,mem:e,sessionId:t,strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s,state:o,signature:a,streamingFieldProcessors:l,thoughtFieldName:c,streamingAsserts:u,asserts:p}){if(i.functionCalls&&i.functionCalls.length>0)er(o.functionCalls,i.functionCalls),e.updateResult({name:i.name,content:i.content,functionCalls:o.functionCalls,thoughtBlocks:i.thoughtBlocks,delta:i.functionCalls?.[0]?.function?.params,index:i.index},t);else if(i.content&&i.content.length>0){i.thought&&i.thought.length>0&&(yield{index:i.index,delta:{[c]:i.thought}}),o.content+=i.content,e.updateResult({name:i.name,content:o.content,thoughtBlocks:i.thoughtBlocks,delta:i.content,index:i.index},t);let d=a.getOutputFields();if(a.hasComplexFields()){let{parsed:g,partialMarker:f}=ka(o.content);if(g&&typeof g=="object"){let y={},x={};for(let b of Object.keys(g))if(d.some(T=>T.name===b)){let T=g[b],A=o.values[b];if(Array.isArray(T)&&T.length>0&&Sc(T,f)&&(T=T.slice(0,-1)),x[b]=T,typeof T=="string"&&typeof A=="string"&&T.startsWith(A)){let I=T.slice(A.length);I&&(y[b]=I)}else Array.isArray(T)&&Array.isArray(A)?T.length>A.length&&(y[b]=T.slice(A.length)):JSON.stringify(T)!==JSON.stringify(A)&&(Array.isArray(T)||(y[b]=T))}try{Bt(a,x,{allowMissingRequired:!0})}catch{}Object.assign(o.values,x),Object.keys(y).length>0&&(yield{index:i.index,delta:y});return}}if(uo(a,o.values,o.xstate,o.content,{strictMode:n,skipEarlyFail:r,treatAllFieldsOptional:s}))return;u.length!==0&&await eo(u,o.xstate,o.content),l.length!==0&&await go(l,o.content,o.xstate,e,o.values,t),yield*mo(a,o.content,o.values,o.xstate,i.index),await Gt(p,o.values)}else i.thought&&i.thought.length>0?(o.values[c]=(o.values[c]??"")+i.thought,yield{index:i.index,delta:{[c]:i.thought}},e.updateResult({name:i.name,content:o.content,delta:"",index:i.index,thought:i.thought,thoughtBlocks:i.thoughtBlocks},t)):i.thoughtBlocks&&i.thoughtBlocks.length>0&&e.updateResult({name:i.name,content:o.content,delta:"",index:i.index,thoughtBlocks:i.thoughtBlocks},t);if(i.finishReason==="length")throw new Error(`Max tokens reached before completion
215
+ Content: ${o.content}`)}async function*vc({state:i,signature:e,ai:t,model:n,functions:r,mem:s,sessionId:o,traceId:a,span:l,strictMode:c,excludeContentFromTrace:u,streamingAsserts:p,asserts:d,fieldProcessors:m,streamingFieldProcessors:h,functionResultFormatter:g,signatureToolCallingManager:f,logger:y,debug:x,stopFunctionNames:b,stepContext:T}){let A=f?void 0:ho(t,i.functionCalls,i.values,n);if(A){if(!r)throw new Error("Functions are not defined");let I=await Nr({ai:t,functionList:r,functionCalls:A,mem:s,sessionId:o,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:g,logger:y,debug:x,stopFunctionNames:b,step:T});i.functionsExecuted=new Set([...i.functionsExecuted,...I]),i.functionCalls=[]}else{let I=e.getOutputFields(),C=e.hasComplexFields(),S=!1;if(C)try{let R=JSON.parse(i.content),P={};for(let E of Object.keys(R))if(I.some(w=>w.name===E)){let w=R[E],v=i.values[E];if(typeof w=="string"&&typeof v=="string"&&w.startsWith(v)){let k=w.slice(v.length);k&&(P[E]=k)}else Array.isArray(w)&&Array.isArray(v)?w.length>v.length&&(P[E]=w.slice(v.length)):JSON.stringify(w)!==JSON.stringify(v)&&(Array.isArray(w)||(P[E]=w))}try{Bt(e,P,{allowMissingRequired:!0})}catch(E){let w=(E.message||"").toLowerCase();if(w.includes("at least")||w.includes("at most")||w.includes("must match pattern")||w.includes("invalid url")||w.includes("required")||w.includes("missing")||w.includes("valid email")||w.includes("number must be"))throw E}for(let E of Object.keys(R))I.some(w=>w.name===E)&&(i.values[E]=R[E]);yield{index:i.index,delta:P},S=!0}catch(R){let P=(R.message||"").toLowerCase();if(P.includes("at least")||P.includes("at most")||P.includes("must match pattern")||P.includes("invalid url")||P.includes("required")||P.includes("missing")||P.includes("valid email")||P.includes("number must be"))throw R}if(!S){let R=f!==void 0;po(e,i.values,i.xstate,i.content,{strictMode:c,treatAllFieldsOptional:R,deferRequiredCheckForStreaming:!0,forceFinalize:!0})}if(f){let R=await f.processResults(i.values);if(R&&R.length>0){if(!r)throw new Error("Functions are not defined");let P=await Nr({ai:t,functionList:r,functionCalls:R,mem:s,sessionId:o,traceId:a,span:l,index:i.index,excludeContentFromTrace:u,functionResultFormatter:g,logger:y,debug:x,stopFunctionNames:b,step:T});i.functionsExecuted=new Set([...i.functionsExecuted,...P]),s.updateResult({name:void 0,content:i.content,functionCalls:R.map(E=>({id:E.id,type:"function",function:{name:E.name,params:E.args}})),index:i.index},o);return}}await eo(p,i.xstate,i.content,!0),await Gt(d,i.values),m.length&&await Mn(m,i.values,s,o),h.length!==0&&await go(h,i.content,i.xstate,s,i.values,o,!0),yield*mo(e,i.content,i.values,i.xstate,i.index)}}async function*Ma({ai:i,res:e,mem:t,sessionId:n,traceId:r,functions:s,span:o,strictMode:a,states:l,usage:c,excludeContentFromTrace:u,asserts:p,fieldProcessors:d,thoughtFieldName:m,signature:h,functionResultFormatter:g,logger:f,debug:y,signatureToolCallingManager:x,stopFunctionNames:b,disableMemoryCleanup:T,stepContext:A}){let I=e.results??[],C=x!==void 0;t.addResponse(I,n);let S=[];for(let w of I)if(Array.isArray(w?.citations))for(let v of w.citations)v?.url&&S.push({url:v.url,title:v.title,description:v.description,license:v.license,publicationDate:v.publicationDate,snippet:v.snippet});for(let w of I){let v=l[w.index];if(!v)throw new Error(`No state found for result (index: ${w.index})`);if(e.modelUsage){let k=Array.from(new Map(S.filter(N=>N.url).map(N=>[N.url,N])).values()),O={...e.modelUsage,...k.length?{citations:k}:{}};if(c.push(O),y&&f){let N=structuredClone(O);delete N.citations,f({name:"ChatResponseUsage",value:N}),O.citations&&O.citations.length>0&&f({name:"ChatResponseCitations",value:O.citations})}}if(x&&w.content){w.thought&&w.thought.length>0&&(v.values[m]=w.thought),Mr(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C});let O=(await x.processResults(v.values))?.map(N=>({id:N.id,type:"function",function:{name:N.name,params:N.args}}));O&&O.length>0&&t.updateResult({name:w.name,content:w.content,functionCalls:O,index:w.index},n)}if(w.functionCalls?.length){let k=ho(i,w.functionCalls,v.values);if(k&&k.length>0){if(!s)throw new Error("Functions are not defined");let O;try{O=await Nr({ai:i,functionList:s,functionCalls:k,mem:t,sessionId:n,traceId:r,span:o,excludeContentFromTrace:u,index:w.index,functionResultFormatter:g,logger:f,debug:y,stopFunctionNames:b,step:A})}catch(N){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),N}v.functionsExecuted=new Set([...v.functionsExecuted,...O])}}else if(w.content){w.thought&&w.thought.length>0&&(v.values[m]=w.thought);let k=h.getOutputFields();if(h.hasComplexFields())try{let N=JSON.parse(w.content),M={};for(let D of Object.keys(N))k.some(F=>F.name===D)&&(M[D]=N[D]);Bt(h,M),Object.assign(v.values,M)}catch(N){let M=N instanceof SyntaxError;if((N.name?.includes("ValidationError")||N.name?.includes("Error"))&&!M){let F=(N.message||"").toLowerCase();if(F.includes("at least")||F.includes("at most")||F.includes("must match pattern")||F.includes("invalid url")||F.includes("required")||F.includes("missing")||F.includes("valid email")||F.includes("number must be"))throw N}if(M)Mr(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C});else throw N}else Mr(h,v.values,w.content,{strictMode:a,treatAllFieldsOptional:C})}if(await Gt(p,v.values),T||(t.removeByTag("correction",n),t.removeByTag("error",n)),d.length&&await Mn(d,v.values,t,n),w.finishReason==="length")throw new Error(`Max tokens reached before completion
216
+ Content: ${w.content}`)}let R=l.map(w=>w.values);for(let w of R)for(let v of h.getOutputFields())v.isInternal&&delete w[v.name];let P=h.getOutputFields(),E=R.map((w,v)=>{let k={};for(let O of P)O.isInternal||(k[O.name]=w[O.name]);return w[m]!==void 0&&(k[m]=w[m]),{index:v,delta:k}});for(let w of E)yield w}function Sc(i,e){return e?!!(e.nestingLevel>0||e.inArray||e.inObject):!1}function Pa(i,e,t,n){let r=i.getLast(n);if(!r)return!0;for(let[s,o]of t.entries()){let a=e?Array.from(e).some(p=>o.functionsExecuted.has(p)):!1;if(!r.chat[s])throw new Error(`No chat message found for result (index: ${s})`);let c=r.role==="function",u=r.tags?r.tags.some(p=>p==="processor"):!1;if(c&&e&&a||!(c||u))return!1}return!0}var kc=["none","minimal","low","medium","high","highest"];function Ea(i,e){let t={};if(e.model!==!1){let o=i.getModelList();if(o&&o.length>0){let a=o.filter(l=>"model"in l);if(a.length>0){let l=a.map(u=>u.key),c=a.map(u=>`${u.key} (${u.description})`);t.model={type:"string",enum:l,description:`Switch model for the next step. Prefer faster/cheaper models for simple tasks; use more capable models for complex reasoning, math, or multi-step analysis. Available: ${c.join(", ")}`}}}}e.thinkingBudget!==!1&&(t.thinkingBudget={type:"string",enum:[...kc],description:"Reasoning depth for the next step. none/minimal: simple lookups or reformatting. low/medium: moderate analysis, summarization. high/highest: math, logic, code analysis, or multi-step reasoning. Higher budgets use more tokens."}),e.temperature&&(t.temperature={type:"number",description:"Sampling temperature for the next step. Lower values (0\u20130.3) for deterministic tasks like math or code; higher values (0.7\u20131.0) for creative or exploratory tasks."});let n;if(e.functions&&e.functions.length>0){n=Ot(e.functions);let o=n.map(l=>l.name),a=n.map(l=>`${l.name} (${l.description})`);t.addFunctions={type:"array",items:{type:"string",enum:o},description:`Activate tools you need for the current sub-task. Only add what you will use immediately \u2014 fewer active tools means less noise. Available: ${a.join(", ")}`},t.removeFunctions={type:"array",items:{type:"string",enum:o},description:"Remove tools you are done with to reduce context size and maintain focus on remaining work."}}let r=n;return{name:"adjustGeneration",description:"Adjust model, reasoning depth, or active tools for the next step. Call when task complexity changes \u2014 upgrade for hard reasoning or analysis, downgrade for simple follow-ups. Only call when there is a clear reason to change.",parameters:Object.keys(t).length>0?{type:"object",properties:t}:void 0,func:(o,a)=>{let l=a?.step;if(!l)return"Generation parameters adjusted for next response.";if(o?.model&&l.setModel(o.model),o?.thinkingBudget&&l.setThinkingBudget(o.thinkingBudget),o?.temperature!==void 0&&l.setTemperature(o.temperature),o?.addFunctions?.length&&r){let c=r.filter(u=>o.addFunctions.includes(u.name));c.length>0&&l.addFunctions(c)}return o?.removeFunctions?.length&&l.removeFunctions(...o.removeFunctions),"Generation parameters adjusted for next response."}}}var Fn=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 V=class extends Error{constructor(t,n,r,s){super(t);this.position=n;this.context=r;this.suggestion=s;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 V("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 V("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 V('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 V(`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 V)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new V(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let r of e.inputs){if(t.has(r.name))throw new V(`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 V(`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 V(`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 V("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new V("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),s=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${s}`].join(`
217
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new V(`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 V?r:new V(`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 V(`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 V?r:new V(`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 V(`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 V(`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 s=this.parseTypeNotClass(),o=this.match("[]");n={name:s,isArray:o}}catch(s){throw s instanceof V?s:new V(`Input field "${e}": ${s instanceof Error?s.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 o=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new V(`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 V(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');r={name:"class",isArray:o,options:l}}else try{let o=this.parseTypeNotClass(),a=this.match("[]");if(r={name:o,isArray:a},o==="image"&&a)throw new V(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(o==="audio"&&a)throw new V(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(o==="image")throw new V(`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(o==="audio")throw new V(`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(o){throw o instanceof V?o:new V(`Output field "${e}": ${o instanceof Error?o.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let s=this.parseParsedString();return{name:e,desc:s?.trim(),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(Z.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 o=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new V(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${o.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,r=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!r.test(e))throw new V(`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 V(`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 V(`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","object"],t=e.find(n=>this.match(n));if(!t){let n=this.input.slice(this.position).match(/^\w+/)?.[0]||"",r=this.suggestType(n),s=`Invalid type "${n||"empty"}"`,o=r?`. Did you mean "${r}"?`:"",a=`${s}${o}`;throw new V(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 V("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 V(`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 V(`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,s=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 o=this.input.slice(s,Math.min(this.position,s+20));throw new V(`Unterminated string starting at position ${s}`,s,this.getErrorContext(),`Add closing ${t} to complete the string: ${o}${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 V(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function Fa(i){return new fo(i).parse()}var $r=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,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([s,o])=>[s,xo(o)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||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,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([s,o])=>[s,xo(o)])):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}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=new fe(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Oe=class i{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;patternDescription;format;itemDescription;constructor(e){this.type=e.type,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.format=e.format}optional(){return new i({...this,isOptional:!0})}array(e){return new i({...this,isArray:!0,description:e||this.description,itemDescription:e?this.description:void 0})}internal(){return new i({...this,isInternal:!0})}cache(){return new i({...this,isCached:!0})}min(e){return this.type==="string"?new i({...this,minLength:e}):this.type==="number"?new i({...this,minimum:e}):this}max(e){return this.type==="string"?new i({...this,maxLength:e}):this.type==="number"?new i({...this,maximum:e}):this}email(){return this.type==="string"?new i({...this,format:"email"}):this}url(){return this.type==="string"?new i({...this,format:"uri"}):this}regex(e,t){return this.type==="string"?new i({...this,pattern:e,patternDescription:t}):this}date(){return this.type==="string"?new i({...this,format:"date"}):this}datetime(){return this.type==="string"?new i({...this,format:"date-time"}):this}},ue=Object.assign(()=>new $r,{string:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),number:i=>new Oe({type:"number",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),boolean:i=>new Oe({type:"boolean",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),json:i=>new Oe({type:"json",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),datetime:i=>new Oe({type:"datetime",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),date:i=>new Oe({type:"date",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),class:(i,e)=>new Oe({type:"class",isArray:!1,options:i,description:e,isOptional:!1,isInternal:!1,isCached:!1}),image:i=>new Oe({type:"image",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),audio:i=>new Oe({type:"audio",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),file:i=>new Oe({type:"file",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),url:i=>new Oe({type:"url",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1}),email:i=>new Oe({type:"string",isArray:!1,description:i,isOptional:!1,isInternal:!1,isCached:!1,format:"email"}),code:(i,e)=>new Oe({type:"code",isArray:!1,description:e||i,isOptional:!1,isInternal:!1,isCached:!1}),object:(i,e)=>new Oe({type:"object",isArray:!1,fields:i,description:e,isOptional:!1,isInternal:!1,isCached:!1})});function xo(i){return{type:i.type,isArray:i.isArray,options:i.options,description:i.description,isOptional:i.isOptional,isInternal:i.isInternal,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,patternDescription:i.patternDescription,format:i.format,fields:i.fields?Object.fromEntries(Object.entries(i.fields).map(([e,t])=>[e,xo(t)])):void 0}}function Lr(i){return{type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields},description:i.description,isOptional:i.isOptional,isInternal:i.isInternal}}var j=class extends Error{constructor(t,n,r){super(t);this.fieldName=n;this.suggestion=r;this.name="AxSignatureValidationError"}},fe=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=Fa(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 j(`Invalid Signature: ${n.message}`,void 0,r)}throw new j(`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),this._forceComplexFields=e._forceComplexFields,this._hasComplexFields=e._hasComplexFields;else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new j("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 j("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 j?t:new j(`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 j("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 j("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 j("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 j("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);ct(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new j(`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 j(`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 j?t:new j(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);ct(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new j(`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 j(`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 j?t:new j(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new j("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 ct(r,"input"),r});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new j("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 ct(r,"output"),r});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof j?t:new j(`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,...Lr(t)}),n};prependInputField=(e,t)=>{let n=new i(this),r={name:e,...Lr(t)},s=n.parseField(r);ct(s,"input");for(let o of n.inputFields)if(o.name===s.name)throw new j(`Duplicate input field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let o of n.outputFields)if(o.name===s.name)throw new j(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.inputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};appendOutputField=(e,t)=>{let n=new i(this);return n.addOutputField({name:e,...Lr(t)}),n};prependOutputField=(e,t)=>{let n=new i(this),r={name:e,...Lr(t)},s=n.parseField(r);ct(s,"output");for(let o of n.outputFields)if(o.name===s.name)throw new j(`Duplicate output field name: "${s.name}"`,s.name,"Each field name must be unique within the signature");for(let o of n.inputFields)if(o.name===s.name)throw new j(`Field name "${s.name}" appears in both inputs and outputs`,s.name,"Use different names for input and output fields to avoid confusion");return n.outputFields.unshift(s),n.invalidateValidationCache(),n.updateHashLight(),n};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=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)};updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{ct(e,"input")}),this.getOutputFields().forEach(e=>{ct(e,"output")}),this.sigHash=Ne("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Na(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{ct(e,"input")}),this.getOutputFields().forEach(e=>{ct(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Ne("sha256").update(this.description??"").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Na(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof j?e:new j(`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 j(`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 j(`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 j(`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 j("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new j("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>this._hasComplexFields!==void 0?this._hasComplexFields:(this._hasComplexFields=this.computeHasComplexFields(),this._hasComplexFields);computeHasComplexFields=()=>this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name==="object"||e.type?.isArray&&e.type.fields!==void 0);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});toJSONSchema=()=>{let e=[...this.inputFields,...this.outputFields];return Pn(e,this.description??"Schema")}};function _a(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 Na(i,e,t){let n=i?`"${i}" `:"",r=e.map(_a).join(", "),s=t.map(_a).join(", ");return`${n}${r} -> ${s}`}function Oc(i){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(i)||t.test(i)}function ct(i,e){if(!i.name||i.name.length===0)throw new j("Field name cannot be blank",i.name,"Every field must have a descriptive name");if(!Oc(i.name))throw new j(`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(Z.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 j(`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 j(`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 j(`Field name '${i.name}' is too long (${i.name.length} characters)`,i.name,"Field names should be 50 characters or less");i.type&&Mc(i,e)}function Mc(i,e){if(!i.type)return;let{type:t}=i;if((t.name==="image"||t.name==="audio"||t.name==="file")&&e==="output")throw new j(`${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 j("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 j("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 j("Empty class option found",i.name,"All class options must be non-empty strings");let s=r.trim();if(s.includes(",")||s.includes("|"))throw new j(`Invalid class option "${s}"`,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 j("Duplicate class options found",i.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new j("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 j("Internal marker (!) is not allowed on input fields",i.name,"Internal markers are only allowed on output fields");t.name==="object"&&t.fields&&Ao(t.fields,i.name,e)}function Ao(i,e,t,n=1){for(let[r,s]of Object.entries(i)){let o=`${e}.${r}`;if(s.type==="image"||s.type==="audio"||s.type==="file")throw new j(`${s.type} type is not allowed in nested object fields`,o,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${n}.`);s.type==="object"&&s.fields&&Ao(s.fields,o,t,n+1),s.isArray&&s.fields&&Ao(s.fields,`${o}[]`,t,n+1)}}var Mt=class{signature;sigHash;examples;examplesOptions;demos;trace;usage=[];traceLabel;key;children;constructor(e,t){this.signature=new fe(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 Fn,this.key={id:this.signature.hash()}}getSignature(){return new fe(this.signature)}setSignature(e){this.signature=new fe(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,s=[...r.getInputFields(),...r.getOutputFields()];this.examples=n.map(o=>{let a={};for(let l of s){let c=o[l.name];c!==void 0&&(Sr(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 La=`
218
218
  ## Function Call Instructions
219
219
  - Complete the task, using the functions defined earlier in this prompt.
220
220
  - Output fields should only be generated after all functions have been called.
@@ -230,36 +230,36 @@ Content: ${w.content}`)}let R=l.map(w=>w.values);for(let w of R)for(let v of h.g
230
230
  The conversation history preceding the final user query consists of **few-shot examples** (demonstrations).
231
231
  - These alternating User/Assistant messages are provided **solely** to illustrate the correct reasoning steps, function usage, and output format.
232
232
  - **Do not** treat the specific data, entities, or facts in these examples as valid context for the current task.
233
- - The actual task begins with the final User message.`,jt=`--- END OF EXAMPLES ---
233
+ - The actual task begins with the final User message.`,qt=`--- END OF EXAMPLES ---
234
234
  The examples above were for training purposes only. Please ignore any specific entities or facts mentioned in them.
235
235
 
236
236
  REAL USER QUERY:
237
- `,zt=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;contextCache;examplesInSystem;ignoreBreakpoints;structuredOutputFunctionName;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions,this.contextCache=t?.contextCache,this.examplesInSystem=t?.examplesInSystem??!1,this.ignoreBreakpoints=t?.ignoreBreakpoints??!1,this.structuredOutputFunctionName=t?.structuredOutputFunctionName,Z.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}getFieldNameToTitleMap=()=>{let e=new Map;for(let t of this.sig.getInputFields())e.set(t.name,t.title);for(let t of this.sig.getOutputFields())e.set(t.name,t.title);return e};sortFieldsCachedFirst=e=>[...e].sort((t,n)=>t.isCached&&!n.isCached?-1:!t.isCached&&n.isCached?1:0);buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=$r(this.sig.getInputFields()),r=$r(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${n}. Your task is to generate new fields: ${r}.`);let o=this.functions?.map(u=>"toFunction"in u?u.toFunction():u)?.flat()?.map(u=>`- \`${u.name}\`: ${qt(u.description)}`).join(`
237
+ `,Ht=class{sig;fieldTemplates;task;customInstruction;setInstruction(e){this.customInstruction=e,this.task={type:"text",text:e}}getInstruction(){return this.customInstruction}thoughtFieldName;functions;contextCache;examplesInSystem;ignoreBreakpoints;structuredOutputFunctionName;constructor(e,t,n){this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=t?.thoughtFieldName??"thought",this.functions=t?.functions,this.contextCache=t?.contextCache,this.examplesInSystem=t?.examplesInSystem??!1,this.ignoreBreakpoints=t?.ignoreBreakpoints??!1,this.structuredOutputFunctionName=t?.structuredOutputFunctionName,Z.useStructuredPrompt?this.task=this.buildStructuredPrompt():this.task=this.buildLegacyPrompt()}getFieldNameToTitleMap=()=>{let e=new Map;for(let t of this.sig.getInputFields())e.set(t.name,t.title);for(let t of this.sig.getOutputFields())e.set(t.name,t.title);return e};sortFieldsCachedFirst=e=>[...e].sort((t,n)=>t.isCached&&!n.isCached?-1:!t.isCached&&n.isCached?1:0);buildLegacyPrompt(){let e=[],t=this.sig.hasComplexFields(),n=Gr(this.sig.getInputFields()),r=Gr(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${n}. Your task is to generate new fields: ${r}.`);let o=this.functions?.map(u=>"toFunction"in u?u.toFunction():u)?.flat()?.map(u=>`- \`${u.name}\`: ${zt(u.description)}`).join(`
238
238
  `);o&&o.length>0&&e.push(`## Available Functions
239
- ${o}`);let a=this.getFieldNameToTitleMap(),l=La(this.sig.getInputFields(),a);if(e.push(`## Input Fields
240
- ${l}`),!t){let u=$a(this.sig.getOutputFields(),a);e.push(`## Output Fields
241
- ${u}`)}o&&o.length>0&&e.push(Na.trim()),t&&this.structuredOutputFunctionName?e.push(`## Strict Output Formatting Rules
239
+ ${o}`);let a=this.getFieldNameToTitleMap(),l=$a(this.sig.getInputFields(),a);if(e.push(`## Input Fields
240
+ ${l}`),!t){let u=Ga(this.sig.getOutputFields(),a);e.push(`## Output Fields
241
+ ${u}`)}o&&o.length>0&&e.push(La.trim()),t&&this.structuredOutputFunctionName?e.push(`## Strict Output Formatting Rules
242
242
  - No formatting rules should override these **Strict Output Formatting Rules**
243
243
  - You MUST call the \`${this.structuredOutputFunctionName}\` function with the complete output data as arguments.
244
244
  - Do NOT output any text. Use the function call to return your structured response.
245
- - The function parameters define the exact schema your output must match.`):t||e.push(Pc.trim());let c=this.sig.getDescription();if(c){let u=qt(c);u=Gr(u,a),e.push(u)}return{type:"text",text:e.join(`
245
+ - The function parameters define the exact schema your output must match.`):t||e.push(Pc.trim());let c=this.sig.getDescription();if(c){let u=zt(c);u=Dr(u,a),e.push(u)}return{type:"text",text:e.join(`
246
246
 
247
247
  `)}}buildStructuredPrompt(){let e=[],t=this.sig.hasComplexFields();e.push("<identity>"),e.push(this.buildIdentitySection()),e.push("</identity>");let n=this.functions?.flatMap(r=>"toFunction"in r?r.toFunction():r);return n&&n.length>0&&(e.push(`
248
248
  <available_functions>`),e.push(this.buildFunctionsSection(n)),e.push("</available_functions>")),e.push(`
249
249
  <input_fields>`),e.push(this.buildInputFieldsSection()),e.push("</input_fields>"),t||(e.push(`
250
250
  <output_fields>`),e.push(this.buildOutputFieldsSection()),e.push("</output_fields>")),e.push(`
251
251
  <formatting_rules>`),e.push(this.buildFormattingRulesSection()),e.push("</formatting_rules>"),{type:"text",text:e.join(`
252
- `)}}buildIdentitySection(){let e=[],t=$r(this.sig.getInputFields()),n=$r(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${t}. Your task is to generate new fields: ${n}.`);let r=this.sig.getDescription();if(r){let s=this.getFieldNameToTitleMap(),o=qt(r);o=Gr(o,s),e.push(`
252
+ `)}}buildIdentitySection(){let e=[],t=Gr(this.sig.getInputFields()),n=Gr(this.sig.getOutputFields());e.push(`You will be provided with the following fields: ${t}. Your task is to generate new fields: ${n}.`);let r=this.sig.getDescription();if(r){let s=this.getFieldNameToTitleMap(),o=zt(r);o=Dr(o,s),e.push(`
253
253
  ${o}`)}return e.join(`
254
254
  `)}buildFunctionsSection(e){let t=[];t.push(`**Available Functions**: You can call the following functions to complete the task:
255
- `);let n=e.map(r=>`- \`${r.name}\`: ${qt(r.description??"")}`).join(`
255
+ `);let n=e.map(r=>`- \`${r.name}\`: ${zt(r.description??"")}`).join(`
256
256
  `);return t.push(n),t.push(`
257
- ${Na.trim()}`),t.join(`
257
+ ${La.trim()}`),t.join(`
258
258
  `)}buildInputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Input Fields**: The following fields will be provided to you:
259
259
 
260
- ${La(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
260
+ ${$a(this.sig.getInputFields(),e)}`}buildOutputFieldsSection(){let e=this.getFieldNameToTitleMap();return`**Output Fields**: You must generate the following fields:
261
261
 
262
- ${$a(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?`**CRITICAL - Structured Output via Function Call**:
262
+ ${Ga(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.sig.hasComplexFields();return e&&this.structuredOutputFunctionName?`**CRITICAL - Structured Output via Function Call**:
263
263
  - You MUST call the \`${this.structuredOutputFunctionName}\` function with the complete output data as arguments.
264
264
  - Do NOT output any text. Use the function call to return your structured response.
265
265
  - The function parameters define the exact schema your output must match.
@@ -280,16 +280,16 @@ ${$a(this.sig.getOutputFields(),e)}`}buildFormattingRulesSection(){let e=this.si
280
280
  ## Examples
281
281
  `},...this.renderExamples(t)]:[],s=n?this.renderDemos(n):[],o=r.every(d=>d.type==="text"),a=s.every(d=>d.type==="text"),l=o&&a,c=this.task.text;if(l){let d=[{type:"text",text:c},...r,...s];d.reduce(Pt(""),[]),d?.[0]&&(c=d[0].text)}let u={role:"system",content:c,cache:!!this.contextCache};if(Array.isArray(e)){let d=[],m=e,h=!0;for(let g of m){let f;if(h?(f=this.renderSingleValueUserContent(g.values,r,s,l),h=!1):f=this.renderSingleValueUserContent(g.values,[],[],!1),g.role==="user"){d.push({role:"user",content:f});continue}if(g.role!=="assistant")throw new Error("Invalid message role");if(typeof f!="string")throw new Error("Assistant message cannot contain non-text content like images, files,etc");d.push({role:"assistant",content:f})}return[u,...d]}let p=this.renderSingleValueUserContent(e,r,s,l);return[u,{role:"user",content:p}]};renderWithMessagePairs=(e,{examples:t,demos:n})=>{let r=t&&t.length>0||n&&n.length>0,o={role:"system",content:r?this.task.text+Ec:this.task.text,cache:!!this.contextCache},a=t?this.renderExamplesAsMessages(t):[],l=n?this.renderDemosAsMessages(n):[],c=[];for(let A of[...a,...l])c.push(A.userMessage),c.push(A.assistantMessage),A.functionResultMessage&&c.push(A.functionResultMessage);let u=this.contextCache?.cacheBreakpoint??"after-examples",p=this.ignoreBreakpoints||u==="after-examples";if(this.contextCache&&c.length>0&&p){let A=c.length-1,I=c[A];I?.role==="assistant"&&(c[A]={...I,cache:!0})}if(Array.isArray(e)){let A=[],I=e,C=!0;for(let S of I){let R=this.renderInputFields(S.values),P=R.every(E=>E.type==="text")?R.map(E=>E.text).join(`
282
282
  `):R.reduce(Pt(`
283
- `),[]);if(S.role==="user"){C&&r&&(typeof P=="string"?P=jt+P:P=[{type:"text",text:jt},...P],C=!1),A.push({role:"user",content:P});continue}if(S.role!=="assistant")throw new Error("Invalid message role");if(typeof P!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");A.push({role:"assistant",content:P})}return[o,...c,...A]}let d=this.sig.getInputFields(),m=d.filter(A=>A.isCached),h=d.filter(A=>!A.isCached),g=m.length>0;if(this.contextCache&&g&&(this.ignoreBreakpoints||u!=="system"&&u!=="after-functions")&&h.length>0){let A=m.map(R=>this.renderInField(R,e,void 0)).filter(R=>R!==void 0).flat();A.filter(R=>R.type==="text").forEach(R=>{R.text=`${R.text}
283
+ `),[]);if(S.role==="user"){C&&r&&(typeof P=="string"?P=qt+P:P=[{type:"text",text:qt},...P],C=!1),A.push({role:"user",content:P});continue}if(S.role!=="assistant")throw new Error("Invalid message role");if(typeof P!="string")throw new Error("Assistant message cannot contain non-text content like images, files, etc");A.push({role:"assistant",content:P})}return[o,...c,...A]}let d=this.sig.getInputFields(),m=d.filter(A=>A.isCached),h=d.filter(A=>!A.isCached),g=m.length>0;if(this.contextCache&&g&&(this.ignoreBreakpoints||u!=="system"&&u!=="after-functions")&&h.length>0){let A=m.map(R=>this.renderInField(R,e,void 0)).filter(R=>R!==void 0).flat();A.filter(R=>R.type==="text").forEach(R=>{R.text=`${R.text}
284
284
  `});let I=A.every(R=>R.type==="text")?A.map(R=>R.text).join(`
285
285
  `):A.reduce(Pt(`
286
- `),[]);r&&(typeof I=="string"?I=jt+I:I=[{type:"text",text:jt},...I]);let C=h.map(R=>this.renderInField(R,e,void 0)).filter(R=>R!==void 0).flat();C.filter(R=>R.type==="text").forEach(R=>{R.text=`${R.text}
286
+ `),[]);r&&(typeof I=="string"?I=qt+I:I=[{type:"text",text:qt},...I]);let C=h.map(R=>this.renderInField(R,e,void 0)).filter(R=>R!==void 0).flat();C.filter(R=>R.type==="text").forEach(R=>{R.text=`${R.text}
287
287
  `});let S=C.every(R=>R.type==="text")?C.map(R=>R.text).join(`
288
288
  `):C.reduce(Pt(`
289
289
  `),[]);return[o,...c,{role:"user",content:I,cache:!0},{role:"user",content:S}]}let x=this.sortFieldsCachedFirst(d).map(A=>this.renderInField(A,e,void 0)).filter(A=>A!==void 0).flat();x.filter(A=>A.type==="text").forEach(A=>{A.text=`${A.text}
290
290
  `});let b=x.every(A=>A.type==="text")?x.map(A=>A.text).join(`
291
291
  `):x.reduce(Pt(`
292
- `),[]);r&&(typeof b=="string"?b=jt+b:b=[{type:"text",text:jt},...b]);let T=g&&h.length===0&&this.contextCache;return[o,...c,{role:"user",content:b,...T?{cache:!0}:{}}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,a)=>{let l=a.title;return o[l]||(o[l]=[]),o[l].push(a),o},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([o,a])=>{if(a.length===1){let l=a[0];return l.type?.name==="object"||l.type?.isArray&&l.type.fields?{title:o,name:l.name,description:`${l.description}
292
+ `),[]);r&&(typeof b=="string"?b=qt+b:b=[{type:"text",text:qt},...b]);let T=g&&h.length===0&&this.contextCache;return[o,...c,{role:"user",content:b,...T?{cache:!0}:{}}]};renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((o,a)=>{let l=a.title;return o[l]||(o[l]=[]),o[l].push(a),o},{}),r=this.sig.hasComplexFields();return Object.entries(n).map(([o,a])=>{if(a.length===1){let l=a[0];return l.type?.name==="object"||l.type?.isArray&&l.type.fields?{title:o,name:l.name,description:`${l.description}
293
293
  IMPORTANT: Provide the FULL JSON object for this field, matching the schema exactly.`}:{title:o,name:l.name,description:l.description}}if(a.length>1){let l=a.map(c=>`- ${c.description}`).join(`
294
294
  `);return{title:o,name:a[0].name,description:l}}}).filter(Boolean).forEach(o=>{let a=this.fieldTemplates?.[o.name]??this.defaultRenderInField;t.push(...a(o,o.description))}),t};renderExamples=e=>{let t=[],n={isExample:!0},r=this.sig.hasComplexFields();for(let[s,o]of e.entries()){if(r){let u=this.sig.getInputFields().map(g=>this.renderInField(g,o,{...n,isInputField:!0})).filter(g=>g!==void 0).flat(),p=this.sig.getOutputFields(),d={};for(let g of p)g.name in o&&(d[g.name]=o[g.name]);let m=JSON.stringify(d,null,2),h=[...u,{type:"text",text:`\`\`\`json
295
295
  ${m}
@@ -309,29 +309,29 @@ ${m}
309
309
  `):a.reduce(Pt(`
310
310
  `),[]);if(r&&this.structuredOutputFunctionName){let d={};for(let g of this.sig.getOutputFields())g.name in s&&(d[g.name]=s[g.name]);if(typeof l=="string"&&l.trim()===""||Array.isArray(l)&&l.length===0||Object.keys(d).length===0)continue;let h=`example-${t.length}`;t.push({userMessage:{role:"user",content:l},assistantMessage:{role:"assistant",functionCalls:[{id:h,type:"function",function:{name:this.structuredOutputFunctionName,params:d}}]},functionResultMessage:{role:"function",result:"done",functionId:h}});continue}let c;if(r){let d={};for(let m of this.sig.getOutputFields())m.name in s&&(d[m.name]=s[m.name]);c=JSON.stringify(d,null,2)}else c=this.sig.getOutputFields().map(m=>this.renderInField(m,s,{...n,isInputField:!1})).filter(m=>m!==void 0).flat().filter(m=>m.type==="text").map(m=>m.text).join(`
311
311
  `);let u=typeof l=="string"&&l.trim()===""||Array.isArray(l)&&l.length===0,p=c.trim()==="";u||p||t.push({userMessage:{role:"user",content:l},assistantMessage:{role:"assistant",content:c}})}return t};renderDemosAsMessages=e=>this.renderExamplesAsMessages(e);renderInputFields=e=>{let n=this.sortFieldsCachedFirst(this.sig.getInputFields()).map(r=>this.renderInField(r,e,void 0)).filter(r=>r!==void 0).flat();return n.filter(r=>r.type==="text").forEach(r=>{r.text=`${r.text}
312
- `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(_c(e,r,n))return;e.type&&vr(e,r);let s=Fc(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,s)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=o=>{if(!o)throw new Error("Image field value is required.");if(typeof o!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in o))throw new Error("Image field must have mimeType");if(!("data"in o))throw new Error("Image field must have data");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let o=r(t);s.push({type:"image",mimeType:o.mimeType,image:o.data})}return s}if(e.type?.name==="audio"){let r=o=>{if(!o)throw new Error("Audio field value is required.");if(typeof o!="object")throw new Error("Audio field value must be an object.");if(!("data"in o))throw new Error("Audio field must have data");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let o=r(t);s.push({type:"audio",format:o.format??"wav",data:o.data})}return s}if(e.type?.name==="file"){let r=o=>{if(!o)throw new Error("File field value is required.");if(typeof o!="object")throw new Error("File field value must be an object.");if(!("mimeType"in o))throw new Error("File field must have mimeType");let a="data"in o,l="fileUri"in o;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 o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let o=r(t);s.push("fileUri"in o?{type:"file",mimeType:o.mimeType,fileUri:o.fileUri}:{type:"file",mimeType:o.mimeType,data:o.data})}return s}if(e.type?.name==="url"){let r=o=>{if(!o)throw new Error("URL field value is required.");if(typeof o=="string")return{url:o};if(typeof o!="object")throw new Error("URL field value must be a string or object.");if(!("url"in o))throw new Error("URL field must have url property");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let o=r(t);s.push({type:"url",url:o.url,...o.title?{title:o.title}:{},...o.description?{description:o.description}:{}})}return s}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
312
+ `}),n};renderInField=(e,t,n)=>{let r=t[e.name];if(Nc(e,r,n))return;e.type&&Sr(e,r);let s=Fc(e,r);return(this.fieldTemplates?.[e.name]??this.defaultRenderInField)(e,s)};defaultRenderInField=(e,t)=>{if(e.type?.name==="image"){let r=o=>{if(!o)throw new Error("Image field value is required.");if(typeof o!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in o))throw new Error("Image field must have mimeType");if(!("data"in o))throw new Error("Image field must have data");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let o=r(t);s.push({type:"image",mimeType:o.mimeType,image:o.data})}return s}if(e.type?.name==="audio"){let r=o=>{if(!o)throw new Error("Audio field value is required.");if(typeof o!="object")throw new Error("Audio field value must be an object.");if(!("data"in o))throw new Error("Audio field must have data");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"audio",format:a.format??"wav",data:a.data}}))}else{let o=r(t);s.push({type:"audio",format:o.format??"wav",data:o.data})}return s}if(e.type?.name==="file"){let r=o=>{if(!o)throw new Error("File field value is required.");if(typeof o!="object")throw new Error("File field value must be an object.");if(!("mimeType"in o))throw new Error("File field must have mimeType");let a="data"in o,l="fileUri"in o;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 o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("File field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return"fileUri"in a?{type:"file",mimeType:a.mimeType,fileUri:a.fileUri}:{type:"file",mimeType:a.mimeType,data:a.data}}))}else{let o=r(t);s.push("fileUri"in o?{type:"file",mimeType:o.mimeType,fileUri:o.fileUri}:{type:"file",mimeType:o.mimeType,data:o.data})}return s}if(e.type?.name==="url"){let r=o=>{if(!o)throw new Error("URL field value is required.");if(typeof o=="string")return{url:o};if(typeof o!="object")throw new Error("URL field value must be a string or object.");if(!("url"in o))throw new Error("URL field must have url property");return o},s=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("URL field value must be an array.");s=s.concat(t.map(o=>{let a=r(o);return{type:"url",url:a.url,...a.title?{title:a.title}:{},...a.description?{description:a.description}:{}}}))}else{let o=r(t);s.push({type:"url",url:o.url,...o.title?{title:o.title}:{},...o.description?{description:o.description}:{}})}return s}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
313
313
  `),n.push(t.map(r=>`- ${r}`).join(`
314
- `))):n.push(t),[{type:"text",text:n.join("")}]}},$r=i=>i.map(e=>`\`${e.title}\``).join(", "),La=(i,e)=>i.map(n=>{let r=n.title,s=n.type?.name?Ga(n.type):"string",o=n.isOptional?`This optional ${s} field may be omitted`:`A ${s} field`,a="";if(n.description){let l=qt(n.description);e&&(l=Gr(l,e)),a=` ${l}`}return`${r}: (${o})${a}`.trim()}).join(`
315
- `),$a=(i,e)=>i.map(n=>{let r=n.title,s=n.type?.name?Ga(n.type):"string",o=n.isOptional?`Only include this ${s} field if its value is available`:`This ${s} field must be included`,a="";if(n.description&&n.description.length>0){let l=n.type?.name==="class"?n.description:qt(n.description);e&&(l=Gr(l,e)),a=` ${l}`}return n.type?.options&&n.type.options.length>0&&(a.length>0&&(a+=". "),a+=`Allowed values: ${n.type.options.join(", ")}`),`${r}: (${o})${a}`.trim()}).join(`
316
- `),Fc=(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?Aa(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)},Ga=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)";case"object":return"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Pt(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 _c=(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 qt(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Gr(i,e){if(e.size===0)return i;let t=i,n=Array.from(e.keys()).sort((r,s)=>s.length-r.length);for(let r of n){let s=e.get(r),o=new RegExp(`\`${r}\``,"g");t=t.replace(o,`\`${s}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${s}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${s}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${s}]`);let u=new RegExp(`\\(${r}\\)`,"g");t=t.replace(u,`(${s})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${s}\``)}return t}function Nc(i,e){let t=i.history(0,e),n=t.some(s=>s.role==="function");return t.some(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0)&&n}function Lc(i,e){let t=i.history(0,e),n=[],r=t.filter(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0),s=t.filter(o=>o.role==="function");for(let o of r)if("functionCalls"in o&&o.functionCalls)for(let a of o.functionCalls){let l=s.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 Dr(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Nc(t,n):!1)&&t){let l=Lc(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 o=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:o});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 Da(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(o=>({version:0,index:o.index,delta:o.value}));return await Dr(r,t,i,e)}var Fn=class{_stepIndex=0;maxSteps;_functionsExecuted=new Set;_lastFunctionCalls=[];_usage={promptTokens:0,completionTokens:0,totalTokens:0};state=new Map;_pendingOptions={};_functionsToAdd=[];_functionsToRemove=[];_stopRequested=!1;_stopResultValues;constructor(e){this.maxSteps=e}get stepIndex(){return this._stepIndex}get isFirstStep(){return this._stepIndex===0}get functionsExecuted(){return this._functionsExecuted}get lastFunctionCalls(){return this._lastFunctionCalls}get usage(){return this._usage}setModel(e){this._pendingOptions.model=e}setThinkingBudget(e){this._pendingOptions.thinkingTokenBudget=e}setTemperature(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.temperature=e}setMaxTokens(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.maxTokens=e}setOptions(e){Object.assign(this._pendingOptions,e)}addFunctions(e){this._functionsToAdd.push(...e)}removeFunctions(...e){this._functionsToRemove.push(...e)}stop(e){this._stopRequested=!0,this._stopResultValues=e}_beginStep(e){this._stepIndex=e,this._functionsExecuted=new Set,this._lastFunctionCalls=[]}_recordFunctionCall(e,t,n){this._functionsExecuted.add(e.toLowerCase()),this._lastFunctionCalls.push({name:e,args:t,result:n})}_addUsage(e,t,n){this._usage.promptTokens+=e,this._usage.completionTokens+=t,this._usage.totalTokens+=n}_consumePendingOptions(){if(Object.keys(this._pendingOptions).length===0)return;let e=this._pendingOptions;return this._pendingOptions={},e}_consumeFunctionsToAdd(){if(this._functionsToAdd.length===0)return;let e=this._functionsToAdd;return this._functionsToAdd=[],e}_consumeFunctionsToRemove(){if(this._functionsToRemove.length===0)return;let e=this._functionsToRemove;return this._functionsToRemove=[],e}get _isStopRequested(){return this._stopRequested}get _stopValues(){return this._stopResultValues}};var Ur=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}=$c(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},s=new Map,o=new Map;for(let[a,l]of this.tools.entries())o.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"&&s.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let p=o.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=s.get(u.name)??{};this.setNested(m,d,l),s.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=s.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new ke(`Missing required arguments for tool '${l.name}': ${p.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,s)=>{for(let[o,a]of Object.entries(r)){let l=[...s,o];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let o=t[s],a=r[o];(typeof a!="object"||a===null)&&(r[o]={}),r=r[o]}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 $c(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||[],s=(o,a,l)=>{for(let[c,u]of Object.entries(o)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)s(u.properties,p,u.required||[]);else{let m=Gc(u);e.push({name:Uc(d),title:Dc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function Gc(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 Dc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Uc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function ja(i,e,t){let n=new fe(e);if(t){let r=t.getToolParamFieldMap();for(let s of i){let o=r.get(s.name);if(o&&o.size>0)for(let a of o.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=Ao(s.name),l=Ba(s.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Ua(s.name),type:l,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let s of i)if(s.parameters?.properties&&Object.keys(s.parameters.properties).length>0){let{fields:o,paramFieldMap:a}=Bc(s);r.set(s.name,a);for(let l of o)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let o=Ao(s.name),a=Ba(s.parameters);n.getOutputFields().some(c=>c.name===o)||n.addOutputField({name:o,title:Ua(s.name),type:a,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function Bc(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||[],s=(o,a,l)=>{for(let[c,u]of Object.entries(o)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)s(u.properties,p,u.required||[]);else{let m=jc(u),h={name:Ao(d),title:qc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(h),t.set(d,h)}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function jc(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 qc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Ao(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ua(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Ba(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var _n=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Ur(e)}processSignature(e){let{signature:t}=ja(this.tools,e),n=new Set(t.getOutputFields().map(s=>s.name)),r=new Set(e.getOutputFields().map(s=>s.name));return this.injectedToolFieldNames=new Set([...n].filter(s=>!r.has(s))),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 Ht="__finalResult",Ae=class i extends Mt{clone=()=>new i(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;structuredOutputFunctionFallback=!1;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??zt)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Ot(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return eo()}getMergedCustomLabels(e,t){return wt(Z.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){eo(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 s=r.type?.name;if(!(!s||s==="string"||s==="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(s=>s.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let s=r.type?.name;if(!(!s||s==="string"||s==="code"))throw new Error(`addFieldProcessor: field ${e} 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:s,functionCall:o,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},h=await Da(t,l,{resultPicker:n?.resultPicker}),g=t?.history(h,l)??[];if(g.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},y=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);s=this.signatureToolCallingManager?[]:s;let T,A=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);T={type:"json_schema",schema:{name:"output",strict:!0,schema:Mn(A)}}}let C=n?.contextCache?.cacheBreakpoint??"after-examples",S=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,R=n?.contextCache&&(S||C==="after-functions"||C==="after-examples"),P=s?.length&&R?s.map((w,v)=>({...w,cache:v===s.length-1})):s;return await e.chat({chatPrompt:g,functions:P,functionCall:o,modelConfig:f,model:c,responseFormat:T},{sessionId:l,rateLimiter:u,stream:p,debug:y,debugHideSystemPrompt:!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??Z.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:s,traceContext:o,states:a,stopFunctionNames:l,stepContext:c}){let{sessionId:u,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,h=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,y=this.usage,x=r===0,b=this.isDebug(e,n),T=this.getLogger(e,n),{functions:A,functionCall:I}=va(p,m,x,n);this.structuredOutputFunctionFallback&&A.filter(R=>R.name!==Ht).length===0&&(I={type:"function",function:{name:Ht}});let C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:A,functionCall:I,stepIndex:r});C instanceof ReadableStream?yield*ka({ai:e,model:f,res:C,mem:t,sessionId:u,traceId:s?s.spanContext?.().traceId:void 0,functions:A,strictMode:g,span:s,states:a,usage:y,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:b,functionResultFormatter:d,signatureToolCallingManager:h,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c}):yield*Oa({ai:e,model:f,res:C,mem:t,sessionId:u,traceId:s?s.spanContext?.().traceId:void 0,functions:A,span:s,strictMode:g,states:a,usage:y,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:b,functionResultFormatter:d,signatureToolCallingManager:h,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c})}async*_forward2(e,t,n,r,s,o){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??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new vn,d=[...this.functions,...r.functions?Ot(r.functions):[]],m=new Fn(u);if(r.selfTuning){let F=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,q=Pa(e,F);d.push(q)}let h={...r},g=r.stepHooks,f=d&&d.length>0,y=r.functionCallMode??this.options?.functionCallMode??"auto";f&&y==="prompt"&&(this.signatureToolCallingManager=new _n(d)),f&&y==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new _n(d));let x,b,T=this.options?.promptTemplate??zt;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A=this.signature.hasComplexFields(),I=e.getFeatures?.(r.model),C=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=A&&(C==="function"||C==="auto"&&!I?.structuredOutputs),this.structuredOutputFunctionFallback){let F={name:Ht,description:"Return the final result. Call this function with the complete output data.",parameters:Mn(this.signature.getOutputFields()),func:async()=>"done"};d.push(F),l=[...l??[],Ht.toLowerCase()]}let S=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,R={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:S,structuredOutputFunctionName:this.structuredOutputFunctionFallback?Ht:void 0};this.promptTemplate=new T(this.signature,R);let P,E=performance.now();Array.isArray(t)?(Pi(t),P=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):P=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let w=performance.now()-E,v=this.getMetricsInstruments(),k=this.getMergedCustomLabels(e,r);v&&Cr(v,"prompt_render",w,this.getSignatureName(),k);let O=performance.now();p.addRequest(P,r.sessionId);let N=performance.now()-O;v&&Cr(v,"memory_update",N,this.getSignatureName(),k);let M=new Map;n.forEach(F=>{M.set(F.index,{})});let D=()=>{let F=m._consumePendingOptions();if(F){let{modelConfig:oe,...U}=F;h={...h,...U},oe&&(h.modelConfig={...h.modelConfig,...oe})}let q=m._consumeFunctionsToAdd();if(q){let oe=Ot(q);for(let U of oe)d.some(ae=>ae.name===U.name)||d.push(U)}let Y=m._consumeFunctionsToRemove();if(Y){let oe=new Set(Y.map(U=>U.toLowerCase()));for(let U=d.length-1;U>=0;U--)oe.has(d[U].name.toLowerCase())&&d.splice(U,1)}};e:for(let F=0;F<u&&(m._beginStep(F),D(),!(m._isStopRequested||g?.beforeStep&&(await g.beforeStep(m),D(),m._isStopRequested)));F++){let q=c;for(let Y=0;Y<=q;Y++)try{for(let U=0;U<c;U++){n.forEach(ne=>{ne.content="",ne.values={},ne.functionCalls=[],ne.functionsExecuted=new Set,ne.xstate={extractedFields:[],streamedIndex:{},s:-1}}),U>0&&M.forEach((ne,Re)=>{M.set(Re,{})});let ae=new Map;n.forEach(ne=>{ae.set(ne.index,{})});try{let ne=this.forwardCore({options:{...h,functions:d},ai:e,mem:p,stepIndex:F,span:s,traceContext:o,states:n,stopFunctionNames:l,stepContext:m}),Re=!1;try{for await(let re of ne)if(re!==void 0){let ye=re.index,he=re.delta,we=ae.get(ye)??{},be=M.get(ye)??{},z={},W=!1;for(let G of Object.keys(he)){let B=he[G],K=we[G],X;typeof B=="string"&&(typeof K=="string"||K===void 0)?X=(K??"")+B:Array.isArray(B)&&(Array.isArray(K)||K===void 0)?X=[...K??[],...B]:X=B,we[G]=X;let _=X,$=be[G];if(typeof _=="string"&&typeof $=="string")if(_.startsWith($)){let L=_.slice($.length);L&&(z[G]=L,W=!0,be[G]=_)}else $.startsWith(_)||_!==$&&(z[G]=_,W=!0,be[G]=_);else if(Array.isArray(_)&&Array.isArray($)){if(_.length>$.length){let L=_.slice($.length);z[G]=L,W=!0,be[G]=_}}else JSON.stringify(_)!==JSON.stringify($)&&(z[G]=_,W=!0,be[G]=_)}W&&(yield{version:U,index:re.index,delta:z})}}catch(re){if(re instanceof Bt){if(Re=!0,this.structuredOutputFunctionFallback){let ye=re.calls.find(he=>he.func.name===Ht);if(ye?.args){let he=ye.args;Ut(this.signature,he);let we=this.signature.getOutputFields();for(let be of n){let z={};for(let W of we)W.name in he&&!W.isInternal&&(z[W.name]=he[W.name],be.values[W.name]=he[W.name]);yield{version:U,index:be.index,delta:z}}for(let be of n)await $t(this.asserts,be.values);if(this.fieldProcessors.length>0)for(let be of n)await On(this.fieldProcessors,be.values,p,r.sessionId)}}}else throw re}if(this.usage.length>0){let re=this.usage[this.usage.length-1];re?.tokens&&m._addUsage(re.tokens.promptTokens??0,re.tokens.completionTokens??0,re.tokens.totalTokens??0)}n.some(re=>re.functionsExecuted.size>0)&&g?.afterFunctionExecution&&(await g.afterFunctionExecution(m),D());let ht=Re||m._isStopRequested?!1:Ma(p,l,n,h?.sessionId);if(g?.afterStep&&(await g.afterStep(m),D()),ht&&!m._isStopRequested){let re=this.getMetricsInstruments();re&&Tr(re,F+1,u,this.getSignatureName(),k);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let De=this.getMetricsInstruments();if(De){Tr(De,F+1,u,this.getSignatureName(),k);let re=new Set;n.forEach(ye=>{ye.functionsExecuted.forEach(he=>re.add(he))}),re.size>0&&na(De,!0,re.size,!0,!1,this.getSignatureName(),k),ra(De,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),k)}return}catch(ne){b=ne;let Re,ot=this.isDebug(e,r),ht=this.getLogger(e,r),De=this.getMetricsInstruments(),re=this.getSignatureName(),ye={error:ne,errCount:U,logger:ht,metricsInstruments:De,signatureName:re,span:s,debug:ot,customLabels:k};if(s?.recordException(ne),ne instanceof ke)Re=ma(ye),x=ne;else if(ne instanceof mt)Re=ga(ye),x=ne;else if(ne instanceof ge)ha(ye);else if(!(ne instanceof Ze)){let he=ne,we=he instanceof Ue&&he.status>=500&&he.status<600,be=he instanceof Pe,z=he instanceof We;throw we||be||z?ne:yo(ne,e,this.signature)}if(Re&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(Re)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let we of n)we.content="",we.values={},we.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let oe=this.getMetricsInstruments();throw oe&&no(oe,c,!1,c,this.getSignatureName(),k),yo(new Error(`Unable to fix validation error: ${(x??b)?.message??(x??b)?.toString()??"unknown error"}
314
+ `))):n.push(t),[{type:"text",text:n.join("")}]}},Gr=i=>i.map(e=>`\`${e.title}\``).join(", "),$a=(i,e)=>i.map(n=>{let r=n.title,s=n.type?.name?Et(n.type):"string",o=n.isOptional?`This optional ${s} field may be omitted`:`${/^[aeiou]/i.test(s)?"An":"A"} ${s} field`,a="";if(n.description){let l=zt(n.description);e&&(l=Dr(l,e)),a=` ${l}`}return`${r}: (${o})${a}`.trim()}).join(`
315
+ `),Ga=(i,e)=>i.map(n=>{let r=n.title,s=n.type?.name?Et(n.type):"string",o=n.isOptional?`Only include this ${s} field if its value is available`:`This ${s} field must be included`,a="";if(n.description&&n.description.length>0){let l=n.type?.name==="class"?n.description:zt(n.description);e&&(l=Dr(l,e)),a=` ${l}`}return n.type?.options&&n.type.options.length>0&&(a.length>0&&(a+=". "),a+=`Allowed values: ${n.type.options.join(", ")}`),`${r}: (${o})${a}`.trim()}).join(`
316
+ `),Fc=(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?ya(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)};function _c(i){return`{ ${Object.entries(i).map(([t,n])=>{let r=n.isOptional?"?":"",s=Et({name:n.type,isArray:n.isArray,fields:n.fields,options:n.options});return`${t}${r}: ${s}`}).join(", ")} }`}var Et=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)";case"object":return i?.fields?`object ${_c(i.fields)}`:"object";default:return"string"}})();return i?.isArray?`json array of ${e} items`:e};function Pt(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 Nc=(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 zt(i){let e=i.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function Dr(i,e){if(e.size===0)return i;let t=i,n=Array.from(e.keys()).sort((r,s)=>s.length-r.length);for(let r of n){let s=e.get(r),o=new RegExp(`\`${r}\``,"g");t=t.replace(o,`\`${s}\``);let a=new RegExp(`"${r}"`,"g");t=t.replace(a,`"${s}"`);let l=new RegExp(`'${r}'`,"g");t=t.replace(l,`'${s}'`);let c=new RegExp(`\\[${r}\\]`,"g");t=t.replace(c,`[${s}]`);let u=new RegExp(`\\(${r}\\)`,"g");t=t.replace(u,`(${s})`);let p=new RegExp(`\\$${r}\\b`,"g");t=t.replace(p,`\`${s}\``)}return t}function Lc(i,e){let t=i.history(0,e),n=t.some(s=>s.role==="function");return t.some(s=>s.role==="assistant"&&"functionCalls"in s&&Array.isArray(s.functionCalls)&&s.functionCalls.length>0)&&n}function $c(i,e){let t=i.history(0,e),n=[],r=t.filter(o=>o.role==="assistant"&&"functionCalls"in o&&Array.isArray(o.functionCalls)&&o.functionCalls.length>0),s=t.filter(o=>o.role==="function");for(let o of r)if("functionCalls"in o&&o.functionCalls)for(let a of o.functionCalls){let l=s.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 Ur(i,e,t,n){if(!e?.resultPicker||i.length<=1)return 0;let r=e.resultPicker;if((t?Lc(t,n):!1)&&t){let l=$c(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 o=i.map((l,c)=>({index:c,sample:l.delta})),a=await r({type:"fields",results:o});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 Da(i,e,t){let n=i?.getLast(e);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let r=n.chat.map(o=>({version:0,index:o.index,delta:o.value}));return await Ur(r,t,i,e)}var _n=class{_stepIndex=0;maxSteps;_functionsExecuted=new Set;_lastFunctionCalls=[];_usage={promptTokens:0,completionTokens:0,totalTokens:0};state=new Map;_pendingOptions={};_functionsToAdd=[];_functionsToRemove=[];_stopRequested=!1;_stopResultValues;constructor(e){this.maxSteps=e}get stepIndex(){return this._stepIndex}get isFirstStep(){return this._stepIndex===0}get functionsExecuted(){return this._functionsExecuted}get lastFunctionCalls(){return this._lastFunctionCalls}get usage(){return this._usage}setModel(e){this._pendingOptions.model=e}setThinkingBudget(e){this._pendingOptions.thinkingTokenBudget=e}setTemperature(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.temperature=e}setMaxTokens(e){this._pendingOptions.modelConfig||(this._pendingOptions.modelConfig={}),this._pendingOptions.modelConfig.maxTokens=e}setOptions(e){Object.assign(this._pendingOptions,e)}addFunctions(e){this._functionsToAdd.push(...e)}removeFunctions(...e){this._functionsToRemove.push(...e)}stop(e){this._stopRequested=!0,this._stopResultValues=e}_beginStep(e){this._stepIndex=e,this._functionsExecuted=new Set,this._lastFunctionCalls=[]}_recordFunctionCall(e,t,n){this._functionsExecuted.add(e.toLowerCase()),this._lastFunctionCalls.push({name:e,args:t,result:n})}_addUsage(e,t,n){this._usage.promptTokens+=e,this._usage.completionTokens+=t,this._usage.totalTokens+=n}_consumePendingOptions(){if(Object.keys(this._pendingOptions).length===0)return;let e=this._pendingOptions;return this._pendingOptions={},e}_consumeFunctionsToAdd(){if(this._functionsToAdd.length===0)return;let e=this._functionsToAdd;return this._functionsToAdd=[],e}_consumeFunctionsToRemove(){if(this._functionsToRemove.length===0)return;let e=this._functionsToRemove;return this._functionsToRemove=[],e}get _isStopRequested(){return this._stopRequested}get _stopValues(){return this._stopResultValues}};var Br=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}=Gc(t);e.set(t.name,n)}else e.set(t.name,new Map);return e}async route(e,t){let n=[],r={},s=new Map,o=new Map;for(let[a,l]of this.tools.entries())o.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"&&s.set(c.name,l);continue}r[a]=l}for(let[a,l]of Object.entries(e))for(let[c,u]of this.tools.entries()){let p=o.get(c);if(!p)continue;let d=p.get(a);if(!d)continue;let m=s.get(u.name)??{};this.setNested(m,d,l),s.set(u.name,m)}for(let[a,l]of this.tools.entries()){let c=s.get(l.name);if(!(!c||Object.keys(c).length===0)){if(l.parameters&&l.parameters.type==="object"){let p=(l.parameters.required||[]).filter(d=>c[d]===void 0);if(p.length>0)throw new ke(`Missing required arguments for tool '${l.name}': ${p.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,s)=>{for(let[o,a]of Object.entries(r)){let l=[...s,o];if(a&&a.type==="object"&&a.properties)n(a.properties,l);else{let c=`${e.name}.${l.join(".")}`,u=this.sanitizeFieldName(c);t.set(u,l)}}};return n(e.parameters.properties??{},[]),t}setNested(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let o=t[s],a=r[o];(typeof a!="object"||a===null)&&(r[o]={}),r=r[o]}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 Gc(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||[],s=(o,a,l)=>{for(let[c,u]of Object.entries(o)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)s(u.properties,p,u.required||[]);else{let m=Dc(u);e.push({name:Bc(d),title:Uc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0}),t.set(d,e[e.length-1])}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function Dc(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 Uc(i,e){return`${i} ${e.replace(/\./g," ")}`}function Bc(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function ja(i,e,t){let n=new fe(e);if(t){let r=t.getToolParamFieldMap();for(let s of i){let o=r.get(s.name);if(o&&o.size>0)for(let a of o.values())n.getOutputFields().some(c=>c.name===a.name)||n.addOutputField(a);else{let a=yo(s.name),l=Ba(s.parameters);n.getOutputFields().some(u=>u.name===a)||n.addOutputField({name:a,title:Ua(s.name),type:l,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}}return{signature:n,toolParamFieldMap:r}}else{let r=new Map;for(let s of i)if(s.parameters?.properties&&Object.keys(s.parameters.properties).length>0){let{fields:o,paramFieldMap:a}=jc(s);r.set(s.name,a);for(let l of o)n.getOutputFields().some(u=>u.name===l.name)||n.addOutputField(l)}else{let o=yo(s.name),a=Ba(s.parameters);n.getOutputFields().some(c=>c.name===o)||n.addOutputField({name:o,title:Ua(s.name),type:a,description:s.description||`Parameters for ${s.name}`,isOptional:!0})}return{signature:n,toolParamFieldMap:r}}}function jc(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||[],s=(o,a,l)=>{for(let[c,u]of Object.entries(o)){let p=a?`${a}.${c}`:c,d=`${i.name}.${p}`;if(u.type==="object"&&u.properties)s(u.properties,p,u.required||[]);else{let m=qc(u),h={name:yo(d),title:zc(i.name,p),type:m,description:u.description||`${c} parameter for ${i.name}`,isOptional:!0};e.push(h),t.set(d,h)}}};return s(n,"",r),{fields:e,paramFieldMap:t}}function qc(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 zc(i,e){return`${i} ${e.replace(/\./g," ")}`}function yo(i){return i.replace(/([A-Z])/g,"_$1").toLowerCase().replace(/^_|_$/g,"").replace(/[^a-z0-9_]/g,"_")}function Ua(i){return i.replace(/([A-Z])/g," $1").replace(/^./,e=>e.toUpperCase()).trim()}function Ba(i){return!i||!i.properties||Object.keys(i.properties).length===0?{name:"string",isArray:!1}:{name:"json",isArray:!1}}var Nn=class{tools;router;injectedToolFieldNames=new Set;constructor(e){this.tools=e,this.router=new Br(e)}processSignature(e){let{signature:t}=ja(this.tools,e),n=new Set(t.getOutputFields().map(s=>s.name)),r=new Set(e.getOutputFields().map(s=>s.name));return this.injectedToolFieldNames=new Set([...n].filter(s=>!r.has(s))),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 Kt="__finalResult",Ae=class i extends Mt{clone=()=>new i(this.signature,this.options);promptTemplate;asserts;streamingAsserts;options;functions;fieldProcessors=[];streamingFieldProcessors=[];excludeContentFromTrace=!1;thoughtFieldName;signatureToolCallingManager;structuredOutputFunctionFallback=!1;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??Ht)(this.signature,n),this.asserts=this.options?.asserts??[],this.streamingAsserts=this.options?.streamingAsserts??[],this.excludeContentFromTrace=t?.excludeContentFromTrace??!1,this.functions=t?.functions?Ot(t.functions):[],this.usage=[]}setInstruction(e){this.promptTemplate.setInstruction(e)}getInstruction(){return this.promptTemplate.getInstruction()}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return to()}getMergedCustomLabels(e,t){return wt(Z.customLabels,e?.getOptions?.()?.customLabels,t?.customLabels)}updateMeter(e){to(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 s=r.type?.name;if(!(!s||s==="string"||s==="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(s=>s.name===e);if(!r)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let s=r.type?.name;if(!(!s||s==="string"||s==="code"))throw new Error(`addFieldProcessor: field ${e} 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:s,functionCall:o,stepIndex:a}){let{sessionId:l,model:c,rateLimiter:u,stream:p,thinkingTokenBudget:d,showThoughts:m}=n??{},h=await Da(t,l,{resultPicker:n?.resultPicker}),g=t?.history(h,l)??[];if(g.length===0)throw new Error("No chat prompt found");let f={...n?.modelConfig,...n?.sampleCount?{n:n.sampleCount}:{},...n?.sampleCount&&n?.modelConfig?.temperature===1?{temperature:.8}:{}},y=this.isDebug(e,n),x=a===0,b=this.getLogger(e,n);s=this.signatureToolCallingManager?[]:s;let T,A=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(c)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${c}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);T={type:"json_schema",schema:{name:"output",strict:!0,schema:Pn(A)}}}let C=n?.contextCache?.cacheBreakpoint??"after-examples",S=e.getFeatures?.(c)?.caching?.cacheBreakpoints===!1,R=n?.contextCache&&(S||C==="after-functions"||C==="after-examples"),P=s?.length&&R?s.map((w,v)=>({...w,cache:v===s.length-1})):s;return await e.chat({chatPrompt:g,functions:P,functionCall:o,modelConfig:f,model:c,responseFormat:T},{sessionId:l,rateLimiter:u,stream:p,debug:y,debugHideSystemPrompt:!x,thinkingTokenBudget:d,showThoughts:m,traceContext:r,abortSignal:n?.abortSignal??Z.abortSignal,stepIndex:a,logger:b,functionCallMode:n?.functionCallMode??this.options?.functionCallMode??"auto",retry:n?.retry??this.options?.retry,customLabels:n?.customLabels})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:r,span:s,traceContext:o,states:a,stopFunctionNames:l,stepContext:c}){let{sessionId:u,functions:p}=n??{},d=n?.functionResultFormatter??this.options?.functionResultFormatter,m=n?.functionCall??this.options?.functionCall,h=this.signatureToolCallingManager,g=n?.strictMode??!1,f=n.model,y=this.usage,x=r===0,b=this.isDebug(e,n),T=this.getLogger(e,n),{functions:A,functionCall:I}=Sa(p,m,x,n);this.structuredOutputFunctionFallback&&A.filter(R=>R.name!==Kt).length===0&&(I={type:"function",function:{name:Kt}});let C=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:A,functionCall:I,stepIndex:r});C instanceof ReadableStream?yield*Oa({ai:e,model:f,res:C,mem:t,sessionId:u,traceId:s?s.spanContext?.().traceId:void 0,functions:A,strictMode:g,span:s,states:a,usage:y,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:b,functionResultFormatter:d,signatureToolCallingManager:h,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c}):yield*Ma({ai:e,model:f,res:C,mem:t,sessionId:u,traceId:s?s.spanContext?.().traceId:void 0,functions:A,span:s,strictMode:g,states:a,usage:y,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,logger:T,debug:b,functionResultFormatter:d,signatureToolCallingManager:h,stopFunctionNames:l,disableMemoryCleanup:n.disableMemoryCleanup,stepContext:c})}async*_forward2(e,t,n,r,s,o){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??3,u=r.maxSteps??this.options?.maxSteps??25,p=r.mem??this.options?.mem??new Sn,d=r.functions?Ot(r.functions):[...this.functions],m=new _n(u);if(r.selfTuning){let F=r.selfTuning===!0?{model:!0,thinkingBudget:!0}:r.selfTuning,q=Ea(e,F);d.push(q)}let h={...r},g=r.stepHooks,f=d&&d.length>0,y=r.functionCallMode??this.options?.functionCallMode??"auto";f&&y==="prompt"&&(this.signatureToolCallingManager=new Nn(d)),f&&y==="auto"&&!e.getFeatures(r.model).functions&&(this.signatureToolCallingManager=new Nn(d));let x,b,T=this.options?.promptTemplate??Ht;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let A=this.signature.hasComplexFields(),I=e.getFeatures?.(r.model),C=r.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=A&&(C==="function"||C==="auto"&&!I?.structuredOutputs),this.structuredOutputFunctionFallback){let F={name:Kt,description:"Return the final result. Call this function with the complete output data.",parameters:Pn(this.signature.getOutputFields()),func:async()=>"done"};d.push(F),l=[...l??[],Kt.toLowerCase()]}let S=e.getFeatures?.(r.model)?.caching?.cacheBreakpoints===!1,R={functions:this.signatureToolCallingManager?[]:d,thoughtFieldName:this.thoughtFieldName,contextCache:r.contextCache,examplesInSystem:r.examplesInSystem,ignoreBreakpoints:S,structuredOutputFunctionName:this.structuredOutputFunctionFallback?Kt:void 0};this.promptTemplate=new T(this.signature,R);let P,E=performance.now();Array.isArray(t)?(Ei(t),P=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):P=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let w=performance.now()-E,v=this.getMetricsInstruments(),k=this.getMergedCustomLabels(e,r);v&&Rr(v,"prompt_render",w,this.getSignatureName(),k);let O=performance.now();p.addRequest(P,r.sessionId);let N=performance.now()-O;v&&Rr(v,"memory_update",N,this.getSignatureName(),k);let M=new Map;n.forEach(F=>{M.set(F.index,{})});let D=()=>{let F=m._consumePendingOptions();if(F){let{modelConfig:oe,...U}=F;h={...h,...U},oe&&(h.modelConfig={...h.modelConfig,...oe})}let q=m._consumeFunctionsToAdd();if(q){let oe=Ot(q);for(let U of oe)d.some(ae=>ae.name===U.name)||d.push(U)}let Y=m._consumeFunctionsToRemove();if(Y){let oe=new Set(Y.map(U=>U.toLowerCase()));for(let U=d.length-1;U>=0;U--)oe.has(d[U].name.toLowerCase())&&d.splice(U,1)}};e:for(let F=0;F<u&&(m._beginStep(F),D(),!(m._isStopRequested||g?.beforeStep&&(await g.beforeStep(m),D(),m._isStopRequested)));F++){let q=c;for(let Y=0;Y<=q;Y++)try{for(let U=0;U<c;U++){n.forEach(ne=>{ne.content="",ne.values={},ne.functionCalls=[],ne.functionsExecuted=new Set,ne.xstate={extractedFields:[],streamedIndex:{},s:-1}}),U>0&&M.forEach((ne,Re)=>{M.set(Re,{})});let ae=new Map;n.forEach(ne=>{ae.set(ne.index,{})});try{let ne=this.forwardCore({options:{...h,functions:d},ai:e,mem:p,stepIndex:F,span:s,traceContext:o,states:n,stopFunctionNames:l,stepContext:m}),Re=!1;try{for await(let re of ne)if(re!==void 0){let ye=re.index,he=re.delta,we=ae.get(ye)??{},be=M.get(ye)??{},z={},W=!1;for(let G of Object.keys(he)){let B=he[G],K=we[G],X;typeof B=="string"&&(typeof K=="string"||K===void 0)?X=(K??"")+B:Array.isArray(B)&&(Array.isArray(K)||K===void 0)?X=[...K??[],...B]:X=B,we[G]=X;let _=X,$=be[G];if(typeof _=="string"&&typeof $=="string")if(_.startsWith($)){let L=_.slice($.length);L&&(z[G]=L,W=!0,be[G]=_)}else $.startsWith(_)||_!==$&&(z[G]=_,W=!0,be[G]=_);else if(Array.isArray(_)&&Array.isArray($)){if(_.length>$.length){let L=_.slice($.length);z[G]=L,W=!0,be[G]=_}}else JSON.stringify(_)!==JSON.stringify($)&&(z[G]=_,W=!0,be[G]=_)}W&&(yield{version:U,index:re.index,delta:z})}}catch(re){if(re instanceof jt){if(Re=!0,this.structuredOutputFunctionFallback){let ye=re.calls.find(he=>he.func.name===Kt);if(ye?.args){let he=ye.args;Bt(this.signature,he);let we=this.signature.getOutputFields();for(let be of n){let z={};for(let W of we)W.name in he&&!W.isInternal&&(z[W.name]=he[W.name],be.values[W.name]=he[W.name]);yield{version:U,index:be.index,delta:z}}for(let be of n)await Gt(this.asserts,be.values);if(this.fieldProcessors.length>0)for(let be of n)await Mn(this.fieldProcessors,be.values,p,r.sessionId)}}}else throw re}if(this.usage.length>0){let re=this.usage[this.usage.length-1];re?.tokens&&m._addUsage(re.tokens.promptTokens??0,re.tokens.completionTokens??0,re.tokens.totalTokens??0)}n.some(re=>re.functionsExecuted.size>0)&&g?.afterFunctionExecution&&(await g.afterFunctionExecution(m),D());let ht=Re||m._isStopRequested?!1:Pa(p,l,n,h?.sessionId);if(g?.afterStep&&(await g.afterStep(m),D()),ht&&!m._isStopRequested){let re=this.getMetricsInstruments();re&&Cr(re,F+1,u,this.getSignatureName(),k);continue e}r?.disableMemoryCleanup||(p.removeByTag("invalid-assistant",r.sessionId),p.removeByTag("correction",r.sessionId),p.removeByTag("error",r.sessionId));let De=this.getMetricsInstruments();if(De){Cr(De,F+1,u,this.getSignatureName(),k);let re=new Set;n.forEach(ye=>{ye.functionsExecuted.forEach(he=>re.add(he))}),re.size>0&&ra(De,!0,re.size,!0,!1,this.getSignatureName(),k),sa(De,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),k)}return}catch(ne){b=ne;let Re,ot=this.isDebug(e,r),ht=this.getLogger(e,r),De=this.getMetricsInstruments(),re=this.getSignatureName(),ye={error:ne,errCount:U,logger:ht,metricsInstruments:De,signatureName:re,span:s,debug:ot,customLabels:k};if(s?.recordException(ne),ne instanceof ke)Re=ga(ye),x=ne;else if(ne instanceof mt)Re=ha(ye),x=ne;else if(ne instanceof ge)fa(ye);else if(!(ne instanceof Ze)){let he=ne,we=he instanceof Ue&&he.status>=500&&he.status<600,be=he instanceof Pe,z=he instanceof We;throw we||be||z?ne:bo(ne,e,this.signature)}if(Re&&(p.addTag("error",r.sessionId),p.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(Re)}],r.sessionId),p.addTag("correction",r.sessionId),this.signature.hasComplexFields()))for(let we of n)we.content="",we.values={},we.xstate={extractedFields:[],streamedIndex:{},s:-1}}}let oe=this.getMetricsInstruments();throw oe&&ro(oe,c,!1,c,this.getSignatureName(),k),bo(new Error(`Unable to fix validation error: ${(x??b)?.message??(x??b)?.toString()??"unknown error"}
317
317
 
318
318
  LLM Output:
319
319
  ${n.map(U=>U.content).join(`
320
320
  ---
321
- `)}`),e,this.signature)}catch(oe){let U=oe,ae=U instanceof Ue&&U.status>=500&&U.status<600,ne=U instanceof Pe,Re=U instanceof We,ot=U instanceof Ze;if((ae||ne||Re||ot)&&Y<q){let De=this.isDebug(e,r),re=this.getLogger(e,r),we=Math.min(6e4,1e3*Math.pow(2,Y));De&&re&&re({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${Y+1}/${q+1}): ${U.message}. Retrying in ${we}ms...`}),s?.addEvent("infrastructure.retry",{attempt:Y+1,maxRetries:q,delay:we,errorType:U instanceof Ue?"status_error":U instanceof Pe?"network_error":U instanceof We?"timeout_error":"stream_terminated",errorMessage:U.message}),await new Promise(be=>setTimeout(be,we));continue}throw oe}}throw v&&Tr(v,u,u,this.getSignatureName(),k),yo(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let s=n.type;if(s&&(s.name==="url"&&Ct(r,n),s.name,s.name,(s.name==="string"||s.name==="code")&&Ve(r,n),s.name==="number"&&Je(r,n),s.name==="object"&&s.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,s.fields,n.name),s.isArray&&Array.isArray(r)))for(let o=0;o<r.length;o++){let a=r[o];s.name==="string"||s.name==="code"?Ve(a,n):s.name==="number"?Je(a,n):s.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,s.fields,`${n.name}[${o}]`)}}}validateObjectFields(e,t,n){for(let[r,s]of Object.entries(t)){let o=e[r];if(s.isOptional&&o===void 0)continue;let a={name:`${n}.${r}`,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,format:s.format},description:s.description,isOptional:s.isOptional};if(s.type==="string"||s.type==="code"?Ve(o,a):s.type==="number"?Je(o,a):s.type==="object"&&s.fields&&typeof o=="object"&&o!==null&&this.validateObjectFields(o,s.fields,a.name),s.isArray&&Array.isArray(o))for(let l=0;l<o.length;l++){let c=o[l];s.type==="string"||s.type==="code"?Ve(c,a):s.type==="number"?Je(c,a):s.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,s.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(x=>"role"in x))&&this.validateInputs(t);let r=performance.now(),s=this.createStates(n.sampleCount??1),o=performance.now()-r,a=this.getMetricsInstruments(),l=this.getMergedCustomLabels(e,n);a&&Cr(a,"state_creation",o,this.getSignatureName(),l);let c=n?.tracer??this.options?.tracer??e.getOptions().tracer,u=this.functions;if(n?.functions&&(u=Ot(n.functions,this.functions)),!c){yield*this._forward2(e,t,s,{...n,functions:u});return}let p=u?.map(x=>x.name).join(","),d={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}:{}},m=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,h=m?`AxGen > ${m}`:"AxGen",g=c.startSpan(h,{kind:Hc.SERVER,attributes:d}),f=zc.active(),y=Kc.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,s,{...n,functions:u},g,y),!this.excludeContentFromTrace){let x=s.map(T=>T.values),b=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(b,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&s){let d=await r(s);if(d!==void 0)return d}let o=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,p=!1;try{let d=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);d&&ia(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let h=this._forward1(e,t,n??{}),g=[],f=0,y=0;for await(let S of h)S.version!==f&&(g=[]),f=S.version,g=io(g,S),y++;u=f;let x=performance.now();p=!!n?.resultPicker;let b=await Dr(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),T=performance.now()-x,I=g[b]?.delta??{},C=Array.isArray(t)?{}:t??{};if(this.trace={...C,...I},p&&this.isDebug(e,n)){let S=this.getLogger(e,n);ui(g.length,b,T,S)}if(c=!0,d&&(oa(d,g.length,p,p?T:void 0,a,m),sa(d,l,y,void 0,a,m)),r&&s)try{await r(s,I)}catch{}return I}catch(d){throw c=!1,d}finally{let d=performance.now()-o,m=this.getMetricsInstruments(),h=this.getMergedCustomLabels(e,n);m&&(ea(m,d,c,a,e.getName(),n?.model?String(n.model):void 0,h),u>0&&no(m,u,c,n?.maxRetries??10,a,h))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&s){let p;try{p=await r(s)}catch{}if(p!==void 0){yield{version:0,index:0,delta:p};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let p of o)p.version!==l&&(a=[]),l=p.version,a=io(a,p);let c=await Dr(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&s)try{await r(s,u.delta)}catch{}yield{version:l,index:c,delta:u.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??Z.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??Z.logger??e.getLogger()}computeCacheKey(e,t){let n=Ne("sha256");n.update(this.signature.hash()??"");let r=s=>{let o=typeof s;if(n.update(`|${o}|`),s==null){n.update("null");return}if(o==="string"||o==="number"||o==="boolean"){n.update(String(s));return}if(Array.isArray(s)){n.update("[");for(let a of s)r(a);n.update("]");return}if(typeof s=="object"&&s!==null&&"mimeType"in s&&"data"in s){let a=s;n.update(a.mimeType??"");let l=Ne("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof s=="object"){let a=s,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(s))};if(Array.isArray(e))for(let s of e){n.update(`role:${s.role}`);let o=t.map(a=>s.values?.[a]);for(let a of o)r(a)}else{let s=t.map(o=>e?.[o]);for(let o of s)r(o)}return n.digest("hex")}},Br=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function yo(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let o=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:o,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new Br(`Generate failed: ${n.message}`,l,{cause:n})}var Wc=i=>i.replace(/^\W+|\W+$/g,""),Vc=(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),s=i.substring(t+n[0].length);return[r,s]},Jc=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Qc=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}},Yc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Xc=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},bo={trimNonAlphaNum:Wc,splitIntoTwo:Vc,dedup:Jc,extractIdAndText:Qc,extractIndexPrefixedText:Yc,batchArray:Xc};var Io=class extends Ae{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."
322
- 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),s=r.map(a=>{let{id:l}=bo.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=s[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var To=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 s=await(this.fetch??fetch)(this.tikaUrl,r);if(!s.ok)throw new Error(`Failed to upload file: ${s.statusText}`);return await s.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let s=0;s<e.length;s+=r){let a=e.slice(s,s+r).map(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var ff=new $e,Co=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},Ro=class{ai;db;debug;constructor(e){this.db=new St,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}),s=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;s=s.filter(l=>l.score<=a)}let o=s.at(0);return o?o.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var qa=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 za(i,e){return i.filter(t=>!e.has(t))}function Ha(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function Et(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 Zc(i,e){return Et(i)===Et(e)?1:0}function eu(i,e){let t=Et(i).split(" "),n=Et(e).split(" "),r=Ha(t),s=Ha(n),o=0;for(let c in r){let u=r[c]??0,p=s[c]??0;o+=Math.min(u,p)}if(o===0)return 0;let a=o/t.length,l=o/n.length;return 2*a*l/(a+l)}function tu(i,e,t,n=!1){let r=Et(i).split(" "),s=Et(e).split(" "),o=Et(t).split(" "),a=new Set([...qa,...r]);s=za(s,a),o=za(o,a);let l=0,c=l/s.length,u=l/o.length,p=2*c*u/(c+u);return n?u:p}var nu={emScore:Zc,f1Score:eu,novelF1ScoreOptimized:tu};var wo=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 o=0;o<n;o++){let a=this.examples[o];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 ${o}: ${l instanceof Error?l.message:"Unknown error"}`)}}let s=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
321
+ `)}`),e,this.signature)}catch(oe){let U=oe,ae=U instanceof Ue&&U.status>=500&&U.status<600,ne=U instanceof Pe,Re=U instanceof We,ot=U instanceof Ze;if((ae||ne||Re||ot)&&Y<q){let De=this.isDebug(e,r),re=this.getLogger(e,r),we=Math.min(6e4,1e3*Math.pow(2,Y));De&&re&&re({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${Y+1}/${q+1}): ${U.message}. Retrying in ${we}ms...`}),s?.addEvent("infrastructure.retry",{attempt:Y+1,maxRetries:q,delay:we,errorType:U instanceof Ue?"status_error":U instanceof Pe?"network_error":U instanceof We?"timeout_error":"stream_terminated",errorMessage:U.message}),await new Promise(be=>setTimeout(be,we));continue}throw oe}}throw v&&Cr(v,u,u,this.getSignatureName(),k),bo(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let r=e[n.name];if(n.isOptional&&r===void 0)continue;let s=n.type;if(s&&(s.name==="url"&&Ct(r,n),s.name,s.name,(s.name==="string"||s.name==="code")&&Ve(r,n),s.name==="number"&&Je(r,n),s.name==="object"&&s.fields&&typeof r=="object"&&r!==null&&this.validateObjectFields(r,s.fields,n.name),s.isArray&&Array.isArray(r)))for(let o=0;o<r.length;o++){let a=r[o];s.name==="string"||s.name==="code"?Ve(a,n):s.name==="number"?Je(a,n):s.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,s.fields,`${n.name}[${o}]`)}}}validateObjectFields(e,t,n){for(let[r,s]of Object.entries(t)){let o=e[r];if(s.isOptional&&o===void 0)continue;let a={name:`${n}.${r}`,type:{name:s.type,isArray:s.isArray,options:s.options?[...s.options]:void 0,fields:s.fields,minLength:s.minLength,maxLength:s.maxLength,minimum:s.minimum,maximum:s.maximum,pattern:s.pattern,format:s.format},description:s.description,isOptional:s.isOptional};if(s.type==="string"||s.type==="code"?Ve(o,a):s.type==="number"?Je(o,a):s.type==="object"&&s.fields&&typeof o=="object"&&o!==null&&this.validateObjectFields(o,s.fields,a.name),s.isArray&&Array.isArray(o))for(let l=0;l<o.length;l++){let c=o[l];s.type==="string"||s.type==="code"?Ve(c,a):s.type==="number"?Je(c,a):s.fields&&typeof c=="object"&&c!==null&&this.validateObjectFields(c,s.fields,`${a.name}[${l}]`)}}}async*_forward1(e,t,n){(!Array.isArray(t)||!t.every(x=>"role"in x))&&this.validateInputs(t);let r=performance.now(),s=this.createStates(n.sampleCount??1),o=performance.now()-r,a=this.getMetricsInstruments(),l=this.getMergedCustomLabels(e,n);a&&Rr(a,"state_creation",o,this.getSignatureName(),l);let c=n?.tracer??this.options?.tracer??e.getOptions().tracer,u=this.functions;if(n?.functions&&(u=Ot(n.functions,this.functions)),!c){yield*this._forward2(e,t,s,{...n,functions:u});return}let p=u?.map(x=>x.name).join(","),d={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}:{}},m=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,h=m?`AxGen > ${m}`:"AxGen",g=c.startSpan(h,{kind:Kc.SERVER,attributes:d}),f=Hc.active(),y=Wc.setSpan(f,g);try{if(this.excludeContentFromTrace||g.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,s,{...n,functions:u},g,y),!this.excludeContentFromTrace){let x=s.map(T=>T.values),b=x.length===1?x[0]:x;g.addEvent("output",{content:JSON.stringify(b,null,2)})}}finally{g.end()}}async forward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;let d=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,d)})();if(r&&s){let d=await r(s);if(d!==void 0)return d}let o=performance.now(),a=this.getSignatureName(),l=n?.stream??!1,c=!1,u=0,p=!1;try{let d=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);d&&aa(d,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let h=this._forward1(e,t,n??{}),g=[],f=0,y=0;for await(let S of h)S.version!==f&&(g=[]),f=S.version,g=ao(g,S),y++;u=f;let x=performance.now();p=!!n?.resultPicker;let b=await Ur(g,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),T=performance.now()-x,I=g[b]?.delta??{},C=Array.isArray(t)?{}:t??{};if(this.trace={...C,...I},p&&this.isDebug(e,n)){let S=this.getLogger(e,n);pi(g.length,b,T,S)}if(c=!0,d&&(ia(d,g.length,p,p?T:void 0,a,m),oa(d,l,y,void 0,a,m)),r&&s)try{await r(s,I)}catch{}return I}catch(d){throw c=!1,d}finally{let d=performance.now()-o,m=this.getMetricsInstruments(),h=this.getMergedCustomLabels(e,n);m&&(ta(m,d,c,a,e.getName(),n?.model?String(n.model):void 0,h),u>0&&ro(m,u,c,n?.maxRetries??10,a,h))}}async*streamingForward(e,t,n){let r=n?.cachingFunction??this.options?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;let p=this.signature.getInputFields().map(d=>d.name);return this.computeCacheKey(t,p)})();if(r&&s){let p;try{p=await r(s)}catch{}if(p!==void 0){yield{version:0,index:0,delta:p};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),a=[],l=0;for await(let p of o)p.version!==l&&(a=[]),l=p.version,a=ao(a,p);let c=await Ur(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[c];if(u){if(r&&s)try{await r(s,u.delta)}catch{}yield{version:l,index:c,delta:u.delta}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??Z.debug??e.getOptions().debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??Z.logger??e.getLogger()}computeCacheKey(e,t){let n=Ne("sha256");n.update(this.signature.hash()??"");let r=s=>{let o=typeof s;if(n.update(`|${o}|`),s==null){n.update("null");return}if(o==="string"||o==="number"||o==="boolean"){n.update(String(s));return}if(Array.isArray(s)){n.update("[");for(let a of s)r(a);n.update("]");return}if(typeof s=="object"&&s!==null&&"mimeType"in s&&"data"in s){let a=s;n.update(a.mimeType??"");let l=Ne("sha256").update(a.data??"").digest("hex");n.update(l);return}if(typeof s=="object"){let a=s,l=Object.keys(a).sort();for(let c of l)n.update(`{${c}}`),r(a[c]);return}n.update(String(s))};if(Array.isArray(e))for(let s of e){n.update(`role:${s.role}`);let o=t.map(a=>s.values?.[a]);for(let a of o)r(a)}else{let s=t.map(o=>e?.[o]);for(let o of s)r(o)}return n.digest("hex")}},jr=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function bo(i,e,t){let n=i instanceof Error?i:new Error(String(i)),r=(n.message||"").toLowerCase();if(r.includes("at least")||r.includes("at most")||r.includes("must match pattern")||r.includes("invalid url")||r.includes("required")||r.includes("missing")||r.includes("valid email")||r.includes("number must be")||n.name==="ValidationError"||n.name==="AssertionError"||n.name==="AxAssertionError"||n.stack?.includes("asserts.ts"))return n;let o=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),l={model:o,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new jr(`Generate failed: ${n.message}`,l,{cause:n})}var Vc=i=>i.replace(/^\W+|\W+$/g,""),Jc=(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),s=i.substring(t+n[0].length);return[r,s]},Qc=i=>{let e=new Set,t=[];for(let n of i)e.has(n)||(e.add(n),t.push(n));return t},Yc=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}},Xc=i=>{let e=i.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():i},Zc=(i,e)=>{let t=[];for(let n=0;n<i.length;n+=e)t.push(i.slice(n,n+e));return t},Io={trimNonAlphaNum:Vc,splitIntoTwo:Jc,dedup:Qc,extractIdAndText:Yc,extractIndexPrefixedText:Xc,batchArray:Zc};var To=class extends Ae{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."
322
+ 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),s=r.map(a=>{let{id:l}=Io.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let c=s[l];return c!==void 0?t.items[c]:void 0}).filter(a=>a!==void 0)}}};var Co=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 s=await(this.fetch??fetch)(this.tikaUrl,r);if(!s.ok)throw new Error(`Failed to upload file: ${s.statusText}`);return await s.text()}catch(r){throw new Error(`Error converting file: ${r}`)}}async convert(e,t){let n=[],r=t?.batchSize??10;for(let s=0;s<e.length;s+=r){let a=e.slice(s,s+r).map(c=>this._convert(c,{format:t?.format})),l=await Promise.all(a);n.push(...l)}return n}};var xf=new $e,Ro=class{name;context;constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},wo=class{ai;db;debug;constructor(e){this.db=new St,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}),s=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof t?.cutoff=="number"){let{cutoff:a}=t;s=s.filter(l=>l.score<=a)}let o=s.at(0);return o?o.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}};var qa=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 za(i,e){return i.filter(t=>!e.has(t))}function Ha(i){let e={};for(let t of i)e[t]=(e[t]||0)+1;return e}function Ft(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 eu(i,e){return Ft(i)===Ft(e)?1:0}function tu(i,e){let t=Ft(i).split(" "),n=Ft(e).split(" "),r=Ha(t),s=Ha(n),o=0;for(let c in r){let u=r[c]??0,p=s[c]??0;o+=Math.min(u,p)}if(o===0)return 0;let a=o/t.length,l=o/n.length;return 2*a*l/(a+l)}function nu(i,e,t,n=!1){let r=Ft(i).split(" "),s=Ft(e).split(" "),o=Ft(t).split(" "),a=new Set([...qa,...r]);s=za(s,a),o=za(o,a);let l=0,c=l/s.length,u=l/o.length,p=2*c*u/(c+u);return n?u:p}var ru={emScore:eu,f1Score:tu,novelF1ScoreOptimized:nu};var vo=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 o=0;o<n;o++){let a=this.examples[o];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 ${o}: ${l instanceof Error?l.message:"Unknown error"}`)}}let s=n>0?r/n:0;this.ai.getOptions().debug&&console.log(`
323
323
  Performance: `,r,"/",n,"Average Score: ",s,`
324
- `)}};function jr(i){return i.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
325
- `)}function ru(i,e){if(i===e)return!0;if(typeof i!=typeof e)return!1;if(typeof i=="object"&&i!==null&&e!==null){let t=JSON.stringify(i),n=JSON.stringify(e);return t===n}return!1}function su(i){return i==null?!1:!!(typeof i=="string"||typeof i=="number"||typeof i=="boolean"||Array.isArray(i)&&i.every(e=>typeof e!="object"))}var Nn=class{signature;options;constructor(e,t){this.signature=e,this.options={ai:t.ai,randomizeOrder:t.randomizeOrder??!0,model:t.model,criteria:t.criteria}}async evaluate(e,t,n){return n&&su(n)?this.runAbsolute(t,n):n?this.runRelativistic(e,t,n):this.runReferenceFree(e,t)}async runAbsolute(e,t){let n=this.signature.getOutputFields(),r=0,s=0,o=[];for(let c of n){let u=e[c.name],p=t[c.name];p!==void 0&&(s++,ru(u,p)?r++:o.push(`${c.name}: expected "${p}", got "${u}"`))}let a=s>0?r/s:0,l=a===1?"All fields match expected values exactly.":`Mismatches found: ${o.join("; ")}`;return{score:a,reasoning:l,mode:"absolute"}}async runRelativistic(e,t,n){let r=this.signature.getDescription(),s=this.signature.getInputFields(),o=this.signature.getOutputFields(),a=this.options.randomizeOrder?Math.random()>.5:!0,l=a?t:n,c=a?n:t,u=`
324
+ `)}};function qr(i){return i.map(e=>{let t=e.type?.name??"string",n=e.description?`: ${e.description}`:"";return`- ${e.name} (${t})${n}`}).join(`
325
+ `)}function su(i,e){if(i===e)return!0;if(typeof i!=typeof e)return!1;if(typeof i=="object"&&i!==null&&e!==null){let t=JSON.stringify(i),n=JSON.stringify(e);return t===n}return!1}function ou(i){return i==null?!1:!!(typeof i=="string"||typeof i=="number"||typeof i=="boolean"||Array.isArray(i)&&i.every(e=>typeof e!="object"))}var Ln=class{signature;options;constructor(e,t){this.signature=e,this.options={ai:t.ai,randomizeOrder:t.randomizeOrder??!0,model:t.model,criteria:t.criteria}}async evaluate(e,t,n){return n&&ou(n)?this.runAbsolute(t,n):n?this.runRelativistic(e,t,n):this.runReferenceFree(e,t)}async runAbsolute(e,t){let n=this.signature.getOutputFields(),r=0,s=0,o=[];for(let c of n){let u=e[c.name],p=t[c.name];p!==void 0&&(s++,su(u,p)?r++:o.push(`${c.name}: expected "${p}", got "${u}"`))}let a=s>0?r/s:0,l=a===1?"All fields match expected values exactly.":`Mismatches found: ${o.join("; ")}`;return{score:a,reasoning:l,mode:"absolute"}}async runRelativistic(e,t,n){let r=this.signature.getDescription(),s=this.signature.getInputFields(),o=this.signature.getOutputFields(),a=this.options.randomizeOrder?Math.random()>.5:!0,l=a?t:n,c=a?n:t,u=`
326
326
  You are an impartial judge comparing two AI responses to the same input.
327
327
 
328
328
  **Task Description:** ${r||"Complete the task based on the input."}
329
329
 
330
330
  **Input Fields:**
331
- ${jr(s)}
331
+ ${qr(s)}
332
332
 
333
333
  **Output Fields:**
334
- ${jr(o)}
334
+ ${qr(o)}
335
335
 
336
336
  **Instructions:**
337
337
  1. Carefully analyze both Response A and Response B
@@ -359,10 +359,10 @@ You are evaluating the quality of an AI response.
359
359
  **Task Description:** ${n||"Complete the task based on the input."}
360
360
 
361
361
  **Input Fields:**
362
- ${jr(r)}
362
+ ${qr(r)}
363
363
 
364
364
  **Output Fields:**
365
- ${jr(s)}
365
+ ${qr(s)}
366
366
 
367
367
  **Evaluation Criteria:**
368
368
  ${o}
@@ -381,7 +381,7 @@ First explain your reasoning, then classify the response into one of the quality
381
381
  ->
382
382
  reasoning:string "Detailed explanation for the quality assessment",
383
383
  quality:class "excellent, good, acceptable, poor, unacceptable" "Quality tier"
384
- `);l.setInstruction(a);let c=await l.forward(this.options.ai,{input:JSON.stringify(e),response:JSON.stringify(t)},{model:this.options.model}),u={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0},p=c.quality.toLowerCase();return{score:u[p]??.5,reasoning:c.reasoning,mode:"reference-free",qualityTier:p}}toMetricFn(){return async e=>{let{example:t,prediction:n}=e,r={};for(let c of this.signature.getInputFields())c.name in t&&(r[c.name]=t[c.name]);let s={},o=!1;for(let c of this.signature.getOutputFields())c.name in t&&(s[c.name]=t[c.name],o=!0);let a=n;return(await this.evaluate(r,a,o?s:void 0)).score}}getSignature(){return this.signature}};function Ka(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${i}-${e}`}var Ln=class i{gen;options;constructor(e,t){this.gen=e,this.options={name:t.name,storage:t.storage,logInputs:t.logInputs??!0,logOutputs:t.logOutputs??!0,metadata:t.metadata,onTrace:t.onTrace,throwOnError:t.throwOnError??!1}}async*streamingForward(e,t,n){let r=Ka(),s=new Date,o,a;try{let l=this.gen.streamingForward(e,t,n);for await(let c of l)c.partial?o=c.partial:c.delta,yield c}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,c=l.getTime()-s.getTime(),u={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&o?o:{},startTime:s,endTime:l,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(u)}}async forward(e,t,n){let r=Ka(),s=new Date,o,a;try{return o=await this.gen.forward(e,t,n),o}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,c=l.getTime()-s.getTime(),u={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&o?o:{},startTime:s,endTime:l,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(u)}}async saveTrace(e){try{await this.options.storage.save(this.options.name,e),this.options.onTrace&&this.options.onTrace(e)}catch(t){if(this.options.throwOnError)throw t;console.warn("AxTraceLogger: Failed to save trace:",t)}}getGen(){return this.gen}getName(){return this.options.name}getStorage(){return this.options.storage}setMetadata(e){this.options.metadata=e}clone(e){return new i(e??this.gen.clone(),{name:this.options.name,storage:this.options.storage,logInputs:this.options.logInputs,logOutputs:this.options.logOutputs,metadata:this.options.metadata,onTrace:this.options.onTrace,throwOnError:this.options.throwOnError})}};var Wa=i=>{console.log(i)},Va=(i=Wa)=>{let e=new $e,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let s="";switch(r.name){case"OptimizationStart":s=`
384
+ `);l.setInstruction(a);let c=await l.forward(this.options.ai,{input:JSON.stringify(e),response:JSON.stringify(t)},{model:this.options.model}),u={excellent:1,good:.8,acceptable:.5,poor:.2,unacceptable:0},p=c.quality.toLowerCase();return{score:u[p]??.5,reasoning:c.reasoning,mode:"reference-free",qualityTier:p}}toMetricFn(){return async e=>{let{example:t,prediction:n}=e,r={};for(let c of this.signature.getInputFields())c.name in t&&(r[c.name]=t[c.name]);let s={},o=!1;for(let c of this.signature.getOutputFields())c.name in t&&(s[c.name]=t[c.name],o=!0);let a=n;return(await this.evaluate(r,a,o?s:void 0)).score}}getSignature(){return this.signature}};function Ka(){let i=Date.now().toString(36),e=Math.random().toString(36).substring(2,8);return`trace-${i}-${e}`}var $n=class i{gen;options;constructor(e,t){this.gen=e,this.options={name:t.name,storage:t.storage,logInputs:t.logInputs??!0,logOutputs:t.logOutputs??!0,metadata:t.metadata,onTrace:t.onTrace,throwOnError:t.throwOnError??!1}}async*streamingForward(e,t,n){let r=Ka(),s=new Date,o,a;try{let l=this.gen.streamingForward(e,t,n);for await(let c of l)c.partial?o=c.partial:c.delta,yield c}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,c=l.getTime()-s.getTime(),u={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&o?o:{},startTime:s,endTime:l,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(u)}}async forward(e,t,n){let r=Ka(),s=new Date,o,a;try{return o=await this.gen.forward(e,t,n),o}catch(l){throw a=l instanceof Error?l.message:String(l),l}finally{let l=new Date,c=l.getTime()-s.getTime(),u={type:"trace",id:r,name:this.options.name,input:this.options.logInputs?t:{},output:this.options.logOutputs&&o?o:{},startTime:s,endTime:l,durationMs:c,model:n?.model??void 0,metadata:this.options.metadata,error:a};this.saveTrace(u)}}async saveTrace(e){try{await this.options.storage.save(this.options.name,e),this.options.onTrace&&this.options.onTrace(e)}catch(t){if(this.options.throwOnError)throw t;console.warn("AxTraceLogger: Failed to save trace:",t)}}getGen(){return this.gen}getName(){return this.options.name}getStorage(){return this.options.storage}setMetadata(e){this.options.metadata=e}clone(e){return new i(e??this.gen.clone(),{name:this.options.name,storage:this.options.storage,logInputs:this.options.logInputs,logOutputs:this.options.logOutputs,metadata:this.options.metadata,onTrace:this.options.onTrace,throwOnError:this.options.throwOnError})}};var Wa=i=>{console.log(i)},Va=(i=Wa)=>{let e=new $e,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return r=>{let s="";switch(r.name){case"OptimizationStart":s=`
385
385
  ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
386
386
  ${t}
387
387
  ${e.white("Optimizer:")} ${e.cyan(r.value.optimizerType)}
@@ -424,7 +424,7 @@ ${t}
424
424
  ${e.white("Config:")} ${e.cyan(JSON.stringify(r.value.config).slice(0,80))}${JSON.stringify(r.value.config).length>80?"...":""}
425
425
  `;break;default:s=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
426
426
  ${e.white(JSON.stringify(r).slice(0,100))}${JSON.stringify(r).length>100?"...":""}
427
- `}i(s)}},ou=(i=Wa)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
427
+ `}i(s)}},iu=(i=Wa)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
428
428
  ${e}
429
429
  Config: ${JSON.stringify(t.value.config,null,2)}
430
430
  Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
@@ -450,7 +450,7 @@ Score: ${t.value.score.toFixed(3)}
450
450
  Config: ${JSON.stringify(t.value.config)}
451
451
  ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
452
452
  ${JSON.stringify(t)}
453
- ${e}`}i(n)}},qr=Va();var Ja={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},zr,iu=i=>{if(zr)return zr;if(i)return zr=cu(i),zr};var Hr=Ja,au=i=>{Hr={...Hr,...i}},lu=()=>({...Hr}),cu=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"})}),st=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),s=Hr.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e},uu=(i,e,t,n,r,s)=>{try{let o=st({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...s});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)}},pu=(i,e,t,n,r,s,o)=>{try{let a=st({optimizer_type:s,...o});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},du=(i,e,t,n)=>{try{let r=st({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},mu=(i,e,t,n,r,s)=>{try{let o=st({optimizer_type:n,...s});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)}},gu=(i,e,t,n)=>{try{let r=st({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},hu=(i,e,t,n,r)=>{try{let s=st({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,s),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,s),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,s)}catch(s){console.warn("Failed to record teacher-student metric:",s)}},fu=(i,e,t,n,r,s)=>{try{let o=st({operation:e,success:n.toString(),optimizer_type:r,...s});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)}},xu=(i,e,t,n,r,s)=>{try{let o=st({optimizer_type:n,...s});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)}},Au=(i,e,t,n,r,s,o)=>{try{let a=st({optimizer_type:s,...o});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},yu=(i,e,t,n,r)=>{try{let s=st({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,s);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,s);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record optimizer performance metric:",s)}},bu=(i,e,t,n,r)=>{try{let s=st({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,s),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,s),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,s)}catch(s){console.warn("Failed to record optimizer configuration metric:",s)}},gt=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)}},Kr=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}},ze=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 Kr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=iu(Z.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?qr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return wt(Z.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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 s=Date.now(),o=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(o,a,r);let l,c=(h,g,f,y,x,b,T,A={},I)=>{this.getOptimizerLogger(I)?.({name:"RoundProgress",value:{round:h,totalRounds:I?.maxIterations??0,currentScore:g,bestScore:b,configuration:f}}),this.updateOptimizationProgress(h,g,f,y,x,b,T,A,I)},u=(h,g)=>{l=h,this.triggerEarlyStopping(h,this.currentRound,r)},p=h=>{this.onProgress?.(h),c(h.round,h.currentScore,h.currentConfiguration||{},o,{},h.bestScore,h.bestConfiguration,h.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:u}),m=Date.now()-s;return this.recordOptimizationComplete(m,!0,o,a,r),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 s=this.constructor.name,o=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),p=this.calculateHypervolume(u);this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);let d=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:u,hypervolume:p,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let s=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let o=t[0],a=await e.forward(this.getAIService(!1,r),o),l=await n({prediction:a,example:o}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let p=0;p<u.length;p++){let d=u[p],m=async({prediction:h,example:g})=>{let f=await n({prediction:h,example:g}),y=0;for(let[x,b]of Object.entries(f))y+=b*(d[x]||0);return y};try{let h=await this.compile(e,t,m,{...r,verbose:!1}),g=await this.evaluateWithMultiObjective(e,h,n,t);s.push({scores:g,demos:h.demos,configuration:{...h.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return s}async generateConstraintSolutions(e,t,n,r){let s=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let o=t[0],a=await e.forward(this.getAIService(!1,r),o),l=await n({prediction:a,example:o}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let h=await n({prediction:d,example:m}),g=h[u]||0,f=0;for(let[y,x]of Object.entries(h))y!==u&&x<.3&&(f+=(.3-x)*2);return g-f};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);s.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return s}generateWeightCombinations(e){let t=[];for(let r of e){let s={};for(let o of e)s[o]=o===r?1:0;t.push(s)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,s]=e;for(let o=.1;o<=.9;o+=.2){let a=1-o;t.push({[r]:o,[s]:a})}}if(e.length===3){let[r,s,o]=e;t.push({[r]:.5,[s]:.3,[o]:.2},{[r]:.3,[s]:.5,[o]:.2},{[r]:.2,[s]:.3,[o]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let s=new Ae(e.getSignature());t.demos&&s.setDemos(t.demos);let o=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let d of u)try{let m=await s.forward(this.studentAI,d),h=await n({prediction:m,example:d});for(let[g,f]of Object.entries(h))c[g]||(c[g]=[]),c[g].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((h,g)=>h+g,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],s=!1,o=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){s=!0;break}this.dominates(r.scores,l.scores)&&o++}s||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:o})}return t}dominates(e,t){let n=Object.keys(e),r=!0,s=!1;for(let o of n){let a=e[o]||0,l=t[o]||0;if(a<l){r=!1;break}a>l&&(s=!0)}return r&&s}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,s]=n,o=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,p=c.scores[s]||0;o+=u*(p-l),l=Math.max(l,p)}return o}}async saveCheckpoint(e,t,n,r,s={},o){let a=o?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let p={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:s,examples:[]};u=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,c,e,o)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),s=!1,o=null;try{o=await n(e),s=o!==null}catch(a){throw s=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,s,"unknown",t)}return o}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,s,o,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,s,o,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:o,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,s={},o){o?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...s,final:!0},o)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let s=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;Au(this.metricsInstruments,s,o,0,0,e,r)}bu(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);uu(this.metricsInstruments,e,t,n,r,o),gu(this.metricsInstruments,e,n,o);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;mu(this.metricsInstruments,l,a,n,void 0,o)}recordConvergenceMetrics(e,t,n,r,s,o){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(o);pu(this.metricsInstruments,e,t,n,r,s,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);du(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);hu(this.metricsInstruments,e,t,n,s)}recordCheckpointMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);fu(this.metricsInstruments,e,t,n,r,o)}recordParetoMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);xu(this.metricsInstruments,e,t,n,r,o)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);yu(this.metricsInstruments,e,t,n,s)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??Z.optimizerLogger??qr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,s=this.stats.totalCalls,o=s>0?this.stats.successfulDemos/s*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${o.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 u=t.bootstrappedDemos;typeof u=="number"&&u===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,s){let o=this.getOptimizerLogger(r);o&&o(s?{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:s.humanExplanation,recommendations:s.recommendations,performanceAssessment:s.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 Iu(i){return fe.create(i)}function Ge(i,e){let t=typeof i=="string"?fe.create(i):i;return new Ae(t,e)}function Qa(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,s=!1;for(let o of n){let a=i[o]??0,l=e[o]??0;if(a+t<l){r=!1;break}a>l+t&&(s=!0)}return r&&s}function ut(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,s=!1;for(let o=0;o<i.length;o++)if(n!==o){if(Qa(i[o].scores,i[n].scores,e)){s=!0;break}Qa(i[n].scores,i[o].scores,e)&&r++}s||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Qe(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)),s=0,o=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-o,0);s+=l*u,o=Math.max(o,c)}return s}function Ft(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function Wr(i){let e={},t={};for(let r of i)for(let[s,o]of Object.entries(r))e[s]=(e[s]||0)+(typeof o=="number"?o:0),t[s]=(t[s]||0)+1;let n={};for(let[r,s]of Object.entries(e))n[r]=s/Math.max(t[r]||1,1);return n}function $n(i,e){let t=new Set;for(let u of i)for(let p of u)t.add(p);let r=[...Array.from(t)].sort((u,p)=>(e[u]??0)-(e[p]??0)),s=new Set,o=(u,p)=>{for(let d of i){if(!d.has(u))continue;let m=!1;for(let h of p)if(d.has(h)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(s.has(u))continue;let p=new Set(r.filter(d=>d!==u&&!s.has(d)));if(o(u,p)){s.add(u),a=!0;break}}}let l=r.filter(u=>!s.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function Gn(i,e,t){let n=$n(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let s=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let p=0;p<c;p++)s.push(u)}if(s.length===0)return 0;let o=typeof t=="function"?t():Math.random(),a=Math.floor(o*s.length);return s[a]}var Dn=class i extends ze{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;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";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 s=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(s??Math.max(3,Math.floor(this.numTrials/4))));let o=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(o)?o: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??5)),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 s=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let o=r?.validationExamples,a=r?.feedbackExamples,l=(o&&o.length>0?o:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(M,D)=>{try{e.setInstruction?.(M);let F=await e.forward(this.studentAI,D,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:F,example:D})||{}}catch{return{}}},p=async(M,D)=>{let F=[];for(let q of D)F.push(await u(M,q));return Wr(F)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],h=M=>{let D=r?.paretoMetricKey,F=r?.paretoScalarize;if(typeof F=="function")return F(M);if(D)return Number.isFinite(M[D])?M[D]:0;let q=Object.values(M);return q.length?q.reduce((Y,oe)=>Y+oe,0)/q.length:0},g=[],f=async(M,D)=>{let F=[];for(let q of D){let Y=await u(M,q);F.push(h(Y))}return F};g.push(await f(d,l));let y=()=>{let M=g[0]?.length??0,D=[];for(let q=0;q<M;q++){let Y=Number.NEGATIVE_INFINITY,oe=new Set;for(let U=0;U<g.length;U++){let ae=g[U][q];ae>Y+this.tieEpsilon?(Y=ae,oe.clear(),oe.add(U)):Math.abs(ae-Y)<=this.tieEpsilon&&oe.add(U)}D.push(oe)}let F=g.map(q=>Ft(q));return Gn(D,F)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let b=Math.floor(x),T=this.getOptimizerLogger(r),A=r?.verbose??this.verbose?M=>console.log(`[GEPA] ${M}`):M=>{};T?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),A(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${b}`);let I=0,C=ut(m.map((M,D)=>({idx:D,scores:M.scores})),this.tieEpsilon).map(M=>M.idx),S;for(let M=0;M<this.numTrials&&!(b!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(b)));M++){let D=g[0]?.length??0,F=[];for(let G=0;G<D;G++){let B=Number.NEGATIVE_INFINITY,K=new Set;for(let X=0;X<g.length;X++){let _=g[X][G];_>B+this.tieEpsilon?(B=_,K.clear(),K.add(X)):Math.abs(_-B)<=this.tieEpsilon&&K.add(X)}F.push(K)}let q=g.map(G=>Ft(G));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let G=L=>{let H=[],ee=L;for(;ee!==void 0;)H.push(ee),ee=m[ee]?.parent;return H},B=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,K=$n(F,q),X=new Set;for(let L of K)for(let H of L)X.add(H);let _=Array.from(X),$;for(let L=0;L<10&&!$&&!(_.length<2);L++){let H=B(_),ee=B(_);if(H===ee)continue;ee<H&&([H,ee]=[ee,H]);let me=new Set(G(H)),te=new Set(G(ee));if(me.has(ee)||te.has(H))continue;let se=[...me].filter(ve=>te.has(ve));if(se.length===0)continue;let le=se.map(ve=>Math.max(1e-9,q[ve])),pe=this.rand()*le.reduce((ve,He)=>ve+He,0),Te=se[se.length-1];for(let ve=0;ve<se.length;ve++){if(pe<le[ve]){Te=se[ve];break}pe-=le[ve]}$={i:H,j:ee,a:Te}}if(this.lastIterFoundNewProgram=!1,$){let{i:L,j:H,a:ee}=$,me=q[ee],te=q[L],se=q[H],le=m[ee].instruction,pe=m[L].instruction,Te=m[H].instruction,ve=pe===le&&Te!==pe||Te===le&&pe!==Te,He=me<=Math.min(te,se)&&ve,Fe="",Be="i",de=!1;if(He){let pt=`${L}|${H}|${ee}`;if(this.mergeAttemptKeys.has(pt))He=!1;else{pe===le&&Te!==pe?(Fe=Te,Be="j"):Te===le&&pe!==Te?(Fe=pe,Be="i"):pe!==le&&Te!==le&&pe!==Te?te>se||te===se&&this.rand()<.5?(Fe=pe,Be="i"):(Fe=Te,Be="j"):(Fe=pe,Be="i");let ft=`${Math.min(L,H)}|${Math.max(L,H)}|${Be}`;if(this.mergeCompositionKeys.has(ft))He=!1;else{this.mergeAttemptKeys.add(pt),this.mergeCompositionKeys.add(ft);let Ye=g[L],xt=g[H],At=Array.from({length:Ye.length},(ce,_e)=>_e),dt=At.filter(ce=>(Ye[ce]??0)>(xt[ce]??0)),yt=At.filter(ce=>(xt[ce]??0)>(Ye[ce]??0)),Rt=At.filter(ce=>!(dt.includes(ce)||yt.includes(ce))),J=5,xe=Math.ceil(J/3),it=(ce,_e)=>{if(_e<=0||ce.length===0)return[];if(ce.length<=_e)return[...ce];let Qt=[],Vn=new Set;for(;Qt.length<_e;){let Xe=Math.floor(this.rand()*ce.length);Vn.has(Xe)||(Vn.add(Xe),Qt.push(ce[Xe]))}return Qt},je=[];je.push(...it(dt,Math.min(xe,dt.length))),je.push(...it(yt,Math.min(xe,yt.length)));let qe=J-je.length;je.push(...it(Rt,Math.max(0,qe)));let Wn=J-je.length;if(Wn>0){let ce=At.filter(_e=>!je.includes(_e));je.push(...it(ce,Math.min(Wn,ce.length)))}let es=je.slice(0,Math.min(J,At.length)),ul=es.map(ce=>l[ce]);de=!0;let pl=(await f(Fe,ul)).reduce((ce,_e)=>ce+_e,0),dl=es.reduce((ce,_e)=>ce+(Ye[_e]??0),0),ml=es.reduce((ce,_e)=>ce+(xt[_e]??0),0);if(pl>=Math.max(dl,ml)+this.tieEpsilon){A(`Iteration ${M+1}: Merge accepted (programs ${L} + ${H} via ancestor ${ee})`);let ce=await p(Fe,l);m.push({instruction:Fe,parent:ee,scores:ce}),g.push(await f(Fe,l));let _e=C.length,Qt=Qe(C.map(Xe=>m[Xe].scores))??0;C=ut(m.map((Xe,gl)=>({idx:gl,scores:Xe.scores})),this.tieEpsilon).map(Xe=>Xe.idx);let Vn=Qe(C.map(Xe=>m[Xe].scores))??0;(C.length>_e||Vn>Qt+1e-6)&&(I=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(de)continue}}let Y=Gn(F,q,()=>this.rand()),oe=this.minibatch?this.nextMinibatchIndices(c.length,M).map(G=>c[G]):c;if(r?.skipPerfectScore??!0){let G=Number(r?.perfectScore??1),B=await f(m[Y].instruction,oe);if(B.length>0&&B.every(K=>K>=G))continue}let U=!1,ae=m[Y].instruction,ne="reflective_mutation",Re,ot;if(U){let G=(Y+1)%m.length;ae=await this.mergeInstructions(m[Y].instruction,m[G].instruction,r),ne="merge",this.mergesUsed+=1}else{let G=r?.gepaAdapter;if(G){try{let B={instruction:m[Y].instruction},K=await G.evaluate(oe,B,!0);Re=Array.isArray(K?.scores)?K.scores.reduce((L,H)=>L+(Number(H)||0),0):void 0;let X=G.make_reflective_dataset(B,K,["instruction"]),_=await G.propose_new_texts?.(B,X,["instruction"]),$=_?.instruction??(_?Object.values(_)[0]:void 0);typeof $=="string"&&$.length>0?ae=$:ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:L,example:H})=>{let ee=await n({prediction:L,example:H}),me=Object.values(ee||{});return me.length?me.reduce((te,se)=>te+se,0)/me.length:0},r)}catch{ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)}if(Re!==void 0)try{let B=await G.evaluate(oe,{instruction:ae},!1);ot=Array.isArray(B?.scores)?B.scores.reduce((K,X)=>K+(Number(X)||0),0):void 0}catch{}}else ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)}let ht=await f(m[Y].instruction,oe),De=await f(ae,oe),re=ht.reduce((G,B)=>G+B,0),ye=De.reduce((G,B)=>G+B,0);if(this.currentRound=M+1,await this.updateOptimizationProgress(this.currentRound,ye,{instructionLen:ae.length,parent:Y,totalRounds:this.numTrials},"GEPA",{strategy:ne,paretoSetSize:l.length},ye,{instructionLen:m[Y].instruction.length,idx:Y},{...r??{},maxIterations:this.numTrials}),!(ye>re+this.tieEpsilon&&(Re===void 0||ot===void 0||ot>Re+this.tieEpsilon))){if(A(`Iteration ${M+1}: Rejected (child=${ye.toFixed(3)} <= parent=${re.toFixed(3)})`),++I>=this.earlyStoppingTrials){A(`Early stopping: ${I} iterations without improvement`);break}continue}A(`Iteration ${M+1}: Accepted (child=${ye.toFixed(3)} > parent=${re.toFixed(3)})`);let we=await p(ae,l);m.push({instruction:ae,parent:Y,scores:we}),g.push(await f(ae,l));let be=C.length,z=Qe(C.map(G=>m[G].scores))??0;C=ut(m.map((G,B)=>({idx:B,scores:G.scores})),this.tieEpsilon).map(G=>G.idx);let W=Qe(C.map(G=>m[G].scores))??0;if(C.length>be||W>z+1e-6)I=0,A(`Iteration ${M+1}: Archive improved (size=${C.length}, hv=${W.toFixed(4)})`);else if(I++,A(`Iteration ${M+1}: Archive unchanged (stagnation=${I}/${this.earlyStoppingTrials})`),I>=this.earlyStoppingTrials){A(`Early stopping: ${I} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=ut(m.map((M,D)=>({idx:D,scores:M.scores})),this.tieEpsilon),P=R.length>0?Math.max(...R.map(M=>h(M.scores))):0,E;if(R.length>0){let M=Number.NEGATIVE_INFINITY;for(let D of R){let F=h(D.scores);F>M&&(M=F,E=D.idx)}}let w=Qe(R.map(M=>M.scores));this.stats.convergenceInfo.converged=!0;let v=this.getMergedCustomLabels(r);this.recordParetoMetrics(R.length,m.length,"GEPA",w,v);let k=Date.now()-s,O=typeof E=="number"?new gt({bestScore:P,stats:this.stats,instruction:m[E].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:k,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,N=this.generateOptimizationReport(R,w,P);return{demos:[],stats:this.stats,bestScore:P,paretoFront:R.map(M=>({demos:[],scores:M.scores,configuration:{candidate:M.idx,instruction:m[M.idx].instruction},dominatedSolutions:M.dominated})),paretoFrontSize:R.length,hypervolume:w,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:O,report:N}}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){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let s=[];for(let o of n){let a=await this.evaluateOne(e,t,o,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?Ft(s):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let o=await r({prediction:s,example:n});if(typeof o=="number"&&!Number.isNaN(o)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return o>=a&&(this.stats.successfulDemos+=1),o}return 0}catch(s){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(s)}),0}}async reflectInstruction(e,t,n,r,s,o){let a=o??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let h=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let g=await r({prediction:h,example:m});a.push({input:m,prediction:h,score:typeof g=="number"?g:0})}catch{a.push({input:m,prediction:{},score:0})}let l=s?.overrideTeacherAI??this.teacherAI??this.studentAI,c=s?.feedbackFn,u=()=>{let m=[];for(let h=0;h<a.length;h++){let g=a[h],f=`# Example ${h+1}
453
+ ${e}`}i(n)}},zr=Va();var Ja={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},Hr,au=i=>{if(Hr)return Hr;if(i)return Hr=uu(i),Hr};var Kr=Ja,lu=i=>{Kr={...Kr,...i}},cu=()=>({...Kr}),uu=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"})}),st=i=>{let e={};for(let[t,n]of Object.entries(i))if(n!=null){let r=String(n),s=Kr.maxLabelLength;e[t]=r.length>s?r.substring(0,s):r}return e},pu=(i,e,t,n,r,s)=>{try{let o=st({success:t.toString(),optimizer_type:n,...r?{program_signature:r}:{},...s});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)}},du=(i,e,t,n,r,s,o)=>{try{let a=st({optimizer_type:s,...o});i.convergenceRoundsHistogram&&i.convergenceRoundsHistogram.record(e,a),i.convergenceScoreGauge&&i.convergenceScoreGauge.record(t,a),i.convergenceImprovementGauge&&i.convergenceImprovementGauge.record(n,a),i.stagnationRoundsGauge&&i.stagnationRoundsGauge.record(r,a)}catch(a){console.warn("Failed to record convergence metric:",a)}},mu=(i,e,t,n)=>{try{let r=st({reason:e,optimizer_type:t,...n});i.earlyStoppingCounter&&i.earlyStoppingCounter.add(1,r)}catch(r){console.warn("Failed to record early stopping metric:",r)}},gu=(i,e,t,n,r,s)=>{try{let o=st({optimizer_type:n,...s});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)}},hu=(i,e,t,n)=>{try{let r=st({optimizer_type:t,...n});i.optimizationDurationHistogram&&i.optimizationDurationHistogram.record(e,r)}catch(r){console.warn("Failed to record optimization duration metric:",r)}},fu=(i,e,t,n,r)=>{try{let s=st({optimizer_type:n,...r});i.teacherStudentUsageCounter&&i.teacherStudentUsageCounter.add(1,s),i.teacherStudentLatencyHistogram&&i.teacherStudentLatencyHistogram.record(e,s),i.teacherStudentScoreImprovementGauge&&i.teacherStudentScoreImprovementGauge.record(t,s)}catch(s){console.warn("Failed to record teacher-student metric:",s)}},xu=(i,e,t,n,r,s)=>{try{let o=st({operation:e,success:n.toString(),optimizer_type:r,...s});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)}},Au=(i,e,t,n,r,s)=>{try{let o=st({optimizer_type:n,...s});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)}},yu=(i,e,t,n,r,s,o)=>{try{let a=st({optimizer_type:s,...o});i.programInputFieldsGauge&&i.programInputFieldsGauge.record(e,a),i.programOutputFieldsGauge&&i.programOutputFieldsGauge.record(t,a),i.examplesCountGauge&&i.examplesCountGauge.record(n,a),i.validationSetSizeGauge&&i.validationSetSizeGauge.record(r,a)}catch(a){console.warn("Failed to record program complexity metric:",a)}},bu=(i,e,t,n,r)=>{try{let s=st({metric_type:e,optimizer_type:n,...r});switch(e){case"evaluation":i.evaluationLatencyHistogram&&i.evaluationLatencyHistogram.record(t,s);break;case"demo_generation":i.demoGenerationLatencyHistogram&&i.demoGenerationLatencyHistogram.record(t,s);break;case"metric_computation":i.metricComputationLatencyHistogram&&i.metricComputationLatencyHistogram.record(t,s);break}}catch(s){console.warn("Failed to record optimizer performance metric:",s)}},Iu=(i,e,t,n,r)=>{try{let s=st({optimizer_type:e,...r});i.optimizerTypeGauge&&i.optimizerTypeGauge.record(1,s),t!==void 0&&i.targetScoreGauge&&i.targetScoreGauge.record(t,s),n!==void 0&&i.maxRoundsGauge&&i.maxRoundsGauge.record(n,s)}catch(s){console.warn("Failed to record optimizer configuration metric:",s)}},gt=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)}},Wr=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}},ze=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 Wr({maxTokens:1e6});this.costTracker=e.costTracker??t,this.metricsInstruments=au(Z.meter),this.stats=this.initializeStats(),this.debugOptimizer=e.debugOptimizer??!1,this.optimizerLogger=e.optimizerLogger??(this.verbose?zr:void 0),this.initializeResultExplainer()}getMergedCustomLabels(e){return wt(Z.customLabels,this.studentAI?.getOptions?.()?.customLabels,this.teacherAI?.getOptions?.()?.customLabels,e?.customLabels)}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,n){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown",n),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 s=Date.now(),o=this.constructor.name,a=e.getSignature().toString();this.recordOptimizationStart(o,a,r);let l,c=(h,g,f,y,x,b,T,A={},I)=>{this.getOptimizerLogger(I)?.({name:"RoundProgress",value:{round:h,totalRounds:I?.maxIterations??0,currentScore:g,bestScore:b,configuration:f}}),this.updateOptimizationProgress(h,g,f,y,x,b,T,A,I)},u=(h,g)=>{l=h,this.triggerEarlyStopping(h,this.currentRound,r)},p=h=>{this.onProgress?.(h),c(h.round,h.currentScore,h.currentConfiguration||{},o,{},h.bestScore,h.bestConfiguration,h.convergenceInfo,r)},d=await this.compile(e,t,n,{...r,overrideOnProgress:p,overrideOnEarlyStop:u}),m=Date.now()-s;return this.recordOptimizationComplete(m,!0,o,a,r),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 s=this.constructor.name,o=Date.now(),a=await this.generateWeightedSolutions(e,t,n,r),l=await this.generateConstraintSolutions(e,t,n,r),c=[...a,...l],u=this.findParetoFrontier(c),p=this.calculateHypervolume(u);this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(u.length,c.length,"base_optimizer",p,r);let d=u.length>0?Math.max(...u.map(m=>Math.max(...Object.values(m.scores)))):0;return{demos:u.length>0?[...u[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:u,hypervolume:p,paretoFrontSize:u.length,finalConfiguration:{paretoFrontSize:u.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:c.length}}}async generateWeightedSolutions(e,t,n,r){let s=[];if(!t||t.length===0)throw new Error("No examples provided for Pareto optimization");let o=t[0],a=await e.forward(this.getAIService(!1,r),o),l=await n({prediction:a,example:o}),c=Object.keys(l),u=this.generateWeightCombinations(c);for(let p=0;p<u.length;p++){let d=u[p],m=async({prediction:h,example:g})=>{let f=await n({prediction:h,example:g}),y=0;for(let[x,b]of Object.entries(f))y+=b*(d[x]||0);return y};try{let h=await this.compile(e,t,m,{...r,verbose:!1}),g=await this.evaluateWithMultiObjective(e,h,n,t);s.push({scores:g,demos:h.demos,configuration:{...h.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch{}}return s}async generateConstraintSolutions(e,t,n,r){let s=[];if(!t||t.length===0)throw new Error("No examples provided for multi-objective optimization");let o=t[0],a=await e.forward(this.getAIService(!1,r),o),l=await n({prediction:a,example:o}),c=Object.keys(l);for(let u of c){let p=async({prediction:d,example:m})=>{let h=await n({prediction:d,example:m}),g=h[u]||0,f=0;for(let[y,x]of Object.entries(h))y!==u&&x<.3&&(f+=(.3-x)*2);return g-f};try{let d=await this.compile(e,t,p,{...r,verbose:!1}),m=await this.evaluateWithMultiObjective(e,d,n,t);s.push({scores:m,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:u,strategy:"constraint_based"}})}catch{}}return s}generateWeightCombinations(e){let t=[];for(let r of e){let s={};for(let o of e)s[o]=o===r?1:0;t.push(s)}let n={};for(let r of e)n[r]=1/e.length;if(t.push(n),e.length===2){let[r,s]=e;for(let o=.1;o<=.9;o+=.2){let a=1-o;t.push({[r]:o,[s]:a})}}if(e.length===3){let[r,s,o]=e;t.push({[r]:.5,[s]:.3,[o]:.2},{[r]:.3,[s]:.5,[o]:.2},{[r]:.2,[s]:.3,[o]:.5})}return t}async evaluateWithMultiObjective(e,t,n,r){let s=new Ae(e.getSignature());t.demos&&s.setDemos(t.demos);let o=[],a=Math.max(1,Math.min(5,Math.floor(r.length*.2))),l=r.slice(-a),c={},u=l;for(let d of u)try{let m=await s.forward(this.studentAI,d),h=await n({prediction:m,example:d});for(let[g,f]of Object.entries(h))c[g]||(c[g]=[]),c[g].push(f)}catch{}let p={};for(let[d,m]of Object.entries(c))p[d]=m.length>0?m.reduce((h,g)=>h+g,0)/m.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n],s=!1,o=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,r.scores)){s=!0;break}this.dominates(r.scores,l.scores)&&o++}s||t.push({demos:r.demos||[],scores:r.scores,configuration:r.configuration,dominatedSolutions:o})}return t}dominates(e,t){let n=Object.keys(e),r=!0,s=!1;for(let o of n){let a=e[o]||0,l=t[o]||0;if(a<l){r=!1;break}a>l&&(s=!0)}return r&&s}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[r,s]=n,o=0,a=[...e].sort((c,u)=>(u.scores[r]||0)-(c.scores[r]||0)),l=0;for(let c of a){let u=c.scores[r]||0,p=c.scores[s]||0;o+=u*(p-l),l=Math.max(l,p)}return o}}async saveCheckpoint(e,t,n,r,s={},o){let a=o?.overrideCheckpointSave||this.checkpointSave;if(!a)return;let l=Date.now(),c=!1,u;try{let p={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:s,examples:[]};u=await a(p),c=!0}catch(p){throw c=!1,p}finally{let p=Date.now()-l;this.recordCheckpointMetrics("save",p,c,e,o)}return u}async loadCheckpoint(e,t){let n=t?.overrideCheckpointLoad||this.checkpointLoad;if(!n)return null;let r=Date.now(),s=!1,o=null;try{o=await n(e),s=o!==null}catch(a){throw s=!1,a}finally{let a=Date.now()-r;this.recordCheckpointMetrics("load",a,s,"unknown",t)}return o}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,s,o,a,l={},c){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,c)&&await this.saveCheckpoint(r,s,o,a,l,c),this.getOptimizerLogger(c)?.({name:"RoundProgress",value:{round:e,totalRounds:c?.maxIterations??0,currentScore:t,bestScore:o,configuration:n}})}async saveFinalCheckpoint(e,t,n,r,s={},o){o?.saveCheckpointOnComplete!==!1&&await this.saveCheckpoint(e,t,n,r,{...s,final:!0},o)}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,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);if(t){let s=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;yu(this.metricsInstruments,s,o,0,0,e,r)}Iu(this.metricsInstruments,e,this.targetScore,void 0,r)}recordOptimizationComplete(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);pu(this.metricsInstruments,e,t,n,r,o),hu(this.metricsInstruments,e,n,o);let a=this.costTracker?.getCurrentCost()??0,l=this.costTracker?.getTotalTokens()??0;gu(this.metricsInstruments,l,a,n,void 0,o)}recordConvergenceMetrics(e,t,n,r,s,o){if(!this.metricsInstruments)return;let a=this.getMergedCustomLabels(o);du(this.metricsInstruments,e,t,n,r,s,a)}recordEarlyStoppingMetrics(e,t,n){if(!this.metricsInstruments)return;let r=this.getMergedCustomLabels(n);mu(this.metricsInstruments,e,t,r)}recordTeacherStudentMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);fu(this.metricsInstruments,e,t,n,s)}recordCheckpointMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);xu(this.metricsInstruments,e,t,n,r,o)}recordParetoMetrics(e,t,n,r,s){if(!this.metricsInstruments)return;let o=this.getMergedCustomLabels(s);Au(this.metricsInstruments,e,t,n,r,o)}recordPerformanceMetrics(e,t,n,r){if(!this.metricsInstruments)return;let s=this.getMergedCustomLabels(r);bu(this.metricsInstruments,e,t,n,s)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(e?.verbose??this.verbose??!1)}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return this.optimizerLogger??Z.optimizerLogger??zr}getStats(){return{...this.stats}}async explainOptimizationResults(e,t,n){let r=this.stats.convergenceInfo.converged,s=this.stats.totalCalls,o=s>0?this.stats.successfulDemos/s*100:0,a=`Optimization finished with best score ${e.toFixed(3)}${t?` using configuration ${JSON.stringify(t)}`:""}. Convergence: ${r?"yes":"no"}. Success rate: ${o.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 u=t.bootstrappedDemos;typeof u=="number"&&u===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,s){let o=this.getOptimizerLogger(r);o&&o(s?{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:s.humanExplanation,recommendations:s.recommendations,performanceAssessment:s.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 Tu(i){return fe.create(i)}function Ge(i,e){let t=typeof i=="string"?fe.create(i):i;return new Ae(t,e)}function Qa(i,e,t=0){let n=new Set([...Object.keys(i),...Object.keys(e)]),r=!0,s=!1;for(let o of n){let a=i[o]??0,l=e[o]??0;if(a+t<l){r=!1;break}a>l+t&&(s=!0)}return r&&s}function ut(i,e=0){let t=[];for(let n=0;n<i.length;n++){let r=0,s=!1;for(let o=0;o<i.length;o++)if(n!==o){if(Qa(i[o].scores,i[n].scores,e)){s=!0;break}Qa(i[n].scores,i[o].scores,e)&&r++}s||t.push({idx:i[n].idx,scores:i[n].scores,dominated:r})}return t}function Qe(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)),s=0,o=0;for(let a of r){let l=a[t]??0,c=a[n]??0,u=Math.max(c-o,0);s+=l*u,o=Math.max(o,c)}return s}function _t(i){if(i.length===0)return 0;let e=0;for(let t of i)e+=t;return e/i.length}function Vr(i){let e={},t={};for(let r of i)for(let[s,o]of Object.entries(r))e[s]=(e[s]||0)+(typeof o=="number"?o:0),t[s]=(t[s]||0)+1;let n={};for(let[r,s]of Object.entries(e))n[r]=s/Math.max(t[r]||1,1);return n}function Gn(i,e){let t=new Set;for(let u of i)for(let p of u)t.add(p);let r=[...Array.from(t)].sort((u,p)=>(e[u]??0)-(e[p]??0)),s=new Set,o=(u,p)=>{for(let d of i){if(!d.has(u))continue;let m=!1;for(let h of p)if(d.has(h)){m=!0;break}if(!m)return!1}return!0},a=!0;for(;a;){a=!1;for(let u of r){if(s.has(u))continue;let p=new Set(r.filter(d=>d!==u&&!s.has(d)));if(o(u,p)){s.add(u),a=!0;break}}}let l=r.filter(u=>!s.has(u)),c=new Set(l);return i.map(u=>{let p=new Set;for(let d of u)c.has(d)&&p.add(d);return p})}function Dn(i,e,t){let n=Gn(i,e),r={};for(let l of n)for(let c of l)r[c]=(r[c]||0)+1;let s=[];for(let[l,c]of Object.entries(r)){let u=Number(l);for(let p=0;p<c;p++)s.push(u)}if(s.length===0)return 0;let o=typeof t=="function"?t():Math.random(),a=Math.floor(o*s.length);return s[a]}var Un=class i extends ze{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;static REFLECTION_PROMPT_TEMPLATE="I provided an assistant with the following instructions to perform a task for me:\n```\n<curr_instructions>\n```\n\nThe following are examples of different task inputs provided to the assistant along with the assistant's response for each of them, and some feedback on how the assistant's response could be better:\n```\n<inputs_outputs_feedback>\n```\n\nYour task is to write a new instruction for the assistant. Read the inputs carefully and identify the input format and infer detailed task description about the task I wish to solve with the assistant. Read all the assistant responses and the corresponding feedback. Identify all niche and domain specific factual information about the task and include it in the instruction, as a lot of it may not be available to the assistant in the future. The assistant may have utilized a generalizable strategy to solve the task, if so, include that in the instruction as well. Provide the new instructions within ``` blocks.";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 s=e?.crossoverEvery;this.crossoverEvery=Math.max(0,Math.floor(s??Math.max(3,Math.floor(this.numTrials/4))));let o=e?.tieEpsilon;this.tieEpsilon=Number.isFinite(o)?o: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??5)),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 s=Date.now();this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let o=r?.validationExamples,a=r?.feedbackExamples,l=(o&&o.length>0?o:t).slice(0,this.paretoSetSize),c=a&&a.length>0?a:t,u=async(M,D)=>{try{e.setInstruction?.(M);let F=await e.forward(this.studentAI,D,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:F,example:D})||{}}catch{return{}}},p=async(M,D)=>{let F=[];for(let q of D)F.push(await u(M,q));return Vr(F)},d=await this.getBaseInstruction(e),m=[{instruction:d,parent:void 0,scores:await p(d,l)}],h=M=>{let D=r?.paretoMetricKey,F=r?.paretoScalarize;if(typeof F=="function")return F(M);if(D)return Number.isFinite(M[D])?M[D]:0;let q=Object.values(M);return q.length?q.reduce((Y,oe)=>Y+oe,0)/q.length:0},g=[],f=async(M,D)=>{let F=[];for(let q of D){let Y=await u(M,q);F.push(h(Y))}return F};g.push(await f(d,l));let y=()=>{let M=g[0]?.length??0,D=[];for(let q=0;q<M;q++){let Y=Number.NEGATIVE_INFINITY,oe=new Set;for(let U=0;U<g.length;U++){let ae=g[U][q];ae>Y+this.tieEpsilon?(Y=ae,oe.clear(),oe.add(U)):Math.abs(ae-Y)<=this.tieEpsilon&&oe.add(U)}D.push(oe)}let F=g.map(q=>_t(q));return Dn(D,F)},x=r?.maxMetricCalls;if(!Number.isFinite(x)||x<=0)throw new Error("AxGEPA: options.maxMetricCalls must be set to a positive integer");let b=Math.floor(x),T=this.getOptimizerLogger(r),A=r?.verbose??this.verbose?M=>console.log(`[GEPA] ${M}`):M=>{};T?.({name:"OptimizationStart",value:{optimizerType:"GEPA",exampleCount:t.length,validationCount:l.length,config:{numTrials:this.numTrials,minibatch:this.minibatch,mergeMax:this.mergeMax}}}),A(`Starting GEPA optimization: ${t.length} train, ${l.length} validation, maxCalls=${b}`);let I=0,C=ut(m.map((M,D)=>({idx:D,scores:M.scores})),this.tieEpsilon).map(M=>M.idx),S;for(let M=0;M<this.numTrials&&!(b!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(b)));M++){let D=g[0]?.length??0,F=[];for(let G=0;G<D;G++){let B=Number.NEGATIVE_INFINITY,K=new Set;for(let X=0;X<g.length;X++){let _=g[X][G];_>B+this.tieEpsilon?(B=_,K.clear(),K.add(X)):Math.abs(_-B)<=this.tieEpsilon&&K.add(X)}F.push(K)}let q=g.map(G=>_t(G));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let G=L=>{let H=[],ee=L;for(;ee!==void 0;)H.push(ee),ee=m[ee]?.parent;return H},B=L=>L.length?L[Math.floor(this.rand()*L.length)]:void 0,K=Gn(F,q),X=new Set;for(let L of K)for(let H of L)X.add(H);let _=Array.from(X),$;for(let L=0;L<10&&!$&&!(_.length<2);L++){let H=B(_),ee=B(_);if(H===ee)continue;ee<H&&([H,ee]=[ee,H]);let me=new Set(G(H)),te=new Set(G(ee));if(me.has(ee)||te.has(H))continue;let se=[...me].filter(ve=>te.has(ve));if(se.length===0)continue;let le=se.map(ve=>Math.max(1e-9,q[ve])),pe=this.rand()*le.reduce((ve,He)=>ve+He,0),Te=se[se.length-1];for(let ve=0;ve<se.length;ve++){if(pe<le[ve]){Te=se[ve];break}pe-=le[ve]}$={i:H,j:ee,a:Te}}if(this.lastIterFoundNewProgram=!1,$){let{i:L,j:H,a:ee}=$,me=q[ee],te=q[L],se=q[H],le=m[ee].instruction,pe=m[L].instruction,Te=m[H].instruction,ve=pe===le&&Te!==pe||Te===le&&pe!==Te,He=me<=Math.min(te,se)&&ve,Fe="",Be="i",de=!1;if(He){let pt=`${L}|${H}|${ee}`;if(this.mergeAttemptKeys.has(pt))He=!1;else{pe===le&&Te!==pe?(Fe=Te,Be="j"):Te===le&&pe!==Te?(Fe=pe,Be="i"):pe!==le&&Te!==le&&pe!==Te?te>se||te===se&&this.rand()<.5?(Fe=pe,Be="i"):(Fe=Te,Be="j"):(Fe=pe,Be="i");let ft=`${Math.min(L,H)}|${Math.max(L,H)}|${Be}`;if(this.mergeCompositionKeys.has(ft))He=!1;else{this.mergeAttemptKeys.add(pt),this.mergeCompositionKeys.add(ft);let Ye=g[L],xt=g[H],At=Array.from({length:Ye.length},(ce,_e)=>_e),dt=At.filter(ce=>(Ye[ce]??0)>(xt[ce]??0)),yt=At.filter(ce=>(xt[ce]??0)>(Ye[ce]??0)),Rt=At.filter(ce=>!(dt.includes(ce)||yt.includes(ce))),J=5,xe=Math.ceil(J/3),it=(ce,_e)=>{if(_e<=0||ce.length===0)return[];if(ce.length<=_e)return[...ce];let Yt=[],Jn=new Set;for(;Yt.length<_e;){let Xe=Math.floor(this.rand()*ce.length);Jn.has(Xe)||(Jn.add(Xe),Yt.push(ce[Xe]))}return Yt},je=[];je.push(...it(dt,Math.min(xe,dt.length))),je.push(...it(yt,Math.min(xe,yt.length)));let qe=J-je.length;je.push(...it(Rt,Math.max(0,qe)));let Vn=J-je.length;if(Vn>0){let ce=At.filter(_e=>!je.includes(_e));je.push(...it(ce,Math.min(Vn,ce.length)))}let ts=je.slice(0,Math.min(J,At.length)),ul=ts.map(ce=>l[ce]);de=!0;let pl=(await f(Fe,ul)).reduce((ce,_e)=>ce+_e,0),dl=ts.reduce((ce,_e)=>ce+(Ye[_e]??0),0),ml=ts.reduce((ce,_e)=>ce+(xt[_e]??0),0);if(pl>=Math.max(dl,ml)+this.tieEpsilon){A(`Iteration ${M+1}: Merge accepted (programs ${L} + ${H} via ancestor ${ee})`);let ce=await p(Fe,l);m.push({instruction:Fe,parent:ee,scores:ce}),g.push(await f(Fe,l));let _e=C.length,Yt=Qe(C.map(Xe=>m[Xe].scores))??0;C=ut(m.map((Xe,gl)=>({idx:gl,scores:Xe.scores})),this.tieEpsilon).map(Xe=>Xe.idx);let Jn=Qe(C.map(Xe=>m[Xe].scores))??0;(C.length>_e||Jn>Yt+1e-6)&&(I=0),this.mergesDue-=1,this.totalMergesTested+=1}}}}if(de)continue}}let Y=Dn(F,q,()=>this.rand()),oe=this.minibatch?this.nextMinibatchIndices(c.length,M).map(G=>c[G]):c;if(r?.skipPerfectScore??!0){let G=Number(r?.perfectScore??1),B=await f(m[Y].instruction,oe);if(B.length>0&&B.every(K=>K>=G))continue}let U=!1,ae=m[Y].instruction,ne="reflective_mutation",Re,ot;if(U){let G=(Y+1)%m.length;ae=await this.mergeInstructions(m[Y].instruction,m[G].instruction,r),ne="merge",this.mergesUsed+=1}else{let G=r?.gepaAdapter;if(G){try{let B={instruction:m[Y].instruction},K=await G.evaluate(oe,B,!0);Re=Array.isArray(K?.scores)?K.scores.reduce((L,H)=>L+(Number(H)||0),0):void 0;let X=G.make_reflective_dataset(B,K,["instruction"]),_=await G.propose_new_texts?.(B,X,["instruction"]),$=_?.instruction??(_?Object.values(_)[0]:void 0);typeof $=="string"&&$.length>0?ae=$:ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:L,example:H})=>{let ee=await n({prediction:L,example:H}),me=Object.values(ee||{});return me.length?me.reduce((te,se)=>te+se,0)/me.length:0},r)}catch{ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)}if(Re!==void 0)try{let B=await G.evaluate(oe,{instruction:ae},!1);ot=Array.isArray(B?.scores)?B.scores.reduce((K,X)=>K+(Number(X)||0),0):void 0}catch{}}else ae=await this.reflectInstruction(m[Y].instruction,e,oe,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)}let ht=await f(m[Y].instruction,oe),De=await f(ae,oe),re=ht.reduce((G,B)=>G+B,0),ye=De.reduce((G,B)=>G+B,0);if(this.currentRound=M+1,await this.updateOptimizationProgress(this.currentRound,ye,{instructionLen:ae.length,parent:Y,totalRounds:this.numTrials},"GEPA",{strategy:ne,paretoSetSize:l.length},ye,{instructionLen:m[Y].instruction.length,idx:Y},{...r??{},maxIterations:this.numTrials}),!(ye>re+this.tieEpsilon&&(Re===void 0||ot===void 0||ot>Re+this.tieEpsilon))){if(A(`Iteration ${M+1}: Rejected (child=${ye.toFixed(3)} <= parent=${re.toFixed(3)})`),++I>=this.earlyStoppingTrials){A(`Early stopping: ${I} iterations without improvement`);break}continue}A(`Iteration ${M+1}: Accepted (child=${ye.toFixed(3)} > parent=${re.toFixed(3)})`);let we=await p(ae,l);m.push({instruction:ae,parent:Y,scores:we}),g.push(await f(ae,l));let be=C.length,z=Qe(C.map(G=>m[G].scores))??0;C=ut(m.map((G,B)=>({idx:B,scores:G.scores})),this.tieEpsilon).map(G=>G.idx);let W=Qe(C.map(G=>m[G].scores))??0;if(C.length>be||W>z+1e-6)I=0,A(`Iteration ${M+1}: Archive improved (size=${C.length}, hv=${W.toFixed(4)})`);else if(I++,A(`Iteration ${M+1}: Archive unchanged (stagnation=${I}/${this.earlyStoppingTrials})`),I>=this.earlyStoppingTrials){A(`Early stopping: ${I} iterations without archive improvement`);break}this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=ut(m.map((M,D)=>({idx:D,scores:M.scores})),this.tieEpsilon),P=R.length>0?Math.max(...R.map(M=>h(M.scores))):0,E;if(R.length>0){let M=Number.NEGATIVE_INFINITY;for(let D of R){let F=h(D.scores);F>M&&(M=F,E=D.idx)}}let w=Qe(R.map(M=>M.scores));this.stats.convergenceInfo.converged=!0;let v=this.getMergedCustomLabels(r);this.recordParetoMetrics(R.length,m.length,"GEPA",w,v);let k=Date.now()-s,O=typeof E=="number"?new gt({bestScore:P,stats:this.stats,instruction:m[E].instruction,demos:[],examples:t,modelConfig:void 0,optimizerType:"GEPA",optimizationTime:k,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged}):void 0,N=this.generateOptimizationReport(R,w,P);return{demos:[],stats:this.stats,bestScore:P,paretoFront:R.map(M=>({demos:[],scores:M.scores,configuration:{candidate:M.idx,instruction:m[M.idx].instruction},dominatedSolutions:M.dominated})),paretoFrontSize:R.length,hypervolume:w,finalConfiguration:{strategy:"gepa",candidates:m.length},optimizedProgram:O,report:N}}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){let t=e.getInstruction?.();if(t&&t.length>0)return t;let r=e.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let s=[];for(let o of n){let a=await this.evaluateOne(e,t,o,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?_t(s):0}async evaluateOne(e,t,n,r){try{e.setInstruction?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let o=await r({prediction:s,example:n});if(typeof o=="number"&&!Number.isNaN(o)){let a=typeof this.targetScore=="number"?this.targetScore:.5;return o>=a&&(this.stats.successfulDemos+=1),o}return 0}catch(s){return this.getLogger()?.({name:"Notification",id:"gepa_eval",value:String(s)}),0}}async reflectInstruction(e,t,n,r,s,o){let a=o??[];if(a.length===0)for(let m of n)try{t.setInstruction?.(e);let h=await t.forward(this.studentAI,m,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let g=await r({prediction:h,example:m});a.push({input:m,prediction:h,score:typeof g=="number"?g:0})}catch{a.push({input:m,prediction:{},score:0})}let l=s?.overrideTeacherAI??this.teacherAI??this.studentAI,c=s?.feedbackFn,u=()=>{let m=[];for(let h=0;h<a.length;h++){let g=a[h],f=`# Example ${h+1}
454
454
  `;if(f+=`## Inputs
455
455
  `,typeof g.input=="object"&&g.input!==null)for(let[x,b]of Object.entries(g.input))f+=`### ${x}
456
456
  ${String(b).trim()}
@@ -472,8 +472,8 @@ ${String(b).trim()}
472
472
  instructionB:string "Parent B instruction",
473
473
  recentFeedback?:string[] "Past feedback memory"
474
474
  -> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await s.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)}};function Ya(i){return i.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.isOptional?" (optional)":"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
475
- `)}function Tu(i){return i.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
476
- `)}var Un=class{signature;options;constructor(e,t){this.signature=e,this.options={teacher:t.teacher,diversity:t.diversity??"none",temperature:t.temperature??.8,domain:t.domain,edgeCases:t.edgeCases,model:t.model}}async generate(e,t){let n=Date.now(),r=t?.batchSize??Math.min(e,10),s=[],o=0,a=0;for(let l=0;l<e;l+=r){let c=Math.min(r,e-l),u=await this.generateInputs(c);for(let p of u){a++;try{let d=await this.labelInput(p);s.push({input:p,expected:d,category:"normal"}),o++}catch(d){console.warn("AxSynth: Failed to label input:",d)}}}if(this.options.edgeCases&&this.options.edgeCases.length>0){let l=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let c of l){a++;try{let u=await this.labelInput(c);s.push({input:c,expected:u,category:"edge_case"}),o++}catch(u){console.warn("AxSynth: Failed to label edge case input:",u)}}}return{examples:s,stats:{requested:e,generated:s.length,labelingSuccessRate:a>0?o/a:0,durationMs:Date.now()-n}}}async generateInputs(e){let t=this.signature.getInputFields(),n=this.signature.getOutputFields(),r=this.signature.getDescription(),s=`
475
+ `)}function Cu(i){return i.map(e=>{let t=e.type?.name??"string",n=e.type?.isArray?"[]":"",r=e.type?.options?` (options: ${e.type.options.join(", ")})`:"",s=e.description?`: ${e.description}`:"";return`- ${e.name}: ${t}${n}${r}${s}`}).join(`
476
+ `)}var Bn=class{signature;options;constructor(e,t){this.signature=e,this.options={teacher:t.teacher,diversity:t.diversity??"none",temperature:t.temperature??.8,domain:t.domain,edgeCases:t.edgeCases,model:t.model}}async generate(e,t){let n=Date.now(),r=t?.batchSize??Math.min(e,10),s=[],o=0,a=0;for(let l=0;l<e;l+=r){let c=Math.min(r,e-l),u=await this.generateInputs(c);for(let p of u){a++;try{let d=await this.labelInput(p);s.push({input:p,expected:d,category:"normal"}),o++}catch(d){console.warn("AxSynth: Failed to label input:",d)}}}if(this.options.edgeCases&&this.options.edgeCases.length>0){let l=await this.generateEdgeCaseInputs(Math.ceil(e*.2));for(let c of l){a++;try{let u=await this.labelInput(c);s.push({input:c,expected:u,category:"edge_case"}),o++}catch(u){console.warn("AxSynth: Failed to label edge case input:",u)}}}return{examples:s,stats:{requested:e,generated:s.length,labelingSuccessRate:a>0?o/a:0,durationMs:Date.now()-n}}}async generateInputs(e){let t=this.signature.getInputFields(),n=this.signature.getOutputFields(),r=this.signature.getDescription(),s=`
477
477
  You are generating realistic input data for an AI system.
478
478
 
479
479
  ${r?`Task description: ${r}`:""}
@@ -483,7 +483,7 @@ The system expects these INPUT fields:
483
483
  ${Ya(t)}
484
484
 
485
485
  The system produces these OUTPUT fields:
486
- ${Tu(n)}
486
+ ${Cu(n)}
487
487
 
488
488
  Generate ${e} diverse, realistic input examples as a JSON array.
489
489
  Each example should be an object with the input fields defined above.
@@ -502,7 +502,7 @@ ${n.map(o=>`- ${o}`).join(`
502
502
  `)}
503
503
 
504
504
  Output ONLY the JSON array, no explanation.
505
- `.trim(),s=new Ae("count:number -> examples:json");s.setInstruction(r);try{let o=await s.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(o.examples)?o.examples.slice(0,e):[]}catch(o){return console.warn("AxSynth: Edge case generation failed:",o),[]}}async labelInput(e){return await new Ae(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var vo=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new Ln(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,s=n.budget??20,o=[...n.examples??[]];if(n.useTraces!==!1){let I=(await this.getTraces()).filter(C=>C.input&&C.output).map(C=>({...C.input,...C.output}));o=[...o,...I]}if(n.generateExamples||o.length===0){let A=n.synthCount??20,I={teacher:r,...n.synthOptions},R=(await new Un(this.gen.getSignature(),I).generate(A)).examples.map(P=>({...P.input,...P.expected}));o=[...o,...R]}if(o.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...o].sort(()=>Math.random()-.5),c=Math.floor(l.length*(1-a)),u=l.slice(0,c),p=l.slice(c),d=n.metric;if(!d){let A={ai:r,criteria:n.criteria,...n.judgeOptions};d=new Nn(this.gen.getSignature(),A).toMetricFn()}let m=new Dn({studentAI:r,numTrials:s,minibatch:!0,minibatchSize:10}),h=s*Math.max(u.length,10),g=await m.compile(this.gen,u,d,{validationExamples:p,maxMetricCalls:h});if(!g.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");g.optimizedProgram.instruction&&this.gen.setInstruction(g.optimizedProgram.instruction),this.currentScore=g.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,y=f,b=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,T={type:"checkpoint",name:this.options.name,version:b,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:s,trainingExamples:u.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,T),{score:f,improvement:y,checkpointVersion:b,stats:{trainingExamples:u.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var So=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(s=>{let o={};return t.forEach(a=>{let l=a.split("."),c=s.row;for(let p of l)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);o[u]=c}),o}).filter(s=>Object.keys(s).length!==0)}};import Cu 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 _t(i){return JSON.parse(JSON.stringify(i))}function Ru(i){return Math.ceil(i.length/4)}function Oo(i,e,t){let n=[],r=[],{maxSectionSize:s=Number.POSITIVE_INFINITY,allowDynamicSections:o=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),u=l??new Set;for(let p of e){if(!p.section)continue;if(!i.sections[p.section]){if(!o)continue;i.sections[p.section]=[]}let d=i.sections[p.section];switch(p.type){case"ADD":{if(d.length>=s){if(!a)continue;let g=vu(d,u);if(!g)continue;n.push(g.id),r.push({type:"REMOVE",section:p.section,bulletId:g.id,metadata:{...g.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??wu(p.section),h={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:p.metadata?{...p.metadata}:void 0};d.push(h),n.push(m);break}case"UPDATE":{let m=d.find(h=>h.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=c,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(h=>h.id===p.bulletId);if(m>=0){let[h]=d.splice(m,1);h&&n.push(h.id)}break}}}return Eo(i),i.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function Mo(i,e,t){for(let n of Object.values(i.sections)){let r=n.find(s=>s.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),Eo(i);return}}}function Bn(i){let e=i.description?`## Context Playbook
505
+ `.trim(),s=new Ae("count:number -> examples:json");s.setInstruction(r);try{let o=await s.forward(this.options.teacher,{count:e},{model:this.options.model});return Array.isArray(o.examples)?o.examples.slice(0,e):[]}catch(o){return console.warn("AxSynth: Edge case generation failed:",o),[]}}async labelInput(e){return await new Ae(this.signature).forward(this.options.teacher,e,{model:this.options.model})}getSignature(){return this.signature}getTeacher(){return this.options.teacher}};var So=class i{gen;options;tracer;currentScore;constructor(e,t){this.gen=e,this.options={...t,enableTracing:t.enableTracing??!0},this.tracer=new $n(e,{name:this.options.name,storage:this.options.storage,metadata:this.options.metadata,onTrace:this.options.onTrace}),this.loadLatestCheckpoint()}async forward(e,t,n){return this.options.enableTracing?this.tracer.forward(e,t,n):this.gen.forward(e,t,n)}async*streamingForward(e,t,n){this.options.enableTracing?yield*this.tracer.streamingForward(e,t,n):yield*this.gen.streamingForward(e,t,n)}getUsage(){return this.gen.getUsage()}resetUsage(){this.gen.resetUsage()}getSignature(){return this.gen.getSignature()}setInstruction(e){this.gen.setInstruction(e)}getInstruction(){return this.gen.getInstruction()}updateMeter(e){this.gen.updateMeter(e)}addAssert(e,t){this.gen.addAssert(e,t)}addStreamingAssert(e,t,n){this.gen.addStreamingAssert(e,t,n)}addFieldProcessor(e,t){this.gen.addFieldProcessor(e,t)}addStreamingFieldProcessor(e,t){this.gen.addStreamingFieldProcessor(e,t)}clone(){return new i(this.gen.clone(),this.options)}async optimize(e={}){let t=Date.now(),n={...this.options,...e},r=n.teacher,s=n.budget??20,o=[...n.examples??[]];if(n.useTraces!==!1){let I=(await this.getTraces()).filter(C=>C.input&&C.output).map(C=>({...C.input,...C.output}));o=[...o,...I]}if(n.generateExamples||o.length===0){let A=n.synthCount??20,I={teacher:r,...n.synthOptions},R=(await new Bn(this.gen.getSignature(),I).generate(A)).examples.map(P=>({...P.input,...P.expected}));o=[...o,...R]}if(o.length===0)throw new Error("No training examples available. Provide examples, enable trace usage, or enable example generation.");let a=n.validationSplit??.2,l=[...o].sort(()=>Math.random()-.5),c=Math.floor(l.length*(1-a)),u=l.slice(0,c),p=l.slice(c),d=n.metric;if(!d){let A={ai:r,criteria:n.criteria,...n.judgeOptions};d=new Ln(this.gen.getSignature(),A).toMetricFn()}let m=new Un({studentAI:r,numTrials:s,minibatch:!0,minibatchSize:10}),h=s*Math.max(u.length,10),g=await m.compile(this.gen,u,d,{validationExamples:p,maxMetricCalls:h});if(!g.optimizedProgram)throw new Error("GEPA optimization failed: no optimizedProgram returned");g.optimizedProgram.instruction&&this.gen.setInstruction(g.optimizedProgram.instruction),this.currentScore=g.optimizedProgram.bestScore,this.tracer=this.tracer.clone(this.gen);let f=this.currentScore,y=f,b=((await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0]?.version??0)+1,T={type:"checkpoint",name:this.options.name,version:b,createdAt:new Date,instruction:this.gen.getInstruction(),score:f,optimizerType:"gepa",metadata:{budget:s,trainingExamples:u.length,durationMs:Date.now()-t}};return await this.options.storage.save(this.options.name,T),{score:f,improvement:y,checkpointVersion:b,stats:{trainingExamples:u.length,validationExamples:p.length,durationMs:Date.now()-t}}}async loadLatestCheckpoint(){try{let t=(await this.options.storage.load(this.options.name,{type:"checkpoint",limit:1}))[0];t?.instruction&&(this.gen.setInstruction(t.instruction),this.currentScore=t.score,this.tracer=this.tracer.clone(this.gen))}catch{}}getGen(){return this.gen}getStorage(){return this.options.storage}async getTraces(e){return this.options.storage.load(this.options.name,{type:"trace",...e})}async addFeedback(e,t){let n=await this.options.storage.load(this.options.name,{id:e,type:"trace",limit:1});if(n.length>0){let r=n[0];r.feedback={...r.feedback,...t},await this.options.storage.save(this.options.name,r)}}};var ko=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(s=>{let o={};return t.forEach(a=>{let l=a.split("."),c=s.row;for(let p of l)Object.hasOwn(c,p)&&(c=c[p]);if(!c)return;let u=n&&a in n?n[a]:a;if(!u)throw new Error(`Invalid field name: ${a}`);o[u]=c}),o}).filter(s=>Object.keys(s).length!==0)}};import Ru from"crypto";function Oo(i){let e=new Date().toISOString();return{version:1,sections:{},stats:{bulletCount:0,helpfulCount:0,harmfulCount:0,tokenEstimate:0},updatedAt:e,description:i}}function Nt(i){return JSON.parse(JSON.stringify(i))}function wu(i){return Math.ceil(i.length/4)}function Mo(i,e,t){let n=[],r=[],{maxSectionSize:s=Number.POSITIVE_INFINITY,allowDynamicSections:o=!0,enableAutoPrune:a=!1,protectedBulletIds:l}=t??{},c=new Date().toISOString(),u=l??new Set;for(let p of e){if(!p.section)continue;if(!i.sections[p.section]){if(!o)continue;i.sections[p.section]=[]}let d=i.sections[p.section];switch(p.type){case"ADD":{if(d.length>=s){if(!a)continue;let g=Su(d,u);if(!g)continue;n.push(g.id),r.push({type:"REMOVE",section:p.section,bulletId:g.id,metadata:{...g.metadata??{},autoPruned:!0,removedAt:c}})}let m=p.bulletId??vu(p.section),h={id:m,section:p.section,content:p.content??"",helpfulCount:0,harmfulCount:0,createdAt:c,updatedAt:c,metadata:p.metadata?{...p.metadata}:void 0};d.push(h),n.push(m);break}case"UPDATE":{let m=d.find(h=>h.id===p.bulletId);if(!m)continue;typeof p.content=="string"&&(m.content=p.content),m.updatedAt=c,p.metadata&&(m.metadata={...m.metadata??{},...p.metadata}),n.push(m.id);break}case"REMOVE":{let m=d.findIndex(h=>h.id===p.bulletId);if(m>=0){let[h]=d.splice(m,1);h&&n.push(h.id)}break}}}return Fo(i),i.updatedAt=c,{updatedBulletIds:n,autoRemoved:r}}function Po(i,e,t){for(let n of Object.values(i.sections)){let r=n.find(s=>s.id===e);if(r){t==="helpful"?r.helpfulCount+=1:t==="harmful"&&(r.harmfulCount+=1),r.updatedAt=new Date().toISOString(),Fo(i);return}}}function jn(i){let e=i.description?`## Context Playbook
506
506
  ${i.description.trim()}
507
507
  `:`## Context Playbook
508
508
  `,t=Object.entries(i.sections).map(([n,r])=>{let s=r.map(o=>`- [${o.id}] ${o.content}`).join(`
@@ -511,11 +511,11 @@ ${s}`:`### ${n}
511
511
  _(empty)_`}).join(`
512
512
 
513
513
  `);return`${e}
514
- ${t}`.trim()}function wu(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Cu.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function vu(i,e){let t=-1,n;for(let s=0;s<i.length;s+=1){let o=i[s];if(e.has(o.id))continue;let a=o.helpfulCount??0,l=o.harmfulCount??0,c=a-l*2,u=Date.parse(o.updatedAt??o.createdAt),p=[c,a,Number.isFinite(u)?u:Number.POSITIVE_INFINITY];if(!n){t=s,n=p;continue}let d=i[t],m=d.helpfulCount??0,h=d.harmfulCount??0,g=m-h*2,f=Date.parse(d.updatedAt??d.createdAt),y=[g,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(p[0]<y[0]||p[0]===y[0]&&p[1]<y[1]||p[0]===y[0]&&p[1]===y[1]&&p[2]<y[2])&&(t=s,n=p)}if(t===-1)return;let[r]=i.splice(t,1);return r}function Po(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,s=[];for(let o of n){let a=o.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=o.helpfulCount,l.harmfulCount+=o.harmfulCount,l.updatedAt=o.updatedAt):(r.set(a,o),s.push(o))}i.sections[t]=s}Eo(i)}function Eo(i){let e=0,t=0,n=0,r=0;for(let s of Object.values(i.sections))for(let o of s)e+=1,t+=o.helpfulCount,n+=o.harmfulCount,r+=Ru(o.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var Su={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},Vr=class extends gt{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=_t(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(),"",Bn(this.playbook)].filter(s=>s&&s.trim().length>0).join(`
514
+ ${t}`.trim()}function vu(i){let e=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,6),t=Ru.randomBytes(4).toString("hex");return`${e||"ctx"}-${t}`}function Su(i,e){let t=-1,n;for(let s=0;s<i.length;s+=1){let o=i[s];if(e.has(o.id))continue;let a=o.helpfulCount??0,l=o.harmfulCount??0,c=a-l*2,u=Date.parse(o.updatedAt??o.createdAt),p=[c,a,Number.isFinite(u)?u:Number.POSITIVE_INFINITY];if(!n){t=s,n=p;continue}let d=i[t],m=d.helpfulCount??0,h=d.harmfulCount??0,g=m-h*2,f=Date.parse(d.updatedAt??d.createdAt),y=[g,m,Number.isFinite(f)?f:Number.POSITIVE_INFINITY];(p[0]<y[0]||p[0]===y[0]&&p[1]<y[1]||p[0]===y[0]&&p[1]===y[1]&&p[2]<y[2])&&(t=s,n=p)}if(t===-1)return;let[r]=i.splice(t,1);return r}function Eo(i,e=.95){for(let[t,n]of Object.entries(i.sections)){let r=new Map,s=[];for(let o of n){let a=o.content.trim().toLowerCase(),l=r.get(a);l?(l.helpfulCount+=o.helpfulCount,l.harmfulCount+=o.harmfulCount,l.updatedAt=o.updatedAt):(r.set(a,o),s.push(o))}i.sections[t]=s}Fo(i)}function Fo(i){let e=0,t=0,n=0,r=0;for(let s of Object.values(i.sections))for(let o of s)e+=1,t+=o.helpfulCount,n+=o.harmfulCount,r+=wu(o.content);i.stats={bulletCount:e,helpfulCount:t,harmfulCount:n,tokenEstimate:r}}var ku={maxEpochs:1,maxReflectorRounds:2,maxSectionSize:25,similarityThreshold:.95,allowDynamicSections:!0},Jr=class extends gt{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=Nt(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(),"",jn(this.playbook)].filter(s=>s&&s.trim().length>0).join(`
515
515
 
516
- `);e.setDescription(r)}},Fo=class extends ze{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...Su,...t},this.playbook=t?.initialPlaybook!==void 0?_t(t.initialPlaybook):ko()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?_t(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 s=r?.aceOptions;s&&(Object.assign(this.aceConfig,{maxEpochs:s.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:s.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:s.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:s.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:s.allowDynamicSections??this.aceConfig.allowDynamicSections}),s.initialPlaybook&&(this.playbook=_t(s.initialPlaybook)));let o=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let y=0;y<p;y++)for(let x=0;x<t.length;x++){let b=t[x],T=this.composeInstruction(a??l,this.playbook);e.setDescription?.(T);let A=await e.forward(this.studentAI,b);this.stats.totalCalls+=1;let I=await n({prediction:A,example:b});typeof I=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,I),c=Math.max(c,I));let C=A?.severity,S=b?.severity,R=this.createGeneratorOutput(A,b),P=S&&C&&S!==C,E=await this.runReflectionRounds({example:b,generatorOutput:R,feedback:S&&C&&S!==C?`Expected severity "${S}" but model predicted "${C}".`:void 0}),w=await this.runCurator({program:e,example:b,reflection:E,playbook:this.playbook}),v=this.normalizeCuratorOperations(w?.operations);v.length===0&&P&&(v=this.inferOperationsFromReflection(E)),v=this.resolveCuratorOperationTargets(v,this.playbook,E,R);let k=w||v.length>0?{...w??{},operations:v}:void 0,O=[];if(v.length>0){let q=this.collectProtectedBulletIds(v),Y=Oo(this.playbook,v,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:q});O=Y.updatedBulletIds,Y.autoRemoved.length>0&&(v.push(...Y.autoRemoved),k&&(k.operations=v))}if(E?.bulletTags)for(let q of E.bulletTags)Mo(this.playbook,q.id,q.tag);v.length>0&&O.length>0&&Po(this.playbook,this.aceConfig.similarityThreshold);let N={example:b,prediction:A,score:typeof I=="number"?I:0,generatorOutput:R,reflection:E,curator:k,timestamp:new Date().toISOString()};this.generatorHistory.push(N),O.length>0&&k?.operations?.length&&this.deltaHistory.push({epoch:y,exampleIndex:x,operations:k.operations}),u+=1,this.currentRound=u;let M=typeof I=="number"&&Number.isFinite(I)?I:0,D=Number.isFinite(c)?c:M,F={...r??{},maxIterations:d};await this.updateOptimizationProgress(u,M,{epoch:y,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},D,{playbookBullets:this.playbook.stats.bulletCount},void 0,F),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,M)}}finally{e.setDescription?.(l)}let m=Date.now()-o;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let h={playbook:_t(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},g=new Vr({baseInstruction:a??l,playbook:this.playbook,artifact:h,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:u,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:g,playbook:_t(this.playbook),artifact:h}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,s=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),o=await this.runCurator({program:this.program,example:e.example,reflection:s,playbook:this.playbook}),a=this.normalizeCuratorOperations(o?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(s)),a=this.resolveCuratorOperationTargets(a,this.playbook,s,t);let c=o||a.length>0?{...o??{},operations:a}:void 0;if(s?.bulletTags)for(let p of s.bulletTags)Mo(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Oo(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Po(this.playbook,this.aceConfig.similarityThreshold)}let u={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:s,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(u),c}composeInstruction(e,t){return[e.trim(),"",Bn(t)].filter(r=>r.trim().length>0).join(`
516
+ `);e.setDescription(r)}},_o=class extends ze{aceConfig;playbook;generatorHistory=[];deltaHistory=[];reflectorProgram;curatorProgram;program;constructor(e,t){super(e),this.aceConfig={...ku,...t},this.playbook=t?.initialPlaybook!==void 0?Nt(t.initialPlaybook):Oo()}reset(){super.reset(),this.playbook=this.aceConfig.initialPlaybook!==void 0?Nt(this.aceConfig.initialPlaybook):Oo(),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 s=r?.aceOptions;s&&(Object.assign(this.aceConfig,{maxEpochs:s.maxEpochs??this.aceConfig.maxEpochs,maxReflectorRounds:s.maxReflectorRounds??this.aceConfig.maxReflectorRounds,maxSectionSize:s.maxSectionSize??this.aceConfig.maxSectionSize,similarityThreshold:s.similarityThreshold??this.aceConfig.similarityThreshold,allowDynamicSections:s.allowDynamicSections??this.aceConfig.allowDynamicSections}),s.initialPlaybook&&(this.playbook=Nt(s.initialPlaybook)));let o=Date.now();this.validateExamples(t),this.program=e;let a=await this.extractProgramInstruction(e),l=e.getSignature().getDescription()??"";this.generatorHistory=[],this.deltaHistory=[];let c=Number.NEGATIVE_INFINITY,u=0,p=Math.max(this.aceConfig.maxEpochs,1),d=p*t.length;try{for(let y=0;y<p;y++)for(let x=0;x<t.length;x++){let b=t[x],T=this.composeInstruction(a??l,this.playbook);e.setDescription?.(T);let A=await e.forward(this.studentAI,b);this.stats.totalCalls+=1;let I=await n({prediction:A,example:b});typeof I=="number"&&(this.stats.bestScore=Math.max(this.stats.bestScore,I),c=Math.max(c,I));let C=A?.severity,S=b?.severity,R=this.createGeneratorOutput(A,b),P=S&&C&&S!==C,E=await this.runReflectionRounds({example:b,generatorOutput:R,feedback:S&&C&&S!==C?`Expected severity "${S}" but model predicted "${C}".`:void 0}),w=await this.runCurator({program:e,example:b,reflection:E,playbook:this.playbook}),v=this.normalizeCuratorOperations(w?.operations);v.length===0&&P&&(v=this.inferOperationsFromReflection(E)),v=this.resolveCuratorOperationTargets(v,this.playbook,E,R);let k=w||v.length>0?{...w??{},operations:v}:void 0,O=[];if(v.length>0){let q=this.collectProtectedBulletIds(v),Y=Mo(this.playbook,v,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:q});O=Y.updatedBulletIds,Y.autoRemoved.length>0&&(v.push(...Y.autoRemoved),k&&(k.operations=v))}if(E?.bulletTags)for(let q of E.bulletTags)Po(this.playbook,q.id,q.tag);v.length>0&&O.length>0&&Eo(this.playbook,this.aceConfig.similarityThreshold);let N={example:b,prediction:A,score:typeof I=="number"?I:0,generatorOutput:R,reflection:E,curator:k,timestamp:new Date().toISOString()};this.generatorHistory.push(N),O.length>0&&k?.operations?.length&&this.deltaHistory.push({epoch:y,exampleIndex:x,operations:k.operations}),u+=1,this.currentRound=u;let M=typeof I=="number"&&Number.isFinite(I)?I:0,D=Number.isFinite(c)?c:M,F={...r??{},maxIterations:d};await this.updateOptimizationProgress(u,M,{epoch:y,exampleIndex:x,playbookBullets:this.playbook.stats.bulletCount},"ACE",{epochs:p,totalRounds:d},D,{playbookBullets:this.playbook.stats.bulletCount},void 0,F),this.stats.convergenceInfo.finalImprovement=Math.max(this.stats.convergenceInfo.finalImprovement,M)}}finally{e.setDescription?.(l)}let m=Date.now()-o;this.stats.resourceUsage.totalTime=m,this.stats.convergenceInfo.converged=!0,this.stats.bestScore=Number.isFinite(c)?c:0;let h={playbook:Nt(this.playbook),feedback:[...this.generatorHistory],history:[...this.deltaHistory]},g=new Jr({baseInstruction:a??l,playbook:this.playbook,artifact:h,bestScore:Number.isFinite(c)?c:0,stats:this.stats,optimizerType:"ACE",optimizationTime:m,totalRounds:u,converged:this.stats.convergenceInfo.converged});return{stats:this.stats,bestScore:Number.isFinite(c)?c:0,finalConfiguration:{strategy:"ace",epochs:p},optimizedProgram:g,playbook:Nt(this.playbook),artifact:h}}async applyOnlineUpdate(e){if(!this.program)throw new Error("AxACE: `compile` must be run before `applyOnlineUpdate`");let t=this.createGeneratorOutput(e.prediction,e.example),n=e.prediction?.severity,r=e.example?.severity,s=await this.runReflectionRounds({example:e.example,generatorOutput:t,feedback:e.feedback??(r&&n&&r!==n?`Expected severity "${r}" but model predicted "${n}".`:void 0)}),o=await this.runCurator({program:this.program,example:e.example,reflection:s,playbook:this.playbook}),a=this.normalizeCuratorOperations(o?.operations),l=r&&n&&r!==n;a.length===0&&l&&(a=this.inferOperationsFromReflection(s)),a=this.resolveCuratorOperationTargets(a,this.playbook,s,t);let c=o||a.length>0?{...o??{},operations:a}:void 0;if(s?.bulletTags)for(let p of s.bulletTags)Po(this.playbook,p.id,p.tag);if(a.length>0){let p=this.collectProtectedBulletIds(a),d=Mo(this.playbook,a,{maxSectionSize:this.aceConfig.maxSectionSize,allowDynamicSections:this.aceConfig.allowDynamicSections,enableAutoPrune:!0,protectedBulletIds:p});d.autoRemoved.length>0&&(a.push(...d.autoRemoved),c&&(c.operations=a)),Eo(this.playbook,this.aceConfig.similarityThreshold)}let u={example:e.example,prediction:e.prediction,score:0,generatorOutput:t,reflection:s,curator:c,timestamp:new Date().toISOString()};return this.generatorHistory.push(u),c}composeInstruction(e,t){return[e.trim(),"",jn(t)].filter(r=>r.trim().length>0).join(`
517
517
 
518
- `)}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 s=[],o=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(o.has(u))return;let d=this.locateBullet(t,u);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let u of n?.bulletTags??[]){let p=u.tag==="harmful"?"harmful":"primary";l(u.id,p)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let p=a.get(u);if(!p)return this.locateFallbackBullet(t,u,o);let d=h=>{for(;h.length>0;){let g=h.shift();if(!o.has(g))return g}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,o)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,o.add(p))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||s.push(u)}return s}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(s=>s.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let s of r)if(!n.has(s.id))return s.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 s=r.type??"ADD",o=typeof s=="string"?s.toUpperCase():"ADD",a=o==="UPDATE"?"UPDATE":o==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",p=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,g=[a,c,p,m??""].join(":");if(n.has(g))continue;n.add(g);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let y=r.metadata;y&&typeof y=="object"&&(f.metadata={...y}),t.push(f)}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=(s,o)=>{if(!o)return;let a=o.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${s}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:s,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),s;for(let o=0;o<r;o++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:s});if(!a)break;s=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return s}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let s=this.getOrCreateReflectorProgram(),o=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await s.forward(o,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:Bn(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({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let s=this.getOrCreateCuratorProgram(),o=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await s.forward(o,{playbook:JSON.stringify({markdown:Bn(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ue().input("question",ue.string("Original task input serialized as JSON")).input("generator_answer",ue.string("Generator output serialized as JSON")).input("generator_reasoning",ue.string("Generator reasoning trace").optional()).input("playbook",ue.string("Current context playbook rendered as markdown")).input("expected_answer",ue.string("Expected output when ground truth is available").optional()).input("feedback",ue.string("External feedback or reward signal").optional()).input("previous_reflection",ue.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ue.string("Step-by-step analysis of generator performance")).output("errorIdentification",ue.string("Specific mistakes detected")).output("rootCauseAnalysis",ue.string("Underlying cause of the error")).output("correctApproach",ue.string("What the generator should do differently")).output("keyInsight",ue.string("Reusable insight to remember")).output("bulletTags",ue.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Ge(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ue().input("playbook",ue.string("Current playbook serialized as JSON")).input("reflection",ue.string("Latest reflection output serialized as JSON")).input("question_context",ue.string("Original task input serialized as JSON")).input("token_budget",ue.number("Approximate token budget for curator response").optional()).output("reasoning",ue.string("Justification for the proposed updates")).output("operations",ue.json("List of operations with type/section/content fields")).build();this.curatorProgram=Ge(e)}return this.curatorProgram}};var jn=class extends ze{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,s){let o=Date.now(),a=s?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Ou([...t],this.maxExamples),u=this.traces.length;for(let p=0;p<c.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=c.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let h=t.filter(y=>y!==m);e.setExamples(h);let g=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let y={...l,maxRetries:1};f=await e.forward(g,m,y),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(y){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${y instanceof Error?y.message:"Unknown error"}`),f={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-u;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 s=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<s&&(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 o=ku(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:o.length,tracesCollected:this.traces.length},r),{demos:o,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function ku(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 Ou=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),s=t[n],o=t[r];if(!s||!o)throw new Error("Invalid array elements");[t[n],t[r]]=[o,s]}return t.slice(0,e)};var _o=class extends ze{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 s=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(s??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 s=Date.now(),o=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=o.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(v,k)=>{try{o.setAllNodeInstructions?.(v);let O=await o.forward(this.studentAI,k,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:O,example:k})||{}}catch{return{}}},h=async(v,k)=>{let O=[];for(let N of k)O.push(await m(v,N));return Wr(O)},g={};for(let v of a)g[v.name]=await this.getBaseInstruction(v.program);let f=[{cfg:{...g},parent:void 0,scores:await h(g,u)}],y=v=>{let k=r?.paretoMetricKey,O=r?.paretoScalarize;if(typeof O=="function")return O(v);if(k)return Number.isFinite(v[k])?v[k]:0;let N=Object.values(v);return N.length?N.reduce((M,D)=>M+D,0)/N.length:0},x=[],b=async(v,k)=>{let O=[];for(let N of k){let M=await m(v,N);O.push(y(M))}return O};x.push(await b(g,u));let T=ut(f.map((v,k)=>({idx:k,scores:v.scores})),this.tieEpsilon).map(v=>v.idx),A=0,I=new Set,C=r?.maxMetricCalls;if(!Number.isFinite(C)||C<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let S=Math.floor(C);for(let v=0;v<this.numTrials&&!(S!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(S)));v++){let k=x[0]?.length??0,O=[];for(let z=0;z<k;z++){let W=Number.NEGATIVE_INFINITY,G=new Set;for(let B=0;B<x.length;B++){let K=x[B][z];K>W+this.tieEpsilon?(W=K,G.clear(),G.add(B)):Math.abs(K-W)<=this.tieEpsilon&&G.add(B)}O.push(G)}let N=x.map(z=>Ft(z));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let z=$n(O,N),W=new Set;for(let _ of z)for(let $ of _)W.add($);let G=Array.from(W),B=_=>{let $=[],L=_;for(;L!==void 0;)$.push(L),L=f[L]?.parent;return $},K=_=>_.length?_[Math.floor(this.rand()*_.length)]:void 0,X;for(let _=0;_<10&&!X&&!(G.length<2);_++){let $=K(G),L=K(G);if($===L)continue;L<$&&([$,L]=[L,$]);let H=new Set(B($)),ee=new Set(B(L));if(H.has(L)||ee.has($))continue;let me=[...H].filter(de=>ee.has(de));if(me.length===0)continue;let te=[];for(let de of me){let pt=f[de].cfg,ft=f[$].cfg,Ye=f[L].cfg,xt=!1,At=new Set([...Object.keys(pt),...Object.keys(ft),...Object.keys(Ye)]);for(let dt of At){let yt=pt[dt],Rt=ft[dt],J=Ye[dt];if(Rt===yt&&J!==Rt||J===yt&&Rt!==J){xt=!0;break}}xt&&te.push(de)}if(te.length===0)continue;let se=te.map(de=>Math.max(1e-9,N[de])),le=this.rand()*se.reduce((de,pt)=>de+pt,0),pe=te[te.length-1];for(let de=0;de<te.length;de++){if(le<se[de]){pe=te[de];break}le-=se[de]}let Te=N[pe],ve=N[$],He=N[L];if(Te>Math.min(ve,He))continue;let Fe=`${$}|${L}|${pe}`;if(this.mergeAttemptKeys.has(Fe))continue;this.mergeAttemptKeys.add(Fe);let Be=`${$}|${L}|${pe}`;I.has(Be)||(X={i:$,j:L,a:pe})}if(this.lastIterFoundNewProgram=!1,X){let{i:_,j:$,a:L}=X,{cfg:H,descSig:ee}=this.systemAwareMergeWithSig(f,_,$,(J,xe)=>N[J]>=N[xe]?J:xe),me=`${Math.min(_,$)}|${Math.max(_,$)}|${ee}`;if(this.mergeCompositionKeys.has(me))continue;this.mergeCompositionKeys.add(me);let te=x[_],se=x[$],le=Array.from({length:te.length},(J,xe)=>xe),pe=le.filter(J=>(te[J]??0)>(se[J]??0)),Te=le.filter(J=>(se[J]??0)>(te[J]??0)),ve=le.filter(J=>!(pe.includes(J)||Te.includes(J))),He=5,Fe=Math.ceil(He/3),Be=(J,xe)=>{if(xe<=0||J.length===0)return[];if(J.length<=xe)return[...J];let it=[],je=new Set;for(;it.length<xe;){let qe=Math.floor(this.rand()*J.length);je.has(qe)||(je.add(qe),it.push(J[qe]))}return it},de=[];de.push(...Be(pe,Math.min(Fe,pe.length))),de.push(...Be(Te,Math.min(Fe,Te.length)));let pt=He-de.length;de.push(...Be(ve,Math.max(0,pt)));let ft=He-de.length;if(ft>0){let J=le.filter(xe=>!de.includes(xe));de.push(...Be(J,Math.min(ft,J.length)))}let Ye=de.slice(0,Math.min(He,le.length)),xt=Ye.map(J=>u[J]),dt=(await b(H,xt)).reduce((J,xe)=>J+xe,0),yt=Ye.reduce((J,xe)=>J+(te[xe]??0),0),Rt=Ye.reduce((J,xe)=>J+(se[xe]??0),0);if(dt>=Math.max(yt,Rt)+this.tieEpsilon){let J=await h(H,u);f.push({cfg:H,parent:L,scores:J}),x.push(await b(H,u));let xe=T.length,it=Qe(T.map(qe=>f[qe].scores))??0;T=ut(f.map((qe,Wn)=>({idx:Wn,scores:qe.scores})),this.tieEpsilon).map(qe=>qe.idx);let je=Qe(T.map(qe=>f[qe].scores))??0;(T.length>xe||je>it+1e-6)&&(A=0),this.mergesDue-=1,this.totalMergesTested+=1,I.add(`${Math.min(_,$)}|${Math.max(_,$)}|${L}`)}continue}}let M=Gn(O,N,()=>this.rand());this.lastIterFoundNewProgram=!1;let D=this.minibatch?this.nextMinibatchIndices(p.length,v).map(z=>p[z]):p;if(r?.skipPerfectScore??!0){let z=Number(r?.perfectScore??1),W=await b(f[M].cfg,D);if(W.length>0&&W.every(G=>G>=z))continue}let F=!1,q={...f[M].cfg},Y="reflective_mutation",oe=v%a.length,U=a[oe],ae,ne;if(F&&this.mergesUsed<this.mergeMax){let z=(M+1)%f.length,W=_=>{let $=[],L=_;for(;L!==void 0;)$.push(L),L=f[L]?.parent;return $},G=W(M),B=W(z),K=G.find(_=>B.includes(_)),X=!0;if(K||(X=!1),(B.includes(M)||G.includes(z))&&(X=!1),X){let _=f[K].cfg,$=f[M].cfg,L=f[z].cfg,H=!1,ee=new Set([...Object.keys(_),...Object.keys($),...Object.keys(L)]);for(let me of ee){let te=_[me],se=$[me],le=L[me];if(se===te&&le!==se||le===te&&se!==le){H=!0;break}}H||(X=!1)}if(X){let _=Math.min(M,z),$=Math.max(M,z),L=`${_}|${$}|${K}`;if(!I.has(L)){let H=y(f[K].scores),ee=y(f[M].scores),me=y(f[z].scores);H<=Math.min(ee,me)&&(q=this.systemAwareMerge(f,M,z,(te,se)=>{let le=y(f[te].scores),pe=y(f[se].scores);return le>=pe?te:se}),Y="system_merge",this.mergesUsed+=1,I.add(L))}}else{let _=f[M].cfg[U.name],$=r?.gepaAdapter,L;if($)try{let H=await $.evaluate(D,{...f[M].cfg},!0);ae=Array.isArray(H?.scores)?H.scores.reduce((se,le)=>se+(Number(le)||0),0):void 0;let ee=$.make_reflective_dataset({...f[M].cfg},H,[U.name]),te=(await $.propose_new_texts?.({...f[M].cfg},ee,[U.name]))?.[U.name];typeof te=="string"&&te.length>0&&(L=te)}catch{}if(L||(L=await this.reflectModuleInstruction(U.name,_,o,a,{...f[M].cfg},D,async({prediction:H,example:ee})=>{let me=await n({prediction:H,example:ee}),te=Object.values(me||{});return te.length?te.reduce((se,le)=>se+le,0)/te.length:0},r)),q[U.name]=L,$&&ae!==void 0)try{let H=await $.evaluate(D,q,!1);ne=Array.isArray(H?.scores)?H.scores.reduce((ee,me)=>ee+(Number(me)||0),0):void 0}catch{}}}else{let z=f[M].cfg[U.name],W=r?.gepaAdapter,G;if(W)try{let B=await W.evaluate(D,{...f[M].cfg},!0);ae=Array.isArray(B?.scores)?B.scores.reduce(($,L)=>$+(Number(L)||0),0):void 0;let K=W.make_reflective_dataset({...f[M].cfg},B,[U.name]),_=(await W.propose_new_texts?.({...f[M].cfg},K,[U.name]))?.[U.name];typeof _=="string"&&_.length>0&&(G=_)}catch{}if(G||(G=await this.reflectModuleInstruction(U.name,z,o,a,{...f[M].cfg},D,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)),q[U.name]=G,W&&ae!==void 0)try{let B=await W.evaluate(D,q,!1);ne=Array.isArray(B?.scores)?B.scores.reduce((K,X)=>K+(Number(X)||0),0):void 0}catch{}}let Re=await b(f[M].cfg,D),ot=await b(q,D),ht=Re.reduce((z,W)=>z+W,0),De=ot.reduce((z,W)=>z+W,0);if(this.currentRound=v+1,await this.updateOptimizationProgress(this.currentRound,De,{modules:a.length,mutatedModule:U.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:Y,paretoSetSize:u.length},De,{idx:M},{...r??{},maxIterations:this.numTrials}),!(De>ht+this.tieEpsilon&&(ae===void 0||ne===void 0||ne>ae+this.tieEpsilon))){if(++A>=this.earlyStoppingTrials)break;continue}let ye=await h(q,u);f.push({cfg:q,parent:M,scores:ye}),x.push(await b(q,u));let he=T.length,we=Qe(T.map(z=>f[z].scores))??0;T=ut(f.map((z,W)=>({idx:W,scores:z.scores})),this.tieEpsilon).map(z=>z.idx);let be=Qe(T.map(z=>f[z].scores))??0;if(T.length>he||be>we+1e-6)A=0;else if(A++,A>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=ut(f.map((v,k)=>({idx:k,scores:v.scores})),this.tieEpsilon),P=R.length>0?Math.max(...R.map(v=>y(v.scores))):0,E=Qe(R.map(v=>v.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);return this.recordParetoMetrics(R.length,f.length,"GEPA-Flow",E,w),{demos:[],stats:this.stats,bestScore:P,paretoFront:R.map(v=>({demos:[],scores:v.scores,configuration:{candidate:v.idx},dominatedSolutions:v.dominated})),paretoFrontSize:R.length,hypervolume:E,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let s=[];for(let o of n){let a=await this.evaluateOne(e,t,o,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?Ft(s):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let o=await r({prediction:s,example:n});return typeof o=="number"&&!Number.isNaN(o)?((typeof this.targetScore=="number"?o>=this.targetScore:o>=.5)&&(this.stats.successfulDemos+=1),o):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,s,o,a,l){let c=[],u=[];for(let y of o)try{s[e]=t,n.setAllNodeInstructions?.(s);let x=await n.forward(this.studentAI,y,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:y});u.push({input:y,prediction:x,score:typeof b=="number"?b:0})}catch{u.push({input:y,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=Ge('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],h=l?.feedbackFn;if(typeof h=="function")for(let y of u){let x=h({prediction:y.prediction,example:y.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let g="";try{g=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=Ge('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 x=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:g,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}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,s=r===0?0:n-r,o=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<s;l++){let c=o[l%o.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)),s=Math.floor(t/r);for(;s>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let o=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(o,o+n)}systemAwareMergeWithSig(e,t,n,r){let s=f=>{let y=[],x=f;for(;x!==void 0;)y.push(x),x=e[x]?.parent;return y},o=s(t),a=s(n),c=o.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},h=[],g=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of g){let y=u[f],x=p[f],b=d[f];if(x===y&&b!==x)m[f]=b,h.push("j");else if(b===y&&x!==b)m[f]=x,h.push("i");else if(x!==b&&x!==y&&b!==y){let T=r(t,n);m[f]=T===t?x:b,h.push(T===t?"i":"j")}else m[f]=x??b??y,h.push("i")}return{cfg:m,descSig:h.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 s=g=>{let f=[],y=g;for(;y!==void 0;)f.push(y),y=e[y]?.parent;return f},o=s(t),a=s(n),c=o.find(g=>a.includes(g))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},h=new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)]);for(let g of h){let f=u[g],y=p[g],x=d[g];if(y===f&&x!==y)m[g]=x;else if(x===f&&y!==x)m[g]=y;else if(y!==x&&y!==f&&x!==f){let b=r(t,n);m[g]=b===t?y:x}else m[g]=y??x??f}return m}};var Jr=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 s=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(s.status))return s;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${s.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 s=0;s<this.retryAttempts;s++)try{let o=new AbortController,a=setTimeout(()=>o.abort(),this.timeout),l=await fetch(n,{...t,signal:o.signal});return clearTimeout(a),l}catch(o){r=o,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${s+1} failed: ${o}`}),s<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,s))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var No=class extends ze{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 Jr(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let s=e.results.findIndex(o=>!o.isError);return s>=0?s:0}let t=new Map;for(let s of e.results){let o=JSON.stringify(s.sample??{}),a=t.get(o);a?a.count+=1:t.set(o,{count:1,firstIndex:s.index})}let n="",r={count:-1,firstIndex:0};for(let[s,o]of t.entries())o.count>r.count&&(r=o,n=s);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=`
518
+ `)}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 s=[],o=new Set(e.map(u=>u.bulletId).filter(u=>typeof u=="string")),a=new Map,l=(u,p)=>{if(o.has(u))return;let d=this.locateBullet(t,u);if(!d)return;let m=a.get(d.section)??{harmful:[],primary:[],generator:[]};m[p].push(d.id),a.set(d.section,m)};for(let u of n?.bulletTags??[]){let p=u.tag==="harmful"?"harmful":"primary";l(u.id,p)}if(r?.bulletIds)for(let u of r.bulletIds)l(u,"generator");let c=u=>{let p=a.get(u);if(!p)return this.locateFallbackBullet(t,u,o);let d=h=>{for(;h.length>0;){let g=h.shift();if(!o.has(g))return g}},m=d(p.harmful)??d(p.primary)??d(p.generator);return m||this.locateFallbackBullet(t,u,o)};for(let u of e){if((u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId){let p=c(u.section);p&&(u.bulletId=p,o.add(p))}(u.type==="UPDATE"||u.type==="REMOVE")&&!u.bulletId||s.push(u)}return s}locateBullet(e,t){for(let n of Object.values(e.sections)){let r=n.find(s=>s.id===t);if(r)return r}}locateFallbackBullet(e,t,n){let r=e.sections[t]??[];for(let s of r)if(!n.has(s.id))return s.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 s=r.type??"ADD",o=typeof s=="string"?s.toUpperCase():"ADD",a=o==="UPDATE"?"UPDATE":o==="REMOVE"?"REMOVE":"ADD",l=r.section??"Guidelines",c=typeof l=="string"&&l.trim().length>0?l.trim():"Guidelines",u=r.content??"",p=typeof u=="string"?u.trim():"";if(a!=="REMOVE"&&p.length===0)continue;let d=r.bulletId??r.id,m=typeof d=="string"&&d.trim().length>0?d.trim():void 0,g=[a,c,p,m??""].join(":");if(n.has(g))continue;n.add(g);let f={type:a,section:c};a!=="REMOVE"&&(f.content=p),m&&(f.bulletId=m);let y=r.metadata;y&&typeof y=="object"&&(f.metadata={...y}),t.push(f)}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=(s,o)=>{if(!o)return;let a=o.trim();if(!a||a.toLowerCase().startsWith("no error"))return;let c=`${s}:${a}`;n.has(c)||(n.add(c),t.push({type:"ADD",section:s,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),s;for(let o=0;o<r;o++){let a=await this.runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:s});if(!a)break;s=a;let l=a.errorIdentification?.toLowerCase().trim()??"";if(a.metadata?.resolved===!0||l.length===0||l.startsWith("no error")||l.startsWith("resolved"))break}return s}async runReflector({example:e,generatorOutput:t,feedback:n,previousReflection:r}){let s=this.getOrCreateReflectorProgram(),o=this.teacherAI??this.studentAI;try{let a={severity:e?.severity,policyHint:e?.policyHint},u=(this.program?.getSignature()?.getInputFields()??[]).reduce((d,m)=>(m.name in e&&(d[m.name]=e[m.name]),d),{});return await s.forward(o,{question:JSON.stringify(u),generator_answer:JSON.stringify(t.answer),generator_reasoning:t.reasoning,playbook:JSON.stringify({markdown:jn(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({program:e,example:t,reflection:n,playbook:r}){if(!n)return;let s=this.getOrCreateCuratorProgram(),o=this.teacherAI??this.studentAI,c=e.getSignature().getInputFields().reduce((u,p)=>(p.name in t&&(u[p.name]=t[p.name]),u),{});try{return await s.forward(o,{playbook:JSON.stringify({markdown:jn(r),structured:r}),reflection:JSON.stringify(n),question_context:JSON.stringify(c),token_budget:1024})}catch(u){this.verbose&&console.warn("[AxACE] Curator error:",u instanceof Error?u.message:u);return}}getOrCreateReflectorProgram(){if(!this.reflectorProgram){let e=ue().input("question",ue.string("Original task input serialized as JSON")).input("generator_answer",ue.string("Generator output serialized as JSON")).input("generator_reasoning",ue.string("Generator reasoning trace").optional()).input("playbook",ue.string("Current context playbook rendered as markdown")).input("expected_answer",ue.string("Expected output when ground truth is available").optional()).input("feedback",ue.string("External feedback or reward signal").optional()).input("previous_reflection",ue.string("Most recent reflection JSON when running multi-round refinement").optional()).output("reasoning",ue.string("Step-by-step analysis of generator performance")).output("errorIdentification",ue.string("Specific mistakes detected")).output("rootCauseAnalysis",ue.string("Underlying cause of the error")).output("correctApproach",ue.string("What the generator should do differently")).output("keyInsight",ue.string("Reusable insight to remember")).output("bulletTags",ue.json("Array of {id, tag} entries referencing playbook bullets")).build();this.reflectorProgram=Ge(e)}return this.reflectorProgram}getOrCreateCuratorProgram(){if(!this.curatorProgram){let e=ue().input("playbook",ue.string("Current playbook serialized as JSON")).input("reflection",ue.string("Latest reflection output serialized as JSON")).input("question_context",ue.string("Original task input serialized as JSON")).input("token_budget",ue.number("Approximate token budget for curator response").optional()).output("reasoning",ue.string("Justification for the proposed updates")).output("operations",ue.json("List of operations with type/section/content fields")).build();this.curatorProgram=Ge(e)}return this.curatorProgram}};var qn=class extends ze{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,s){let o=Date.now(),a=s?.maxDemos??this.maxDemos,l={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(l.modelConfig.max_tokens=this.maxTokensPerGeneration);let c=Mu([...t],this.maxExamples),u=this.traces.length;for(let p=0;p<c.length;p+=this.batchSize){p>0&&(l.modelConfig.temperature=.7+.001*p);let d=c.slice(p,p+this.batchSize);for(let m of d){if(!m||typeof m!="object")continue;let h=t.filter(y=>y!==m);e.setExamples(h);let g=this.getTeacherOrStudentAI();this.stats.totalCalls++;let f;try{let y={...l,maxRetries:1};f=await e.forward(g,m,y),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(m).length/4+JSON.stringify(f).length/4),await r({prediction:f,example:m})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(y){(this.verboseMode||this.debugMode)&&console.warn(`Student model failed during bootstrap: ${y instanceof Error?y.message:"Unknown error"}`),f={}}if(this.traces.length>=a)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-u;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 s=r?.maxIterations??this.maxRounds;this.traces=[],this.reset();for(let l=0;l<s&&(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 o=Ou(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:o.length,tracesCollected:this.traces.length},r),{demos:o,stats:this.stats,bestScore:a,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:a}}}};function Ou(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 Mu=(i,e)=>{let t=[...i];for(let n=t.length-1;n>0;n--){let r=Math.floor(Math.random()*(n+1)),s=t[n],o=t[r];if(!s||!o)throw new Error("Invalid array elements");[t[n],t[r]]=[o,s]}return t.slice(0,e)};var No=class extends ze{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 s=e?.mergeMax;this.mergeMax=Math.max(0,Math.floor(s??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 s=Date.now(),o=e;this.validateExamples(t),r?.auto&&this.configureAuto(r.auto);let a=o.getNodePrograms?.();if(!a||a.length===0)throw new Error("AxGEPAFlow: flow has no nodes to optimize");let l=r?.validationExamples,c=r?.feedbackExamples,u=(l&&l.length>0?l:t).slice(0,this.paretoSetSize),p=c&&c.length>0?c:t;this.getOptimizerLogger(r)?.({name:"OptimizationStart",value:{optimizerType:"GEPA-Flow",exampleCount:t.length,validationCount:u.length,config:{numTrials:this.numTrials,minibatch:this.minibatch}}});let m=async(v,k)=>{try{o.setAllNodeInstructions?.(v);let O=await o.forward(this.studentAI,k,{sampleCount:this.sampleCount});return this.stats.totalCalls+=1,await n({prediction:O,example:k})||{}}catch{return{}}},h=async(v,k)=>{let O=[];for(let N of k)O.push(await m(v,N));return Vr(O)},g={};for(let v of a)g[v.name]=await this.getBaseInstruction(v.program);let f=[{cfg:{...g},parent:void 0,scores:await h(g,u)}],y=v=>{let k=r?.paretoMetricKey,O=r?.paretoScalarize;if(typeof O=="function")return O(v);if(k)return Number.isFinite(v[k])?v[k]:0;let N=Object.values(v);return N.length?N.reduce((M,D)=>M+D,0)/N.length:0},x=[],b=async(v,k)=>{let O=[];for(let N of k){let M=await m(v,N);O.push(y(M))}return O};x.push(await b(g,u));let T=ut(f.map((v,k)=>({idx:k,scores:v.scores})),this.tieEpsilon).map(v=>v.idx),A=0,I=new Set,C=r?.maxMetricCalls;if(!Number.isFinite(C)||C<=0)throw new Error("AxGEPA-Flow: options.maxMetricCalls must be set to a positive integer");let S=Math.floor(C);for(let v=0;v<this.numTrials&&!(S!==void 0&&this.stats.totalCalls>=Math.max(1,Math.floor(S)));v++){let k=x[0]?.length??0,O=[];for(let z=0;z<k;z++){let W=Number.NEGATIVE_INFINITY,G=new Set;for(let B=0;B<x.length;B++){let K=x[B][z];K>W+this.tieEpsilon?(W=K,G.clear(),G.add(B)):Math.abs(K-W)<=this.tieEpsilon&&G.add(B)}O.push(G)}let N=x.map(z=>_t(z));if(this.mergeMax>0&&this.mergesDue>0&&this.lastIterFoundNewProgram){let z=Gn(O,N),W=new Set;for(let _ of z)for(let $ of _)W.add($);let G=Array.from(W),B=_=>{let $=[],L=_;for(;L!==void 0;)$.push(L),L=f[L]?.parent;return $},K=_=>_.length?_[Math.floor(this.rand()*_.length)]:void 0,X;for(let _=0;_<10&&!X&&!(G.length<2);_++){let $=K(G),L=K(G);if($===L)continue;L<$&&([$,L]=[L,$]);let H=new Set(B($)),ee=new Set(B(L));if(H.has(L)||ee.has($))continue;let me=[...H].filter(de=>ee.has(de));if(me.length===0)continue;let te=[];for(let de of me){let pt=f[de].cfg,ft=f[$].cfg,Ye=f[L].cfg,xt=!1,At=new Set([...Object.keys(pt),...Object.keys(ft),...Object.keys(Ye)]);for(let dt of At){let yt=pt[dt],Rt=ft[dt],J=Ye[dt];if(Rt===yt&&J!==Rt||J===yt&&Rt!==J){xt=!0;break}}xt&&te.push(de)}if(te.length===0)continue;let se=te.map(de=>Math.max(1e-9,N[de])),le=this.rand()*se.reduce((de,pt)=>de+pt,0),pe=te[te.length-1];for(let de=0;de<te.length;de++){if(le<se[de]){pe=te[de];break}le-=se[de]}let Te=N[pe],ve=N[$],He=N[L];if(Te>Math.min(ve,He))continue;let Fe=`${$}|${L}|${pe}`;if(this.mergeAttemptKeys.has(Fe))continue;this.mergeAttemptKeys.add(Fe);let Be=`${$}|${L}|${pe}`;I.has(Be)||(X={i:$,j:L,a:pe})}if(this.lastIterFoundNewProgram=!1,X){let{i:_,j:$,a:L}=X,{cfg:H,descSig:ee}=this.systemAwareMergeWithSig(f,_,$,(J,xe)=>N[J]>=N[xe]?J:xe),me=`${Math.min(_,$)}|${Math.max(_,$)}|${ee}`;if(this.mergeCompositionKeys.has(me))continue;this.mergeCompositionKeys.add(me);let te=x[_],se=x[$],le=Array.from({length:te.length},(J,xe)=>xe),pe=le.filter(J=>(te[J]??0)>(se[J]??0)),Te=le.filter(J=>(se[J]??0)>(te[J]??0)),ve=le.filter(J=>!(pe.includes(J)||Te.includes(J))),He=5,Fe=Math.ceil(He/3),Be=(J,xe)=>{if(xe<=0||J.length===0)return[];if(J.length<=xe)return[...J];let it=[],je=new Set;for(;it.length<xe;){let qe=Math.floor(this.rand()*J.length);je.has(qe)||(je.add(qe),it.push(J[qe]))}return it},de=[];de.push(...Be(pe,Math.min(Fe,pe.length))),de.push(...Be(Te,Math.min(Fe,Te.length)));let pt=He-de.length;de.push(...Be(ve,Math.max(0,pt)));let ft=He-de.length;if(ft>0){let J=le.filter(xe=>!de.includes(xe));de.push(...Be(J,Math.min(ft,J.length)))}let Ye=de.slice(0,Math.min(He,le.length)),xt=Ye.map(J=>u[J]),dt=(await b(H,xt)).reduce((J,xe)=>J+xe,0),yt=Ye.reduce((J,xe)=>J+(te[xe]??0),0),Rt=Ye.reduce((J,xe)=>J+(se[xe]??0),0);if(dt>=Math.max(yt,Rt)+this.tieEpsilon){let J=await h(H,u);f.push({cfg:H,parent:L,scores:J}),x.push(await b(H,u));let xe=T.length,it=Qe(T.map(qe=>f[qe].scores))??0;T=ut(f.map((qe,Vn)=>({idx:Vn,scores:qe.scores})),this.tieEpsilon).map(qe=>qe.idx);let je=Qe(T.map(qe=>f[qe].scores))??0;(T.length>xe||je>it+1e-6)&&(A=0),this.mergesDue-=1,this.totalMergesTested+=1,I.add(`${Math.min(_,$)}|${Math.max(_,$)}|${L}`)}continue}}let M=Dn(O,N,()=>this.rand());this.lastIterFoundNewProgram=!1;let D=this.minibatch?this.nextMinibatchIndices(p.length,v).map(z=>p[z]):p;if(r?.skipPerfectScore??!0){let z=Number(r?.perfectScore??1),W=await b(f[M].cfg,D);if(W.length>0&&W.every(G=>G>=z))continue}let F=!1,q={...f[M].cfg},Y="reflective_mutation",oe=v%a.length,U=a[oe],ae,ne;if(F&&this.mergesUsed<this.mergeMax){let z=(M+1)%f.length,W=_=>{let $=[],L=_;for(;L!==void 0;)$.push(L),L=f[L]?.parent;return $},G=W(M),B=W(z),K=G.find(_=>B.includes(_)),X=!0;if(K||(X=!1),(B.includes(M)||G.includes(z))&&(X=!1),X){let _=f[K].cfg,$=f[M].cfg,L=f[z].cfg,H=!1,ee=new Set([...Object.keys(_),...Object.keys($),...Object.keys(L)]);for(let me of ee){let te=_[me],se=$[me],le=L[me];if(se===te&&le!==se||le===te&&se!==le){H=!0;break}}H||(X=!1)}if(X){let _=Math.min(M,z),$=Math.max(M,z),L=`${_}|${$}|${K}`;if(!I.has(L)){let H=y(f[K].scores),ee=y(f[M].scores),me=y(f[z].scores);H<=Math.min(ee,me)&&(q=this.systemAwareMerge(f,M,z,(te,se)=>{let le=y(f[te].scores),pe=y(f[se].scores);return le>=pe?te:se}),Y="system_merge",this.mergesUsed+=1,I.add(L))}}else{let _=f[M].cfg[U.name],$=r?.gepaAdapter,L;if($)try{let H=await $.evaluate(D,{...f[M].cfg},!0);ae=Array.isArray(H?.scores)?H.scores.reduce((se,le)=>se+(Number(le)||0),0):void 0;let ee=$.make_reflective_dataset({...f[M].cfg},H,[U.name]),te=(await $.propose_new_texts?.({...f[M].cfg},ee,[U.name]))?.[U.name];typeof te=="string"&&te.length>0&&(L=te)}catch{}if(L||(L=await this.reflectModuleInstruction(U.name,_,o,a,{...f[M].cfg},D,async({prediction:H,example:ee})=>{let me=await n({prediction:H,example:ee}),te=Object.values(me||{});return te.length?te.reduce((se,le)=>se+le,0)/te.length:0},r)),q[U.name]=L,$&&ae!==void 0)try{let H=await $.evaluate(D,q,!1);ne=Array.isArray(H?.scores)?H.scores.reduce((ee,me)=>ee+(Number(me)||0),0):void 0}catch{}}}else{let z=f[M].cfg[U.name],W=r?.gepaAdapter,G;if(W)try{let B=await W.evaluate(D,{...f[M].cfg},!0);ae=Array.isArray(B?.scores)?B.scores.reduce(($,L)=>$+(Number(L)||0),0):void 0;let K=W.make_reflective_dataset({...f[M].cfg},B,[U.name]),_=(await W.propose_new_texts?.({...f[M].cfg},K,[U.name]))?.[U.name];typeof _=="string"&&_.length>0&&(G=_)}catch{}if(G||(G=await this.reflectModuleInstruction(U.name,z,o,a,{...f[M].cfg},D,async({prediction:B,example:K})=>{let X=await n({prediction:B,example:K}),_=Object.values(X||{});return _.length?_.reduce(($,L)=>$+L,0)/_.length:0},r)),q[U.name]=G,W&&ae!==void 0)try{let B=await W.evaluate(D,q,!1);ne=Array.isArray(B?.scores)?B.scores.reduce((K,X)=>K+(Number(X)||0),0):void 0}catch{}}let Re=await b(f[M].cfg,D),ot=await b(q,D),ht=Re.reduce((z,W)=>z+W,0),De=ot.reduce((z,W)=>z+W,0);if(this.currentRound=v+1,await this.updateOptimizationProgress(this.currentRound,De,{modules:a.length,mutatedModule:U.name,totalRounds:this.numTrials},"GEPA-Flow",{strategy:Y,paretoSetSize:u.length},De,{idx:M},{...r??{},maxIterations:this.numTrials}),!(De>ht+this.tieEpsilon&&(ae===void 0||ne===void 0||ne>ae+this.tieEpsilon))){if(++A>=this.earlyStoppingTrials)break;continue}let ye=await h(q,u);f.push({cfg:q,parent:M,scores:ye}),x.push(await b(q,u));let he=T.length,we=Qe(T.map(z=>f[z].scores))??0;T=ut(f.map((z,W)=>({idx:W,scores:z.scores})),this.tieEpsilon).map(z=>z.idx);let be=Qe(T.map(z=>f[z].scores))??0;if(T.length>he||be>we+1e-6)A=0;else if(A++,A>=this.earlyStoppingTrials)break;this.lastIterFoundNewProgram=!0,this.mergeMax>0&&this.totalMergesTested<this.mergeMax&&(this.mergesDue+=1)}let R=ut(f.map((v,k)=>({idx:k,scores:v.scores})),this.tieEpsilon),P=R.length>0?Math.max(...R.map(v=>y(v.scores))):0,E=Qe(R.map(v=>v.scores));this.stats.convergenceInfo.converged=!0;let w=this.getMergedCustomLabels(r);return this.recordParetoMetrics(R.length,f.length,"GEPA-Flow",E,w),{demos:[],stats:this.stats,bestScore:P,paretoFront:R.map(v=>({demos:[],scores:v.scores,configuration:{candidate:v.idx},dominatedSolutions:v.dominated})),paretoFrontSize:R.length,hypervolume:E,finalConfiguration:{strategy:"gepa_flow_pareto",candidates:f.length}}}async getBaseInstruction(e){let t=e?.getInstruction?.();if(t&&t.length>0)return t;let r=e?.getSignature?.()?.getDescription?.();return r&&r.length>0?r:"Follow the task precisely. Be concise, correct, and consistent."}async evaluateOnSet(e,t,n,r){let s=[];for(let o of n){let a=await this.evaluateOne(e,t,o,r);s.push(a)}return s}async evaluateAvg(e,t,n,r){let s=await this.evaluateOnSet(e,t,n,r);return s.length>0?_t(s):0}async evaluateOne(e,t,n,r){try{e.setAllNodeInstructions?.(t);let s=await e.forward(this.studentAI,n,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let o=await r({prediction:s,example:n});return typeof o=="number"&&!Number.isNaN(o)?((typeof this.targetScore=="number"?o>=this.targetScore:o>=.5)&&(this.stats.successfulDemos+=1),o):0}catch{return 0}}async reflectModuleInstruction(e,t,n,r,s,o,a,l){let c=[],u=[];for(let y of o)try{s[e]=t,n.setAllNodeInstructions?.(s);let x=await n.forward(this.studentAI,y,{sampleCount:this.sampleCount});this.stats.totalCalls+=1;let b=await a({prediction:x,example:y});u.push({input:y,prediction:x,score:typeof b=="number"?b:0})}catch{u.push({input:y,prediction:{},score:0})}let p=l?.overrideTeacherAI??this.teacherAI??this.studentAI,d=Ge('moduleName:string "Target module", minibatch:json "Array of {input,prediction,score}", evalFeedback?:string[] "Evaluator feedback when available" -> feedbackSummary:string "Concise module-focused feedback"'),m=[],h=l?.feedbackFn;if(typeof h=="function")for(let y of u){let x=h({prediction:y.prediction,example:y.input});x&&(Array.isArray(x)?m.push(...x):m.push(x))}let g="";try{g=(await d.forward(p,{moduleName:e,minibatch:u,evalFeedback:m}))?.feedbackSummary?.trim()||""}catch{}let f=Ge('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 x=(await f.forward(p,{moduleName:e,currentInstruction:t,feedbackSummary:g,minibatch:u}))?.newInstruction?.trim();if(x&&x.length>16)return x}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,s=r===0?0:n-r,o=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<s;l++){let c=o[l%o.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)),s=Math.floor(t/r);for(;s>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let o=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(o,o+n)}systemAwareMergeWithSig(e,t,n,r){let s=f=>{let y=[],x=f;for(;x!==void 0;)y.push(x),x=e[x]?.parent;return y},o=s(t),a=s(n),c=o.find(f=>a.includes(f))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},h=[],g=Array.from(new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)])).sort();for(let f of g){let y=u[f],x=p[f],b=d[f];if(x===y&&b!==x)m[f]=b,h.push("j");else if(b===y&&x!==b)m[f]=x,h.push("i");else if(x!==b&&x!==y&&b!==y){let T=r(t,n);m[f]=T===t?x:b,h.push(T===t?"i":"j")}else m[f]=x??b??y,h.push("i")}return{cfg:m,descSig:h.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 s=g=>{let f=[],y=g;for(;y!==void 0;)f.push(y),y=e[y]?.parent;return f},o=s(t),a=s(n),c=o.find(g=>a.includes(g))??t,u=e[c].cfg,p=e[t].cfg,d=e[n].cfg,m={},h=new Set([...Object.keys(u),...Object.keys(p),...Object.keys(d)]);for(let g of h){let f=u[g],y=p[g],x=d[g];if(y===f&&x!==y)m[g]=x;else if(x===f&&y!==x)m[g]=y;else if(y!==x&&y!==f&&x!==f){let b=r(t,n);m[g]=b===t?y:x}else m[g]=y??x??f}return m}};var Qr=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 s=await this.getJobStatus(e);if(["completed","failed","cancelled"].includes(s.status))return s;this.logger?.({name:"Notification",id:"job_status",value:`Job ${e} status: ${s.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 s=0;s<this.retryAttempts;s++)try{let o=new AbortController,a=setTimeout(()=>o.abort(),this.timeout),l=await fetch(n,{...t,signal:o.signal});return clearTimeout(a),l}catch(o){r=o,this.logger?.({name:"Notification",id:"retry_attempt",value:`Attempt ${s+1} failed: ${o}`}),s<this.retryAttempts-1&&await this.sleep(this.retryDelay*Math.pow(2,s))}throw new Error(`Request failed after ${this.retryAttempts} attempts: ${r?.message}`)}sleep(e){return new Promise(t=>setTimeout(t,e))}};var Lo=class extends ze{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 Qr(t)}this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}defaultResultPicker=async e=>{if(e.type==="function"){let s=e.results.findIndex(o=>!o.isError);return s>=0?s:0}let t=new Map;for(let s of e.results){let o=JSON.stringify(s.sample??{}),a=t.get(o);a?a.count+=1:t.set(o,{count:1,firstIndex:s.index})}let n="",r={count:-1,firstIndex:0};for(let[s,o]of t.entries())o.count>r.count&&(r=o,n=s);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=`
519
519
  Analyze this language model program and provide a concise summary of its purpose and structure.
520
520
 
521
521
  Program Signature: ${e.getSignature()}
@@ -555,12 +555,12 @@ Requirements:
555
555
  5. Keep it concise but comprehensive
556
556
 
557
557
  Generate a single, well-crafted instruction:
558
- Instruction:`;try{let m=(await Ge('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:s??"",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."],u=c[t%c.length]||c[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let r=[],s=this.getTeacherOrStudentAI(t),o,a;this.programAwareProposer&&(o=await this.generateProgramSummary(e,s)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],s));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let u=l.length>0?c%l.length:-1,p=u>=0?l[u]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:s,programSummary:o,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new jn({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 s=e[r];s&&t.push(s)}}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 s=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 s=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let o=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:o},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...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},c=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,h=0;for(let A=0;A<this.numTrials;A++)try{let I=await this.pythonClient.suggestParameters(a),C=I.params.temperature,S=I.params.bootstrappedDemos,R=I.params.instruction,P=I.params.labeledExamples,E=this.optimizeTopP?I.params.topP:void 0;if(C===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(I)}`);if(S===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(I)}`);if(R===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(I)}`);if(P===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(I)}`);let w=e.clone();w.setInstruction(R),w.setExamples(this.selectLabeledExamples(t).slice(0,P));let k=!this.minibatch||this.minibatchFullEvalSteps>0&&A%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let M=Math.min(this.minibatchSize,t.length),D=new Set;for(;D.size<M;)D.add(Math.floor(Math.random()*t.length));return Array.from(D).map(F=>t[F])})(),O=await this.evaluateConfiguration(w,n,{temperature:C,bootstrappedDemos:S,topP:E},k);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:I.trial_number,value:O}),O>p+this.minImprovementThreshold?(p=O,d={temperature:C,bootstrappedDemos:S,...E!==void 0?{topP:E}:{},trialNumber:I.trial_number},h=0):h+=1,this.currentRound=A+1;let N={temperature:C,bootstrappedDemos:S,...E!==void 0?{topP:E}:{},trialNumber:I.trial_number};if(this.localScoreHistory.push(O),this.localConfigurationHistory.push(N),await this.updateOptimizationProgress(this.currentRound,O,N,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:A+1,totalRounds:this.numTrials,currentScore:O,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-s,successfulExamples:m,totalExamples:t.length}),this.earlyStoppingTrials>0&&h>=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={},y=[];try{let A=await this.pythonClient.getStudyResults(a);if(g=A.best_value||p,f=A.best_params||{},f&&Object.keys(f).length>0){let I=f.bootstrappedDemos||0;I>0&&(y=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),y=y.slice(0,I))}}catch{}let x;try{let I=await Ge('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:I.humanExplanation??"",recommendations:I.recommendations??[],performanceAssessment:I.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,f,r,x);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=g;let b=new Ae(e.getSignature());f.instruction&&b.setInstruction(f.instruction),y.length>0&&b.setDemos(y),f.temperature&&(b._optimizedModelConfig={temperature:f.temperature});let T=new gt({bestScore:g,stats:this.stats,instruction:f.instruction,demos:y,examples:[],modelConfig:{temperature:f.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-s,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(g,y.length),{bestScore:g,demos:y,stats:this.stats,optimizedGen:b,optimizedProgram:T,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
558
+ Instruction:`;try{let m=(await Ge('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:s??"",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."],u=c[t%c.length]||c[0];return e&&(u=`${u} ${e}`),u}async proposeInstructionCandidates(e,t,n=[]){let r=[],s=this.getTeacherOrStudentAI(t),o,a;this.programAwareProposer&&(o=await this.generateProgramSummary(e,s)),this.dataAwareProposer&&(a=await this.generateDatasetSummary([...n],s));let l=this.tipAwareProposer?this.generateTips():[];for(let c=0;c<this.numCandidates;c++){let u=l.length>0?c%l.length:-1,p=u>=0?l[u]:void 0,d=await this.generateInstruction({tip:p,candidateIndex:c,ai:s,programSummary:o,datasetSummary:a,previousInstructions:r});r.push(d)}return r}async bootstrapFewShotExamples(e,t,n){return(await new qn({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 s=e[r];s&&t.push(s)}}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 s=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 s=Date.now();this.localScoreHistory=[],this.localConfigurationHistory=[];let o=await this.proposeInstructionCandidates(e,r,t),a=`mipro_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,l={study_name:a,parameters:[{name:"temperature",type:"float",low:.1,high:2},{name:"bootstrappedDemos",type:"int",low:0,high:this.maxBootstrappedDemos},{name:"instruction",type:"categorical",choices:o},{name:"labeledExamples",type:"int",low:0,high:this.maxLabeledDemos},...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},c=await this.pythonClient.createOptimizationJob(l);this.getOptimizerLogger()?.({name:"OptimizationStart",value:{optimizerType:"MiPRO (Python)",exampleCount:t.length,validationCount:0,config:{jobId:c.job_id,numTrials:this.numTrials}}});let p=Number.NEGATIVE_INFINITY,d,m=0,h=0;for(let A=0;A<this.numTrials;A++)try{let I=await this.pythonClient.suggestParameters(a),C=I.params.temperature,S=I.params.bootstrappedDemos,R=I.params.instruction,P=I.params.labeledExamples,E=this.optimizeTopP?I.params.topP:void 0;if(C===void 0)throw new Error(`Missing temperature parameter in suggestion: ${JSON.stringify(I)}`);if(S===void 0)throw new Error(`Missing bootstrappedDemos parameter in suggestion: ${JSON.stringify(I)}`);if(R===void 0)throw new Error(`Missing instruction parameter in suggestion: ${JSON.stringify(I)}`);if(P===void 0)throw new Error(`Missing labeledExamples parameter in suggestion: ${JSON.stringify(I)}`);let w=e.clone();w.setInstruction(R),w.setExamples(this.selectLabeledExamples(t).slice(0,P));let k=!this.minibatch||this.minibatchFullEvalSteps>0&&A%this.minibatchFullEvalSteps===this.minibatchFullEvalSteps-1?[...t]:(()=>{let M=Math.min(this.minibatchSize,t.length),D=new Set;for(;D.size<M;)D.add(Math.floor(Math.random()*t.length));return Array.from(D).map(F=>t[F])})(),O=await this.evaluateConfiguration(w,n,{temperature:C,bootstrappedDemos:S,topP:E},k);m++,await this.pythonClient.evaluateTrial({study_name:a,trial_number:I.trial_number,value:O}),O>p+this.minImprovementThreshold?(p=O,d={temperature:C,bootstrappedDemos:S,...E!==void 0?{topP:E}:{},trialNumber:I.trial_number},h=0):h+=1,this.currentRound=A+1;let N={temperature:C,bootstrappedDemos:S,...E!==void 0?{topP:E}:{},trialNumber:I.trial_number};if(this.localScoreHistory.push(O),this.localConfigurationHistory.push(N),await this.updateOptimizationProgress(this.currentRound,O,N,"MiPRO (Python)",{sampler:"TPESampler"},p,d),this.onProgress?.({round:A+1,totalRounds:this.numTrials,currentScore:O,bestScore:p,tokensUsed:this.stats.estimatedTokenUsage,timeElapsed:Date.now()-s,successfulExamples:m,totalExamples:t.length}),this.earlyStoppingTrials>0&&h>=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={},y=[];try{let A=await this.pythonClient.getStudyResults(a);if(g=A.best_value||p,f=A.best_params||{},f&&Object.keys(f).length>0){let I=f.bootstrappedDemos||0;I>0&&(y=await this.bootstrapFewShotExamples(e,n,t.slice(0,Math.floor(t.length*.8))),y=y.slice(0,I))}}catch{}let x;try{let I=await Ge('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:I.humanExplanation??"",recommendations:I.recommendations??[],performanceAssessment:I.performanceAssessment??""}}catch{}await this.logOptimizationComplete("MiPRO (Python)",g,f,r,x);try{await this.pythonClient.deleteStudy(a)}catch{}this.stats.bestScore=g;let b=new Ae(e.getSignature());f.instruction&&b.setInstruction(f.instruction),y.length>0&&b.setDemos(y),f.temperature&&(b._optimizedModelConfig={temperature:f.temperature});let T=new gt({bestScore:g,stats:this.stats,instruction:f.instruction,demos:y,examples:[],modelConfig:{temperature:f.temperature},optimizerType:"MiPRO (Python)",optimizationTime:Date.now()-s,totalRounds:this.numTrials,converged:this.stats.convergenceInfo.converged,scoreHistory:[...this.localScoreHistory],configurationHistory:[...this.localConfigurationHistory]});return this.generateOptimizationReport(g,y.length),{bestScore:g,demos:y,stats:this.stats,optimizedGen:b,optimizedProgram:T,finalConfiguration:{temperature:f.temperature,bootstrappedDemos:f.bootstrappedDemos||0,...f}}}generateOptimizationReport(e,t){console.log(`
559
559
  \u{1F389} MiPRO Optimization Complete!
560
560
  `),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
561
561
  `),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
562
562
  `),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
563
- `),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 s=0,o=0,a=0,l=r;for(let c of l)try{let u=await e.forward(this.studentAI,c,{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 p=await t({prediction:u,example:c});if(typeof p=="number"&&!Number.isNaN(p)){s+=p,o++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(u){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof u=="string"?u:String(u)})}return this.stats.successfulDemos+=a,o>0?s/o:0}};var qn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),s=Array.from(r.matchAll(/state\.(\w+)/g));for(let o of s)o[1]&&!n.includes(o[1])&&n.push(o[1]);if(n.length===0)try{let o=this.createDependencyTracker(n);e(o)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,s){typeof s=="string"&&!t.includes(s)&&t.push(s);let o=r[s];return o&&typeof o=="object"?n.createTrackingProxy(o,t):o},has(r,s){return typeof s=="string"&&!t.includes(s)&&t.push(s),s in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let o of n)o[1]&&!t.includes(o[1])&&t.push(o[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let o of r)o[1]&&!t.includes(o[1])&&t.push(o[1]);let s=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let o of s)for(let a=1;a<o.length;a++)o[a]&&!t.includes(o[a])&&t.push(o[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 Kt(i,e,t){if(!t||t<=0||t>=i.length){let r=i.map((s,o)=>e(s,o));return Promise.all(r)}let n=new Array(i.length);for(let r=0;r<i.length;r+=t){let o=i.slice(r,r+t).map((l,c)=>{let u=r+c;return e(l,u).then(p=>({result:p,originalIndex:u}))}),a=await Promise.all(o);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var zn=class{steps=[];parallelGroups=[];analyzer=new qn;initialFields=new Set;addExecutionStep(e,t,n,r,s,o,a){let l=[],c=[],u=r||"map";if(t&&n)u="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(u==="map"&&s)c=this.analyzeMapTransformation(s),l=this.getAllProducedFields();else if(u==="parallel-map"){if(Array.isArray(s)){let d=new Set;for(let m of s)this.analyzeMapTransformation(m).forEach(g=>d.add(g));c=Array.from(d)}else s?c=this.analyzeMapTransformation(s):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(u==="merge"){if(o?.resultKey)c=[o.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(u==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(u==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=s?this.analyzer.analyzeMappingDependencies(s,"derive"):[];l=[a.inputFieldName,...d].filter((m,h,g)=>g.indexOf(m)===h)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(u="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 p={type:u,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(p)}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),s=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(s&&typeof s=="object"&&"then"in s)return this.analyzeStepFunctionSource(e);if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Object.keys(s).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 s=n.map(o=>{let a=o.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}let r=t.match(/state\.(\w+)\s*=/g);if(r){let s=r.map(o=>{let a=o.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}}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 s of this.steps){if(e.has(s.stepIndex))continue;if(s.dependencies.length===0||s.dependencies.every(a=>t.has(a))){if(s.type==="merge"&&r.length>0)continue;if(r.push(s),e.add(s.stepIndex),s.type==="merge")break}}if(r.length>0){for(let s of r)s.produces.forEach(o=>t.add(o));this.parallelGroups.push({level:n,steps:r}),n++}else{let s=this.steps.filter(o=>!e.has(o.stepIndex));if(s.length>0){let o=s[0];e.add(o.stepIndex),o.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[o]}),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(s,o)=>{let a=await Kt(n.steps,async u=>await u.stepFunction(s,o),e);if(a.some(u=>u&&typeof u=="object"&&"_parallelResults"in u)){let u=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return u||s}let c=s;for(let u of a)c={...c,...u};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 Eu,SpanKind as Fu,trace as _u}from"@opentelemetry/api";var Xa=i=>{console.log(i)},Wt=(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 s=JSON.stringify(r);s.length>200?t[n]=`${s.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},Vt=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,Qr=(i=Xa)=>{let e=new $e,t=e.gray(`${"\u2501".repeat(80)}
563
+ `),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 s=0,o=0,a=0,l=r;for(let c of l)try{let u=await e.forward(this.studentAI,c,{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 p=await t({prediction:u,example:c});if(typeof p=="number"&&!Number.isNaN(p)){s+=p,o++;let d=typeof this.targetScore=="number"?this.targetScore:.5;p>=d&&a++}}catch(u){this.getLogger()?.({name:"Notification",id:"mipro_evaluate",value:typeof u=="string"?u:String(u)})}return this.stats.successfulDemos+=a,o>0?s/o:0}};var zn=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let r=e.toString(),s=Array.from(r.matchAll(/state\.(\w+)/g));for(let o of s)o[1]&&!n.includes(o[1])&&n.push(o[1]);if(n.length===0)try{let o=this.createDependencyTracker(n);e(o)}catch{}}catch(r){console.debug("Dependency analysis failed:",r)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(r,s){typeof s=="string"&&!t.includes(s)&&t.push(s);let o=r[s];return o&&typeof o=="object"?n.createTrackingProxy(o,t):o},has(r,s){return typeof s=="string"&&!t.includes(s)&&t.push(s),s in r}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let o of n)o[1]&&!t.includes(o[1])&&t.push(o[1]);let r=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let o of r)o[1]&&!t.includes(o[1])&&t.push(o[1]);let s=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let o of s)for(let a=1;a<o.length;a++)o[a]&&!t.includes(o[a])&&t.push(o[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 Wt(i,e,t){if(!t||t<=0||t>=i.length){let r=i.map((s,o)=>e(s,o));return Promise.all(r)}let n=new Array(i.length);for(let r=0;r<i.length;r+=t){let o=i.slice(r,r+t).map((l,c)=>{let u=r+c;return e(l,u).then(p=>({result:p,originalIndex:u}))}),a=await Promise.all(o);for(let{result:l,originalIndex:c}of a)n[c]=l}return n}var Hn=class{steps=[];parallelGroups=[];analyzer=new zn;initialFields=new Set;addExecutionStep(e,t,n,r,s,o,a){let l=[],c=[],u=r||"map";if(t&&n)u="execute",l=this.analyzer.analyzeMappingDependencies(n,t),c=[`${t}Result`];else if(u==="map"&&s)c=this.analyzeMapTransformation(s),l=this.getAllProducedFields();else if(u==="parallel-map"){if(Array.isArray(s)){let d=new Set;for(let m of s)this.analyzeMapTransformation(m).forEach(g=>d.add(g));c=Array.from(d)}else s?c=this.analyzeMapTransformation(s):c=["_parallelMapResult"];l=this.getAllProducedFields()}else if(u==="merge"){if(o?.resultKey)c=[o.resultKey];else{let m=this.analyzeBranchMergeFields();c=m.length>0?m:["_mergedResult"]}e.toString().includes("_parallelResults")?l=["_parallelResults"]:l=this.getAllProducedFields()}else if(u==="parallel")c=["_parallelResults"],l=this.getAllProducedFields();else if(u==="derive")if(a?.outputFieldName&&a?.inputFieldName){c=[a.outputFieldName];let d=s?this.analyzer.analyzeMappingDependencies(s,"derive"):[];l=[a.inputFieldName,...d].filter((m,h,g)=>g.indexOf(m)===h)}else c=["_deriveResult"],l=this.getAllProducedFields();else e.toString().includes("transform(")?(u="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 p={type:u,nodeName:t,dependencies:l,produces:c,stepFunction:e,stepIndex:this.steps.length};this.steps.push(p)}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),s=e(t,{mainAi:{getOptions:()=>({trace:!1}),forward:()=>Promise.resolve({text:"mock"})},mainOptions:void 0});if(s&&typeof s=="object"&&"then"in s)return this.analyzeStepFunctionSource(e);if(s&&typeof s=="object"&&!Array.isArray(s)){let a=Object.keys(s).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 s=n.map(o=>{let a=o.match(/(\w+)\s*:/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}let r=t.match(/state\.(\w+)\s*=/g);if(r){let s=r.map(o=>{let a=o.match(/state\.(\w+)\s*=/);return a?a[1]:null}).filter(Boolean);if(s.length>0)return s}}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 s of this.steps){if(e.has(s.stepIndex))continue;if(s.dependencies.length===0||s.dependencies.every(a=>t.has(a))){if(s.type==="merge"&&r.length>0)continue;if(r.push(s),e.add(s.stepIndex),s.type==="merge")break}}if(r.length>0){for(let s of r)s.produces.forEach(o=>t.add(o));this.parallelGroups.push({level:n,steps:r}),n++}else{let s=this.steps.filter(o=>!e.has(o.stepIndex));if(s.length>0){let o=s[0];e.add(o.stepIndex),o.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[o]}),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(s,o)=>{let a=await Wt(n.steps,async u=>await u.stepFunction(s,o),e);if(a.some(u=>u&&typeof u=="object"&&"_parallelResults"in u)){let u=a.find(p=>p&&typeof p=="object"&&"_parallelResults"in p);return u||s}let c=s;for(let u of a)c={...c,...u};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 Fu,SpanKind as _u,trace as Nu}from"@opentelemetry/api";var Xa=i=>{console.log(i)},Vt=(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 s=JSON.stringify(r);s.length>200?t[n]=`${s.substring(0,200)}...`:t[n]=r}else t[n]=r;return JSON.stringify(t,null,2)},Jt=i=>i<1e3?`${i.toFixed(1)}ms`:i<6e4?`${(i/1e3).toFixed(2)}s`:`${(i/6e4).toFixed(2)}min`,Yr=(i=Xa)=>{let e=new $e,t=e.gray(`${"\u2501".repeat(80)}
564
564
  `),n=e.gray(`${"\u2500".repeat(40)}
565
565
  `);return r=>{let s="";switch(r.name){case"FlowStart":s=`
566
566
  ${e.blueBright("\u{1F504} [ AXFLOW START ]")}
@@ -572,13 +572,13 @@ ${t}`,s+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
572
572
  `,s+=t;break;case"StepStart":{let o=r.stepType==="execute"?"\u26A1":r.stepType==="map"?"\u{1F504}":r.stepType==="merge"?"\u{1F500}":r.stepType==="parallel"?"\u2696\uFE0F":"\u{1F4CB}";s=`${e.greenBright(`${o} [ STEP ${r.stepIndex} START ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=`
573
573
  `,r.dependencies.length>0&&(s+=`${e.white("Dependencies:")} ${e.gray(r.dependencies.join(", "))}
574
574
  `),r.produces.length>0&&(s+=`${e.white("Produces:")} ${e.cyan(r.produces.join(", "))}
575
- `),s+=`${e.white("State:")} ${e.gray(Wt(r.state,!0))}
576
- `,s+=n;break}case"StepComplete":{let o=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");s=`${e.greenBright(`${o} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=` ${e.magenta(`in ${Vt(r.executionTime)}`)}
575
+ `),s+=`${e.white("State:")} ${e.gray(Vt(r.state,!0))}
576
+ `,s+=n;break}case"StepComplete":{let o=(r.stepType==="execute"||r.stepType==="map"||r.stepType==="merge"||r.stepType==="parallel","\u2705");s=`${e.greenBright(`${o} [ STEP ${r.stepIndex} COMPLETE ]`)} ${e.white(`(${r.stepType})`)}`,r.nodeName&&(s+=` ${e.cyanBright(`Node: ${r.nodeName}`)}`),s+=` ${e.magenta(`in ${Jt(r.executionTime)}`)}
577
577
  `,r.newFields&&r.newFields.length>0&&(s+=`${e.white("New Fields:")} ${e.green(r.newFields.join(", "))}
578
578
  `),r.result&&r.nodeName&&(s+=`${e.white("Result:")} ${e.yellow(JSON.stringify(r.result,null,2))}
579
579
  `),s+=n;break}case"ParallelGroupStart":s=`${e.blueBright("\u2696\uFE0F [ PARALLEL GROUP START ]")} ${e.white(`Level ${r.groupLevel}`)}
580
580
  `,s+=`${e.white("Steps:")} ${e.yellow(r.stepsCount.toString())} ${e.gray(`(${r.stepTypes.join(", ")})`)}
581
- `,s+=n;break;case"ParallelGroupComplete":s=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,s+=` ${e.magenta(`in ${Vt(r.executionTime)}`)}
581
+ `,s+=n;break;case"ParallelGroupComplete":s=`${e.blueBright("\u2705 [ PARALLEL GROUP COMPLETE ]")} ${e.white(`Level ${r.groupLevel}`)}`,s+=` ${e.magenta(`in ${Jt(r.executionTime)}`)}
582
582
  `,s+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsCount.toString())}
583
583
  `,s+=n;break;case"BranchEvaluation":s=`${e.yellow("\u{1F500} [ BRANCH EVALUATION ]")}
584
584
  `,s+=`${e.white("Branch Value:")} ${e.cyan(JSON.stringify(r.branchValue))}
@@ -586,16 +586,16 @@ ${t}`,s+=`${e.white("Input Fields:")} ${e.cyan(r.inputFields.join(", "))}
586
586
  `,r.hasMatchingBranch&&(s+=`${e.white("Branch Steps:")} ${e.yellow(r.branchStepsCount.toString())}
587
587
  `),s+=n;break;case"FlowComplete":s=`
588
588
  ${e.greenBright("\u2705 [ AXFLOW COMPLETE ]")}
589
- ${t}`,s+=`${e.white("Total Time:")} ${e.magenta(Vt(r.totalExecutionTime))}
589
+ ${t}`,s+=`${e.white("Total Time:")} ${e.magenta(Jt(r.totalExecutionTime))}
590
590
  `,s+=`${e.white("Steps Executed:")} ${e.yellow(r.stepsExecuted.toString())}
591
591
  `,s+=`${e.white("Output Fields:")} ${e.green(r.outputFields.join(", "))}
592
- `,s+=`${e.white("Final State:")} ${e.gray(Wt(r.finalState,!0))}
592
+ `,s+=`${e.white("Final State:")} ${e.gray(Vt(r.finalState,!0))}
593
593
  `,s+=t;break;case"FlowError":s=`
594
594
  ${e.redBright("\u274C [ AXFLOW ERROR ]")}
595
595
  ${t}`,r.stepIndex!==void 0&&(s+=`${e.white("Step:")} ${e.yellow(r.stepIndex.toString())}`,r.stepType&&(s+=` ${e.gray(`(${r.stepType})`)}`),r.nodeName&&(s+=` ${e.cyan(`Node: ${r.nodeName}`)}`),s+=`
596
596
  `),s+=`${e.white("Error:")} ${e.red(r.error)}
597
- `,r.state&&(s+=`${e.white("State:")} ${e.gray(Wt(r.state,!0))}
598
- `),s+=t;break;default:s=e.gray(JSON.stringify(r,null,2))}i(s)}},Mu=(i=Xa)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
597
+ `,r.state&&(s+=`${e.white("State:")} ${e.gray(Vt(r.state,!0))}
598
+ `),s+=t;break;default:s=e.gray(JSON.stringify(r,null,2))}i(s)}},Pu=(i=Xa)=>{let e="=".repeat(80),t="-".repeat(40);return n=>{let r="";switch(n.name){case"FlowStart":r=`
599
599
  [ AXFLOW START ]
600
600
  ${e}
601
601
  `,r+=`Input Fields: ${n.inputFields.join(", ")}
@@ -607,16 +607,16 @@ ${e}
607
607
  `;break;case"StepStart":r=`[ STEP ${n.stepIndex} START ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
608
608
  `,n.dependencies.length>0&&(r+=`Dependencies: ${n.dependencies.join(", ")}
609
609
  `),n.produces.length>0&&(r+=`Produces: ${n.produces.join(", ")}
610
- `),r+=`State: ${Wt(n.state,!0)}
610
+ `),r+=`State: ${Vt(n.state,!0)}
611
611
  `,r+=`${t}
612
- `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Vt(n.executionTime)}
612
+ `;break;case"StepComplete":r=`[ STEP ${n.stepIndex} COMPLETE ] (${n.stepType})`,n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=` in ${Jt(n.executionTime)}
613
613
  `,n.newFields&&n.newFields.length>0&&(r+=`New Fields: ${n.newFields.join(", ")}
614
614
  `),n.result&&n.nodeName&&(r+=`Result: ${JSON.stringify(n.result,null,2)}
615
615
  `),r+=`${t}
616
616
  `;break;case"ParallelGroupStart":r=`[ PARALLEL GROUP START ] Level ${n.groupLevel}
617
617
  `,r+=`Steps: ${n.stepsCount} (${n.stepTypes.join(", ")})
618
618
  `,r+=`${t}
619
- `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Vt(n.executionTime)}
619
+ `;break;case"ParallelGroupComplete":r=`[ PARALLEL GROUP COMPLETE ] Level ${n.groupLevel} in ${Jt(n.executionTime)}
620
620
  `,r+=`Steps Executed: ${n.stepsCount}
621
621
  `,r+=`${t}
622
622
  `;break;case"BranchEvaluation":r=`[ BRANCH EVALUATION ]
@@ -627,27 +627,28 @@ ${e}
627
627
  `;break;case"FlowComplete":r=`
628
628
  [ AXFLOW COMPLETE ]
629
629
  ${e}
630
- `,r+=`Total Time: ${Vt(n.totalExecutionTime)}
630
+ `,r+=`Total Time: ${Jt(n.totalExecutionTime)}
631
631
  `,r+=`Steps Executed: ${n.stepsExecuted}
632
632
  `,r+=`Output Fields: ${n.outputFields.join(", ")}
633
- `,r+=`Final State: ${Wt(n.finalState,!0)}
633
+ `,r+=`Final State: ${Vt(n.finalState,!0)}
634
634
  `,r+=`${e}
635
635
  `;break;case"FlowError":r=`
636
636
  [ AXFLOW ERROR ]
637
637
  ${e}
638
638
  `,n.stepIndex!==void 0&&(r+=`Step: ${n.stepIndex}`,n.stepType&&(r+=` (${n.stepType})`),n.nodeName&&(r+=` Node: ${n.nodeName}`),r+=`
639
639
  `),r+=`Error: ${n.error}
640
- `,n.state&&(r+=`State: ${Wt(n.state,!0)}
640
+ `,n.state&&(r+=`State: ${Vt(n.state,!0)}
641
641
  `),r+=`${e}
642
- `;break;default:r=JSON.stringify(n,null,2)}i(r)}},Pu=Qr(),Za=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 Hn=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(s,o)=>{let a=n?.ai??o.mainAi,l=n?.options??o.mainOptions,c=t(s),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:p}}),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}},Lo=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(s,o)=>{let a=n?.ai??o.mainAi,l=n?.options??o.mainOptions,c=t(s),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:p}}),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 Yr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new zn;program;flowName;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 s={...t},o=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),u=this.getStepMetadata(l,a),p=Object.keys(s);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...s}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{s=await l(s,n),o++;let h=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,f=Object.keys(s).filter(x=>!p.includes(x)),y;if(c==="execute"&&u.nodeName&&f.length>0){let x=`${u.nodeName}Result`;y=s[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,executionTime:h,state:{...s},newFields:f,result:y})}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:u.nodeName,state:{...s}}),m}}return{finalState:s,stepsExecuted:o}}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 s=e.toString();return{nodeName:this.extractNodeNameFromSource(s),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 ue().input("userInput",ue.string("User input to the flow")).output("flowOutput",ue.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(p=>t.add(p)),u.dependencies.forEach(p=>n.add(p));let r=new Set;for(let u of Array.from(n))t.has(u)||r.add(u);let s=new Set,o=e.steps[e.steps.length-1];if(o&&(o.type==="map"||o.type==="merge")){if(o.produces.forEach(u=>{u.startsWith("_")||s.add(u)}),o.type==="merge"&&o.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(p=>s.add(p))}else for(let u of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(u)){p=!0;break}if(!p)if(u.endsWith("Result")){let d=u.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let g=m.getSignature().getOutputFields();for(let f of g)s.add(f.name)}else s.add(u)}else s.add(u)}if(r.size===0&&s.size===0){let u=[],p=[];for(let[m,h]of Array.from(this.nodeGenerators)){let g=h.getSignature();for(let f of g.getInputFields()){let y=this.toCamelCase(`${m}_${f.name}`);u.push({name:y,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of g.getOutputFields()){let y=this.toCamelCase(`${m}_${f.name}`);p.push({name:y,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let d=new fe;return u.length>0?d.setInputFields(u):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new fe,l=[];for(let u of Array.from(r))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let u of Array.from(s))u.startsWith("_")||c.push({name:u,type:{name:"string"},description:`Output field: ${u}`});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=Qr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Za(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 Mt(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)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
642
+ `;break;default:r=JSON.stringify(n,null,2)}i(r)}},Eu=Yr(),Za=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 Kn=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(s,o)=>{let a=n?.ai??o.mainAi,l=n?.options??o.mainOptions,c=t(s),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:p}}),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}},$o=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(s,o)=>{let a=n?.ai??o.mainAi,l=n?.options??o.mainOptions,c=t(s),u=l?.traceLabel?`Node:${e} (${l.traceLabel})`:`Node:${e}`,p;if("forward"in r&&typeof r.forward=="function")p=await r.forward(a,c,{...l,traceLabel:u});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...s,[`${e}Result`]:p}}),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 Xr=class i{static _ctorWarned=!1;nodes=new Map;flowDefinition=[];nodeGenerators=new Map;loopStack=[];stepLabels=new Map;branchContext=null;autoParallelConfig;executionPlanner=new Hn;program;flowName;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 s={...t},o=0;for(let a=0;a<e.length;a++){let l=e[a];if(!l)continue;let c=this.getStepType(l,a),u=this.getStepMetadata(l,a),p=Object.keys(s);this.flowLogger&&this.flowLogger({name:"StepStart",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,dependencies:u.dependencies,produces:u.produces,state:{...s}});let d=Date.now();this.timingLogger?.startTiming(`step-${a}`);try{s=await l(s,n),o++;let h=this.timingLogger?.endTiming(`step-${a}`)??Date.now()-d,f=Object.keys(s).filter(x=>!p.includes(x)),y;if(c==="execute"&&u.nodeName&&f.length>0){let x=`${u.nodeName}Result`;y=s[x]}this.flowLogger&&this.flowLogger({name:"StepComplete",timestamp:Date.now(),stepIndex:a,stepType:c,nodeName:u.nodeName,executionTime:h,state:{...s},newFields:f,result:y})}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:u.nodeName,state:{...s}}),m}}return{finalState:s,stepsExecuted:o}}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 s=e.toString();return{nodeName:this.extractNodeNameFromSource(s),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 ue().input("userInput",ue.string("User input to the flow")).output("flowOutput",ue.string("Output from the flow")).build();let t=new Set,n=new Set;for(let u of e.steps)u.produces.forEach(p=>t.add(p)),u.dependencies.forEach(p=>n.add(p));let r=new Set;for(let u of Array.from(n))t.has(u)||r.add(u);let s=new Set,o=e.steps[e.steps.length-1];if(o&&(o.type==="map"||o.type==="merge")){if(o.produces.forEach(u=>{u.startsWith("_")||s.add(u)}),o.type==="merge"&&o.produces.includes("_mergedResult"))for(let u of e.steps)u.type==="execute"&&u.produces.length>0&&u.produces.forEach(p=>s.add(p))}else for(let u of Array.from(t)){let p=!1;for(let d of e.steps)if(d.dependencies.includes(u)){p=!0;break}if(!p)if(u.endsWith("Result")){let d=u.replace("Result",""),m=this.nodeGenerators.get(d);if(m){let g=m.getSignature().getOutputFields();for(let f of g)s.add(f.name)}else s.add(u)}else s.add(u)}if(r.size===0&&s.size===0){let u=[],p=[];for(let[m,h]of Array.from(this.nodeGenerators)){let g=h.getSignature();for(let f of g.getInputFields()){let y=this.toCamelCase(`${m}_${f.name}`);u.push({name:y,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}for(let f of g.getOutputFields()){let y=this.toCamelCase(`${m}_${f.name}`);p.push({name:y,type:f.type,description:f.description,isOptional:f.isOptional,isInternal:f.isInternal})}}let d=new fe;return u.length>0?d.setInputFields(u):d.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),p.length>0?d.setOutputFields(p):d.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),d}let a=new fe,l=[];for(let u of Array.from(r))l.push({name:u,type:{name:"string"},description:`Input field: ${u}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let c=[];for(let u of Array.from(s))u.startsWith("_")||c.push({name:u,type:{name:"string"},description:`Output field: ${u}`});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=Yr():this.flowLogger=void 0,this.timingLogger=this.flowLogger?Za(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 Mt(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)}description(e,t){return this.ensureProgram(),this.flowName=e,this.program.setDescription(t),this}toFunction(){this.ensureProgram();let e=this.program.getSignature(),n=(this.flowName??(e.getDescription()?.trim().split(`
643
643
  `)[0]||"axFlow")).replace(/\s+/g,"_"),r=this.toCamelCase(n),s=async(o,a)=>{let l=a?.ai;if(!l)throw new Error("AI service is required to run the flow");let c=await this.forward(l,o??{}),u=e.getOutputFields(),p=c??{};return Object.keys(p).map(d=>{let m=u.find(h=>h.name===d);return m&&m.title?`${m.title}: ${p[d]}`:`${d}: ${p[d]}`}).join(`
644
- `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:s}}getUsage(){let e=[];for(let[t,n]of Array.from(this.nodeUsage))e.push(...n);return kn(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]=kn(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){let r=n?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),c=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,u=Ne("sha256");u.update(a.hash()??"");let p=d=>{let m=typeof d;if(u.update(`|${m}|`),d==null){u.update("null");return}if(m==="string"||m==="number"||m==="boolean"){u.update(String(d));return}if(Array.isArray(d)){u.update("[");for(let h of d)p(h);u.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let h=d;u.update(h.mimeType??"");let g=Ne("sha256").update(h.data??"").digest("hex");u.update(g);return}if(typeof d=="object"){let h=d,g=Object.keys(h).sort();for(let f of g)u.update(`{${f}}`),p(h[f]);return}u.update(String(d))};for(let d of l)p(c?.[d]);return u.digest("hex")})();if(r&&s){let a;try{a=await r(s)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let o=await this.forward(e,t,n);if(r&&s)try{await r(s,o)}catch{}yield{version:1,index:0,delta:o}}async forward(e,t,n){let r=n?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),c=l.getInputFields().map(m=>m.name),u=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=Ne("sha256");p.update(l.hash()??"");let d=m=>{let h=typeof m;if(p.update(`|${h}|`),m==null){p.update("null");return}if(h==="string"||h==="number"||h==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let g of m)d(g);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let g=m;p.update(g.mimeType??"");let f=Ne("sha256").update(g.data??"").digest("hex");p.update(f);return}if(typeof m=="object"){let g=m,f=Object.keys(g).sort();for(let y of f)p.update(`{${y}}`),d(g[y]);return}p.update(String(m))};for(let m of c)d(u?.[m]);return p.digest("hex")})();if(r&&s){let l=await r(s);if(l!==void 0)return l}let o=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(y=>y.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:o,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let c=n?.tracer??this.defaultAIOptions?.tracer,u=n?.traceContext,p,d=u;if(c){let f=this.getExecutionPlan(),y=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=c.startSpan(y,{kind:Fu.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let x=u??Eu.active();d=_u.setSpan(x,p)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),c&&(f.tracer=c),d&&(f.traceContext=d),Object.keys(f).length>0?f:void 0})()},h=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,g=0;if(h){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),y=await this.executeStepsWithLogging(f,a,m,!0);a=y.finalState,g=y.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,g=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-o;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:g})}if(p&&p.end(),r&&s)try{await r(s,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof fe){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=Ge(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 s=>(await Kt(n,async(l,c)=>{let u=l(s);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),s);if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}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 s=e(r);return Promise.resolve(s)};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 s=async(o,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(o),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,u,{...c,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let h=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...h,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let h=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...h,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=e.predicate(n),o=e.branches.get(s);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:s,hasMatchingBranch:!!o,branchStepsCount:o?.length??0}),!o)return n;let a=n;for(let l of o)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 s=await Kt(e,async(o,a)=>{let l=new Hn(this.nodeGenerators);return await o(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:s}};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 s=o=>{let a=o._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...o};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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),s=this.flowDefinition.length;return this.flowDefinition.push(async(o,a)=>{let l=o,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let p=r;p<s;p++){let d=this.flowDefinition[p];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(s=>s,{_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,s=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(o,a)=>{let l=o,c=0;for(;n(l)&&c<r;){c++;for(let u of s)l=await u(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 s=async o=>{let a=o[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 Kt(a,async(u,p)=>n(u,p,o),c)}else l=a.map((c,u)=>n(c,u,o));else l=n(a,void 0,o);return{...o,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=typeof t=="string"?fe.create(t):t;if(n.prependInputs)for(let o of n.prependInputs)s=s.prependInputField(o.name,o.type);if(n.appendInputs)for(let o of n.appendInputs)s=s.appendInputField(o.name,o.type);if(n.prependOutputs)for(let o of n.prependOutputs)s=s.prependOutputField(o.name,o.type);if(n.appendOutputs)for(let o of n.appendOutputs)s=s.appendOutputField(o.name,o.type);return this.node(e,s)}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 $o(i){return Yr.create(i)}var Go=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 s=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let o={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:s},Labels:{}};r&&(o.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});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 o=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(o&&o.length>0){let l=Math.floor(Math.random()*o.length),c=o[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=[],s=await this.listContainers(!0),o=e?s.filter(a=>a.Labels["com.example.tag"]===e):s;for(let a of o){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(),s=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!s.ok)throw new Error(`Failed to start exec instance: ${s.statusText}`);return await s.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(s=>setTimeout(s,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 Do=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 Uo=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=[];promptFunctions=[];resourceFunctions=[];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"),this.capabilities.tools&&await this.discoverFunctions(),this.capabilities.prompts&&await this.discoverPromptFunctions(),this.capabilities.resources&&await this.discoverResourceFunctions()}async discoverFunctions(){let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(s=>s.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 s=>{let{result:o}=await this.sendRequest("tools/call",{name:t.name,arguments:s});return o}}})}async discoverPromptFunctions(){let e;do{let t=await this.listPrompts(e);for(let n of t.prompts??[])this.promptFunctions.push(this.promptToFunction(n));e=t.nextCursor}while(e)}async discoverResourceFunctions(){let e;do{let t=await this.listResources(e);for(let n of t.resources??[])this.resourceFunctions.push(this.resourceToFunction(n));e=t.nextCursor}while(e);e=void 0;do{let t=await this.listResourceTemplates(e);for(let n of t.resourceTemplates??[])this.resourceFunctions.push(this.resourceTemplateToFunction(n));e=t.nextCursor}while(e)}promptToFunction(e){let t=`prompt_${e.name}`,n=this.options.functionOverrides?.find(s=>s.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(s=>[s.name,{type:"string",description:s.description??""}])),required:e.arguments.filter(s=>s.required).map(s=>s.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async s=>{let o=await this.getPrompt(e.name,s);return this.formatPromptMessages(o.messages)}}}resourceToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(r=>r.name===t);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:void 0,func:async()=>{let r=await this.readResource(e.uri);return this.formatResourceContents(r.contents)}}}resourceTemplateToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(s=>s.name===t),r=this.parseUriTemplate(e.uriTemplate);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:r.length?{type:"object",properties:Object.fromEntries(r.map(s=>[s,{type:"string",description:`Value for ${s}`}])),required:r}:void 0,func:async s=>{let o=this.expandUriTemplate(e.uriTemplate,s??{}),a=await this.readResource(o);return this.formatResourceContents(a.contents)}}}formatPromptMessages(e){return e.map(t=>{let n=t.role==="user"?"User":"Assistant",r=this.extractContent(t.content);return`${n}: ${r}`}).join(`
644
+ `)};return{name:r,description:e.getDescription()??"Execute this AxFlow",parameters:e.toJSONSchema(),func:s}}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){let r=n?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;this.ensureProgram();let a=this.program.getSignature(),l=a.getInputFields().map(d=>d.name),c=Array.isArray(t)?t.filter(d=>d.role==="user").pop().values:t,u=Ne("sha256");u.update(a.hash()??"");let p=d=>{let m=typeof d;if(u.update(`|${m}|`),d==null){u.update("null");return}if(m==="string"||m==="number"||m==="boolean"){u.update(String(d));return}if(Array.isArray(d)){u.update("[");for(let h of d)p(h);u.update("]");return}if(typeof d=="object"&&d!==null&&"mimeType"in d&&"data"in d){let h=d;u.update(h.mimeType??"");let g=Ne("sha256").update(h.data??"").digest("hex");u.update(g);return}if(typeof d=="object"){let h=d,g=Object.keys(h).sort();for(let f of g)u.update(`{${f}}`),p(h[f]);return}u.update(String(d))};for(let d of l)p(c?.[d]);return u.digest("hex")})();if(r&&s){let a;try{a=await r(s)}catch{}if(a!==void 0){yield{version:0,index:0,delta:a};return}}let o=await this.forward(e,t,n);if(r&&s)try{await r(s,o)}catch{}yield{version:1,index:0,delta:o}}async forward(e,t,n){let r=n?.cachingFunction??Z.cachingFunction,s=(()=>{if(!r)return;this.ensureProgram();let l=this.program.getSignature(),c=l.getInputFields().map(m=>m.name),u=Array.isArray(t)?t.filter(m=>m.role==="user").pop().values:t,p=Ne("sha256");p.update(l.hash()??"");let d=m=>{let h=typeof m;if(p.update(`|${h}|`),m==null){p.update("null");return}if(h==="string"||h==="number"||h==="boolean"){p.update(String(m));return}if(Array.isArray(m)){p.update("[");for(let g of m)d(g);p.update("]");return}if(typeof m=="object"&&m!==null&&"mimeType"in m&&"data"in m){let g=m;p.update(g.mimeType??"");let f=Ne("sha256").update(g.data??"").digest("hex");p.update(f);return}if(typeof m=="object"){let g=m,f=Object.keys(g).sort();for(let y of f)p.update(`{${y}}`),d(g[y]);return}p.update(String(m))};for(let m of c)d(u?.[m]);return p.digest("hex")})();if(r&&s){let l=await r(s);if(l!==void 0)return l}let o=Date.now();this.timingLogger?.startTiming("flow-execution");let a={};try{this.resetUsage(),this.resetTraces();let l;if(Array.isArray(t)){let f=t.filter(y=>y.role==="user").pop();if(!f)throw new Error("No user message found in values array");l=f.values}else l=t;if(this.nodeGenerators.size>0&&this.ensureProgram(),a={...l},this.flowLogger){let f=this.getExecutionPlan();this.flowLogger({name:"FlowStart",timestamp:o,inputFields:Object.keys(l),totalSteps:f.totalSteps,parallelGroups:f.parallelGroups,maxParallelism:f.maxParallelism,autoParallelEnabled:f.autoParallelEnabled})}let c=n?.tracer??this.defaultAIOptions?.tracer,u=n?.traceContext,p,d=u;if(c){let f=this.getExecutionPlan(),y=n?.traceLabel?`AxFlow > ${n.traceLabel}`:"AxFlow";p=c.startSpan(y,{kind:_u.INTERNAL,attributes:{total_steps:f.totalSteps,parallel_groups:f.parallelGroups,max_parallelism:f.maxParallelism,auto_parallel_enabled:f.autoParallelEnabled}});let x=u??Fu.active();d=Nu.setSpan(x,p)}let m={mainAi:e,mainOptions:(()=>{let f={...this.defaultAIOptions??{},...n};return n?.model&&(f.model=String(n.model)),c&&(f.tracer=c),d&&(f.traceContext=d),Object.keys(f).length>0?f:void 0})()},h=n?.autoParallel!==!1&&this.autoParallelConfig.enabled,g=0;if(h){this.executionPlanner.setInitialFields(Object.keys(l));let f=this.executionPlanner.createOptimizedExecution(this.autoParallelConfig.batchSize),y=await this.executeStepsWithLogging(f,a,m,!0);a=y.finalState,g=y.stepsExecuted}else{let f=await this.executeStepsWithLogging(this.flowDefinition,a,m,!1);a=f.finalState,g=f.stepsExecuted}if(this.flowLogger){let f=this.timingLogger?.endTiming("flow-execution")??Date.now()-o;this.flowLogger({name:"FlowComplete",timestamp:Date.now(),totalExecutionTime:f,finalState:a,outputFields:Object.keys(a),stepsExecuted:g})}if(p&&p.end(),r&&s)try{await r(s,a)}catch{}return a}catch(l){throw this.flowLogger&&this.flowLogger({name:"FlowError",timestamp:Date.now(),error:l instanceof Error?l.message:String(l),state:a}),typeof parentSpan<"u"&&parentSpan&&parentSpan.end(),l}}node(e,t){if(typeof t=="string"||t instanceof fe){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=Ge(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 s=>(await Wt(n,async(l,c)=>{let u=l(s);return Promise.resolve(u)},this.autoParallelConfig.batchSize)).reduce((l,c)=>({...l,...c}),s);if(this.branchContext?.currentBranchValue!==void 0){let s=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];s.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,s)}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 s=e(r);return Promise.resolve(s)};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 s=async(o,a)=>{let l=n?.ai??a.mainAi,c={...a.mainOptions??{},...n?.options??{}},u=t(o),p=c?.traceLabel?`Node:${e} (${c.traceLabel})`:`Node:${e}`,d;if("forward"in r&&typeof r.forward=="function"){if(d=await r.forward(l,u,{...c,traceLabel:p}),"getUsage"in r&&typeof r.getUsage=="function"){let m=r.getUsage();if(m&&m.length>0){let h=this.nodeUsage.get(e)||[];this.nodeUsage.set(e,[...h,...m])}}if("getTraces"in r&&typeof r.getTraces=="function"){let m=r.getTraces();if(m&&m.length>0){let h=this.nodeTraces.get(e)||[];this.nodeTraces.set(e,[...h,...m])}}}else throw new Error(`Node program for '${e}' does not have a forward method`);return{...o,[`${e}Result`]:d}};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=e.predicate(n),o=e.branches.get(s);if(this.flowLogger&&this.flowLogger({name:"BranchEvaluation",timestamp:Date.now(),branchValue:s,hasMatchingBranch:!!o,branchStepsCount:o?.length??0}),!o)return n;let a=n;for(let l of o)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 s=await Wt(e,async(o,a)=>{let l=new Kn(this.nodeGenerators);return await o(l).executeSteps(n,r)},this.autoParallelConfig.batchSize);return{...n,_parallelResults:s}};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 s=o=>{let a=o._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=r(...a),c={...o};return delete c._parallelResults,c[n]=l,c};return this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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),s=this.flowDefinition.length;return this.flowDefinition.push(async(o,a)=>{let l=o,c=1,u=`_feedback_${t}_iterations`;for(typeof l[u]!="number"&&(l={...l,[u]:1});e(l)&&c<n;){c++,l={...l,[u]:c};for(let p=r;p<s;p++){let d=this.flowDefinition[p];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(s=>s,{_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,s=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(o,a)=>{let l=o,c=0;for(;n(l)&&c<r;){c++;for(let u of s)l=await u(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 s=async o=>{let a=o[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 Wt(a,async(u,p)=>n(u,p,o),c)}else l=a.map((c,u)=>n(c,u,o));else l=n(a,void 0,o);return{...o,[e]:l}};if(this.branchContext?.currentBranchValue!==void 0){let o=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];o.push(s),this.branchContext.branches.set(this.branchContext.currentBranchValue,o)}else this.flowDefinition.push(s),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(s,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 s=typeof t=="string"?fe.create(t):t;if(n.prependInputs)for(let o of n.prependInputs)s=s.prependInputField(o.name,o.type);if(n.appendInputs)for(let o of n.appendInputs)s=s.appendInputField(o.name,o.type);if(n.prependOutputs)for(let o of n.prependOutputs)s=s.prependOutputField(o.name,o.type);if(n.appendOutputs)for(let o of n.appendOutputs)s=s.appendOutputField(o.name,o.type);return this.node(e,s)}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 Go(i){return Xr.create(i)}var Do=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 s=t.map(c=>`${c.hostPath}:${c.containerPath}`);n||await this.pullImage(e);let o={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:s},Labels:{}};r&&(o.Labels["com.example.tag"]=r);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});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 o=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===r);if(o&&o.length>0){let l=Math.floor(Math.random()*o.length),c=o[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=[],s=await this.listContainers(!0),o=e?s.filter(a=>a.Labels["com.example.tag"]===e):s;for(let a of o){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(),s=await this.fetchDockerAPI(`/exec/${r.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!s.ok)throw new Error(`Failed to start exec instance: ${s.statusText}`);return await s.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(s=>setTimeout(s,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 Uo=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 Bo=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=[];promptFunctions=[];resourceFunctions=[];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"),this.capabilities.tools&&await this.discoverFunctions(),this.capabilities.prompts&&await this.discoverPromptFunctions(),this.capabilities.resources&&await this.discoverResourceFunctions()}async discoverFunctions(){let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=this.options.functionOverrides?.find(s=>s.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 s=>{let{result:o}=await this.sendRequest("tools/call",{name:t.name,arguments:s});return o}}})}async discoverPromptFunctions(){let e;do{let t=await this.listPrompts(e);for(let n of t.prompts??[])this.promptFunctions.push(this.promptToFunction(n));e=t.nextCursor}while(e)}async discoverResourceFunctions(){let e;do{let t=await this.listResources(e);for(let n of t.resources??[])this.resourceFunctions.push(this.resourceToFunction(n));e=t.nextCursor}while(e);e=void 0;do{let t=await this.listResourceTemplates(e);for(let n of t.resourceTemplates??[])this.resourceFunctions.push(this.resourceTemplateToFunction(n));e=t.nextCursor}while(e)}promptToFunction(e){let t=`prompt_${e.name}`,n=this.options.functionOverrides?.find(s=>s.name===t),r=e.arguments?.length?{type:"object",properties:Object.fromEntries(e.arguments.map(s=>[s.name,{type:"string",description:s.description??""}])),required:e.arguments.filter(s=>s.required).map(s=>s.name)}:void 0;return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Get the ${e.name} prompt`,parameters:r,func:async s=>{let o=await this.getPrompt(e.name,s);return this.formatPromptMessages(o.messages)}}}resourceToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(r=>r.name===t);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:void 0,func:async()=>{let r=await this.readResource(e.uri);return this.formatResourceContents(r.contents)}}}resourceTemplateToFunction(e){let t=`resource_${this.sanitizeName(e.name)}`,n=this.options.functionOverrides?.find(s=>s.name===t),r=this.parseUriTemplate(e.uriTemplate);return{name:n?.updates.name??t,description:n?.updates.description??e.description??`Read ${e.name}`,parameters:r.length?{type:"object",properties:Object.fromEntries(r.map(s=>[s,{type:"string",description:`Value for ${s}`}])),required:r}:void 0,func:async s=>{let o=this.expandUriTemplate(e.uriTemplate,s??{}),a=await this.readResource(o);return this.formatResourceContents(a.contents)}}}formatPromptMessages(e){return e.map(t=>{let n=t.role==="user"?"User":"Assistant",r=this.extractContent(t.content);return`${n}: ${r}`}).join(`
645
645
 
646
646
  `)}extractContent(e){if(e.type==="text")return e.text;if(e.type==="image")return`[Image: ${e.mimeType}]`;if(e.type==="resource"){let t=e.resource;return"text"in t?t.text:`[Binary: ${t.uri}]`}return""}formatResourceContents(e){return e.map(t=>"text"in t?t.text:`[Binary: ${t.uri}]`).join(`
647
- `)}sanitizeName(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}parseUriTemplate(e){return(e.match(/\{([^}]+)\}/g)??[]).map(n=>n.slice(1,-1))}expandUriTemplate(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>t[r]??"")}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((o,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:s}=r;if(typeof s!="object"||s===null||Object.keys(s).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(s)}`)}toFunction(){return[...this.functions,...this.promptFunctions,...this.resourceFunctions]}getCapabilities(){return{tools:this.capabilities.tools??!1,resources:this.capabilities.resources??!1,prompts:this.capabilities.prompts??!1}}hasToolsCapability(){return this.capabilities.tools??!1}hasPromptsCapability(){return this.capabilities.prompts??!1}hasResourcesCapability(){return this.capabilities.resources??!1}async listPrompts(e){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("prompts/list",t);return n}async getPrompt(e,t){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let{result:n}=await this.sendRequest("prompts/get",{name:e,arguments:t});return n}async listResources(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/list",t);return n}async listResourceTemplates(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/templates/list",t);return n}async readResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let{result:t}=await this.sendRequest("resources/read",{uri:e});return t}async subscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/subscribe",{uri:e})}async unsubscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/unsubscribe",{uri:e})}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=Me(),r={jsonrpc:"2.0",id:n,method:e,params:t},s=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 u=c;l(new Error(`RPC Error ${u.error.code}: ${u.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:o}=await s;return{id:n,result:o}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let s={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(s)}await this.transport.sendNotification(n)}};function el(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 tl(i){let t=new TextEncoder().encode(i),n=await Ho().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function Bo(){return el(await tl(Me()+Math.random().toString(36)))}async function nl(i){return el(await tl(i))}async function Xr(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 rl(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function Kn(i){return i.endsWith("/")?i.slice(0,-1):i}function Nu(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 sl(i,e){let t=Nu(e);if(t){let a=await Xr(t),l=Kn(new URL(i).toString().split("?")[0]),c=Kn(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),s=[];r&&r!=="/"&&s.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),s.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let o;for(let a of s)try{let l=await Xr(a.url),c=Kn(l.resource??""),u=Kn(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:p}}catch(l){o=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(o)}`)}async function ol(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 s of n)try{let o=await Xr(s);if(!o.authorization_endpoint||!o.token_endpoint)throw new Error("AS metadata missing endpoints");let a=o.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return o}catch(o){r=o}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Jt=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 ol(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await sl(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],s=await this.getASMeta(r),o=e.currentToken??await this.getStoredToken(t,r);if(o?.accessToken&&!this.isExpired(o.expiresAt))return{token:o,issuer:r,asMeta:s,resource:t};if(o?.refreshToken)try{let x=await this.refreshToken(o.refreshToken,t,r,s);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:s,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(s,a),c=await Bo(),u=await nl(c),p=await Bo(),d=this.oauth.scopes?.join(" "),m=`${s.authorization_endpoint}?${rl({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:u,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:h,redirectUri:g}=await this.oauth.onAuthCode(m),f=g??a,y=await this.exchangeCodeForToken({asMeta:s,code:h,codeVerifier:c,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,y),{token:y,issuer:r,asMeta:s,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"},s=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`Dynamic client registration failed: ${s.status} ${s.statusText}`);let o=await s.json();if(!o.client_id)throw new Error("Dynamic client registration did not return client_id");return o}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 s=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:s}}async refreshToken(e,t,n,r){let s=new URLSearchParams;s.set("grant_type","refresh_token"),s.set("refresh_token",e),s.set("resource",t),this.oauth?.clientId&&s.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&s.set("client_secret",this.oauth.clientSecret);let o=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});if(!o.ok)throw new Error(`Token refresh failed: ${o.status} ${o.statusText}`);let a=await o.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 jo=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 Jt(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=s=>{try{let o=JSON.parse(s.data);this.messageHandler&&this.messageHandler(o)}catch(o){console.error("Failed to parse SSE message:",o)}},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,s="",o=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}s+=r.decode(l,{stream:!0});let c=s.split(`
647
+ `)}sanitizeName(e){return e.replace(/[^a-zA-Z0-9_]/g,"_")}parseUriTemplate(e){return(e.match(/\{([^}]+)\}/g)??[]).map(n=>n.slice(1,-1))}expandUriTemplate(e,t){return e.replace(/\{([^}]+)\}/g,(n,r)=>t[r]??"")}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((o,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),r=await Promise.race([t,n]),{result:s}=r;if(typeof s!="object"||s===null||Object.keys(s).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(s)}`)}toFunction(){return[...this.functions,...this.promptFunctions,...this.resourceFunctions]}getCapabilities(){return{tools:this.capabilities.tools??!1,resources:this.capabilities.resources??!1,prompts:this.capabilities.prompts??!1}}hasToolsCapability(){return this.capabilities.tools??!1}hasPromptsCapability(){return this.capabilities.prompts??!1}hasResourcesCapability(){return this.capabilities.resources??!1}async listPrompts(e){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("prompts/list",t);return n}async getPrompt(e,t){if(!this.capabilities.prompts)throw new Error("Prompts are not supported");let{result:n}=await this.sendRequest("prompts/get",{name:e,arguments:t});return n}async listResources(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/list",t);return n}async listResourceTemplates(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let t=e?{cursor:e}:void 0,{result:n}=await this.sendRequest("resources/templates/list",t);return n}async readResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");let{result:t}=await this.sendRequest("resources/read",{uri:e});return t}async subscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/subscribe",{uri:e})}async unsubscribeResource(e){if(!this.capabilities.resources)throw new Error("Resources are not supported");await this.sendRequest("resources/unsubscribe",{uri:e})}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=Me(),r={jsonrpc:"2.0",id:n,method:e,params:t},s=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 u=c;l(new Error(`RPC Error ${u.error.code}: ${u.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:o}=await s;return{id:n,result:o}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:r}=this.options;if(r){let s={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(s)}await this.transport.sendNotification(n)}};function el(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 tl(i){let t=new TextEncoder().encode(i),n=await Ko().subtle.digest("SHA-256",t);return new Uint8Array(n)}async function jo(){return el(await tl(Me()+Math.random().toString(36)))}async function nl(i){return el(await tl(i))}async function Zr(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 rl(i){let e=new URLSearchParams;for(let[t,n]of Object.entries(i))n!==void 0&&e.set(t,n);return e.toString()}function Wn(i){return i.endsWith("/")?i.slice(0,-1):i}function Lu(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 sl(i,e){let t=Lu(e);if(t){let a=await Zr(t),l=Wn(new URL(i).toString().split("?")[0]),c=Wn(a.resource??"");if(!c||c!==l)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${l} but got ${c}`);let u=Array.isArray(a.authorization_servers)?a.authorization_servers:[];if(u.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:l,issuers:u}}let n=new URL(i),r=n.pathname.replace(/\/+$/,""),s=[];r&&r!=="/"&&s.push({url:`${n.origin}/.well-known/oauth-protected-resource${r}`,expected:`${n.origin}${r}`}),s.push({url:`${n.origin}/.well-known/oauth-protected-resource`,expected:`${n.origin}`});let o;for(let a of s)try{let l=await Zr(a.url),c=Wn(l.resource??""),u=Wn(a.expected);if(!c||c!==u)throw new Error(`Protected resource metadata 'resource' mismatch. Expected ${u} but got ${c}`);let p=Array.isArray(l.authorization_servers)?l.authorization_servers:[];if(p.length===0)throw new Error("No authorization_servers advertised by protected resource");return{resource:u,issuers:p}}catch(l){o=l}throw new Error(`Failed to resolve protected resource metadata via well-known endpoints. Last error: ${String(o)}`)}async function ol(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 s of n)try{let o=await Zr(s);if(!o.authorization_endpoint||!o.token_endpoint)throw new Error("AS metadata missing endpoints");let a=o.code_challenge_methods_supported;if(!a||!a.includes("S256"))throw new Error("Authorization server does not advertise PKCE S256 support");return o}catch(o){r=o}throw new Error(`Failed to discover AS metadata for ${i}: ${String(r)}`)}var Qt=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 ol(e);return this.asMetaCache.set(e,t),t}async ensureAccessToken(e){if(!this.oauth)return null;let{resource:t,issuers:n}=await sl(e.requestedUrl,e.wwwAuthenticate),r=this.oauth.selectAuthorizationServer?await this.oauth.selectAuthorizationServer(n,{}):n[0],s=await this.getASMeta(r),o=e.currentToken??await this.getStoredToken(t,r);if(o?.accessToken&&!this.isExpired(o.expiresAt))return{token:o,issuer:r,asMeta:s,resource:t};if(o?.refreshToken)try{let x=await this.refreshToken(o.refreshToken,t,r,s);return await this.setStoredToken(t,r,x),{token:x,issuer:r,asMeta:s,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(s,a),c=await jo(),u=await nl(c),p=await jo(),d=this.oauth.scopes?.join(" "),m=`${s.authorization_endpoint}?${rl({response_type:"code",client_id:l.client_id,redirect_uri:a,scope:d,state:p,code_challenge:u,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:h,redirectUri:g}=await this.oauth.onAuthCode(m),f=g??a,y=await this.exchangeCodeForToken({asMeta:s,code:h,codeVerifier:c,client:l,redirectUri:f,resource:t});return await this.setStoredToken(t,r,y),{token:y,issuer:r,asMeta:s,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"},s=await fetch(e.registration_endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok)throw new Error(`Dynamic client registration failed: ${s.status} ${s.statusText}`);let o=await s.json();if(!o.client_id)throw new Error("Dynamic client registration did not return client_id");return o}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 s=r.expires_in?Date.now()+r.expires_in*1e3:void 0;return{accessToken:r.access_token,refreshToken:r.refresh_token,expiresAt:s}}async refreshToken(e,t,n,r){let s=new URLSearchParams;s.set("grant_type","refresh_token"),s.set("refresh_token",e),s.set("resource",t),this.oauth?.clientId&&s.set("client_id",this.oauth.clientId),this.oauth?.clientSecret&&s.set("client_secret",this.oauth.clientSecret);let o=await fetch(r.token_endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString()});if(!o.ok)throw new Error(`Token refresh failed: ${o.status} ${o.statusText}`);let a=await o.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 qo=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 Qt(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=s=>{try{let o=JSON.parse(s.data);this.messageHandler&&this.messageHandler(o)}catch(o){console.error("Failed to parse SSE message:",o)}},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,s="",o=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}s+=r.decode(l,{stream:!0});let c=s.split(`
648
648
  `);s=c.pop()||"";for(let u of c)if(u.startsWith("data: ")){let p=u.slice(6);if(p==="[DONE]")return;try{let d=JSON.parse(p);this.messageHandler&&this.messageHandler(d)}catch(d){console.error("Failed to parse SSE data:",d)}}await o()}catch(a){throw n.releaseLock(),a}};await o()}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 s=r.headers.get("Mcp-Session-Id");s&&(this.sessionId=s);let o=r.headers.get("Content-Type");if(o?.includes("text/event-stream"))return this.handleSSEResponse(r,e.id);if(o?.includes("application/json"))return r.json();throw new Error(`Unexpected content type: ${o}`)}async handleSSEResponse(e,t){return new Promise((n,r)=>{let s=e.body?.getReader();if(!s){r(new Error("No response body reader available"));return}let o=new TextDecoder,a="",l=async()=>{try{let{done:c,value:u}=await s.read();if(c){s.releaseLock();return}a+=o.decode(u,{stream:!0});let p=a.split(`
649
- `);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let h=JSON.parse(m);if("id"in h&&h.id===t){n(h);return}this.messageHandler&&this.messageHandler(h)}catch(h){console.error("Failed to parse SSE data:",h)}}await l()}catch(c){s.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 s=r.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${o.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 qo=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 Jt(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 s=n.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${o.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="",s=null;for(;;){let{done:o,value:a}=await t.read();if(o)break;r+=n.decode(a,{stream:!0});let l=r.split(`
650
- `);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))s=c.slice(7).trim();else if(c.startsWith("data: ")){let u=c.slice(6);if(s==="endpoint"){let p=u.trim(),d;try{let m=JSON.parse(p);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=p}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 p=u.trim();try{let d=JSON.parse(p);if(d&&typeof d=="object"&&"id"in d){let m=d.id,h=this.pendingRequests.get(m);h?(h.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else c.trim()===""&&(s=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})}),s=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(s.status===401){let a=s.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}`,s=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!s.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${s.status}: ${s.statusText}`);if(s.headers.get("Content-Type")?.includes("application/json")){let a=await s.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 s=r.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${o.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 zo(i,e,t){let n=t.join(", ");return`${i?`${i}
649
+ `);a=p.pop()||"";for(let d of p)if(d.startsWith("data: ")){let m=d.slice(6);if(m==="[DONE]")return;try{let h=JSON.parse(m);if("id"in h&&h.id===t){n(h);return}this.messageHandler&&this.messageHandler(h)}catch(h){console.error("Failed to parse SSE data:",h)}}await l()}catch(c){s.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 s=r.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.mcpEndpoint,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${o.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 Qt(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 s=n.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");return this.customHeaders.Authorization=`Bearer ${o.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="",s=null;for(;;){let{done:o,value:a}=await t.read();if(o)break;r+=n.decode(a,{stream:!0});let l=r.split(`
650
+ `);r=l.pop()||"";for(let c of l)if(c.startsWith("event: "))s=c.slice(7).trim();else if(c.startsWith("data: ")){let u=c.slice(6);if(s==="endpoint"){let p=u.trim(),d;try{let m=JSON.parse(p);typeof m=="string"?d=m:m&&typeof m=="object"&&"uri"in m&&(d=m.uri)}catch{d=p}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 p=u.trim();try{let d=JSON.parse(p);if(d&&typeof d=="object"&&"id"in d){let m=d.id,h=this.pendingRequests.get(m);h?(h.resolve(d),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(d)}else this.messageHandler&&this.messageHandler(d)}catch{}}}else c.trim()===""&&(s=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})}),s=await fetch(this.endpoint,{method:"POST",headers:t,body:n});if(s.status===401){let a=s.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}`,s=await fetch(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!s.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${s.status}: ${s.statusText}`);if(s.headers.get("Content-Type")?.includes("application/json")){let a=await s.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 s=r.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:s,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`Bearer ${o.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 Ho(i,e,t){let n=t.length>0&&typeof t[0]=="string"?t.map(a=>({name:a,title:a})):t,r=n.map(a=>{let l=Et(a.type),c=a.description?`: ${a.description}`:"";return`- \`${a.name}\` (${l})${c}`}).join(`
651
+ `),s=n[0]?.name??"context";return`${i?`${i}
651
652
 
652
653
  `:""}## Code Interpreter
653
654
 
@@ -655,35 +656,36 @@ You have a persistent ${e} REPL via the \`codeInterpreter\` function.
655
656
  Variables and state persist across calls.
656
657
 
657
658
  ### Pre-loaded context variables
658
- The following variables are available in the interpreter session: ${n}
659
+ The following variables are available in the interpreter session:
660
+ ${r}
659
661
 
660
662
  ### Available APIs
661
- - \`await llmQuery(query, context?)\` \u2014 Ask a sub-LM a natural-language question. Optionally pass a context string.
662
- - \`await llmQueryBatched([{ query, context? }, ...])\` \u2014 Run multiple sub-LM queries in parallel.
663
+ - \`await llmQuery(query, context?)\` \u2014 Ask a sub-LM a natural-language question. Optionally pass a context string (for objects/arrays, use JSON.stringify()). Returns a string.
664
+ - \`await llmQueryBatched([{ query, context? }, ...])\` \u2014 Run multiple sub-LM queries in parallel (same context rules as llmQuery). Returns string[]. Each query counts toward the call limit.
663
665
  - \`print(...args)\` \u2014 Print output (appears in the function result).
664
666
 
665
667
  ### Workflow
666
- 1. First, peek at the context to understand its structure (e.g. \`typeof ${t[0]??"context"}\`, \`${t[0]??"context"}.length\`, \`${t[0]??"context"}.slice(0, 500)\`).
667
- 2. Use string operations, regex, chunking, and iteration to process the context.
668
- 3. For semantic analysis of chunks, use \`await llmQuery(question, chunk)\`.
668
+ 1. The variable schemas are described above \u2014 use property names directly in code. Probe only for runtime size (e.g. \`${s}.length\`).
669
+ 2. Use code to process the context \u2014 property access, array methods (.map, .filter), string operations, regex, or iteration as appropriate for the data type.
670
+ 3. For semantic analysis, pass relevant subsets to llmQuery \u2014 strings directly, objects/arrays via JSON.stringify().
669
671
  4. For parallel analysis, use \`await llmQueryBatched([...])\`.
670
672
  5. Aggregate results as needed.
671
673
  6. When done, provide your final answer with the required output fields.
672
674
 
673
675
  ### Tips
674
- - Never try to pass the full context to llmQuery \u2014 chunk it first.
675
- - Use code for structural operations (split, filter, count, regex) and llmQuery for semantic understanding.
676
+ - Keep llmQuery context small \u2014 for strings, chunk the text; for structured data, filter or slice to relevant items.
677
+ - Use code for structural operations (.map, .filter, property access for objects; split, regex for strings) and llmQuery for semantic understanding.
676
678
  - Use \`var\` (not \`const\`/\`let\`) to persist variables across calls for synchronous code.
677
679
  - When using \`await\`, use bare assignments (e.g. \`results = await llmQuery(...)\`) to persist values.
678
680
  - The last expression value is auto-returned for synchronous code. When using \`await\`, code runs inside a wrapper function, so use \`return <value>\` to produce output.
679
- - If \`llmQuery\` fails with an error, use try/catch and retry with a smaller chunk or different query.`}function Lu(i,e,t,n,r){let s={...i};if(s.parameters){let o=s.parameters.properties?Object.keys(s.parameters.properties):[],l=t.filter(c=>o.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){s.parameters=Du(s.parameters,l);let c=s.func;s.func=async(u,p)=>{let d={};if(Array.isArray(e)){let h=e.filter(g=>g.role==="user").pop();h&&(d=ll(h.values,l))}else d=ll(e,l);let m={...u,...d};return await c(m,p)}}return s}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(s.parameters=cl(s.parameters,n)),s}var il=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),al=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),Zr=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;rlmConfig;rlmProgram;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:s,agents:o,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:u,debug:p}=l??{};if(this.ai=e,this.agents=o,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=u??[],this.debug=p,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 il;if(r&&r.length<100)throw al;this.program=new Ae(s,{...l,description:r??n});for(let m of o??[])this.program.register(m);this.name=t,this.func={name:Gu(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();if(d&&!this.disableSmartModelRouting&&(this.func.parameters=cl(this.func.parameters,d)),l?.rlm){this.rlmConfig=l.rlm;let m=this.program.getSignature().getInputFields();for(let f of l.rlm.contextFields)if(!m.some(y=>y.name===f))throw new Error(`RLM contextField "${f}" not found in signature`);if(!l.rlm.interpreter)throw new Error("RLM interpreter is required. Use AxRLMJSInterpreter from @ax-llm/ax-tools or provide a custom AxCodeInterpreter.");let h=new fe({description:this.program.getSignature().getDescription(),inputs:m.filter(f=>!l.rlm.contextFields.includes(f.name)),outputs:this.program.getSignature().getOutputFields()}),g=zo(r??n,l.rlm.interpreter.language,l.rlm.contextFields);this.rlmProgram=new Ae(h,{...l,description:g})}}static create(e,t){let n=fe.create(e),{ai:r,name:s,description:o,definition:a,agents:l,functions:c,...u}=t;return new i({ai:r,name:s,description:o,definition:a,signature:n,agents:l,functions:c},u)}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:s,...o}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,o,{...r,model:s}),u=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=u.find(h=>h.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
680
- `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,s=r?.getModelList(),a=this.program.getSignature().getInputFields().map(p=>p.name),l=this.getDebug(r,n),c=this.agents?.map(p=>{let d=p.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return Lu(p.getFunction(),t,a,s,m)}),u=[...n?.functions??this.functions??[],...c??[]];return{ai:r,functions:u,debug:l}}async forward(e,t,n){return this.rlmConfig&&this.rlmProgram?this._rlmForward(e,t,n):this._defaultForward(e,t,n)}async*streamingForward(e,t,n){if(this.rlmConfig&&this.rlmProgram){yield{version:1,index:0,delta:await this._rlmForward(e,t,n)};return}return yield*this._defaultStreamingForward(e,t,n)}async _defaultForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a={...this.options,...n,debug:o,functions:s};return await this.program.forward(r,t,a)}async*_defaultStreamingForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a={...this.options,...n,debug:o,functions:s};return yield*this.program.streamingForward(r,t,a)}async _rlmForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a=this.rlmConfig,l=a.interpreter,c={},u={},p;Array.isArray(t)?p=t.filter(I=>I.role==="user").pop()?.values??{}:p=t;for(let[A,I]of Object.entries(p))a.contextFields.includes(A)?c[A]=I:u[A]=I;for(let A of a.contextFields)if(!(A in c))throw new Error(`RLM contextField "${A}" is missing from input values`);let d=0,m=a.maxLlmCalls??50,h=async(A,I)=>{if(d++>=m)throw new Error(`Max LLM sub-calls (${m}) exceeded`);let C=3,S;for(let R=0;R<C;R++)try{return(await r.chat({chatPrompt:[{role:"system",content:"Answer the query based on the provided context."},{role:"user",content:I?`Context:
681
- ${I}
682
-
683
- Query: ${A}`:A}],...a.subModel?{model:a.subModel}:{}},{stream:!1})).results?.[0]?.content??""}catch(P){if(S=P,!$u(P)||R>=C-1)throw P;let E=Math.min(6e4,1e3*Math.pow(2,R));await new Promise(w=>setTimeout(w,E))}throw S},g=async A=>Promise.all(A.map(I=>h(I.query,I.context))),f=[],y=0,x=1048576,b=l.createSession({...c,llmQuery:h,llmQueryBatched:g,print:(...A)=>{if(y>=x)return;let I=A.map(String).join(" ");y+=I.length,f.push(I)}}),T={name:"codeInterpreter",description:`Execute ${l.language} code in a persistent REPL. Context available as: ${a.contextFields.join(", ")}. Use \`await llmQuery(query, context?)\` for semantic analysis. Use var (not const/let) to persist variables. Return a value to see it.`,parameters:{type:"object",properties:{code:{type:"string",description:`${l.language} code to execute`}},required:["code"]},func:async({code:A})=>{try{let I=await b.execute(A),C=f.splice(0).join(`
684
- `),S="";if(I!==void 0)if(typeof I=="string")S=I;else try{S=JSON.stringify(I,null,2)}catch{S=String(I)}return[C,S].filter(Boolean).join(`
685
- `)||"(no output)"}catch(I){let C=f.splice(0).join(`
686
- `),S=`Error: ${I.message}`;return C?`${C}
687
- ${S}`:S}}};try{let A={...this.options,...n,debug:o,functions:[...s,T],maxSteps:n?.maxSteps??this.options?.maxSteps??20};return await this.rlmProgram.forward(r,u,A)}finally{try{b.close()}catch{}}}setDescription(e){if(!e||e.length<20)throw il;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw al;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 $u(i){return i instanceof Ue&&i.status>=500&&i.status<600?!0:i instanceof Pe||i instanceof We}function Gu(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let s=n.toLowerCase();return r>0&&s&&s[0]?s[0].toUpperCase()+s.slice(1):s}).join("")}function cl(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(o=>o.key),description:`The AI model to use for this function call. Available options: ${e.map(o=>`\`${o.key}\` ${o.description}`).join(", ")}`},r={...t.properties??{},model:n},s=[...t.required??[],"model"];return{...t,properties:r,required:s}}function Du(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 ll(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Uu(i,e){let t=typeof i=="string"?fe.create(i):i,{ai:n,name:r,description:s,definition:o,agents:a,functions:l,...c}=e;return new Zr({ai:n,name:r,description:s,definition:o,signature:t,agents:a,functions:l},c)}var Bu=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,s=e?.qualityTarget??.85,o=e?.disableQualityHealing??!1;return $o({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:s,disableQualityHealing:o,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(u=>i(u))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],u=[...l,...c].filter(Boolean);return{collectedEvidence:u.length>0?u:["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 p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
688
- `):"").toString().trim();return p.length>0?p:"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`,u=await i(c);return{...a,healingResult:{healingDocument:u}}}).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{Fo as AxACE,Vr as AxACEOptimizedProgram,br as AxAI,en as AxAIAnthropic,nr as AxAIAnthropicModel,rr as AxAIAnthropicVertexModel,on as AxAIAzureOpenAI,an as AxAICohere,ar as AxAICohereEmbedModel,ir as AxAICohereModel,ln as AxAIDeepSeek,lr as AxAIDeepSeekModel,cn as AxAIGoogleGemini,ws as AxAIGoogleGeminiEmbedModel,Ui as AxAIGoogleGeminiEmbedTypes,cr as AxAIGoogleGeminiModel,vs as AxAIGoogleGeminiSafetyCategory,Ss as AxAIGoogleGeminiSafetyThreshold,In as AxAIGrok,Xi as AxAIGrokEmbedModels,yr as AxAIGrokModel,pn as AxAIGroq,pr as AxAIGroqModel,dn as AxAIHuggingFace,Es as AxAIHuggingFaceModel,mn as AxAIMistral,Ki as AxAIMistralEmbedModels,dr as AxAIMistralModel,gn as AxAIOllama,sn as AxAIOpenAI,Ie as AxAIOpenAIBase,tn as AxAIOpenAIEmbedModel,or as AxAIOpenAIModel,fn as AxAIOpenAIResponses,gr as AxAIOpenAIResponsesBase,hn as AxAIOpenAIResponsesImpl,nn as AxAIOpenAIResponsesModel,xn as AxAIOpenRouter,ge as AxAIRefusalError,An as AxAIReka,fr as AxAIRekaModel,Yt as AxAIServiceAbortedError,It as AxAIServiceAuthenticationError,Le as AxAIServiceError,Pe as AxAIServiceNetworkError,bt as AxAIServiceResponseError,Ue as AxAIServiceStatusError,Ze as AxAIServiceStreamTerminatedError,We as AxAIServiceTimeoutError,yn as AxAITogether,bn as AxAIWebLLM,Ar as AxAIWebLLMModel,Zr as AxAgent,To as AxApacheTika,mt as AxAssertionError,ys as AxBalancer,Ce as AxBaseAI,ze as AxBaseOptimizer,jn as AxBootstrapFewShot,at as AxContentProcessingError,Qs as AxDB,nt as AxDBBase,Tn as AxDBCloudflare,Xs as AxDBManager,St as AxDBMemory,Cn as AxDBPinecone,Rn as AxDBWeaviate,Kr as AxDefaultCostTracker,Io as AxDefaultResultReranker,Go as AxDockerSession,Do as AxEmbeddingAdapter,nu as AxEvalUtil,Yr as AxFlow,qn as AxFlowDependencyAnalyzer,zn as AxFlowExecutionPlanner,Hn as AxFlowSubContextImpl,Lo as AxFlowTypedSubContextImpl,Oe as AxFluentFieldType,Er as AxFunctionError,Fr as AxFunctionProcessor,Dn as AxGEPA,_o as AxGEPAFlow,Ae as AxGen,Br as AxGenerateError,So as AxHFDataLoader,En as AxInstanceRegistry,Nn as AxJudge,Zo as AxLLMRequestTypeValues,vo as AxLearn,Uo as AxMCPClient,qo as AxMCPHTTPSSETransport,jo as AxMCPStreambleHTTPTransport,et as AxMediaNotSupportedError,vn as AxMemory,No as AxMiPRO,Ls as AxMockAIService,$s as AxMultiServiceRouter,gt as AxOptimizedProgramImpl,Mt as AxProgram,zt as AxPromptTemplate,js as AxProviderRouter,un as AxRateLimiterTokenUsage,fe as AxSignature,Lr as AxSignatureBuilder,Ro as AxSimpleClassifier,Co as AxSimpleClassifierClass,ei as AxSpanKindValues,Fn as AxStepContextImpl,Bt as AxStopFunctionCallException,bo as AxStringUtil,Un as AxSynth,wo as AxTestPrompt,Yn as AxTokenLimitError,Ln as AxTraceLogger,Uu as agent,ic as ai,Ge as ax,Fi as axAIAnthropicDefaultConfig,vl as axAIAnthropicVertexDefaultConfig,Ll as axAIAzureOpenAIBestConfig,_l as axAIAzureOpenAICreativeConfig,Ni as axAIAzureOpenAIDefaultConfig,Nl as axAIAzureOpenAIFastConfig,Bl as axAICohereCreativeConfig,Gi as axAICohereDefaultConfig,ql as axAIDeepSeekCodeConfig,Di as axAIDeepSeekDefaultConfig,zi as axAIGoogleGeminiDefaultConfig,zl as axAIGoogleGeminiDefaultCreativeConfig,oc as axAIGrokBestConfig,Ws as axAIGrokDefaultConfig,Wl as axAIHuggingFaceCreativeConfig,Hi as axAIHuggingFaceDefaultConfig,Vl as axAIMistralBestConfig,Ns as axAIMistralDefaultConfig,Wi as axAIOllamaDefaultConfig,Jl as axAIOllamaDefaultCreativeConfig,fs as axAIOpenAIBestConfig,xs as axAIOpenAICreativeConfig,Nt as axAIOpenAIDefaultConfig,As as axAIOpenAIFastConfig,Yl as axAIOpenAIResponsesBestConfig,Xl as axAIOpenAIResponsesCreativeConfig,hr as axAIOpenAIResponsesDefaultConfig,Vi as axAIOpenRouterDefaultConfig,ec as axAIRekaBestConfig,tc as axAIRekaCreativeConfig,xr as axAIRekaDefaultConfig,nc as axAIRekaFastConfig,Qi as axAITogetherDefaultConfig,sc as axAIWebLLMCreativeConfig,Yi as axAIWebLLMDefaultConfig,Zl as axAnalyzeChatPromptRequirements,Lt as axAnalyzeRequestRequirements,ie as axBaseAIDefaultConfig,Se as axBaseAIDefaultCreativeConfig,zo as axBuildRLMDefinition,pc as axCheckMetricsHealth,Yo as axCreateDefaultColorLogger,Va as axCreateDefaultOptimizerColorLogger,ou as axCreateDefaultOptimizerTextLogger,bl as axCreateDefaultTextLogger,Qr as axCreateFlowColorLogger,Mu as axCreateFlowTextLogger,Pu as axDefaultFlowLogger,Zi as axDefaultMetricsConfig,qr as axDefaultOptimizerLogger,Ja as axDefaultOptimizerMetricsConfig,Gl as axGetCompatibilityReport,Ul as axGetFormatCompatibility,gc as axGetMetricsConfig,lu as axGetOptimizerMetricsConfig,Dl as axGetProvidersWithMediaSupport,Z as axGlobals,sr as axModelInfoAnthropic,Ts as axModelInfoCohere,Rs as axModelInfoDeepSeek,ks as axModelInfoGoogleGemini,Ks as axModelInfoGrok,Ms as axModelInfoGroq,Ps as axModelInfoHuggingFace,_s as axModelInfoMistral,rn as axModelInfoOpenAI,gs as axModelInfoOpenAIResponses,Us as axModelInfoReka,qs as axModelInfoTogether,zs as axModelInfoWebLLM,Ds as axProcessContentForProvider,Bu as axRAG,bs as axScoreProvidersForRequest,Is as axSelectOptimalProvider,Q as axSpanAttributes,lt as axSpanEvents,mc as axUpdateMetricsConfig,au as axUpdateOptimizerMetricsConfig,Zt as axValidateChatRequestMessage,ps as axValidateChatResponseResult,Li as axValidateProviderCapabilities,ue as f,$o as flow,Iu as s};
681
+ - If \`llmQuery\` fails with an error, use try/catch and retry with a smaller chunk or different query.`}function $u(i,e,t,n,r){let s={...i};if(s.parameters){let o=s.parameters.properties?Object.keys(s.parameters.properties):[],l=t.filter(c=>o.includes(c)).filter(c=>c!=="model").filter(c=>!r.excludeFieldsFromPassthrough.includes(c));if(l.length>0){s.parameters=Uu(s.parameters,l);let c=s.func;s.func=async(u,p)=>{let d={};if(Array.isArray(e)){let h=e.filter(g=>g.role==="user").pop();h&&(d=ll(h.values,l))}else d=ll(e,l);let m={...u,...d};return await c(m,p)}}return s}return n&&!r.disableSmartModelRouting&&r.canConfigureSmartModelRouting&&(s.parameters=cl(s.parameters,n)),s}var il=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),al=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),es=class i{ai;program;functions;agents;disableSmartModelRouting;excludeFieldsFromPassthrough;debug;options;rlmConfig;rlmContextFields;rlmProgram;name;func;constructor({ai:e,name:t,description:n,definition:r,signature:s,agents:o,functions:a},l){let{disableSmartModelRouting:c,excludeFieldsFromPassthrough:u,debug:p}=l??{};if(this.ai=e,this.agents=o,this.functions=a,this.disableSmartModelRouting=c,this.excludeFieldsFromPassthrough=u??[],this.debug=p,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 il;if(r&&r.length<100)throw al;this.program=new Ae(s,{...l,description:r??n});for(let m of o??[])this.program.register(m);this.name=t,this.func={name:Du(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let d=e?.getModelList();if(d&&!this.disableSmartModelRouting&&(this.func.parameters=cl(this.func.parameters,d)),l?.rlm){this.rlmConfig=l.rlm;let m=this.program.getSignature().getInputFields();for(let y of l.rlm.contextFields)if(!m.some(x=>x.name===y))throw new Error(`RLM contextField "${y}" not found in signature`);if(!l.rlm.interpreter)throw new Error("RLM interpreter is required. Use AxRLMJSInterpreter from @ax-llm/ax-tools or provide a custom AxCodeInterpreter.");let h=new fe({description:this.program.getSignature().getDescription(),inputs:m.filter(y=>!l.rlm.contextFields.includes(y.name)),outputs:this.program.getSignature().getOutputFields()}),g=m.filter(y=>l.rlm.contextFields.includes(y.name));this.rlmContextFields=g;let f=Ho(r??n,l.rlm.interpreter.language,g);this.rlmProgram=new Ae(h,{...l,description:f})}}static create(e,t){let n=fe.create(e),{ai:r,name:s,description:o,definition:a,agents:l,functions:c,...u}=t;return new i({ai:r,name:s,description:o,definition:a,signature:n,agents:l,functions:c},u)}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:s,...o}=n,a=this.ai??r?.ai;if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,o,{...r,model:s}),u=this.program.getSignature().getOutputFields();return Object.keys(l).map(d=>{let m=u.find(h=>h.name===d);return m?`${m.title}: ${l[d]}`:`${d}: ${l[d]}`}).join(`
682
+ `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let r=this.ai??e,s=r?.getModelList(),a=this.program.getSignature().getInputFields().map(p=>p.name),l=this.getDebug(r,n),c=this.agents?.map(p=>{let d=p.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:d.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:d.canConfigureSmartModelRouting};return $u(p.getFunction(),t,a,s,m)}),u=[...n?.functions??this.functions??[],...c??[]];return{ai:r,functions:u,debug:l}}async forward(e,t,n){return this.rlmConfig&&this.rlmProgram?this._rlmForward(e,t,n):this._defaultForward(e,t,n)}async*streamingForward(e,t,n){if(this.rlmConfig&&this.rlmProgram){yield{version:1,index:0,delta:await this._rlmForward(e,t,n)};return}return yield*this._defaultStreamingForward(e,t,n)}async _defaultForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a={...this.options,...n,debug:o,functions:s};return await this.program.forward(r,t,a)}async*_defaultStreamingForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a={...this.options,...n,debug:o,functions:s};return yield*this.program.streamingForward(r,t,a)}async _rlmForward(e,t,n){let{ai:r,functions:s,debug:o}=this.init(e,t,n),a=this.rlmConfig,l=a.interpreter,c={},u={},p;Array.isArray(t)?p=t.filter(C=>C.role==="user").pop()?.values??{}:p=t;for(let[I,C]of Object.entries(p))a.contextFields.includes(I)?c[I]=C:u[I]=C;for(let I of a.contextFields)if(!(I in c))throw new Error(`RLM contextField "${I}" is missing from input values`);let d=0,m=a.maxLlmCalls??50,h=async(I,C)=>{if(d++>=m)throw new Error(`Max LLM sub-calls (${m}) exceeded`);let S=3,R;for(let P=0;P<S;P++)try{return(await r.chat({chatPrompt:[{role:"system",content:"Answer the query based on the provided context."},{role:"user",content:C?`Context:
683
+ ${C}
684
+
685
+ Query: ${I}`:I}],...a.subModel?{model:a.subModel}:{}},{stream:!1})).results?.[0]?.content??""}catch(E){if(R=E,!Gu(E)||P>=S-1)throw E;let w=Math.min(6e4,1e3*Math.pow(2,P));await new Promise(v=>setTimeout(v,w))}throw R},g=async I=>Promise.all(I.map(C=>h(C.query,C.context))),f=[],y=0,x=1048576,b=l.createSession({...c,llmQuery:h,llmQueryBatched:g,print:(...I)=>{if(y>=x)return;let C=I.map(String).join(" ");y+=C.length,f.push(C)}}),T=(this.rlmContextFields??[]).map(I=>`${I.name}: ${Et(I.type)}`).join(", "),A={name:"codeInterpreter",description:`Execute ${l.language} code in a persistent REPL. Context available as: ${T||a.contextFields.join(", ")}. Use \`await llmQuery(query, context?)\` or \`llmQueryBatched([...])\` for semantic analysis. Persist with var (sync) or bare assignment (async). Return a value to see it.`,parameters:{type:"object",properties:{code:{type:"string",description:`${l.language} code to execute`}},required:["code"]},func:async({code:I})=>{try{let C=await b.execute(I),S=f.splice(0).join(`
686
+ `),R="";if(C!==void 0)if(typeof C=="string")R=C;else try{R=JSON.stringify(C,null,2)}catch{R=String(C)}return[S,R].filter(Boolean).join(`
687
+ `)||"(no output)"}catch(C){let S=f.splice(0).join(`
688
+ `),R=`Error: ${C.message}`;return S?`${S}
689
+ ${R}`:R}}};try{let I={...this.options,...n,debug:o,functions:[...s,A],maxSteps:n?.maxSteps??this.options?.maxSteps??20};return await this.rlmProgram.forward(r,u,I)}finally{try{b.close()}catch{}}}setDescription(e){if(!e||e.length<20)throw il;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw al;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 Gu(i){return i instanceof Ue&&i.status>=500&&i.status<600?!0:i instanceof Pe||i instanceof We}function Du(i){return i.split(/[^a-zA-Z0-9]/).map((n,r)=>{let s=n.toLowerCase();return r>0&&s&&s[0]?s[0].toUpperCase()+s.slice(1):s}).join("")}function cl(i,e){let t=i?structuredClone(i):{type:"object",properties:{},required:[]};if(t.properties?.model)return t;let n={type:"string",enum:e.map(o=>o.key),description:`The AI model to use for this function call. Available options: ${e.map(o=>`\`${o.key}\` ${o.description}`).join(", ")}`},r={...t.properties??{},model:n},s=[...t.required??[],"model"];return{...t,properties:r,required:s}}function Uu(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 ll(i,e){let t={};for(let n of e)n in i&&(t[n]=i[n]);return t}function Bu(i,e){let t=typeof i=="string"?fe.create(i):i,{ai:n,name:r,description:s,definition:o,agents:a,functions:l,...c}=e;return new es({ai:n,name:r,description:s,definition:o,signature:t,agents:a,functions:l},c)}var ju=(i,e)=>{let t=e?.maxHops??3,n=e?.qualityThreshold??.8,r=e?.maxIterations??2,s=e?.qualityTarget??.85,o=e?.disableQualityHealing??!1;return Go({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:s,disableQualityHealing:o,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(u=>i(u))):[];return{...a,retrievalResults:c}}).execute("evidenceSynthesizer",a=>{let l=Array.isArray(a.allEvidence)?a.allEvidence:[],c=Array.isArray(a.retrievalResults)?a.retrievalResults:[],u=[...l,...c].filter(Boolean);return{collectedEvidence:u.length>0?u:["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 p=(Array.isArray(a.allEvidence)?a.allEvidence.filter(Boolean).join(`
690
+ `):"").toString().trim();return p.length>0?p:"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`,u=await i(c);return{...a,healingResult:{healingDocument:u}}}).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{_o as AxACE,Jr as AxACEOptimizedProgram,Ir as AxAI,tn as AxAIAnthropic,rr as AxAIAnthropicModel,sr as AxAIAnthropicVertexModel,an as AxAIAzureOpenAI,ln as AxAICohere,lr as AxAICohereEmbedModel,ar as AxAICohereModel,cn as AxAIDeepSeek,cr as AxAIDeepSeekModel,un as AxAIGoogleGemini,vs as AxAIGoogleGeminiEmbedModel,Bi as AxAIGoogleGeminiEmbedTypes,ur as AxAIGoogleGeminiModel,Ss as AxAIGoogleGeminiSafetyCategory,ks as AxAIGoogleGeminiSafetyThreshold,Tn as AxAIGrok,Zi as AxAIGrokEmbedModels,br as AxAIGrokModel,dn as AxAIGroq,dr as AxAIGroqModel,mn as AxAIHuggingFace,Fs as AxAIHuggingFaceModel,gn as AxAIMistral,Wi as AxAIMistralEmbedModels,mr as AxAIMistralModel,hn as AxAIOllama,on as AxAIOpenAI,Ie as AxAIOpenAIBase,nn as AxAIOpenAIEmbedModel,ir as AxAIOpenAIModel,xn as AxAIOpenAIResponses,hr as AxAIOpenAIResponsesBase,fn as AxAIOpenAIResponsesImpl,rn as AxAIOpenAIResponsesModel,An as AxAIOpenRouter,ge as AxAIRefusalError,yn as AxAIReka,xr as AxAIRekaModel,Xt as AxAIServiceAbortedError,It as AxAIServiceAuthenticationError,Le as AxAIServiceError,Pe as AxAIServiceNetworkError,bt as AxAIServiceResponseError,Ue as AxAIServiceStatusError,Ze as AxAIServiceStreamTerminatedError,We as AxAIServiceTimeoutError,bn as AxAITogether,In as AxAIWebLLM,yr as AxAIWebLLMModel,es as AxAgent,Co as AxApacheTika,mt as AxAssertionError,bs as AxBalancer,Ce as AxBaseAI,ze as AxBaseOptimizer,qn as AxBootstrapFewShot,at as AxContentProcessingError,Ys as AxDB,nt as AxDBBase,Cn as AxDBCloudflare,Zs as AxDBManager,St as AxDBMemory,Rn as AxDBPinecone,wn as AxDBWeaviate,Wr as AxDefaultCostTracker,To as AxDefaultResultReranker,Do as AxDockerSession,Uo as AxEmbeddingAdapter,ru as AxEvalUtil,Xr as AxFlow,zn as AxFlowDependencyAnalyzer,Hn as AxFlowExecutionPlanner,Kn as AxFlowSubContextImpl,$o as AxFlowTypedSubContextImpl,Oe as AxFluentFieldType,Fr as AxFunctionError,_r as AxFunctionProcessor,Un as AxGEPA,No as AxGEPAFlow,Ae as AxGen,jr as AxGenerateError,ko as AxHFDataLoader,Fn as AxInstanceRegistry,Ln as AxJudge,ei as AxLLMRequestTypeValues,So as AxLearn,Bo as AxMCPClient,zo as AxMCPHTTPSSETransport,qo as AxMCPStreambleHTTPTransport,et as AxMediaNotSupportedError,Sn as AxMemory,Lo as AxMiPRO,$s as AxMockAIService,Gs as AxMultiServiceRouter,gt as AxOptimizedProgramImpl,Mt as AxProgram,Ht as AxPromptTemplate,qs as AxProviderRouter,pn as AxRateLimiterTokenUsage,fe as AxSignature,$r as AxSignatureBuilder,wo as AxSimpleClassifier,Ro as AxSimpleClassifierClass,ti as AxSpanKindValues,_n as AxStepContextImpl,jt as AxStopFunctionCallException,Io as AxStringUtil,Bn as AxSynth,vo as AxTestPrompt,Xn as AxTokenLimitError,$n as AxTraceLogger,Bu as agent,ic as ai,Ge as ax,_i as axAIAnthropicDefaultConfig,vl as axAIAnthropicVertexDefaultConfig,Ll as axAIAzureOpenAIBestConfig,_l as axAIAzureOpenAICreativeConfig,Li as axAIAzureOpenAIDefaultConfig,Nl as axAIAzureOpenAIFastConfig,Bl as axAICohereCreativeConfig,Di as axAICohereDefaultConfig,ql as axAIDeepSeekCodeConfig,Ui as axAIDeepSeekDefaultConfig,Hi as axAIGoogleGeminiDefaultConfig,zl as axAIGoogleGeminiDefaultCreativeConfig,oc as axAIGrokBestConfig,Vs as axAIGrokDefaultConfig,Wl as axAIHuggingFaceCreativeConfig,Ki as axAIHuggingFaceDefaultConfig,Vl as axAIMistralBestConfig,Ls as axAIMistralDefaultConfig,Vi as axAIOllamaDefaultConfig,Jl as axAIOllamaDefaultCreativeConfig,xs as axAIOpenAIBestConfig,As as axAIOpenAICreativeConfig,Lt as axAIOpenAIDefaultConfig,ys as axAIOpenAIFastConfig,Yl as axAIOpenAIResponsesBestConfig,Xl as axAIOpenAIResponsesCreativeConfig,fr as axAIOpenAIResponsesDefaultConfig,Ji as axAIOpenRouterDefaultConfig,ec as axAIRekaBestConfig,tc as axAIRekaCreativeConfig,Ar as axAIRekaDefaultConfig,nc as axAIRekaFastConfig,Yi as axAITogetherDefaultConfig,sc as axAIWebLLMCreativeConfig,Xi as axAIWebLLMDefaultConfig,Zl as axAnalyzeChatPromptRequirements,$t as axAnalyzeRequestRequirements,ie as axBaseAIDefaultConfig,Se as axBaseAIDefaultCreativeConfig,Ho as axBuildRLMDefinition,pc as axCheckMetricsHealth,Xo as axCreateDefaultColorLogger,Va as axCreateDefaultOptimizerColorLogger,iu as axCreateDefaultOptimizerTextLogger,bl as axCreateDefaultTextLogger,Yr as axCreateFlowColorLogger,Pu as axCreateFlowTextLogger,Eu as axDefaultFlowLogger,ea as axDefaultMetricsConfig,zr as axDefaultOptimizerLogger,Ja as axDefaultOptimizerMetricsConfig,Gl as axGetCompatibilityReport,Ul as axGetFormatCompatibility,gc as axGetMetricsConfig,cu as axGetOptimizerMetricsConfig,Dl as axGetProvidersWithMediaSupport,Z as axGlobals,or as axModelInfoAnthropic,Cs as axModelInfoCohere,ws as axModelInfoDeepSeek,Os as axModelInfoGoogleGemini,Ws as axModelInfoGrok,Ps as axModelInfoGroq,Es as axModelInfoHuggingFace,Ns as axModelInfoMistral,sn as axModelInfoOpenAI,hs as axModelInfoOpenAIResponses,Bs as axModelInfoReka,zs as axModelInfoTogether,Hs as axModelInfoWebLLM,Us as axProcessContentForProvider,ju as axRAG,Is as axScoreProvidersForRequest,Ts as axSelectOptimalProvider,Q as axSpanAttributes,lt as axSpanEvents,mc as axUpdateMetricsConfig,lu as axUpdateOptimizerMetricsConfig,en as axValidateChatRequestMessage,ds as axValidateChatResponseResult,$i as axValidateProviderCapabilities,ue as f,Go as flow,Tu as s};
689
691
  //# sourceMappingURL=index.js.map