@ax-llm/ax 13.0.5 → 13.0.7

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.cjs CHANGED
@@ -1,77 +1,134 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32; var _class33; var _class34; var _class35; var _class36; var _class37; var _class38; var _class39; var _class40; var _class41; var _class42; var _class43; var _class44; var _class45; var _class46;function L({model:s,modelInfo:e,models:t}){let n=_optionalChain([t, 'optionalAccess', _2 => _2.find, 'call', _3 => _3(l=>l.key===s)]),o=n&&"model"in n?n.model:s,r=e.find(l=>l.name===s);if(r)return r;let i=o.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===i);return a||null}var po=(()=>{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 B(){return po.randomUUID()}async function Jr(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await po.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var wt= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.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),o=0;for(let r=0;r<n.length;r++){let i=n[r];o=(o<<5)-o+i,o=o&o}return Math.abs(o).toString(16).padStart(8,"0")}async digestAsync(){return Jr(this.data)}}, _class);function je(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new wt}var He= (_class2 =class extends TransformStream{__init2() {this.buffer=""}__init3() {this.currentEvent={rawData:""}}constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)});_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);,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
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; } var _class; var _class2; var _class3; var _class4; var _class5; var _class6; var _class7; var _class8; var _class9; var _class10; var _class11; var _class12; var _class13; var _class14; var _class15; var _class16; var _class17; var _class18; var _class19; var _class20; var _class21; var _class22; var _class23; var _class24; var _class25; var _class26; var _class27; var _class28; var _class29; var _class30; var _class31; var _class32; var _class33; var _class34; var _class35; var _class36; var _class37; var _class38; var _class39; var _class40; var _class41; var _class42; var _class43; var _class44; var _class45; var _class46;function B({model:s,modelInfo:e,models:t}){let n=_optionalChain([t, 'optionalAccess', _2 => _2.find, 'call', _3 => _3(l=>l.key===s)]),o=n&&"model"in n?n.model:s,r=e.find(l=>l.name===s);if(r)return r;let i=o.replace(/^(anthropic\.|openai\.)/,"").replace(/-latest$/,"").replace(/-\d{8}$/,"").replace(/-v\d+:\d+$/,"").replace(/@\d{8}$/,"").replace(/-\d{2,}(-[a-zA-Z0-9-]+)?$/,"").replace(/-v\d+@\d{8}$/,"").replace(/-v\d+$/,""),a=e.find(l=>l.name===i);return a||null}var no=(()=>{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 q(){return no.randomUUID()}async function Xr(s){let e=new TextEncoder,t=typeof s=="string"?e.encode(s):s,n=await no.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(i=>i.toString(16).padStart(2,"0")).join("")}var wt= (_class =class{constructor() { _class.prototype.__init.call(this); }__init() {this.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),o=0;for(let r=0;r<n.length;r++){let i=n[r];o=(o<<5)-o+i,o=o&o}return Math.abs(o).toString(16).padStart(8,"0")}async digestAsync(){return Xr(this.data)}}, _class);function Be(s){if(s!=="sha256")throw new Error("Only SHA-256 algorithm is supported");return new wt}var qe= (_class2 =class extends TransformStream{__init2() {this.buffer=""}__init3() {this.currentEvent={rawData:""}}constructor(e={}){super({transform:(t,n)=>this.handleChunk(t,n),flush:t=>this.handleFlush(t)});_class2.prototype.__init2.call(this);_class2.prototype.__init3.call(this);,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 o of n)o===""?this.processEvent(e):this.parseLine(o)}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(),o=e.slice(t+1).trim();switch(n){case"event":this.currentEvent.event=o;break;case"data":this.currentEvent.rawData+=(this.currentEvent.rawData&&!this.currentEvent.rawData.endsWith(`
6
6
  `)?`
7
- `:"")+o;break;case"id":this.currentEvent.id=o;break;case"retry":{let r=Number.parseInt(o,10);Number.isNaN(r)||(this.currentEvent.retry=r);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:""}}}}, _class2);var vt=class{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)}},Ve=class extends TransformStream{constructor(){super(new vt)}};var Yr={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},Kr=3e4,Qr=_nullishCoalesce(globalThis.TextDecoderStream, () => (Ve)),U= exports.AxAIServiceError =class extends Error{constructor(t,n,o,r,i={}){super(t);this.url=n;this.requestBody=o;this.responseBody=r;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=B(),this.context=i,this.stack=this.toString()}toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},le= exports.AxAIServiceStatusError =class extends U{constructor(t,n,o,r,i,a){super(`HTTP ${t} - ${n}`,o,r,{httpStatus:t,httpStatusText:n,responseBody:i,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},X= exports.AxAIServiceNetworkError =class extends U{constructor(t,n,o,r,i){super(`Network Error: ${t.message}`,n,o,r,{originalErrorName:t.name,originalErrorStack:t.stack,...i});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},Q= exports.AxAIServiceResponseError =class extends U{constructor(e,t,n,o){super(e,t,n,void 0,o),this.name=this.constructor.name}},Y= exports.AxAIServiceStreamTerminatedError =class extends U{constructor(t,n,o,r){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...r});this.lastChunk=o;this.name=this.constructor.name}},pe= exports.AxAIServiceTimeoutError =class extends U{constructor(e,t,n,o){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o}),this.name=this.constructor.name}},me= exports.AxAIServiceAbortedError =class extends U{constructor(e,t,n,o){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...o}),this.name=this.constructor.name}},ne= exports.AxAIServiceAuthenticationError =class extends U{constructor(e,t,n,o){super("Authentication failed",e,t,n,o),this.name=this.constructor.name}},v= exports.AxAIRefusalError =class extends Error{constructor(t,n,o){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=o;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=B()}toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function co(s){try{return _optionalChain([s, 'access', _4 => _4.headers, 'access', _5 => _5.get, 'call', _6 => _6("content-type"), 'optionalAccess', _7 => _7.includes, 'call', _8 => _8("application/json")])?await s.json():await s.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function uo(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function Xr(){return{startTime:Date.now(),retryCount:0}}function mo(s){s.retryCount++,s.lastRetryTime=Date.now()}function go(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof X&&!(s instanceof ne)}var D=async(s,e)=>{let t={...Yr,...s.retry},n=_nullishCoalesce(s.timeout, () => (Kr)),o=Xr(),r,i=new URL(_nullishCoalesce(process.env.PROXY, () => (s.url))),a=`${[i.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${i.search}`,l=new URL(a,i),p=B();if(s.validateRequest&&!await s.validateRequest(e))throw new Q("Invalid request data",l.href,e,{validation:"request"});_optionalChain([s, 'access', _9 => _9.span, 'optionalAccess', _10 => _10.setAttributes, 'call', _11 => _11({"http.request.method":s.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":o.startTime})]);let c=0;for(;;){let d=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new me(l.href,s.abortSignal.reason,e,{metrics:o});let u=()=>{d.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",u,{once:!0});let m=d.abort.bind(d);d.abort=A=>{s.abortSignal.removeEventListener("abort",u),m(A)}}r=setTimeout(()=>{d.abort("Request timeout")},n);try{let u=await(_nullishCoalesce(s.fetch, () => (fetch)))(l,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":c.toString(),...s.headers},body:JSON.stringify(e),signal:d.signal});if(clearTimeout(r),u.status===401||u.status===403){let h=await co(u);throw new ne(l.href,e,h,{metrics:o})}if(u.status>=400&&go(new Error,u.status,c,t)){let h=uo(c,t);c++,mo(o),_optionalChain([s, 'access', _12 => _12.span, 'optionalAccess', _13 => _13.addEvent, 'call', _14 => _14("retry",{attempt:c,delay:h,status:u.status,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime})]),await new Promise(I=>setTimeout(I,h));continue}if(u.status>=400){let h=await co(u);throw new le(u.status,u.statusText,l.href,e,h,{metrics:o})}if(!s.stream){let h=await u.json();if(s.validateResponse&&!await s.validateResponse(h))throw new Q("Invalid response data",l.href,e,{validation:"response"});return _optionalChain([s, 'access', _15 => _15.span, 'optionalAccess', _16 => _16.setAttributes, 'call', _17 => _17({"response.time":Date.now()-o.startTime,"response.retries":o.retryCount})]),h}if(!u.body)throw new Q("Response body is null",l.href,e,{metrics:o});let m,A=0,g=new TransformStream({transform(h,I){m=h,A++,o.streamChunks=A,o.lastChunkTime=Date.now(),I.enqueue(h),_optionalChain([s, 'access', _18 => _18.span, 'optionalAccess', _19 => _19.addEvent, 'call', _20 => _20("stream.chunk",{"stream.chunks":A,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})])}}),f=!1;return new ReadableStream({start(h){let I=u.body.pipeThrough(new Qr).pipeThrough(new He).pipeThrough(g).getReader();async function x(){try{for(;;){let{done:b,value:T}=await I.read();if(b){f||(f=!0,h.close());break}if(f)break;h.enqueue(T)}}catch(b){let T=b,O={...o,streamDuration:Date.now()-o.startTime};throw T.name==="AbortError"||_optionalChain([T, 'access', _21 => _21.message, 'optionalAccess', _22 => _22.includes, 'call', _23 => _23("aborted")])?h.error(new Y(l.href,e,m,{streamMetrics:O})):T instanceof TypeError&&T.message.includes("cancelled")?h.error(new Y(l.href,e,m,{streamMetrics:O,cancelReason:"Stream cancelled by client"})):h.error(new X(T,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:O})),T}finally{clearTimeout(r),I.releaseLock()}}x()},cancel(){f=!0}})}catch(u){if(u instanceof Error&&u.name==="AbortError")throw _optionalChain([s, 'access', _24 => _24.abortSignal, 'optionalAccess', _25 => _25.aborted])?new me(l.href,s.abortSignal.reason,e,{metrics:o}):new pe(l.href,n,e,{metrics:o});if(_optionalChain([s, 'access', _26 => _26.span, 'optionalAccess', _27 => _27.isRecording, 'call', _28 => _28()])&&(s.span.recordException(u),s.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),u instanceof X&&go(u,void 0,c,t)){let m=uo(c,t);c++,mo(o),_optionalChain([s, 'access', _29 => _29.span, 'optionalAccess', _30 => _30.addEvent, 'call', _31 => _31("retry",{attempt:c,delay:m,error:u.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime})]),await new Promise(A=>setTimeout(A,m));continue}throw u instanceof U&&(u.context.metrics=o),u}finally{r!==void 0&&clearTimeout(r)}}};var _api = require('@opentelemetry/api');var k={signatureStrict:!0,tracer:void 0,meter:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var C={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"},j= exports.axSpanEvents ={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"},Ao= exports.AxLLMRequestTypeValues =(o=>(o.COMPLETION="completion",o.CHAT="chat",o.RERANK="rerank",o.UNKNOWN="unknown",o))(Ao||{}),ho= exports.AxSpanKindValues =(r=>(r.WORKFLOW="workflow",r.TASK="task",r.AGENT="agent",r.TOOL="tool",r.UNKNOWN="unknown",r))(ho||{});var Ot=class{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),_optionalChain([this, 'access', _32 => _32.buffer, 'optionalAccess', _33 => _33.push, 'call', _34 => _34(n)]))}async flush(e){await _optionalChain([this, 'access', _35 => _35.doneCallback, 'optionalCall', _36 => _36(_nullishCoalesce(this.buffer, () => ([])))]),e.terminate()}},We=class extends TransformStream{constructor(e,t){super(new Ot(e,t))}};var H= (_class3 =class{constructor() { _class3.prototype.__init4.call(this);_class3.prototype.__init5.call(this);_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);_class3.prototype.__init10.call(this);_class3.prototype.__init11.call(this);_class3.prototype.__init12.call(this); }__init4() {this.ANSI_WHITE_BRIGHT="\x1B[97m"}__init5() {this.ANSI_GREEN_BRIGHT="\x1B[92m"}__init6() {this.ANSI_BLUE_BRIGHT="\x1B[94m"}__init7() {this.ANSI_RED_BRIGHT="\x1B[91m"}__init8() {this.ANSI_YELLOW="\x1B[93m"}__init9() {this.ANSI_RED="\x1B[91m"}__init10() {this.ANSI_RESET="\x1B[0m"}__init11() {this.ANSI_ORANGE="\x1B[38;5;208m"}__init12() {this.ANSI_WHITE="\x1B[37m"}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)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}}, _class3);var K=new H,xo=s=>{process.stdout.write(s)},St= exports.axCreateDefaultColorLogger =(s=xo)=>(e,t)=>{let n=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _37 => _37.tags]), () => ([])),o=e,r=i=>i;n.includes("systemContent")?r=i=>K.white(i):n.includes("userContent")?r=i=>K.white(i):n.includes("functionName")?r=i=>K.greenBright(i):n.includes("functionArg")?r=i=>K.greenBright(i):n.includes("assistantContent")?r=i=>K.white(i):n.includes("responseContent")?r=i=>K.greenBright(i):n.includes("functionResult")&&(r=i=>K.blueBright(i)),n.includes("error")?r=i=>K.redBright(i):n.includes("warning")&&(r=i=>K.red(i)),(n.includes("systemContent")||n.includes("userContent")||n.includes("functionName")||n.includes("functionArg")||n.includes("functionResult")||n.includes("assistantStart")||n.includes("start")||n.includes("end"))&&(o=`
10
- ${o}`),n.includes("responseEnd")&&(o=`${o}
11
- \u2500\u2500\u2500
12
- `),s(r(o))},V=St(),Zr= exports.axCreateDefaultTextLogger =(s=xo)=>(e,t)=>{let n=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _38 => _38.tags]), () => ([])),o=e;(n.includes("systemContent")||n.includes("userContent")||n.includes("functionName")||n.includes("functionArg")||n.includes("functionResult")||n.includes("assistantStart")||n.includes("start")||n.includes("end"))&&(o=`
13
- ${o}`),n.includes("responseEnd")&&(o=`${o}\u2500\u2500\u2500
14
- `),s(o)},fo= exports.axCreateOptimizerLogger =(s=e=>process.stdout.write(e))=>{let e=St(s),t=!0;return(n,o)=>{let r=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _39 => _39.tags]), () => ([])),i=n;if(r.includes("optimizer")){if(r.includes("start")){let a=n.match(/with (\d+) trials?/)||n.match(/(\d+) trials?/),l=n.match(/(MIPROv2|BootstrapFewshot|[A-Z][a-zA-Z]+)/),p=l?l[1]:"Optimizer";_optionalChain([a, 'optionalAccess', _40 => _40[1]])?i=`
15
- \u250C\u2500 ${p} optimization (${a[1]} trials)
16
- `:i=`
17
- \u250C\u2500 ${p} optimization
18
- `,t=!0}else if(r.includes("config"))if(n.includes("examples")&&n.includes("training")){let a=n.match(/(\d+) examples for training and (\d+) for validation/)||n.match(/(\d+) training.*?(\d+) validation/);if(_optionalChain([a, 'optionalAccess', _41 => _41[1]])&&a[2])i=`\u2502 Dataset: ${a[1]} training, ${a[2]} validation
19
- `;else{let l=n.match(/(\d+) examples/);_optionalChain([l, 'optionalAccess', _42 => _42[1]])&&(i=`\u2502 Dataset: ${l[1]} examples
20
- `)}}else n.includes("teacher")?i=`\u2502 Using teacher model
21
- `:i=`\u2502 ${n}
22
- `;else if(r.includes("phase"))t?(i=`\u251C\u2500 ${n}
23
- `,t=!1):i=`\u251C\u2500 ${n}
24
- `;else if(r.includes("result"))n.includes("Generated")||n.includes("Selected")?_optionalChain([n, 'access', _43 => _43.match, 'call', _44 => _44(/(\d+)/), 'optionalAccess', _45 => _45[1]])?i=`\u2502 \u2713 ${n}
25
- `:i=`\u2502 \u2713 ${n}
26
- `:n.includes("configuration")?i=`\u2502 Applied best configuration
27
- `:i=`\u2502 ${n}
28
- `;else if(r.includes("progress"))i=`\u2502 ${n}
29
- `;else if(r.includes("complete")){let a=n.match(/(score|performance):\s*([\d.]+)/);if(_optionalChain([a, 'optionalAccess', _46 => _46[2]])){let l=Number.parseFloat(a[2]);i=`\u251C\u2500 Complete! Best: ${l<=1?`${(l*100).toFixed(1)}%`:l.toFixed(3)}
30
- `}else n.includes("Bootstrap")?i=`\u251C\u2500 ${n}
31
- `:i=`\u251C\u2500 Optimization complete
32
- `}else if(r.includes("checkpoint"))if(n.includes("Resuming"))i=`\u2502 ${n}
33
- `;else{let a=n.match(/checkpoint:\s*(.+)/)||n.match(/Saved\s+(.+)/);_optionalChain([a, 'optionalAccess', _47 => _47[1]])?i=`\u2514\u2500 Saved: ${a[1]}
34
- `:i=`\u2514\u2500 Checkpoint saved
35
- `}}else if(r.includes("discovery")&&n.includes("Found")&&n.includes("examples")){let a=n.match(/Found (\d+)/);_optionalChain([a, 'optionalAccess', _48 => _48[1]])&&(i=`\u2502 Found ${a[1]} examples
36
- `)}r.includes("error")?i=`
37
- \u2717 ${n}
38
- `:r.includes("warning")&&(i=`
39
- \u26A0 ${n}
40
- `),e(i,o)}},kt= exports.axDefaultOptimizerLogger =fo();var es=(s,e,t)=>{switch(s.role){case"system":return t?"":`\u2500\u2500\u2500 System: \u2500\u2500\u2500
41
- ${s.content}`;case"function":return`\u2500\u2500\u2500 Function Result: \u2500\u2500\u2500
42
- ${s.result}`;case"user":return typeof s.content=="string"?`\u2500\u2500\u2500 User: \u2500\u2500\u2500
43
- ${s.content}`:`\u2500\u2500\u2500 User: \u2500\u2500\u2500
44
- ${s.content.map(o=>{switch(o.type){case"text":return o.text;case"image":return`(Image, ${o.mimeType}) ${o.image.substring(0,10)}`;default:throw new Error("Invalid content type")}}).join(`
45
- `)}`;case"assistant":return s.functionCalls?`\u2500\u2500\u2500 Functions: \u2500\u2500\u2500
46
- ${(_optionalChain([s, 'access', _49 => _49.functionCalls, 'optionalAccess', _50 => _50.map, 'call', _51 => _51(({function:o})=>{let r=typeof o.params!="string"?JSON.stringify(o.params,null,2):o.params;return`${o.name}(${r})`})])).join(`
47
- `)}`:`\u2500\u2500\u2500 Assistant: \u2500\u2500\u2500
48
- ${e?"":_nullishCoalesce(s.content, () => ("<empty>"))}`;default:throw new Error("Invalid role")}},yo=(s,e,t=V)=>{ge([s],e,t)},ge=(s,e,t=V)=>{for(let n of _nullishCoalesce(s, () => ([]))){let o=es(n,!1,e);if(o){let r=[];switch(n.role){case"system":r.push("systemContent");break;case"function":r.push("functionName");break;case"user":r.push("userContent");break}t(o,{tags:r})}}t("\u2500\u2500\u2500 Assistant: \u2500\u2500\u2500",{tags:["assistantStart"]})},Mt=(s,e=V)=>{s.content&&e(s.content,{tags:["responseContent"]});let t=new Set;if(s.functionCalls&&s.functionCalls.length>0)for(let[n,o]of s.functionCalls.entries()){if(o.id){if(t.has(o.id))continue;t.add(o.id);let r=["functionName"];n===0&&r.push("firstFunction"),s.functionCalls.length>1&&r.push("multipleFunctions"),e(`[${n+1}] ${o.function.name} [${o.id}]`,{tags:r})}if(o.function.params){let r=typeof o.function.params=="string"?o.function.params:JSON.stringify(o.function.params,null,2);e(r,{tags:["functionArg"]})}}},Et=(s,e=V)=>{if(s.results)for(let t of s.results)Mt(t,e)},Io=(s,e=V)=>{e(s,{tags:["responseContent","responseDelta"]})},bo=(s,e=V)=>{for(let t of s)e(`Function Result [${t.functionId}]:`,{tags:["functionResult"]}),t.isError?e(t.result,{tags:["functionResult","error"]}):e(t.result,{tags:["functionResult"]})};var Pt=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n);e[t]=o.length>100?o.substring(0,100):o}return e},Je,Ro=s=>{if(Je)return Je;if(s)return Je=ts(s),Je};var ts=s=>({latencyHistogram:s.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:s.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:s.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:s.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:s.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:s.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:s.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:s.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:s.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:s.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:s.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:s.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:s.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:s.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:s.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:s.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:s.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:s.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:s.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:s.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:s.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:s.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:s.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:s.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),Co=(s,e,t,n,o)=>{try{if(s.latencyHistogram){let r=Pt({operation:e,ai_service:n,...o?{model:o}:{}});s.latencyHistogram.record(t,r)}}catch(r){console.warn("Failed to record latency metric:",r)}},To=(s,e,t,n,o,r,i)=>{let a={operation:e,ai_service:r,...i?{model:i}:{}};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,a),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,a),s.p99LatencyGauge&&s.p99LatencyGauge.record(o,a)},wo=(s,e,t,n)=>{try{if(s.errorCounter){let o=Pt({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},vo=(s,e,t,n,o)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...o?{model:o}:{}})},Oo=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Ae=(s,e,t,n,o)=>{try{let r=Pt({ai_service:n,...o?{model:o}:{}});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...r}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,r),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,r)}catch(r){console.warn("Failed to record token metric:",r)}},So=(s,e,t,n,o)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...o?{model:o}:{}})},ko=(s,e,t,n,o)=>{let r={function_name:e,...n?{ai_service:n}:{},...o?{model:o}:{}};s.functionCallsCounter&&s.functionCallsCounter.add(1,r),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,r)},_t=(s,e,t,n,o)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Ft=(s,e,t,n,o)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Mo=(s,e,t,n,o)=>{let r={...n?{ai_service:n}:{},...o?{model:o}:{}};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,r),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,r)},Gt=(s,e,t,n,o)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Eo=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Po=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},_o=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Fo=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Go=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},Do=(s,e,t,n,o)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...o?{model:o}:{}})};var w=()=>structuredClone({temperature:0,topK:40,topP:.9}),F= exports.axBaseAIDefaultCreativeConfig =()=>structuredClone({temperature:.4,topP:.7,frequencyPenalty:.2}),E= exports.AxBaseAI = (_class4 =class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:r,defaults:i,options:a={},supportFor:l,models:p}){;_class4.prototype.__init13.call(this);_class4.prototype.__init14.call(this);_class4.prototype.__init15.call(this);this.aiImpl=e;this.name=t,this.apiURL=n,this.headers=o,this.supportFor=l,this.tracer=_nullishCoalesce(a.tracer, () => (k.tracer)),this.meter=_nullishCoalesce(a.meter, () => (k.meter)),this.modelInfo=r,this.models=p,this.id=B();let c=_nullishCoalesce(this.getModel(i.model), () => (i.model)),d=_nullishCoalesce(this.getEmbedModel(i.embedModel), () => (i.embedModel));if(this.defaults={model:c,embedModel:d},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),p&&os(p)}__init13() {this.debug=!1}__init14() {this.logger=V}__init15() {this.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 Ro(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=_nullishCoalesce(e.debug, () => (!1)),this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=_nullishCoalesce(e.tracer, () => (k.tracer)),this.meter=_nullishCoalesce(e.meter, () => (k.meter)),this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=_nullishCoalesce(e.logger, () => (V))}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of _nullishCoalesce(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(_nullishCoalesce(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((r,i)=>r-i),o=Math.ceil(t/100*n.length)-1;return _nullishCoalesce(n[o], () => (0))}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((r,i)=>r+i,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Co(o,e,t,this.name,r),To(o,e,n.mean,n.p95,n.p99,this.name,r)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Oo(o,e,this.name,r),t&&wo(o,e,this.name,r),vo(o,e,n.rate,this.name,r)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&_optionalChain([e, 'optionalAccess', _52 => _52.tokens])){let{promptTokens:n,completionTokens:o,totalTokens:r,thoughtsTokens:i}=e.tokens;n&&Ae(t,"input",n,this.name,e.model),o&&Ae(t,"output",o,this.name,e.model),r&&Ae(t,"total",r,this.name,e.model),i&&Ae(t,"thoughts",i,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch (e2){return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch (e3){return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let r of o.content)r.type==="image"?t=!0:r.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 o of n.content)o.type==="text"&&(t+=o.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!_optionalChain([t, 'optionalAccess', _53 => _53.tokens, 'optionalAccess', _54 => _54.promptTokens]))return 0;let n=this.modelInfo.find(o=>o.name===e);return _optionalChain([n, 'optionalAccess', _55 => _55.contextWindow])?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!_optionalChain([t, 'optionalAccess', _56 => _56.tokens]))return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}estimateCostByName(e,t){if(!_optionalChain([t, 'optionalAccess', _57 => _57.tokens]))return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&ko(n,o.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;_o(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Fo(t,e,this.name,n)}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments();if(!o)return;let r=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _58 => _58.stream]), () => (!1));So(o,"chat",a,this.name,r);let{hasImages:l,hasAudio:p}=this.detectMultimodalContent(e);Do(o,l,p,this.name,r);let c=this.calculatePromptLength(e);Eo(o,c,this.name,r),Mo(o,_optionalChain([i, 'optionalAccess', _59 => _59.temperature]),_optionalChain([i, 'optionalAccess', _60 => _60.maxTokens]),this.name,r),_optionalChain([t, 'optionalAccess', _61 => _61.thinkingTokenBudget])&&_optionalChain([this, 'access', _62 => _62.modelUsage, 'optionalAccess', _63 => _63.tokens, 'optionalAccess', _64 => _64.thoughtsTokens])&&Go(o,this.modelUsage.tokens.thoughtsTokens,this.name,r);let d=this.calculateRequestSize(e);if(_t(o,"chat",d,this.name,r),n&&!a){let u=n,m=this.calculateResponseSize(u);if(Ft(o,"chat",m,this.name,r),u.results)for(let f of u.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let A=this.calculateContextWindowUsage(this.lastUsedChatModel,u.modelUsage);A>0&&Po(o,A,this.name,r);let g=this.estimateCost(this.lastUsedChatModel,u.modelUsage);g>0&&Gt(o,"chat",g,this.name,r)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let o=this.lastUsedEmbedModel,r=this.calculateRequestSize(e);_t(n,"embed",r,this.name,o);let i=this.calculateResponseSize(t);Ft(n,"embed",i,this.name,o);let a=this.estimateCostByName(o,t.modelUsage);a>0&&Gt(n,"embed",a,this.name,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),o=!1,r;try{return r=await this._chat1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("chat")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("chat",i),this.updateErrorMetrics("chat",o),o||this.recordChatMetrics(e,t,r)}}async _chat1(e,t){let n=_nullishCoalesce(_nullishCoalesce(this.getModel(e.model), () => (e.model)), () => (this.defaults.model));e.chatPrompt&&Array.isArray(e.chatPrompt)&&Dt(e.chatPrompt);let o={...this.aiImpl.getModelConfig(),...e.modelConfig};if(_optionalChain([t, 'optionalAccess', _65 => _65.thinkingTokenBudget])&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(_optionalChain([t, 'optionalAccess', _66 => _66.showThoughts])&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(_optionalChain([this, 'access', _67 => _67.modelInfo, 'access', _68 => _68.find, 'call', _69 => _69(a=>a.name===n), 'optionalAccess', _70 => _70.isExpensive])&&_optionalChain([t, 'optionalAccess', _71 => _71.useExpensiveModel])!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=_nullishCoalesce((_optionalChain([t, 'optionalAccess', _72 => _72.stream])!==void 0?t.stream:o.stream), () => (!0)),this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:_api.SpanKind.SERVER,attributes:{[C.LLM_SYSTEM]:this.name,[C.LLM_OPERATION_NAME]:"chat",[C.LLM_REQUEST_MODEL]:n,[C.LLM_REQUEST_MAX_TOKENS]:_nullishCoalesce(o.maxTokens, () => ("Not set")),[C.LLM_REQUEST_TEMPERATURE]:o.temperature,[C.LLM_REQUEST_TOP_P]:_nullishCoalesce(o.topP, () => ("Not set")),[C.LLM_REQUEST_TOP_K]:_nullishCoalesce(o.topK, () => ("Not set")),[C.LLM_REQUEST_FREQUENCY_PENALTY]:_nullishCoalesce(o.frequencyPenalty, () => ("Not set")),[C.LLM_REQUEST_PRESENCE_PENALTY]:_nullishCoalesce(o.presencePenalty, () => ("Not set")),[C.LLM_REQUEST_STOP_SEQUENCES]:_nullishCoalesce(_optionalChain([o, 'access', _73 => _73.stopSequences, 'optionalAccess', _74 => _74.join, 'call', _75 => _75(", ")]), () => ("Not set")),[C.LLM_REQUEST_LLM_IS_STREAMING]:_nullishCoalesce(o.stream, () => ("Not set"))}},_nullishCoalesce(_optionalChain([t, 'optionalAccess', _76 => _76.traceContext]), () => (_api.context.active())),async a=>await this._chat2(n,o,e,t,a)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,o,r){if(!this.aiImpl.createChatReq)throw new Error("generateChatReq not implemented");let i=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _77 => _77.debug]), () => (this.debug)),a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let p=async()=>{let[m,A]=await this.aiImpl.createChatReq(l,o);return _optionalChain([r, 'optionalAccess', _78 => _78.isRecording, 'call', _79 => _79()])&&ns(n,r,this.excludeContentFromTrace),await D({name:m.name,url:this.apiURL,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:r,abortSignal:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _80 => _80.abortSignal]), () => (this.abortSignal))},A)};i&&ge(l.chatPrompt,_optionalChain([o, 'optionalAccess', _81 => _81.debugHideSystemPrompt]),_nullishCoalesce(_optionalChain([o, 'optionalAccess', _82 => _82.logger]), () => (this.logger)));let c=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _83 => _83.rateLimiter]), () => (this.rt)),d=c?await c(p,{modelUsage:this.modelUsage}):await p();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("generateChatResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),A=h=>I=>{let x=m(I,h);if(x.sessionId=_optionalChain([o, 'optionalAccess', _84 => _84.sessionId]),!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}return this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage),_optionalChain([r, 'optionalAccess', _85 => _85.isRecording, 'call', _86 => _86()])&&Lo(x,r,this.excludeContentFromTrace),i&&Et(x,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _87 => _87.logger]), () => (this.logger))),x},g=async h=>{_optionalChain([r, 'optionalAccess', _88 => _88.isRecording, 'call', _89 => _89()])&&r.end()};return d.pipeThrough(new We(A({}),g))}if(!this.aiImpl.createChatResp)throw new Error("generateChatResp not implemented");let u=this.aiImpl.createChatResp(d);if(u.sessionId=_optionalChain([o, 'optionalAccess', _90 => _90.sessionId]),!u.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(u.modelUsage={ai:this.name,model:e,tokens:m})}return u.modelUsage&&(this.modelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage)),_optionalChain([r, 'optionalAccess', _91 => _91.isRecording, 'call', _92 => _92()])&&(Lo(u,r,this.excludeContentFromTrace),r.end()),i&&Et(u,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _93 => _93.logger]), () => (this.logger))),u}async embed(e,t){let n=performance.now(),o=!1,r;try{return r=await this._embed1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("embed")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("embed",i),this.updateErrorMetrics("embed",o),o||this.recordEmbedMetrics(e,r)}}async _embed1(e,t){let n=_nullishCoalesce(_nullishCoalesce(this.getEmbedModel(e.embedModel), () => (e.embedModel)), () => (this.defaults.embedModel));if(!n)throw new Error("No embed model defined");return this.tracer&&await _optionalChain([this, 'access', _94 => _94.tracer, 'optionalAccess', _95 => _95.startActiveSpan, 'call', _96 => _96("AI Embed Request",{kind:_api.SpanKind.SERVER,attributes:{[C.LLM_SYSTEM]:this.name,[C.LLM_OPERATION_NAME]:"embeddings",[C.LLM_REQUEST_MODEL]:n}},_nullishCoalesce(_optionalChain([t, 'optionalAccess', _97 => _97.traceContext]), () => (_api.context.active())),async o=>{try{return await this._embed2(n,e,t,o)}finally{o.end()}})]),this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("generateEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("generateEmbedResp not implemented");let r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _98 => _98.debug]), () => (this.debug)),i={...t,embedModel:e};this.lastUsedEmbedModel=e;let a=async()=>{let[c,d]=await this.aiImpl.createEmbedReq(i);return await D({name:c.name,url:this.apiURL,headers:await this.buildHeaders(c.headers),debug:r,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _99 => _99.abortSignal]), () => (this.abortSignal))},d)},l=this.rt?await this.rt(a,{modelUsage:this.embedModelUsage}):await a(),p=this.aiImpl.createEmbedResp(l);if(p.sessionId=_optionalChain([n, 'optionalAccess', _100 => _100.sessionId]),!p.modelUsage){let c=this.aiImpl.getTokenUsage();c&&(p.modelUsage={ai:this.name,model:e,tokens:c})}return this.embedModelUsage=p.modelUsage,this.recordTokenUsage(p.modelUsage),_optionalChain([o, 'optionalAccess', _101 => _101.isRecording, 'call', _102 => _102()])&&_optionalChain([p, 'access', _103 => _103.modelUsage, 'optionalAccess', _104 => _104.tokens])&&o.addEvent(j.GEN_AI_USAGE,{[C.LLM_USAGE_INPUT_TOKENS]:p.modelUsage.tokens.promptTokens,[C.LLM_USAGE_OUTPUT_TOKENS]:_nullishCoalesce(p.modelUsage.tokens.completionTokens, () => (0)),[C.LLM_USAGE_TOTAL_TOKENS]:p.modelUsage.tokens.totalTokens}),_optionalChain([o, 'optionalAccess', _105 => _105.end, 'call', _106 => _106()]),p}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?_optionalChain([this, 'access', _107 => _107.models, 'optionalAccess', _108 => _108.find, 'call', _109 => _109(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}}, _class4);function ns(s,e,t){let n=[];if(s.chatPrompt&&Array.isArray(s.chatPrompt)&&s.chatPrompt.length>0)for(let r of s.chatPrompt)switch(r.role){case"system":if(r.content){let i={};t||(i.content=r.content),e.addEvent(j.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof r.content=="string")n.push(r.content);else if(Array.isArray(r.content))for(let i of r.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=_optionalChain([r, 'access', _110 => _110.functionCalls, 'optionalAccess', _111 => _111.map, 'call', _112 => _112(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}))]);if(i&&i.length>0){let a={function_calls:JSON.stringify(i,null,2)};!t&&r.content&&(a.content=r.content),e.addEvent(j.GEN_AI_ASSISTANT_MESSAGE,a)}else if(r.content){let a={};t||(a.content=r.content),e.addEvent(j.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:r.functionId};t||(i.content=r.result),e.addEvent(j.GEN_AI_TOOL_MESSAGE,i);break}}let o={};t||(o.content=n.join(`
49
- `)),e.addEvent(j.GEN_AI_USER_MESSAGE,o)}function Lo(s,e,t){if(_optionalChain([s, 'access', _113 => _113.modelUsage, 'optionalAccess', _114 => _114.tokens])){let n=s.modelUsage.tokens.thoughtsTokens?{[C.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(j.GEN_AI_USAGE,{[C.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[C.LLM_USAGE_OUTPUT_TOKENS]:_nullishCoalesce(s.modelUsage.tokens.completionTokens, () => (0)),[C.LLM_USAGE_TOTAL_TOKENS]:s.modelUsage.tokens.totalTokens,...n})}if(s.results)for(let n=0;n<s.results.length;n++){let o=s.results[n];if(!o||!o.content&&!o.thought&&!_optionalChain([o, 'access', _115 => _115.functionCalls, 'optionalAccess', _116 => _116.length])&&!o.finishReason)continue;let r=_optionalChain([o, 'access', _117 => _117.functionCalls, 'optionalAccess', _118 => _118.map, 'call', _119 => _119(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}))]),i={};r&&r.length>0?(t||(i.content=o.content),i.tool_calls=r):t||(i.content=_nullishCoalesce(o.content, () => (""))),e.addEvent(j.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Dt(s){for(let e=0;e<s.length;e++){let t=s[e];if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if("content"in t&&typeof t.content=="string"&&t.content.trim()==="")throw new Error(`AxMessage array validation failed: Item at index ${e} has empty content`)}}function os(s){let e=new Set;for(let t of s){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 Ye=(c=>(c.Claude4Opus="claude-opus-4-20250514",c.Claude4Sonnet="claude-sonnet-4-20250514",c.Claude37Sonnet="claude-3-7-sonnet-latest",c.Claude35Sonnet="claude-3-5-sonnet-latest",c.Claude35Haiku="claude-3-5-haiku-latest",c.Claude3Opus="claude-3-opus-latest",c.Claude3Sonnet="claude-3-sonnet-20240229",c.Claude3Haiku="claude-3-haiku-20240307",c.Claude21="claude-2.1",c.ClaudeInstant12="claude-instant-1.2",c))(Ye||{}),Ut= exports.AxAIAnthropicVertexModel =(i=>(i.Claude37Sonnet="claude-3-7-sonnet",i.Claude35Haiku="claude-3-5-haiku",i.Claude35Sonnet="claude-3-5-sonnet",i.Claude35SonnetV2="claude-3-5-sonnet-v2",i.Claude3Haiku="claude-3-haiku",i.Claude3Opus="claude-3-opus",i))(Ut||{});var Ke=[{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var $o=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...w()}),rs= exports.axAIAnthropicVertexDefaultConfig =()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...w()}),Nt= (_class5 =class{constructor(e,t){;_class5.prototype.__init16.call(this);_class5.prototype.__init17.call(this);_class5.prototype.__init18.call(this);this.config=e;this.isVertex=t}getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:_nullishCoalesce(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}}__init16() {this.createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=_nullishCoalesce(_optionalChain([e, 'access', _166 => _166.modelConfig, 'optionalAccess', _167 => _167.stream]), () => (this.config.stream)),r;this.isVertex?r={name:o?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:r={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(x=>x.role==="system").map(x=>({type:"text",text:x.content,...x.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(x=>x.role!=="system"),p=ss(l),c=_optionalChain([e, 'access', _168 => _168.functions, 'optionalAccess', _169 => _169.map, 'call', _170 => _170(x=>({name:x.name,description:x.description,input_schema:x.parameters}))]),d=_nullishCoalesce(_optionalChain([e, 'access', _171 => _171.modelConfig, 'optionalAccess', _172 => _172.maxTokens]), () => (this.config.maxTokens)),u=_nullishCoalesce(_optionalChain([e, 'access', _173 => _173.modelConfig, 'optionalAccess', _174 => _174.stopSequences]), () => (this.config.stopSequences)),m=_nullishCoalesce(_optionalChain([e, 'access', _175 => _175.modelConfig, 'optionalAccess', _176 => _176.temperature]), () => (this.config.temperature)),A=_nullishCoalesce(_optionalChain([e, 'access', _177 => _177.modelConfig, 'optionalAccess', _178 => _178.topP]), () => (this.config.topP)),g=_nullishCoalesce(_optionalChain([e, 'access', _179 => _179.modelConfig, 'optionalAccess', _180 => _180.topK]), () => (this.config.topK)),f=_nullishCoalesce(_optionalChain([e, 'access', _181 => _181.modelConfig, 'optionalAccess', _182 => _182.n]), () => (this.config.n));if(f&&f>1)throw new Error("Anthropic does not support sampling (n > 1)");let h;if(_optionalChain([this, 'access', _183 => _183.config, 'access', _184 => _184.thinking, 'optionalAccess', _185 => _185.budget_tokens])&&(h=this.config.thinking),_optionalChain([t, 'optionalAccess', _186 => _186.thinkingTokenBudget])){let x=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":h=void 0;break;case"minimal":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _187 => _187.minimal]), () => (1024))};break;case"low":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _188 => _188.low]), () => (5e3))};break;case"medium":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _189 => _189.medium]), () => (1e4))};break;case"high":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _190 => _190.high]), () => (2e4))};break;case"highest":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _191 => _191.highest]), () => (32e3))};break}}let I={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...d?{max_tokens:d}:{},...u&&u.length>0?{stop_sequences:u}:{},...m&&!h?{temperature:m}:{},...A&&(!h||A>=.95)?{top_p:A}:{},...g&&!h?{top_k:g}:{},...i,...c&&c.length>0?{tools:c}:{},...o?{stream:!0}:{},...a?{system:a}:{},...h?{thinking:h}:{},messages:p};return[r,I]}}__init17() {this.createChatResp=e=>{if(e.type==="error")throw new v(e.error.message,void 0,void 0);let t=Bo(e.stop_reason),n=_optionalChain([this, 'access', _192 => _192.currentPromptConfig, 'optionalAccess', _193 => _193.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _194 => _194.currentPromptConfig, 'optionalAccess', _195 => _195.showThoughts])!==!1,o=e.content.map((r,i)=>r.type==="tool_use"?{index:i,id:r.id,functionCalls:[{id:r.id,type:"function",function:{name:r.name,params:r.input}}],finishReason:t}:(r.type==="thinking"||r.type==="redacted_thinking")&&n?{index:i,thought:r.thinking,id:e.id,finishReason:t}:{index:i,content:r.type==="text"?r.text:"",id:e.id,finishReason:t}).filter(r=>r.content!==""||r.thought!==void 0||r.functionCalls!==void 0);return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:o,remoteId:e.id}}}__init18() {this.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:r}=e;throw new v(r.message,void 0,void 0)}let o=0;if(e.type==="message_start"){let{message:r}=e,i=[{index:o,content:"",id:r.id}];return this.tokensUsed={promptTokens:_nullishCoalesce(_optionalChain([r, 'access', _196 => _196.usage, 'optionalAccess', _197 => _197.input_tokens]), () => (0)),completionTokens:_nullishCoalesce(_optionalChain([r, 'access', _198 => _198.usage, 'optionalAccess', _199 => _199.output_tokens]), () => (0)),totalTokens:(_nullishCoalesce(_optionalChain([r, 'access', _200 => _200.usage, 'optionalAccess', _201 => _201.input_tokens]), () => (0)))+(_nullishCoalesce(_optionalChain([r, 'access', _202 => _202.usage, 'optionalAccess', _203 => _203.output_tokens]), () => (0)))},{results:i}}if(e.type==="content_block_start"){let{content_block:r}=e;if(r.type==="text")return{results:[{index:o,content:r.text}]};if(r.type==="thinking")return _optionalChain([this, 'access', _204 => _204.currentPromptConfig, 'optionalAccess', _205 => _205.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _206 => _206.currentPromptConfig, 'optionalAccess', _207 => _207.showThoughts])!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="tool_use"&&typeof r.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=r.id;let i=[{id:r.id,type:"function",function:{name:r.name,params:""}}];return{results:[{index:o,functionCalls:i}]}}}if(e.type==="content_block_delta"){let{delta:r}=e;if(r.type==="text_delta")return{results:[{index:o,content:r.text}]};if(r.type==="thinking_delta")return _optionalChain([this, 'access', _208 => _208.currentPromptConfig, 'optionalAccess', _209 => _209.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _210 => _210.currentPromptConfig, 'optionalAccess', _211 => _211.showThoughts])!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="signature_delta")return{results:[{index:o,content:""}]};if(r.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)throw new Error(`invalid streaming index no id found: ${e.index}`);let a=[{id:i,type:"function",function:{name:"",params:r.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:r,usage:i}=e;return this.tokensUsed={promptTokens:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:o,content:"",finishReason:Bo(r.stop_reason)}]}}return{results:[{index:o,content:""}]}}}}, _class5),he= exports.AxAIAnthropic =class extends E{constructor({apiKey:e,projectId:t,region:n,config:o,options:r,models:i}){let a=t!==void 0&&n!==void 0,l,p;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,p=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",p=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let c={...$o(),...o},d=new Nt(c,a),u=m=>{let A=L({model:m,modelInfo:Ke,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([A, 'optionalAccess', _212 => _212.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([A, 'optionalAccess', _213 => _213.hasShowThoughts]), () => (!1)),functionCot:!0}};super(d,{name:"Anthropic",apiURL:l,headers:p,modelInfo:Ke,defaults:{model:c.model},options:r,supportFor:u,models:i})}};function ss(s){let e=s.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(o=>{let r={};return typeof o.function.params=="string"?r=JSON.parse(o.function.params):typeof o.function.params=="object"&&(r=o.function.params),{type:"tool_use",id:o.id,name:o.function.name,input:r,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return is(e)}function is(s){let e=[];for(let[t,n]of s.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&_optionalChain([s, 'access', _214 => _214.at, 'call', _215 => _215(t-1), 'optionalAccess', _216 => _216.role])==="assistant"){let o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function Bo(s){if(s)switch(s){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 Qe=(h=>(h.GPT4="gpt-4",h.GPT41="gpt-4.1",h.GPT41Mini="gpt-4.1-mini",h.GPT4O="gpt-4o",h.GPT4OMini="gpt-4o-mini",h.GPT4ChatGPT4O="chatgpt-4o-latest",h.GPT4Turbo="gpt-4-turbo",h.GPT35Turbo="gpt-3.5-turbo",h.GPT35TurboInstruct="gpt-3.5-turbo-instruct",h.GPT35TextDavinci002="text-davinci-002",h.GPT3TextBabbage002="text-babbage-002",h.GPT3TextAda001="text-ada-001",h.O1="o1",h.O1Mini="o1-mini",h.O3="o3",h.O3Mini="o3-mini",h.O4Mini="o4-mini",h))(Qe||{}),xe= exports.AxAIOpenAIEmbedModel =(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(xe||{});var fe=(x=>(x.GPT4="gpt-4",x.GPT41="gpt-4.1",x.GPT41Mini="gpt-4.1-mini",x.GPT4O="gpt-4o",x.GPT4OMini="gpt-4o-mini",x.GPT4ChatGPT4O="chatgpt-4o-latest",x.GPT4Turbo="gpt-4-turbo",x.GPT35Turbo="gpt-3.5-turbo",x.GPT35TurboInstruct="gpt-3.5-turbo-instruct",x.GPT35TextDavinci002="text-davinci-002",x.GPT3TextBabbage002="text-babbage-002",x.GPT3TextAda001="text-ada-001",x.O1Pro="o1-pro",x.O1="o1",x.O1Mini="o1-mini",x.O3Pro="o3-pro",x.O3="o3",x.O3Mini="o3-mini",x.O4Mini="o4-mini",x))(fe||{});var ye=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Lt= exports.axModelInfoOpenAIResponses =[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0}];var as=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},ce= exports.axAIOpenAIDefaultConfig =()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...w()}),$t= exports.axAIOpenAIBestConfig =()=>structuredClone({...ce(),model:"gpt-4.1"}),qt= exports.axAIOpenAICreativeConfig =()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...F()}),zt= exports.axAIOpenAIFastConfig =()=>({...ce(),model:"gpt-4.1-mini"}),Bt=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}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 o={name:"/chat/completions"},r=_optionalChain([e, 'access', _217 => _217.functions, 'optionalAccess', _218 => _218.map, 'call', _219 => _219(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}}))]),i=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=ls(e),l=_nullishCoalesce(_optionalChain([e, 'access', _220 => _220.modelConfig, 'optionalAccess', _221 => _221.frequencyPenalty]), () => (this.config.frequencyPenalty)),p=_nullishCoalesce(_optionalChain([e, 'access', _222 => _222.modelConfig, 'optionalAccess', _223 => _223.stream]), () => (this.config.stream)),c=this.config.store,d=as(n),u={model:n,messages:a,response_format:_optionalChain([this, 'access', _224 => _224.config, 'optionalAccess', _225 => _225.responseFormat])?{type:this.config.responseFormat}:void 0,tools:r,tool_choice:i,...d?{}:{max_completion_tokens:_nullishCoalesce(_optionalChain([e, 'access', _226 => _226.modelConfig, 'optionalAccess', _227 => _227.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _228 => _228.modelConfig, 'optionalAccess', _229 => _229.temperature]), () => (this.config.temperature)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _230 => _230.modelConfig, 'optionalAccess', _231 => _231.topP]), () => (this.config.topP)), () => (1)),n:_nullishCoalesce(_optionalChain([e, 'access', _232 => _232.modelConfig, 'optionalAccess', _233 => _233.n]), () => (this.config.n)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _234 => _234.modelConfig, 'optionalAccess', _235 => _235.presencePenalty]), () => (this.config.presencePenalty)),...l?{frequency_penalty:l}:{}},stop:_nullishCoalesce(_optionalChain([e, 'access', _236 => _236.modelConfig, 'optionalAccess', _237 => _237.stopSequences]), () => (this.config.stop)),logit_bias:this.config.logitBias,...p&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...c?{store:c}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(u.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(u.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}}}}}),_optionalChain([t, 'optionalAccess', _238 => _238.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":u.reasoning_effort=void 0;break;case"minimal":u.reasoning_effort="low";break;case"low":u.reasoning_effort="medium";break;case"medium":u.reasoning_effort="high";break;case"high":u.reasoning_effort="high";break;case"highest":u.reasoning_effort="high";break}return this.chatReqUpdater&&(u=this.chatReqUpdater(u)),[o,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:"/embeddings"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}createChatResp(e){let{id:t,usage:n,choices:o,error:r}=e;if(r)throw r;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:o.map(a=>{if(a.message.refusal)throw new v(a.message.refusal,e.model,e.id);let l=qo(a.finish_reason),p=_optionalChain([a, 'access', _239 => _239.message, 'access', _240 => _240.tool_calls, 'optionalAccess', _241 => _241.map, 'call', _242 => _242(({id:c,function:{arguments:d,name:u}})=>({id:c,type:"function",function:{name:u,params:d}}))]);return{index:a.index,id:`${a.index}`,content:_nullishCoalesce(a.message.content, () => (void 0)),thought:a.message.reasoning_content,annotations:a.message.annotations,functionCalls:p,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:o,choices:r}=e;this.tokensUsed=o?{promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens}:void 0;let i=t;return i.indexIdMap||(i.indexIdMap={}),{results:r.map(({index:l,delta:{content:p,role:c,refusal:d,tool_calls:u,reasoning_content:m,annotations:A},finish_reason:g})=>{if(d)throw new v(d,void 0,n);let f=qo(g),h=_optionalChain([u, 'optionalAccess', _243 => _243.map, 'call', _244 => _244(({id:I,index:x,function:{name:b,arguments:T}})=>{typeof I=="string"&&typeof x=="number"&&!i.indexIdMap[x]&&(i.indexIdMap[x]=I);let O=i.indexIdMap[x];return O?{id:O,type:"function",function:{name:b,params:T}}:null}), 'access', _245 => _245.filter, 'call', _246 => _246(I=>I!==null)]);return{index:l,content:_nullishCoalesce(p, () => (void 0)),role:c,thought:m,annotations:A,functionCalls:h,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(o=>o.embedding)}}},qo=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function ls(s){return s.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(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.image}`,details:_nullishCoalesce(o.details, () => ("auto"))}};case"audio":return{type:"input_audio",input_audio:{data:o.data,format:_nullishCoalesce(o.format, () => ("wav"))}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=_optionalChain([t, 'access', _247 => _247.functionCalls, 'optionalAccess', _248 => _248.map, 'call', _249 => _249(o=>({id:o.id,type:"function",function:{name:o.function.name,arguments:typeof o.function.params=="object"?JSON.stringify(o.function.params):o.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 M=class extends E{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r,models:i,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new Bt(t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _250 => _250.streamingUsage]), () => (!0)),a);super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:i})}},Ie= exports.AxAIOpenAI =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...ye,..._nullishCoalesce(r, () => ([]))];let i=a=>{let l=L({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _251 => _251.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _252 => _252.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:{...ce(),...t},options:n,modelInfo:r,models:o,supportFor:i}),super.setName("OpenAI")}};var zo=ce,ps= exports.axAIAzureOpenAICreativeConfig =qt,cs= exports.axAIAzureOpenAIFastConfig =zt,us= exports.axAIAzureOpenAIBestConfig =$t,be= exports.AxAIAzureOpenAI =class extends M{constructor({apiKey:e,resourceName:t,deploymentName:n,version:o="api-version=2024-02-15-preview",config:r,options:i,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 p={...zo(),...r};l=[...ye,..._nullishCoalesce(l, () => ([]))];let c=u=>{let m=L({model:u,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _253 => _253.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _254 => _254.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:p,options:i,models:a,modelInfo:l,supportFor:c});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${o}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var jt= (_class6 =class s{__init19() {this.currentServiceIndex=0}__init20() {this.serviceFailures=new Map}constructor(e,t){;_class6.prototype.__init19.call(this);_class6.prototype.__init20.call(this);if(e.length===0)throw new Error("No AI services provided.");ds(e),this.services=[...e].sort(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _255 => _255.comparator]), () => (s.metricComparator)));let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _256 => _256.debug]), () => (!0)),this.initialBackoffMs=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _257 => _257.initialBackoffMs]), () => (1e3)),this.maxBackoffMs=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _258 => _258.maxBackoffMs]), () => (32e3)),this.maxRetries=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _259 => _259.maxRetries]), () => (3))}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static __initStatic() {this.inputOrderComparator=()=>0}static __initStatic2() {this.metricComparator=(e,t)=>{let n=e.getMetrics(),o=t.getMetrics();return n.latency.chat.mean-o.latency.chat.mean}}getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,o=Date.now()-n,r=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return o>=r}handleFailure(){let t=(_nullishCoalesce(_optionalChain([this, 'access', _260 => _260.serviceFailures, 'access', _261 => _261.get, 'call', _262 => _262(this.currentService.getId()), 'optionalAccess', _263 => _263.retries]), () => (0)))+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof U))throw n;switch(n.constructor){case ne:throw n;case le:break;case X:break;case Q:break;case Y:break;case pe:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}}, _class6.__initStatic(), _class6.__initStatic2(), _class6);function ds(s){let e=s.find(o=>o.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(o=>o.key));for(let o=0;o<s.length;o++){let r=s[o];if(!r)throw new Error(`Service at index ${o} is undefined`);let i=r.getModelList();if(!i)throw new Error(`Service at index ${o} (${r.getName()}) has no model list while another service does.`);let a=new Set(i.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${o} (${r.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${o} (${r.getName()}) has extra model "${l}"`)}}var Xe=(o=>(o.CommandRPlus="command-r-plus",o.CommandR="command-r",o.Command="command",o.CommandLight="command-light",o))(Xe||{}),Ze= exports.AxAICohereEmbedModel =(o=>(o.EmbedEnglishV30="embed-english-v3.0",o.EmbedEnglishLightV30="embed-english-light-v3.0",o.EmbedMultiLingualV30="embed-multilingual-v3.0",o.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",o))(Ze||{});var Ht=[{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 Ho=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...w()}),ms= exports.axAICohereCreativeConfig =()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...F()}),Vt= (_class7 =class{constructor(e){;_class7.prototype.__init21.call(this);_class7.prototype.__init22.call(this);_class7.prototype.__init23.call(this);this.config=e}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,t){let n=e.model,o=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),i;o&&o.role==="user"&&typeof o.content=="string"&&(i=_optionalChain([o, 'optionalAccess', _273 => _273.content]));let a=gs(r),l=_optionalChain([e, 'access', _274 => _274.functions, 'optionalAccess', _275 => _275.map, 'call', _276 => _276(u=>{let m={};if(_optionalChain([u, 'access', _277 => _277.parameters, 'optionalAccess', _278 => _278.properties]))for(let[A,g]of Object.entries(u.parameters.properties))m[A]={description:g.description,type:g.type,required:_nullishCoalesce(_optionalChain([u, 'access', _279 => _279.parameters, 'access', _280 => _280.required, 'optionalAccess', _281 => _281.includes, 'call', _282 => _282(A)]), () => (!1))};return{name:u.name,description:u.description,parameter_definitions:m}})]),p=e.chatPrompt.filter(u=>u.role==="function").map(u=>{let m=_optionalChain([l, 'optionalAccess', _283 => _283.find, 'call', _284 => _284(A=>A.name===u.functionId)]);if(!m)throw new Error("Function not found");return{call:{name:m.name,parameters:m.parameter_definitions},outputs:[{result:_nullishCoalesce(u.result, () => (""))}]}}),c={name:"/chat"},d={message:i,model:n,tools:l,...p&&!i?{tool_results:p}:{},chat_history:a,max_tokens:_nullishCoalesce(_optionalChain([e, 'access', _285 => _285.modelConfig, 'optionalAccess', _286 => _286.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _287 => _287.modelConfig, 'optionalAccess', _288 => _288.temperature]), () => (this.config.temperature)),k:_nullishCoalesce(_optionalChain([e, 'access', _289 => _289.modelConfig, 'optionalAccess', _290 => _290.topK]), () => (this.config.topK)),p:_nullishCoalesce(_optionalChain([e, 'access', _291 => _291.modelConfig, 'optionalAccess', _292 => _292.topP]), () => (this.config.topP)),frequency_penalty:_nullishCoalesce(_optionalChain([e, 'access', _293 => _293.modelConfig, 'optionalAccess', _294 => _294.frequencyPenalty]), () => (this.config.frequencyPenalty)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _295 => _295.modelConfig, 'optionalAccess', _296 => _296.presencePenalty]), () => (this.config.presencePenalty)),end_sequences:this.config.endSequences,stop_sequences:_nullishCoalesce(_optionalChain([e, 'access', _297 => _297.modelConfig, 'optionalAccess', _298 => _298.stopSequences]), () => (this.config.stopSequences))};return[c,d]}__init21() {this.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"},o={model:t,texts:_nullishCoalesce(e.texts, () => ([])),input_type:"classification",truncate:""};return[n,o]}}__init22() {this.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=_optionalChain([e, 'access', _299 => _299.tool_calls, 'optionalAccess', _300 => _300.map, 'call', _301 => _301(r=>({id:r.name,type:"function",function:{name:r.name,params:r.parameters}}))])),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}}}__init23() {this.createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:_nullishCoalesce(_optionalChain([e, 'access', _302 => _302.meta, 'access', _303 => _303.billed_units, 'optionalAccess', _304 => _304.output_tokens]), () => (0)),totalTokens:_nullishCoalesce(_optionalChain([e, 'access', _305 => _305.meta, 'access', _306 => _306.billed_units, 'optionalAccess', _307 => _307.output_tokens]), () => (0))};let{results:o}=this.createChatResp(e),r=o[0];if(!r)throw new Error("No result");return r.id=_nullishCoalesce(n.generation_id, () => ("")),{results:o}}}createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}}, _class7),Re= exports.AxAICohere =class extends E{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("Cohere API key not set");let r={...Ho(),...t},i=new Vt(r);super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Ht,defaults:{model:r.model},supportFor:{functions:!0,streaming:!0},options:n,models:o})}};function gs(s){return s.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=jo(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=s.map(i=>{if(i.role==="assistant")return _optionalChain([i, 'access', _308 => _308.functionCalls, 'optionalAccess', _309 => _309.find, 'call', _310 => _310(a=>a.id===e.functionId)])}).filter(i=>i!==void 0),o=_optionalChain([jo, 'call', _311 => _311(n), 'optionalAccess', _312 => _312.at, 'call', _313 => _313(0)]);if(!o)throw new Error("Function call not found");let r=[{result:e.result}];return{role:"TOOL",tool_results:[{call:o,outputs:r}]}}default:throw new Error("Unknown role")}})}function jo(s){return _optionalChain([s, 'optionalAccess', _314 => _314.map, 'call', _315 => _315(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})])}var et=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(et||{});var Wt=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Vo=()=>structuredClone({model:"deepseek-chat",...w()}),As= exports.axAIDeepSeekCodeConfig =()=>structuredClone({model:"deepseek-coder",...F()}),Ce= exports.AxAIDeepSeek =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Vo(),...t};r=[...Wt,..._nullishCoalesce(r, () => ([]))],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:r,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},models:o}),super.setName("DeepSeek")}};var tt=(c=>(c.Gemini25Pro="gemini-2.5-pro",c.Gemini25Flash="gemini-2.5-flash",c.Gemini25FlashLite="gemini-2.5-flash-lite-preview-06-17",c.Gemini20Flash="gemini-2.0-flash",c.Gemini20FlashLite="gemini-2.0-flash-lite-preview-02-05",c.Gemini1Pro="gemini-1.0-pro",c.Gemini15Flash="gemini-1.5-flash",c.Gemini15Flash002="gemini-1.5-flash-002",c.Gemini15Flash8B="gemini-1.5-flash-8b",c.Gemini15Pro="gemini-1.5-pro",c))(tt||{}),Jt= exports.AxAIGoogleGeminiEmbedModel =(o=>(o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(Jt||{}),Yt= exports.AxAIGoogleGeminiSafetyCategory =(o=>(o.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",o.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",o.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",o.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",o))(Yt||{}),Kt= exports.AxAIGoogleGeminiSafetyThreshold =(r=>(r.BlockNone="BLOCK_NONE",r.BlockOnlyHigh="BLOCK_ONLY_HIGH",r.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",r.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",r.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",r))(Kt||{}),Wo= exports.AxAIGoogleGeminiEmbedTypes =(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))(Wo||{});var Qt=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash-lite-preview-06-17",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite-preview-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var Jo=[{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"}],Yo= exports.axAIGoogleGeminiDefaultConfig =()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Jo,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...w()}),hs= exports.axAIGoogleGeminiDefaultCreativeConfig =()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Jo,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...F()}),Xt= (_class8 =class{constructor(e,t,n,o,r){;_class8.prototype.__init24.call(this);_class8.prototype.__init25.call(this);_class8.prototype.__init26.call(this);_class8.prototype.__init27.call(this);_class8.prototype.__init28.call(this);this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=o;this.options=r;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}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}}__init24() {this.createChatReq=async(e,t)=>{let n=e.model,o=_nullishCoalesce(_optionalChain([e, 'access', _358 => _358.modelConfig, 'optionalAccess', _359 => _359.stream]), () => (this.config.stream));if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r;if(this.endpointId?r={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:r={name:o?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let g=o?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;r.name+=`${g}key=${f}`}let i=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((I,x)=>{switch(I.type){case"text":return{text:I.text};case"image":return{inlineData:{mimeType:I.mimeType,data:I.image}};default:throw new Error(`Chat prompt content type not supported (index: ${x})`)}}):[{text:g.content}]};case"assistant":{let h=[];if(g.functionCalls){if(h=g.functionCalls.map(I=>{let x=typeof I.function.params=="string"?JSON.parse(I.function.params):I.function.params;return{functionCall:{name:I.function.name,args:x}}}),!h)throw new Error("Function call is empty");return{role:"model",parts:h}}if(!g.content)throw new Error("Assistant content is empty");return h=[{text:g.content}],{role:"model",parts:h}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),p=[];e.functions&&e.functions.length>0&&p.push({function_declarations:e.functions}),_optionalChain([this, 'access', _360 => _360.options, 'optionalAccess', _361 => _361.codeExecution])&&p.push({code_execution:{}}),_optionalChain([this, 'access', _362 => _362.options, 'optionalAccess', _363 => _363.googleSearchRetrieval])&&p.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),_optionalChain([this, 'access', _364 => _364.options, 'optionalAccess', _365 => _365.googleSearch])&&p.push({google_search:{}}),_optionalChain([this, 'access', _366 => _366.options, 'optionalAccess', _367 => _367.urlContext])&&p.push({url_context:{}}),p.length===0&&(p=void 0);let c;if(e.functionCall)if(e.functionCall==="none")c={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")c={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")c={function_calling_config:{mode:"ANY"}};else{let g=_optionalChain([e, 'access', _368 => _368.functionCall, 'access', _369 => _369.function, 'optionalAccess', _370 => _370.name])?{allowedFunctionNames:[e.functionCall.function.name]}:{};c={function_calling_config:{mode:"ANY"},...g}}else p&&p.length>0&&(c={function_calling_config:{mode:"AUTO"}});let d={};if(_optionalChain([this, 'access', _371 => _371.config, 'access', _372 => _372.thinking, 'optionalAccess', _373 => _373.includeThoughts])&&(d.includeThoughts=!0),_optionalChain([this, 'access', _374 => _374.config, 'access', _375 => _375.thinking, 'optionalAccess', _376 => _376.thinkingTokenBudget])&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),_optionalChain([t, 'optionalAccess', _377 => _377.thinkingTokenBudget])){let g=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _378 => _378.minimal]), () => (200));break;case"low":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _379 => _379.low]), () => (800));break;case"medium":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _380 => _380.medium]), () => (5e3));break;case"high":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _381 => _381.high]), () => (1e4));break;case"highest":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _382 => _382.highest]), () => (24500));break}}_optionalChain([t, 'optionalAccess', _383 => _383.showThoughts])!==void 0&&_optionalChain([t, 'optionalAccess', _384 => _384.thinkingTokenBudget])!=="none"&&(d.includeThoughts=t.showThoughts);let u={maxOutputTokens:_nullishCoalesce(_optionalChain([e, 'access', _385 => _385.modelConfig, 'optionalAccess', _386 => _386.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _387 => _387.modelConfig, 'optionalAccess', _388 => _388.temperature]), () => (this.config.temperature)),topP:_nullishCoalesce(_optionalChain([e, 'access', _389 => _389.modelConfig, 'optionalAccess', _390 => _390.topP]), () => (this.config.topP)),topK:_nullishCoalesce(_optionalChain([e, 'access', _391 => _391.modelConfig, 'optionalAccess', _392 => _392.topK]), () => (this.config.topK)),frequencyPenalty:_nullishCoalesce(_optionalChain([e, 'access', _393 => _393.modelConfig, 'optionalAccess', _394 => _394.frequencyPenalty]), () => (this.config.frequencyPenalty)),candidateCount:1,stopSequences:_nullishCoalesce(_optionalChain([e, 'access', _395 => _395.modelConfig, 'optionalAccess', _396 => _396.stopSequences]), () => (this.config.stopSequences)),responseMimeType:"text/plain",...Object.keys(d).length>0?{thinkingConfig:d}:{}},m=this.config.safetySettings;return[r,{contents:l,tools:p,toolConfig:c,systemInstruction:a,generationConfig:u,safetySettings:m}]}}__init25() {this.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,o;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},o={instances:e.texts.map(r=>({content:r,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let r=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${r}`},o={requests:e.texts.map(i=>({model:`models/${t}`,content:{parts:[{text:i}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,o]}}__init26() {this.createChatResp=e=>{let t=_optionalChain([e, 'access', _397 => _397.candidates, 'optionalAccess', _398 => _398.map, 'call', _399 => _399(n=>{let o={index:0};switch(n.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new v("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new v("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new v("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new v("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new v("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new v("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new v("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new v("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new v("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return o;for(let r of n.content.parts){if("text"in r){"thought"in r&&r.thought?o.thought=r.text:o.content=r.text;continue}"functionCall"in r&&(o.functionCalls=[{id:B(),type:"function",function:{name:r.functionCall.name,params:r.functionCall.args}}])}return o})]);return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}}}__init27() {this.createChatStreamResp=e=>this.createChatResp(e)}__init28() {this.createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}}}, _class8),Te= exports.AxAIGoogleGemini =class extends E{constructor({apiKey:e,projectId:t,region:n,endpointId:o,config:r,options:i,models:a,modelInfo:l}){let p=t!==void 0&&n!==void 0,c,d;if(p){if(!e)throw new Error("GoogleGemini Vertex API key not set");let g;o?g="endpoints":g="publishers/google",c=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");c="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let u={...Yo(),...r},m=new Xt(u,p,o,e,i);l=[...Qt,..._nullishCoalesce(l, () => ([]))];let A=g=>{let f=L({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _400 => _400.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _401 => _401.hasShowThoughts]), () => (!1)),functionCot:!1}};super(m,{name:"GoogleGeminiAI",apiURL:c,headers:d,modelInfo:l,defaults:{model:u.model,embedModel:u.embedModel},options:i,supportFor:A,models:a})}};var xs=new H,we= exports.AxRateLimiterTokenUsage =class{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 _optionalChain([this, 'access', _402 => _402.options, 'optionalAccess', _403 => _403.debug])&&console.log(xs.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 nt=(o=>(o.Llama3_8B="llama3-8b-8192",o.Llama33_70B="llama-3.3-70b-versatile",o.Mixtral_8x7B="mixtral-8x7b-32768",o.Gemma2_9B="gemma2-9b-it",o))(nt||{});var Zt=[{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 fs=()=>structuredClone({model:"llama-3.3-70b-versatile",...w()}),ve= exports.AxAIGroq = (_class9 =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Groq API key not set");let i={...fs(),...t},a={...n,streamingUsage:!1};r=[...Zt,..._nullishCoalesce(r, () => ([]))];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:a,modelInfo:r,apiURL:"https://api.groq.com/openai/v1",models:o,supportFor:l});_class9.prototype.__init29.call(this);_class9.prototype.__init30.call(this);,super.setName("Groq"),this.setOptions(a)}__init29() {this.setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})}}__init30() {this.newRateLimiter=e=>{if(_optionalChain([e, 'optionalAccess', _410 => _410.rateLimiter]))return e.rateLimiter;let t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _411 => _411.tokensPerMinute]), () => (4800)),n=new we(t,t/60,{debug:_optionalChain([e, 'optionalAccess', _412 => _412.debug])});return async(r,i)=>{let a=_optionalChain([i, 'access', _413 => _413.modelUsage, 'optionalAccess', _414 => _414.tokens, 'optionalAccess', _415 => _415.totalTokens])||0;return await n.acquire(a),await r()}}}}, _class9);var en=[];var tn=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(tn||{});var Ko=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...w()}),ys= exports.axAIHuggingFaceCreativeConfig =()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...F()}),nn= (_class10 =class{constructor(e){;_class10.prototype.__init31.call(this);_class10.prototype.__init32.call(this);this.config=e}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}}__init31() {this.createChatReq=(e,t)=>{let n=e.model,o=e.functions?`Functions:
7
+ `:"")+o;break;case"id":this.currentEvent.id=o;break;case"retry":{let r=Number.parseInt(o,10);Number.isNaN(r)||(this.currentEvent.retry=r);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:""}}}}, _class2);var Tt=class{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)}},ze=class extends TransformStream{constructor(){super(new Tt)}};var Zr={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504]},es=3e4,ts=_nullishCoalesce(globalThis.TextDecoderStream, () => (ze)),U= exports.AxAIServiceError =class extends Error{constructor(t,n,o,r,i={}){super(t);this.url=n;this.requestBody=o;this.responseBody=r;this.name=this.constructor.name,this.timestamp=new Date().toISOString(),this.errorId=q(),this.context=i,this.stack=this.toString()}toString(){return[`${this.name}: ${this.message}`,`URL: ${this.url}`,`Request Body: ${JSON.stringify(this.requestBody,null,2)}`,`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
8
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},re= exports.AxAIServiceStatusError =class extends U{constructor(t,n,o,r,i,a){super(`HTTP ${t} - ${n}`,o,r,{httpStatus:t,httpStatusText:n,responseBody:i,...a});this.status=t;this.statusText=n;this.name=this.constructor.name}},Y= exports.AxAIServiceNetworkError =class extends U{constructor(t,n,o,r,i){super(`Network Error: ${t.message}`,n,o,r,{originalErrorName:t.name,originalErrorStack:t.stack,...i});this.originalError=t;this.name=this.constructor.name,this.stack=t.stack}},J= exports.AxAIServiceResponseError =class extends U{constructor(e,t,n,o){super(e,t,n,void 0,o),this.name=this.constructor.name}},W= exports.AxAIServiceStreamTerminatedError =class extends U{constructor(t,n,o,r){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...r});this.lastChunk=o;this.name=this.constructor.name}},se= exports.AxAIServiceTimeoutError =class extends U{constructor(e,t,n,o){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o}),this.name=this.constructor.name}},le= exports.AxAIServiceAbortedError =class extends U{constructor(e,t,n,o){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...o}),this.name=this.constructor.name}},Q= exports.AxAIServiceAuthenticationError =class extends U{constructor(e,t,n,o){super("Authentication failed",e,t,n,o),this.name=this.constructor.name}},O= exports.AxAIRefusalError =class extends Error{constructor(t,n,o){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=o;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=q()}toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
9
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function oo(s){try{return _optionalChain([s, 'access', _4 => _4.headers, 'access', _5 => _5.get, 'call', _6 => _6("content-type"), 'optionalAccess', _7 => _7.includes, 'call', _8 => _8("application/json")])?await s.json():await s.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function ro(s,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**s)*(.75+Math.random()*.5)}function ns(){return{startTime:Date.now(),retryCount:0}}function so(s){s.retryCount++,s.lastRetryTime=Date.now()}function io(s,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:s instanceof Y&&!(s instanceof Q)}var D=async(s,e)=>{let t={...Zr,...s.retry},n=_nullishCoalesce(s.timeout, () => (es)),o=ns(),r,i=new URL(_nullishCoalesce(process.env.PROXY, () => (s.url))),a=`${[i.pathname,s.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${i.search}`,l=new URL(a,i),p=q();if(s.validateRequest&&!await s.validateRequest(e))throw new J("Invalid request data",l.href,e,{validation:"request"});_optionalChain([s, 'access', _9 => _9.span, 'optionalAccess', _10 => _10.setAttributes, 'call', _11 => _11({"http.request.method":s.put?"PUT":"POST","url.full":l.href,"request.id":p,"request.startTime":o.startTime})]);let c=0;for(;;){let d=new AbortController;if(s.abortSignal){if(s.abortSignal.aborted)throw new le(l.href,s.abortSignal.reason,e,{metrics:o});let u=()=>{d.abort(s.abortSignal.reason||"User aborted request")};s.abortSignal.addEventListener("abort",u,{once:!0});let m=d.abort.bind(d);d.abort=A=>{s.abortSignal.removeEventListener("abort",u),m(A)}}r=setTimeout(()=>{d.abort("Request timeout")},n);try{let u=await(_nullishCoalesce(s.fetch, () => (fetch)))(l,{method:s.put?"PUT":"POST",headers:{"Content-Type":"application/json","X-Request-ID":p,"X-Retry-Count":c.toString(),...s.headers},body:JSON.stringify(e),signal:d.signal});if(clearTimeout(r),u.status===401||u.status===403){let h=await oo(u);throw new Q(l.href,e,h,{metrics:o})}if(u.status>=400&&io(new Error,u.status,c,t)){let h=ro(c,t);c++,so(o),_optionalChain([s, 'access', _12 => _12.span, 'optionalAccess', _13 => _13.addEvent, 'call', _14 => _14("retry",{attempt:c,delay:h,status:u.status,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime})]),await new Promise(y=>setTimeout(y,h));continue}if(u.status>=400){let h=await oo(u);throw new re(u.status,u.statusText,l.href,e,h,{metrics:o})}if(!s.stream){let h=await u.json();if(s.validateResponse&&!await s.validateResponse(h))throw new J("Invalid response data",l.href,e,{validation:"response"});return _optionalChain([s, 'access', _15 => _15.span, 'optionalAccess', _16 => _16.setAttributes, 'call', _17 => _17({"response.time":Date.now()-o.startTime,"response.retries":o.retryCount})]),h}if(!u.body)throw new J("Response body is null",l.href,e,{metrics:o});let m,A=0,g=new TransformStream({transform(h,y){m=h,A++,o.streamChunks=A,o.lastChunkTime=Date.now(),y.enqueue(h),_optionalChain([s, 'access', _18 => _18.span, 'optionalAccess', _19 => _19.addEvent, 'call', _20 => _20("stream.chunk",{"stream.chunks":A,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})])}}),f=!1;return new ReadableStream({start(h){let y=u.body.pipeThrough(new ts).pipeThrough(new qe).pipeThrough(g).getReader();async function x(){try{for(;;){let{done:b,value:R}=await y.read();if(b){f||(f=!0,h.close());break}if(f)break;h.enqueue(R)}}catch(b){let R=b,T={...o,streamDuration:Date.now()-o.startTime};throw R.name==="AbortError"||_optionalChain([R, 'access', _21 => _21.message, 'optionalAccess', _22 => _22.includes, 'call', _23 => _23("aborted")])?h.error(new W(l.href,e,m,{streamMetrics:T})):R instanceof TypeError&&R.message.includes("cancelled")?h.error(new W(l.href,e,m,{streamMetrics:T,cancelReason:"Stream cancelled by client"})):h.error(new Y(R,l.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:T})),R}finally{clearTimeout(r),y.releaseLock()}}x()},cancel(){f=!0}})}catch(u){if(u instanceof Error&&u.name==="AbortError")throw _optionalChain([s, 'access', _24 => _24.abortSignal, 'optionalAccess', _25 => _25.aborted])?new le(l.href,s.abortSignal.reason,e,{metrics:o}):new se(l.href,n,e,{metrics:o});if(_optionalChain([s, 'access', _26 => _26.span, 'optionalAccess', _27 => _27.isRecording, 'call', _28 => _28()])&&(s.span.recordException(u),s.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),u instanceof Y&&io(u,void 0,c,t)){let m=ro(c,t);c++,so(o),_optionalChain([s, 'access', _29 => _29.span, 'optionalAccess', _30 => _30.addEvent, 'call', _31 => _31("retry",{attempt:c,delay:m,error:u.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime})]),await new Promise(A=>setTimeout(A,m));continue}throw u instanceof U&&(u.context.metrics=o),u}finally{r!==void 0&&clearTimeout(r)}}};var _api = require('@opentelemetry/api');var E={signatureStrict:!0,tracer:void 0,meter:void 0,functionResultFormatter:s=>typeof s=="string"?s:s==null?"":JSON.stringify(s,null,2)};var N= (_class3 =class{constructor() { _class3.prototype.__init4.call(this);_class3.prototype.__init5.call(this);_class3.prototype.__init6.call(this);_class3.prototype.__init7.call(this);_class3.prototype.__init8.call(this);_class3.prototype.__init9.call(this);_class3.prototype.__init10.call(this);_class3.prototype.__init11.call(this);_class3.prototype.__init12.call(this);_class3.prototype.__init13.call(this);_class3.prototype.__init14.call(this);_class3.prototype.__init15.call(this);_class3.prototype.__init16.call(this);_class3.prototype.__init17.call(this);_class3.prototype.__init18.call(this);_class3.prototype.__init19.call(this);_class3.prototype.__init20.call(this); }__init4() {this.ANSI_WHITE_BRIGHT="\x1B[97m"}__init5() {this.ANSI_GREEN_BRIGHT="\x1B[92m"}__init6() {this.ANSI_BLUE_BRIGHT="\x1B[94m"}__init7() {this.ANSI_RED_BRIGHT="\x1B[91m"}__init8() {this.ANSI_YELLOW="\x1B[93m"}__init9() {this.ANSI_RED="\x1B[91m"}__init10() {this.ANSI_RESET="\x1B[0m"}__init11() {this.ANSI_ORANGE="\x1B[38;5;208m"}__init12() {this.ANSI_WHITE="\x1B[37m"}__init13() {this.ANSI_CYAN_BRIGHT="\x1B[96m"}__init14() {this.ANSI_MAGENTA_BRIGHT="\x1B[95m"}__init15() {this.ANSI_GRAY="\x1B[90m"}__init16() {this.ANSI_GREEN="\x1B[32m"}__init17() {this.ANSI_CYAN="\x1B[36m"}__init18() {this.ANSI_MAGENTA="\x1B[35m"}__init19() {this.ANSI_BLUE="\x1B[34m"}__init20() {this.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)}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)}}, _class3);var na=new N,ao=s=>{process.stdout.write(s)},lo=(s,e,t)=>{let n=(o,r)=>t&&r&&r in t?t[r](o):o;switch(s.role){case"system":return`${n("[ SYSTEM ]","magentaBright")}
10
+ ${n(s.content,"magenta")}`;case"function":return`${n("[ FUNCTION RESULT ]","yellow")}
11
+ ${n(_nullishCoalesce(s.result, () => ("[No result]")),"yellowDim")}`;case"user":{let o=`${n("[ USER ]","greenBright")}
12
+ `;if(typeof s.content=="string")return o+n(s.content,"green");let r=s.content.map(i=>{if(i.type==="text")return n(i.text,"green");if(i.type==="image"){let a=e?"[Image]":`[Image: ${i.image}]`;return n(a,"green")}if(i.type==="audio"){let a=e?"[Audio]":`[Audio: ${i.data}]`;return n(a,"green")}return n("[Unknown content type]","gray")});return o+r.join(`
13
+ `)}case"assistant":{let o=n("[ ASSISTANT","cyanBright");s.name&&(o+=` ${s.name}`),o+=" ]";let r=`${o}
14
+ `;return s.content&&(r+=`${n(s.content,"cyan")}
15
+ `),s.functionCalls&&s.functionCalls.length>0&&(r+=`${n("[ FUNCTION CALLS ]","yellow")}
16
+ `,s.functionCalls.forEach((i,a)=>{let l=typeof i.function.params=="string"?i.function.params:JSON.stringify(i.function.params,null,2);r+=n(`${a+1}. ${i.function.name}(${l}) [id: ${i.id}]`,"yellowDim"),a<s.functionCalls.length-1&&(r+=`
17
+ `)}),r+=`
18
+ `),!s.content&&(!s.functionCalls||s.functionCalls.length===0)&&(r+=n("[No content]","gray")),r}default:return`${n("[ UNKNOWN ]","redBright")}
19
+ ${n(JSON.stringify(s),"gray")}`}},po= exports.axCreateDefaultColorLogger =(s=ao)=>{let e=new N,t=e.gray("\u2500".repeat(60));return n=>{let o=n,r="";switch(o.name){case"ChatRequestChatPrompt":r=`${o.step>0?`
20
+ ${t}
21
+ `:""}${e.blueBright(`[ CHAT REQUEST Step ${o.step} ]`)}
22
+ ${t}
23
+ `,o.value.forEach((i,a)=>{r+=lo(i,void 0,e),a<o.value.length-1&&(r+=`
24
+ ${t}
25
+ `)}),r+=`
26
+ ${t}`;break;case"FunctionResults":r=`
27
+ ${e.yellow("[ FUNCTION RESULTS ]")}
28
+ ${t}
29
+ `,o.value.forEach((i,a)=>{r+=e.yellowDim(`Function: ${i.functionId}
30
+ Result: ${i.result}`),a<o.value.length-1&&(r+=`
31
+ ${t}
32
+ `)});break;case"ChatResponseResults":r=`
33
+ ${e.cyanBright("[ CHAT RESPONSE ]")}
34
+ ${t}
35
+ `,o.value.forEach((i,a)=>{r+=e.cyan(i.content||"[No content]"),a<o.value.length-1&&(r+=`
36
+ ${t}
37
+ `)});break;case"ChatResponseStreamingResult":{let i=o.value.delta||o.value.content||"";r=i.trim().length>0&&(i.includes("Reply:")||i.includes("\u{1F916}")||i.length>50)?`
38
+ ${e.cyanBright(i)}`:e.cyanBright(i);break}case"FunctionError":r=`
39
+ ${e.redBright(`[ FUNCTION ERROR #${o.index} ]`)}
40
+ ${t}
41
+ ${e.white(o.fixingInstructions)}
42
+ ${e.red(`Error: ${o.error}`)}`;break;case"ValidationError":r=`
43
+ ${e.redBright(`[ VALIDATION ERROR #${o.index} ]`)}
44
+ ${t}
45
+ ${e.white(o.fixingInstructions)}
46
+ ${e.red(`Error: ${o.error}`)}`;break;case"AssertionError":r=`
47
+ ${e.redBright(`[ ASSERTION ERROR #${o.index} ]`)}
48
+ ${t}
49
+ ${e.white(o.fixingInstructions)}
50
+ ${e.red(`Error: ${o.error}`)}`;break;case"ResultPickerUsed":r=`${e.greenBright("[ RESULT PICKER ]")}
51
+ ${t}
52
+ ${e.green(`Selected sample ${o.selectedIndex+1} of ${o.sampleCount} (${o.latency.toFixed(2)}ms)`)}`;break;case"Notification":r=`${e.gray(`[ NOTIFICATION ${o.id} ]`)}
53
+ ${t}
54
+ ${e.white(o.value)}`;break;case"EmbedRequest":r=`${e.orange(`[ EMBED REQUEST ${o.embedModel} ]`)}
55
+ ${t}
56
+ `,o.value.forEach((i,a)=>{r+=e.white(`Text ${a+1}: ${i.substring(0,100)}${i.length>100?"...":""}`),a<o.value.length-1&&(r+=`
57
+ ${t}
58
+ `)});break;case"EmbedResponse":r=`${e.orange(`[ EMBED RESPONSE (${o.totalEmbeddings} embeddings) ]`)}
59
+ ${t}
60
+ `,o.value.forEach((i,a)=>{r+=e.white(`Embedding ${a+1}: [${i.sample.join(", ")}${i.truncated?", ...":""}] (length: ${i.length})`),a<o.value.length-1&&(r+=`
61
+ ${t}
62
+ `)});break;default:r=e.gray(JSON.stringify(o,null,2))}s(r)}},P=po(),os= exports.axCreateDefaultTextLogger =(s=ao)=>{let e="\u2500".repeat(60);return t=>{let n=t,o="";switch(n.name){case"ChatRequestChatPrompt":o=`${n.step>0?`
63
+ ${e}
64
+ `:""}[ CHAT REQUEST Step ${n.step} ]
65
+ ${e}
66
+ `,n.value.forEach((r,i)=>{o+=lo(r),i<n.value.length-1&&(o+=`
67
+ ${e}
68
+ `)}),o+=`
69
+ ${e}`;break;case"FunctionResults":o=`
70
+ [ FUNCTION RESULTS ]
71
+ ${e}
72
+ `,n.value.forEach((r,i)=>{o+=`Function: ${r.functionId}
73
+ Result: ${r.result}`,i<n.value.length-1&&(o+=`
74
+ ${e}
75
+ `)});break;case"ChatResponseResults":o=`
76
+ [ CHAT RESPONSE ]
77
+ ${e}
78
+ `,n.value.forEach((r,i)=>{o+=r.content||"[No content]",i<n.value.length-1&&(o+=`
79
+ ${e}
80
+ `)});break;case"ChatResponseStreamingResult":{let r=n.value.delta||n.value.content||"";o=r.trim().length>0&&(r.includes("Reply:")||r.includes("\u{1F916}")||r.length>50)?`
81
+ ${r}`:r;break}case"FunctionError":o=`
82
+ [ FUNCTION ERROR #${n.index} ]
83
+ ${e}
84
+ ${n.fixingInstructions}
85
+ Error: ${n.error}`;break;case"ValidationError":o=`
86
+ [ VALIDATION ERROR #${n.index} ]
87
+ ${e}
88
+ ${n.fixingInstructions}
89
+ Error: ${n.error}`;break;case"AssertionError":o=`
90
+ [ ASSERTION ERROR #${n.index} ]
91
+ ${e}
92
+ ${n.fixingInstructions}
93
+ Error: ${n.error}`;break;case"ResultPickerUsed":o=`[ RESULT PICKER ]
94
+ ${e}
95
+ Selected sample ${n.selectedIndex+1} of ${n.sampleCount} (${n.latency.toFixed(2)}ms)`;break;case"Notification":o=`[ NOTIFICATION ${n.id} ]
96
+ ${e}
97
+ ${n.value}`;break;case"EmbedRequest":o=`[ EMBED REQUEST ${n.embedModel} ]
98
+ ${e}
99
+ `,n.value.forEach((r,i)=>{o+=`Text ${i+1}: ${r.substring(0,100)}${r.length>100?"...":""}`,i<n.value.length-1&&(o+=`
100
+ ${e}
101
+ `)});break;case"EmbedResponse":o=`[ EMBED RESPONSE (${n.totalEmbeddings} embeddings) ]
102
+ ${e}
103
+ `,n.value.forEach((r,i)=>{o+=`Embedding ${i+1}: [${r.sample.join(", ")}${r.truncated?", ...":""}] (length: ${r.length})`,i<n.value.length-1&&(o+=`
104
+ ${e}
105
+ `)});break;default:o=JSON.stringify(n,null,2)}s(o)}};var w={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"},V= exports.axSpanEvents ={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"},co= exports.AxLLMRequestTypeValues =(o=>(o.COMPLETION="completion",o.CHAT="chat",o.RERANK="rerank",o.UNKNOWN="unknown",o))(co||{}),uo= exports.AxSpanKindValues =(r=>(r.WORKFLOW="workflow",r.TASK="task",r.AGENT="agent",r.TOOL="tool",r.UNKNOWN="unknown",r))(uo||{});var vt=class{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),_optionalChain([this, 'access', _32 => _32.buffer, 'optionalAccess', _33 => _33.push, 'call', _34 => _34(n)]))}async flush(e){await _optionalChain([this, 'access', _35 => _35.doneCallback, 'optionalCall', _36 => _36(_nullishCoalesce(this.buffer, () => ([])))]),e.terminate()}},je=class extends TransformStream{constructor(e,t){super(new vt(e,t))}};var mo=(s,e,t,n=P)=>{let o=t?s.filter(i=>i.role!=="system"):[...s];n({name:"ChatRequestChatPrompt",step:e,value:o})};var go=(s,e=P)=>{if(!s.results)return;let t={name:"ChatResponseResults",value:s.results};e(t)},Ao=(s,e,t=P)=>{t({name:"ChatResponseStreamingResult",index:e,value:s})},ho=(s,e=P)=>{e({name:"FunctionResults",value:s})},xo=(s,e,t,n=P)=>{n({name:"FunctionError",index:e,fixingInstructions:t,error:s})},fo=(s,e,t,n=P)=>{n({name:"ValidationError",index:e,fixingInstructions:t,error:s})},yo=(s,e,t,n=P)=>{n({name:"AssertionError",index:e,fixingInstructions:t,error:s})},Io=(s,e,t=P)=>{t({name:"RefusalError",index:e,error:s})};var bo=(s,e,t=P)=>{t({name:"EmbedRequest",embedModel:e,value:s})},Ro=(s,e=P)=>{let t=s.slice(0,3).map(o=>({length:o.length,sample:o.slice(0,5),truncated:o.length>5})),n={name:"EmbedResponse",totalEmbeddings:s.length,value:t};e(n)},Co=(s,e,t,n=P)=>{n({name:"ResultPickerUsed",sampleCount:s,selectedIndex:e,latency:t})};var Ot=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n);e[t]=o.length>100?o.substring(0,100):o}return e},He,wo=s=>{if(He)return He;if(s)return He=rs(s),He};var rs=s=>({latencyHistogram:s.createHistogram("ax_llm_request_duration_ms",{description:"Duration of LLM requests in milliseconds",unit:"ms"}),errorCounter:s.createCounter("ax_llm_errors_total",{description:"Total number of LLM request errors"}),requestCounter:s.createCounter("ax_llm_requests_total",{description:"Total number of LLM requests"}),tokenCounter:s.createCounter("ax_llm_tokens_total",{description:"Total number of LLM tokens consumed"}),inputTokenCounter:s.createCounter("ax_llm_input_tokens_total",{description:"Total number of input/prompt tokens consumed"}),outputTokenCounter:s.createCounter("ax_llm_output_tokens_total",{description:"Total number of output/completion tokens generated"}),errorRateGauge:s.createGauge("ax_llm_error_rate",{description:"Current error rate as a percentage (0-100)"}),meanLatencyGauge:s.createGauge("ax_llm_mean_latency_ms",{description:"Mean latency of LLM requests in milliseconds",unit:"ms"}),p95LatencyGauge:s.createGauge("ax_llm_p95_latency_ms",{description:"95th percentile latency of LLM requests in milliseconds",unit:"ms"}),p99LatencyGauge:s.createGauge("ax_llm_p99_latency_ms",{description:"99th percentile latency of LLM requests in milliseconds",unit:"ms"}),streamingRequestsCounter:s.createCounter("ax_llm_streaming_requests_total",{description:"Total number of streaming LLM requests"}),functionCallsCounter:s.createCounter("ax_llm_function_calls_total",{description:"Total number of function/tool calls made"}),functionCallLatencyHistogram:s.createHistogram("ax_llm_function_call_latency_ms",{description:"Latency of function calls in milliseconds",unit:"ms"}),requestSizeHistogram:s.createHistogram("ax_llm_request_size_bytes",{description:"Size of LLM request payloads in bytes",unit:"By"}),responseSizeHistogram:s.createHistogram("ax_llm_response_size_bytes",{description:"Size of LLM response payloads in bytes",unit:"By"}),temperatureGauge:s.createGauge("ax_llm_temperature_gauge",{description:"Temperature setting used for LLM requests"}),maxTokensGauge:s.createGauge("ax_llm_max_tokens_gauge",{description:"Maximum tokens setting used for LLM requests"}),estimatedCostCounter:s.createCounter("ax_llm_estimated_cost_total",{description:"Estimated cost of LLM requests in USD",unit:"$"}),promptLengthHistogram:s.createHistogram("ax_llm_prompt_length_chars",{description:"Length of prompts in characters"}),contextWindowUsageGauge:s.createGauge("ax_llm_context_window_usage_ratio",{description:"Context window utilization ratio (0-1)"}),timeoutsCounter:s.createCounter("ax_llm_timeouts_total",{description:"Total number of timed out LLM requests"}),abortsCounter:s.createCounter("ax_llm_aborts_total",{description:"Total number of aborted LLM requests"}),thinkingBudgetUsageCounter:s.createCounter("ax_llm_thinking_budget_usage_total",{description:"Total thinking budget tokens used"}),multimodalRequestsCounter:s.createCounter("ax_llm_multimodal_requests_total",{description:"Total number of multimodal requests (with images/audio)"})}),To=(s,e,t,n,o)=>{try{if(s.latencyHistogram){let r=Ot({operation:e,ai_service:n,...o?{model:o}:{}});s.latencyHistogram.record(t,r)}}catch(r){console.warn("Failed to record latency metric:",r)}},vo=(s,e,t,n,o,r,i)=>{let a={operation:e,ai_service:r,...i?{model:i}:{}};s.meanLatencyGauge&&s.meanLatencyGauge.record(t,a),s.p95LatencyGauge&&s.p95LatencyGauge.record(n,a),s.p99LatencyGauge&&s.p99LatencyGauge.record(o,a)},Oo=(s,e,t,n)=>{try{if(s.errorCounter){let o=Ot({operation:e,ai_service:t,...n?{model:n}:{}});s.errorCounter.add(1,o)}}catch(o){console.warn("Failed to record error metric:",o)}},So=(s,e,t,n,o)=>{s.errorRateGauge&&s.errorRateGauge.record(t*100,{operation:e,ai_service:n,...o?{model:o}:{}})},ko=(s,e,t,n)=>{s.requestCounter&&s.requestCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},pe=(s,e,t,n,o)=>{try{let r=Ot({ai_service:n,...o?{model:o}:{}});s.tokenCounter&&s.tokenCounter.add(t,{token_type:e,...r}),e==="input"&&s.inputTokenCounter&&s.inputTokenCounter.add(t,r),e==="output"&&s.outputTokenCounter&&s.outputTokenCounter.add(t,r)}catch(r){console.warn("Failed to record token metric:",r)}},Eo=(s,e,t,n,o)=>{t&&s.streamingRequestsCounter&&s.streamingRequestsCounter.add(1,{operation:e,ai_service:n,...o?{model:o}:{}})},Mo=(s,e,t,n,o)=>{let r={function_name:e,...n?{ai_service:n}:{},...o?{model:o}:{}};s.functionCallsCounter&&s.functionCallsCounter.add(1,r),t&&s.functionCallLatencyHistogram&&s.functionCallLatencyHistogram.record(t,r)},St=(s,e,t,n,o)=>{s.requestSizeHistogram&&s.requestSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},kt=(s,e,t,n,o)=>{s.responseSizeHistogram&&s.responseSizeHistogram.record(t,{operation:e,ai_service:n,...o?{model:o}:{}})},_o=(s,e,t,n,o)=>{let r={...n?{ai_service:n}:{},...o?{model:o}:{}};e!==void 0&&s.temperatureGauge&&s.temperatureGauge.record(e,r),t!==void 0&&s.maxTokensGauge&&s.maxTokensGauge.record(t,r)},Et=(s,e,t,n,o)=>{s.estimatedCostCounter&&s.estimatedCostCounter.add(t,{operation:e,ai_service:n,...o?{model:o}:{}})},Po=(s,e,t,n)=>{s.promptLengthHistogram&&s.promptLengthHistogram.record(e,{ai_service:t,...n?{model:n}:{}})},Fo=(s,e,t,n)=>{s.contextWindowUsageGauge&&s.contextWindowUsageGauge.record(e,{ai_service:t,...n?{model:n}:{}})},Go=(s,e,t,n)=>{s.timeoutsCounter&&s.timeoutsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Do=(s,e,t,n)=>{s.abortsCounter&&s.abortsCounter.add(1,{operation:e,ai_service:t,...n?{model:n}:{}})},Uo=(s,e,t,n)=>{s.thinkingBudgetUsageCounter&&s.thinkingBudgetUsageCounter.add(e,{ai_service:t,...n?{model:n}:{}})},No=(s,e,t,n,o)=>{(e||t)&&s.multimodalRequestsCounter&&s.multimodalRequestsCounter.add(1,{ai_service:n,has_images:e.toString(),has_audio:t.toString(),...o?{model:o}:{}})};var v=()=>structuredClone({temperature:0,topK:40,topP:.9}),F= exports.axBaseAIDefaultCreativeConfig =()=>structuredClone({temperature:.4,topP:.7,frequencyPenalty:.2}),_= exports.AxBaseAI = (_class4 =class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:r,defaults:i,options:a={},supportFor:l,models:p}){;_class4.prototype.__init21.call(this);_class4.prototype.__init22.call(this);_class4.prototype.__init23.call(this);this.aiImpl=e;this.name=t,this.apiURL=n,this.headers=o,this.supportFor=l,this.tracer=_nullishCoalesce(a.tracer, () => (E.tracer)),this.meter=_nullishCoalesce(a.meter, () => (E.meter)),this.modelInfo=r,this.models=p,this.id=q();let c=_nullishCoalesce(this.getModel(i.model), () => (i.model)),d=_nullishCoalesce(this.getEmbedModel(i.embedModel), () => (i.embedModel));if(this.defaults={model:c,embedModel:d},!i.model||typeof i.model!="string"||i.model==="")throw new Error("No model defined");this.setOptions(a),p&&is(p)}__init21() {this.debug=!1}__init22() {this.logger=P}__init23() {this.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 wo(this.meter)}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}setOptions(e){this.debug=_nullishCoalesce(e.debug, () => (!1)),this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=_nullishCoalesce(e.tracer, () => (E.tracer)),this.meter=_nullishCoalesce(e.meter, () => (E.meter)),this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=_nullishCoalesce(e.logger, () => (P))}getOptions(){return{debug:this.debug,rateLimiter:this.rt,fetch:this.fetch,tracer:this.tracer,meter:this.meter,timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.abortSignal,logger:this.logger}}getLogger(){return this.logger}getModelList(){let e=[];for(let t of _nullishCoalesce(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(_nullishCoalesce(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((r,i)=>r-i),o=Math.ceil(t/100*n.length)-1;return _nullishCoalesce(n[o], () => (0))}updateLatencyMetrics(e,t){let n=this.metrics.latency[e];n.samples.push(t),n.samples.length>1e3&&n.samples.shift(),n.mean=n.samples.reduce((r,i)=>r+i,0)/n.samples.length,n.p95=this.calculatePercentile(n.samples,95),n.p99=this.calculatePercentile(n.samples,99);let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;To(o,e,t,this.name,r),vo(o,e,n.mean,n.p95,n.p99,this.name,r)}}updateErrorMetrics(e,t){let n=this.metrics.errors[e];n.total++,t&&n.count++,n.rate=n.count/n.total;let o=this.getMetricsInstruments();if(o){let r=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;ko(o,e,this.name,r),t&&Oo(o,e,this.name,r),So(o,e,n.rate,this.name,r)}}recordTokenUsage(e){let t=this.getMetricsInstruments();if(t&&_optionalChain([e, 'optionalAccess', _37 => _37.tokens])){let{promptTokens:n,completionTokens:o,totalTokens:r,thoughtsTokens:i}=e.tokens;n&&pe(t,"input",n,this.name,e.model),o&&pe(t,"output",o,this.name,e.model),r&&pe(t,"total",r,this.name,e.model),i&&pe(t,"thoughts",i,this.name,e.model)}}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch (e2){return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch (e3){return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let r of o.content)r.type==="image"?t=!0:r.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 o of n.content)o.type==="text"&&(t+=o.text.length)}else n.role==="function"&&n.result&&(t+=n.result.length);return t}calculateContextWindowUsage(e,t){if(!_optionalChain([t, 'optionalAccess', _38 => _38.tokens, 'optionalAccess', _39 => _39.promptTokens]))return 0;let n=this.modelInfo.find(o=>o.name===e);return _optionalChain([n, 'optionalAccess', _40 => _40.contextWindow])?t.tokens.promptTokens/n.contextWindow:0}estimateCost(e,t){if(!_optionalChain([t, 'optionalAccess', _41 => _41.tokens]))return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}estimateCostByName(e,t){if(!_optionalChain([t, 'optionalAccess', _42 => _42.tokens]))return 0;let n=this.modelInfo.find(l=>l.name===e);if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:r=0}=t.tokens,i=n.promptTokenCostPer1M||0,a=n.completionTokenCostPer1M||0;return o*i/1e6+r*a/1e6}recordFunctionCallMetrics(e,t){let n=this.getMetricsInstruments();if(!(!n||!e))for(let o of e)o&&typeof o=="object"&&"function"in o&&o.function&&typeof o.function=="object"&&"name"in o.function&&Mo(n,o.function.name,void 0,this.name,t)}recordTimeoutMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Go(t,e,this.name,n)}}recordAbortMetric(e){let t=this.getMetricsInstruments();if(t){let n=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;Do(t,e,this.name,n)}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments();if(!o)return;let r=this.lastUsedChatModel,i=this.lastUsedModelConfig,a=_nullishCoalesce(_optionalChain([i, 'optionalAccess', _43 => _43.stream]), () => (!1));Eo(o,"chat",a,this.name,r);let{hasImages:l,hasAudio:p}=this.detectMultimodalContent(e);No(o,l,p,this.name,r);let c=this.calculatePromptLength(e);Po(o,c,this.name,r),_o(o,_optionalChain([i, 'optionalAccess', _44 => _44.temperature]),_optionalChain([i, 'optionalAccess', _45 => _45.maxTokens]),this.name,r),_optionalChain([t, 'optionalAccess', _46 => _46.thinkingTokenBudget])&&_optionalChain([this, 'access', _47 => _47.modelUsage, 'optionalAccess', _48 => _48.tokens, 'optionalAccess', _49 => _49.thoughtsTokens])&&Uo(o,this.modelUsage.tokens.thoughtsTokens,this.name,r);let d=this.calculateRequestSize(e);if(St(o,"chat",d,this.name,r),n&&!a){let u=n,m=this.calculateResponseSize(u);if(kt(o,"chat",m,this.name,r),u.results)for(let f of u.results)f.functionCalls&&this.recordFunctionCallMetrics(f.functionCalls,this.lastUsedChatModel);let A=this.calculateContextWindowUsage(this.lastUsedChatModel,u.modelUsage);A>0&&Fo(o,A,this.name,r);let g=this.estimateCost(this.lastUsedChatModel,u.modelUsage);g>0&&Et(o,"chat",g,this.name,r)}}recordEmbedMetrics(e,t){let n=this.getMetricsInstruments();if(!n)return;let o=this.lastUsedEmbedModel,r=this.calculateRequestSize(e);St(n,"embed",r,this.name,o);let i=this.calculateResponseSize(t);kt(n,"embed",i,this.name,o);let a=this.estimateCostByName(o,t.modelUsage);a>0&&Et(n,"embed",a,this.name,o)}getMetrics(){return structuredClone(this.metrics)}async chat(e,t){let n=performance.now(),o=!1,r;try{return r=await this._chat1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("chat"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("chat")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("chat",i),this.updateErrorMetrics("chat",o),o||this.recordChatMetrics(e,t,r)}}async _chat1(e,t){let n=_nullishCoalesce(_nullishCoalesce(this.getModel(e.model), () => (e.model)), () => (this.defaults.model));e.chatPrompt&&Array.isArray(e.chatPrompt)&&Mt(e.chatPrompt);let o={...this.aiImpl.getModelConfig(),...e.modelConfig};if(_optionalChain([t, 'optionalAccess', _50 => _50.thinkingTokenBudget])&&!this.getFeatures(n).hasThinkingBudget)throw new Error(`Model ${n} does not support thinkingTokenBudget.`);if(_optionalChain([t, 'optionalAccess', _51 => _51.showThoughts])&&!this.getFeatures(n).hasShowThoughts)throw new Error(`Model ${n} does not support showThoughts.`);if(_optionalChain([this, 'access', _52 => _52.modelInfo, 'access', _53 => _53.find, 'call', _54 => _54(a=>a.name===n), 'optionalAccess', _55 => _55.isExpensive])&&_optionalChain([t, 'optionalAccess', _56 => _56.useExpensiveModel])!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);return o.stream=_nullishCoalesce((_optionalChain([t, 'optionalAccess', _57 => _57.stream])!==void 0?t.stream:o.stream), () => (!0)),this.getFeatures(n).streaming||(o.stream=!1),this.tracer?await this.tracer.startActiveSpan("AI Chat Request",{kind:_api.SpanKind.SERVER,attributes:{[w.LLM_SYSTEM]:this.name,[w.LLM_OPERATION_NAME]:"chat",[w.LLM_REQUEST_MODEL]:n,[w.LLM_REQUEST_MAX_TOKENS]:_nullishCoalesce(o.maxTokens, () => ("Not set")),[w.LLM_REQUEST_TEMPERATURE]:o.temperature,[w.LLM_REQUEST_TOP_P]:_nullishCoalesce(o.topP, () => ("Not set")),[w.LLM_REQUEST_TOP_K]:_nullishCoalesce(o.topK, () => ("Not set")),[w.LLM_REQUEST_FREQUENCY_PENALTY]:_nullishCoalesce(o.frequencyPenalty, () => ("Not set")),[w.LLM_REQUEST_PRESENCE_PENALTY]:_nullishCoalesce(o.presencePenalty, () => ("Not set")),[w.LLM_REQUEST_STOP_SEQUENCES]:_nullishCoalesce(_optionalChain([o, 'access', _58 => _58.stopSequences, 'optionalAccess', _59 => _59.join, 'call', _60 => _60(", ")]), () => ("Not set")),[w.LLM_REQUEST_LLM_IS_STREAMING]:_nullishCoalesce(o.stream, () => ("Not set"))}},_nullishCoalesce(_optionalChain([t, 'optionalAccess', _61 => _61.traceContext]), () => (_api.context.active())),async a=>await this._chat2(n,o,e,t,a)):await this._chat2(n,o,e,t)}cleanupFunctionSchema(e){let t={...e};if(t.parameters){let n={...t.parameters};Array.isArray(n.required)&&n.required.length===0&&delete n.required,n.properties&&Object.keys(n.properties).length===0&&delete n.properties,Object.keys(n).length===0||Object.keys(n).length===1&&n.type==="object"?delete t.parameters:t.parameters=n}return t}async _chat2(e,t,n,o,r){if(!this.aiImpl.createChatReq)throw new Error("generateChatReq not implemented");let i=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _62 => _62.debug]), () => (this.debug)),a;n.functions&&n.functions.length>0&&(a=n.functions.map(m=>this.cleanupFunctionSchema(m)));let l={...n,model:e,functions:a,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t;let p=async()=>{let[m,A]=await this.aiImpl.createChatReq(l,o);return _optionalChain([r, 'optionalAccess', _63 => _63.isRecording, 'call', _64 => _64()])&&ss(n,r,this.excludeContentFromTrace),await D({name:m.name,url:this.apiURL,headers:await this.buildHeaders(m.headers),stream:t.stream,timeout:this.timeout,debug:i,fetch:this.fetch,span:r,abortSignal:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _65 => _65.abortSignal]), () => (this.abortSignal))},A)};i&&mo(l.chatPrompt,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _66 => _66.stepIndex]), () => (0)),_optionalChain([o, 'optionalAccess', _67 => _67.debugHideSystemPrompt]),_nullishCoalesce(_optionalChain([o, 'optionalAccess', _68 => _68.logger]), () => (this.logger)));let c=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _69 => _69.rateLimiter]), () => (this.rt)),d=c?await c(p,{modelUsage:this.modelUsage}):await p();if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("generateChatResp not implemented");let m=this.aiImpl.createChatStreamResp.bind(this),A=h=>y=>{let x=m(y,h);if(x.sessionId=_optionalChain([o, 'optionalAccess', _70 => _70.sessionId]),!x.modelUsage){let b=this.aiImpl.getTokenUsage();b&&(x.modelUsage={ai:this.name,model:e,tokens:b})}if(this.modelUsage=x.modelUsage,this.recordTokenUsage(x.modelUsage),_optionalChain([r, 'optionalAccess', _71 => _71.isRecording, 'call', _72 => _72()])&&Bo(x,r,this.excludeContentFromTrace),i)for(let b of x.results)Ao(b,b.index,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _73 => _73.logger]), () => (this.logger)));return x},g=async h=>{_optionalChain([r, 'optionalAccess', _74 => _74.isRecording, 'call', _75 => _75()])&&r.end()};return d.pipeThrough(new je(A({}),g))}if(!this.aiImpl.createChatResp)throw new Error("generateChatResp not implemented");let u=this.aiImpl.createChatResp(d);if(u.sessionId=_optionalChain([o, 'optionalAccess', _76 => _76.sessionId]),!u.modelUsage){let m=this.aiImpl.getTokenUsage();m&&(u.modelUsage={ai:this.name,model:e,tokens:m})}return u.modelUsage&&(this.modelUsage=u.modelUsage,this.recordTokenUsage(u.modelUsage)),_optionalChain([r, 'optionalAccess', _77 => _77.isRecording, 'call', _78 => _78()])&&(Bo(u,r,this.excludeContentFromTrace),r.end()),i&&go(u,_nullishCoalesce(_optionalChain([o, 'optionalAccess', _79 => _79.logger]), () => (this.logger))),u}async embed(e,t){let n=performance.now(),o=!1,r;try{return r=await this._embed1(e,t),r}catch(i){throw o=!0,i instanceof Error&&(i.message.includes("timeout")||i.name==="TimeoutError"?this.recordTimeoutMetric("embed"):(i.message.includes("abort")||i.name==="AbortError")&&this.recordAbortMetric("embed")),i}finally{let i=performance.now()-n;this.updateLatencyMetrics("embed",i),this.updateErrorMetrics("embed",o),o||this.recordEmbedMetrics(e,r)}}async _embed1(e,t){let n=_nullishCoalesce(_nullishCoalesce(this.getEmbedModel(e.embedModel), () => (e.embedModel)), () => (this.defaults.embedModel));if(!n)throw new Error("No embed model defined");return this.tracer&&await _optionalChain([this, 'access', _80 => _80.tracer, 'optionalAccess', _81 => _81.startActiveSpan, 'call', _82 => _82("AI Embed Request",{kind:_api.SpanKind.SERVER,attributes:{[w.LLM_SYSTEM]:this.name,[w.LLM_OPERATION_NAME]:"embeddings",[w.LLM_REQUEST_MODEL]:n}},_nullishCoalesce(_optionalChain([t, 'optionalAccess', _83 => _83.traceContext]), () => (_api.context.active())),async o=>{try{return await this._embed2(n,e,t,o)}finally{o.end()}})]),this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("generateEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("generateEmbedResp not implemented");let r=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _84 => _84.debug]), () => (this.debug)),i={...t,embedModel:e};this.lastUsedEmbedModel=e,r&&bo(_nullishCoalesce(i.texts, () => ([])),e,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _85 => _85.logger]), () => (this.logger)));let a=async()=>{let[c,d]=await this.aiImpl.createEmbedReq(i);return await D({name:c.name,url:this.apiURL,headers:await this.buildHeaders(c.headers),debug:r,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _86 => _86.abortSignal]), () => (this.abortSignal))},d)},l=this.rt?await this.rt(a,{modelUsage:this.embedModelUsage}):await a(),p=this.aiImpl.createEmbedResp(l);if(p.sessionId=_optionalChain([n, 'optionalAccess', _87 => _87.sessionId]),!p.modelUsage){let c=this.aiImpl.getTokenUsage();c&&(p.modelUsage={ai:this.name,model:e,tokens:c})}return this.embedModelUsage=p.modelUsage,this.recordTokenUsage(p.modelUsage),_optionalChain([o, 'optionalAccess', _88 => _88.isRecording, 'call', _89 => _89()])&&_optionalChain([p, 'access', _90 => _90.modelUsage, 'optionalAccess', _91 => _91.tokens])&&o.addEvent(V.GEN_AI_USAGE,{[w.LLM_USAGE_INPUT_TOKENS]:p.modelUsage.tokens.promptTokens,[w.LLM_USAGE_OUTPUT_TOKENS]:_nullishCoalesce(p.modelUsage.tokens.completionTokens, () => (0)),[w.LLM_USAGE_TOTAL_TOKENS]:p.modelUsage.tokens.totalTokens}),r&&Ro(p.embeddings,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _92 => _92.logger]), () => (this.logger))),_optionalChain([o, 'optionalAccess', _93 => _93.end, 'call', _94 => _94()]),p}async buildHeaders(e={}){return{...e,...await this.headers()}}getModelByKey(e){return e?_optionalChain([this, 'access', _95 => _95.models, 'optionalAccess', _96 => _96.find, 'call', _97 => _97(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}}, _class4);function ss(s,e,t){let n=[];if(s.chatPrompt&&Array.isArray(s.chatPrompt)&&s.chatPrompt.length>0)for(let r of s.chatPrompt)switch(r.role){case"system":if(r.content){let i={};t||(i.content=r.content),e.addEvent(V.GEN_AI_SYSTEM_MESSAGE,i)}break;case"user":if(typeof r.content=="string")n.push(r.content);else if(Array.isArray(r.content))for(let i of r.content)i.type==="text"&&n.push(i.text);break;case"assistant":{let i=_optionalChain([r, 'access', _98 => _98.functionCalls, 'optionalAccess', _99 => _99.map, 'call', _100 => _100(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}))]);if(i&&i.length>0){let a={function_calls:JSON.stringify(i,null,2)};!t&&r.content&&(a.content=r.content),e.addEvent(V.GEN_AI_ASSISTANT_MESSAGE,a)}else if(r.content){let a={};t||(a.content=r.content),e.addEvent(V.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let i={id:r.functionId};t||(i.content=r.result),e.addEvent(V.GEN_AI_TOOL_MESSAGE,i);break}}let o={};t||(o.content=n.join(`
106
+ `)),e.addEvent(V.GEN_AI_USER_MESSAGE,o)}function Bo(s,e,t){if(_optionalChain([s, 'access', _101 => _101.modelUsage, 'optionalAccess', _102 => _102.tokens])){let n=s.modelUsage.tokens.thoughtsTokens?{[w.LLM_USAGE_THOUGHTS_TOKENS]:s.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(V.GEN_AI_USAGE,{[w.LLM_USAGE_INPUT_TOKENS]:s.modelUsage.tokens.promptTokens,[w.LLM_USAGE_OUTPUT_TOKENS]:_nullishCoalesce(s.modelUsage.tokens.completionTokens, () => (0)),[w.LLM_USAGE_TOTAL_TOKENS]:s.modelUsage.tokens.totalTokens,...n})}if(s.results)for(let n=0;n<s.results.length;n++){let o=s.results[n];if(!o||!o.content&&!o.thought&&!_optionalChain([o, 'access', _103 => _103.functionCalls, 'optionalAccess', _104 => _104.length])&&!o.finishReason)continue;let r=_optionalChain([o, 'access', _105 => _105.functionCalls, 'optionalAccess', _106 => _106.map, 'call', _107 => _107(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}))]),i={};r&&r.length>0?(t||(i.content=o.content),i.tool_calls=r):t||(i.content=_nullishCoalesce(o.content, () => (""))),e.addEvent(V.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(i,null,2)})}}function Mt(s){for(let e=0;e<s.length;e++){let t=s[e];if(!t||typeof t!="object")throw new Error(`AxMessage array validation failed: Item at index ${e} is not a valid message object`);if("content"in t&&typeof t.content=="string"&&t.content.trim()==="")throw new Error(`AxMessage array validation failed: Item at index ${e} has empty content`)}}function is(s){let e=new Set;for(let t of s){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 Ve=(c=>(c.Claude4Opus="claude-opus-4-20250514",c.Claude4Sonnet="claude-sonnet-4-20250514",c.Claude37Sonnet="claude-3-7-sonnet-latest",c.Claude35Sonnet="claude-3-5-sonnet-latest",c.Claude35Haiku="claude-3-5-haiku-latest",c.Claude3Opus="claude-3-opus-latest",c.Claude3Sonnet="claude-3-sonnet-20240229",c.Claude3Haiku="claude-3-haiku-20240307",c.Claude21="claude-2.1",c.ClaudeInstant12="claude-instant-1.2",c))(Ve||{}),_t= exports.AxAIAnthropicVertexModel =(i=>(i.Claude37Sonnet="claude-3-7-sonnet",i.Claude35Haiku="claude-3-5-haiku",i.Claude35Sonnet="claude-3-5-sonnet",i.Claude35SonnetV2="claude-3-5-sonnet-v2",i.Claude3Haiku="claude-3-haiku",i.Claude3Opus="claude-3-opus",i))(_t||{});var We=[{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:32e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:64e3,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:8192},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,maxTokens:4096},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,maxTokens:4096},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,maxTokens:4096},{name:"claude-2.1",currency:"usd",promptTokenCostPer1M:8,completionTokenCostPer1M:25,maxTokens:4096},{name:"claude-instant-1.2",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:2.24,maxTokens:4096}];var zo=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...v()}),as= exports.axAIAnthropicVertexDefaultConfig =()=>structuredClone({model:"claude-3-7-sonnet",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},...v()}),Pt= (_class5 =class{constructor(e,t){;_class5.prototype.__init24.call(this);_class5.prototype.__init25.call(this);_class5.prototype.__init26.call(this);this.config=e;this.isVertex=t}getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:_nullishCoalesce(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}}__init24() {this.createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=_nullishCoalesce(_optionalChain([e, 'access', _154 => _154.modelConfig, 'optionalAccess', _155 => _155.stream]), () => (this.config.stream)),r;this.isVertex?r={name:o?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:r={name:"/messages"};let i;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":i={tool_choice:{type:"auto"}};break;case"required":i={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)i={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let a=e.chatPrompt.filter(x=>x.role==="system").map(x=>({type:"text",text:x.content,...x.cache?{cache:{type:"ephemeral"}}:{}})),l=e.chatPrompt.filter(x=>x.role!=="system"),p=ls(l),c=_optionalChain([e, 'access', _156 => _156.functions, 'optionalAccess', _157 => _157.map, 'call', _158 => _158(x=>({name:x.name,description:x.description,input_schema:x.parameters}))]),d=_nullishCoalesce(_optionalChain([e, 'access', _159 => _159.modelConfig, 'optionalAccess', _160 => _160.maxTokens]), () => (this.config.maxTokens)),u=_nullishCoalesce(_optionalChain([e, 'access', _161 => _161.modelConfig, 'optionalAccess', _162 => _162.stopSequences]), () => (this.config.stopSequences)),m=_nullishCoalesce(_optionalChain([e, 'access', _163 => _163.modelConfig, 'optionalAccess', _164 => _164.temperature]), () => (this.config.temperature)),A=_nullishCoalesce(_optionalChain([e, 'access', _165 => _165.modelConfig, 'optionalAccess', _166 => _166.topP]), () => (this.config.topP)),g=_nullishCoalesce(_optionalChain([e, 'access', _167 => _167.modelConfig, 'optionalAccess', _168 => _168.topK]), () => (this.config.topK)),f=_nullishCoalesce(_optionalChain([e, 'access', _169 => _169.modelConfig, 'optionalAccess', _170 => _170.n]), () => (this.config.n));if(f&&f>1)throw new Error("Anthropic does not support sampling (n > 1)");let h;if(_optionalChain([this, 'access', _171 => _171.config, 'access', _172 => _172.thinking, 'optionalAccess', _173 => _173.budget_tokens])&&(h=this.config.thinking),_optionalChain([t, 'optionalAccess', _174 => _174.thinkingTokenBudget])){let x=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":h=void 0;break;case"minimal":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _175 => _175.minimal]), () => (1024))};break;case"low":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _176 => _176.low]), () => (5e3))};break;case"medium":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _177 => _177.medium]), () => (1e4))};break;case"high":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _178 => _178.high]), () => (2e4))};break;case"highest":h={type:"enabled",budget_tokens:_nullishCoalesce(_optionalChain([x, 'optionalAccess', _179 => _179.highest]), () => (32e3))};break}}let y={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...d?{max_tokens:d}:{},...u&&u.length>0?{stop_sequences:u}:{},...m&&!h?{temperature:m}:{},...A&&(!h||A>=.95)?{top_p:A}:{},...g&&!h?{top_k:g}:{},...i,...c&&c.length>0?{tools:c}:{},...o?{stream:!0}:{},...a?{system:a}:{},...h?{thinking:h}:{},messages:p};return[r,y]}}__init25() {this.createChatResp=e=>{if(e.type==="error")throw new O(e.error.message,void 0,void 0);let t=qo(e.stop_reason),n=_optionalChain([this, 'access', _180 => _180.currentPromptConfig, 'optionalAccess', _181 => _181.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _182 => _182.currentPromptConfig, 'optionalAccess', _183 => _183.showThoughts])!==!1,o=e.content.map((r,i)=>r.type==="tool_use"?{index:i,id:r.id,functionCalls:[{id:r.id,type:"function",function:{name:r.name,params:r.input}}],finishReason:t}:(r.type==="thinking"||r.type==="redacted_thinking")&&n?{index:i,thought:r.thinking,id:e.id,finishReason:t}:{index:i,content:r.type==="text"?r.text:"",id:e.id,finishReason:t}).filter(r=>r.content!==""||r.thought!==void 0||r.functionCalls!==void 0);return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens},{results:o,remoteId:e.id}}}__init26() {this.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:r}=e;throw new O(r.message,void 0,void 0)}let o=0;if(e.type==="message_start"){let{message:r}=e,i=[{index:o,content:"",id:r.id}];return this.tokensUsed={promptTokens:_nullishCoalesce(_optionalChain([r, 'access', _184 => _184.usage, 'optionalAccess', _185 => _185.input_tokens]), () => (0)),completionTokens:_nullishCoalesce(_optionalChain([r, 'access', _186 => _186.usage, 'optionalAccess', _187 => _187.output_tokens]), () => (0)),totalTokens:(_nullishCoalesce(_optionalChain([r, 'access', _188 => _188.usage, 'optionalAccess', _189 => _189.input_tokens]), () => (0)))+(_nullishCoalesce(_optionalChain([r, 'access', _190 => _190.usage, 'optionalAccess', _191 => _191.output_tokens]), () => (0)))},{results:i}}if(e.type==="content_block_start"){let{content_block:r}=e;if(r.type==="text")return{results:[{index:o,content:r.text}]};if(r.type==="thinking")return _optionalChain([this, 'access', _192 => _192.currentPromptConfig, 'optionalAccess', _193 => _193.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _194 => _194.currentPromptConfig, 'optionalAccess', _195 => _195.showThoughts])!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="tool_use"&&typeof r.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=r.id;let i=[{id:r.id,type:"function",function:{name:r.name,params:""}}];return{results:[{index:o,functionCalls:i}]}}}if(e.type==="content_block_delta"){let{delta:r}=e;if(r.type==="text_delta")return{results:[{index:o,content:r.text}]};if(r.type==="thinking_delta")return _optionalChain([this, 'access', _196 => _196.currentPromptConfig, 'optionalAccess', _197 => _197.thinkingTokenBudget])!=="none"&&_optionalChain([this, 'access', _198 => _198.currentPromptConfig, 'optionalAccess', _199 => _199.showThoughts])!==!1?{results:[{index:o,thought:r.thinking}]}:{results:[{index:o,content:""}]};if(r.type==="signature_delta")return{results:[{index:o,content:""}]};if(r.type==="input_json_delta"){let i=n.indexIdMap[e.index];if(!i)throw new Error(`invalid streaming index no id found: ${e.index}`);let a=[{id:i,type:"function",function:{name:"",params:r.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:r,usage:i}=e;return this.tokensUsed={promptTokens:0,completionTokens:i.output_tokens,totalTokens:i.output_tokens},{results:[{index:o,content:"",finishReason:qo(r.stop_reason)}]}}return{results:[{index:o,content:""}]}}}}, _class5),ce= exports.AxAIAnthropic =class extends _{constructor({apiKey:e,projectId:t,region:n,config:o,options:r,models:i}){let a=t!==void 0&&n!==void 0,l,p;if(a){if(!e)throw new Error("Anthropic Vertex API key not set");if(typeof e!="function")throw new Error("Anthropic Vertex API key must be a function for token-based authentication");l=`https://${n}-aiplatform.googleapis.com/v1/projects/${t}/locations/${n}/publishers/anthropic/`,p=async()=>({Authorization:`Bearer ${await e()}`})}else{if(!e)throw new Error("Anthropic API key not set");l="https://api.anthropic.com/v1",p=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":"prompt-caching-2024-07-31","x-api-key":typeof e=="function"?await e():e})}let c={...zo(),...o},d=new Pt(c,a),u=m=>{let A=B({model:m,modelInfo:We,models:i});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([A, 'optionalAccess', _200 => _200.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([A, 'optionalAccess', _201 => _201.hasShowThoughts]), () => (!1)),functionCot:!0}};super(d,{name:"Anthropic",apiURL:l,headers:p,modelInfo:We,defaults:{model:c.model},options:r,supportFor:u,models:i})}};function ls(s){let e=s.map(t=>{switch(t.role){case"function":return{role:"user",content:[{type:"tool_result",content:t.result,tool_use_id:t.functionId,...t.isError?{is_error:!0}:{},...t.cache?{cache:{type:"ephemeral"}}:{}}]};case"user":return typeof t.content=="string"?{role:"user",content:t.content}:{role:"user",content:t.content.map(o=>{switch(o.type){case"text":return{type:"text",text:o.text,...o.cache?{cache:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:o.mimeType,data:o.image},...o.cache?{cache:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}})};case"assistant":{let n="";return typeof t.content=="string"&&(n=t.content),typeof t.functionCalls<"u"&&(n=t.functionCalls.map(o=>{let r={};return typeof o.function.params=="string"?r=JSON.parse(o.function.params):typeof o.function.params=="object"&&(r=o.function.params),{type:"tool_use",id:o.id,name:o.function.name,input:r,...t.cache?{cache:{type:"ephemeral"}}:{}}})),{role:"assistant",content:n}}default:throw new Error("Invalid role")}});return ps(e)}function ps(s){let e=[];for(let[t,n]of s.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&_optionalChain([s, 'access', _202 => _202.at, 'call', _203 => _203(t-1), 'optionalAccess', _204 => _204.role])==="assistant"){let o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function qo(s){if(s)switch(s){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 Je=(h=>(h.GPT4="gpt-4",h.GPT41="gpt-4.1",h.GPT41Mini="gpt-4.1-mini",h.GPT4O="gpt-4o",h.GPT4OMini="gpt-4o-mini",h.GPT4ChatGPT4O="chatgpt-4o-latest",h.GPT4Turbo="gpt-4-turbo",h.GPT35Turbo="gpt-3.5-turbo",h.GPT35TurboInstruct="gpt-3.5-turbo-instruct",h.GPT35TextDavinci002="text-davinci-002",h.GPT3TextBabbage002="text-babbage-002",h.GPT3TextAda001="text-ada-001",h.O1="o1",h.O1Mini="o1-mini",h.O3="o3",h.O3Mini="o3-mini",h.O4Mini="o4-mini",h))(Je||{}),ue= exports.AxAIOpenAIEmbedModel =(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(ue||{});var de=(x=>(x.GPT4="gpt-4",x.GPT41="gpt-4.1",x.GPT41Mini="gpt-4.1-mini",x.GPT4O="gpt-4o",x.GPT4OMini="gpt-4o-mini",x.GPT4ChatGPT4O="chatgpt-4o-latest",x.GPT4Turbo="gpt-4-turbo",x.GPT35Turbo="gpt-3.5-turbo",x.GPT35TurboInstruct="gpt-3.5-turbo-instruct",x.GPT35TextDavinci002="text-davinci-002",x.GPT3TextBabbage002="text-babbage-002",x.GPT3TextAda001="text-ada-001",x.O1Pro="o1-pro",x.O1="o1",x.O1Mini="o1-mini",x.O3Pro="o3-pro",x.O3="o3",x.O3Mini="o3-mini",x.O4Mini="o4-mini",x))(de||{});var me=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:14.4},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],Ft= exports.axModelInfoOpenAIResponses =[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,hasThinkingBudget:!0,hasShowThoughts:!0,isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,hasThinkingBudget:!0,hasShowThoughts:!0}];var cs=s=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(s)||e.includes(s)},ie= exports.axAIOpenAIDefaultConfig =()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...v()}),Dt= exports.axAIOpenAIBestConfig =()=>structuredClone({...ie(),model:"gpt-4.1"}),Ut= exports.axAIOpenAICreativeConfig =()=>structuredClone({model:"gpt-4.1",embedModel:"text-embedding-3-small",...F()}),Nt= exports.axAIOpenAIFastConfig =()=>({...ie(),model:"gpt-4.1-mini"}),Gt=class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.chatReqUpdater=n}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 o={name:"/chat/completions"},r=_optionalChain([e, 'access', _205 => _205.functions, 'optionalAccess', _206 => _206.map, 'call', _207 => _207(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.parameters}}))]),i=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,a=us(e),l=_nullishCoalesce(_optionalChain([e, 'access', _208 => _208.modelConfig, 'optionalAccess', _209 => _209.frequencyPenalty]), () => (this.config.frequencyPenalty)),p=_nullishCoalesce(_optionalChain([e, 'access', _210 => _210.modelConfig, 'optionalAccess', _211 => _211.stream]), () => (this.config.stream)),c=this.config.store,d=cs(n),u={model:n,messages:a,response_format:_optionalChain([this, 'access', _212 => _212.config, 'optionalAccess', _213 => _213.responseFormat])?{type:this.config.responseFormat}:void 0,tools:r,tool_choice:i,...d?{}:{max_completion_tokens:_nullishCoalesce(_optionalChain([e, 'access', _214 => _214.modelConfig, 'optionalAccess', _215 => _215.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _216 => _216.modelConfig, 'optionalAccess', _217 => _217.temperature]), () => (this.config.temperature)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _218 => _218.modelConfig, 'optionalAccess', _219 => _219.topP]), () => (this.config.topP)), () => (1)),n:_nullishCoalesce(_optionalChain([e, 'access', _220 => _220.modelConfig, 'optionalAccess', _221 => _221.n]), () => (this.config.n)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _222 => _222.modelConfig, 'optionalAccess', _223 => _223.presencePenalty]), () => (this.config.presencePenalty)),...l?{frequency_penalty:l}:{}},stop:_nullishCoalesce(_optionalChain([e, 'access', _224 => _224.modelConfig, 'optionalAccess', _225 => _225.stopSequences]), () => (this.config.stop)),logit_bias:this.config.logitBias,...p&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...c?{store:c}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(this.config.reasoningEffort&&(u.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(u.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}}}}}),_optionalChain([t, 'optionalAccess', _226 => _226.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":u.reasoning_effort=void 0;break;case"minimal":u.reasoning_effort="low";break;case"low":u.reasoning_effort="medium";break;case"medium":u.reasoning_effort="high";break;case"high":u.reasoning_effort="high";break;case"highest":u.reasoning_effort="high";break}return this.chatReqUpdater&&(u=this.chatReqUpdater(u)),[o,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:"/embeddings"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}createChatResp(e){let{id:t,usage:n,choices:o,error:r}=e;if(r)throw r;return this.tokensUsed=n?{promptTokens:n.prompt_tokens,completionTokens:n.completion_tokens,totalTokens:n.total_tokens}:void 0,{results:o.map(a=>{if(a.message.refusal)throw new O(a.message.refusal,e.model,e.id);let l=jo(a.finish_reason),p=_optionalChain([a, 'access', _227 => _227.message, 'access', _228 => _228.tool_calls, 'optionalAccess', _229 => _229.map, 'call', _230 => _230(({id:c,function:{arguments:d,name:u}})=>({id:c,type:"function",function:{name:u,params:d}}))]);return{index:a.index,id:`${a.index}`,content:_nullishCoalesce(a.message.content, () => (void 0)),thought:a.message.reasoning_content,annotations:a.message.annotations,functionCalls:p,finishReason:l}}),remoteId:t}}createChatStreamResp(e,t){let{id:n,usage:o,choices:r}=e;this.tokensUsed=o?{promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens}:void 0;let i=t;return i.indexIdMap||(i.indexIdMap={}),{results:r.map(({index:l,delta:{content:p,role:c,refusal:d,tool_calls:u,reasoning_content:m,annotations:A},finish_reason:g})=>{if(d)throw new O(d,void 0,n);let f=jo(g),h=_optionalChain([u, 'optionalAccess', _231 => _231.map, 'call', _232 => _232(({id:y,index:x,function:{name:b,arguments:R}})=>{typeof y=="string"&&typeof x=="number"&&!i.indexIdMap[x]&&(i.indexIdMap[x]=y);let T=i.indexIdMap[x];return T?{id:T,type:"function",function:{name:b,params:R}}:null}), 'access', _233 => _233.filter, 'call', _234 => _234(y=>y!==null)]);return{index:l,content:_nullishCoalesce(p, () => (void 0)),role:c,thought:m,annotations:A,functionCalls:h,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(o=>o.embedding)}}},jo=s=>{switch(s){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function us(s){return s.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(o=>{switch(o.type){case"text":return{type:"text",text:o.text};case"image":return{type:"image_url",image_url:{url:`data:${o.mimeType};base64,${o.image}`,details:_nullishCoalesce(o.details, () => ("auto"))}};case"audio":return{type:"input_audio",input_audio:{data:o.data,format:_nullishCoalesce(o.format, () => ("wav"))}};default:throw new Error("Invalid content type")}}):t.content;return{role:"user",...t.name?{name:t.name}:{},content:n}}case"assistant":{let n=_optionalChain([t, 'access', _235 => _235.functionCalls, 'optionalAccess', _236 => _236.map, 'call', _237 => _237(o=>({id:o.id,type:"function",function:{name:o.function.name,arguments:typeof o.function.params=="object"?JSON.stringify(o.function.params):o.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 M=class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r,models:i,chatReqUpdater:a,supportFor:l}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new Gt(t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _238 => _238.streamingUsage]), () => (!0)),a);super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:i})}},ge= exports.AxAIOpenAI =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...me,..._nullishCoalesce(r, () => ([]))];let i=a=>{let l=B({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _239 => _239.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _240 => _240.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:{...ie(),...t},options:n,modelInfo:r,models:o,supportFor:i}),super.setName("OpenAI")}};var Ho=ie,ds= exports.axAIAzureOpenAICreativeConfig =Ut,ms= exports.axAIAzureOpenAIFastConfig =Nt,gs= exports.axAIAzureOpenAIBestConfig =Dt,Ae= exports.AxAIAzureOpenAI =class extends M{constructor({apiKey:e,resourceName:t,deploymentName:n,version:o="api-version=2024-02-15-preview",config:r,options:i,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 p={...Ho(),...r};l=[...me,..._nullishCoalesce(l, () => ([]))];let c=u=>{let m=B({model:u,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _241 => _241.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _242 => _242.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:p,options:i,models:a,modelInfo:l,supportFor:c});let d=t.includes("://")?t:`https://${t}.openai.azure.com/`;super.setName("Azure OpenAI"),super.setAPIURL(new URL(`/openai/deployments/${n}?api-version=${o}`,d).href),super.setHeaders(async()=>({"api-key":e}))}};var $t= (_class6 =class s{__init27() {this.currentServiceIndex=0}__init28() {this.serviceFailures=new Map}constructor(e,t){;_class6.prototype.__init27.call(this);_class6.prototype.__init28.call(this);if(e.length===0)throw new Error("No AI services provided.");As(e),this.services=[...e].sort(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _243 => _243.comparator]), () => (s.metricComparator)));let n=this.services[this.currentServiceIndex];if(n===void 0)throw new Error("Error initializing the AI services.");this.currentService=n,this.debug=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _244 => _244.debug]), () => (!0)),this.initialBackoffMs=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _245 => _245.initialBackoffMs]), () => (1e3)),this.maxBackoffMs=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _246 => _246.maxBackoffMs]), () => (32e3)),this.maxRetries=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _247 => _247.maxRetries]), () => (3))}getLastUsedChatModel(){return this.currentService.getLastUsedChatModel()}getLastUsedEmbedModel(){return this.currentService.getLastUsedEmbedModel()}getLastUsedModelConfig(){return this.currentService.getLastUsedModelConfig()}static __initStatic() {this.inputOrderComparator=()=>0}static __initStatic2() {this.metricComparator=(e,t)=>{let n=e.getMetrics(),o=t.getMetrics();return n.latency.chat.mean-o.latency.chat.mean}}getModelList(){return this.currentService.getModelList()}getNextService(){let e=this.services[++this.currentServiceIndex];return e===void 0?!1:(this.currentService=e,!0)}reset(){this.currentServiceIndex=0;let e=this.services[this.currentServiceIndex];if(e===void 0)throw new Error("No AI services provided.");this.currentService=e}getName(){return this.currentService.getName()}getId(){return this.currentService.getId()}getFeatures(e){return this.currentService.getFeatures(e)}getMetrics(){return this.currentService.getMetrics()}canRetryService(){let e=this.serviceFailures.get(this.currentService.getId());if(!e)return!0;let{retries:t,lastFailureTime:n}=e,o=Date.now()-n,r=Math.min(this.initialBackoffMs*2**t,this.maxBackoffMs);return o>=r}handleFailure(){let t=(_nullishCoalesce(_optionalChain([this, 'access', _248 => _248.serviceFailures, 'access', _249 => _249.get, 'call', _250 => _250(this.currentService.getId()), 'optionalAccess', _251 => _251.retries]), () => (0)))+1;if(this.serviceFailures.set(this.currentService.getId(),{retries:t,lastFailureTime:Date.now()}),this.debug&&console.warn(`AxBalancer: Service ${this.currentService.getName()} failed (retry ${t}/${this.maxRetries})`),t>=this.maxRetries){let n=this.getNextService();return this.debug&&console.warn(`AxBalancer: Switching to service ${this.currentService.getName()}`),n}return!0}handleSuccess(){this.serviceFailures.delete(this.currentService.getId())}async chat(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.chat(e,t);return this.handleSuccess(),n}catch(n){if(!(n instanceof U))throw n;switch(n.constructor){case Q:throw n;case re:break;case Y:break;case J:break;case W:break;case se:break;default:throw n}if(!this.handleFailure())throw n}}}async embed(e,t){for(this.reset();;){if(!this.canRetryService()){if(!this.getNextService())throw new Error("All services exhausted");continue}try{let n=await this.currentService.embed(e,t);return this.handleSuccess(),n}catch(n){if(!this.handleFailure())throw n}}}setOptions(e){this.currentService.setOptions(e)}getOptions(){return this.currentService.getOptions()}getLogger(){return this.currentService.getLogger()}}, _class6.__initStatic(), _class6.__initStatic2(), _class6);function As(s){let e=s.find(o=>o.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(o=>o.key));for(let o=0;o<s.length;o++){let r=s[o];if(!r)throw new Error(`Service at index ${o} is undefined`);let i=r.getModelList();if(!i)throw new Error(`Service at index ${o} (${r.getName()}) has no model list while another service does.`);let a=new Set(i.map(l=>l.key));for(let l of n)if(!a.has(l))throw new Error(`Service at index ${o} (${r.getName()}) is missing model "${l}"`);for(let l of a)if(!n.has(l))throw new Error(`Service at index ${o} (${r.getName()}) has extra model "${l}"`)}}var Ye=(o=>(o.CommandRPlus="command-r-plus",o.CommandR="command-r",o.Command="command",o.CommandLight="command-light",o))(Ye||{}),Ke= exports.AxAICohereEmbedModel =(o=>(o.EmbedEnglishV30="embed-english-v3.0",o.EmbedEnglishLightV30="embed-english-light-v3.0",o.EmbedMultiLingualV30="embed-multilingual-v3.0",o.EmbedMultiLingualLightV30="embed-multilingual-light-v3.0",o))(Ke||{});var Lt=[{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 Wo=()=>structuredClone({model:"command-r-plus",embedModel:"embed-english-v3.0",...v()}),hs= exports.axAICohereCreativeConfig =()=>structuredClone({model:"command-r",embedModel:"embed-english-v3.0",...F()}),Bt= (_class7 =class{constructor(e){;_class7.prototype.__init29.call(this);_class7.prototype.__init30.call(this);_class7.prototype.__init31.call(this);this.config=e}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,t){let n=e.model,o=e.chatPrompt.at(-1),r=e.chatPrompt.slice(0,-1),i;o&&o.role==="user"&&typeof o.content=="string"&&(i=_optionalChain([o, 'optionalAccess', _261 => _261.content]));let a=xs(r),l=_optionalChain([e, 'access', _262 => _262.functions, 'optionalAccess', _263 => _263.map, 'call', _264 => _264(u=>{let m={};if(_optionalChain([u, 'access', _265 => _265.parameters, 'optionalAccess', _266 => _266.properties]))for(let[A,g]of Object.entries(u.parameters.properties))m[A]={description:g.description,type:g.type,required:_nullishCoalesce(_optionalChain([u, 'access', _267 => _267.parameters, 'access', _268 => _268.required, 'optionalAccess', _269 => _269.includes, 'call', _270 => _270(A)]), () => (!1))};return{name:u.name,description:u.description,parameter_definitions:m}})]),p=e.chatPrompt.filter(u=>u.role==="function").map(u=>{let m=_optionalChain([l, 'optionalAccess', _271 => _271.find, 'call', _272 => _272(A=>A.name===u.functionId)]);if(!m)throw new Error("Function not found");return{call:{name:m.name,parameters:m.parameter_definitions},outputs:[{result:_nullishCoalesce(u.result, () => (""))}]}}),c={name:"/chat"},d={message:i,model:n,tools:l,...p&&!i?{tool_results:p}:{},chat_history:a,max_tokens:_nullishCoalesce(_optionalChain([e, 'access', _273 => _273.modelConfig, 'optionalAccess', _274 => _274.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _275 => _275.modelConfig, 'optionalAccess', _276 => _276.temperature]), () => (this.config.temperature)),k:_nullishCoalesce(_optionalChain([e, 'access', _277 => _277.modelConfig, 'optionalAccess', _278 => _278.topK]), () => (this.config.topK)),p:_nullishCoalesce(_optionalChain([e, 'access', _279 => _279.modelConfig, 'optionalAccess', _280 => _280.topP]), () => (this.config.topP)),frequency_penalty:_nullishCoalesce(_optionalChain([e, 'access', _281 => _281.modelConfig, 'optionalAccess', _282 => _282.frequencyPenalty]), () => (this.config.frequencyPenalty)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _283 => _283.modelConfig, 'optionalAccess', _284 => _284.presencePenalty]), () => (this.config.presencePenalty)),end_sequences:this.config.endSequences,stop_sequences:_nullishCoalesce(_optionalChain([e, 'access', _285 => _285.modelConfig, 'optionalAccess', _286 => _286.stopSequences]), () => (this.config.stopSequences))};return[c,d]}__init29() {this.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"},o={model:t,texts:_nullishCoalesce(e.texts, () => ([])),input_type:"classification",truncate:""};return[n,o]}}__init30() {this.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=_optionalChain([e, 'access', _287 => _287.tool_calls, 'optionalAccess', _288 => _288.map, 'call', _289 => _289(r=>({id:r.name,type:"function",function:{name:r.name,params:r.parameters}}))])),{results:[{index:0,id:e.generation_id,content:e.text,functionCalls:n,finishReason:t}],remoteId:e.response_id}}}__init31() {this.createChatStreamResp=(e,t)=>{let n=t;e.event_type==="stream-start"&&(n.generation_id=e.generation_id),this.tokensUsed={promptTokens:0,completionTokens:_nullishCoalesce(_optionalChain([e, 'access', _290 => _290.meta, 'access', _291 => _291.billed_units, 'optionalAccess', _292 => _292.output_tokens]), () => (0)),totalTokens:_nullishCoalesce(_optionalChain([e, 'access', _293 => _293.meta, 'access', _294 => _294.billed_units, 'optionalAccess', _295 => _295.output_tokens]), () => (0))};let{results:o}=this.createChatResp(e),r=o[0];if(!r)throw new Error("No result");return r.id=_nullishCoalesce(n.generation_id, () => ("")),{results:o}}}createEmbedResp(e){return{remoteId:e.id,embeddings:e.embeddings}}}, _class7),he= exports.AxAICohere =class extends _{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("Cohere API key not set");let r={...Wo(),...t},i=new Bt(r);super(i,{name:"Cohere",apiURL:"https://api.cohere.ai/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Lt,defaults:{model:r.model},supportFor:{functions:!0,streaming:!0},options:n,models:o})}};function xs(s){return s.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=Vo(e.functionCalls);return{role:"CHATBOT",message:t,tool_calls:n}}case"function":{let n=s.map(i=>{if(i.role==="assistant")return _optionalChain([i, 'access', _296 => _296.functionCalls, 'optionalAccess', _297 => _297.find, 'call', _298 => _298(a=>a.id===e.functionId)])}).filter(i=>i!==void 0),o=_optionalChain([Vo, 'call', _299 => _299(n), 'optionalAccess', _300 => _300.at, 'call', _301 => _301(0)]);if(!o)throw new Error("Function call not found");let r=[{result:e.result}];return{role:"TOOL",tool_results:[{call:o,outputs:r}]}}default:throw new Error("Unknown role")}})}function Vo(s){return _optionalChain([s, 'optionalAccess', _302 => _302.map, 'call', _303 => _303(e=>{let t=typeof e.function.params=="string"?JSON.parse(e.function.params):e.function.params;return{name:e.function.name,parameters:t}})])}var Qe=(n=>(n.DeepSeekChat="deepseek-chat",n.DeepSeekCoder="deepseek-coder",n.DeepSeekReasoner="deepseek-reasoner",n))(Qe||{});var qt=[{name:"deepseek-chat",currency:"USD",promptTokenCostPer1M:.27,completionTokenCostPer1M:1.1},{name:"deepseek-reasoner",currency:"USD",promptTokenCostPer1M:.55,completionTokenCostPer1M:2.19}];var Jo=()=>structuredClone({model:"deepseek-chat",...v()}),fs= exports.axAIDeepSeekCodeConfig =()=>structuredClone({model:"deepseek-coder",...F()}),xe= exports.AxAIDeepSeek =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("DeepSeek API key not set");let i={...Jo(),...t};r=[...qt,..._nullishCoalesce(r, () => ([]))],super({apiKey:e,config:i,options:n,apiURL:"https://api.deepseek.com",modelInfo:r,supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},models:o}),super.setName("DeepSeek")}};var Xe=(c=>(c.Gemini25Pro="gemini-2.5-pro",c.Gemini25Flash="gemini-2.5-flash",c.Gemini25FlashLite="gemini-2.5-flash-lite-preview-06-17",c.Gemini20Flash="gemini-2.0-flash",c.Gemini20FlashLite="gemini-2.0-flash-lite-preview-02-05",c.Gemini1Pro="gemini-1.0-pro",c.Gemini15Flash="gemini-1.5-flash",c.Gemini15Flash002="gemini-1.5-flash-002",c.Gemini15Flash8B="gemini-1.5-flash-8b",c.Gemini15Pro="gemini-1.5-pro",c))(Xe||{}),zt= exports.AxAIGoogleGeminiEmbedModel =(o=>(o.GeminiEmbedding="gemini-embedding-exp",o.TextEmbeddingLarge="text-embedding-large-exp-03-07",o.TextEmbedding004="text-embedding-004",o.TextEmbedding005="text-embedding-005",o))(zt||{}),jt= exports.AxAIGoogleGeminiSafetyCategory =(o=>(o.HarmCategoryHarassment="HARM_CATEGORY_HARASSMENT",o.HarmCategoryHateSpeech="HARM_CATEGORY_HATE_SPEECH",o.HarmCategorySexuallyExplicit="HARM_CATEGORY_SEXUALLY_EXPLICIT",o.HarmCategoryDangerousContent="HARM_CATEGORY_DANGEROUS_CONTENT",o))(jt||{}),Ht= exports.AxAIGoogleGeminiSafetyThreshold =(r=>(r.BlockNone="BLOCK_NONE",r.BlockOnlyHigh="BLOCK_ONLY_HIGH",r.BlockMediumAndAbove="BLOCK_MEDIUM_AND_ABOVE",r.BlockLowAndAbove="BLOCK_LOW_AND_ABOVE",r.BlockDefault="HARM_BLOCK_THRESHOLD_UNSPECIFIED",r))(Ht||{}),Yo= exports.AxAIGoogleGeminiEmbedTypes =(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))(Yo||{});var Vt=[{name:"gemini-2.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:15,completionTokenCostPer1M:3.5,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.5-flash-lite-preview-06-17",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,hasThinkingBudget:!0,hasShowThoughts:!0},{name:"gemini-2.0-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.01,completionTokenCostPer1M:.4},{name:"gemini-2.0-flash-lite-preview-02-05",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:0,completionTokenCostPer1M:0},{name:"gemini-1.5-flash",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.075,completionTokenCostPer1M:.3},{name:"gemini-1.5-flash-8b",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.0375,completionTokenCostPer1M:.15},{name:"gemini-1.5-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:1.25,completionTokenCostPer1M:5},{name:"gemini-1.0-pro",currency:"usd",characterIsToken:!1,promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5}];var Ko=[{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"}],Qo= exports.axAIGoogleGeminiDefaultConfig =()=>structuredClone({model:"gemini-2.5-flash",embedModel:"text-embedding-005",safetySettings:Ko,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...v()}),ys= exports.axAIGoogleGeminiDefaultCreativeConfig =()=>structuredClone({model:"gemini-2.0-flash",embedModel:"text-embedding-005",safetySettings:Ko,thinkingTokenBudgetLevels:{minimal:200,low:800,medium:5e3,high:1e4,highest:24500},...F()}),Wt= (_class8 =class{constructor(e,t,n,o,r){;_class8.prototype.__init32.call(this);_class8.prototype.__init33.call(this);_class8.prototype.__init34.call(this);_class8.prototype.__init35.call(this);_class8.prototype.__init36.call(this);this.config=e;this.isVertex=t;this.endpointId=n;this.apiKey=o;this.options=r;if(!this.isVertex&&this.config.autoTruncate)throw new Error("Auto truncate is not supported for GoogleGemini")}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}}__init32() {this.createChatReq=async(e,t)=>{let n=e.model,o=_nullishCoalesce(_optionalChain([e, 'access', _346 => _346.modelConfig, 'optionalAccess', _347 => _347.stream]), () => (this.config.stream));if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let r;if(this.endpointId?r={name:o?`/${this.endpointId}:streamGenerateContent?alt=sse`:`/${this.endpointId}:generateContent`}:r={name:o?`/models/${n}:streamGenerateContent?alt=sse`:`/models/${n}:generateContent`},!this.isVertex){let g=o?"&":"?",f=typeof this.apiKey=="function"?await this.apiKey():this.apiKey;r.name+=`${g}key=${f}`}let i=e.chatPrompt.filter(g=>g.role==="system").map(g=>g.content),a=i.length>0?{role:"user",parts:[{text:i.join(" ")}]}:void 0,l=e.chatPrompt.filter(g=>g.role!=="system").map((g,f)=>{switch(g.role){case"user":return{role:"user",parts:Array.isArray(g.content)?g.content.map((y,x)=>{switch(y.type){case"text":return{text:y.text};case"image":return{inlineData:{mimeType:y.mimeType,data:y.image}};default:throw new Error(`Chat prompt content type not supported (index: ${x})`)}}):[{text:g.content}]};case"assistant":{let h=[];if(g.functionCalls){if(h=g.functionCalls.map(y=>{let x=typeof y.function.params=="string"?JSON.parse(y.function.params):y.function.params;return{functionCall:{name:y.function.name,args:x}}}),!h)throw new Error("Function call is empty");return{role:"model",parts:h}}if(!g.content)throw new Error("Assistant content is empty");return h=[{text:g.content}],{role:"model",parts:h}}case"function":{if(!("functionId"in g))throw new Error(`Chat prompt functionId is empty (index: ${f})`);return{role:"user",parts:[{functionResponse:{name:g.functionId,response:{result:g.result}}}]}}default:throw new Error(`Invalid role: ${JSON.stringify(g)} (index: ${f})`)}}),p=[];e.functions&&e.functions.length>0&&p.push({function_declarations:e.functions}),_optionalChain([this, 'access', _348 => _348.options, 'optionalAccess', _349 => _349.codeExecution])&&p.push({code_execution:{}}),_optionalChain([this, 'access', _350 => _350.options, 'optionalAccess', _351 => _351.googleSearchRetrieval])&&p.push({google_search_retrieval:{dynamic_retrieval_config:this.options.googleSearchRetrieval}}),_optionalChain([this, 'access', _352 => _352.options, 'optionalAccess', _353 => _353.googleSearch])&&p.push({google_search:{}}),_optionalChain([this, 'access', _354 => _354.options, 'optionalAccess', _355 => _355.urlContext])&&p.push({url_context:{}}),p.length===0&&(p=void 0);let c;if(e.functionCall)if(e.functionCall==="none")c={function_calling_config:{mode:"NONE"}};else if(e.functionCall==="auto")c={function_calling_config:{mode:"AUTO"}};else if(e.functionCall==="required")c={function_calling_config:{mode:"ANY"}};else{let g=_optionalChain([e, 'access', _356 => _356.functionCall, 'access', _357 => _357.function, 'optionalAccess', _358 => _358.name])?{allowedFunctionNames:[e.functionCall.function.name]}:{};c={function_calling_config:{mode:"ANY"},...g}}else p&&p.length>0&&(c={function_calling_config:{mode:"AUTO"}});let d={};if(_optionalChain([this, 'access', _359 => _359.config, 'access', _360 => _360.thinking, 'optionalAccess', _361 => _361.includeThoughts])&&(d.includeThoughts=!0),_optionalChain([this, 'access', _362 => _362.config, 'access', _363 => _363.thinking, 'optionalAccess', _364 => _364.thinkingTokenBudget])&&(d.thinkingBudget=this.config.thinking.thinkingTokenBudget),_optionalChain([t, 'optionalAccess', _365 => _365.thinkingTokenBudget])){let g=this.config.thinkingTokenBudgetLevels;switch(t.thinkingTokenBudget){case"none":d.thinkingBudget=0,d.includeThoughts=!1;break;case"minimal":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _366 => _366.minimal]), () => (200));break;case"low":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _367 => _367.low]), () => (800));break;case"medium":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _368 => _368.medium]), () => (5e3));break;case"high":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _369 => _369.high]), () => (1e4));break;case"highest":d.thinkingBudget=_nullishCoalesce(_optionalChain([g, 'optionalAccess', _370 => _370.highest]), () => (24500));break}}_optionalChain([t, 'optionalAccess', _371 => _371.showThoughts])!==void 0&&_optionalChain([t, 'optionalAccess', _372 => _372.thinkingTokenBudget])!=="none"&&(d.includeThoughts=t.showThoughts);let u={maxOutputTokens:_nullishCoalesce(_optionalChain([e, 'access', _373 => _373.modelConfig, 'optionalAccess', _374 => _374.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _375 => _375.modelConfig, 'optionalAccess', _376 => _376.temperature]), () => (this.config.temperature)),topP:_nullishCoalesce(_optionalChain([e, 'access', _377 => _377.modelConfig, 'optionalAccess', _378 => _378.topP]), () => (this.config.topP)),topK:_nullishCoalesce(_optionalChain([e, 'access', _379 => _379.modelConfig, 'optionalAccess', _380 => _380.topK]), () => (this.config.topK)),frequencyPenalty:_nullishCoalesce(_optionalChain([e, 'access', _381 => _381.modelConfig, 'optionalAccess', _382 => _382.frequencyPenalty]), () => (this.config.frequencyPenalty)),candidateCount:1,stopSequences:_nullishCoalesce(_optionalChain([e, 'access', _383 => _383.modelConfig, 'optionalAccess', _384 => _384.stopSequences]), () => (this.config.stopSequences)),responseMimeType:"text/plain",...Object.keys(d).length>0?{thinkingConfig:d}:{}},m=this.config.safetySettings;return[r,{contents:l,tools:p,toolConfig:c,systemInstruction:a,generationConfig:u,safetySettings:m}]}}__init33() {this.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,o;if(this.isVertex)this.endpointId?n={name:`/${this.endpointId}:predict`}:n={name:`/models/${t}:predict`},o={instances:e.texts.map(r=>({content:r,...this.config.embedType&&{taskType:this.config.embedType}})),parameters:{autoTruncate:this.config.autoTruncate,outputDimensionality:this.config.dimensions}};else{let r=typeof this.apiKey=="function"?this.apiKey():this.apiKey;n={name:`/models/${t}:batchEmbedContents?key=${r}`},o={requests:e.texts.map(i=>({model:`models/${t}`,content:{parts:[{text:i}]},outputDimensionality:this.config.dimensions,...this.config.embedType&&{taskType:this.config.embedType}}))}}return[n,o]}}__init34() {this.createChatResp=e=>{let t=_optionalChain([e, 'access', _385 => _385.candidates, 'optionalAccess', _386 => _386.map, 'call', _387 => _387(n=>{let o={index:0};switch(n.finishReason){case"MAX_TOKENS":o.finishReason="length";break;case"STOP":o.finishReason="stop";break;case"SAFETY":throw new O("Content was blocked due to safety settings",void 0,void 0);case"RECITATION":throw new O("Content was blocked due to recitation policy",void 0,void 0);case"MALFORMED_FUNCTION_CALL":throw new O("Function call was malformed and blocked",void 0,void 0);case"UNEXPECTED_TOOL_CALL":throw new O("Unexpected tool call",void 0,void 0);case"FINISH_REASON_UNSPECIFIED":throw new O("Finish reason unspecified",void 0,void 0);case"BLOCKLIST":throw new O("Content was blocked due to blocklist",void 0,void 0);case"PROHIBITED_CONTENT":throw new O("Content was blocked due to prohibited content",void 0,void 0);case"SPII":throw new O("Content was blocked due to SPII",void 0,void 0);case"OTHER":throw new O("Other finish reason",void 0,void 0)}if(!n.content||!n.content.parts)return o;for(let r of n.content.parts){if("text"in r){"thought"in r&&r.thought?o.thought=r.text:o.content=r.text;continue}"functionCall"in r&&(o.functionCalls=[{id:q(),type:"function",function:{name:r.functionCall.name,params:r.functionCall.args}}])}return o})]);return e.usageMetadata&&(this.tokensUsed={totalTokens:e.usageMetadata.totalTokenCount,promptTokens:e.usageMetadata.promptTokenCount,completionTokens:e.usageMetadata.candidatesTokenCount,thoughtsTokens:e.usageMetadata.thoughtsTokenCount}),{results:t}}}__init35() {this.createChatStreamResp=e=>this.createChatResp(e)}__init36() {this.createEmbedResp=e=>{let t;return this.isVertex?t=e.predictions.map(n=>n.embeddings.values):t=e.embeddings.map(n=>n.values),{embeddings:t}}}}, _class8),fe= exports.AxAIGoogleGemini =class extends _{constructor({apiKey:e,projectId:t,region:n,endpointId:o,config:r,options:i,models:a,modelInfo:l}){let p=t!==void 0&&n!==void 0,c,d;if(p){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 g;o?g="endpoints":g="publishers/google",c=`https://${n==="global"?"aiplatform":`${n}-aiplatform`}.googleapis.com/v1/projects/${t}/locations/${n}/${g}`,d=async()=>({Authorization:`Bearer ${typeof e=="function"?await e():e}`})}else{if(!e)throw new Error("GoogleGemini AI API key not set");c="https://generativelanguage.googleapis.com/v1beta",d=async()=>({})}let u={...Qo(),...r},m=new Wt(u,p,o,e,i);l=[...Vt,..._nullishCoalesce(l, () => ([]))];let A=g=>{let f=B({model:g,modelInfo:l,models:a});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _388 => _388.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([f, 'optionalAccess', _389 => _389.hasShowThoughts]), () => (!1)),functionCot:!1}};super(m,{name:"GoogleGeminiAI",apiURL:c,headers:d,modelInfo:l,defaults:{model:u.model,embedModel:u.embedModel},options:i,supportFor:A,models:a})}};var Is=new N,ye= exports.AxRateLimiterTokenUsage =class{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 _optionalChain([this, 'access', _390 => _390.options, 'optionalAccess', _391 => _391.debug])&&console.log(Is.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 Ze=(o=>(o.Llama3_8B="llama3-8b-8192",o.Llama33_70B="llama-3.3-70b-versatile",o.Mixtral_8x7B="mixtral-8x7b-32768",o.Gemma2_9B="gemma2-9b-it",o))(Ze||{});var Jt=[{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 bs=()=>structuredClone({model:"llama-3.3-70b-versatile",...v()}),Ie= exports.AxAIGroq = (_class9 =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Groq API key not set");let i={...bs(),...t},a={...n,streamingUsage:!1};r=[...Jt,..._nullishCoalesce(r, () => ([]))];let l={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:a,modelInfo:r,apiURL:"https://api.groq.com/openai/v1",models:o,supportFor:l});_class9.prototype.__init37.call(this);_class9.prototype.__init38.call(this);,super.setName("Groq"),this.setOptions(a)}__init37() {this.setOptions=e=>{let t=this.newRateLimiter(e);super.setOptions({...e,rateLimiter:t})}}__init38() {this.newRateLimiter=e=>{if(_optionalChain([e, 'optionalAccess', _398 => _398.rateLimiter]))return e.rateLimiter;let t=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _399 => _399.tokensPerMinute]), () => (4800)),n=new ye(t,t/60,{debug:_optionalChain([e, 'optionalAccess', _400 => _400.debug])});return async(r,i)=>{let a=_optionalChain([i, 'access', _401 => _401.modelUsage, 'optionalAccess', _402 => _402.tokens, 'optionalAccess', _403 => _403.totalTokens])||0;return await n.acquire(a),await r()}}}}, _class9);var Yt=[];var Kt=(e=>(e.MetaLlama270BChatHF="meta-llama/Llama-2-70b-chat-hf",e))(Kt||{});var Xo=()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...v()}),Rs= exports.axAIHuggingFaceCreativeConfig =()=>structuredClone({model:"meta-llama/Llama-2-70b-chat-hf",...F()}),Qt= (_class10 =class{constructor(e){;_class10.prototype.__init39.call(this);_class10.prototype.__init40.call(this);this.config=e}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}}__init39() {this.createChatReq=(e,t)=>{let n=e.model,o=e.functions?`Functions:
50
107
  ${JSON.stringify(e.functions,null,2)}
51
- `:"",r=_optionalChain([e, 'access', _436 => _436.chatPrompt, 'optionalAccess', _437 => _437.map, 'call', _438 => _438(p=>{switch(p.role){case"user":return`User: ${p.content}`;case"system":return`System: ${p.content}`;case"function":return`Function Result: ${p.result}`;case"assistant":{let c=_optionalChain([p, 'access', _439 => _439.functionCalls, 'optionalAccess', _440 => _440.map, 'call', _441 => _441(d=>{let u=typeof d.function.params=="string"?d.function.params:JSON.stringify(d.function.params);return`${d.function.name}(${u})`}), 'access', _442 => _442.join, 'call', _443 => _443(`
108
+ `:"",r=_optionalChain([e, 'access', _424 => _424.chatPrompt, 'optionalAccess', _425 => _425.map, 'call', _426 => _426(p=>{switch(p.role){case"user":return`User: ${p.content}`;case"system":return`System: ${p.content}`;case"function":return`Function Result: ${p.result}`;case"assistant":{let c=_optionalChain([p, 'access', _427 => _427.functionCalls, 'optionalAccess', _428 => _428.map, 'call', _429 => _429(d=>{let u=typeof d.function.params=="string"?d.function.params:JSON.stringify(d.function.params);return`${d.function.name}(${u})`}), 'access', _430 => _430.join, 'call', _431 => _431(`
52
109
  `)]);return c?`Assistant: ${p.content}
53
110
  Functions:
54
- ${c}`:`Assistant: ${p.content}`}default:throw new Error("Unknown role")}}), 'access', _444 => _444.join, 'call', _445 => _445(`
55
- `)]),i=`${o} ${r}`.trim(),a={name:"/models"},l={model:n,inputs:i,parameters:{max_new_tokens:_nullishCoalesce(_optionalChain([e, 'access', _446 => _446.modelConfig, 'optionalAccess', _447 => _447.maxTokens]), () => (this.config.maxTokens)),repetition_penalty:_nullishCoalesce(_optionalChain([e, 'access', _448 => _448.modelConfig, 'optionalAccess', _449 => _449.presencePenalty]), () => (this.config.presencePenalty)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _450 => _450.modelConfig, 'optionalAccess', _451 => _451.temperature]), () => (this.config.temperature)),top_p:_nullishCoalesce(_optionalChain([e, 'access', _452 => _452.modelConfig, 'optionalAccess', _453 => _453.topP]), () => (this.config.topP)),top_k:_nullishCoalesce(_optionalChain([e, 'access', _454 => _454.modelConfig, 'optionalAccess', _455 => _455.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[a,l]}}__init32() {this.createChatResp=e=>({results:[{index:0,content:e.generated_text}]})}}, _class10),Oe= exports.AxAIHuggingFace =class extends E{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("HuggingFace API key not set");let r={...Ko(),...t},i=new nn(r);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:en,defaults:{model:r.model},options:n,supportFor:{functions:!1,streaming:!1},models:o})}};var ot=(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))(ot||{}),Qo= exports.AxAIMistralEmbedModels =(e=>(e.MistralEmbed="mistral-embed",e))(Qo||{});var on=[{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 rn=()=>structuredClone({model:"mistral-small-latest",...w(),topP:1}),Is= exports.axAIMistralBestConfig =()=>structuredClone({...rn(),model:"mistral-large-latest"}),Se= exports.AxAIMistral =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...rn(),...t};r=[...on,..._nullishCoalesce(r, () => ([]))];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},l=p=>{let{max_completion_tokens:c,messages:d,...u}=p;return{...u,messages:this.updateMessages(d),max_tokens:c}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:r,models:o,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 o=n.content.map(r=>typeof r=="object"&&r!==null&&"image_url"in r?{type:"image_url",image_url:{url:_optionalChain([r, 'access', _456 => _456.image_url, 'optionalAccess', _457 => _457.url])}}:r);t.push({...n,content:o})}else t.push(n);return t}};var sn= (_class11 =class{constructor(e={}){;_class11.prototype.__init33.call(this);this.config=e;this.config.id=_nullishCoalesce(this.config.id, () => (B()))}__init33() {this.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 _nullishCoalesce(_optionalChain([this, 'access', _458 => _458.config, 'access', _459 => _459.modelInfo, 'optionalAccess', _460 => _460.name]), () => ("mock-model"))}getLastUsedEmbedModel(){return _nullishCoalesce(_optionalChain([this, 'access', _461 => _461.config, 'access', _462 => _462.embedModelInfo, 'optionalAccess', _463 => _463.name]), () => ("mock-embed-model"))}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:_nullishCoalesce(_optionalChain([this, 'access', _464 => _464.config, 'access', _465 => _465.features, 'optionalAccess', _466 => _466.streaming]), () => (!1))}:void 0}getName(){return _nullishCoalesce(this.config.name, () => ("mock-ai-service"))}getId(){return _nullishCoalesce(this.config.id, () => ("mock-ai-service-id"))}getFeatures(e){return{functions:_nullishCoalesce(_optionalChain([this, 'access', _467 => _467.config, 'access', _468 => _468.features, 'optionalAccess', _469 => _469.functions]), () => (!1)),streaming:_nullishCoalesce(_optionalChain([this, 'access', _470 => _470.config, 'access', _471 => _471.features, 'optionalAccess', _472 => _472.streaming]), () => (!1))}}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(_nullishCoalesce(this.config.errorMessage, () => ("Mock chat error")));return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):_nullishCoalesce(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(_nullishCoalesce(this.config.errorMessage, () => ("Mock embed error")));return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):_nullishCoalesce(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 _nullishCoalesce(this.config.options, () => ({}))}getLogger(){return _nullishCoalesce(_optionalChain([this, 'access', _473 => _473.config, 'access', _474 => _474.options, 'optionalAccess', _475 => _475.logger]), () => ((e=>{process.stdout.write(e)})))}updateMetrics(e){let t=_nullishCoalesce(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((o,r)=>o+r,0)/n.length,n.length>0){let o=[...n].sort((a,l)=>a-l),r=Math.max(0,Math.floor(o.length*.95)-1);this.metrics.latency[e].p95=_nullishCoalesce(o[r], () => (t));let i=Math.max(0,Math.floor(o.length*.99)-1);this.metrics.latency[e].p99=_nullishCoalesce(o[i], () => (t))}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let o=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=o>0?this.metrics.errors[e].count/o:0}}}, _class11);var an= (_class12 =class{__init34() {this.services=new Map}constructor(e){;_class12.prototype.__init34.call(this);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:r,description:i,isInternal:a}=n;this.services.set(n.key,{service:r,description:i,isInternal:a})}else{let r=n.getModelList();if(!r)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of r){if(this.services.has(i.key)){let a=_optionalChain([this, 'access', _476 => _476.services, 'access', _477 => _477.get, 'call', _478 => _478(i.key), 'optionalAccess', _479 => _479.service]);throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${_optionalChain([a, 'optionalAccess', _480 => _480.getName, 'call', _481 => _481()])}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}getLastUsedChatModel(){return _optionalChain([this, 'access', _482 => _482.lastUsedService, 'optionalAccess', _483 => _483.getLastUsedChatModel, 'call', _484 => _484()])}getLastUsedEmbedModel(){return _optionalChain([this, 'access', _485 => _485.lastUsedService, 'optionalAccess', _486 => _486.getLastUsedEmbedModel, 'call', _487 => _487()])}getLastUsedModelConfig(){return _optionalChain([this, 'access', _488 => _488.lastUsedService, 'optionalAccess', _489 => _489.getLastUsedModelConfig, 'call', _490 => _490()])}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{model:r,...i}=e;return await o.service.chat(i,t)}return await o.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 o=this.services.get(n);if(!o)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{embedModel:r,...i}=e;return await o.service.embed(i,t)}return await o.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}}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 _nullishCoalesce(this.options, () => ({}))}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}return e?e.getLogger():t=>{process.stdout.write(t)}}setServiceEntry(e,t){this.services.set(e,t)}}, _class12);var Xo=()=>structuredClone({...w(),model:"nous-hermes2",embedModel:"all-minilm"}),bs= exports.axAIOllamaDefaultCreativeConfig =()=>structuredClone({...F(),model:"nous-hermes2",embedModel:"all-minilm"}),ke= exports.AxAIOllama =class extends M{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:o,models:r}){let i={...Xo(),...n};super({apiKey:e,options:o,config:i,apiURL:t,models:r,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1}}),super.setName("Ollama")}};var Rs=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),Me= exports.AxAIOpenAIResponsesImpl =class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}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){return e.map(n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image")return{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.image}`,details:_nullishCoalesce(n.details, () => ("auto"))}};if(n.type==="audio")return{type:"input_audio",input_audio:{data:n.data,format:_nullishCoalesce(n.format, () => ("wav"))}};let o=n;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)})}createResponsesReqInternalInput(e,t=!1){let n=[];for(let o of e){if(t&&o.role==="system")continue;let r;if(o.role==="system"||o.role==="user"||o.role==="assistant"&&o.content)if(typeof o.content=="string")r=o.content;else if(Array.isArray(o.content))r=this.mapInternalContentToResponsesInput(o.content);else{if(!(o.role==="assistant"&&!o.content&&o.functionCalls))throw new Error(`Invalid content type for role ${o.role}`);r=""}else o.role,r="";switch(o.role){case"system":n.push({type:"message",role:"system",content:r});break;case"user":n.push({type:"message",role:"user",content:r,name:o.name});break;case"assistant":if(o.content||o.functionCalls){let i={type:"message",role:"assistant",content:""};if(o.content&&(i.content=r),o.name&&(i.name=o.name),o.content&&n.push(i),o.functionCalls)for(let a of o.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:o.functionId,output:o.result});break;default:{let i=o.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,o={name:"/responses"},r=null,i=!1;if(e.chatPrompt){for(let h of e.chatPrompt)if(h.role==="system"&&typeof h.content=="string"){r=h.content,i=!0;break}}let a=_nullishCoalesce(_nullishCoalesce(r, () => (this.config.systemPrompt)), () => (null)),l=_optionalChain([e, 'access', _491 => _491.functions, 'optionalAccess', _492 => _492.map, 'call', _493 => _493(h=>({type:"function",name:h.name,description:h.description,parameters:_nullishCoalesce(h.parameters, () => ({}))}))]),p=[],c=Rs(n),d=this.config.reasoningSummary;_optionalChain([t, 'optionalAccess', _494 => _494.showThoughts])?d||(d="auto"):d=void 0;let u=this.config.reasoningEffort;if(_optionalChain([t, 'optionalAccess', _495 => _495.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":u=void 0;break;case"minimal":u="low";break;case"low":u="medium";break;case"medium":case"high":case"highest":u="high";break}let m={model:n,input:"",instructions:a,tools:_optionalChain([l, 'optionalAccess', _496 => _496.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,...c?{max_output_tokens:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _497 => _497.modelConfig, 'optionalAccess', _498 => _498.maxTokens]), () => (this.config.maxTokens)), () => (void 0))}:{temperature:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _499 => _499.modelConfig, 'optionalAccess', _500 => _500.temperature]), () => (this.config.temperature)), () => (void 0)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _501 => _501.modelConfig, 'optionalAccess', _502 => _502.topP]), () => (this.config.topP)), () => (void 0)),presence_penalty:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _503 => _503.modelConfig, 'optionalAccess', _504 => _504.presencePenalty]), () => (this.config.presencePenalty)), () => (void 0)),frequency_penalty:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _505 => _505.modelConfig, 'optionalAccess', _506 => _506.frequencyPenalty]), () => (this.config.frequencyPenalty)), () => (void 0))},stream:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _507 => _507.modelConfig, 'optionalAccess', _508 => _508.stream]), () => (this.config.stream)), () => (!1)),background:void 0,include:p.length>0?p:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...u?{reasoning:{effort:u,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let A=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(A.length>0)m.input=A;else if(e.chatPrompt&&e.chatPrompt.length===1&&_optionalChain([e, 'access', _509 => _509.chatPrompt, 'access', _510 => _510[0], 'optionalAccess', _511 => _511.role])==="user"&&_optionalChain([e, 'access', _512 => _512.chatPrompt, 'access', _513 => _513[0], 'optionalAccess', _514 => _514.content])&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(A.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let g=_nullishCoalesce(m.reasoning, () => ({}));if(this.config.reasoningEffort&&(g={...g,effort:this.config.reasoningEffort}),_optionalChain([t, 'optionalAccess', _515 => _515.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":g={};break;case"minimal":g={...g,effort:"low"};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)),[o,f]}createChatResp(e){let{id:t,output:n,usage:o}=e;o&&(this.tokensUsed={promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens});let r={};for(let i of _nullishCoalesce(n, () => ([])))switch(i.type){case"message":r.id=i.id,r.content=ln(i.content,t),r.finishReason=i.status==="completed"?"stop":"content_filter";break;case"reasoning":r.id=i.id,i.encrypted_content?r.thought=i.encrypted_content:r.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
56
- `);break;case"file_search_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],r.finishReason="function_call";break;case"web_search_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],r.finishReason="function_call";break;case"computer_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],r.finishReason="function_call";break;case"code_interpreter_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],r.finishReason="function_call";break;case"image_generation_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],r.finishReason="function_call";break;case"local_shell_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],r.finishReason="function_call";break;case"mcp_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"mcp",params:{name:i.name,args:i.args,serverLabel:i.server_label,output:i.output,error:i.error}}}],r.finishReason="function_call";break;case"function_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],r.finishReason="function_call";break}return{results:[{...r,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},o;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":o=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=ln(t.item.content,t.item.id);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 r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"file_search",params:{queries:r.queries||[],results:_optionalChain([r, 'access', _516 => _516.results, 'optionalAccess', _517 => _517.map, 'call', _518 => _518(i=>({fileId:i.file_id,filename:i.filename,score:i.score,text:i.text,attributes:i.attributes}))])}}}]}break;case"web_search_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"web_search",params:{queries:r.queries||[]}}}]}break;case"computer_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"computer_use",params:{action:r.action||{}}}}]}break;case"code_interpreter_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"code_interpreter",params:{code:r.code||"",results:r.results}}}]}break;case"image_generation_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"image_generation",params:{result:r.result}}}]}break;case"local_shell_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"local_shell",params:{action:r.action||{}}}}]}break;case"mcp_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"mcp",params:{name:r.name||"",args:r.args||"",serverLabel:r.server_label||"",output:r.output,error:r.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=ln([t.part],t.item_id);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":n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error";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,totalTokens:t.response.usage.total_tokens}),o=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":o=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":o=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:o}}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"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}},ln=(s,e)=>{let t=s.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(o=>o.refusal).join(`
57
- `);throw new v(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
58
- `)};var st=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),Cs= exports.axAIOpenAIResponsesBestConfig =()=>({...st(),model:"gpt-4o",temperature:.5}),Ts= exports.axAIOpenAIResponsesCreativeConfig =()=>({...st(),model:"gpt-4o",temperature:.9}),rt= exports.AxAIOpenAIResponsesBase =class extends E{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new Me(t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _519 => _519.streamingUsage]), () => (!0)),a),c=i;super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:c})}},Ee= exports.AxAIOpenAIResponses =class extends rt{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...Lt,..._nullishCoalesce(r, () => ([]))];let i=a=>{let l=L({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _520 => _520.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _521 => _521.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:{...st(),...t},options:n,modelInfo:r,models:o,supportFor:i})}};var it=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(it||{});var pn=[{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 at=()=>structuredClone({model:"reka-core",...w()}),ws= exports.axAIRekaBestConfig =()=>structuredClone({...at(),model:"reka-core"}),vs= exports.axAIRekaCreativeConfig =()=>structuredClone({model:"reka-core",...F()}),Os= exports.axAIRekaFastConfig =()=>({...at(),model:"reka-flash"}),cn= (_class13 =class{constructor(e){;_class13.prototype.__init35.call(this);_class13.prototype.__init36.call(this);_class13.prototype.__init37.call(this);this.config=e}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}}__init35() {this.createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o={name:"/chat/completions"},r=Ss(e),i=_nullishCoalesce(_optionalChain([e, 'access', _538 => _538.modelConfig, 'optionalAccess', _539 => _539.frequencyPenalty]), () => (this.config.frequencyPenalty)),a=_nullishCoalesce(_optionalChain([e, 'access', _540 => _540.modelConfig, 'optionalAccess', _541 => _541.stream]), () => (this.config.stream)),l={model:n,messages:r,max_tokens:_nullishCoalesce(_optionalChain([e, 'access', _542 => _542.modelConfig, 'optionalAccess', _543 => _543.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _544 => _544.modelConfig, 'optionalAccess', _545 => _545.temperature]), () => (this.config.temperature)),top_k:_nullishCoalesce(_optionalChain([e, 'access', _546 => _546.modelConfig, 'optionalAccess', _547 => _547.n]), () => (this.config.n)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _548 => _548.modelConfig, 'optionalAccess', _549 => _549.topP]), () => (this.config.topP)), () => (1)),stop:_nullishCoalesce(_optionalChain([e, 'access', _550 => _550.modelConfig, 'optionalAccess', _551 => _551.stopSequences]), () => (this.config.stop)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _552 => _552.modelConfig, 'optionalAccess', _553 => _553.presencePenalty]), () => (this.config.presencePenalty)),...i?{frequency_penalty:i}:{},...a?{stream:!0}:{}};return[o,l]}}__init36() {this.createChatResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=Zo(i.finish_reason),p;return typeof i.message.content=="string"?p=i.message.content:p=i.message.content.text,{index:a,id:`${t}`,content:p,finishReason:l}}),remoteId:t}}}__init37() {this.createChatStreamResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=Zo(i.finish_reason),p;return typeof i.chunk.content=="string"?p=i.chunk.content:p=i.chunk.content.text,{index:a,id:`${t}`,content:p,finishReason:l}})}}}}, _class13),Zo=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Ss(s){return s.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 Pe=class extends E{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=pn,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...at(),...t},l=new cn(a);super(l,{name:"Reka",apiURL:o||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:r,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0},models:i})}};var un=[];var er=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...w()}),_e= exports.AxAITogether =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Together API key not set");let i={...er(),...t};r=[...un,..._nullishCoalesce(r, () => ([]))];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:r,models:o,supportFor:a}),super.setName("Together")}};function dn(s){let e=n=>JSON.stringify(n,null,2);if(!s)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(s)}`);let t=_optionalChain([s, 'optionalAccess', _554 => _554.role]);if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=s;if(!n.content||n.content.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n.content)}`);break}case"user":{let n=s;if(!n.content)throw new Error(`User message content cannot be undefined, received: ${e(n.content)}`);if(typeof n.content=="string"){if(n.content.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n.content)}`)}else if(Array.isArray(n.content)){if(n.content.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n.content)}`);for(let o=0;o<n.content.length;o++){let r=n.content[o];if(!r||typeof r!="object")throw new Error(`User message content item at index ${o} must be an object, received: ${e(r)}`);let i=_optionalChain([r, 'optionalAccess', _555 => _555.type]);if(!i)throw new Error(`User message content item at index ${o} must have a type, received: ${e(i)}`);switch(i){case"text":{let a=r;if(!a.text||a.text.trim()==="")throw new Error(`User message text content at index ${o} cannot be empty or whitespace-only, received: ${e(a.text)}`);break}case"image":{let a=r;if(!a.image||a.image.trim()==="")throw new Error(`User message image content at index ${o} cannot be empty, received: ${e(a.image)}`);if(!a.mimeType||a.mimeType.trim()==="")throw new Error(`User message image content at index ${o} must have a mimeType, received: ${e(a.mimeType)}`);break}case"audio":{let a=r;if(!a.data||a.data.trim()==="")throw new Error(`User message audio content at index ${o} cannot be empty, received: ${e(a.data)}`);break}default:throw new Error(`User message content item at index ${o} has unsupported type: ${e(i)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n.content)}`);break}case"assistant":{let n=s;if(!n.content&&!n.functionCalls)throw new Error(`Assistant message must have either content or function calls, received content: ${e(n.content)}, functionCalls: ${e(n.functionCalls)}`);if(n.content&&typeof n.content!="string")throw new Error(`Assistant message content must be a string, received: ${e(n.content)}`);if(n.functionCalls&&!Array.isArray(n.functionCalls))throw new Error(`Assistant message function calls must be an array, received: ${e(n.functionCalls)}`);break}case"function":{let n=s;if(!n.functionId||n.functionId.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n.functionId)}`);if(n.result===void 0||n.result===null)throw new Error(`Function message must have a result, received: ${e(n.result)}`);if(typeof n.result!="string")throw new Error(`Function message result must be a string, received: ${e(n.result)}`);break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function mn(s){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(s)?s:[s];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 o=t[n];if(!o)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(o)}`);if(typeof o.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(o.index)}`);if(o.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(o.index)}`);if(!o.content&&!o.thought&&!o.functionCalls&&!o.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:o.content,thought:o.thought,functionCalls:o.functionCalls,finishReason:o.finishReason})}`);if(o.content!==void 0&&typeof o.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(o.content)}`);if(o.thought!==void 0&&typeof o.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(o.thought)}`);if(o.name!==void 0){if(typeof o.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(o.name)}`);if(o.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(o.name)}`)}if(o.annotations!==void 0){if(!Array.isArray(o.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(o.annotations)}`);for(let r=0;r<o.annotations.length;r++){let i=o.annotations[r];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${r}] must have type 'url_citation', received: ${e(i.type)}`);if(!i.url_citation||typeof i.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must have a valid url_citation object, received: ${e(i.url_citation)}`);if(typeof i.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${r}] url_citation.url must be a string, received: ${e(i.url_citation.url)}`)}}if(o.id!==void 0){if(typeof o.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(o.id)}`);if(o.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(o.id)}`)}if(o.functionCalls!==void 0){if(!Array.isArray(o.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(o.functionCalls)}`);for(let r=0;r<o.functionCalls.length;r++){let i=o.functionCalls[r];if(!i)throw new Error(`Function call at index ${r} in result ${n} cannot be null or undefined, received: ${e(i)}`);if(!i.id||typeof i.id!="string"||i.id.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty string id, received: ${e(i.id)}`);if(i.type!=="function")throw new Error(`Function call at index ${r} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${r} in result ${n} must have a function object, received: ${e(i.function)}`);if(!i.function.name||typeof i.function.name!="string"||i.function.name.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty function name, received: ${e(i.function.name)}`);if(i.function.params!==void 0&&typeof i.function.params!="string"&&typeof i.function.params!="object")throw new Error(`Function call params at index ${r} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(o.finishReason!==void 0){let r=["stop","length","function_call","content_filter","error"];if(!r.includes(o.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${r.join(", ")}, received: ${e(o.finishReason)}`)}}}var gn=class{constructor(e){switch(e.name){case"openai":this.ai=new Ie(e);break;case"openai-responses":this.ai=new Ee(e);break;case"azure-openai":this.ai=new be(e);break;case"huggingface":this.ai=new Oe(e);break;case"groq":this.ai=new ve(e);break;case"together":this.ai=new _e(e);break;case"cohere":this.ai=new Re(e);break;case"google-gemini":this.ai=new Te(e);break;case"anthropic":this.ai=new he(e);break;case"mistral":this.ai=new Se(e);break;case"deepseek":this.ai=new Ce(e);break;case"ollama":this.ai=new ke(e);break;case"reka":this.ai=new Pe(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()}};var lt=(o=>(o.Grok3="grok-3",o.Grok3Mini="grok-3-mini",o.Grok3Fast="grok-3-fast",o.Grok3MiniFast="grok-3-mini-fast",o))(lt||{}),tr= exports.AxAIGrokEmbedModels =(e=>(e.GrokEmbedSmall="grok-embed-small",e))(tr||{});var An=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,hasThinkingBudget:!0},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,hasThinkingBudget:!0}];var xn=()=>structuredClone({model:"grok-3-mini",...w()}),ks= exports.axAIGrokBestConfig =()=>structuredClone({...xn(),model:"grok-3"}),hn= exports.AxAIGrok =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Grok API key not set");let i={...xn(),...t};r=[...An,..._nullishCoalesce(r, () => ([]))];let a=p=>{let c=L({model:p,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _556 => _556.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _557 => _557.hasShowThoughts]), () => (!1))}},l=p=>{if(_optionalChain([n, 'optionalAccess', _558 => _558.searchParameters])){let c=n.searchParameters;return{...p,search_parameters:{mode:c.mode,return_citations:c.returnCitations,from_date:c.fromDate,to_date:c.toDate,max_search_results:c.maxSearchResults,sources:_optionalChain([c, 'access', _559 => _559.sources, 'optionalAccess', _560 => _560.map, 'call', _561 => _561(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))])}}}return p};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};var $=class{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:_api.SpanKind.SERVER,attributes:{[C.DB_SYSTEM]:this.name,[C.DB_OPERATION_NAME]:"upsert",[C.DB_TABLE]:e.table,[C.DB_NAMESPACE]:e.namespace,[C.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:_api.SpanKind.SERVER,attributes:{[C.DB_SYSTEM]:this.name,[C.DB_OPERATION_NAME]:"upsert",[C.DB_TABLE]:e[0].table,[C.DB_NAMESPACE]:e[0].namespace,[C.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:_api.SpanKind.SERVER,attributes:{[C.DB_SYSTEM]:this.name,[C.DB_OPERATION_NAME]:"upsert",[C.DB_TABLE]:e.table,[C.DB_NAMESPACE]:e.namespace,[C.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var yn="https://api.cloudflare.com/client/v4/accounts/",Fe= exports.AxDBCloudflare = (_class14 =class extends ${constructor({apiKey:e,accountId:t,fetch:n,tracer:o}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:o});_class14.prototype.__init38.call(this);_class14.prototype.__init39.call(this);_class14.prototype.__init40.call(this);,this.apiKey=e,this.accountId=t}__init38() {this._upsert=async(e,t,n)=>{let o=await D({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,yn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _565 => _565.span])},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(o.errors)throw new Error(`Cloudflare upsert failed: ${o.errors.map(({message:r})=>r).join(", ")}`);return{ids:o.result.ids}}}__init39() {this.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 o=e[0].table,r=await D({url:new URL(`${this.accountId}/vectorize/indexes/${o}/upsert`,yn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _566 => _566.span])},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(r.errors)throw new Error(`Cloudflare batch upsert failed: ${r.errors.map(({message:i})=>i).join(", ")}`);return{ids:r.result.ids}}}__init40() {this.query=async(e,t)=>{let n=await D({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,yn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _567 => _567.span])},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:r})=>r).join(", ")}`);return{matches:n.result.matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,values:a,metadata:l}))}}}}, _class14);var oe= (_class15 =class extends ${constructor({tracer:e}={}){super({name:"Memory",tracer:e});_class15.prototype.__init41.call(this);_class15.prototype.__init42.call(this);_class15.prototype.__init43.call(this);_class15.prototype.__init44.call(this);_class15.prototype.__init45.call(this);_class15.prototype.__init46.call(this);,this.state={}}__init41() {this._upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let o=this.state[e.table];if(!o)throw new Error(`Table not found: ${e.table}`);o[e.id]=e}return{ids:[e.id]}}}__init42() {this._batchUpsert=async(e,t,n)=>{let o=[];for(let r of e){let i=await this.upsert(r,t);o.push(...i.ids)}return{ids:o}}}__init43() {this._query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let o=[];return Object.entries(n).forEach(([r,i])=>{if(e.values&&i.values){let a=Ms(e.values,i.values);o.push({id:r,score:a,metadata:i.metadata})}}),o.sort((r,i)=>r.score-i.score),e.limit&&(o.length=e.limit),{matches:o}}}__init44() {this.getDB=()=>structuredClone(this.state)}__init45() {this.setDB=e=>{this.state=structuredClone(e)}}__init46() {this.clearDB=()=>{this.state={}}}}, _class15),Ms=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,o=0,r=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let u=0;u<a.length;u++)t+=a[u]*l[u],n+=a[u]*a[u],o+=l[u]*l[u],a[u]!==0&&(r=!1),l[u]!==0&&(i=!1);if(r||i)return 1;let p=Math.sqrt(n),c=Math.sqrt(o);return 1-t/(p*c)};var Es=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:_nullishCoalesce(s.values, () => ([])),id:s.id}),Ge= exports.AxDBPinecone = (_class16 =class extends ${constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:o});_class16.prototype.__init47.call(this);_class16.prototype.__init48.call(this);_class16.prototype.__init49.call(this);,this.apiKey=e,this.apiURL=t}__init47() {this._upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]})}__init48() {this._batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _570 => _570.span])},e.map(({id:o,values:r=[],metadata:i})=>({id:o,values:r,metadata:i}))),{ids:e.map(({id:o})=>o)}}}__init49() {this.query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _571 => _571.span])},Es(e))).matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,metadata:l,values:a}))}}}}, _class16);var De= (_class17 =class extends ${constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:o});_class17.prototype.__init50.call(this);_class17.prototype.__init51.call(this);_class17.prototype.__init52.call(this);,this.apiKey=e,this.apiURL=t}__init50() {this._upsert=async(e,t,n)=>{let o=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _589 => _589.span])},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:_nullishCoalesce(e.metadata, () => ({}))});if(_optionalChain([o, 'optionalAccess', _590 => _590.result, 'optionalAccess', _591 => _591.errors]))throw new Error(`Weaviate upsert failed: ${o.result.errors.error.map(({message:r})=>r).join(", ")}`);return{ids:[o.id]}}}__init51() {this._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 o=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:_nullishCoalesce(i.metadata, () => ({}))})),r=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _592 => _592.span])},{objects:o});if(_optionalChain([r, 'optionalAccess', _593 => _593.some, 'call', _594 => _594(({result:i})=>_optionalChain([i, 'optionalAccess', _595 => _595.errors]))]))throw new Error(`Weaviate batch upsert failed: ${r.map(({result:i})=>_optionalChain([i, 'optionalAccess', _596 => _596.errors, 'optionalAccess', _597 => _597.error, 'access', _598 => _598.map, 'call', _599 => _599(({message:a})=>a), 'access', _600 => _600.join, 'call', _601 => _601(", ")])).join(", ")}`);return{ids:r.map(({id:i})=>i)}}}__init52() {this._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: {
111
+ ${c}`:`Assistant: ${p.content}`}default:throw new Error("Unknown role")}}), 'access', _432 => _432.join, 'call', _433 => _433(`
112
+ `)]),i=`${o} ${r}`.trim(),a={name:"/models"},l={model:n,inputs:i,parameters:{max_new_tokens:_nullishCoalesce(_optionalChain([e, 'access', _434 => _434.modelConfig, 'optionalAccess', _435 => _435.maxTokens]), () => (this.config.maxTokens)),repetition_penalty:_nullishCoalesce(_optionalChain([e, 'access', _436 => _436.modelConfig, 'optionalAccess', _437 => _437.presencePenalty]), () => (this.config.presencePenalty)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _438 => _438.modelConfig, 'optionalAccess', _439 => _439.temperature]), () => (this.config.temperature)),top_p:_nullishCoalesce(_optionalChain([e, 'access', _440 => _440.modelConfig, 'optionalAccess', _441 => _441.topP]), () => (this.config.topP)),top_k:_nullishCoalesce(_optionalChain([e, 'access', _442 => _442.modelConfig, 'optionalAccess', _443 => _443.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[a,l]}}__init40() {this.createChatResp=e=>({results:[{index:0,content:e.generated_text}]})}}, _class10),be= exports.AxAIHuggingFace =class extends _{constructor({apiKey:e,config:t,options:n,models:o}){if(!e||e==="")throw new Error("HuggingFace API key not set");let r={...Xo(),...t},i=new Qt(r);super(i,{name:"HuggingFace",apiURL:"https://api-inference.huggingface.co",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:Yt,defaults:{model:r.model},options:n,supportFor:{functions:!1,streaming:!1},models:o})}};var et=(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))(et||{}),Zo= exports.AxAIMistralEmbedModels =(e=>(e.MistralEmbed="mistral-embed",e))(Zo||{});var Xt=[{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 Zt=()=>structuredClone({model:"mistral-small-latest",...v(),topP:1}),Cs= exports.axAIMistralBestConfig =()=>structuredClone({...Zt(),model:"mistral-large-latest"}),Re= exports.AxAIMistral =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Mistral API key not set");let i={...Zt(),...t};r=[...Xt,..._nullishCoalesce(r, () => ([]))];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1},l=p=>{let{max_completion_tokens:c,messages:d,...u}=p;return{...u,messages:this.updateMessages(d),max_tokens:c}};super({apiKey:e,config:i,options:n,apiURL:"https://api.mistral.ai/v1",modelInfo:r,models:o,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 o=n.content.map(r=>typeof r=="object"&&r!==null&&"image_url"in r?{type:"image_url",image_url:{url:_optionalChain([r, 'access', _444 => _444.image_url, 'optionalAccess', _445 => _445.url])}}:r);t.push({...n,content:o})}else t.push(n);return t}};var en= (_class11 =class{constructor(e={}){;_class11.prototype.__init41.call(this);this.config=e;this.config.id=_nullishCoalesce(this.config.id, () => (q()))}__init41() {this.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 _nullishCoalesce(_optionalChain([this, 'access', _446 => _446.config, 'access', _447 => _447.modelInfo, 'optionalAccess', _448 => _448.name]), () => ("mock-model"))}getLastUsedEmbedModel(){return _nullishCoalesce(_optionalChain([this, 'access', _449 => _449.config, 'access', _450 => _450.embedModelInfo, 'optionalAccess', _451 => _451.name]), () => ("mock-embed-model"))}getLastUsedModelConfig(){return this.config.modelInfo?{maxTokens:this.config.modelInfo.maxTokens,temperature:.7,stream:_nullishCoalesce(_optionalChain([this, 'access', _452 => _452.config, 'access', _453 => _453.features, 'optionalAccess', _454 => _454.streaming]), () => (!1))}:void 0}getName(){return _nullishCoalesce(this.config.name, () => ("mock-ai-service"))}getId(){return _nullishCoalesce(this.config.id, () => ("mock-ai-service-id"))}getFeatures(e){return{functions:_nullishCoalesce(_optionalChain([this, 'access', _455 => _455.config, 'access', _456 => _456.features, 'optionalAccess', _457 => _457.functions]), () => (!1)),streaming:_nullishCoalesce(_optionalChain([this, 'access', _458 => _458.config, 'access', _459 => _459.features, 'optionalAccess', _460 => _460.streaming]), () => (!1))}}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(_nullishCoalesce(this.config.errorMessage, () => ("Mock chat error")));return this.updateMetrics("chat"),typeof this.config.chatResponse=="function"?await this.config.chatResponse(e):_nullishCoalesce(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(_nullishCoalesce(this.config.errorMessage, () => ("Mock embed error")));return this.updateMetrics("embed"),typeof this.config.embedResponse=="function"?this.config.embedResponse(e):_nullishCoalesce(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 _nullishCoalesce(this.config.options, () => ({}))}getLogger(){return _nullishCoalesce(_optionalChain([this, 'access', _461 => _461.config, 'access', _462 => _462.options, 'optionalAccess', _463 => _463.logger]), () => ((e=>{typeof e=="string"?process.stdout.write(e):process.stdout.write(JSON.stringify(e,null,2))})))}updateMetrics(e){let t=_nullishCoalesce(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((o,r)=>o+r,0)/n.length,n.length>0){let o=[...n].sort((a,l)=>a-l),r=Math.max(0,Math.floor(o.length*.95)-1);this.metrics.latency[e].p95=_nullishCoalesce(o[r], () => (t));let i=Math.max(0,Math.floor(o.length*.99)-1);this.metrics.latency[e].p99=_nullishCoalesce(o[i], () => (t))}if(this.config.shouldError){this.metrics.errors[e].count++,this.metrics.errors[e].total++;let o=this.metrics.latency[e].samples.length;this.metrics.errors[e].rate=o>0?this.metrics.errors[e].count/o:0}}}, _class11);var tn= (_class12 =class{__init42() {this.services=new Map}constructor(e){;_class12.prototype.__init42.call(this);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:r,description:i,isInternal:a}=n;this.services.set(n.key,{service:r,description:i,isInternal:a})}else{let r=n.getModelList();if(!r)throw new Error(`Service ${t} \`${n.getName()}\` has no model list.`);for(let i of r){if(this.services.has(i.key)){let a=_optionalChain([this, 'access', _464 => _464.services, 'access', _465 => _465.get, 'call', _466 => _466(i.key), 'optionalAccess', _467 => _467.service]);throw new Error(`Service ${t} \`${n.getName()}\` has duplicate model key: ${i.key} as service ${_optionalChain([a, 'optionalAccess', _468 => _468.getName, 'call', _469 => _469()])}`)}if("model"in i&&typeof i.model)this.services.set(i.key,{description:i.description,service:n,model:i.model});else if("embedModel"in i&&i.embedModel)this.services.set(i.key,{description:i.description,service:n,embedModel:i.embedModel});else throw new Error(`Key ${i.key} in model list for service ${t} \`${n.getName()}\` is missing a model or embedModel property.`)}}}getLastUsedChatModel(){return _optionalChain([this, 'access', _470 => _470.lastUsedService, 'optionalAccess', _471 => _471.getLastUsedChatModel, 'call', _472 => _472()])}getLastUsedEmbedModel(){return _optionalChain([this, 'access', _473 => _473.lastUsedService, 'optionalAccess', _474 => _474.getLastUsedEmbedModel, 'call', _475 => _475()])}getLastUsedModelConfig(){return _optionalChain([this, 'access', _476 => _476.lastUsedService, 'optionalAccess', _477 => _477.getLastUsedModelConfig, 'call', _478 => _478()])}async chat(e,t){let n=e.model;if(!n)throw new Error("Model key must be specified for multi-service");let o=this.services.get(n);if(!o)throw new Error(`No service found for model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{model:r,...i}=e;return await o.service.chat(i,t)}return await o.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 o=this.services.get(n);if(!o)throw new Error(`No service found for embed model key: ${n}`);if(this.lastUsedService=o.service,!o.model){let{embedModel:r,...i}=e;return await o.service.embed(i,t)}return await o.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}}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 _nullishCoalesce(this.options, () => ({}))}getLogger(){let e=this.lastUsedService;if(!e){let t=this.services.values().next().value;t&&(e=t.service)}return e?e.getLogger():t=>{typeof t=="string"?process.stdout.write(t):process.stdout.write(JSON.stringify(t,null,2))}}setServiceEntry(e,t){this.services.set(e,t)}}, _class12);var er=()=>structuredClone({...v(),model:"nous-hermes2",embedModel:"all-minilm"}),ws= exports.axAIOllamaDefaultCreativeConfig =()=>structuredClone({...F(),model:"nous-hermes2",embedModel:"all-minilm"}),Ce= exports.AxAIOllama =class extends M{constructor({apiKey:e="not-set",url:t="http://localhost:11434/v1",config:n,options:o,models:r}){let i={...er(),...n};super({apiKey:e,options:o,config:i,apiURL:t,models:r,modelInfo:[],supportFor:{functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1}}),super.setName("Ollama")}};var Ts=s=>["o1","o1-mini","o1-pro","o3","o3-mini","o3-pro","o4-mini"].includes(s),we= exports.AxAIOpenAIResponsesImpl =class{constructor(e,t,n){this.config=e;this.streamingUsage=t;this.responsesReqUpdater=n}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){return e.map(n=>{if(n.type==="text")return{type:"text",text:n.text};if(n.type==="image")return{type:"image_url",image_url:{url:`data:${n.mimeType};base64,${n.image}`,details:_nullishCoalesce(n.details, () => ("auto"))}};if(n.type==="audio")return{type:"input_audio",input_audio:{data:n.data,format:_nullishCoalesce(n.format, () => ("wav"))}};let o=n;throw new Error(`Unsupported content part: ${JSON.stringify(o)}`)})}createResponsesReqInternalInput(e,t=!1){let n=[];for(let o of e){if(t&&o.role==="system")continue;let r;if(o.role==="system"||o.role==="user"||o.role==="assistant"&&o.content)if(typeof o.content=="string")r=o.content;else if(Array.isArray(o.content))r=this.mapInternalContentToResponsesInput(o.content);else{if(!(o.role==="assistant"&&!o.content&&o.functionCalls))throw new Error(`Invalid content type for role ${o.role}`);r=""}else o.role,r="";switch(o.role){case"system":n.push({type:"message",role:"system",content:r});break;case"user":n.push({type:"message",role:"user",content:r,name:o.name});break;case"assistant":if(o.content||o.functionCalls){let i={type:"message",role:"assistant",content:""};if(o.content&&(i.content=r),o.name&&(i.name=o.name),o.content&&n.push(i),o.functionCalls)for(let a of o.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:o.functionId,output:o.result});break;default:{let i=o.role;throw new Error(`Invalid role in chat prompt: ${i}`)}}}return n}createChatReq(e,t){let n=e.model,o={name:"/responses"},r=null,i=!1;if(e.chatPrompt){for(let h of e.chatPrompt)if(h.role==="system"&&typeof h.content=="string"){r=h.content,i=!0;break}}let a=_nullishCoalesce(_nullishCoalesce(r, () => (this.config.systemPrompt)), () => (null)),l=_optionalChain([e, 'access', _479 => _479.functions, 'optionalAccess', _480 => _480.map, 'call', _481 => _481(h=>({type:"function",name:h.name,description:h.description,parameters:_nullishCoalesce(h.parameters, () => ({}))}))]),p=[],c=Ts(n),d=this.config.reasoningSummary;_optionalChain([t, 'optionalAccess', _482 => _482.showThoughts])?d||(d="auto"):d=void 0;let u=this.config.reasoningEffort;if(_optionalChain([t, 'optionalAccess', _483 => _483.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":u=void 0;break;case"minimal":u="low";break;case"low":u="medium";break;case"medium":case"high":case"highest":u="high";break}let m={model:n,input:"",instructions:a,tools:_optionalChain([l, 'optionalAccess', _484 => _484.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,...c?{max_output_tokens:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _485 => _485.modelConfig, 'optionalAccess', _486 => _486.maxTokens]), () => (this.config.maxTokens)), () => (void 0))}:{temperature:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _487 => _487.modelConfig, 'optionalAccess', _488 => _488.temperature]), () => (this.config.temperature)), () => (void 0)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _489 => _489.modelConfig, 'optionalAccess', _490 => _490.topP]), () => (this.config.topP)), () => (void 0)),presence_penalty:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _491 => _491.modelConfig, 'optionalAccess', _492 => _492.presencePenalty]), () => (this.config.presencePenalty)), () => (void 0)),frequency_penalty:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _493 => _493.modelConfig, 'optionalAccess', _494 => _494.frequencyPenalty]), () => (this.config.frequencyPenalty)), () => (void 0))},stream:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _495 => _495.modelConfig, 'optionalAccess', _496 => _496.stream]), () => (this.config.stream)), () => (!1)),background:void 0,include:p.length>0?p:void 0,metadata:void 0,parallel_tool_calls:this.config.parallelToolCalls,previous_response_id:void 0,...u?{reasoning:{effort:u,summary:d}}:{},service_tier:this.config.serviceTier,store:this.config.store,text:void 0,truncation:void 0,user:this.config.user,seed:this.config.seed};this.config.user&&(m.user=this.config.user),this.config.parallelToolCalls!==void 0&&(m.parallel_tool_calls=this.config.parallelToolCalls),this.config.responseFormat&&(m.text={format:{type:this.config.responseFormat}}),this.config.seed&&(m.seed=this.config.seed);let A=e.chatPrompt?this.createResponsesReqInternalInput(e.chatPrompt,i):[];if(A.length>0)m.input=A;else if(e.chatPrompt&&e.chatPrompt.length===1&&_optionalChain([e, 'access', _497 => _497.chatPrompt, 'access', _498 => _498[0], 'optionalAccess', _499 => _499.role])==="user"&&_optionalChain([e, 'access', _500 => _500.chatPrompt, 'access', _501 => _501[0], 'optionalAccess', _502 => _502.content])&&typeof e.chatPrompt[0].content=="string"&&!a)m.input=e.chatPrompt[0].content;else if(A.length===0&&!a)throw new Error("Responses API request must have input or instructions.");let g=_nullishCoalesce(m.reasoning, () => ({}));if(this.config.reasoningEffort&&(g={...g,effort:this.config.reasoningEffort}),_optionalChain([t, 'optionalAccess', _503 => _503.thinkingTokenBudget]))switch(t.thinkingTokenBudget){case"none":g={};break;case"minimal":g={...g,effort:"low"};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)),[o,f]}createChatResp(e){let{id:t,output:n,usage:o}=e;o&&(this.tokensUsed={promptTokens:o.prompt_tokens,completionTokens:o.completion_tokens,totalTokens:o.total_tokens});let r={};for(let i of _nullishCoalesce(n, () => ([])))switch(i.type){case"message":r.id=i.id,r.content=nn(i.content,t),r.finishReason=i.status==="completed"?"stop":"content_filter";break;case"reasoning":r.id=i.id,i.encrypted_content?r.thought=i.encrypted_content:r.thought=i.summary.map(a=>typeof a=="object"?JSON.stringify(a):a).join(`
113
+ `);break;case"file_search_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"file_search",params:{queries:i.queries,results:i.results}}}],r.finishReason="function_call";break;case"web_search_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"web_search",params:{queries:i.queries}}}],r.finishReason="function_call";break;case"computer_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"computer_use",params:{action:i.action}}}],r.finishReason="function_call";break;case"code_interpreter_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"code_interpreter",params:{code:i.code,results:i.results}}}],r.finishReason="function_call";break;case"image_generation_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"image_generation",params:{result:i.result}}}],r.finishReason="function_call";break;case"local_shell_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"local_shell",params:{action:i.action}}}],r.finishReason="function_call";break;case"mcp_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:"mcp",params:{name:i.name,args:i.args,serverLabel:i.server_label,output:i.output,error:i.error}}}],r.finishReason="function_call";break;case"function_call":r.id=i.id,r.functionCalls=[{id:i.id,type:"function",function:{name:i.name,params:i.arguments}}],r.finishReason="function_call";break}return{results:[{...r,index:0}],remoteId:t}}createChatStreamResp(e){let t=e,n={index:0,id:"",content:"",finishReason:"stop"},o;switch(t.type){case"response.created":case"response.in_progress":case"response.queued":o=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=nn(t.item.content,t.item.id);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 r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"file_search",params:{queries:r.queries||[],results:_optionalChain([r, 'access', _504 => _504.results, 'optionalAccess', _505 => _505.map, 'call', _506 => _506(i=>({fileId:i.file_id,filename:i.filename,score:i.score,text:i.text,attributes:i.attributes}))])}}}]}break;case"web_search_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"web_search",params:{queries:r.queries||[]}}}]}break;case"computer_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"computer_use",params:{action:r.action||{}}}}]}break;case"code_interpreter_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"code_interpreter",params:{code:r.code||"",results:r.results}}}]}break;case"image_generation_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"image_generation",params:{result:r.result}}}]}break;case"local_shell_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"local_shell",params:{action:r.action||{}}}}]}break;case"mcp_call":{let r=t.item;n.id=t.item.id,n.functionCalls=[{id:r.id,type:"function",function:{name:"mcp",params:{name:r.name||"",args:r.args||"",serverLabel:r.server_label||"",output:r.output,error:r.error}}}]}break}break;case"response.content_part.added":n.id=t.item_id,n.content=nn([t.part],t.item_id);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":n.id=t.item.id,n.finishReason=t.item.status==="completed"?"stop":"error";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,totalTokens:t.response.usage.total_tokens}),o=t.response.id,n.id=`${t.response.id}_completed`,n.finishReason="stop";break;case"response.failed":o=t.response.id,n.id=`${t.response.id}_failed`,n.finishReason="error";break;case"response.incomplete":o=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:o}}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"},o={model:t,input:e.texts,dimensions:this.config.dimensions};return[n,o]}},nn=(s,e)=>{let t=s.filter(n=>n.type==="refusal");if(t.length>0){let n=t.map(o=>o.refusal).join(`
114
+ `);throw new O(n,void 0,e)}return s.filter(n=>n.type==="output_text").map(n=>n.text).join(`
115
+ `)};var nt=()=>({model:"gpt-4o",embedModel:"text-embedding-ada-002",temperature:.7,topP:1,stream:!0}),vs= exports.axAIOpenAIResponsesBestConfig =()=>({...nt(),model:"gpt-4o",temperature:.5}),Os= exports.axAIOpenAIResponsesCreativeConfig =()=>({...nt(),model:"gpt-4o",temperature:.9}),tt= exports.AxAIOpenAIResponsesBase =class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=[],models:i,responsesReqUpdater:a,supportFor:l={functions:!0,streaming:!0}}){if(!e||e==="")throw new Error("OpenAI API key not set");let p=new we(t,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _507 => _507.streamingUsage]), () => (!0)),a),c=i;super(p,{name:"OpenAI",apiURL:o||"https://api.openai.com/v1",headers:async()=>({Authorization:`Bearer ${e}`}),modelInfo:r,defaults:{model:t.model,embedModel:t.embedModel},options:n,supportFor:l,models:c})}},Te= exports.AxAIOpenAIResponses =class extends tt{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("OpenAI API key not set");r=[...Ft,..._nullishCoalesce(r, () => ([]))];let i=a=>{let l=B({model:a,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _508 => _508.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([l, 'optionalAccess', _509 => _509.hasShowThoughts]), () => (!1))}};super({apiKey:e,config:{...nt(),...t},options:n,modelInfo:r,models:o,supportFor:i})}};var ot=(n=>(n.RekaCore="reka-core",n.RekaFlash="reka-flash",n.RekaEdge="reka-edge",n))(ot||{});var on=[{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 rt=()=>structuredClone({model:"reka-core",...v()}),Ss= exports.axAIRekaBestConfig =()=>structuredClone({...rt(),model:"reka-core"}),ks= exports.axAIRekaCreativeConfig =()=>structuredClone({model:"reka-core",...F()}),Es= exports.axAIRekaFastConfig =()=>({...rt(),model:"reka-flash"}),rn= (_class13 =class{constructor(e){;_class13.prototype.__init43.call(this);_class13.prototype.__init44.call(this);_class13.prototype.__init45.call(this);this.config=e}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}}__init43() {this.createChatReq=(e,t)=>{let n=e.model;if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let o={name:"/chat/completions"},r=Ms(e),i=_nullishCoalesce(_optionalChain([e, 'access', _526 => _526.modelConfig, 'optionalAccess', _527 => _527.frequencyPenalty]), () => (this.config.frequencyPenalty)),a=_nullishCoalesce(_optionalChain([e, 'access', _528 => _528.modelConfig, 'optionalAccess', _529 => _529.stream]), () => (this.config.stream)),l={model:n,messages:r,max_tokens:_nullishCoalesce(_optionalChain([e, 'access', _530 => _530.modelConfig, 'optionalAccess', _531 => _531.maxTokens]), () => (this.config.maxTokens)),temperature:_nullishCoalesce(_optionalChain([e, 'access', _532 => _532.modelConfig, 'optionalAccess', _533 => _533.temperature]), () => (this.config.temperature)),top_k:_nullishCoalesce(_optionalChain([e, 'access', _534 => _534.modelConfig, 'optionalAccess', _535 => _535.n]), () => (this.config.n)),top_p:_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'access', _536 => _536.modelConfig, 'optionalAccess', _537 => _537.topP]), () => (this.config.topP)), () => (1)),stop:_nullishCoalesce(_optionalChain([e, 'access', _538 => _538.modelConfig, 'optionalAccess', _539 => _539.stopSequences]), () => (this.config.stop)),presence_penalty:_nullishCoalesce(_optionalChain([e, 'access', _540 => _540.modelConfig, 'optionalAccess', _541 => _541.presencePenalty]), () => (this.config.presencePenalty)),...i?{frequency_penalty:i}:{},...a?{stream:!0}:{}};return[o,l]}}__init44() {this.createChatResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=tr(i.finish_reason),p;return typeof i.message.content=="string"?p=i.message.content:p=i.message.content.text,{index:a,id:`${t}`,content:p,finishReason:l}}),remoteId:t}}}__init45() {this.createChatStreamResp=e=>{let{id:t,usage:n,responses:o}=e;return this.tokensUsed=n?{promptTokens:n.input_tokens,completionTokens:n.output_tokens,totalTokens:n.input_tokens+n.output_tokens}:void 0,{results:o.map((i,a)=>{let l=tr(i.finish_reason),p;return typeof i.chunk.content=="string"?p=i.chunk.content:p=i.chunk.content.text,{index:a,id:`${t}`,content:p,finishReason:l}})}}}}, _class13),tr=s=>{switch(s){case"stop":return"stop";case"context":return"length";case"length":return"length"}};function Ms(s){return s.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 ve=class extends _{constructor({apiKey:e,config:t,options:n,apiURL:o,modelInfo:r=on,models:i}){if(!e||e==="")throw new Error("Reka API key not set");let a={...rt(),...t},l=new rn(a);super(l,{name:"Reka",apiURL:o||"https://api.reka.ai/v1/chat",headers:async()=>({"X-Api-Key":e}),modelInfo:r,defaults:{model:a.model},options:n,supportFor:{functions:!0,streaming:!0},models:i})}};var sn=[];var nr=()=>structuredClone({model:"mistralai/Mixtral-8x7B-Instruct-v0.1",...v()}),Oe= exports.AxAITogether =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Together API key not set");let i={...nr(),...t};r=[...sn,..._nullishCoalesce(r, () => ([]))];let a={functions:!0,streaming:!0,hasThinkingBudget:!1,hasShowThoughts:!1};super({apiKey:e,config:i,options:n,apiURL:"https://api.together.xyz/v1",modelInfo:r,models:o,supportFor:a}),super.setName("Together")}};function an(s){let e=n=>JSON.stringify(n,null,2);if(!s)throw new Error(`Chat request message item cannot be null or undefined, received: ${e(s)}`);let t=_optionalChain([s, 'optionalAccess', _542 => _542.role]);if(!t)throw new Error(`Chat request message must have a role, received: ${e(t)}`);switch(t){case"system":{let n=s;if(!n.content||n.content.trim()==="")throw new Error(`System message content cannot be empty or whitespace-only, received: ${e(n.content)}`);break}case"user":{let n=s;if(!n.content)throw new Error(`User message content cannot be undefined, received: ${e(n.content)}`);if(typeof n.content=="string"){if(n.content.trim()==="")throw new Error(`User message content cannot be empty or whitespace-only, received: ${e(n.content)}`)}else if(Array.isArray(n.content)){if(n.content.length===0)throw new Error(`User message content array cannot be empty, received: ${e(n.content)}`);for(let o=0;o<n.content.length;o++){let r=n.content[o];if(!r||typeof r!="object")throw new Error(`User message content item at index ${o} must be an object, received: ${e(r)}`);let i=_optionalChain([r, 'optionalAccess', _543 => _543.type]);if(!i)throw new Error(`User message content item at index ${o} must have a type, received: ${e(i)}`);switch(i){case"text":{let a=r;if(!a.text||a.text.trim()==="")throw new Error(`User message text content at index ${o} cannot be empty or whitespace-only, received: ${e(a.text)}`);break}case"image":{let a=r;if(!a.image||a.image.trim()==="")throw new Error(`User message image content at index ${o} cannot be empty, received: ${e(a.image)}`);if(!a.mimeType||a.mimeType.trim()==="")throw new Error(`User message image content at index ${o} must have a mimeType, received: ${e(a.mimeType)}`);break}case"audio":{let a=r;if(!a.data||a.data.trim()==="")throw new Error(`User message audio content at index ${o} cannot be empty, received: ${e(a.data)}`);break}default:throw new Error(`User message content item at index ${o} has unsupported type: ${e(i)}`)}}}else throw new Error(`User message content must be a string or array of content objects, received: ${e(n.content)}`);break}case"assistant":{let n=s;if(!n.content&&!n.functionCalls)throw new Error(`Assistant message must have either content or function calls, received content: ${e(n.content)}, functionCalls: ${e(n.functionCalls)}`);if(n.content&&typeof n.content!="string")throw new Error(`Assistant message content must be a string, received: ${e(n.content)}`);if(n.functionCalls&&!Array.isArray(n.functionCalls))throw new Error(`Assistant message function calls must be an array, received: ${e(n.functionCalls)}`);break}case"function":{let n=s;if(!n.functionId||n.functionId.trim()==="")throw new Error(`Function message must have a non-empty functionId, received: ${e(n.functionId)}`);if(n.result===void 0||n.result===null)throw new Error(`Function message must have a result, received: ${e(n.result)}`);if(typeof n.result!="string")throw new Error(`Function message result must be a string, received: ${e(n.result)}`);break}default:throw new Error(`Unsupported message role: ${e(t)}`)}}function ln(s){let e=n=>JSON.stringify(n,null,2),t=Array.isArray(s)?s:[s];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 o=t[n];if(!o)throw new Error(`Chat response result at index ${n} cannot be null or undefined, received: ${e(o)}`);if(typeof o.index!="number")throw new Error(`Chat response result at index ${n} must have a numeric index, received: ${e(o.index)}`);if(o.index<0)throw new Error(`Chat response result at index ${n} must have a non-negative index, received: ${e(o.index)}`);if(!o.content&&!o.thought&&!o.functionCalls&&!o.finishReason)throw new Error(`Chat response result at index ${n} must have at least one of: content, thought, functionCalls, or finishReason, received: ${e({content:o.content,thought:o.thought,functionCalls:o.functionCalls,finishReason:o.finishReason})}`);if(o.content!==void 0&&typeof o.content!="string")throw new Error(`Chat response result content at index ${n} must be a string, received: ${e(o.content)}`);if(o.thought!==void 0&&typeof o.thought!="string")throw new Error(`Chat response result thought at index ${n} must be a string, received: ${e(o.thought)}`);if(o.name!==void 0){if(typeof o.name!="string")throw new Error(`Chat response result name at index ${n} must be a string, received: ${e(o.name)}`);if(o.name.trim()==="")throw new Error(`Chat response result name at index ${n} cannot be empty or whitespace-only, received: ${e(o.name)}`)}if(o.annotations!==void 0){if(!Array.isArray(o.annotations))throw new Error(`Chat response result annotations at index ${n} must be an array, received: ${e(o.annotations)}`);for(let r=0;r<o.annotations.length;r++){let i=o.annotations[r];if(!i||typeof i!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must be an object, received: ${e(i)}`);if(i.type!=="url_citation")throw new Error(`Chat response result annotation at index ${n}[${r}] must have type 'url_citation', received: ${e(i.type)}`);if(!i.url_citation||typeof i.url_citation!="object")throw new Error(`Chat response result annotation at index ${n}[${r}] must have a valid url_citation object, received: ${e(i.url_citation)}`);if(typeof i.url_citation.url!="string")throw new Error(`Chat response result annotation at index ${n}[${r}] url_citation.url must be a string, received: ${e(i.url_citation.url)}`)}}if(o.id!==void 0){if(typeof o.id!="string")throw new Error(`Chat response result id at index ${n} must be a string, received: ${e(o.id)}`);if(o.id.trim()==="")throw new Error(`Chat response result id at index ${n} cannot be empty or whitespace-only, received: ${e(o.id)}`)}if(o.functionCalls!==void 0){if(!Array.isArray(o.functionCalls))throw new Error(`Chat response result functionCalls at index ${n} must be an array, received: ${e(o.functionCalls)}`);for(let r=0;r<o.functionCalls.length;r++){let i=o.functionCalls[r];if(!i)throw new Error(`Function call at index ${r} in result ${n} cannot be null or undefined, received: ${e(i)}`);if(!i.id||typeof i.id!="string"||i.id.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty string id, received: ${e(i.id)}`);if(i.type!=="function")throw new Error(`Function call at index ${r} in result ${n} must have type 'function', received: ${e(i.type)}`);if(!i.function)throw new Error(`Function call at index ${r} in result ${n} must have a function object, received: ${e(i.function)}`);if(!i.function.name||typeof i.function.name!="string"||i.function.name.trim()==="")throw new Error(`Function call at index ${r} in result ${n} must have a non-empty function name, received: ${e(i.function.name)}`);if(i.function.params!==void 0&&typeof i.function.params!="string"&&typeof i.function.params!="object")throw new Error(`Function call params at index ${r} in result ${n} must be a string or object, received: ${e(i.function.params)}`)}}if(o.finishReason!==void 0){let r=["stop","length","function_call","content_filter","error"];if(!r.includes(o.finishReason))throw new Error(`Chat response result finishReason at index ${n} must be one of: ${r.join(", ")}, received: ${e(o.finishReason)}`)}}}var pn=class{constructor(e){switch(e.name){case"openai":this.ai=new ge(e);break;case"openai-responses":this.ai=new Te(e);break;case"azure-openai":this.ai=new Ae(e);break;case"huggingface":this.ai=new be(e);break;case"groq":this.ai=new Ie(e);break;case"together":this.ai=new Oe(e);break;case"cohere":this.ai=new he(e);break;case"google-gemini":this.ai=new fe(e);break;case"anthropic":this.ai=new ce(e);break;case"mistral":this.ai=new Re(e);break;case"deepseek":this.ai=new xe(e);break;case"ollama":this.ai=new Ce(e);break;case"reka":this.ai=new ve(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()}};var st=(o=>(o.Grok3="grok-3",o.Grok3Mini="grok-3-mini",o.Grok3Fast="grok-3-fast",o.Grok3MiniFast="grok-3-mini-fast",o))(st||{}),or= exports.AxAIGrokEmbedModels =(e=>(e.GrokEmbedSmall="grok-embed-small",e))(or||{});var cn=[{name:"grok-3",currency:"USD",promptTokenCostPer1M:3,completionTokenCostPer1M:15},{name:"grok-3-mini",currency:"USD",promptTokenCostPer1M:.3,completionTokenCostPer1M:.5,hasThinkingBudget:!0},{name:"grok-3-fast",currency:"USD",promptTokenCostPer1M:5,completionTokenCostPer1M:25},{name:"grok-3-mini-fast",currency:"USD",promptTokenCostPer1M:.6,completionTokenCostPer1M:4,hasThinkingBudget:!0}];var dn=()=>structuredClone({model:"grok-3-mini",...v()}),_s= exports.axAIGrokBestConfig =()=>structuredClone({...dn(),model:"grok-3"}),un= exports.AxAIGrok =class extends M{constructor({apiKey:e,config:t,options:n,models:o,modelInfo:r}){if(!e||e==="")throw new Error("Grok API key not set");let i={...dn(),...t};r=[...cn,..._nullishCoalesce(r, () => ([]))];let a=p=>{let c=B({model:p,modelInfo:r,models:o});return{functions:!0,streaming:!0,hasThinkingBudget:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _544 => _544.hasThinkingBudget]), () => (!1)),hasShowThoughts:_nullishCoalesce(_optionalChain([c, 'optionalAccess', _545 => _545.hasShowThoughts]), () => (!1))}},l=p=>{if(_optionalChain([n, 'optionalAccess', _546 => _546.searchParameters])){let c=n.searchParameters;return{...p,search_parameters:{mode:c.mode,return_citations:c.returnCitations,from_date:c.fromDate,to_date:c.toDate,max_search_results:c.maxSearchResults,sources:_optionalChain([c, 'access', _547 => _547.sources, 'optionalAccess', _548 => _548.map, 'call', _549 => _549(d=>({type:d.type,country:d.country,excluded_websites:d.excludedWebsites,allowed_websites:d.allowedWebsites,safe_search:d.safeSearch,x_handles:d.xHandles,links:d.links}))])}}}return p};super({apiKey:e,config:i,options:n,apiURL:"https://api.x.ai/v1",modelInfo:r,models:o,supportFor:a,chatReqUpdater:l}),super.setName("Grok")}};var z=class{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:_api.SpanKind.SERVER,attributes:{[w.DB_SYSTEM]:this.name,[w.DB_OPERATION_NAME]:"upsert",[w.DB_TABLE]:e.table,[w.DB_NAMESPACE]:e.namespace,[w.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:_api.SpanKind.SERVER,attributes:{[w.DB_SYSTEM]:this.name,[w.DB_OPERATION_NAME]:"upsert",[w.DB_TABLE]:e[0].table,[w.DB_NAMESPACE]:e[0].namespace,[w.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:_api.SpanKind.SERVER,attributes:{[w.DB_SYSTEM]:this.name,[w.DB_OPERATION_NAME]:"upsert",[w.DB_TABLE]:e.table,[w.DB_NAMESPACE]:e.namespace,[w.DB_OPERATION_NAME]:"query"}},async t=>{try{return await this._query(e,{span:t})}finally{t.end()}}):await this._query(e)}};var gn="https://api.cloudflare.com/client/v4/accounts/",Se= exports.AxDBCloudflare = (_class14 =class extends z{constructor({apiKey:e,accountId:t,fetch:n,tracer:o}){if(!e||!t)throw new Error("Cloudflare credentials not set");super({name:"Cloudflare",fetch:n,tracer:o});_class14.prototype.__init46.call(this);_class14.prototype.__init47.call(this);_class14.prototype.__init48.call(this);,this.apiKey=e,this.accountId=t}__init46() {this._upsert=async(e,t,n)=>{let o=await D({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/upsert`,gn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _553 => _553.span])},{id:e.id,values:e.values,namespace:e.namespace,metadata:e.metadata});if(o.errors)throw new Error(`Cloudflare upsert failed: ${o.errors.map(({message:r})=>r).join(", ")}`);return{ids:o.result.ids}}}__init47() {this.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 o=e[0].table,r=await D({url:new URL(`${this.accountId}/vectorize/indexes/${o}/upsert`,gn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _554 => _554.span])},e.map(i=>({id:i.id,values:i.values,namespace:i.namespace,metadata:i.metadata})));if(r.errors)throw new Error(`Cloudflare batch upsert failed: ${r.errors.map(({message:i})=>i).join(", ")}`);return{ids:r.result.ids}}}__init48() {this.query=async(e,t)=>{let n=await D({url:new URL(`${this.accountId}/vectorize/indexes/${e.table}/query`,gn),headers:{"X-Auth-Key":this.apiKey},fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _555 => _555.span])},{vector:e.values,topK:e.limit||10,returnValues:!0});if(n.errors)throw new Error(`Cloudflare query failed: ${n.errors.map(({message:r})=>r).join(", ")}`);return{matches:n.result.matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,values:a,metadata:l}))}}}}, _class14);var X= (_class15 =class extends z{constructor({tracer:e}={}){super({name:"Memory",tracer:e});_class15.prototype.__init49.call(this);_class15.prototype.__init50.call(this);_class15.prototype.__init51.call(this);_class15.prototype.__init52.call(this);_class15.prototype.__init53.call(this);_class15.prototype.__init54.call(this);,this.state={}}__init49() {this._upsert=async(e,t,n)=>{if(!this.state[e.table])this.state[e.table]={[e.id]:e};else{let o=this.state[e.table];if(!o)throw new Error(`Table not found: ${e.table}`);o[e.id]=e}return{ids:[e.id]}}}__init50() {this._batchUpsert=async(e,t,n)=>{let o=[];for(let r of e){let i=await this.upsert(r,t);o.push(...i.ids)}return{ids:o}}}__init51() {this._query=async(e,t)=>{let n=this.state[e.table];if(!n)return{matches:[]};let o=[];return Object.entries(n).forEach(([r,i])=>{if(e.values&&i.values){let a=Ps(e.values,i.values);o.push({id:r,score:a,metadata:i.metadata})}}),o.sort((r,i)=>r.score-i.score),e.limit&&(o.length=e.limit),{matches:o}}}__init52() {this.getDB=()=>structuredClone(this.state)}__init53() {this.setDB=e=>{this.state=structuredClone(e)}}__init54() {this.clearDB=()=>{this.state={}}}}, _class15),Ps=(s,e)=>{if(s.length!==e.length)throw new Error("Vectors must be of the same length.");let t=0,n=0,o=0,r=!0,i=!0,a=new Float64Array(s),l=new Float64Array(e);for(let u=0;u<a.length;u++)t+=a[u]*l[u],n+=a[u]*a[u],o+=l[u]*l[u],a[u]!==0&&(r=!1),l[u]!==0&&(i=!1);if(r||i)return 1;let p=Math.sqrt(n),c=Math.sqrt(o);return 1-t/(p*c)};var Fs=s=>({namespace:s.namespace,topK:s.limit||10,filter:{},includeValues:!0,includeMetadata:!0,vector:_nullishCoalesce(s.values, () => ([])),id:s.id}),ke= exports.AxDBPinecone = (_class16 =class extends z{constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Pinecone API key not set");super({name:"Pinecone",fetch:n,tracer:o});_class16.prototype.__init55.call(this);_class16.prototype.__init56.call(this);_class16.prototype.__init57.call(this);,this.apiKey=e,this.apiURL=t}__init55() {this._upsert=async(e,t,n)=>(await this._batchUpsert([e],t,n),{ids:[e.id]})}__init56() {this._batchUpsert=async(e,t,n)=>{if(e.length===0)throw new Error("Batch request is empty");return await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/vectors/upsert",fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _558 => _558.span])},e.map(({id:o,values:r=[],metadata:i})=>({id:o,values:r,metadata:i}))),{ids:e.map(({id:o})=>o)}}}__init57() {this.query=async(e,t)=>{if(e.text)throw new Error("Pinecone does not support text");return{matches:(await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/query",fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _559 => _559.span])},Fs(e))).matches.map(({id:r,score:i,values:a,metadata:l})=>({id:r,score:i,metadata:l,values:a}))}}}}, _class16);var Ee= (_class17 =class extends z{constructor({apiKey:e,host:t,fetch:n,tracer:o}){if(!e||e==="")throw new Error("Weaviate API key not set");super({name:"Weaviate",fetch:n,tracer:o});_class17.prototype.__init58.call(this);_class17.prototype.__init59.call(this);_class17.prototype.__init60.call(this);,this.apiKey=e,this.apiURL=t}__init58() {this._upsert=async(e,t,n)=>{let o=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:`/v1/objects/${e.table}/${e.id}`,put:!!t,fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _577 => _577.span])},{id:e.id,class:e.table,tenant:e.namespace,vector:e.values,properties:_nullishCoalesce(e.metadata, () => ({}))});if(_optionalChain([o, 'optionalAccess', _578 => _578.result, 'optionalAccess', _579 => _579.errors]))throw new Error(`Weaviate upsert failed: ${o.result.errors.error.map(({message:r})=>r).join(", ")}`);return{ids:[o.id]}}}__init59() {this._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 o=e.map(i=>({id:i.id,class:i.table,tenant:i.namespace,vector:i.values,properties:_nullishCoalesce(i.metadata, () => ({}))})),r=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/batch/objects",fetch:this.fetch,span:_optionalChain([n, 'optionalAccess', _580 => _580.span])},{objects:o});if(_optionalChain([r, 'optionalAccess', _581 => _581.some, 'call', _582 => _582(({result:i})=>_optionalChain([i, 'optionalAccess', _583 => _583.errors]))]))throw new Error(`Weaviate batch upsert failed: ${r.map(({result:i})=>_optionalChain([i, 'optionalAccess', _584 => _584.errors, 'optionalAccess', _585 => _585.error, 'access', _586 => _586.map, 'call', _587 => _587(({message:a})=>a), 'access', _588 => _588.join, 'call', _589 => _589(", ")])).join(", ")}`);return{ids:r.map(({id:i})=>i)}}}__init60() {this._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: {
59
116
  vector: [${e.values.join(",")}],
60
117
  }`;else if(e.text)n=`nearText: {
61
118
  concepts: ['${e.text}'],
62
- }`;else throw new Error("Weaviate requires either text or values");let o=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _602 => _602.span])},{query:`{
119
+ }`;else throw new Error("Weaviate requires either text or values");let o=await D({url:this.apiURL,headers:{Authorization:`Bearer ${this.apiKey}`},name:"/v1/graphql",fetch:this.fetch,span:_optionalChain([t, 'optionalAccess', _590 => _590.span])},{query:`{
63
120
  Get {
64
121
  ${e.table} (
65
122
  limit: ${e.limit||10},
66
123
  ${n}
67
124
  ) {
68
- ${_optionalChain([e, 'access', _603 => _603.columns, 'optionalAccess', _604 => _604.join, 'call', _605 => _605(`
125
+ ${_optionalChain([e, 'access', _591 => _591.columns, 'optionalAccess', _592 => _592.join, 'call', _593 => _593(`
69
126
  `)])}
70
127
  }
71
128
  }
72
- }`});if(o.errors)throw new Error(`Weaviate query failed: ${o.errors.map(({message:a})=>a).join(", ")}`);let r=o.data.Get[e.table];return r?{matches:r.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}}}, _class17);var In=class{constructor(e){switch(e.name){case"weaviate":this.db=new De(e);break;case"pinecone":this.db=new Ge(e);break;case"cloudflare":this.db=new Fe(e);break;case"memory":this.db=new oe(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 bn="_internal",Rn= exports.AxDBManager = (_class18 =class{constructor({ai:e,db:t,config:n}){;_class18.prototype.__init53.call(this);_class18.prototype.__init54.call(this);_class18.prototype.__init55.call(this);this.ai=e,this.db=t,this.chunker=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _621 => _621.chunker]), () => (this.defaultChunker)),this.reranker=_optionalChain([n, 'optionalAccess', _622 => _622.reranker]),this.rewriter=_optionalChain([n, 'optionalAccess', _623 => _623.rewriter])}__init53() {this.defaultChunker=e=>e.split(/\n\n+/)}__init54() {this.insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
129
+ }`});if(o.errors)throw new Error(`Weaviate query failed: ${o.errors.map(({message:a})=>a).join(", ")}`);let r=o.data.Get[e.table];return r?{matches:r.map(a=>({id:a.id,score:1,metadata:a}))}:{matches:[]}}}}, _class17);var An=class{constructor(e){switch(e.name){case"weaviate":this.db=new Ee(e);break;case"pinecone":this.db=new ke(e);break;case"cloudflare":this.db=new Se(e);break;case"memory":this.db=new X(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 hn="_internal",xn= exports.AxDBManager = (_class18 =class{constructor({ai:e,db:t,config:n}){;_class18.prototype.__init61.call(this);_class18.prototype.__init62.call(this);_class18.prototype.__init63.call(this);this.ai=e,this.db=t,this.chunker=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _609 => _609.chunker]), () => (this.defaultChunker)),this.reranker=_optionalChain([n, 'optionalAccess', _610 => _610.reranker]),this.rewriter=_optionalChain([n, 'optionalAccess', _611 => _611.rewriter])}__init61() {this.defaultChunker=e=>e.split(/\n\n+/)}__init62() {this.insert=async(e,t)=>{try{let n=Array.isArray(e)?e.join(`
73
130
 
74
- `):e,o=this.chunker(n).filter(p=>p.length>0),r=_optionalChain([t, 'optionalAccess', _624 => _624.maxWordsPerChunk]),i=_optionalChain([t, 'optionalAccess', _625 => _625.minWordsPerChunk]),a=Ps({initialChunks:o,minWordsPerChunk:i,maxWordsPerChunk:r}),l=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _626 => _626.batchSize]), () => (10));for(let p=0;p<a.length;p+=l){let c=a.slice(p,p+l),u=(await this.ai.embed({texts:c},{abortSignal:_optionalChain([t, 'optionalAccess', _627 => _627.abortSignal])})).embeddings.map((m,A)=>({id:`chunk_${Date.now()+A}`,table:bn,values:m,metadata:{text:_nullishCoalesce(c[A], () => (""))}})).filter(m=>_optionalChain([m, 'access', _628 => _628.metadata, 'optionalAccess', _629 => _629.text])&&_optionalChain([m, 'access', _630 => _630.metadata, 'optionalAccess', _631 => _631.text, 'access', _632 => _632.length])>0);await this.db.batchUpsert(u)}}catch(n){throw new Error(`Error processing text: ${n}`)}}}__init55() {this.query=async(e,{topPercent:t,abortSignal:n}={})=>{let o=Array.isArray(e)?e:[e];if(typeof o[0]=="string"&&this.rewriter)for(let[l,p]of o.entries()){let{rewrittenQuery:c}=await this.rewriter.forward(this.ai,{query:p});o[l]=c}let r;typeof o[0]=="string"?r=(await this.ai.embed({texts:o},{abortSignal:n})).embeddings.map(p=>this.db.query({table:bn,values:p})):r=o.map(l=>this.db.query({table:bn,values:l}));let i=await Promise.all(r),a=[];for(let{matches:l}of i){let p=l.filter(u=>_optionalChain([u, 'access', _633 => _633.metadata, 'optionalAccess', _634 => _634.text])&&_optionalChain([u, 'access', _635 => _635.metadata, 'optionalAccess', _636 => _636.text, 'access', _637 => _637.length])>0).map(({score:u,metadata:m})=>({score:u,text:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _638 => _638.text]), () => (""))})),c=t&&t>1?t/100:t,d=c?_s(p,c):p;if(this.reranker){let{rankedItems:u}=await this.reranker.forward(this.ai,{query:o[0],items:d.map(A=>A.text)}),m=u.map(A=>d.find(g=>g.text===A)).filter(A=>A!==void 0);a.push(m)}else a.push(d)}return a}}}, _class18),Ps=({initialChunks:s,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],o="",r=0;return s.forEach(i=>{let a=i.split(/\s+/),l=a.length;if(r+l<=e)o+=`${i}
131
+ `):e,o=this.chunker(n).filter(p=>p.length>0),r=_optionalChain([t, 'optionalAccess', _612 => _612.maxWordsPerChunk]),i=_optionalChain([t, 'optionalAccess', _613 => _613.minWordsPerChunk]),a=Gs({initialChunks:o,minWordsPerChunk:i,maxWordsPerChunk:r}),l=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _614 => _614.batchSize]), () => (10));for(let p=0;p<a.length;p+=l){let c=a.slice(p,p+l),u=(await this.ai.embed({texts:c},{abortSignal:_optionalChain([t, 'optionalAccess', _615 => _615.abortSignal])})).embeddings.map((m,A)=>({id:`chunk_${Date.now()+A}`,table:hn,values:m,metadata:{text:_nullishCoalesce(c[A], () => (""))}})).filter(m=>_optionalChain([m, 'access', _616 => _616.metadata, 'optionalAccess', _617 => _617.text])&&_optionalChain([m, 'access', _618 => _618.metadata, 'optionalAccess', _619 => _619.text, 'access', _620 => _620.length])>0);await this.db.batchUpsert(u)}}catch(n){throw new Error(`Error processing text: ${n}`)}}}__init63() {this.query=async(e,{topPercent:t,abortSignal:n}={})=>{let o=Array.isArray(e)?e:[e];if(typeof o[0]=="string"&&this.rewriter)for(let[l,p]of o.entries()){let{rewrittenQuery:c}=await this.rewriter.forward(this.ai,{query:p});o[l]=c}let r;typeof o[0]=="string"?r=(await this.ai.embed({texts:o},{abortSignal:n})).embeddings.map(p=>this.db.query({table:hn,values:p})):r=o.map(l=>this.db.query({table:hn,values:l}));let i=await Promise.all(r),a=[];for(let{matches:l}of i){let p=l.filter(u=>_optionalChain([u, 'access', _621 => _621.metadata, 'optionalAccess', _622 => _622.text])&&_optionalChain([u, 'access', _623 => _623.metadata, 'optionalAccess', _624 => _624.text, 'access', _625 => _625.length])>0).map(({score:u,metadata:m})=>({score:u,text:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _626 => _626.text]), () => (""))})),c=t&&t>1?t/100:t,d=c?Ds(p,c):p;if(this.reranker){let{rankedItems:u}=await this.reranker.forward(this.ai,{query:o[0],items:d.map(A=>A.text)}),m=u.map(A=>d.find(g=>g.text===A)).filter(A=>A!==void 0);a.push(m)}else a.push(d)}return a}}}, _class18),Gs=({initialChunks:s,maxWordsPerChunk:e=350,minWordsPerChunk:t=250})=>{let n=[],o="",r=0;return s.forEach(i=>{let a=i.split(/\s+/),l=a.length;if(r+l<=e)o+=`${i}
75
132
 
76
133
  `,r+=l;else if(r>0&&r+l<=e*1.5)o+=`${i}
77
134
 
@@ -79,65 +136,114 @@ ${c}`:`Assistant: ${p.content}`}default:throw new Error("Unknown role")}}), 'acc
79
136
 
80
137
  `,r+=p.length)}else o=`${i}
81
138
 
82
- `,r=l}),(r>t||n.length===0)&&n.push(o.trim()),n},_s=(s,e=.1)=>{let t=[...s].sort((o,r)=>o.score-r.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var Ue= (_class19 =class{constructor(e){;_class19.prototype.__init56.call(this);this.options=e}__init56() {this.data=[]}addRequest(e,t){this.data.push(...e.map(n=>{let o=structuredClone(n);return{role:n.role,chat:[{index:t,value:o}]}})),_optionalChain([this, 'access', _639 => _639.options, 'optionalAccess', _640 => _640.debug])&&Fs(e,_optionalChain([this, 'access', _641 => _641.options, 'optionalAccess', _642 => _642.debugHideSystemPrompt]),_optionalChain([this, 'access', _643 => _643.options, 'optionalAccess', _644 => _644.logger]))}addFunctionResults(e){let t=e.map(({index:o,...r})=>({index:o,value:structuredClone(r)})),n=this.getLast();_optionalChain([n, 'optionalAccess', _645 => _645.role])==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t}),_optionalChain([this, 'access', _646 => _646.options, 'optionalAccess', _647 => _647.debug])&&Ds(e,_optionalChain([this, 'access', _648 => _648.options, 'optionalAccess', _649 => _649.logger]))}addResponse(e){let t=e.map(({index:n,...o})=>({index:n,value:structuredClone(o)}));if(this.data.push({role:"assistant",chat:t}),_optionalChain([this, 'access', _650 => _650.options, 'optionalAccess', _651 => _651.debug]))for(let n of e)nr(n,_optionalChain([this, 'access', _652 => _652.options, 'optionalAccess', _653 => _653.logger]))}updateResult({content:e,name:t,functionCalls:n,delta:o,index:r}){let i=this.data.at(-1),a=p=>{_optionalChain([this, 'access', _654 => _654.options, 'optionalAccess', _655 => _655.debug])&&(o&&typeof o=="string"?Gs(o,p):nr({content:e,name:t,functionCalls:n,index:r},p))};if(!i||i.role!=="assistant"||i.role==="assistant"&&!i.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:r,value:structuredClone({content:e,name:t,functionCalls:n})}]}),a(_optionalChain([this, 'access', _656 => _656.options, 'optionalAccess', _657 => _657.logger]));return}let l=i.chat.find(p=>p.index===r);if(!l){i.chat.push({index:r,value:structuredClone({content:e,name:t,functionCalls:n})}),a(_optionalChain([this, 'access', _658 => _658.options, 'optionalAccess', _659 => _659.logger]));return}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),a(_optionalChain([this, 'access', _660 => _660.options, 'optionalAccess', _661 => _661.logger]))}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>_optionalChain([n, 'access', _662 => _662.tags, 'optionalAccess', _663 => _663.includes, 'call', _664 => _664(e)]));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,o,r)=>(_optionalChain([o, 'access', _665 => _665.tags, 'optionalAccess', _666 => _666.includes, 'call', _667 => _667(e)])&&n.push(r),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return 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:o}of this.data){let r;n==="function"?r=o.filter(i=>i.index===e).map(i=>i.value):r=_optionalChain([o, 'access', _668 => _668.find, 'call', _669 => _669(i=>i.index===e), 'optionalAccess', _670 => _670.value]),Array.isArray(r)&&r.length>0?t.push(...r.map(i=>({...i,role:n}))):typeof r=="object"&&r!==null&&t.push({...r,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}}, _class19),Ne= exports.AxMemory = (_class20 =class{constructor(e){;_class20.prototype.__init57.call(this);this.options=e;this.defaultMemory=new Ue(e)}__init57() {this.memories=new Map}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Ue(this.options)),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)dn(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){mn(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)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Ue(this.options)):this.defaultMemory.reset()}}, _class20);function Fs(s,e,t){Array.isArray(s)?ge(s,e,t):yo(s,e,t)}function nr(s,e){Mt(s,e)}function Gs(s,e){Io(s,e)}function Ds(s,e){bo(s,e)}var re= (_class21 =class extends Error{constructor({message:e}){super(e);_class21.prototype.__init58.call(this);,this.name=this.constructor.name}__init58() {this.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()}}, _class21),pt=async(s,e)=>{for(let t of s){let{fn:n,message:o}=t,r=await n(e);if(r!==void 0&&!r)throw o?new re({message:o}):new Error("Assertion Failed: No message provided for assertion")}},Cn=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let o=s.filter(i=>i.fieldName===_optionalChain([e, 'access', _671 => _671.currField, 'optionalAccess', _672 => _672.name]));if(o.length===0)return;let r=t.substring(e.s);for(let i of o){let{message:a,fn:l}=i,p=await l(r,n);if(p!==void 0&&!p&&a)throw new re({message:a})}};var G= (_class22 =class extends Error{constructor({message:e,fields:t}){super(e);_class22.prototype.__init59.call(this);,this.fields=t,this.name=this.constructor.name}__init59() {this.getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(_optionalChain([t, 'optionalAccess', _675 => _675.name])){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return _optionalChain([t, 'optionalAccess', _676 => _676.isArray])?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))}}toString(){let e=t=>{let n=(()=>{switch(_optionalChain([t, 'optionalAccess', _677 => _677.name])){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return _optionalChain([t, 'optionalAccess', _678 => _678.isArray])?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
83
- `)}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}}, _class22);var or=s=>{let e=[],t=(n,o="")=>{if(!n||typeof n!="object")return;let r=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:o||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((i,a)=>{t(i,`${o}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:o||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((i,a)=>{t(i,`${o}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:o||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((i,a)=>{t(i,`${o}allOf[${a}].`)});return}if(n.type){if(!r.includes(n.type)){e.push({path:o||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${r.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:o||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let i in n.properties){let a=n.properties[i];if(a!=null){if(typeof a!="object"){e.push({path:`${o}${i}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${i}: { type: "string", description: "..." }`});continue}t(a,`${o}${i}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:o||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let i of n.required)typeof i!="string"?e.push({path:`${o}required`,issue:`Required property names must be strings, got ${typeof i}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):i in n.properties||e.push({path:`${o}required`,issue:`Required property '${i}' is not defined in properties`,fix:`Either add '${i}' to properties or remove it from required`,example:`properties: { ${i}: { type: "string" } }`})}}}n.type==="array"&&n.items&&(typeof n.items!="object"?e.push({path:`${o}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${o}items.`))}};if(t(s),e.length>0){let n=["JSON Schema validation failed:","",...e.map((o,r)=>{let i=[`${r+1}. Path: ${o.path}`,` Issue: ${o.issue}`,` Fix: ${o.fix}`];return o.example&&i.push(` Example: ${o.example}`),i.join(`
139
+ `,r=l}),(r>t||n.length===0)&&n.push(o.trim()),n},Ds=(s,e=.1)=>{let t=[...s].sort((o,r)=>o.score-r.score),n=Math.ceil(t.length*e);return t.slice(0,n)};var Me= (_class19 =class{constructor() { _class19.prototype.__init64.call(this); }__init64() {this.data=[]}addRequest(e,t){this.data.push(...e.map(n=>{let o=structuredClone(n);return{role:n.role,chat:[{index:t,value:o}]}}))}addFunctionResults(e){let t=e.map(({index:o,...r})=>({index:o,value:structuredClone(r)})),n=this.getLast();_optionalChain([n, 'optionalAccess', _627 => _627.role])==="function"?n.chat.push(...t):this.data.push({role:"function",chat:t})}addResponse(e){let t=e.map(({index:n,...o})=>({index:n,value:structuredClone(o)}));this.data.push({role:"assistant",chat:t})}updateResult({content:e,name:t,functionCalls:n,index:o}){let r=this.data.at(-1);if(!r||r.role!=="assistant"||r.role==="assistant"&&!r.updatable){this.data.push({role:"assistant",updatable:!0,chat:[{index:o,value:structuredClone({content:e,name:t,functionCalls:n})}]});return}let i=r.chat.find(a=>a.index===o);if(!i){r.chat.push({index:o,value:structuredClone({content:e,name:t,functionCalls:n})});return}typeof e=="string"&&e.trim()!==""&&(i.value.content=e),typeof t=="string"&&t.trim()!==""&&(i.value.name=t),Array.isArray(n)&&n.length>0&&(i.value.functionCalls=n)}addTag(e){let t=this.data.at(-1);t&&(t.tags||(t.tags=[]),t.tags.includes(e)||t.tags.push(e))}rewindToTag(e){let t=this.data.findIndex(n=>_optionalChain([n, 'access', _628 => _628.tags, 'optionalAccess', _629 => _629.includes, 'call', _630 => _630(e)]));if(t===-1)throw new Error(`Tag "${e}" not found`);return this.data.splice(t)}removeByTag(e){let t=this.data.reduce((n,o,r)=>(_optionalChain([o, 'access', _631 => _631.tags, 'optionalAccess', _632 => _632.includes, 'call', _633 => _633(e)])&&n.push(r),n),[]);if(t.length===0)throw new Error(`No items found with tag "${e}"`);return 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:o}of this.data){let r;n==="function"?r=o.filter(i=>i.index===e).map(i=>i.value):r=_optionalChain([o, 'access', _634 => _634.find, 'call', _635 => _635(i=>i.index===e), 'optionalAccess', _636 => _636.value]),Array.isArray(r)&&r.length>0?t.push(...r.map(i=>({...i,role:n}))):typeof r=="object"&&r!==null&&t.push({...r,role:n})}return t}getLast(){return this.data.at(-1)}reset(){this.data=[]}}, _class19),_e= exports.AxMemory = (_class20 =class{__init65() {this.memories=new Map}constructor(){;_class20.prototype.__init65.call(this);this.defaultMemory=new Me}getMemory(e){return e?(this.memories.has(e)||this.memories.set(e,new Me),this.memories.get(e)):this.defaultMemory}addRequest(e,t){for(let n of e)an(n);this.getMemory(t).addRequest(e,0)}addResponse(e,t){ln(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)}history(e,t){return this.getMemory(t).history(e)}getLast(e){return this.getMemory(e).getLast()}reset(e){e?this.memories.set(e,new Me):this.defaultMemory.reset()}}, _class20);var Z= (_class21 =class extends Error{constructor({message:e}){super(e);_class21.prototype.__init66.call(this);,this.name=this.constructor.name}__init66() {this.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()}}, _class21),it=async(s,e)=>{for(let t of s){let{fn:n,message:o}=t,r=await n(e);if(r!==void 0&&!r)throw o?new Z({message:o}):new Error("Assertion Failed: No message provided for assertion")}},fn=async(s,e,t,n=!1)=>{if(!e.currField||e.s===-1||!s||s.length===0)return;let o=s.filter(i=>i.fieldName===_optionalChain([e, 'access', _637 => _637.currField, 'optionalAccess', _638 => _638.name]));if(o.length===0)return;let r=t.substring(e.s);for(let i of o){let{message:a,fn:l}=i,p=await l(r,n);if(p!==void 0&&!p&&a)throw new Z({message:a})}};var rr={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Pe,yn=s=>{if(Pe)return Pe;let e=_nullishCoalesce(s, () => (E.meter));if(e)return Pe=Ns(e),Pe};var Us=()=>{let s=[];return E.meter||s.push("Global meter not initialized"),!Pe&&E.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Ns=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),at=rr,$s= exports.axUpdateMetricsConfig =s=>{at={...at,...s}},Ls= exports.axGetMetricsConfig =()=>({...at}),j=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=at.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},sr=(s,e,t,n,o,r)=>{try{let i=j({success:t.toString(),...n?{signature:n}:{},...o?{ai_service:o}:{},...r?{model:r}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},lt=(s,e,t,n)=>{try{let o=j({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,o),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,o),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},In=(s,e,t)=>{try{let n=j({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},ir=(s,e)=>{try{let t=j({error_type:"refusal",...e?{signature:e}:{}});s.validationErrorsCounter&&s.validationErrorsCounter.add(1,t)}catch(t){console.warn("Failed to record refusal error metric:",t)}},bn=(s,e,t,n,o)=>{try{let r=j({success:t.toString(),...o?{signature:o}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,r),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,r),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,r),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,r))}catch(r){console.warn("Failed to record error correction metric:",r)}},Rn=(s,e,t,n,o=!1,r)=>{try{let i=j({functions_enabled:e.toString(),had_function_calls:n.toString(),...r?{signature:r}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),o&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},ar=(s,e,t,n)=>{try{let o=j({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,o),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},lr=(s,e,t,n,o)=>{try{let r=j({is_streaming:e.toString(),...o?{signature:o}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,r),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,r),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record streaming metric:",r)}},pr=(s,e,t,n,o)=>{try{let r=j({result_picker_used:t.toString(),...o?{signature:o}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,r),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,r),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record samples metric:",r)}},cr=(s,e,t,n,o,r)=>{try{let i=j({...r?{signature:r}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(o,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},pt=(s,e,t,n)=>{try{let o=j({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,o);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,o);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,o);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};var G= (_class22 =class extends Error{constructor({message:e,fields:t}){super(e);_class22.prototype.__init67.call(this);,this.fields=t,this.name=this.constructor.name}__init67() {this.getFixingInstructions=()=>{let e=t=>{let n=(()=>{switch(_optionalChain([t, 'optionalAccess', _641 => _641.name])){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return _optionalChain([t, 'optionalAccess', _642 => _642.isArray])?`json array of ${n} items`:n};return this.fields.map(t=>({name:"outputError",title:"Output Correction Required",description:`The section labeled '${t.title}' does not match the expected format of '${e(t.type)}'. ${this.message} Please revise your response to ensure it conforms to the specified format.`}))}}toString(){let e=t=>{let n=(()=>{switch(_optionalChain([t, 'optionalAccess', _643 => _643.name])){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return'date ("YYYY-MM-DD" format)';case"datetime":return'date time ("YYYY-MM-DD HH:mm Timezone" format)';case"json":return"JSON object";case"class":return"classification class";case"code":return"code";default:return"string"}})();return _optionalChain([t, 'optionalAccess', _644 => _644.isArray])?`json array of ${n} items`:n};return[`${this.name}: ${this.message}`,...this.fields.map(t=>` - ${t.title}: Expected format '${e(t.type)}'`)].join(`
140
+ `)}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}}, _class22),ur=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _645 => _645.map, 'call', _646 => _646(p=>p.title), 'access', _647 => _647.join, 'call', _648 => _648(", ")]), () => (""));fo(s,e,l,n)}return o&&In(o,"validation",r),i&&i.addEvent("validation.error",{message:s.toString(),fixing_instructions:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _649 => _649.map, 'call', _650 => _650(l=>l.title), 'access', _651 => _651.join, 'call', _652 => _652(", ")]), () => (""))}),a},dr=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:i})=>{let a=s.getFixingInstructions();if(t&&n){let l=_nullishCoalesce(_optionalChain([a, 'optionalAccess', _653 => _653.map, 'call', _654 => _654(p=>p.title), 'access', _655 => _655.join, 'call', _656 => _656(", ")]), () => (""));yo(s,e,l,n)}return o&&In(o,"assertion",r),i&&i.addEvent("assertion.error",{message:s.toString(),fixing_instructions:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _657 => _657.map, 'call', _658 => _658(l=>l.title), 'access', _659 => _659.join, 'call', _660 => _660(", ")]), () => (""))}),a},mr=({error:s,errCount:e,debug:t,logger:n,metricsInstruments:o,signatureName:r,span:i})=>{t&&n&&Io(s,e,n),o&&ir(o,r),i&&i.addEvent("refusal.error",{message:s.toString()})};var gr=s=>{let e=[],t=(n,o="")=>{if(!n||typeof n!="object")return;let r=["array","integer","number","string","boolean","null","object"];if(n.anyOf&&Array.isArray(n.anyOf)){n.anyOf.length===0&&e.push({path:o||"root",issue:"anyOf array is empty",fix:"Add at least one schema to the anyOf array",example:'anyOf: [{ type: "string" }, { type: "null" }]'}),n.anyOf.forEach((i,a)=>{t(i,`${o}anyOf[${a}].`)});return}if(n.oneOf&&Array.isArray(n.oneOf)){n.oneOf.length===0&&e.push({path:o||"root",issue:"oneOf array is empty",fix:"Add at least one schema to the oneOf array",example:'oneOf: [{ type: "string" }, { type: "number" }]'}),n.oneOf.forEach((i,a)=>{t(i,`${o}oneOf[${a}].`)});return}if(n.allOf&&Array.isArray(n.allOf)){n.allOf.length===0&&e.push({path:o||"root",issue:"allOf array is empty",fix:"Add at least one schema to the allOf array",example:'allOf: [{ type: "object" }, { properties: { name: { type: "string" } } }]'}),n.allOf.forEach((i,a)=>{t(i,`${o}allOf[${a}].`)});return}if(n.type){if(!r.includes(n.type)){e.push({path:o||"root",issue:`Invalid type '${n.type}'`,fix:`Change type to one of: ${r.join(", ")}`,example:'{ type: "string" } or { type: "object" }'});return}if(n.type==="object"){if(n.properties)if(typeof n.properties!="object"||Array.isArray(n.properties))e.push({path:o||"root",issue:"properties must be an object, not an array or primitive",fix:"Change properties to be an object with property names as keys",example:'properties: { name: { type: "string" }, age: { type: "number" } }'});else for(let i in n.properties){let a=n.properties[i];if(a!=null){if(typeof a!="object"){e.push({path:`${o}${i}`,issue:`Property schema must be an object, got ${typeof a}`,fix:"Define the property as a proper schema object",example:`${i}: { type: "string", description: "..." }`});continue}t(a,`${o}${i}.`)}}if(n.required){if(!Array.isArray(n.required))e.push({path:o||"root",issue:`'required' must be an array, got ${typeof n.required}`,fix:"Change required to be an array of property names",example:'required: ["name", "email"] instead of required: "name,email"'});else if(n.required.length!==0){if(n.properties)for(let i of n.required)typeof i!="string"?e.push({path:`${o}required`,issue:`Required property names must be strings, got ${typeof i}`,fix:"Ensure all items in required array are strings",example:'required: ["name", "email"] not required: [123, "email"]'}):i in n.properties||e.push({path:`${o}required`,issue:`Required property '${i}' is not defined in properties`,fix:`Either add '${i}' to properties or remove it from required`,example:`properties: { ${i}: { type: "string" } }`})}}}n.type==="array"&&n.items&&(typeof n.items!="object"?e.push({path:`${o}items`,issue:`Array items schema must be an object, got ${typeof n.items}`,fix:"Define items as a proper schema object",example:'items: { type: "string" } or items: { type: "object", properties: {...} }'}):t(n.items,`${o}items.`))}};if(t(s),e.length>0){let n=["JSON Schema validation failed:","",...e.map((o,r)=>{let i=[`${r+1}. Path: ${o.path}`,` Issue: ${o.issue}`,` Fix: ${o.fix}`];return o.example&&i.push(` Example: ${o.example}`),i.join(`
84
141
  `)}),"","Please fix these issues and try again."].join(`
85
- `);throw new Error(n)}};var ct= (_class23 =class extends Error{constructor(t){super();_class23.prototype.__init60.call(this);;this.fields=t;this.name=this.constructor.name}__init60() {this.getFields=()=>this.fields}toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
86
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}}, _class23),ut= (_class24 =class extends Error{constructor(t,n,o){super();_class24.prototype.__init61.call(this);_class24.prototype.__init62.call(this);;this.fields=t;this.func=n;this.funcId=o}__init61() {this.getFunctionId=()=>this.funcId}getFieldDescription(t){if(!_optionalChain([this, 'access', _679 => _679.func, 'access', _680 => _680.parameters, 'optionalAccess', _681 => _681.properties, 'optionalAccess', _682 => _682[t]]))return"";let n=this.func.parameters.properties[t],o=n.description;return _optionalChain([n, 'access', _683 => _683.enum, 'optionalAccess', _684 => _684.length])&&(o+=` Allowed values are: ${n.enum.join(", ")}`),o}__init62() {this.getFixingInstructions=()=>{let t=this.fields.map(n=>{let o=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${o}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
142
+ `);throw new Error(n)}};var ct= (_class23 =class extends Error{constructor(t){super();_class23.prototype.__init68.call(this);;this.fields=t;this.name=this.constructor.name}__init68() {this.getFields=()=>this.fields}toString(){return[`${this.name}: Function validation error`,...this.fields.map(t=>` - ${t.field}: ${t.message}`)].join(`
143
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}}, _class23),ut= (_class24 =class extends Error{constructor(t,n,o){super();_class24.prototype.__init69.call(this);_class24.prototype.__init70.call(this);;this.fields=t;this.func=n;this.funcId=o}__init69() {this.getFunctionId=()=>this.funcId}getFieldDescription(t){if(!_optionalChain([this, 'access', _661 => _661.func, 'access', _662 => _662.parameters, 'optionalAccess', _663 => _663.properties, 'optionalAccess', _664 => _664[t]]))return"";let n=this.func.parameters.properties[t],o=n.description;return _optionalChain([n, 'access', _665 => _665.enum, 'optionalAccess', _666 => _666.length])&&(o+=` Allowed values are: ${n.enum.join(", ")}`),o}__init70() {this.getFixingInstructions=()=>{let t=this.fields.map(n=>{let o=this.getFieldDescription(n.field)||"";return`- \`${n.field}\` - ${n.message} (${o}).`});return`Errors In Function Arguments: Fix the following invalid arguments to '${this.func.name}'
87
144
  ${t.join(`
88
145
  `)}`}}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(`
89
- `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}}, _class24),dt= exports.AxFunctionProcessor = (_class25 =class{__init63() {this.funcList=[]}constructor(e){;_class25.prototype.__init63.call(this);_class25.prototype.__init64.call(this);_class25.prototype.__init65.call(this);this.funcList=e}__init64() {this.executeFunction=async(e,t,n)=>{let o;typeof t.args=="string"&&t.args.length>0?o=JSON.parse(t.args):o=t.args;let r=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,i;return e.parameters?i=e.func.length===2?await e.func(o,r):await e.func(o):i=e.func.length===1?await e.func(r):await e.func(),(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _686 => _686.functionResultFormatter]), () => (k.functionResultFormatter)))(i)}}__init65() {this.execute=async(e,t)=>{let n=this.funcList.find(o=>o.name.localeCompare(e.name)===0);if(!n)throw new Error(`Function not found: ${e.name}`);if(!n.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(n,e,t)}catch(o){throw o instanceof ct?new ut(o.getFields(),n,e.id):o}}}}, _class25),Tn=(s,e)=>{if(s.length===0)return[..._nullishCoalesce(e, () => ([]))];let t=s.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(o=>o.parameters))n.parameters&&or(n.parameters);return[..._nullishCoalesce(e, () => ([])),...t]},wn=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:o,traceId:r,span:i,excludeContentFromTrace:a,index:l,functionResultFormatter:p})=>{let c=new dt(e),d=new Set,u=t.map(g=>{if(!g.id)throw new Error(`Function ${g.name} did not return an ID`);return c.execute(g,{sessionId:o,traceId:r,ai:s,functionResultFormatter:p}).then(h=>{if(d.add(g.name.toLowerCase()),i){let I={name:g.name};a||(I.args=g.args,I.result=_nullishCoalesce(h, () => (""))),i.addEvent("function.call",I)}return{result:_nullishCoalesce(h, () => ("")),role:"function",functionId:g.id,index:l}}).catch(h=>{if(!(h instanceof ut))throw h;let I=h.getFixingInstructions();if(i){let x={name:g.name,message:h.toString()};a||(x.args=g.args,x.fixing_instructions=I),i.addEvent("function.error",x)}return s.getOptions().debug&&s.getLogger()(`\u274C Function Error Correction:
90
- ${I}`,{tags:["error"]}),{functionId:g.id,isError:!0,index:l,result:I,role:"function"}})}),A=(await Promise.all(u)).filter(g=>g!==void 0);return n.addFunctionResults(A,o),A.some(g=>g.isError)&&n.addTag("error",o),d};function vn(s,e,t,n){if(!e||e.length===0)return;if(!s.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(r=>({id:r.id,name:r.function.name,args:r.function.params}))}function rr(s,e,t){let n=e;return!t&&(n==="required"||typeof n=="function")?{functions:[],functionCall:void 0}:s?{functions:s.map(r=>"toFunction"in r?r.toFunction():r).flat(),functionCall:n}:{functions:[],functionCall:n}}var sr={enabled:!0,enabledCategories:["generation","streaming","functions","errors","performance"],maxLabelLength:100,samplingRate:1},Le,On=s=>{if(Le)return Le;let e=_nullishCoalesce(s, () => (k.meter));if(e)return Le=Ns(e),Le};var Us=()=>{let s=[];return k.meter||s.push("Global meter not initialized"),!Le&&k.meter&&s.push("Metrics instruments not created despite available meter"),{healthy:s.length===0,issues:s}},Ns=s=>({generationLatencyHistogram:s.createHistogram("ax_gen_generation_duration_ms",{description:"End-to-end duration of AxGen generation requests",unit:"ms"}),generationRequestsCounter:s.createCounter("ax_gen_generation_requests_total",{description:"Total number of AxGen generation requests"}),generationErrorsCounter:s.createCounter("ax_gen_generation_errors_total",{description:"Total number of failed AxGen generations"}),multiStepGenerationsCounter:s.createCounter("ax_gen_multistep_generations_total",{description:"Total number of generations that required multiple steps"}),stepsPerGenerationHistogram:s.createHistogram("ax_gen_steps_per_generation",{description:"Number of steps taken per generation"}),maxStepsReachedCounter:s.createCounter("ax_gen_max_steps_reached_total",{description:"Total number of generations that hit max steps limit"}),validationErrorsCounter:s.createCounter("ax_gen_validation_errors_total",{description:"Total number of validation errors encountered"}),assertionErrorsCounter:s.createCounter("ax_gen_assertion_errors_total",{description:"Total number of assertion errors encountered"}),errorCorrectionAttemptsHistogram:s.createHistogram("ax_gen_error_correction_attempts",{description:"Number of error correction attempts per generation"}),errorCorrectionSuccessCounter:s.createCounter("ax_gen_error_correction_success_total",{description:"Total number of successful error corrections"}),errorCorrectionFailureCounter:s.createCounter("ax_gen_error_correction_failure_total",{description:"Total number of failed error corrections"}),maxRetriesReachedCounter:s.createCounter("ax_gen_max_retries_reached_total",{description:"Total number of generations that hit max retries limit"}),functionsEnabledGenerationsCounter:s.createCounter("ax_gen_functions_enabled_generations_total",{description:"Total number of generations with functions enabled"}),functionCallStepsCounter:s.createCounter("ax_gen_function_call_steps_total",{description:"Total number of steps that included function calls"}),functionsExecutedPerGenerationHistogram:s.createHistogram("ax_gen_functions_executed_per_generation",{description:"Number of unique functions executed per generation"}),functionErrorCorrectionCounter:s.createCounter("ax_gen_function_error_correction_total",{description:"Total number of function-related error corrections"}),fieldProcessorsExecutedCounter:s.createCounter("ax_gen_field_processors_executed_total",{description:"Total number of field processors executed"}),streamingFieldProcessorsExecutedCounter:s.createCounter("ax_gen_streaming_field_processors_executed_total",{description:"Total number of streaming field processors executed"}),streamingGenerationsCounter:s.createCounter("ax_gen_streaming_generations_total",{description:"Total number of streaming generations"}),streamingDeltasEmittedCounter:s.createCounter("ax_gen_streaming_deltas_emitted_total",{description:"Total number of streaming deltas emitted"}),streamingFinalizationLatencyHistogram:s.createHistogram("ax_gen_streaming_finalization_duration_ms",{description:"Duration of streaming response finalization",unit:"ms"}),samplesGeneratedHistogram:s.createHistogram("ax_gen_samples_generated",{description:"Number of samples generated per request"}),resultPickerUsageCounter:s.createCounter("ax_gen_result_picker_usage_total",{description:"Total number of times result picker was used"}),resultPickerLatencyHistogram:s.createHistogram("ax_gen_result_picker_duration_ms",{description:"Duration of result picker execution",unit:"ms"}),inputFieldsGauge:s.createGauge("ax_gen_input_fields",{description:"Number of input fields in signature"}),outputFieldsGauge:s.createGauge("ax_gen_output_fields",{description:"Number of output fields in signature"}),examplesUsedGauge:s.createGauge("ax_gen_examples_used",{description:"Number of examples used in generation"}),demosUsedGauge:s.createGauge("ax_gen_demos_used",{description:"Number of demos used in generation"}),promptRenderLatencyHistogram:s.createHistogram("ax_gen_prompt_render_duration_ms",{description:"Duration of prompt template rendering",unit:"ms"}),extractionLatencyHistogram:s.createHistogram("ax_gen_extraction_duration_ms",{description:"Duration of value extraction from responses",unit:"ms"}),assertionLatencyHistogram:s.createHistogram("ax_gen_assertion_duration_ms",{description:"Duration of assertion checking",unit:"ms"}),stateCreationLatencyHistogram:s.createHistogram("ax_gen_state_creation_duration_ms",{description:"Duration of state creation for multiple samples",unit:"ms"}),memoryUpdateLatencyHistogram:s.createHistogram("ax_gen_memory_update_duration_ms",{description:"Duration of memory updates during generation",unit:"ms"})}),mt=sr,Ls= exports.axUpdateMetricsConfig =s=>{mt={...mt,...s}},Bs= exports.axGetMetricsConfig =()=>({...mt}),W=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=mt.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},ir=(s,e,t,n,o,r)=>{try{let i=W({success:t.toString(),...n?{signature:n}:{},...o?{ai_service:o}:{},...r?{model:r}:{}});s.generationLatencyHistogram&&s.generationLatencyHistogram.record(e,i),s.generationRequestsCounter&&s.generationRequestsCounter.add(1,i),!t&&s.generationErrorsCounter&&s.generationErrorsCounter.add(1,i)}catch(i){console.warn("Failed to record generation metric:",i)}},gt=(s,e,t,n)=>{try{let o=W({...n?{signature:n}:{}});e>1&&s.multiStepGenerationsCounter&&s.multiStepGenerationsCounter.add(1,o),s.stepsPerGenerationHistogram&&s.stepsPerGenerationHistogram.record(e,o),e>=t&&s.maxStepsReachedCounter&&s.maxStepsReachedCounter.add(1,o)}catch(o){console.warn("Failed to record multi-step metric:",o)}},Sn=(s,e,t)=>{try{let n=W({error_type:e,...t?{signature:t}:{}});e==="validation"&&s.validationErrorsCounter&&s.validationErrorsCounter.add(1,n),e==="assertion"&&s.assertionErrorsCounter&&s.assertionErrorsCounter.add(1,n)}catch(n){console.warn("Failed to record validation error metric:",n)}},kn=(s,e,t,n,o)=>{try{let r=W({success:t.toString(),...o?{signature:o}:{}});s.errorCorrectionAttemptsHistogram&&s.errorCorrectionAttemptsHistogram.record(e,r),t&&s.errorCorrectionSuccessCounter&&s.errorCorrectionSuccessCounter.add(1,r),t||(s.errorCorrectionFailureCounter&&s.errorCorrectionFailureCounter.add(1,r),e>=n&&s.maxRetriesReachedCounter&&s.maxRetriesReachedCounter.add(1,r))}catch(r){console.warn("Failed to record error correction metric:",r)}},Mn=(s,e,t,n,o=!1,r)=>{try{let i=W({functions_enabled:e.toString(),had_function_calls:n.toString(),...r?{signature:r}:{}});e&&s.functionsEnabledGenerationsCounter&&s.functionsEnabledGenerationsCounter.add(1,i),n&&s.functionCallStepsCounter&&s.functionCallStepsCounter.add(1,i),t>0&&s.functionsExecutedPerGenerationHistogram&&s.functionsExecutedPerGenerationHistogram.record(t,i),o&&s.functionErrorCorrectionCounter&&s.functionErrorCorrectionCounter.add(1,i)}catch(i){console.warn("Failed to record function calling metric:",i)}},ar=(s,e,t,n)=>{try{let o=W({...n?{signature:n}:{}});e>0&&s.fieldProcessorsExecutedCounter&&s.fieldProcessorsExecutedCounter.add(e,o),t>0&&s.streamingFieldProcessorsExecutedCounter&&s.streamingFieldProcessorsExecutedCounter.add(t,o)}catch(o){console.warn("Failed to record field processing metric:",o)}},lr=(s,e,t,n,o)=>{try{let r=W({is_streaming:e.toString(),...o?{signature:o}:{}});e&&s.streamingGenerationsCounter&&s.streamingGenerationsCounter.add(1,r),t>0&&s.streamingDeltasEmittedCounter&&s.streamingDeltasEmittedCounter.add(t,r),n&&s.streamingFinalizationLatencyHistogram&&s.streamingFinalizationLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record streaming metric:",r)}},pr=(s,e,t,n,o)=>{try{let r=W({result_picker_used:t.toString(),...o?{signature:o}:{}});s.samplesGeneratedHistogram&&s.samplesGeneratedHistogram.record(e,r),t&&s.resultPickerUsageCounter&&s.resultPickerUsageCounter.add(1,r),n&&s.resultPickerLatencyHistogram&&s.resultPickerLatencyHistogram.record(n,r)}catch(r){console.warn("Failed to record samples metric:",r)}},cr=(s,e,t,n,o,r)=>{try{let i=W({...r?{signature:r}:{}});s.inputFieldsGauge&&s.inputFieldsGauge.record(e,i),s.outputFieldsGauge&&s.outputFieldsGauge.record(t,i),s.examplesUsedGauge&&s.examplesUsedGauge.record(n,i),s.demosUsedGauge&&s.demosUsedGauge.record(o,i)}catch(i){console.warn("Failed to record signature complexity metrics:",i)}},At=(s,e,t,n)=>{try{let o=W({metric_type:e,...n?{signature:n}:{}});switch(e){case"prompt_render":s.promptRenderLatencyHistogram&&s.promptRenderLatencyHistogram.record(t,o);break;case"extraction":s.extractionLatencyHistogram&&s.extractionLatencyHistogram.record(t,o);break;case"assertion":s.assertionLatencyHistogram&&s.assertionLatencyHistogram.record(t,o);break;case"state_creation":s.stateCreationLatencyHistogram&&s.stateCreationLatencyHistogram.record(t,o);break;case"memory_update":s.memoryUpdateLatencyHistogram&&s.memoryUpdateLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record performance metric:",o)}};function ur(s,e){for(let t of e){let n=s.find(o=>o.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)):s.push(t)}}var _dayjs = require('dayjs'); var _dayjs2 = _interopRequireDefault(_dayjs);var _customParseFormat = require('dayjs/plugin/customParseFormat'); var _customParseFormat2 = _interopRequireDefault(_customParseFormat);var _timezone = require('dayjs/plugin/timezone'); var _timezone2 = _interopRequireDefault(_timezone);var _utc = require('dayjs/plugin/utc'); var _utc2 = _interopRequireDefault(_utc);_dayjs2.default.extend(_utc2.default);_dayjs2.default.extend(_timezone2.default);_dayjs2.default.extend(_customParseFormat2.default);function dr(s,e,t=!1){try{return js(e)}catch(n){if(s.isOptional&&!t)return;let o=n.message;throw new G({fields:[s],message:o,value:e})}}function js(s){if(!_dayjs2.default.call(void 0, s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return _dayjs2.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function mr(s,e,t=!1){try{return Hs(e)}catch(n){if(s.isOptional&&!t)return;let o=n.message;throw new G({fields:[s],message:o,value:e})}}function Hs(s){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=s.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,o]=t;if(!n||!o)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 r=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=_dayjs2.default.tz(n,r,o);if(!i.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return i.utc().toDate()}catch (e4){throw new Error(`Unrecognized time zone ${o}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var gr=s=>_dayjs2.default.call(void 0, s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var En=new H,ue=(s,e,t,n,o,r=20)=>{let i=(s/e*100).toFixed(1),a=Math.round(r*s/e),l=r-a,p=En.blueBright("\u2588".repeat(a)),c=" ".repeat(l),d=e>0?(t/e*100).toFixed(1):"0.0",u=o.includes("Running MIPROv2 optimization")?"Testing prompt variations":o.includes("Tuning Prompt")?"Generating training examples":o;process.stdout.write(`\u2502 ${u}: ${s}/${e} (${En.yellow(i)}%) |${p}${c}| Success rate: ${En.greenBright(d)}%
91
- `)},ht=(s,e)=>{let t=_nullishCoalesce(s.type, () => ({name:"string",isArray:!1})),n=(a,l)=>{switch(a){case"class":return typeof l=="string";case"code":return typeof l=="string";case"string":return typeof l=="string";case"number":return typeof l=="number";case"boolean":return typeof l=="boolean";case"date":return l instanceof Date||typeof l=="string";case"datetime":return l instanceof Date||typeof l=="string";case"json":return typeof l=="object"||typeof l=="string";default:return!1}},o=a=>!(!a||typeof a!="object"||!("mimeType"in a)||!("data"in a));if(_optionalChain([s, 'access', _687 => _687.type, 'optionalAccess', _688 => _688.name])==="image"){let a;if(Array.isArray(e)){for(let l of e)if(!o(l)){a="object ({ mimeType: string; data: string })";break}}else o(e)||(a="object ({ mimeType: string; data: string })");if(a)throw new Error(`Validation failed: Expected '${s.name}' to be type '${a}' instead got '${e}'`);return}let r=a=>!(!a||typeof a!="object"||!("data"in a));if(_optionalChain([s, 'access', _689 => _689.type, 'optionalAccess', _690 => _690.name])==="audio"){let a;if(Array.isArray(e)){for(let l of e)if(!r(l)){a="object ({ data: string; format?: string })";break}}else r(e)||(a="object ({ data: string; format?: string })");if(a)throw new Error(`Validation failed: Expected '${s.name}' to be type '${a}' instead got '${e}'`);return}let i=!0;if(t.isArray){if(!Array.isArray(e))i=!1;else for(let a of e)if(!n(t.name,a)){i=!1;break}}else i=n(t.name,e);if(!i){let a=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${s.name}' to be a ${_optionalChain([s, 'access', _691 => _691.type, 'optionalAccess', _692 => _692.isArray])?"an array of ":""}${t.name} instead got '${a}' (${JSON.stringify(e)})`)}};function Ar(s){let e={};for(let t of s){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let o=e[n];if(o){let r=_nullishCoalesce(o.tokens, () => ({promptTokens:0,completionTokens:0,totalTokens:0}));r.promptTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _693 => _693.tokens, 'optionalAccess', _694 => _694.promptTokens]), () => (0)),r.completionTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _695 => _695.tokens, 'optionalAccess', _696 => _696.completionTokens]), () => (0)),r.totalTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _697 => _697.tokens, 'optionalAccess', _698 => _698.totalTokens]), () => (0)),o.tokens=r}}return Object.values(e)}var hr=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
92
- `),o=[];for(let r of n){let i=r.trim();if(i){if(i[0]&&e.has(i[0]))o.push(i.slice(1).trim());else if(t.test(i))o.push(i.replace(t,"").trim());else if(o.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(o.length===0)throw new Error("Could not parse markdown list: no valid list items found");return o};function _n(s,e){let{index:t,delta:n,version:o}=e,r=_optionalChain([s, 'access', _699 => _699.find, 'call', _700 => _700(i=>i.index===t), 'optionalAccess', _701 => _701.delta]);if(!r)return s.push({index:t,delta:n,version:o}),s;for(let i of Object.keys(n)){let a=r[i],l=n[i];a===void 0&&Array.isArray(l)?r[i]=[...l]:Array.isArray(a)&&Array.isArray(l)?r[i]=[...a,...l]:(a===void 0||typeof a=="string")&&typeof l=="string"?r[i]=`${_nullishCoalesce(a, () => (""))}${l}`:r[i]=l}return s}var Pn= (_class26 =class{__init66() {this.cache=new Map}constructor(e){;_class26.prototype.__init66.call(this);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)}}, _class26),Vs=new Pn(500);function xr(s,e,t=0,n=Vs){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let o=s.indexOf(e,t);if(o!==-1)return o;let r=_nullishCoalesce(n.get(e), () => (Array.from({length:e.length},(a,l)=>e.slice(0,l+1))));n.get(e)||n.set(e,r);let i=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}var fr=s=>{let e=Math.floor(s/1e3);if(e<60)return`${e}s`;let t=Math.floor(e/60),n=e%60;if(t<60)return`${t}m ${n}s`;let o=Math.floor(t/60),r=t%60;return`${o}h ${r}m ${n}s`},Ws=(s,e,t)=>{if(s===0)return"calculating...";let n=t/s,o=e-s,r=n*o;return fr(r)},yr=(s,e,t,n,o,r,i,a,l)=>{process.stdout.write("\r\x1B[K");let p=(e/t*100).toFixed(1),c=fr(n),d=Ws(e,t,n),u=`Training round ${s+1}/${i.maxRounds}: ${e}/${t} (${p}%) [${c}, ETA: ${d}]`,m=r.totalCalls>0?r.successfulDemos/r.totalCalls*100:0;if(u+=` | Success rate: ${m.toFixed(1)}% (${r.successfulDemos}/${r.totalCalls})`,(i.verboseMode||i.debugMode)&&(i.costMonitoring&&(u+=`
93
- Tokens: ~${r.estimatedTokenUsage.toLocaleString()} total`),u+=`
94
- Batch: ${Math.floor(e/i.batchSize)+1}/${Math.ceil(t/i.batchSize)}`,i.earlyStoppingPatience>0&&r.earlyStopping&&(u+=`
95
- Best round: ${r.earlyStopping.bestScoreRound+1}, Patience: ${i.earlyStoppingPatience}`)),i.debugMode){let A=Object.keys(o).map(g=>{let f=JSON.stringify(o[g]),h=f.length>30?`${f.substring(0,30)}...`:f;return`${g}: ${h}`}).join(", ");if(u+=`
96
- Example: {${A}}`,l)u+=`
97
- ERROR: ${l.message}`;else if(a){let g=JSON.stringify(a),f=g.length>50?`${g.substring(0,50)}...`:g;u+=`
98
- Result: ${f}`}u+=`
99
- Temperature: ${(.7+.001*e).toFixed(3)}`}console.log(u)};var Rr=(s,e,t,n=!1)=>{let o={extractedFields:[],streamedIndex:{},s:-1};Fn(s,e,o,t,{strictMode:n}),Gn(s,e,o,t);for(let r of s.getOutputFields())r.isInternal&&delete e[r.name]},Js=(s,e,t)=>{let n=[];for(let o of t)o&&!o.isOptional&&e[o.name]===void 0&&n.push(o);if(n.length>0)throw new G({message:`Required ${n.length===1?"field":"fields"} not found`,fields:n})},Fn=(s,e,t,n,{strictMode:o,skipEarlyFail:r}={})=>{let i=s.getOutputFields(),a;for(let[l,p]of i.entries()){if(l===t.currFieldIndex&&!t.inAssumedField||p.name in e&&!(l===t.currFieldIndex&&t.inAssumedField))continue;let d=`${(t.extractedFields.length===0?"":`
100
- `)+p.title}:`,u=xr(n,d,t.s),m=d.length;switch(u){case-1:if(r)continue;if(!o&&i.length===1&&t.currField===void 0){t.inAssumedField=!0,a=p,m=0,u=0;break}if(t.currField===void 0&&!p.isOptional)throw new G({message:"Expected (Required) field not found",fields:[p]});a=p.isOptional?void 0:p;continue;case-2:return!0;case-3:return!0;case-4:return t.inBlock=!0,!0}if(a&&a.name!==p.name)throw new G({message:"Expected (Required) field not found",fields:[a]});if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let A=n.substring(t.s,u).trim(),g=Cr(t.currField,A);g!==void 0&&(e[t.currField.name]=g),t.prevFields?_optionalChain([t, 'access', _702 => _702.prevFields, 'optionalAccess', _703 => _703.push, 'call', _704 => _704({field:t.currField,s:t.s,e:u})]):t.prevFields=[{field:t.currField,s:t.s,e:u}]}t.s=u+m,t.currField=p,t.currFieldIndex=l,t.extractedFields.includes(p)||t.extractedFields.push(p),t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},Gn=(s,e,t,n)=>{if(t.currField){let o=n.substring(t.s).trim(),r=Cr(t.currField,o);r!==void 0&&(e[t.currField.name]=r)}Js(t,e,s.getOutputFields())},Ir=(s,e,t=!1)=>{switch(_optionalChain([s, 'access', _705 => _705.type, 'optionalAccess', _706 => _706.name])){case"code":return Tr(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.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(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return dr(s,e,t);case"datetime":return mr(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*br(s,e,t,n,o,r){let{name:i,isInternal:a}=e,{isArray:l,name:p}=_nullishCoalesce(e.type, () => ({}));if(a||l||p&&p!=="string"&&p!=="code")return;let c=_nullishCoalesce(o.streamedIndex[i], () => (0)),d=c===0,u=s.substring(t+c,n);if(u.length===0)return;let m=u.replace(/\s+$/,"");_optionalChain([o, 'access', _707 => _707.currField, 'optionalAccess', _708 => _708.type, 'optionalAccess', _709 => _709.name])==="code"&&(m=m.replace(/\s*```\s*$/,""));let A=d?m.trimStart():m;_optionalChain([o, 'access', _710 => _710.currField, 'optionalAccess', _711 => _711.type, 'optionalAccess', _712 => _712.name])==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:r,delta:{[i]:A}},o.streamedIndex[i]=c+m.length)}function*Dn(s,e,t,n,o){for(let i of _nullishCoalesce(n.prevFields, () => ([]))){let{field:a,s:l,e:p}=i;yield*br(e,a,l,p,n,o)}if(n.prevFields=void 0,!n.currField||n.currField.isInternal)return;yield*br(e,n.currField,n.s,e.length,n,o);let r=s.getOutputFields();for(let i of Object.keys(t)){let a=r.find(p=>p.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let p=_nullishCoalesce(_optionalChain([n, 'access', _713 => _713.streamedIndex, 'optionalAccess', _714 => _714[i]]), () => (0)),c=l.slice(p);c&&c.length>0&&(yield{index:o,delta:{[i]:c}},n.streamedIndex[i]=p+c.length);continue}n.streamedIndex[i]||(yield{index:o,delta:{[i]:l}},n.streamedIndex[i]=1)}}function Cr(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw new G({message:"Required field is missing",fields:[s],value:e})}let t;if(_optionalChain([s, 'access', _715 => _715.type, 'optionalAccess', _716 => _716.name])==="json")try{let n=Tr(e);return t=JSON.parse(n),t}catch(n){throw new G({message:`Invalid JSON: ${n.message}`,fields:[s],value:e})}if(_optionalChain([s, 'access', _717 => _717.type, 'optionalAccess', _718 => _718.isArray]))try{try{t=JSON.parse(e)}catch (e5){t=hr(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw new G({message:`Invalid Array: ${n.message}`,fields:[s],value:e})}try{if(Array.isArray(t)){for(let[n,o]of t.entries())if(o!==void 0){let r=typeof o=="string"?o.trim():o;t[n]=Ir(s,r,!0)}}else t=Ir(s,e)}catch(n){throw new G({message:n.message,fields:[s],value:e})}if(!(typeof t=="string"&&t===""))return t}var Tr=s=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function Un(s,e,t,n){for(let o of s){if(e[o.field.name]===void 0)continue;let r=o.process,i=await r(e[o.field.name],{sessionId:n,values:e,done:!0});wr(o.field,t,i,n)}}async function Nn(s,e,t,n,o,r,i=!1){for(let a of s){if(_optionalChain([t, 'access', _719 => _719.currField, 'optionalAccess', _720 => _720.name])!==a.field.name)continue;let l=e.substring(t.s);_optionalChain([t, 'access', _721 => _721.currField, 'optionalAccess', _722 => _722.type, 'optionalAccess', _723 => _723.name])==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let p=a.process,c=await p(l,{sessionId:r,values:o,done:i});wr(t.currField,n,c,r)}}var wr=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let o=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),r=Ys(s,o);e.addRequest([{role:"user",content:[{type:"text",text:r}]}],n),e.addTag("processor",n)};function Ys(s,e){let t=_optionalChain([s, 'access', _724 => _724.type, 'optionalAccess', _725 => _725.name])==="code",n=s.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*vr({res:s,usage:e,states:t,...n}){let o=(_nullishCoalesce(n.ai.getFeatures().functionCot, () => (!1)))&&n.functions!==void 0&&n.functions.length>0,r=s.getReader();try{for(;;){let{done:i,value:a}=await r.read();if(i)break;let l=a;l.modelUsage&&e.push(l.modelUsage);for(let p of l.results){if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&(!p.functionCalls||p.functionCalls.length===0))continue;let c=t.find(d=>d.index===p.index);if(!c)throw new Error(`No state found for result (index: ${p.index})`);yield*Ks({...n,result:p,skipEarlyFail:o,state:c})}}}finally{r.releaseLock()}for(let i of t)yield*Qs({...n,state:i})}async function*Ks({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:o,state:r,signature:i,streamingFieldProcessors:a,thoughtFieldName:l,streamingAsserts:p,asserts:c}){if(s.functionCalls&&s.functionCalls.length>0)ur(r.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:r.functionCalls,delta:_optionalChain([s, 'access', _726 => _726.functionCalls, 'optionalAccess', _727 => _727[0], 'optionalAccess', _728 => _728.function, 'optionalAccess', _729 => _729.params]),index:s.index},t);else if(s.content&&s.content.length>0){if(s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[l]:s.thought}}),r.content+=s.content,e.updateResult({name:s.name,content:r.content,delta:s.content,index:s.index},t),Fn(i,r.values,r.xstate,r.content,{strictMode:n,skipEarlyFail:o}))return;p.length!==0&&await Cn(p,r.xstate,r.content),a.length!==0&&await Nn(a,r.content,r.xstate,e,r.values,t),yield*Dn(i,r.content,r.values,r.xstate,s.index),await pt(c,r.values)}else s.thought&&s.thought.length>0&&(r.values[l]=(_nullishCoalesce(r.values[l], () => ("")))+s.thought,yield{index:s.index,delta:{[l]:s.thought}});if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
101
- Content: ${r.content}`)}async function*Qs({state:s,signature:e,ai:t,model:n,functions:o,mem:r,sessionId:i,traceId:a,span:l,excludeContentFromTrace:p,streamingAsserts:c,asserts:d,fieldProcessors:u,streamingFieldProcessors:m,functionResultFormatter:A}){let g=vn(t,s.functionCalls,s.values,n);if(g){if(!o)throw new Error("Functions are not defined");let f=await wn({ai:t,functionList:o,functionCalls:g,mem:r,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:p,functionResultFormatter:A});s.functionsExecuted=new Set([...s.functionsExecuted,...f])}else Gn(e,s.values,s.xstate,s.content),await Cn(c,s.xstate,s.content,!0),await pt(d,s.values),u.length&&await Un(u,s.values,r,i),m.length!==0&&await Nn(m,s.content,s.xstate,r,s.values,i,!0),yield*Dn(e,s.content,s.values,s.xstate,s.index)}async function*Or({ai:s,res:e,mem:t,sessionId:n,traceId:o,functions:r,span:i,strictMode:a,states:l,usage:p,excludeContentFromTrace:c,asserts:d,fieldProcessors:u,thoughtFieldName:m,signature:A,functionResultFormatter:g}){let f=_nullishCoalesce(e.results, () => ([]));t.addResponse(f,n);for(let b of f){let T=l[b.index];if(!T)throw new Error(`No state found for result (index: ${b.index})`);if(e.modelUsage&&p.push(e.modelUsage),_optionalChain([b, 'access', _730 => _730.functionCalls, 'optionalAccess', _731 => _731.length])){let O=vn(s,b.functionCalls,T.values);if(O){if(!r)throw new Error("Functions are not defined");let J=await wn({ai:s,functionList:r,functionCalls:O,mem:t,sessionId:n,traceId:o,span:i,excludeContentFromTrace:c,index:b.index,functionResultFormatter:g});T.functionsExecuted=new Set([...T.functionsExecuted,...J])}}else b.content&&(b.thought&&b.thought.length>0&&(T.values[m]=b.thought),Rr(A,T.values,b.content,a),await pt(d,T.values),u.length&&await Un(u,T.values,t,n));if(b.finishReason==="length")throw new Error(`Max tokens reached before completion
102
- Content: ${b.content}`)}let h=l.map(b=>b.values);for(let b of h)for(let T of A.getOutputFields())T.isInternal&&delete b[T.name];let I=A.getOutputFields(),x=h.map((b,T)=>{let O={};for(let J of I)J.isInternal||(O[J.name]=b[J.name]);return b[m]!==void 0&&(O[m]=b[m]),{index:T,delta:O}});for(let b of x)yield b}function Sr(s,e,t,n){let o=s.getLast(n);if(!o)return!0;for(let[r,i]of t.entries()){let a=e&&i.functionsExecuted.has(e);if(!o.chat[r])throw new Error(`No chat message found for result (index: ${r})`);let p=o.role==="function",c=o.tags?o.tags.some(d=>d==="processor"):!1;if(p&&e&&a||!(p||c))return!1}return!0}var Be=class{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 R=class extends Error{constructor(t,n,o,r){super(t);this.position=n;this.context=o;this.suggestion=r;this.name="SignatureValidationError"}},Ln= (_class27 =class{__init67() {this.currentFieldName=null}__init68() {this.currentSection="description"}constructor(e){;_class27.prototype.__init67.call(this);_class27.prototype.__init68.call(this);if(this.input=e.trim(),this.position=0,!this.input)throw new R("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 R("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 R('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 o=this.input.slice(this.position);throw new R(`Unexpected content after signature: "${o}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:_optionalChain([e, 'optionalAccess', _732 => _732.trim, 'call', _733 => _733()]),inputs:t,outputs:n}),{desc:_optionalChain([e, 'optionalAccess', _734 => _734.trim, 'call', _735 => _735()]),inputs:t,outputs:n}}catch(e){if(e instanceof R)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new R(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let o of e.inputs){if(t.has(o.name))throw new R(`Duplicate input field name: "${o.name}"`,0,"","Each field name must be unique within the signature");t.add(o.name)}let n=new Set;for(let o of e.outputs){if(n.has(o.name))throw new R(`Duplicate output field name: "${o.name}"`,0,"","Each field name must be unique within the signature");n.add(o.name)}for(let o of e.outputs)if(t.has(o.name))throw new R(`Field name "${o.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 R("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new R("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),o=this.input.slice(this.position,t),r=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${o}"`,` ${r}`].join(`
103
- `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new R(`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(o){throw o instanceof R?o:new R(`Invalid first ${t} field: ${o instanceof Error?o.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 R(`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(o){throw o instanceof R?o:new R(`Invalid ${t} field after comma: ${o instanceof Error?o.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 R(`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 R(`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 r=this.parseTypeNotClass(),i=this.match("[]");if(n={name:r,isArray:i},(r==="image"||r==="audio")&&i)throw new R(`Input field "${e}": Arrays of ${r} are not supported`,this.position,this.getErrorContext(),`Use a single ${r} type instead: "${r}"`)}catch(r){throw r instanceof R?r:new R(`Input field "${e}": ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:_optionalChain([o, 'optionalAccess', _736 => _736.trim, 'call', _737 => _737()]),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 o;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new R(`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(p=>p.trim()).filter(p=>p.length>0);if(l.length===0)throw new R(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');o={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(o={name:i,isArray:a},i==="image"&&a)throw new R(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new R(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new R(`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(i==="audio")throw new R(`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(i){throw i instanceof R?i:new R(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:_optionalChain([r, 'optionalAccess', _738 => _738.trim, 'call', _739 => _739()]),type:o,isOptional:t,isInternal:n}}validateFieldName(e,t){if(k.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 i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new R(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,o=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!o.test(e))throw new R(`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 R(`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 R(`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","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=_optionalChain([this, 'access', _740 => _740.input, 'access', _741 => _741.slice, 'call', _742 => _742(this.position), 'access', _743 => _743.match, 'call', _744 => _744(/^\w+/), 'optionalAccess', _745 => _745[0]])||"",o=this.suggestType(n),r=`Invalid type "${n||"empty"}"`,i=o?`. Did you mean "${o}"?`:"",a=`${r}${i}`;throw new R(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 R("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 R(`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 R(`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="",o=!1,r=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,o)n+=a,o=!1;else if(a==="\\")o=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(r,Math.min(this.position,r+20));throw new R(`Unterminated string starting at position ${r}`,r,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${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 R(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}}, _class27);function kr(s){return new Ln(s).parse()}var y=class extends Error{constructor(t,n,o){super(t);this.fieldName=n;this.suggestion=o;this.name="AxSignatureValidationError"}},P= exports.AxSignature = (_class28 =class s{constructor(e){;_class28.prototype.__init69.call(this);_class28.prototype.__init70.call(this);_class28.prototype.__init71.call(this);_class28.prototype.__init72.call(this);_class28.prototype.__init73.call(this);_class28.prototype.__init74.call(this);_class28.prototype.__init75.call(this);_class28.prototype.__init76.call(this);_class28.prototype.__init77.call(this);_class28.prototype.__init78.call(this);_class28.prototype.__init79.call(this);_class28.prototype.__init80.call(this);_class28.prototype.__init81.call(this);_class28.prototype.__init82.call(this);_class28.prototype.__init83.call(this);_class28.prototype.__init84.call(this);_class28.prototype.__init85.call(this);_class28.prototype.__init86.call(this);_class28.prototype.__init87.call(this);if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=kr(e)}catch(n){if(n instanceof Error){let o="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new y(`Invalid Signature: ${n.message}`,void 0,o)}throw new y(`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 s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new y("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 y("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 y?t:new y(`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 y("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}__init69() {this.parseParsedField=e=>{if(!e.name||e.name.length===0)throw new y("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:_nullishCoalesce(e.type, () => ({name:"string",isArray:!1})),..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}}}__init70() {this.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 y("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, date, datetime, class, code");return{...e,title:t}}}__init71() {this.setDescription=e=>{if(typeof e!="string")throw new y("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()}}__init72() {this.addInputField=e=>{try{let t=this.parseField(e);Z(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new y(`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 y(`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 y?t:new y(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}}}__init73() {this.addOutputField=e=>{try{let t=this.parseField(e);Z(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new y(`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 y(`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 y?t:new y(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}}}__init74() {this.setInputFields=e=>{if(!Array.isArray(e))throw new y("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return Z(o,"input"),o});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof y?t:new y(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}}}__init75() {this.setOutputFields=e=>{if(!Array.isArray(e))throw new y("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return Z(o,"output"),o});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof y?t:new y(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}}}__init76() {this.getInputFields=()=>this.inputFields}__init77() {this.getOutputFields=()=>this.outputFields}__init78() {this.getDescription=()=>this.description}__init79() {this.invalidateValidationCache=()=>{this.validatedAtHash=void 0}}__init80() {this.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)}}__init81() {this.toJSONSchema=()=>{let e={},t=[];for(let o of this.inputFields){let r=o.type?o.type.name:"string";_optionalChain([o, 'access', _748 => _748.type, 'optionalAccess', _749 => _749.isArray])?e[o.name]={description:o.description,type:"array",items:{type:r,description:o.description}}:e[o.name]={description:o.description,type:r},o.isOptional||t.push(o.name)}return{type:"object",properties:e,required:t}}}__init82() {this.updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{Z(e,"input")}),this.getOutputFields().forEach(e=>{Z(e,"output")}),this.sigHash=je("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Er(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof y?e:new y(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}}}__init83() {this.updateHash=()=>{try{return this.getInputFields().forEach(e=>{Z(e,"input")}),this.getOutputFields().forEach(e=>{Z(e,"output")}),this.validateSignatureConsistency(),this.sigHash=je("sha256").update(_nullishCoalesce(this.description, () => (""))).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Er(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof y?e:new y(`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 y(`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 y(`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 y(`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 y("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new y("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}__init84() {this.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}}}__init85() {this.hash=()=>this.sigHash}__init86() {this.toString=()=>this.sigString}__init87() {this.toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})}}, _class28);function Mr(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&_optionalChain([s, 'access', _750 => _750.type, 'optionalAccess', _751 => _751.name])!=="class"&&(e+=` "${s.description}"`),e}function Er(s,e,t){let n=s?`"${s}" `:"",o=e.map(Mr).join(", "),r=t.map(Mr).join(", ");return`${n}${o} -> ${r}`}function Xs(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function Z(s,e){if(!s.name||s.name.length===0)throw new y("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!Xs(s.name))throw new y(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(k.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new y(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new y(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new y(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Zs(s,e)}function Zs(s,e){if(!s.type)return;let{type:t}=s;if(t.name==="image"||t.name==="audio"){if(e==="output")throw new y(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.isArray)throw new y(`Arrays of ${t.name} are not supported`,s.name,`Use a single ${t.name} type instead`)}if(t.name==="class"){if(e==="input")throw new y("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new y("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let o of t.options){if(!o||o.trim().length===0)throw new y("Empty class option found",s.name,"All class options must be non-empty strings");let r=o.trim();if(r.includes(",")||r.includes("|"))throw new y(`Invalid class option "${r}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(o=>o.trim().toLowerCase())).size!==t.options.length)throw new y("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new y("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new y("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var ee= (_class29 =class{__init88() {this.usage=[]}constructor(e,t){;_class29.prototype.__init88.call(this);this.signature=new P(e),_optionalChain([t, 'optionalAccess', _752 => _752.description])&&this.signature.setDescription(t.description),_optionalChain([t, 'optionalAccess', _753 => _753.traceLabel])&&(this.traceLabel=t.traceLabel),this.signature.validate(),this.sigHash=_optionalChain([this, 'access', _754 => _754.signature, 'optionalAccess', _755 => _755.hash, 'call', _756 => _756()]),this.children=new Be,this.key={id:this.signature.hash()}}getSignature(){return this.signature}register(e){this.key&&e.setParentId(this.key.id),this.children.register(e)}async forward(e,t,n){throw new Error("forward() not implemented")}async*streamingForward(e,t,n){throw new Error("streamingForward() not implemented")}setId(e){this.key={id:e,custom:!0};for(let t of Array.from(this.children))_optionalChain([t, 'optionalAccess', _757 => _757.setParentId, 'call', _758 => _758(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))_optionalChain([n, 'optionalAccess', _759 => _759.setExamples, 'call', _760 => _760(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 o=this.signature,r=[...o.getInputFields(),...o.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of r){let p=i[l.name];p!==void 0&&(ht(l,p),a[l.name]=p)}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=_optionalChain([t, 'optionalAccess', _761 => _761.getTraces, 'call', _762 => _762()]);e=[...e,..._nullishCoalesce(n, () => ([]))]}return e}getUsage(){let e=[..._nullishCoalesce(this.usage, () => ([]))];for(let t of Array.from(this.children)){let n=_optionalChain([t, 'optionalAccess', _763 => _763.getUsage, 'call', _764 => _764()]);e=[...e,..._nullishCoalesce(n, () => ([]))]}return Ar(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))_optionalChain([e, 'optionalAccess', _765 => _765.resetUsage, 'call', _766 => _766()])}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(o=>o.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(o=>o.programId===this.key.id).map(o=>o.traces).flat();for(let o of Array.from(this.children))_optionalChain([o, 'optionalAccess', _767 => _767.setDemos, 'call', _768 => _768(e)])}}, _class29);var ei=`
146
+ `)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}}, _class24),dt= exports.AxFunctionProcessor = (_class25 =class{__init71() {this.funcList=[]}constructor(e){;_class25.prototype.__init71.call(this);_class25.prototype.__init72.call(this);_class25.prototype.__init73.call(this);this.funcList=e}__init72() {this.executeFunction=async(e,t,n)=>{let o;typeof t.args=="string"&&t.args.length>0?o=JSON.parse(t.args):o=t.args;let r=n?{sessionId:n.sessionId,traceId:n.traceId,ai:n.ai}:void 0,i;return e.parameters?i=e.func.length===2?await e.func(o,r):await e.func(o):i=e.func.length===1?await e.func(r):await e.func(),(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _668 => _668.functionResultFormatter]), () => (E.functionResultFormatter)))(i)}}__init73() {this.execute=async(e,t)=>{let n=this.funcList.find(o=>o.name.localeCompare(e.name)===0);if(!n)throw new Error(`Function not found: ${e.name}`);if(!n.func)throw new Error(`No handler for function: ${e.name}`);try{return await this.executeFunction(n,e,t)}catch(o){throw o instanceof ct?new ut(o.getFields(),n,e.id):o}}}}, _class25),Cn=(s,e)=>{if(s.length===0)return[..._nullishCoalesce(e, () => ([]))];let t=s.map(n=>"toFunction"in n?n.toFunction():n).flat();for(let n of t.filter(o=>o.parameters))n.parameters&&gr(n.parameters);return[..._nullishCoalesce(e, () => ([])),...t]},wn=async({ai:s,functionList:e,functionCalls:t,mem:n,sessionId:o,traceId:r,span:i,excludeContentFromTrace:a,index:l,functionResultFormatter:p})=>{let c=new dt(e),d=new Set,u=t.map(g=>{if(!g.id)throw new Error(`Function ${g.name} did not return an ID`);return c.execute(g,{sessionId:o,traceId:r,ai:s,functionResultFormatter:p}).then(h=>{if(d.add(g.name.toLowerCase()),i){let y={name:g.name};a||(y.args=g.args,y.result=_nullishCoalesce(h, () => (""))),i.addEvent("function.call",y)}return{result:_nullishCoalesce(h, () => ("")),role:"function",functionId:g.id,index:l}}).catch(h=>{if(!(h instanceof ut))throw h;let y=h.getFixingInstructions();if(i){let x={name:g.name,message:h.toString()};a||(x.args=g.args,x.fixing_instructions=y),i.addEvent("function.error",x)}if(s.getOptions().debug){let x=s.getLogger();xo(h,l,y,x)}return{functionId:g.id,isError:!0,index:l,result:y,role:"function"}})}),A=(await Promise.all(u)).filter(g=>g!==void 0);if(n.addFunctionResults(A,o),s.getOptions().debug){let g=A.filter(f=>!f.isError);if(g.length>0){let f=s.getLogger();ho(g,f)}}return A.some(g=>g.isError)&&n.addTag("error",o),d};function Tn(s,e,t,n){if(!e||e.length===0)return;if(!s.getFeatures(n).functions)throw new Error("Functions are not supported by the AI service");return e.map(r=>({id:r.id,name:r.function.name,args:r.function.params}))}function Ar(s,e,t){let n=e;return!t&&(n==="required"||typeof n=="function")?{functions:[],functionCall:void 0}:s?{functions:s.map(r=>"toFunction"in r?r.toFunction():r).flat(),functionCall:n}:{functions:[],functionCall:n}}function hr(s,e){for(let t of e){let n=s.find(o=>o.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)):s.push(t)}}var _dayjs = require('dayjs'); var _dayjs2 = _interopRequireDefault(_dayjs);var _customParseFormatjs = require('dayjs/plugin/customParseFormat.js'); var _customParseFormatjs2 = _interopRequireDefault(_customParseFormatjs);var _timezonejs = require('dayjs/plugin/timezone.js'); var _timezonejs2 = _interopRequireDefault(_timezonejs);var _utcjs = require('dayjs/plugin/utc.js'); var _utcjs2 = _interopRequireDefault(_utcjs);_dayjs2.default.extend(_utcjs2.default);_dayjs2.default.extend(_timezonejs2.default);_dayjs2.default.extend(_customParseFormatjs2.default);function xr(s,e,t=!1){try{return js(e)}catch(n){if(s.isOptional&&!t)return;let o=n.message;throw new G({fields:[s],message:o,value:e})}}function js(s){if(!_dayjs2.default.call(void 0, s,"YYYY-MM-DD",!0).isValid())throw new Error('Invalid date format. Please provide the date in "YYYY-MM-DD" format.');return _dayjs2.default.utc(s,"YYYY-MM-DD").startOf("day").toDate()}function fr(s,e,t=!1){try{return Hs(e)}catch(n){if(s.isOptional&&!t)return;let o=n.message;throw new G({fields:[s],message:o,value:e})}}function Hs(s){let e=/^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}(?::\d{2})?) (.+)$/,t=s.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,o]=t;if(!n||!o)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 r=n.includes(":")&&n.split(":").length===3?"YYYY-MM-DD HH:mm:ss":"YYYY-MM-DD HH:mm",i=_dayjs2.default.tz(n,r,o);if(!i.isValid())throw new Error("Invalid date and time values. Please ensure all components are correct.");return i.utc().toDate()}catch (e4){throw new Error(`Unrecognized time zone ${o}. Please provide a valid time zone name, abbreviation, or offset. For example, "America/New_York", or "EST".`)}}var yr=s=>_dayjs2.default.call(void 0, s).utc().format("YYYY-MM-DD HH:mm:ss [UTC]");var vn=new N,Ir=(s,e,t,n,o,r=20)=>{let i=(s/e*100).toFixed(1),a=Math.round(r*s/e),l=r-a,p=vn.blueBright("\u2588".repeat(a)),c=" ".repeat(l),d=e>0?(t/e*100).toFixed(1):"0.0",u=o.includes("Running MIPROv2 optimization")?"Testing prompt variations":o.includes("Tuning Prompt")?"Generating training examples":o;process.stdout.write(`\u2502 ${u}: ${s}/${e} (${vn.yellow(i)}%) |${p}${c}| Success rate: ${vn.greenBright(d)}%
147
+ `)},mt=(s,e)=>{let t=_nullishCoalesce(s.type, () => ({name:"string",isArray:!1})),n=(a,l)=>{switch(a){case"class":return typeof l=="string";case"code":return typeof l=="string";case"string":return typeof l=="string";case"number":return typeof l=="number";case"boolean":return typeof l=="boolean";case"date":return l instanceof Date||typeof l=="string";case"datetime":return l instanceof Date||typeof l=="string";case"json":return typeof l=="object"||typeof l=="string";default:return!1}},o=a=>!(!a||typeof a!="object"||!("mimeType"in a)||!("data"in a));if(_optionalChain([s, 'access', _669 => _669.type, 'optionalAccess', _670 => _670.name])==="image"){let a;if(Array.isArray(e)){for(let l of e)if(!o(l)){a="object ({ mimeType: string; data: string })";break}}else o(e)||(a="object ({ mimeType: string; data: string })");if(a)throw new Error(`Validation failed: Expected '${s.name}' to be type '${a}' instead got '${e}'`);return}let r=a=>!(!a||typeof a!="object"||!("data"in a));if(_optionalChain([s, 'access', _671 => _671.type, 'optionalAccess', _672 => _672.name])==="audio"){let a;if(Array.isArray(e)){for(let l of e)if(!r(l)){a="object ({ data: string; format?: string })";break}}else r(e)||(a="object ({ data: string; format?: string })");if(a)throw new Error(`Validation failed: Expected '${s.name}' to be type '${a}' instead got '${e}'`);return}let i=!0;if(t.isArray){if(!Array.isArray(e))i=!1;else for(let a of e)if(!n(t.name,a)){i=!1;break}}else i=n(t.name,e);if(!i){let a=Array.isArray(e)?"array":typeof e;throw new Error(`Validation failed: Expected '${s.name}' to be a ${_optionalChain([s, 'access', _673 => _673.type, 'optionalAccess', _674 => _674.isArray])?"an array of ":""}${t.name} instead got '${a}' (${JSON.stringify(e)})`)}};function br(s){let e={};for(let t of s){let n=`${t.ai}:${t.model}`;if(!e[n]){e[n]={...t};continue}let o=e[n];if(o){let r=_nullishCoalesce(o.tokens, () => ({promptTokens:0,completionTokens:0,totalTokens:0}));r.promptTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _675 => _675.tokens, 'optionalAccess', _676 => _676.promptTokens]), () => (0)),r.completionTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _677 => _677.tokens, 'optionalAccess', _678 => _678.completionTokens]), () => (0)),r.totalTokens+=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _679 => _679.tokens, 'optionalAccess', _680 => _680.totalTokens]), () => (0)),o.tokens=r}}return Object.values(e)}var Rr=s=>{if(!s.trim())return[];let e=new Set(["-","*","+"]),t=/^\d+[\s]*[.)\]]\s*/,n=s.split(`
148
+ `),o=[];for(let r of n){let i=r.trim();if(i){if(i[0]&&e.has(i[0]))o.push(i.slice(1).trim());else if(t.test(i))o.push(i.replace(t,"").trim());else if(o.length!==0)throw new Error("Could not parse markdown list: mixed content detected")}}if(o.length===0)throw new Error("Could not parse markdown list: no valid list items found");return o};function Sn(s,e){let{index:t,delta:n,version:o}=e,r=_optionalChain([s, 'access', _681 => _681.find, 'call', _682 => _682(i=>i.index===t), 'optionalAccess', _683 => _683.delta]);if(!r)return s.push({index:t,delta:n,version:o}),s;for(let i of Object.keys(n)){let a=r[i],l=n[i];a===void 0&&Array.isArray(l)?r[i]=[...l]:Array.isArray(a)&&Array.isArray(l)?r[i]=[...a,...l]:(a===void 0||typeof a=="string")&&typeof l=="string"?r[i]=`${_nullishCoalesce(a, () => (""))}${l}`:r[i]=l}return s}var On= (_class26 =class{__init74() {this.cache=new Map}constructor(e){;_class26.prototype.__init74.call(this);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)}}, _class26),Vs=new On(500);function Cr(s,e,t=0,n=Vs){if(/^```[a-zA-Z]*\s*$/.test(s))return-4;if(/^[\s`]*$/.test(s))return-3;let o=s.indexOf(e,t);if(o!==-1)return o;let r=_nullishCoalesce(n.get(e), () => (Array.from({length:e.length},(a,l)=>e.slice(0,l+1))));n.get(e)||n.set(e,r);let i=-1;for(let a=r.length-1;a>=0;a--){let l=r[a];if(s.endsWith(l)){i=a;break}}return i>=0?-2:-1}var vr=(s,e,t,n=!1)=>{let o={extractedFields:[],streamedIndex:{},s:-1};kn(s,e,o,t,{strictMode:n}),En(s,e,o,t);for(let r of s.getOutputFields())r.isInternal&&delete e[r.name]},Ws=(s,e,t)=>{let n=[];for(let o of t)o&&!o.isOptional&&e[o.name]===void 0&&n.push(o);if(n.length>0)throw new G({message:`Required ${n.length===1?"field":"fields"} not found`,fields:n})},kn=(s,e,t,n,{strictMode:o,skipEarlyFail:r}={})=>{let i=s.getOutputFields(),a;for(let[l,p]of i.entries()){if(l===t.currFieldIndex&&!t.inAssumedField||p.name in e&&!(l===t.currFieldIndex&&t.inAssumedField))continue;let d=`${(t.extractedFields.length===0?"":`
149
+ `)+p.title}:`,u=Cr(n,d,t.s),m=d.length;switch(u){case-1:if(r)continue;if(!o&&i.length===1&&t.currField===void 0){t.inAssumedField=!0,a=p,m=0,u=0;break}if(t.currField===void 0&&!p.isOptional)throw new G({message:"Expected (Required) field not found",fields:[p]});a=p.isOptional?void 0:p;continue;case-2:return!0;case-3:return!0;case-4:return t.inBlock=!0,!0}if(a&&a.name!==p.name)throw new G({message:"Expected (Required) field not found",fields:[a]});if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let A=n.substring(t.s,u).trim(),g=Or(t.currField,A);g!==void 0&&(e[t.currField.name]=g),t.prevFields?_optionalChain([t, 'access', _684 => _684.prevFields, 'optionalAccess', _685 => _685.push, 'call', _686 => _686({field:t.currField,s:t.s,e:u})]):t.prevFields=[{field:t.currField,s:t.s,e:u}]}t.s=u+m,t.currField=p,t.currFieldIndex=l,t.extractedFields.includes(p)||t.extractedFields.push(p),t.streamedIndex[p.name]===void 0&&(t.streamedIndex[p.name]=0)}},En=(s,e,t,n)=>{if(t.currField){let o=n.substring(t.s).trim(),r=Or(t.currField,o);r!==void 0&&(e[t.currField.name]=r)}Ws(t,e,s.getOutputFields())},wr=(s,e,t=!1)=>{switch(_optionalChain([s, 'access', _687 => _687.type, 'optionalAccess', _688 => _688.name])){case"code":return Sr(e);case"string":return e;case"number":{let n=Number(e);if(Number.isNaN(n)){if(s.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(s.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return xr(s,e,t);case"datetime":return fr(s,e,t);case"class":{let n=e;if(s.type.options&&!s.type.options.includes(n)){if(s.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${s.type.options.join(", ")}`)}return n}default:return e}};function*Tr(s,e,t,n,o,r){let{name:i,isInternal:a}=e,{isArray:l,name:p}=_nullishCoalesce(e.type, () => ({}));if(a||l||p&&p!=="string"&&p!=="code")return;let c=_nullishCoalesce(o.streamedIndex[i], () => (0)),d=c===0,u=s.substring(t+c,n);if(u.length===0)return;let m=u.replace(/\s+$/,"");_optionalChain([o, 'access', _689 => _689.currField, 'optionalAccess', _690 => _690.type, 'optionalAccess', _691 => _691.name])==="code"&&(m=m.replace(/\s*```\s*$/,""));let A=d?m.trimStart():m;_optionalChain([o, 'access', _692 => _692.currField, 'optionalAccess', _693 => _693.type, 'optionalAccess', _694 => _694.name])==="code"&&(A=A.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),A.length>0&&(yield{index:r,delta:{[i]:A}},o.streamedIndex[i]=c+m.length)}function*Mn(s,e,t,n,o){for(let i of _nullishCoalesce(n.prevFields, () => ([]))){let{field:a,s:l,e:p}=i;yield*Tr(e,a,l,p,n,o)}if(n.prevFields=void 0,!n.currField||n.currField.isInternal)return;yield*Tr(e,n.currField,n.s,e.length,n,o);let r=s.getOutputFields();for(let i of Object.keys(t)){let a=r.find(p=>p.name===i);if(!a||a.isInternal)continue;let l=t[i];if(Array.isArray(l)){let p=_nullishCoalesce(_optionalChain([n, 'access', _695 => _695.streamedIndex, 'optionalAccess', _696 => _696[i]]), () => (0)),c=l.slice(p);c&&c.length>0&&(yield{index:o,delta:{[i]:c}},n.streamedIndex[i]=p+c.length);continue}n.streamedIndex[i]||(yield{index:o,delta:{[i]:l}},n.streamedIndex[i]=1)}}function Or(s,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(s.isOptional)return;throw new G({message:"Required field is missing",fields:[s],value:e})}let t;if(_optionalChain([s, 'access', _697 => _697.type, 'optionalAccess', _698 => _698.name])==="json")try{let n=Sr(e);return t=JSON.parse(n),t}catch(n){throw new G({message:`Invalid JSON: ${n.message}`,fields:[s],value:e})}if(_optionalChain([s, 'access', _699 => _699.type, 'optionalAccess', _700 => _700.isArray]))try{try{t=JSON.parse(e)}catch (e5){t=Rr(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(n){throw new G({message:`Invalid Array: ${n.message}`,fields:[s],value:e})}try{if(Array.isArray(t)){for(let[n,o]of t.entries())if(o!==void 0){let r=typeof o=="string"?o.trim():o;t[n]=wr(s,r,!0)}}else t=wr(s,e)}catch(n){throw new G({message:n.message,fields:[s],value:e})}if(!(typeof t=="string"&&t===""))return t}var Sr=s=>{let t=/```([A-Za-z]*)\n([\s\S]*?)\n```/g.exec(s);return t?t.length===3?t[2]:t.length===2?t[1]:s:s};async function _n(s,e,t,n){for(let o of s){if(e[o.field.name]===void 0)continue;let r=o.process,i=await r(e[o.field.name],{sessionId:n,values:e,done:!0});kr(o.field,t,i,n)}}async function Pn(s,e,t,n,o,r,i=!1){for(let a of s){if(_optionalChain([t, 'access', _701 => _701.currField, 'optionalAccess', _702 => _702.name])!==a.field.name)continue;let l=e.substring(t.s);_optionalChain([t, 'access', _703 => _703.currField, 'optionalAccess', _704 => _704.type, 'optionalAccess', _705 => _705.name])==="code"&&(l=l.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,""),l=l.replace(/\s*```\s*$/,""));let p=a.process,c=await p(l,{sessionId:r,values:o,done:i});kr(t.currField,n,c,r)}}var kr=(s,e,t,n)=>{if(t===void 0||typeof t=="string"&&(t===""||/^(null|undefined)\s*$/i.test(t)))return;let o=JSON.stringify(t,(i,a)=>typeof a=="bigint"?Number(a):a,2),r=Js(s,o);e.addRequest([{role:"user",content:[{type:"text",text:r}]}],n),e.addTag("processor",n)};function Js(s,e){let t=_optionalChain([s, 'access', _706 => _706.type, 'optionalAccess', _707 => _707.name])==="code",n=s.title;return t?`Code in the field "${n}" was executed. The code execution produced the following output: ${e}`:`The field "${n}" was processed. The field contents were transformed into the following output: ${e}`}async function*Er({res:s,usage:e,states:t,...n}){let o=(_nullishCoalesce(n.ai.getFeatures().functionCot, () => (!1)))&&n.functions!==void 0&&n.functions.length>0,r=s.getReader();try{for(;;){let{done:i,value:a}=await r.read();if(i)break;let l=a;l.modelUsage&&e.push(l.modelUsage);for(let p of l.results){if((!p.content||p.content==="")&&(!p.thought||p.thought==="")&&(!p.functionCalls||p.functionCalls.length===0))continue;let c=t.find(d=>d.index===p.index);if(!c)throw new Error(`No state found for result (index: ${p.index})`);yield*Ys({...n,result:p,skipEarlyFail:o,state:c})}}}finally{r.releaseLock()}for(let i of t)yield*Ks({...n,state:i})}async function*Ys({result:s,mem:e,sessionId:t,strictMode:n,skipEarlyFail:o,state:r,signature:i,streamingFieldProcessors:a,thoughtFieldName:l,streamingAsserts:p,asserts:c}){if(s.functionCalls&&s.functionCalls.length>0)hr(r.functionCalls,s.functionCalls),e.updateResult({name:s.name,content:s.content,functionCalls:r.functionCalls,delta:_optionalChain([s, 'access', _708 => _708.functionCalls, 'optionalAccess', _709 => _709[0], 'optionalAccess', _710 => _710.function, 'optionalAccess', _711 => _711.params]),index:s.index},t);else if(s.content&&s.content.length>0){if(s.thought&&s.thought.length>0&&(yield{index:s.index,delta:{[l]:s.thought}}),r.content+=s.content,e.updateResult({name:s.name,content:r.content,delta:s.content,index:s.index},t),kn(i,r.values,r.xstate,r.content,{strictMode:n,skipEarlyFail:o}))return;p.length!==0&&await fn(p,r.xstate,r.content),a.length!==0&&await Pn(a,r.content,r.xstate,e,r.values,t),yield*Mn(i,r.content,r.values,r.xstate,s.index),await it(c,r.values)}else s.thought&&s.thought.length>0&&(r.values[l]=(_nullishCoalesce(r.values[l], () => ("")))+s.thought,yield{index:s.index,delta:{[l]:s.thought}});if(s.finishReason==="length")throw new Error(`Max tokens reached before completion
150
+ Content: ${r.content}`)}async function*Ks({state:s,signature:e,ai:t,model:n,functions:o,mem:r,sessionId:i,traceId:a,span:l,excludeContentFromTrace:p,streamingAsserts:c,asserts:d,fieldProcessors:u,streamingFieldProcessors:m,functionResultFormatter:A}){let g=Tn(t,s.functionCalls,s.values,n);if(g){if(!o)throw new Error("Functions are not defined");let f=await wn({ai:t,functionList:o,functionCalls:g,mem:r,sessionId:i,traceId:a,span:l,index:s.index,excludeContentFromTrace:p,functionResultFormatter:A});s.functionsExecuted=new Set([...s.functionsExecuted,...f])}else En(e,s.values,s.xstate,s.content),await fn(c,s.xstate,s.content,!0),await it(d,s.values),u.length&&await _n(u,s.values,r,i),m.length!==0&&await Pn(m,s.content,s.xstate,r,s.values,i,!0),yield*Mn(e,s.content,s.values,s.xstate,s.index)}async function*Mr({ai:s,res:e,mem:t,sessionId:n,traceId:o,functions:r,span:i,strictMode:a,states:l,usage:p,excludeContentFromTrace:c,asserts:d,fieldProcessors:u,thoughtFieldName:m,signature:A,functionResultFormatter:g}){let f=_nullishCoalesce(e.results, () => ([]));t.addResponse(f,n);for(let b of f){let R=l[b.index];if(!R)throw new Error(`No state found for result (index: ${b.index})`);if(e.modelUsage&&p.push(e.modelUsage),_optionalChain([b, 'access', _712 => _712.functionCalls, 'optionalAccess', _713 => _713.length])){let T=Tn(s,b.functionCalls,R.values);if(T){if(!r)throw new Error("Functions are not defined");let $=await wn({ai:s,functionList:r,functionCalls:T,mem:t,sessionId:n,traceId:o,span:i,excludeContentFromTrace:c,index:b.index,functionResultFormatter:g});R.functionsExecuted=new Set([...R.functionsExecuted,...$])}}else b.content&&(b.thought&&b.thought.length>0&&(R.values[m]=b.thought),vr(A,R.values,b.content,a),await it(d,R.values),u.length&&await _n(u,R.values,t,n));if(b.finishReason==="length")throw new Error(`Max tokens reached before completion
151
+ Content: ${b.content}`)}let h=l.map(b=>b.values);for(let b of h)for(let R of A.getOutputFields())R.isInternal&&delete b[R.name];let y=A.getOutputFields(),x=h.map((b,R)=>{let T={};for(let $ of y)$.isInternal||(T[$.name]=b[$.name]);return b[m]!==void 0&&(T[m]=b[m]),{index:R,delta:T}});for(let b of x)yield b}function _r(s,e,t,n){let o=s.getLast(n);if(!o)return!0;for(let[r,i]of t.entries()){let a=e&&i.functionsExecuted.has(e);if(!o.chat[r])throw new Error(`No chat message found for result (index: ${r})`);let p=o.role==="function",c=o.tags?o.tags.some(d=>d==="processor"):!1;if(p&&e&&a||!(p||c))return!1}return!0}var Fe=class{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 C=class extends Error{constructor(t,n,o,r){super(t);this.position=n;this.context=o;this.suggestion=r;this.name="SignatureValidationError"}},Fn= (_class27 =class{__init75() {this.currentFieldName=null}__init76() {this.currentSection="description"}constructor(e){;_class27.prototype.__init75.call(this);_class27.prototype.__init76.call(this);if(this.input=e.trim(),this.position=0,!this.input)throw new C("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 C("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 C('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 o=this.input.slice(this.position);throw new C(`Unexpected content after signature: "${o}"`,this.position,this.getErrorContext(),"Remove any extra content after the output fields")}return this.validateParsedSignature({desc:_optionalChain([e, 'optionalAccess', _714 => _714.trim, 'call', _715 => _715()]),inputs:t,outputs:n}),{desc:_optionalChain([e, 'optionalAccess', _716 => _716.trim, 'call', _717 => _717()]),inputs:t,outputs:n}}catch(e){if(e instanceof C)throw e;let t=e instanceof Error?e.message:"Unknown error";throw new C(t,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=new Set;for(let o of e.inputs){if(t.has(o.name))throw new C(`Duplicate input field name: "${o.name}"`,0,"","Each field name must be unique within the signature");t.add(o.name)}let n=new Set;for(let o of e.outputs){if(n.has(o.name))throw new C(`Duplicate output field name: "${o.name}"`,0,"","Each field name must be unique within the signature");n.add(o.name)}for(let o of e.outputs)if(t.has(o.name))throw new C(`Field name "${o.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 C("Signature must have at least one input field",0,"",'Add an input field before "->". Example: "userInput:string -> ..."');if(e.outputs.length===0)throw new C("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),o=this.input.slice(this.position,t),r=`${" ".repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${o}"`,` ${r}`].join(`
152
+ `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new C(`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(o){throw o instanceof C?o:new C(`Invalid first ${t} field: ${o instanceof Error?o.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 C(`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(o){throw o instanceof C?o:new C(`Invalid ${t} field after comma: ${o instanceof Error?o.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 C(`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 C(`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 r=this.parseTypeNotClass(),i=this.match("[]");if(n={name:r,isArray:i},(r==="image"||r==="audio")&&i)throw new C(`Input field "${e}": Arrays of ${r} are not supported`,this.position,this.getErrorContext(),`Use a single ${r} type instead: "${r}"`)}catch(r){throw r instanceof C?r:new C(`Input field "${e}": ${r instanceof Error?r.message:"Unknown error"}`,this.position,this.getErrorContext())}}this.skipWhitespace();let o=this.parseParsedString();return{name:e,desc:_optionalChain([o, 'optionalAccess', _718 => _718.trim, 'call', _719 => _719()]),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 o;if(this.skipWhitespace(),this.match(":"))if(this.skipWhitespace(),this.match("class")){let i=this.match("[]");this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new C(`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(p=>p.trim()).filter(p=>p.length>0);if(l.length===0)throw new C(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),'Provide at least one class option. Example: "positive, negative"');o={name:"class",isArray:i,options:l}}else try{let i=this.parseTypeNotClass(),a=this.match("[]");if(o={name:i,isArray:a},i==="image"&&a)throw new C(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),'Use a single image type instead: "image"');if(i==="audio"&&a)throw new C(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),'Use a single audio type instead: "audio"');if(i==="image")throw new C(`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(i==="audio")throw new C(`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(i){throw i instanceof C?i:new C(`Output field "${e}": ${i instanceof Error?i.message:"Unknown error"}`,this.position,this.getErrorContext())}this.skipWhitespace();let r=this.parseParsedString();return{name:e,desc:_optionalChain([r, 'optionalAccess', _720 => _720.trim, 'call', _721 => _721()]),type:o,isOptional:t,isInternal:n}}validateFieldName(e,t){if(E.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 i=t==="input"?["userInput","questionText","documentContent","messageText"]:["responseText","analysisResult","categoryType","summaryText"];throw new C(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${i.join(", ")}`)}let n=/^[a-z][a-zA-Z0-9]*$/,o=/^[a-z]+(_[a-z0-9]+)*$/;if(!n.test(e)&&!o.test(e))throw new C(`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 C(`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 C(`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","datetime","date","code"],t=e.find(n=>this.match(n));if(!t){let n=_optionalChain([this, 'access', _722 => _722.input, 'access', _723 => _723.slice, 'call', _724 => _724(this.position), 'access', _725 => _725.match, 'call', _726 => _726(/^\w+/), 'optionalAccess', _727 => _727[0]])||"",o=this.suggestType(n),r=`Invalid type "${n||"empty"}"`,i=o?`. Did you mean "${o}"?`:"",a=`${r}${i}`;throw new C(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 C("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 C(`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 C(`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="",o=!1,r=this.position-1;for(;this.position<this.input.length;){let a=this.input[this.position];if(this.position++,o)n+=a,o=!1;else if(a==="\\")o=!0;else{if(a===t)return n;n+=a}}let i=this.input.slice(r,Math.min(this.position,r+20));throw new C(`Unterminated string starting at position ${r}`,r,this.getErrorContext(),`Add closing ${t} to complete the string: ${i}${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 C(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}}, _class27);function Pr(s){return new Fn(s).parse()}var I=class extends Error{constructor(t,n,o){super(t);this.fieldName=n;this.suggestion=o;this.name="AxSignatureValidationError"}},S= exports.AxSignature = (_class28 =class s{constructor(e){;_class28.prototype.__init77.call(this);_class28.prototype.__init78.call(this);_class28.prototype.__init79.call(this);_class28.prototype.__init80.call(this);_class28.prototype.__init81.call(this);_class28.prototype.__init82.call(this);_class28.prototype.__init83.call(this);_class28.prototype.__init84.call(this);_class28.prototype.__init85.call(this);_class28.prototype.__init86.call(this);_class28.prototype.__init87.call(this);_class28.prototype.__init88.call(this);_class28.prototype.__init89.call(this);_class28.prototype.__init90.call(this);_class28.prototype.__init91.call(this);_class28.prototype.__init92.call(this);_class28.prototype.__init93.call(this);_class28.prototype.__init94.call(this);_class28.prototype.__init95.call(this);if(!e){this.inputFields=[],this.outputFields=[],this.sigHash="",this.sigString="";return}if(typeof e=="string"){let t;try{t=Pr(e)}catch(n){if(n instanceof Error){let o="suggestion"in n&&typeof n.suggestion=="string"?n.suggestion:'Please check the signature format. Example: "userInput:string -> responseText:string"';throw new I(`Invalid Signature: ${n.message}`,void 0,o)}throw new I(`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 s)this.description=e.getDescription(),this.inputFields=structuredClone(e.getInputFields()),this.outputFields=structuredClone(e.getOutputFields()),this.sigHash=e.hash(),this.sigString=e.toString(),e.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash);else if(typeof e=="object"&&e!==null){if(!("inputs"in e)||!("outputs"in e))throw new I("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 I("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 I?t:new I(`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 I("Invalid signature argument type",void 0,"Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays")}__init77() {this.parseParsedField=e=>{if(!e.name||e.name.length===0)throw new I("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:_nullishCoalesce(e.type, () => ({name:"string",isArray:!1})),..."isInternal"in e?{isInternal:e.isInternal}:{},..."isOptional"in e?{isOptional:e.isOptional}:{}}}}__init78() {this.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 I("Field type name is required",e.name,"Specify a valid type. Available types: string, number, boolean, json, image, audio, date, datetime, class, code");return{...e,title:t}}}__init79() {this.setDescription=e=>{if(typeof e!="string")throw new I("Description must be a string",void 0,"Provide a string description for the signature");this.description=e,this.invalidateValidationCache(),this.updateHashLight()}}__init80() {this.addInputField=e=>{try{let t=this.parseField(e);K(t,"input");for(let n of this.inputFields)if(n.name===t.name)throw new I(`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 I(`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 I?t:new I(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}}}__init81() {this.addOutputField=e=>{try{let t=this.parseField(e);K(t,"output");for(let n of this.outputFields)if(n.name===t.name)throw new I(`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 I(`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 I?t:new I(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:"Unknown error"}`,e.name)}}}__init82() {this.setInputFields=e=>{if(!Array.isArray(e))throw new I("Input fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return K(o,"input"),o});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof I?t:new I(`Failed to set input fields: ${t instanceof Error?t.message:"Unknown error"}`)}}}__init83() {this.setOutputFields=e=>{if(!Array.isArray(e))throw new I("Output fields must be an array",void 0,"Provide an array of field objects");try{let t=e.map(n=>{let o=this.parseField(n);return K(o,"output"),o});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof I?t:new I(`Failed to set output fields: ${t instanceof Error?t.message:"Unknown error"}`)}}}__init84() {this.getInputFields=()=>this.inputFields}__init85() {this.getOutputFields=()=>this.outputFields}__init86() {this.getDescription=()=>this.description}__init87() {this.invalidateValidationCache=()=>{this.validatedAtHash=void 0}}__init88() {this.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)}}__init89() {this.toJSONSchema=()=>{let e={},t=[];for(let o of this.inputFields){let r=o.type?o.type.name:"string";_optionalChain([o, 'access', _730 => _730.type, 'optionalAccess', _731 => _731.isArray])?e[o.name]={description:o.description,type:"array",items:{type:r,description:o.description}}:e[o.name]={description:o.description,type:r},o.isOptional||t.push(o.name)}return{type:"object",properties:e,required:t}}}__init90() {this.updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{K(e,"input")}),this.getOutputFields().forEach(e=>{K(e,"output")}),this.sigHash=Be("sha256").update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Gr(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof I?e:new I(`Signature validation failed: ${e instanceof Error?e.message:"Unknown error"}`)}}}__init91() {this.updateHash=()=>{try{return this.getInputFields().forEach(e=>{K(e,"input")}),this.getOutputFields().forEach(e=>{K(e,"output")}),this.validateSignatureConsistency(),this.sigHash=Be("sha256").update(_nullishCoalesce(this.description, () => (""))).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest("hex"),this.sigString=Gr(this.description,this.inputFields,this.outputFields),[this.sigHash,this.sigString]}catch(e){throw e instanceof I?e:new I(`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 I(`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 I(`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 I(`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 I("Signature must have at least one input field",void 0,'Add an input field. Example: "userInput:string -> ..."');if(this.outputFields.length===0)throw new I("Signature must have at least one output field",void 0,'Add an output field. Example: "... -> responseText:string"')}__init92() {this.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}}}__init93() {this.hash=()=>this.sigHash}__init94() {this.toString=()=>this.sigString}__init95() {this.toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields})}}, _class28);function Fr(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${s.type.name}`,s.type.isArray&&(e+="[]"),s.type.name==="class"&&s.type.options&&(e+=` "${s.type.options.join(" | ")}"`)),s.description&&_optionalChain([s, 'access', _732 => _732.type, 'optionalAccess', _733 => _733.name])!=="class"&&(e+=` "${s.description}"`),e}function Gr(s,e,t){let n=s?`"${s}" `:"",o=e.map(Fr).join(", "),r=t.map(Fr).join(", ");return`${n}${o} -> ${r}`}function Qs(s){let e=/^[a-z][a-zA-Z0-9]*$/,t=/^[a-z]+(_[a-z0-9]+)*$/;return e.test(s)||t.test(s)}function K(s,e){if(!s.name||s.name.length===0)throw new I("Field name cannot be blank",s.name,"Every field must have a descriptive name");if(!Qs(s.name))throw new I(`Invalid field name '${s.name}' - must be camelCase or snake_case`,s.name,'Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")');if(E.signatureStrict&&["text","object","image","string","number","boolean","json","array","datetime","date","time","type","class","input","output","data","value","result","response","request","item","element"].includes(s.name.toLowerCase())){let n=e==="input"?["userInput","questionText","documentContent","messageText","queryString"]:["responseText","analysisResult","categoryType","summaryText","outputData"];throw new I(`Field name '${s.name}' is too generic`,s.name,`Use a more descriptive name. Examples for ${e} fields: ${n.join(", ")}`)}if(s.name.length<2)throw new I(`Field name '${s.name}' is too short`,s.name,"Field names must be at least 2 characters long");if(s.name.length>50)throw new I(`Field name '${s.name}' is too long (${s.name.length} characters)`,s.name,"Field names should be 50 characters or less");s.type&&Xs(s,e)}function Xs(s,e){if(!s.type)return;let{type:t}=s;if(t.name==="image"||t.name==="audio"){if(e==="output")throw new I(`${t.name} type is not supported in output fields`,s.name,`${t.name} types can only be used in input fields`);if(t.isArray)throw new I(`Arrays of ${t.name} are not supported`,s.name,`Use a single ${t.name} type instead`)}if(t.name==="class"){if(e==="input")throw new I("Class type is not supported in input fields",s.name,'Class types are only allowed on output fields. Use "string" type for input classifications');if(!t.options||t.options.length===0)throw new I("Class type requires options",s.name,'Provide class options. Example: class "positive, negative, neutral"');for(let o of t.options){if(!o||o.trim().length===0)throw new I("Empty class option found",s.name,"All class options must be non-empty strings");let r=o.trim();if(r.includes(",")||r.includes("|"))throw new I(`Invalid class option "${r}"`,s.name,"Class options cannot contain commas (,) or pipes (|) as they are used to separate options")}if(new Set(t.options.map(o=>o.trim().toLowerCase())).size!==t.options.length)throw new I("Duplicate class options found",s.name,"Each class option must be unique (case-insensitive)")}if(t.name==="code"&&t.isArray)throw new I("Arrays of code are not commonly supported",s.name,"Consider using a single code field or an array of strings instead");if(s.isInternal&&e==="input")throw new I("Internal marker (!) is not allowed on input fields",s.name,"Internal markers are only allowed on output fields")}var te= (_class29 =class{__init96() {this.usage=[]}constructor(e,t){;_class29.prototype.__init96.call(this);this.signature=new S(e),_optionalChain([t, 'optionalAccess', _734 => _734.description])&&this.signature.setDescription(t.description),_optionalChain([t, 'optionalAccess', _735 => _735.traceLabel])&&(this.traceLabel=t.traceLabel),e&&this.signature.validate(),this.sigHash=_optionalChain([this, 'access', _736 => _736.signature, 'optionalAccess', _737 => _737.hash, 'call', _738 => _738()]),this.children=new Fe,this.key={id:this.signature.hash()}}getSignature(){return new S(this.signature)}setSignature(e){this.signature=new S(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))_optionalChain([t, 'optionalAccess', _739 => _739.setParentId, 'call', _740 => _740(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))_optionalChain([n, 'optionalAccess', _741 => _741.setExamples, 'call', _742 => _742(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 o=this.signature,r=[...o.getInputFields(),...o.getOutputFields()];this.examples=n.map(i=>{let a={};for(let l of r){let p=i[l.name];p!==void 0&&(mt(l,p),a[l.name]=p)}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=_optionalChain([t, 'optionalAccess', _743 => _743.getTraces, 'call', _744 => _744()]);e=[...e,..._nullishCoalesce(n, () => ([]))]}return e}getUsage(){let e=[..._nullishCoalesce(this.usage, () => ([]))];for(let t of Array.from(this.children)){let n=_optionalChain([t, 'optionalAccess', _745 => _745.getUsage, 'call', _746 => _746()]);e=[...e,..._nullishCoalesce(n, () => ([]))]}return br(e)}resetUsage(){this.usage=[];for(let e of Array.from(this.children))_optionalChain([e, 'optionalAccess', _747 => _747.resetUsage, 'call', _748 => _748()])}setDemos(e){let t=Array.from(this.children).length>0,n=e.some(o=>o.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(o=>o.programId===this.key.id).map(o=>o.traces).flat();for(let o of Array.from(this.children))_optionalChain([o, 'optionalAccess', _749 => _749.setDemos, 'call', _750 => _750(e)])}}, _class29);var Zs=`
104
153
  ## Function Call Instructions
105
154
  - Complete the task, using the functions defined earlier in this prompt.
106
155
  - Output fields should only be generated after all functions have been called.
107
- - Use the function results to generate the output fields.`,ti=`
156
+ - Use the function results to generate the output fields.`,ei=`
108
157
  ## Strict Output Formatting Rules
109
158
  - Output must strictly follow the defined plain-text \`field name: value\` field format.
110
159
  - Output field, values must strictly adhere to the specified output field formatting rules.
111
160
  - No formatting rules should override these **Strict Output Formatting Rules**
112
161
  - Do not add any text before or after the output fields, just the field name and value.
113
- - Do not use code blocks.`,de= exports.AxPromptTemplate = (_class30 =class{constructor(e,t,n){;_class30.prototype.__init89.call(this);_class30.prototype.__init90.call(this);_class30.prototype.__init91.call(this);_class30.prototype.__init92.call(this);_class30.prototype.__init93.call(this);_class30.prototype.__init94.call(this);_class30.prototype.__init95.call(this);_class30.prototype.__init96.call(this);this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _780 => _780.thoughtFieldName]), () => ("thought")),this.functions=_optionalChain([t, 'optionalAccess', _781 => _781.functions]);let o=[],r=Pr(this.sig.getInputFields()),i=Pr(this.sig.getOutputFields());o.push(`You will be provided with the following fields: ${r}. Your task is to generate new fields: ${i}.`);let l=_optionalChain([this, 'access', _782 => _782.functions, 'optionalAccess', _783 => _783.map, 'call', _784 => _784(u=>"toFunction"in u?u.toFunction():u), 'optionalAccess', _785 => _785.flat, 'call', _786 => _786(), 'optionalAccess', _787 => _787.map, 'call', _788 => _788(u=>`- \`${u.name}\`: ${xt(u.description)}`), 'access', _789 => _789.join, 'call', _790 => _790(`
162
+ - Do not use code blocks.`,ae= exports.AxPromptTemplate = (_class30 =class{constructor(e,t,n){;_class30.prototype.__init97.call(this);_class30.prototype.__init98.call(this);_class30.prototype.__init99.call(this);_class30.prototype.__init100.call(this);_class30.prototype.__init101.call(this);_class30.prototype.__init102.call(this);_class30.prototype.__init103.call(this);_class30.prototype.__init104.call(this);this.sig=e,this.fieldTemplates=n,this.thoughtFieldName=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _762 => _762.thoughtFieldName]), () => ("thought")),this.functions=_optionalChain([t, 'optionalAccess', _763 => _763.functions]);let o=[],r=Dr(this.sig.getInputFields()),i=Dr(this.sig.getOutputFields());o.push(`You will be provided with the following fields: ${r}. Your task is to generate new fields: ${i}.`);let l=_optionalChain([this, 'access', _764 => _764.functions, 'optionalAccess', _765 => _765.map, 'call', _766 => _766(u=>"toFunction"in u?u.toFunction():u), 'optionalAccess', _767 => _767.flat, 'call', _768 => _768(), 'optionalAccess', _769 => _769.map, 'call', _770 => _770(u=>`- \`${u.name}\`: ${gt(u.description)}`), 'access', _771 => _771.join, 'call', _772 => _772(`
114
163
  `)]);l&&l.length>0&&o.push(`## Available Functions
115
- ${l}`);let p=ni(this.sig.getInputFields());o.push(`## Input Fields
116
- ${p}`);let c=oi(this.sig.getOutputFields());o.push(`## Output Fields
117
- ${c}`),l&&l.length>0&&o.push(ei.trim()),o.push(ti.trim());let d=this.sig.getDescription();if(d){let u=xt(d);o.push(u)}this.task={type:"text",text:o.join(`
164
+ ${l}`);let p=ti(this.sig.getInputFields());o.push(`## Input Fields
165
+ ${p}`);let c=ni(this.sig.getOutputFields());o.push(`## Output Fields
166
+ ${c}`),l&&l.length>0&&o.push(Zs.trim()),o.push(ei.trim());let d=this.sig.getDescription();if(d){let u=gt(d);o.push(u)}this.task={type:"text",text:o.join(`
118
167
 
119
- `)}}__init89() {this.renderSingleValueUserContent=(e,t,n,o)=>{let r=this.renderInputFields(e),a=(o?r:[...t,...n,...r]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
120
- `):a.reduce(_r(`
121
- `),[])}}__init90() {this.render=(e,{examples:t,demos:n})=>{let o=t?[{type:"text",text:`
168
+ `)}}__init97() {this.renderSingleValueUserContent=(e,t,n,o)=>{let r=this.renderInputFields(e),a=(o?r:[...t,...n,...r]).filter(l=>l!==void 0);return a.every(l=>l.type==="text")?a.map(l=>l.text).join(`
169
+ `):a.reduce(Ur(`
170
+ `),[])}}__init98() {this.render=(e,{examples:t,demos:n})=>{let o=t?[{type:"text",text:`
122
171
 
123
172
  ## Examples
124
- `},...this.renderExamples(t)]:[],r=n?this.renderDemos(n):[],i=o.every(u=>u.type==="text"),a=r.every(u=>u.type==="text"),l=i&&a,p=this.task.text;if(l){let u=[{type:"text",text:p},...o,...r];u.reduce(_r(""),[]),_optionalChain([u, 'optionalAccess', _791 => _791[0]])&&(p=u[0].text)}let c={role:"system",content:p};if(Array.isArray(e)){let u=[],m=e,A=!0;for(let g of m){let f;if(A?(f=this.renderSingleValueUserContent(g.values,o,r,l),A=!1):f=this.renderSingleValueUserContent(g.values,[],[],!1),g.role==="user"){u.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");u.push({role:"assistant",content:f})}return[c,...u]}let d=this.renderSingleValueUserContent(e,o,r,l);return[c,{role:"user",content:d}]}}__init91() {this.renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((r,i)=>{let a=i.title;return r[a]||(r[a]=[]),r[a].push(i),r},{});return Object.entries(n).map(([r,i])=>{if(i.length===1){let a=i[0];return{title:r,name:a.name,description:a.description}}if(i.length>1){let a=i.map(l=>`- ${l.description}`).join(`
125
- `);return{title:r,name:i[0].name,description:a}}}).filter(Boolean).forEach(r=>{let i=_nullishCoalesce(_optionalChain([this, 'access', _792 => _792.fieldTemplates, 'optionalAccess', _793 => _793[r.name]]), () => (this.defaultRenderInField));t.push(...i(r,r.description))}),t}}__init92() {this.renderExamples=e=>{let t=[],n={isExample:!0};for(let[o,r]of e.entries()){let i=this.sig.getInputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!0})).filter(p=>p!==void 0).flat(),a=this.sig.getOutputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!1})).filter(p=>p!==void 0).flat(),l=[...i,...a];o>0&&l.length>0&&_optionalChain([l, 'access', _794 => _794[0], 'optionalAccess', _795 => _795.type])==="text"&&t.push({type:"text",text:`---
173
+ `},...this.renderExamples(t)]:[],r=n?this.renderDemos(n):[],i=o.every(u=>u.type==="text"),a=r.every(u=>u.type==="text"),l=i&&a,p=this.task.text;if(l){let u=[{type:"text",text:p},...o,...r];u.reduce(Ur(""),[]),_optionalChain([u, 'optionalAccess', _773 => _773[0]])&&(p=u[0].text)}let c={role:"system",content:p};if(Array.isArray(e)){let u=[],m=e,A=!0;for(let g of m){let f;if(A?(f=this.renderSingleValueUserContent(g.values,o,r,l),A=!1):f=this.renderSingleValueUserContent(g.values,[],[],!1),g.role==="user"){u.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");u.push({role:"assistant",content:f})}return[c,...u]}let d=this.renderSingleValueUserContent(e,o,r,l);return[c,{role:"user",content:d}]}}__init99() {this.renderExtraFields=e=>{let t=[];if(!e||e.length===0)return t;let n=e.reduce((r,i)=>{let a=i.title;return r[a]||(r[a]=[]),r[a].push(i),r},{});return Object.entries(n).map(([r,i])=>{if(i.length===1){let a=i[0];return{title:r,name:a.name,description:a.description}}if(i.length>1){let a=i.map(l=>`- ${l.description}`).join(`
174
+ `);return{title:r,name:i[0].name,description:a}}}).filter(Boolean).forEach(r=>{let i=_nullishCoalesce(_optionalChain([this, 'access', _774 => _774.fieldTemplates, 'optionalAccess', _775 => _775[r.name]]), () => (this.defaultRenderInField));t.push(...i(r,r.description))}),t}}__init100() {this.renderExamples=e=>{let t=[],n={isExample:!0};for(let[o,r]of e.entries()){let i=this.sig.getInputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!0})).filter(p=>p!==void 0).flat(),a=this.sig.getOutputFields().map(p=>this.renderInField(p,r,{...n,isInputField:!1})).filter(p=>p!==void 0).flat(),l=[...i,...a];o>0&&l.length>0&&_optionalChain([l, 'access', _776 => _776[0], 'optionalAccess', _777 => _777.type])==="text"&&t.push({type:"text",text:`---
126
175
 
127
176
  `}),l.forEach(p=>{"text"in p&&(p.text=`${p.text}
128
- `),t.push(p)})}return t}}__init93() {this.renderDemos=e=>{let t=[],n=this.sig.getInputFields(),o=this.sig.getOutputFields(),r={isExample:!0};for(let i of e){let a=n.map(c=>this.renderInField(c,i,{...r,isInputField:!0})).filter(c=>c!==void 0).flat(),l=o.map(c=>this.renderInField(c,i,{...r,isInputField:!1})).filter(c=>c!==void 0).flat();[...a,...l].slice(0,-1).forEach(c=>{"text"in c&&(c.text=`${c.text}
129
- `),t.push(c)})}return t}}__init94() {this.renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
130
- `}),t}}__init95() {this.renderInField=(e,t,n)=>{let o=t[e.name];if(si(e,o,n))return;e.type&&ht(e,o);let r=ri(e,o);return(_nullishCoalesce(_optionalChain([this, 'access', _796 => _796.fieldTemplates, 'optionalAccess', _797 => _797[e.name]]), () => (this.defaultRenderInField)))(e,r)}}__init96() {this.defaultRenderInField=(e,t)=>{if(_optionalChain([e, 'access', _798 => _798.type, 'optionalAccess', _799 => _799.name])==="image"){let o=i=>{if(!i)throw new Error("Image field value is required.");if(typeof i!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in i))throw new Error("Image field must have mimeType");if(!("data"in i))throw new Error("Image field must have data");return i},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");r=r.concat(t.map(i=>{let a=o(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=o(t);r.push({type:"image",mimeType:i.mimeType,image:i.data})}return r}if(_optionalChain([e, 'access', _800 => _800.type, 'optionalAccess', _801 => _801.name])==="audio"){let o=i=>{if(!i)throw new Error("Audio field value is required.");if(typeof i!="object")throw new Error("Audio field value must be an object.");if(!("data"in i))throw new Error("Audio field must have data");return i},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");r=r.concat(t.map(i=>{let a=o(i);return{type:"audio",format:_nullishCoalesce(a.format, () => ("wav")),data:a.data}}))}else{let i=o(t);r.push({type:"audio",format:_nullishCoalesce(i.format, () => ("wav")),data:i.data})}return r}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
177
+ `),t.push(p)})}return t}}__init101() {this.renderDemos=e=>{let t=[],n=this.sig.getInputFields(),o=this.sig.getOutputFields(),r={isExample:!0};for(let i of e){let a=n.map(c=>this.renderInField(c,i,{...r,isInputField:!0})).filter(c=>c!==void 0).flat(),l=o.map(c=>this.renderInField(c,i,{...r,isInputField:!1})).filter(c=>c!==void 0).flat();[...a,...l].slice(0,-1).forEach(c=>{"text"in c&&(c.text=`${c.text}
178
+ `),t.push(c)})}return t}}__init102() {this.renderInputFields=e=>{let t=this.sig.getInputFields().map(n=>this.renderInField(n,e,void 0)).filter(n=>n!==void 0).flat();return t.filter(n=>n.type==="text").forEach(n=>{n.text=`${n.text}
179
+ `}),t}}__init103() {this.renderInField=(e,t,n)=>{let o=t[e.name];if(ri(e,o,n))return;e.type&&mt(e,o);let r=oi(e,o);return(_nullishCoalesce(_optionalChain([this, 'access', _778 => _778.fieldTemplates, 'optionalAccess', _779 => _779[e.name]]), () => (this.defaultRenderInField)))(e,r)}}__init104() {this.defaultRenderInField=(e,t)=>{if(_optionalChain([e, 'access', _780 => _780.type, 'optionalAccess', _781 => _781.name])==="image"){let o=i=>{if(!i)throw new Error("Image field value is required.");if(typeof i!="object")throw new Error("Image field value must be an object.");if(!("mimeType"in i))throw new Error("Image field must have mimeType");if(!("data"in i))throw new Error("Image field must have data");return i},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Image field value must be an array.");r=r.concat(t.map(i=>{let a=o(i);return{type:"image",mimeType:a.mimeType,image:a.data}}))}else{let i=o(t);r.push({type:"image",mimeType:i.mimeType,image:i.data})}return r}if(_optionalChain([e, 'access', _782 => _782.type, 'optionalAccess', _783 => _783.name])==="audio"){let o=i=>{if(!i)throw new Error("Audio field value is required.");if(typeof i!="object")throw new Error("Audio field value must be an object.");if(!("data"in i))throw new Error("Audio field must have data");return i},r=[{type:"text",text:`${e.title}: `}];if(e.type.isArray){if(!Array.isArray(t))throw new Error("Audio field value must be an array.");r=r.concat(t.map(i=>{let a=o(i);return{type:"audio",format:_nullishCoalesce(a.format, () => ("wav")),data:a.data}}))}else{let i=o(t);r.push({type:"audio",format:_nullishCoalesce(i.format, () => ("wav")),data:i.data})}return r}let n=[e.title,": "];return Array.isArray(t)?(n.push(`
131
180
  `),n.push(t.map(o=>`- ${o}`).join(`
132
- `))):n.push(t),[{type:"text",text:n.join("")}]}}}, _class30),Pr=s=>s.map(e=>`\`${e.title}\``).join(", "),ni=s=>s.map(t=>{let n=t.title,o=_optionalChain([t, 'access', _802 => _802.type, 'optionalAccess', _803 => _803.name])?Fr(t.type):"string",r=t.isOptional?`This optional ${o} field may be omitted`:`A ${o} field`,i=t.description?` ${xt(t.description)}`:"";return`${n}: (${r})${i}`.trim()}).join(`
133
- `),oi=s=>s.map(t=>{let n=t.title,o=_optionalChain([t, 'access', _804 => _804.type, 'optionalAccess', _805 => _805.name])?Fr(t.type):"string",r=t.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,i="";return t.description&&t.description.length>0&&(i=` ${_optionalChain([t, 'access', _806 => _806.type, 'optionalAccess', _807 => _807.name])==="class"?t.description:xt(t.description)}`),_optionalChain([t, 'access', _808 => _808.type, 'optionalAccess', _809 => _809.options])&&t.type.options.length>0&&(i.length>0&&(i+=". "),i+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${r})${i}`.trim()}).join(`
134
- `),ri=(s,e)=>{if(_optionalChain([s, 'access', _810 => _810.type, 'optionalAccess', _811 => _811.name])==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return _optionalChain([s, 'access', _812 => _812.type, 'optionalAccess', _813 => _813.name])==="datetime"&&e instanceof Date?gr(e):_optionalChain([s, 'access', _814 => _814.type, 'optionalAccess', _815 => _815.name])==="image"&&typeof e=="object"||_optionalChain([s, 'access', _816 => _816.type, 'optionalAccess', _817 => _817.name])==="audio"&&typeof e=="object"||typeof e=="string"?e:JSON.stringify(e,null,2)},Fr=s=>{let e=(()=>{switch(_optionalChain([s, 'optionalAccess', _818 => _818.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";default:return"string"}})();return _optionalChain([s, 'optionalAccess', _819 => _819.isArray])?`json array of ${e} items`:e};function _r(s){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=s+t.text:e.push(t)}else e.push(t);return e}}var si=(s,e,t)=>{if(typeof e=="boolean")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(_optionalChain([t, 'optionalAccess', _820 => _820.isExample])||s.isOptional||s.isInternal)return!0;let n=_optionalChain([t, 'optionalAccess', _821 => _821.isInputField])!==!1?"input":"output";throw new Error(`Value for ${n} field '${s.name}' is required.`)}return!1};function xt(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function ii(s,e){let t=s.history(0,e),n=t.some(r=>r.role==="function");return t.some(r=>r.role==="assistant"&&"functionCalls"in r&&Array.isArray(r.functionCalls)&&r.functionCalls.length>0)&&n}function ai(s,e){let t=s.history(0,e),n=[],o=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),r=t.filter(i=>i.role==="function");for(let i of o)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let l=r.find(p=>"functionId"in p&&p.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 ft(s,e,t,n){if(!_optionalChain([e, 'optionalAccess', _822 => _822.resultPicker])||s.length<=1)return 0;let o=e.resultPicker;if((t?ii(t,n):!1)&&t){let l=ai(t,n),p=await o({type:"function",results:l});if(p<0||p>=l.length)throw new Error(`Result picker returned invalid index: ${p}. Must be between 0 and ${l.length-1}`);return p}let i=s.map((l,p)=>({index:p,sample:l.delta})),a=await o({type:"fields",results:i});if(a<0||a>=s.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${s.length-1}`);return a}async function Gr(s,e,t){let n=_optionalChain([s, 'optionalAccess', _823 => _823.getLast, 'call', _824 => _824(e)]);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let o=n.chat.map(i=>({version:0,index:i.index,delta:i.value}));return await ft(o,t,s,e)}function Dr(s,e,t,n,o){if(s.addRequest([{role:"user",content:n.renderExtraFields(e)}],o),s.addTag("error",o),t.getOptions().debug){let r=e.map(a=>`- ${a.title}: ${a.description}`).join(`
135
- `);t.getLogger()(`\u274C Error Correction:
136
- ${r}`,{tags:["error"]})}}var S= (_class31 =class extends ee{__init97() {this.fieldProcessors=[]}__init98() {this.streamingFieldProcessors=[]}__init99() {this.excludeContentFromTrace=!1}constructor(e,t){super(e,{description:_optionalChain([t, 'optionalAccess', _827 => _827.description]),traceLabel:_optionalChain([t, 'optionalAccess', _828 => _828.traceLabel])});_class31.prototype.__init97.call(this);_class31.prototype.__init98.call(this);_class31.prototype.__init99.call(this);_class31.prototype.__init100.call(this);_class31.prototype.__init101.call(this);_class31.prototype.__init102.call(this);_class31.prototype.__init103.call(this);_class31.prototype.__init104.call(this);,this.options=t,this.thoughtFieldName=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _829 => _829.thoughtFieldName]), () => ("thought"));let n={functions:_optionalChain([t, 'optionalAccess', _830 => _830.functions]),thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _831 => _831.promptTemplate]), () => (de)))(this.signature,n),this.asserts=_nullishCoalesce(_optionalChain([this, 'access', _832 => _832.options, 'optionalAccess', _833 => _833.asserts]), () => ([])),this.streamingAsserts=_nullishCoalesce(_optionalChain([this, 'access', _834 => _834.options, 'optionalAccess', _835 => _835.streamingAsserts]), () => ([])),this.excludeContentFromTrace=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _836 => _836.excludeContentFromTrace]), () => (!1)),this.usage=[],_optionalChain([t, 'optionalAccess', _837 => _837.functions])&&(this.functions=Tn(t.functions))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return On()}updateMeter(e){On(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}__init100() {this.addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})}}__init101() {this.addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})}}__init102() {this.addFieldProcessorInternal=(e,t,n=!1)=>{let o=this.signature.getOutputFields().find(r=>r.name===e);if(!o)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let r=_optionalChain([o, 'access', _838 => _838.type, 'optionalAccess', _839 => _839.name]);if(!(!r||r==="string"||r==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:o,process:t})}else this.fieldProcessors.push({field:o,process:t})}}__init103() {this.addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)}}__init104() {this.addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)}}async forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:r,functionCall:i}){let{sessionId:a,traceId:l,model:p,rateLimiter:c,stream:d,thinkingTokenBudget:u,showThoughts:m}=_nullishCoalesce(n, () => ({})),A=await Gr(t,a,{resultPicker:_optionalChain([n, 'optionalAccess', _840 => _840.resultPicker])}),g=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _841 => _841.history, 'call', _842 => _842(A,a)]), () => ([]));if(g.length===0)throw new Error("No chat prompt found");let f={..._optionalChain([n, 'optionalAccess', _843 => _843.modelConfig]),..._optionalChain([n, 'optionalAccess', _844 => _844.sampleCount])?{n:n.sampleCount}:{},..._optionalChain([n, 'optionalAccess', _845 => _845.sampleCount])&&_optionalChain([n, 'optionalAccess', _846 => _846.modelConfig, 'optionalAccess', _847 => _847.temperature])===1?{temperature:.8}:{}};return await e.chat({chatPrompt:g,functions:r,functionCall:i,modelConfig:f,model:p},{sessionId:a,traceId:l,rateLimiter:c,stream:d,debug:!1,thinkingTokenBudget:u,showThoughts:m,traceContext:o,abortSignal:_optionalChain([n, 'optionalAccess', _848 => _848.abortSignal])})}async*forwardCore({ai:e,mem:t,options:n,firstStep:o,span:r,traceContext:i}){let{sessionId:a,traceId:l,functions:p}=_nullishCoalesce(n, () => ({})),c=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _849 => _849.functionCall]), () => (_optionalChain([this, 'access', _850 => _850.options, 'optionalAccess', _851 => _851.functionCall]))),d=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _852 => _852.strictMode]), () => (!1)),u=n.model,m=this.createStates(_nullishCoalesce(n.sampleCount, () => (1))),A=this.usage,{functions:g,functionCall:f}=rr(p,c,o),h=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:g,functionCall:f});h instanceof ReadableStream?yield*vr({ai:e,model:u,res:h,mem:t,traceId:l,sessionId:a,functions:g,strictMode:d,span:r,states:m,usage:A,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,functionResultFormatter:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _853 => _853.functionResultFormatter]), () => (_optionalChain([this, 'access', _854 => _854.options, 'optionalAccess', _855 => _855.functionResultFormatter])))}):yield*Or({ai:e,model:u,res:h,mem:t,traceId:l,sessionId:a,functions:g,span:r,strictMode:d,states:m,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,functionResultFormatter:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _856 => _856.functionResultFormatter]), () => (_optionalChain([this, 'access', _857 => _857.options, 'optionalAccess', _858 => _858.functionResultFormatter])))}),_optionalChain([this, 'access', _859 => _859.getLogger, 'call', _860 => _860(e,n), 'optionalCall', _861 => _861("",{tags:["responseEnd"]})])}async*_forward2(e,t,n,o,r,i){let a=_optionalChain([(_nullishCoalesce(_optionalChain([o, 'optionalAccess', _862 => _862.stopFunction]), () => (_optionalChain([this, 'access', _863 => _863.options, 'optionalAccess', _864 => _864.stopFunction])))), 'optionalAccess', _865 => _865.toLowerCase, 'call', _866 => _866()]),l=_nullishCoalesce(_nullishCoalesce(o.maxRetries, () => (_optionalChain([this, 'access', _867 => _867.options, 'optionalAccess', _868 => _868.maxRetries]))), () => (10)),p=_nullishCoalesce(_nullishCoalesce(o.maxSteps, () => (_optionalChain([this, 'access', _869 => _869.options, 'optionalAccess', _870 => _870.maxSteps]))), () => (10)),c=o.debugHideSystemPrompt,d={debug:this.isDebug(e,o),debugHideSystemPrompt:c,logger:this.getLogger(e,o)},u=_nullishCoalesce(_nullishCoalesce(o.mem, () => (_optionalChain([this, 'access', _871 => _871.options, 'optionalAccess', _872 => _872.mem]))), () => (new Ne(d))),m;if(_optionalChain([o, 'optionalAccess', _873 => _873.functions])&&o.functions.length>0){let b=_nullishCoalesce(_optionalChain([this, 'access', _874 => _874.options, 'optionalAccess', _875 => _875.promptTemplate]), () => (de)),T={functions:o.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new b(this.signature,T)}let A,g=performance.now();Array.isArray(t)?(Dt(t),A=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):A=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let f=performance.now()-g,h=this.getMetricsInstruments();h&&At(h,"prompt_render",f,this.getSignatureName());let I=performance.now();u.addRequest(A,o.sessionId);let x=performance.now()-I;h&&At(h,"memory_update",x,this.getSignatureName());e:for(let b=0;b<p;b++){let T=b===0;for(let J=0;J<l;J++)try{let N=this.forwardCore({options:o,ai:e,mem:u,firstStep:T,span:r,traceContext:i});for await(let _ of N)_!==void 0&&(yield{version:J,index:_.index,delta:_.delta});if(Sr(u,a,n,_optionalChain([o, 'optionalAccess', _876 => _876.sessionId]))){let _=this.getMetricsInstruments();_&&gt(_,b+1,p,this.getSignatureName());continue e}let z=this.getMetricsInstruments();if(z){gt(z,b+1,p,this.getSignatureName());let _=new Set;n.forEach(Tt=>{Tt.functionsExecuted.forEach(Wr=>_.add(Wr))}),_.size>0&&Mn(z,!0,_.size,!0,!1,this.getSignatureName()),ar(z,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(N){let te;if(_optionalChain([r, 'optionalAccess', _877 => _877.recordException, 'call', _878 => _878(N)]),N instanceof G){te=N.getFixingInstructions(),m=N;let z=this.getMetricsInstruments();z&&Sn(z,"validation",this.getSignatureName()),r&&r.addEvent("validation.error",{message:N.toString(),fixing_instructions:_nullishCoalesce(_optionalChain([te, 'optionalAccess', _879 => _879.map, 'call', _880 => _880(_=>_.title), 'access', _881 => _881.join, 'call', _882 => _882(", ")]), () => (""))})}else if(N instanceof re){let z=N;te=z.getFixingInstructions(),m=N;let _=this.getMetricsInstruments();_&&Sn(_,"assertion",this.getSignatureName()),r&&r.addEvent("assertion.error",{message:z.toString(),fixing_instructions:_nullishCoalesce(_optionalChain([te, 'optionalAccess', _883 => _883.map, 'call', _884 => _884(Tt=>Tt.title), 'access', _885 => _885.join, 'call', _886 => _886(", ")]), () => (""))})}else if(!(N instanceof Y))throw Bn(N,e,this.signature);te&&Dr(u,te,e,this.promptTemplate,o.sessionId)}let O=this.getMetricsInstruments();throw O&&kn(O,l,!1,l,this.getSignatureName()),Bn(new Error(`Unable to fix validation error: ${_optionalChain([m, 'optionalAccess', _887 => _887.toString, 'call', _888 => _888()])}`),e,this.signature)}throw h&&gt(h,p,p,this.getSignatureName()),Bn(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let o=performance.now(),r=this.createStates(_nullishCoalesce(n.sampleCount, () => (1))),i=performance.now()-o,a=this.getMetricsInstruments();a&&At(a,"state_creation",i,this.getSignatureName());let l=_nullishCoalesce(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _889 => _889.tracer]), () => (_optionalChain([this, 'access', _890 => _890.options, 'optionalAccess', _891 => _891.tracer]))), () => (e.getOptions().tracer)),p=this.functions;if(_optionalChain([n, 'optionalAccess', _892 => _892.functions])&&(p=Tn(n.functions,this.functions)),!l){yield*this._forward2(e,t,r,{...n,functions:p});return}let c=_optionalChain([p, 'optionalAccess', _893 => _893.map, 'call', _894 => _894(h=>h.name), 'access', _895 => _895.join, 'call', _896 => _896(",")]),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...c?{provided_functions:c}:{},..._optionalChain([n, 'optionalAccess', _897 => _897.model])?{model:n.model}:{},..._optionalChain([n, 'optionalAccess', _898 => _898.thinkingTokenBudget])?{thinking_token_budget:n.thinkingTokenBudget}:{},..._optionalChain([n, 'optionalAccess', _899 => _899.showThoughts])?{show_thoughts:n.showThoughts}:{},..._optionalChain([n, 'optionalAccess', _900 => _900.maxSteps])?{max_steps:n.maxSteps}:{},..._optionalChain([n, 'optionalAccess', _901 => _901.maxRetries])?{max_retries:n.maxRetries}:{}},u=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:_nullishCoalesce(n.traceLabel, () => (this.traceLabel)),m=u?`AxGen > ${u}`:"AxGen",A=l.startSpan(m,{kind:_api.SpanKind.SERVER,attributes:d}),g=_api.context.active(),f=_api.trace.setSpan(g,A);try{if(this.excludeContentFromTrace||A.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,r,{...n,functions:p},A,f),!this.excludeContentFromTrace){let h=r.map(x=>x.values),I=h.length===1?h[0]:h;A.addEvent("output",{content:JSON.stringify(I,null,2)})}}finally{A.end()}}async forward(e,t,n){let o=performance.now(),r=this.getSignatureName(),i=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _902 => _902.stream]), () => (!1)),a=!1,l=0,p=!1,c=0,d=!1;try{let u=this.getMetricsInstruments();u&&cr(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,_nullishCoalesce(_optionalChain([this, 'access', _903 => _903.examples, 'optionalAccess', _904 => _904.length]), () => (0)),_nullishCoalesce(_optionalChain([this, 'access', _905 => _905.demos, 'optionalAccess', _906 => _906.length]), () => (0)),r),p=!!(_optionalChain([n, 'optionalAccess', _907 => _907.functions])||this.functions);let m=this._forward1(e,t,_nullishCoalesce(n, () => ({}))),A=[],g=0,f=0;for await(let O of m)O.version!==g&&(A=[]),g=O.version,A=_n(A,O),f++;l=g;let h=performance.now();d=!!_optionalChain([n, 'optionalAccess', _908 => _908.resultPicker]);let I=await ft(A,{resultPicker:_optionalChain([n, 'optionalAccess', _909 => _909.resultPicker])},_optionalChain([n, 'optionalAccess', _910 => _910.mem]),_optionalChain([n, 'optionalAccess', _911 => _911.sessionId])),x=performance.now()-h,T=_nullishCoalesce(_optionalChain([A, 'access', _912 => _912[I], 'optionalAccess', _913 => _913.delta]), () => ({}));return this.trace={...t,...T},a=!0,u&&(pr(u,A.length,d,d?x:void 0,r),lr(u,i,f,void 0,r)),T}catch(u){throw a=!1,u}finally{let u=performance.now()-o,m=this.getMetricsInstruments();m&&(ir(m,u,a,r,e.getName(),_optionalChain([n, 'optionalAccess', _914 => _914.model])),p&&Mn(m,p,c,c>0,!1,r),l>0&&kn(m,l,a,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _915 => _915.maxRetries]), () => (10)),r))}}async*streamingForward(e,t,n){if(!_optionalChain([n, 'optionalAccess', _916 => _916.resultPicker])){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),r=[],i=0;for await(let p of o)p.version!==i&&(r=[]),i=p.version,r=_n(r,p);let a=await ft(r,{resultPicker:_optionalChain([n, 'optionalAccess', _917 => _917.resultPicker])},_optionalChain([n, 'optionalAccess', _918 => _918.mem]),_optionalChain([n, 'optionalAccess', _919 => _919.sessionId])),l=r[a];l&&(yield{version:i,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _920 => _920.debug]), () => (_optionalChain([this, 'access', _921 => _921.options, 'optionalAccess', _922 => _922.debug]))), () => (e.getOptions().debug)), () => (!1))}getLogger(e,t){return _nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _923 => _923.logger]), () => (_optionalChain([this, 'access', _924 => _924.options, 'optionalAccess', _925 => _925.logger]))), () => (e.getLogger()))}}, _class31),yt= exports.AxGenerateError =class extends Error{constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,_optionalChain([n, 'optionalAccess', _926 => _926.cause])&&(this.cause=n.cause)}};function Bn(s,e,t){let n=s instanceof Error?s:new Error(String(s)),o=e.getLastUsedChatModel(),r=e.getLastUsedModelConfig(),i={model:o,maxTokens:_optionalChain([r, 'optionalAccess', _927 => _927.maxTokens]),streaming:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _928 => _928.stream]), () => (!1)),signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new yt("Generate failed",i,{cause:n})}var ui=s=>s.replace(/^\W+|\W+$/g,""),di=(s,e)=>{let t=s.search(e);if(t===-1)return[s];let n=s.match(e);if(!n)throw new Error("Match failed unexpectedly.");let o=s.substring(0,t),r=s.substring(t+n[0].length);return[o,r]},mi=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},gi=s=>{let e=s.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}},Ai=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},hi=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},$e= exports.AxStringUtil ={trimNonAlphaNum:ui,splitIntoTwo:di,dedup:mi,extractIdAndText:gi,extractIndexPrefixedText:Ai,batchArray:hi};var $n= (_class32 =class extends S{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."
137
- query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e);_class32.prototype.__init105.call(this);}__init105() {this.forward=async(e,t,n)=>{let{rankedItems:o}=await super.forward(e,t,n),r=o.map(a=>{let{id:l}=$e.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let p=r[l];return p!==void 0?t.items[p]:void 0}).filter(a=>a!==void 0)}}}}, _class32);var qn=class{constructor(e){let t=_nullishCoalesce(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=_optionalChain([t, 'optionalAccess', _929 => _929.format])==="html"?"text/html":"text/plain";try{let o={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(o.duplex="half");let r=await(_nullishCoalesce(this.fetch, () => (fetch)))(this.tikaUrl,o);if(!r.ok)throw new Error(`Failed to upload file: ${r.statusText}`);return await r.text()}catch(o){throw new Error(`Error converting file: ${o}`)}}async convert(e,t){let n=[],o=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _930 => _930.batchSize]), () => (10));for(let r=0;r<e.length;r+=o){let a=e.slice(r,r+o).map(p=>this._convert(p,{format:_optionalChain([t, 'optionalAccess', _931 => _931.format])})),l=await Promise.all(a);n.push(...l)}return n}};var Ur=new H,zn= exports.AxSimpleClassifierClass =class{constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},jn= exports.AxSimpleClassifier = (_class33 =class{constructor(e){;_class33.prototype.__init106.call(this);this.db=new oe,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}__init106() {this.setClasses=async(e,t)=>{for(let n of e){let o=await this.ai.embed({texts:n.getContext()},{abortSignal:_optionalChain([t, 'optionalAccess', _933 => _933.abortSignal])});await this.db.upsert({id:n.getName(),table:"classes",values:o.embeddings[0]})}}}async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:_optionalChain([t, 'optionalAccess', _934 => _934.abortSignal])}),r=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof _optionalChain([t, 'optionalAccess', _935 => _935.cutoff])=="number"){let{cutoff:a}=t;r=r.filter(l=>l.score<=a)}this.debug&&console.log(`${Ur.whiteBright(`query: ${e}`)}
138
- ${Ur.greenBright(JSON.stringify(r.map(a=>`${a.id}, ${a.score}`)))}`);let i=r.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}}, _class33);var Nr=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 Lr(s,e){return s.filter(t=>!e.has(t))}function Br(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function ie(s){let e=s.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function xi(s,e){return ie(s)===ie(e)?1:0}function fi(s,e){let t=ie(s).split(" "),n=ie(e).split(" "),o=Br(t),r=Br(n),i=0;for(let p in o){let c=_nullishCoalesce(o[p], () => (0)),d=_nullishCoalesce(r[p], () => (0));i+=Math.min(c,d)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function yi(s,e,t,n=!1){let o=ie(s).split(" "),r=ie(e).split(" "),i=ie(t).split(" "),a=new Set([...Nr,...o]);r=Lr(r,a),i=Lr(i,a);let l=0,p=l/r.length,c=l/i.length,d=2*p*c/(p+c);return n?c:d}var Ii={emScore:xi,f1Score:fi,novelF1ScoreOptimized:yi};var Hn=class{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,o=0;for(let i=0;i<n;i++){let a=this.examples[i];if(!a)throw new Error("Invalid example");let l=await this.program.forward(this.ai,a),p=await e({prediction:l,example:a});o+=p;let c=Date.now()-t;ue(i,n,o,c,"Testing Prompt",30)}let r=n>0?o/n:0;console.log(`
181
+ `))):n.push(t),[{type:"text",text:n.join("")}]}}}, _class30),Dr=s=>s.map(e=>`\`${e.title}\``).join(", "),ti=s=>s.map(t=>{let n=t.title,o=_optionalChain([t, 'access', _784 => _784.type, 'optionalAccess', _785 => _785.name])?Nr(t.type):"string",r=t.isOptional?`This optional ${o} field may be omitted`:`A ${o} field`,i=t.description?` ${gt(t.description)}`:"";return`${n}: (${r})${i}`.trim()}).join(`
182
+ `),ni=s=>s.map(t=>{let n=t.title,o=_optionalChain([t, 'access', _786 => _786.type, 'optionalAccess', _787 => _787.name])?Nr(t.type):"string",r=t.isOptional?`Only include this ${o} field if its value is available`:`This ${o} field must be included`,i="";return t.description&&t.description.length>0&&(i=` ${_optionalChain([t, 'access', _788 => _788.type, 'optionalAccess', _789 => _789.name])==="class"?t.description:gt(t.description)}`),_optionalChain([t, 'access', _790 => _790.type, 'optionalAccess', _791 => _791.options])&&t.type.options.length>0&&(i.length>0&&(i+=". "),i+=`Allowed values: ${t.type.options.join(", ")}`),`${n}: (${r})${i}`.trim()}).join(`
183
+ `),oi=(s,e)=>{if(_optionalChain([s, 'access', _792 => _792.type, 'optionalAccess', _793 => _793.name])==="date"&&e instanceof Date){let t=e.toISOString();return t.slice(0,t.indexOf("T"))}return _optionalChain([s, 'access', _794 => _794.type, 'optionalAccess', _795 => _795.name])==="datetime"&&e instanceof Date?yr(e):_optionalChain([s, 'access', _796 => _796.type, 'optionalAccess', _797 => _797.name])==="image"&&typeof e=="object"||_optionalChain([s, 'access', _798 => _798.type, 'optionalAccess', _799 => _799.name])==="audio"&&typeof e=="object"||typeof e=="string"?e:JSON.stringify(e,null,2)},Nr=s=>{let e=(()=>{switch(_optionalChain([s, 'optionalAccess', _800 => _800.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";default:return"string"}})();return _optionalChain([s, 'optionalAccess', _801 => _801.isArray])?`json array of ${e} items`:e};function Ur(s){return(e,t)=>{if(t.type==="text"){let n=e.length>0?e[e.length-1]:null;n&&n.type==="text"?n.text+=s+t.text:e.push(t)}else e.push(t);return e}}var ri=(s,e,t)=>{if(typeof e=="boolean")return!1;if(!e||(Array.isArray(e)||typeof e=="string")&&e.length===0){if(_optionalChain([t, 'optionalAccess', _802 => _802.isExample])||s.isOptional||s.isInternal)return!0;let n=_optionalChain([t, 'optionalAccess', _803 => _803.isInputField])!==!1?"input":"output";throw new Error(`Value for ${n} field '${s.name}' is required.`)}return!1};function gt(s){let e=s.trim();return e.length>0?`${e.charAt(0).toUpperCase()}${e.slice(1)}${e.endsWith(".")?"":"."}`:""}function si(s,e){let t=s.history(0,e),n=t.some(r=>r.role==="function");return t.some(r=>r.role==="assistant"&&"functionCalls"in r&&Array.isArray(r.functionCalls)&&r.functionCalls.length>0)&&n}function ii(s,e){let t=s.history(0,e),n=[],o=t.filter(i=>i.role==="assistant"&&"functionCalls"in i&&Array.isArray(i.functionCalls)&&i.functionCalls.length>0),r=t.filter(i=>i.role==="function");for(let i of o)if("functionCalls"in i&&i.functionCalls)for(let a of i.functionCalls){let l=r.find(p=>"functionId"in p&&p.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 At(s,e,t,n){if(!_optionalChain([e, 'optionalAccess', _804 => _804.resultPicker])||s.length<=1)return 0;let o=e.resultPicker;if((t?si(t,n):!1)&&t){let l=ii(t,n),p=await o({type:"function",results:l});if(p<0||p>=l.length)throw new Error(`Result picker returned invalid index: ${p}. Must be between 0 and ${l.length-1}`);return p}let i=s.map((l,p)=>({index:p,sample:l.delta})),a=await o({type:"fields",results:i});if(a<0||a>=s.length)throw new Error(`Result picker returned invalid index: ${a}. Must be between 0 and ${s.length-1}`);return a}async function $r(s,e,t){let n=_optionalChain([s, 'optionalAccess', _805 => _805.getLast, 'call', _806 => _806(e)]);if(!n||n.role!=="assistant"||n.chat.length<=1)return 0;let o=n.chat.map(i=>({version:0,index:i.index,delta:i.value}));return await At(o,t,s,e)}var k= (_class31 =class extends te{__init105() {this.fieldProcessors=[]}__init106() {this.streamingFieldProcessors=[]}__init107() {this.excludeContentFromTrace=!1}constructor(e,t){super(e,{description:_optionalChain([t, 'optionalAccess', _809 => _809.description]),traceLabel:_optionalChain([t, 'optionalAccess', _810 => _810.traceLabel])});_class31.prototype.__init105.call(this);_class31.prototype.__init106.call(this);_class31.prototype.__init107.call(this);_class31.prototype.__init108.call(this);_class31.prototype.__init109.call(this);_class31.prototype.__init110.call(this);_class31.prototype.__init111.call(this);_class31.prototype.__init112.call(this);,this.options=t,this.thoughtFieldName=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _811 => _811.thoughtFieldName]), () => ("thought"));let n={functions:_optionalChain([t, 'optionalAccess', _812 => _812.functions]),thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _813 => _813.promptTemplate]), () => (ae)))(this.signature,n),this.asserts=_nullishCoalesce(_optionalChain([this, 'access', _814 => _814.options, 'optionalAccess', _815 => _815.asserts]), () => ([])),this.streamingAsserts=_nullishCoalesce(_optionalChain([this, 'access', _816 => _816.options, 'optionalAccess', _817 => _817.streamingAsserts]), () => ([])),this.excludeContentFromTrace=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _818 => _818.excludeContentFromTrace]), () => (!1)),this.usage=[],_optionalChain([t, 'optionalAccess', _819 => _819.functions])&&(this.functions=Cn(t.functions))}getSignatureName(){return this.signature.getDescription()||"unknown_signature"}getMetricsInstruments(){return yn()}updateMeter(e){yn(e)}createStates(e){return Array.from({length:e},(t,n)=>({index:n,functionCalls:[],values:{},content:"",functionsExecuted:new Set,xstate:{extractedFields:[],streamedIndex:{},s:-1}}))}__init108() {this.addAssert=(e,t)=>{this.asserts.push({fn:e,message:t})}}__init109() {this.addStreamingAssert=(e,t,n)=>{this.streamingAsserts.push({fieldName:e,fn:t,message:n})}}__init110() {this.addFieldProcessorInternal=(e,t,n=!1)=>{let o=this.signature.getOutputFields().find(r=>r.name===e);if(!o)throw new Error(`addFieldProcessor: field ${e} not found`);if(n){let r=_optionalChain([o, 'access', _820 => _820.type, 'optionalAccess', _821 => _821.name]);if(!(!r||r==="string"||r==="code"))throw new Error(`addFieldProcessor: field ${e} is must be a text field`);this.streamingFieldProcessors.push({field:o,process:t})}else this.fieldProcessors.push({field:o,process:t})}}__init111() {this.addStreamingFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!0)}}__init112() {this.addFieldProcessor=(e,t)=>{this.addFieldProcessorInternal(e,t,!1)}}async forwardSendRequest({ai:e,mem:t,options:n,traceContext:o,functions:r,functionCall:i,stepIndex:a}){let{sessionId:l,traceId:p,model:c,rateLimiter:d,stream:u,thinkingTokenBudget:m,showThoughts:A}=_nullishCoalesce(n, () => ({})),g=await $r(t,l,{resultPicker:_optionalChain([n, 'optionalAccess', _822 => _822.resultPicker])}),f=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _823 => _823.history, 'call', _824 => _824(g,l)]), () => ([]));if(f.length===0)throw new Error("No chat prompt found");let h={..._optionalChain([n, 'optionalAccess', _825 => _825.modelConfig]),..._optionalChain([n, 'optionalAccess', _826 => _826.sampleCount])?{n:n.sampleCount}:{},..._optionalChain([n, 'optionalAccess', _827 => _827.sampleCount])&&_optionalChain([n, 'optionalAccess', _828 => _828.modelConfig, 'optionalAccess', _829 => _829.temperature])===1?{temperature:.8}:{}},y=this.isDebug(e,n),x=a===0;return await e.chat({chatPrompt:f,functions:r,functionCall:i,modelConfig:h,model:c},{sessionId:l,traceId:p,rateLimiter:d,stream:u,debug:y,debugHideSystemPrompt:!x,thinkingTokenBudget:m,showThoughts:A,traceContext:o,abortSignal:_optionalChain([n, 'optionalAccess', _830 => _830.abortSignal]),stepIndex:a})}async*forwardCore({ai:e,mem:t,options:n,stepIndex:o,span:r,traceContext:i}){let{sessionId:a,traceId:l,functions:p}=_nullishCoalesce(n, () => ({})),c=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _831 => _831.functionCall]), () => (_optionalChain([this, 'access', _832 => _832.options, 'optionalAccess', _833 => _833.functionCall]))),d=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _834 => _834.strictMode]), () => (!1)),u=n.model,m=this.createStates(_nullishCoalesce(n.sampleCount, () => (1))),A=this.usage,g=o===0,{functions:f,functionCall:h}=Ar(p,c,g),y=await this.forwardSendRequest({ai:e,mem:t,options:n,traceContext:i,functions:f,functionCall:h,stepIndex:o});y instanceof ReadableStream?yield*Er({ai:e,model:u,res:y,mem:t,traceId:l,sessionId:a,functions:f,strictMode:d,span:r,states:m,usage:A,asserts:this.asserts,streamingAsserts:this.streamingAsserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,functionResultFormatter:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _835 => _835.functionResultFormatter]), () => (_optionalChain([this, 'access', _836 => _836.options, 'optionalAccess', _837 => _837.functionResultFormatter])))}):yield*Mr({ai:e,model:u,res:y,mem:t,traceId:l,sessionId:a,functions:f,span:r,strictMode:d,states:m,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,functionResultFormatter:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _838 => _838.functionResultFormatter]), () => (_optionalChain([this, 'access', _839 => _839.options, 'optionalAccess', _840 => _840.functionResultFormatter])))})}async*_forward2(e,t,n,o,r,i){let a=_optionalChain([(_nullishCoalesce(_optionalChain([o, 'optionalAccess', _841 => _841.stopFunction]), () => (_optionalChain([this, 'access', _842 => _842.options, 'optionalAccess', _843 => _843.stopFunction])))), 'optionalAccess', _844 => _844.toLowerCase, 'call', _845 => _845()]),l=_nullishCoalesce(_nullishCoalesce(o.maxRetries, () => (_optionalChain([this, 'access', _846 => _846.options, 'optionalAccess', _847 => _847.maxRetries]))), () => (10)),p=_nullishCoalesce(_nullishCoalesce(o.maxSteps, () => (_optionalChain([this, 'access', _848 => _848.options, 'optionalAccess', _849 => _849.maxSteps]))), () => (10)),c=_nullishCoalesce(_nullishCoalesce(o.mem, () => (_optionalChain([this, 'access', _850 => _850.options, 'optionalAccess', _851 => _851.mem]))), () => (new _e)),d;if(_optionalChain([o, 'optionalAccess', _852 => _852.functions])&&o.functions.length>0){let y=_nullishCoalesce(_optionalChain([this, 'access', _853 => _853.options, 'optionalAccess', _854 => _854.promptTemplate]), () => (ae)),x={functions:o.functions,thoughtFieldName:this.thoughtFieldName};this.promptTemplate=new y(this.signature,x)}let u,m=performance.now();Array.isArray(t)?(Mt(t),u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})):u=this.promptTemplate.render(t,{examples:this.examples,demos:this.demos});let A=performance.now()-m,g=this.getMetricsInstruments();g&&pt(g,"prompt_render",A,this.getSignatureName());let f=performance.now();c.addRequest(u,o.sessionId);let h=performance.now()-f;g&&pt(g,"memory_update",h,this.getSignatureName());e:for(let y=0;y<p;y++){for(let b=0;b<l;b++)try{let R=this.forwardCore({options:o,ai:e,mem:c,stepIndex:y,span:r,traceContext:i});for await(let L of R)L!==void 0&&(yield{version:b,index:L.index,delta:L.delta});if(_r(c,a,n,_optionalChain([o, 'optionalAccess', _855 => _855.sessionId]))){let L=this.getMetricsInstruments();L&&lt(L,y+1,p,this.getSignatureName());continue e}let $=this.getMetricsInstruments();if($){lt($,y+1,p,this.getSignatureName());let L=new Set;n.forEach(bt=>{bt.functionsExecuted.forEach(Rt=>L.add(Rt))}),L.size>0&&Rn($,!0,L.size,!0,!1,this.getSignatureName()),ar($,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName())}return}catch(R){let T,$=this.isDebug(e,o),L=this.getLogger(e,o),bt=this.getMetricsInstruments(),Rt=this.getSignatureName(),Ct={error:R,errCount:b,logger:L,metricsInstruments:bt,signatureName:Rt,span:r,debug:$};if(_optionalChain([r, 'optionalAccess', _856 => _856.recordException, 'call', _857 => _857(R)]),R instanceof G)T=ur(Ct),d=R;else if(R instanceof Z)T=dr(Ct),d=R;else if(R instanceof O)mr(Ct);else if(!(R instanceof W))throw Gn(R,e,this.signature);T&&(c.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(T)}],o.sessionId),c.addTag("error",o.sessionId))}let x=this.getMetricsInstruments();throw x&&bn(x,l,!1,l,this.getSignatureName()),Gn(new Error(`Unable to fix validation error: ${_optionalChain([d, 'optionalAccess', _858 => _858.toString, 'call', _859 => _859()])}`),e,this.signature)}throw g&&lt(g,p,p,this.getSignatureName()),Gn(new Error(`Max steps reached: ${p}`),e,this.signature)}async*_forward1(e,t,n){let o=performance.now(),r=this.createStates(_nullishCoalesce(n.sampleCount, () => (1))),i=performance.now()-o,a=this.getMetricsInstruments();a&&pt(a,"state_creation",i,this.getSignatureName());let l=_nullishCoalesce(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _860 => _860.tracer]), () => (_optionalChain([this, 'access', _861 => _861.options, 'optionalAccess', _862 => _862.tracer]))), () => (e.getOptions().tracer)),p=this.functions;if(_optionalChain([n, 'optionalAccess', _863 => _863.functions])&&(p=Cn(n.functions,this.functions)),!l){yield*this._forward2(e,t,r,{...n,functions:p});return}let c=_optionalChain([p, 'optionalAccess', _864 => _864.map, 'call', _865 => _865(h=>h.name), 'access', _866 => _866.join, 'call', _867 => _867(",")]),d={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...c?{provided_functions:c}:{},..._optionalChain([n, 'optionalAccess', _868 => _868.model])?{model:n.model}:{},..._optionalChain([n, 'optionalAccess', _869 => _869.thinkingTokenBudget])?{thinking_token_budget:n.thinkingTokenBudget}:{},..._optionalChain([n, 'optionalAccess', _870 => _870.showThoughts])?{show_thoughts:n.showThoughts}:{},..._optionalChain([n, 'optionalAccess', _871 => _871.maxSteps])?{max_steps:n.maxSteps}:{},..._optionalChain([n, 'optionalAccess', _872 => _872.maxRetries])?{max_retries:n.maxRetries}:{}},u=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:_nullishCoalesce(n.traceLabel, () => (this.traceLabel)),m=u?`AxGen > ${u}`:"AxGen",A=l.startSpan(m,{kind:_api.SpanKind.SERVER,attributes:d}),g=_api.context.active(),f=_api.trace.setSpan(g,A);try{if(this.excludeContentFromTrace||A.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,r,{...n,functions:p},A,f),!this.excludeContentFromTrace){let h=r.map(x=>x.values),y=h.length===1?h[0]:h;A.addEvent("output",{content:JSON.stringify(y,null,2)})}}finally{A.end()}}async forward(e,t,n){let o=performance.now(),r=this.getSignatureName(),i=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _873 => _873.stream]), () => (!1)),a=!1,l=0,p=!1,c=0,d=!1;try{let u=this.getMetricsInstruments();u&&cr(u,this.signature.getInputFields().length,this.signature.getOutputFields().length,_nullishCoalesce(_optionalChain([this, 'access', _874 => _874.examples, 'optionalAccess', _875 => _875.length]), () => (0)),_nullishCoalesce(_optionalChain([this, 'access', _876 => _876.demos, 'optionalAccess', _877 => _877.length]), () => (0)),r),p=!!(_optionalChain([n, 'optionalAccess', _878 => _878.functions])||this.functions);let m=this._forward1(e,t,_nullishCoalesce(n, () => ({}))),A=[],g=0,f=0;for await(let T of m)T.version!==g&&(A=[]),g=T.version,A=Sn(A,T),f++;l=g;let h=performance.now();d=!!_optionalChain([n, 'optionalAccess', _879 => _879.resultPicker]);let y=await At(A,{resultPicker:_optionalChain([n, 'optionalAccess', _880 => _880.resultPicker])},_optionalChain([n, 'optionalAccess', _881 => _881.mem]),_optionalChain([n, 'optionalAccess', _882 => _882.sessionId])),x=performance.now()-h,R=_nullishCoalesce(_optionalChain([A, 'access', _883 => _883[y], 'optionalAccess', _884 => _884.delta]), () => ({}));if(this.trace={...t,...R},d&&this.isDebug(e,n)){let T=this.getLogger(e,n);Co(A.length,y,x,T)}return a=!0,u&&(pr(u,A.length,d,d?x:void 0,r),lr(u,i,f,void 0,r)),R}catch(u){throw a=!1,u}finally{let u=performance.now()-o,m=this.getMetricsInstruments();m&&(sr(m,u,a,r,e.getName(),_optionalChain([n, 'optionalAccess', _885 => _885.model])),p&&Rn(m,p,c,c>0,!1,r),l>0&&bn(m,l,a,_nullishCoalesce(_optionalChain([n, 'optionalAccess', _886 => _886.maxRetries]), () => (10)),r))}}async*streamingForward(e,t,n){if(!_optionalChain([n, 'optionalAccess', _887 => _887.resultPicker])){yield*this._forward1(e,t,{...n,stream:!0});return}let o=this._forward1(e,t,{...n,stream:!0}),r=[],i=0;for await(let p of o)p.version!==i&&(r=[]),i=p.version,r=Sn(r,p);let a=await At(r,{resultPicker:_optionalChain([n, 'optionalAccess', _888 => _888.resultPicker])},_optionalChain([n, 'optionalAccess', _889 => _889.mem]),_optionalChain([n, 'optionalAccess', _890 => _890.sessionId])),l=r[a];l&&(yield{version:i,index:a,delta:l.delta})}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _891 => _891.debug]), () => (_optionalChain([this, 'access', _892 => _892.options, 'optionalAccess', _893 => _893.debug]))), () => (e.getOptions().debug)), () => (!1))}getLogger(e,t){return _nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _894 => _894.logger]), () => (_optionalChain([this, 'access', _895 => _895.options, 'optionalAccess', _896 => _896.logger]))), () => (e.getLogger()))}}, _class31),ht= exports.AxGenerateError =class extends Error{constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,_optionalChain([n, 'optionalAccess', _897 => _897.cause])&&(this.cause=n.cause)}};function Gn(s,e,t){let n=s instanceof Error?s:new Error(String(s)),o=e.getLastUsedChatModel(),r=e.getLastUsedModelConfig(),i={model:o,maxTokens:_optionalChain([r, 'optionalAccess', _898 => _898.maxTokens]),streaming:_nullishCoalesce(_optionalChain([r, 'optionalAccess', _899 => _899.stream]), () => (!1)),signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new ht("Generate failed",i,{cause:n})}var ci=s=>s.replace(/^\W+|\W+$/g,""),ui=(s,e)=>{let t=s.search(e);if(t===-1)return[s];let n=s.match(e);if(!n)throw new Error("Match failed unexpectedly.");let o=s.substring(0,t),r=s.substring(t+n[0].length);return[o,r]},di=s=>{let e=new Set,t=[];for(let n of s)e.has(n)||(e.add(n),t.push(n));return t},mi=s=>{let e=s.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}},gi=s=>{let e=s.match(/^(\d+)[.,\s]+(.*)$/);return e&&e[2]!==void 0?e[2].trim():s},Ai=(s,e)=>{let t=[];for(let n=0;n<s.length;n+=e)t.push(s.slice(n,n+e));return t},Ge= exports.AxStringUtil ={trimNonAlphaNum:ci,splitIntoTwo:ui,dedup:di,extractIdAndText:mi,extractIndexPrefixedText:gi,batchArray:Ai};var Dn= (_class32 =class extends k{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."
184
+ query: string, items: string[] -> rankedItems: string[] "list of id, 5-words Rationale, relevance score"`,e);_class32.prototype.__init113.call(this);}__init113() {this.forward=async(e,t,n)=>{let{rankedItems:o}=await super.forward(e,t,n),r=o.map(a=>{let{id:l}=Ge.extractIdAndText(a);return l});return{rankedItems:t.items.map((a,l)=>{let p=r[l];return p!==void 0?t.items[p]:void 0}).filter(a=>a!==void 0)}}}}, _class32);var Un=class{constructor(e){let t=_nullishCoalesce(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=_optionalChain([t, 'optionalAccess', _900 => _900.format])==="html"?"text/html":"text/plain";try{let o={body:e,headers:{Accept:n},method:"PUT"};typeof window>"u"&&typeof process<"u"&&(o.duplex="half");let r=await(_nullishCoalesce(this.fetch, () => (fetch)))(this.tikaUrl,o);if(!r.ok)throw new Error(`Failed to upload file: ${r.statusText}`);return await r.text()}catch(o){throw new Error(`Error converting file: ${o}`)}}async convert(e,t){let n=[],o=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _901 => _901.batchSize]), () => (10));for(let r=0;r<e.length;r+=o){let a=e.slice(r,r+o).map(p=>this._convert(p,{format:_optionalChain([t, 'optionalAccess', _902 => _902.format])})),l=await Promise.all(a);n.push(...l)}return n}};var Lr=new N,Nn= exports.AxSimpleClassifierClass =class{constructor(e,t){this.name=e,this.context=t}getName(){return this.name}getContext(){return this.context}},$n= exports.AxSimpleClassifier = (_class33 =class{constructor(e){;_class33.prototype.__init114.call(this);this.db=new X,this.ai=e}getState(){return this.db.getDB()}setState(e){this.db.setDB(e)}__init114() {this.setClasses=async(e,t)=>{for(let n of e){let o=await this.ai.embed({texts:n.getContext()},{abortSignal:_optionalChain([t, 'optionalAccess', _904 => _904.abortSignal])});await this.db.upsert({id:n.getName(),table:"classes",values:o.embeddings[0]})}}}async forward(e,t){let{embeddings:n}=await this.ai.embed({texts:[e]},{abortSignal:_optionalChain([t, 'optionalAccess', _905 => _905.abortSignal])}),r=(await this.db.query({table:"classes",values:n[0]})).matches;if(typeof _optionalChain([t, 'optionalAccess', _906 => _906.cutoff])=="number"){let{cutoff:a}=t;r=r.filter(l=>l.score<=a)}this.debug&&console.log(`${Lr.whiteBright(`query: ${e}`)}
185
+ ${Lr.greenBright(JSON.stringify(r.map(a=>`${a.id}, ${a.score}`)))}`);let i=r.at(0);return i?i.id:""}setOptions(e){typeof e.debug=="boolean"&&(this.debug=e.debug)}}, _class33);var Br=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 qr(s,e){return s.filter(t=>!e.has(t))}function zr(s){let e={};for(let t of s)e[t]=(e[t]||0)+1;return e}function ne(s){let e=s.normalize("NFD");return e=e.replace(/\b(a|an|the)\b/g," "),e=e.split(/\s+/).join(" "),e=e.replace(/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/g,""),e.toLowerCase()}function hi(s,e){return ne(s)===ne(e)?1:0}function xi(s,e){let t=ne(s).split(" "),n=ne(e).split(" "),o=zr(t),r=zr(n),i=0;for(let p in o){let c=_nullishCoalesce(o[p], () => (0)),d=_nullishCoalesce(r[p], () => (0));i+=Math.min(c,d)}if(i===0)return 0;let a=i/t.length,l=i/n.length;return 2*a*l/(a+l)}function fi(s,e,t,n=!1){let o=ne(s).split(" "),r=ne(e).split(" "),i=ne(t).split(" "),a=new Set([...Br,...o]);r=qr(r,a),i=qr(i,a);let l=0,p=l/r.length,c=l/i.length,d=2*p*c/(p+c);return n?c:d}var yi={emScore:hi,f1Score:xi,novelF1ScoreOptimized:fi};var Ln=class{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,o=0;for(let i=0;i<n;i++){let a=this.examples[i];if(!a)throw new Error("Invalid example");let l=await this.program.forward(this.ai,a),p=await e({prediction:l,example:a});o+=p;let c=Date.now()-t;Ir(i,n,o,c,"Testing Prompt",30)}let r=n>0?o/n:0;console.log(`
139
186
  Performance: `,o,"/",n,"Average Score: ",r,`
140
- `)}};var Vn= (_class34 =class{__init107() {this.rows=[]}constructor({dataset:e,split:t,config:n,options:o}){;_class34.prototype.__init107.call(this);this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=o}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(!_optionalChain([n, 'optionalAccess', _936 => _936.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=_nullishCoalesce(_optionalChain([this, 'access', _937 => _937.options, 'optionalAccess', _938 => _938.offset]), () => (0)),t=_nullishCoalesce(_optionalChain([this, 'access', _939 => _939.options, 'optionalAccess', _940 => _940.length]), () => (100)),n=encodeURIComponent(this.dataset),o=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return console.log("Downloading data from API."),this.rows=await this.fetchDataFromAPI(o),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(r=>{let i={};return t.forEach(a=>{let l=a.split("."),p=r.row;for(let d of l)Object.hasOwn(p,d)&&(p=p[d]);if(!p)return;let c=n&&a in n?n[a]:a;if(!c)throw new Error(`Invalid field name: ${a}`);i[c]=p}),i}).filter(r=>Object.keys(r).length!==0)}}, _class34);var $r={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},It,bi=s=>{if(It)return It;if(s)return It=Ti(s),It};var bt=$r,Ri= exports.axUpdateOptimizerMetricsConfig =s=>{bt={...bt,...s}},Ci= exports.axGetOptimizerMetricsConfig =()=>({...bt}),Ti=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),q=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=bt.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},wi=(s,e,t,n,o)=>{try{let r=q({success:t.toString(),optimizer_type:n,...o?{program_signature:o}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,r),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,r),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record optimization metric:",r)}},vi=(s,e,t,n,o,r)=>{try{let i=q({optimizer_type:r});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(o,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Oi=(s,e,t)=>{try{let n=q({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Si=(s,e,t,n,o)=>{try{let r=q({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,r),s.costUsageCounter&&s.costUsageCounter.add(t,r),o!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(o,r)}catch(r){console.warn("Failed to record resource usage metric:",r)}},ki=(s,e,t)=>{try{let n=q({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Mi=(s,e,t,n)=>{try{let o=q({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,o),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,o),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},Ei=(s,e,t,n,o)=>{try{let r=q({operation:e,success:n.toString(),optimizer_type:o});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,r),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,r)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,r),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,r))}catch(r){console.warn("Failed to record checkpoint metric:",r)}},Pi=(s,e,t,n,o)=>{try{let r=q({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,r),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,r),o!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(o,r),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,r)}catch(r){console.warn("Failed to record Pareto metric:",r)}},_i=(s,e,t,n,o,r)=>{try{let i=q({optimizer_type:r});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(o,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},Fi=(s,e,t,n)=>{try{let o=q({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Gi=(s,e,t,n)=>{try{let o=q({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,o),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,o),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},Rt= exports.AxDefaultCostTracker = (_class35 =class{__init108() {this.tokenUsage={}}__init109() {this.totalTokens=0}constructor(e){;_class35.prototype.__init108.call(this);_class35.prototype.__init109.call(this);this.costPerModel=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _941 => _941.costPerModel]), () => ({})),this.maxCost=_optionalChain([e, 'optionalAccess', _942 => _942.maxCost]),this.maxTokens=_optionalChain([e, 'optionalAccess', _943 => _943.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 o=this.costPerModel[t]||.001;e+=n/1e3*o}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}}, _class35),ae= exports.AxBaseOptimizer = (_class36 =class{__init110() {this.currentRound=0}__init111() {this.scoreHistory=[]}__init112() {this.configurationHistory=[]}constructor(e){;_class36.prototype.__init110.call(this);_class36.prototype.__init111.call(this);_class36.prototype.__init112.call(this);if(e.examples.length===0)throw new Error("No examples found");this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.examples=e.examples,this.validationSet=e.validationSet,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=_nullishCoalesce(e.checkpointInterval, () => (10)),this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new Rt({maxTokens:1e6});this.costTracker=_nullishCoalesce(e.costTracker, () => (t)),this.metricsInstruments=bi(k.meter),this.stats=this.initializeStats()}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}}}setupRandomSeed(){this.seed!==void 0&&(Math.random=(()=>{let e=this.seed;return()=>(e=(e*9301+49297)%233280,e/233280)})())}checkCostLimits(){return _nullishCoalesce(_optionalChain([this, 'access', _944 => _944.costTracker, 'optionalAccess', _945 => _945.isLimitReached, 'call', _946 => _946()]), () => (!1))}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats)}getValidationSet(e){return _optionalChain([e, 'optionalAccess', _947 => _947.overrideValidationSet])||this.validationSet||this.examples.slice(0,Math.floor(this.examples.length*.2))}getAIService(e=!1,t){return e&&_optionalChain([t, 'optionalAccess', _948 => _948.overrideTeacherAI])?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return _optionalChain([e, 'optionalAccess', _949 => _949.overrideTeacherAI])!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return _optionalChain([e, 'optionalAccess', _950 => _950.overrideTeacherAI])||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let o=this.getAIService(t,n);return await e(o)}getStats(){return{...this.stats}}reset(){this.stats=this.initializeStats(),_optionalChain([this, 'access', _951 => _951.costTracker, 'optionalAccess', _952 => _952.reset, 'call', _953 => _953()]),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}validateProgram(e){let t=[],n=[];return(!("forward"in e)||typeof e.forward!="function")&&t.push("Program must have a forward method"),this.examples.length<2&&(t.push("Need at least 2 examples for optimization"),n.push("Provide more training examples")),this.getValidationSet().length<1&&(t.push("Validation set is empty"),n.push("Provide examples or a validation set")),{isValid:t.length===0,issues:t,suggestions:n}}async compilePareto(e,t,n){let o=Date.now();_optionalChain([n, 'optionalAccess', _954 => _954.verbose])&&(_optionalChain([this, 'access', _955 => _955.getLogger, 'call', _956 => _956(n), 'optionalCall', _957 => _957("Starting Pareto optimization using base implementation",{tags:["discovery"]})]),_optionalChain([this, 'access', _958 => _958.getLogger, 'call', _959 => _959(n), 'optionalCall', _960 => _960("This will run multiple single-objective optimizations",{tags:["discovery"]})]));let r=await this.generateWeightedSolutions(e,t,n),i=await this.generateConstraintSolutions(e,t,n),a=[...r,...i];_optionalChain([n, 'optionalAccess', _961 => _961.verbose])&&_optionalChain([this, 'access', _962 => _962.getLogger, 'call', _963 => _963(n), 'optionalCall', _964 => _964(`Generated ${a.length} candidate solutions`,{tags:["discovery"]})]);let l=this.findParetoFrontier(a),p=this.calculateHypervolume(l);_optionalChain([n, 'optionalAccess', _965 => _965.verbose])&&(_optionalChain([this, 'access', _966 => _966.getLogger, 'call', _967 => _967(n), 'optionalCall', _968 => _968(`Found ${l.length} non-dominated solutions`,{tags:["discovery"]})]),_optionalChain([this, 'access', _969 => _969.getLogger, 'call', _970 => _970(n), 'optionalCall', _971 => _971(`Hypervolume: ${_optionalChain([p, 'optionalAccess', _972 => _972.toFixed, 'call', _973 => _973(4)])||"N/A"}`,{tags:["discovery"]})])),this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(l.length,a.length,"base_optimizer",p);let c=l.length>0?Math.max(...l.map(d=>Math.max(...Object.values(d.scores)))):0;return{demos:l.length>0?[...l[0].demos]:void 0,stats:this.stats,bestScore:c,paretoFront:l,hypervolume:p,paretoFrontSize:l.length,finalConfiguration:{paretoFrontSize:l.length,hypervolume:p,strategy:"weighted_combinations_and_constraints",numSolutions:a.length}}}async generateWeightedSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.studentAI,r),a=await t({prediction:i,example:r}),l=Object.keys(a);_optionalChain([n, 'optionalAccess', _974 => _974.verbose])&&_optionalChain([this, 'access', _975 => _975.getLogger, 'call', _976 => _976(n), 'optionalCall', _977 => _977(`Detected objectives: ${l.join(", ")}`,{tags:["discovery"]})]);let p=this.generateWeightCombinations(l);for(let c=0;c<p.length;c++){let d=p[c];_optionalChain([n, 'optionalAccess', _978 => _978.verbose])&&_optionalChain([this, 'access', _979 => _979.getLogger, 'call', _980 => _980(n), 'optionalCall', _981 => _981(`Optimizing with weights: ${JSON.stringify(d)}`,{tags:["discovery"]})]);let u=async({prediction:m,example:A})=>{let g=await t({prediction:m,example:A}),f=0;for(let[h,I]of Object.entries(g))f+=I*(d[h]||0);return f};try{let m=await this.compile(e,u,{...n,verbose:!1}),A=await this.evaluateWithMultiObjective(e,m,t);o.push({scores:A,demos:m.demos,configuration:{...m.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch(m){_optionalChain([n, 'optionalAccess', _982 => _982.verbose])&&_optionalChain([this, 'access', _983 => _983.getLogger, 'call', _984 => _984(n), 'optionalCall', _985 => _985(`Failed optimization with weights ${JSON.stringify(d)}: ${m}`,{tags:["warning"]})])}}return o}async generateConstraintSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.studentAI,r),a=await t({prediction:i,example:r}),l=Object.keys(a);for(let p of l){_optionalChain([n, 'optionalAccess', _986 => _986.verbose])&&_optionalChain([this, 'access', _987 => _987.getLogger, 'call', _988 => _988(n), 'optionalCall', _989 => _989(`Optimizing ${p} with constraints on other objectives`,{tags:["discovery"]})]);let c=async({prediction:d,example:u})=>{let m=await t({prediction:d,example:u}),A=m[p]||0,g=0;for(let[f,h]of Object.entries(m))f!==p&&h<.3&&(g+=(.3-h)*2);return A-g};try{let d=await this.compile(e,c,{...n,verbose:!1}),u=await this.evaluateWithMultiObjective(e,d,t);o.push({scores:u,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:p,strategy:"constraint_based"}})}catch(d){_optionalChain([n, 'optionalAccess', _990 => _990.verbose])&&_optionalChain([this, 'access', _991 => _991.getLogger, 'call', _992 => _992(n), 'optionalCall', _993 => _993(`Failed constraint optimization for ${p}: ${d}`,{tags:["warning"]})])}}return o}generateWeightCombinations(e){let t=[];for(let o of e){let r={};for(let i of e)r[i]=i===o?1:0;t.push(r)}let n={};for(let o of e)n[o]=1/e.length;if(t.push(n),e.length===2){let[o,r]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[o]:i,[r]:a})}}if(e.length===3){let[o,r,i]=e;t.push({[o]:.5,[r]:.3,[i]:.2},{[o]:.3,[r]:.5,[i]:.2},{[o]:.2,[r]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n){let o=this.getValidationSet(),r={},i={...e};t.demos&&"setDemos"in i&&i.setDemos(t.demos);let a=o.slice(0,Math.min(5,o.length));for(let p of a)try{let c=await i.forward(this.studentAI,p),d=await n({prediction:c,example:p});for(let[u,m]of Object.entries(d))r[u]||(r[u]=[]),r[u].push(m)}catch (e6){}let l={};for(let[p,c]of Object.entries(r))l[p]=c.length>0?c.reduce((d,u)=>d+u,0)/c.length:0;return l}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n],r=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,o.scores)){r=!0;break}this.dominates(o.scores,l.scores)&&i++}r||t.push({demos:o.demos||[],scores:o.scores,configuration:o.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),o=!0,r=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){o=!1;break}a>l&&(r=!0)}return o&&r}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[o,r]=n,i=0,a=[...e].sort((p,c)=>(c.scores[o]||0)-(p.scores[o]||0)),l=0;for(let p of a){let c=p.scores[o]||0,d=p.scores[r]||0;i+=c*(d-l),l=Math.max(l,d)}return i}}async saveCheckpoint(e,t,n,o,r={},i){let a=_optionalChain([i, 'optionalAccess', _994 => _994.overrideCheckpointSave])||this.checkpointSave;if(!a)return;let l=Date.now(),p=!1,c;try{let d={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:o,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:r,examples:this.examples,validationSet:this.validationSet};c=await a(d),p=!0}catch(d){throw p=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,p,e)}return c}async loadCheckpoint(e,t){let n=_optionalChain([t, 'optionalAccess', _995 => _995.overrideCheckpointLoad])||this.checkpointLoad;if(!n)return null;let o=Date.now(),r=!1,i=null;try{i=await n(e),r=i!==null}catch(a){throw r=!1,a}finally{let a=Date.now()-o;this.recordCheckpointMetrics("load",a,r,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=_optionalChain([t, 'optionalAccess', _996 => _996.overrideCheckpointInterval])||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,o,r,i,a,l={},p){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,p)&&await this.saveCheckpoint(o,r,i,a,l,p)}async saveFinalCheckpoint(e,t,n,o,r={},i){_optionalChain([i, 'optionalAccess', _997 => _997.saveCheckpointOnComplete])!==!1&&await this.saveCheckpoint(e,t,n,o,{...r,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:kt}isLoggingEnabled(e){return _optionalChain([e, 'optionalAccess', _998 => _998.verbose])!==void 0?e.verbose:_nullishCoalesce(this.verbose, () => (!0))}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;_i(this.metricsInstruments,n,o,this.examples.length,this.getValidationSet().length,e)}Gi(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,o){if(!this.metricsInstruments)return;wi(this.metricsInstruments,e,t,n,o),ki(this.metricsInstruments,e,n);let r=_nullishCoalesce(_optionalChain([this, 'access', _999 => _999.costTracker, 'optionalAccess', _1000 => _1000.getCurrentCost, 'call', _1001 => _1001()]), () => (0)),i=_nullishCoalesce(_optionalChain([this, 'access', _1002 => _1002.costTracker, 'optionalAccess', _1003 => _1003.getTotalTokens, 'call', _1004 => _1004()]), () => (0));Si(this.metricsInstruments,i,r,n)}recordConvergenceMetrics(e,t,n,o,r){this.metricsInstruments&&vi(this.metricsInstruments,e,t,n,o,r)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Oi(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Mi(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,o){this.metricsInstruments&&Ei(this.metricsInstruments,e,t,n,o)}recordParetoMetrics(e,t,n,o){this.metricsInstruments&&Pi(this.metricsInstruments,e,t,n,o)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&Fi(this.metricsInstruments,e,t,n)}}, _class36);var qe= (_class37 =class extends ae{__init113() {this.traces=[]}constructor(e){super(e);_class37.prototype.__init113.call(this);;let t=e.options||{};this.maxRounds=_nullishCoalesce(t.maxRounds, () => (3)),this.maxDemos=_nullishCoalesce(t.maxDemos, () => (4)),this.maxExamples=_nullishCoalesce(t.maxExamples, () => (16)),this.batchSize=_nullishCoalesce(t.batchSize, () => (1)),this.earlyStoppingPatience=_nullishCoalesce(t.earlyStoppingPatience, () => (0)),this.costMonitoring=_nullishCoalesce(t.costMonitoring, () => (!1)),this.maxTokensPerGeneration=_nullishCoalesce(t.maxTokensPerGeneration, () => (0)),this.verboseMode=_nullishCoalesce(t.verboseMode, () => (!0)),this.debugMode=_nullishCoalesce(t.debugMode, () => (!1))}async compileRound(e,t,n,o){let r=Date.now(),i=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _1005 => _1005.maxDemos]), () => (this.maxDemos)),a={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(a.modelConfig.max_tokens=this.maxTokensPerGeneration);let l=Ui(this.examples,this.maxExamples),p=this.traces.length;for(let c=0;c<l.length;c+=this.batchSize){c>0&&(a.modelConfig.temperature=.7+.001*c);let d=l.slice(c,c+this.batchSize);for(let u of d){if(!u)continue;let m=l.filter(b=>b!==u);e.setExamples(m);let A=this.getTeacherOrStudentAI();this.stats.totalCalls++;let g,f;try{g=await e.forward(A,u,a),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(u).length/4+JSON.stringify(g).length/4),await n({prediction:g,example:u})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch(b){f=b,g={}}let h=c+l.length*t+(d.indexOf(u)+1),I=l.length*this.maxRounds,x=Date.now()-r;if(this.verboseMode||this.debugMode){let b={maxRounds:this.maxRounds,batchSize:this.batchSize,earlyStoppingPatience:this.earlyStoppingPatience,costMonitoring:this.costMonitoring,verboseMode:this.verboseMode,debugMode:this.debugMode};yr(t,h,I,x,u,this.stats,b,g,f)}else ue(h,I,this.traces.length,x,"Tuning Prompt",30);if(this.traces.length>=i)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-p;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?t:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=t;else if(t-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`,(this.verboseMode||this.debugMode)&&_optionalChain([this, 'access', _1006 => _1006.getLogger, 'call', _1007 => _1007(), 'optionalCall', _1008 => _1008(`Early stopping after ${t+1} rounds (no improvement for ${this.earlyStoppingPatience} rounds)`,{tags:["optimizer","warning"]})]);return}}}async compile(e,t,n){let o=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1009 => _1009.maxIterations]), () => (this.maxRounds));this.traces=[],this.reset(),(this.verboseMode||this.debugMode)&&(_optionalChain([this, 'access', _1010 => _1010.getLogger, 'call', _1011 => _1011(), 'optionalCall', _1012 => _1012(`Starting BootstrapFewshot optimization with ${o} rounds`,{tags:["optimizer","start"]})]),_optionalChain([this, 'access', _1013 => _1013.getLogger, 'call', _1014 => _1014(), 'optionalCall', _1015 => _1015(`Using ${this.examples.length} examples, max ${this.maxDemos} demos`,{tags:["optimizer","config"]})]));for(let a=0;a<o&&(await this.compileRound(e,a,t,n),!this.stats.earlyStopped);a++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let r=Di(this.traces),i=0;return this.traces.length>0&&(i=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),(this.verboseMode||this.debugMode)&&_optionalChain([this, 'access', _1016 => _1016.getLogger, 'call', _1017 => _1017(), 'optionalCall', _1018 => _1018(`Bootstrap complete. Generated ${r.length} demos with ${i.toFixed(3)} success rate`,{tags:["optimizer","complete"]})]),{demos:r,stats:this.stats,bestScore:i,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:i}}}}, _class37);function Di(s){let e=new Map;for(let n of s)if(e.has(n.programId)){let o=e.get(n.programId);o&&o.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,o)=>{t.push({traces:n,programId:o})}),t}var Ui=(s,e)=>{let t=[...s];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1)),r=t[n],i=t[o];if(!r||!i)throw new Error("Invalid array elements");[t[n],t[o]]=[i,r]}return t.slice(0,e)};var Wn= (_class38 =class extends ae{__init114() {this.miproConfigHistory=[]}__init115() {this.surrogateModel=new Map}constructor(e){super(e);_class38.prototype.__init114.call(this);_class38.prototype.__init115.call(this);;let t=e.options||{};this.numCandidates=_nullishCoalesce(t.numCandidates, () => (5)),this.initTemperature=_nullishCoalesce(t.initTemperature, () => (.7)),this.maxBootstrappedDemos=_nullishCoalesce(t.maxBootstrappedDemos, () => (3)),this.maxLabeledDemos=_nullishCoalesce(t.maxLabeledDemos, () => (4)),this.numTrials=_nullishCoalesce(t.numTrials, () => (30)),this.minibatch=_nullishCoalesce(t.minibatch, () => (!0)),this.minibatchSize=_nullishCoalesce(t.minibatchSize, () => (25)),this.minibatchFullEvalSteps=_nullishCoalesce(t.minibatchFullEvalSteps, () => (10)),this.programAwareProposer=_nullishCoalesce(t.programAwareProposer, () => (!0)),this.dataAwareProposer=_nullishCoalesce(t.dataAwareProposer, () => (!0)),this.viewDataBatchSize=_nullishCoalesce(t.viewDataBatchSize, () => (10)),this.tipAwareProposer=_nullishCoalesce(t.tipAwareProposer, () => (!0)),this.fewshotAwareProposer=_nullishCoalesce(t.fewshotAwareProposer, () => (!0)),this.earlyStoppingTrials=_nullishCoalesce(t.earlyStoppingTrials, () => (5)),this.minImprovementThreshold=_nullishCoalesce(t.minImprovementThreshold, () => (.01)),this.bayesianOptimization=_nullishCoalesce(t.bayesianOptimization, () => (!1)),this.acquisitionFunction=_nullishCoalesce(t.acquisitionFunction, () => ("expected_improvement")),this.explorationWeight=_nullishCoalesce(t.explorationWeight, () => (.1)),this.sampleCount=_nullishCoalesce(t.sampleCount, () => (1)),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}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 o=`
187
+ `)}};var Bn= (_class34 =class{__init115() {this.rows=[]}constructor({dataset:e,split:t,config:n,options:o}){;_class34.prototype.__init115.call(this);this.baseUrl="https://datasets-server.huggingface.co/rows",this.dataset=e,this.split=t,this.config=n,this.options=o}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(!_optionalChain([n, 'optionalAccess', _907 => _907.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=_nullishCoalesce(_optionalChain([this, 'access', _908 => _908.options, 'optionalAccess', _909 => _909.offset]), () => (0)),t=_nullishCoalesce(_optionalChain([this, 'access', _910 => _910.options, 'optionalAccess', _911 => _911.length]), () => (100)),n=encodeURIComponent(this.dataset),o=`${this.baseUrl}?dataset=${n}&config=${this.config}&split=${this.split}&offset=${e}&length=${t}`;return console.log("Downloading data from API."),this.rows=await this.fetchDataFromAPI(o),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(r=>{let i={};return t.forEach(a=>{let l=a.split("."),p=r.row;for(let d of l)Object.hasOwn(p,d)&&(p=p[d]);if(!p)return;let c=n&&a in n?n[a]:a;if(!c)throw new Error(`Invalid field name: ${a}`);i[c]=p}),i}).filter(r=>Object.keys(r).length!==0)}}, _class34);var jr=s=>{process.stdout.write(s)},Hr= exports.axCreateDefaultOptimizerColorLogger =(s=jr)=>{let e=new N,t=e.gray("\u2500".repeat(50)),n=e.gray("\u2501".repeat(50));return o=>{let r="";switch(o.name){case"OptimizationStart":r=`
188
+ ${e.blueBright("\u25CF ")}${e.whiteBright("Optimization Started")}
189
+ ${t}
190
+ ${e.white("Optimizer:")} ${e.cyan(o.value.optimizerType)}
191
+ ${e.white("Examples:")} ${e.green(o.value.exampleCount.toString())} training, ${e.green(o.value.validationCount.toString())} validation
192
+ ${e.white("Config:")} ${e.white(JSON.stringify(o.value.config).slice(0,80))}${JSON.stringify(o.value.config).length>80?"...":""}
193
+ ${n}
194
+ `;break;case"RoundProgress":r=`${e.yellow("\u25CF ")}${e.whiteBright(`Round ${o.value.round}/${o.value.totalRounds}`)}
195
+ ${e.white("Score:")} ${e.green(o.value.currentScore.toFixed(3))} ${e.white("(best:")} ${e.greenBright(o.value.bestScore.toFixed(3))}${e.white(")")}
196
+ `;break;case"EarlyStopping":r=`
197
+ ${e.red("\u25CF ")}${e.whiteBright("Early Stopping")}
198
+ ${t}
199
+ ${e.white("Round:")} ${e.yellow(o.value.round.toString())}
200
+ ${e.white("Reason:")} ${e.yellow(o.value.reason)}
201
+ ${e.white("Final Score:")} ${e.green(o.value.finalScore.toFixed(3))}
202
+ ${n}
203
+ `;break;case"OptimizationComplete":r=`
204
+ ${e.green("\u25CF ")}${e.whiteBright("Optimization Complete")}
205
+ ${t}
206
+ ${e.white("Best Score:")} ${e.greenBright(o.value.bestScore.toFixed(3))}
207
+ ${e.white("Best Config:")} ${e.cyan(JSON.stringify(o.value.bestConfiguration).slice(0,80))}${JSON.stringify(o.value.bestConfiguration).length>80?"...":""}
208
+ ${e.white("Total Calls:")} ${e.white(_optionalChain([o, 'access', _912 => _912.value, 'access', _913 => _913.stats, 'access', _914 => _914.totalCalls, 'optionalAccess', _915 => _915.toString, 'call', _916 => _916()])||"N/A")}
209
+ ${e.white("Success Rate:")} ${e.green(`${((o.value.stats.successfulDemos||0)/Math.max(o.value.stats.totalCalls||1,1)*100).toFixed(1)}%`)}
210
+ ${n}
211
+ `;break;case"ConfigurationProposal":r=`${e.magenta("\u25CF ")}${e.whiteBright(`${o.value.type} Proposals`)} ${e.white(`(${o.value.count})`)}
212
+ ${e.white("Candidates:")} ${e.white(o.value.proposals.slice(0,2).map(i=>typeof i=="string"?`"${i.slice(0,40)}..."`:`${JSON.stringify(i).slice(0,40)}...`).join(", "))}
213
+ `;break;case"BootstrappedDemos":r=`${e.cyan("\u25CF ")}${e.whiteBright("Bootstrapped Demos")} ${e.white(`(${o.value.count})`)}
214
+ ${e.white("Generated:")} ${e.green(o.value.count.toString())} demonstration examples
215
+ `;break;case"BestConfigFound":r=`${e.green("\u25CF ")}${e.whiteBright("Best Configuration Found")}
216
+ ${e.white("Score:")} ${e.greenBright(o.value.score.toFixed(3))}
217
+ ${e.white("Config:")} ${e.cyan(JSON.stringify(o.value.config).slice(0,80))}${JSON.stringify(o.value.config).length>80?"...":""}
218
+ `;break;default:r=`${e.red("\u25CF ")}${e.whiteBright("Unknown Event")}
219
+ ${e.white(JSON.stringify(o).slice(0,100))}${JSON.stringify(o).length>100?"...":""}
220
+ `}s(r)}},Ii= exports.axCreateDefaultOptimizerTextLogger =(s=jr)=>{let e="\u2500".repeat(60);return t=>{let n="";switch(t.name){case"OptimizationStart":n=`[ OPTIMIZATION START: ${t.value.optimizerType} ]
221
+ ${e}
222
+ Config: ${JSON.stringify(t.value.config,null,2)}
223
+ Examples: ${t.value.exampleCount}, Validation: ${t.value.validationCount}
224
+ ${e}`;break;case"RoundProgress":n=`[ ROUND ${t.value.round}/${t.value.totalRounds} ]
225
+ Current Score: ${t.value.currentScore.toFixed(3)}, Best: ${t.value.bestScore.toFixed(3)}
226
+ Config: ${JSON.stringify(t.value.configuration)}
227
+ ${e}`;break;case"EarlyStopping":n=`[ EARLY STOPPING at Round ${t.value.round} ]
228
+ Reason: ${t.value.reason}
229
+ Final Score: ${t.value.finalScore.toFixed(3)}
230
+ ${e}`;break;case"OptimizationComplete":n=`[ OPTIMIZATION COMPLETE ]
231
+ ${e}
232
+ Best Score: ${t.value.bestScore.toFixed(3)}
233
+ Best Config: ${JSON.stringify(t.value.bestConfiguration)}
234
+ Stats: ${JSON.stringify(t.value.stats,null,2)}
235
+ ${e}`;break;case"ConfigurationProposal":n=`[ CONFIG PROPOSAL: ${t.value.type} ]
236
+ Count: ${t.value.count}
237
+ Proposals: ${JSON.stringify(t.value.proposals.slice(0,3),null,2)} ${t.value.proposals.length>3?"... (truncated)":""}
238
+ ${e}`;break;case"BootstrappedDemos":n=`[ BOOTSTRAPPED DEMOS ]
239
+ Count: ${t.value.count}
240
+ Demos: ${JSON.stringify(t.value.demos.slice(0,2),null,2)} ${t.value.demos.length>2?"... (truncated)":""}
241
+ ${e}`;break;case"BestConfigFound":n=`[ BEST CONFIG FOUND ]
242
+ Score: ${t.value.score.toFixed(3)}
243
+ Config: ${JSON.stringify(t.value.config)}
244
+ ${e}`;break;default:n=`[ UNKNOWN OPTIMIZER EVENT ]
245
+ ${JSON.stringify(t)}
246
+ ${e}`}s(n)}},qn= exports.axDefaultOptimizerLogger =Hr();var Vr={enabled:!0,enabledCategories:["optimization","convergence","resource_usage","teacher_student","checkpointing","pareto"],maxLabelLength:100,samplingRate:1},xt,bi=s=>{if(xt)return xt;if(s)return xt=wi(s),xt};var ft=Vr,Ri= exports.axUpdateOptimizerMetricsConfig =s=>{ft={...ft,...s}},Ci= exports.axGetOptimizerMetricsConfig =()=>({...ft}),wi=s=>({optimizationLatencyHistogram:s.createHistogram("ax_optimizer_optimization_duration_ms",{description:"End-to-end duration of optimization runs",unit:"ms"}),optimizationRequestsCounter:s.createCounter("ax_optimizer_optimization_requests_total",{description:"Total number of optimization requests"}),optimizationErrorsCounter:s.createCounter("ax_optimizer_optimization_errors_total",{description:"Total number of failed optimizations"}),convergenceRoundsHistogram:s.createHistogram("ax_optimizer_convergence_rounds",{description:"Number of rounds until convergence"}),convergenceScoreGauge:s.createGauge("ax_optimizer_convergence_score",{description:"Current best score during optimization"}),convergenceImprovementGauge:s.createGauge("ax_optimizer_convergence_improvement",{description:"Improvement in score from baseline"}),stagnationRoundsGauge:s.createGauge("ax_optimizer_stagnation_rounds",{description:"Number of rounds without improvement"}),earlyStoppingCounter:s.createCounter("ax_optimizer_early_stopping_total",{description:"Total number of early stopping events"}),tokenUsageCounter:s.createCounter("ax_optimizer_token_usage_total",{description:"Total tokens used during optimization"}),costUsageCounter:s.createCounter("ax_optimizer_cost_usage_total",{description:"Total cost incurred during optimization",unit:"$"}),memoryUsageGauge:s.createGauge("ax_optimizer_memory_usage_bytes",{description:"Peak memory usage during optimization",unit:"By"}),optimizationDurationHistogram:s.createHistogram("ax_optimizer_duration_ms",{description:"Duration of optimization runs",unit:"ms"}),teacherStudentUsageCounter:s.createCounter("ax_optimizer_teacher_student_usage_total",{description:"Total number of teacher-student interactions"}),teacherStudentLatencyHistogram:s.createHistogram("ax_optimizer_teacher_student_latency_ms",{description:"Latency of teacher-student interactions",unit:"ms"}),teacherStudentScoreImprovementGauge:s.createGauge("ax_optimizer_teacher_student_score_improvement",{description:"Score improvement from teacher-student interactions"}),checkpointSaveCounter:s.createCounter("ax_optimizer_checkpoint_save_total",{description:"Total number of checkpoint saves"}),checkpointLoadCounter:s.createCounter("ax_optimizer_checkpoint_load_total",{description:"Total number of checkpoint loads"}),checkpointSaveLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_save_latency_ms",{description:"Latency of checkpoint save operations",unit:"ms"}),checkpointLoadLatencyHistogram:s.createHistogram("ax_optimizer_checkpoint_load_latency_ms",{description:"Latency of checkpoint load operations",unit:"ms"}),paretoOptimizationsCounter:s.createCounter("ax_optimizer_pareto_optimizations_total",{description:"Total number of Pareto optimizations"}),paretoFrontSizeHistogram:s.createHistogram("ax_optimizer_pareto_front_size",{description:"Size of Pareto frontier"}),paretoHypervolumeGauge:s.createGauge("ax_optimizer_pareto_hypervolume",{description:"Hypervolume of Pareto frontier"}),paretoSolutionsGeneratedHistogram:s.createHistogram("ax_optimizer_pareto_solutions_generated",{description:"Number of solutions generated for Pareto optimization"}),programInputFieldsGauge:s.createGauge("ax_optimizer_program_input_fields",{description:"Number of input fields in optimized program"}),programOutputFieldsGauge:s.createGauge("ax_optimizer_program_output_fields",{description:"Number of output fields in optimized program"}),examplesCountGauge:s.createGauge("ax_optimizer_examples_count",{description:"Number of training examples used"}),validationSetSizeGauge:s.createGauge("ax_optimizer_validation_set_size",{description:"Size of validation set used"}),evaluationLatencyHistogram:s.createHistogram("ax_optimizer_evaluation_latency_ms",{description:"Latency of program evaluations",unit:"ms"}),demoGenerationLatencyHistogram:s.createHistogram("ax_optimizer_demo_generation_latency_ms",{description:"Latency of demo generation",unit:"ms"}),metricComputationLatencyHistogram:s.createHistogram("ax_optimizer_metric_computation_latency_ms",{description:"Latency of metric computation",unit:"ms"}),optimizerTypeGauge:s.createGauge("ax_optimizer_type",{description:"Type of optimizer being used"}),targetScoreGauge:s.createGauge("ax_optimizer_target_score",{description:"Target score for optimization"}),maxRoundsGauge:s.createGauge("ax_optimizer_max_rounds",{description:"Maximum rounds for optimization"})}),H=s=>{let e={};for(let[t,n]of Object.entries(s))if(n!=null){let o=String(n),r=ft.maxLabelLength;e[t]=o.length>r?o.substring(0,r):o}return e},Ti=(s,e,t,n,o)=>{try{let r=H({success:t.toString(),optimizer_type:n,...o?{program_signature:o}:{}});s.optimizationLatencyHistogram&&s.optimizationLatencyHistogram.record(e,r),s.optimizationRequestsCounter&&s.optimizationRequestsCounter.add(1,r),!t&&s.optimizationErrorsCounter&&s.optimizationErrorsCounter.add(1,r)}catch(r){console.warn("Failed to record optimization metric:",r)}},vi=(s,e,t,n,o,r)=>{try{let i=H({optimizer_type:r});s.convergenceRoundsHistogram&&s.convergenceRoundsHistogram.record(e,i),s.convergenceScoreGauge&&s.convergenceScoreGauge.record(t,i),s.convergenceImprovementGauge&&s.convergenceImprovementGauge.record(n,i),s.stagnationRoundsGauge&&s.stagnationRoundsGauge.record(o,i)}catch(i){console.warn("Failed to record convergence metric:",i)}},Oi=(s,e,t)=>{try{let n=H({reason:e,optimizer_type:t});s.earlyStoppingCounter&&s.earlyStoppingCounter.add(1,n)}catch(n){console.warn("Failed to record early stopping metric:",n)}},Si=(s,e,t,n,o)=>{try{let r=H({optimizer_type:n});s.tokenUsageCounter&&s.tokenUsageCounter.add(e,r),s.costUsageCounter&&s.costUsageCounter.add(t,r),o!==void 0&&s.memoryUsageGauge&&s.memoryUsageGauge.record(o,r)}catch(r){console.warn("Failed to record resource usage metric:",r)}},ki=(s,e,t)=>{try{let n=H({optimizer_type:t});s.optimizationDurationHistogram&&s.optimizationDurationHistogram.record(e,n)}catch(n){console.warn("Failed to record optimization duration metric:",n)}},Ei=(s,e,t,n)=>{try{let o=H({optimizer_type:n});s.teacherStudentUsageCounter&&s.teacherStudentUsageCounter.add(1,o),s.teacherStudentLatencyHistogram&&s.teacherStudentLatencyHistogram.record(e,o),s.teacherStudentScoreImprovementGauge&&s.teacherStudentScoreImprovementGauge.record(t,o)}catch(o){console.warn("Failed to record teacher-student metric:",o)}},Mi=(s,e,t,n,o)=>{try{let r=H({operation:e,success:n.toString(),optimizer_type:o});e==="save"?(s.checkpointSaveCounter&&s.checkpointSaveCounter.add(1,r),s.checkpointSaveLatencyHistogram&&s.checkpointSaveLatencyHistogram.record(t,r)):(s.checkpointLoadCounter&&s.checkpointLoadCounter.add(1,r),s.checkpointLoadLatencyHistogram&&s.checkpointLoadLatencyHistogram.record(t,r))}catch(r){console.warn("Failed to record checkpoint metric:",r)}},_i=(s,e,t,n,o)=>{try{let r=H({optimizer_type:n});s.paretoOptimizationsCounter&&s.paretoOptimizationsCounter.add(1,r),s.paretoFrontSizeHistogram&&s.paretoFrontSizeHistogram.record(e,r),o!==void 0&&s.paretoHypervolumeGauge&&s.paretoHypervolumeGauge.record(o,r),s.paretoSolutionsGeneratedHistogram&&s.paretoSolutionsGeneratedHistogram.record(t,r)}catch(r){console.warn("Failed to record Pareto metric:",r)}},Pi=(s,e,t,n,o,r)=>{try{let i=H({optimizer_type:r});s.programInputFieldsGauge&&s.programInputFieldsGauge.record(e,i),s.programOutputFieldsGauge&&s.programOutputFieldsGauge.record(t,i),s.examplesCountGauge&&s.examplesCountGauge.record(n,i),s.validationSetSizeGauge&&s.validationSetSizeGauge.record(o,i)}catch(i){console.warn("Failed to record program complexity metric:",i)}},Fi=(s,e,t,n)=>{try{let o=H({metric_type:e,optimizer_type:n});switch(e){case"evaluation":s.evaluationLatencyHistogram&&s.evaluationLatencyHistogram.record(t,o);break;case"demo_generation":s.demoGenerationLatencyHistogram&&s.demoGenerationLatencyHistogram.record(t,o);break;case"metric_computation":s.metricComputationLatencyHistogram&&s.metricComputationLatencyHistogram.record(t,o);break}}catch(o){console.warn("Failed to record optimizer performance metric:",o)}},Gi=(s,e,t,n)=>{try{let o=H({optimizer_type:e});s.optimizerTypeGauge&&s.optimizerTypeGauge.record(1,o),t!==void 0&&s.targetScoreGauge&&s.targetScoreGauge.record(t,o),n!==void 0&&s.maxRoundsGauge&&s.maxRoundsGauge.record(n,o)}catch(o){console.warn("Failed to record optimizer configuration metric:",o)}},yt= exports.AxDefaultCostTracker = (_class35 =class{__init116() {this.tokenUsage={}}__init117() {this.totalTokens=0}constructor(e){;_class35.prototype.__init116.call(this);_class35.prototype.__init117.call(this);this.costPerModel=_nullishCoalesce(_optionalChain([e, 'optionalAccess', _917 => _917.costPerModel]), () => ({})),this.maxCost=_optionalChain([e, 'optionalAccess', _918 => _918.maxCost]),this.maxTokens=_optionalChain([e, 'optionalAccess', _919 => _919.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 o=this.costPerModel[t]||.001;e+=n/1e3*o}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}}, _class35),oe= exports.AxBaseOptimizer = (_class36 =class{__init118() {this.currentRound=0}__init119() {this.scoreHistory=[]}__init120() {this.configurationHistory=[]}constructor(e){;_class36.prototype.__init118.call(this);_class36.prototype.__init119.call(this);_class36.prototype.__init120.call(this);if(e.examples.length===0)throw new Error("No examples found");this.studentAI=e.studentAI,this.teacherAI=e.teacherAI,this.examples=e.examples,this.validationSet=e.validationSet,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=_nullishCoalesce(e.checkpointInterval, () => (10)),this.resumeFromCheckpoint=e.resumeFromCheckpoint,this.logger=e.logger,this.verbose=e.verbose;let t=new yt({maxTokens:1e6});this.costTracker=_nullishCoalesce(e.costTracker, () => (t)),this.metricsInstruments=bi(E.meter),this.stats=this.initializeStats(),this.debugOptimizer=_nullishCoalesce(e.debugOptimizer, () => (!1)),this.optimizerLogger=e.optimizerLogger}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 _nullishCoalesce(_optionalChain([this, 'access', _920 => _920.costTracker, 'optionalAccess', _921 => _921.isLimitReached, 'call', _922 => _922()]), () => (!1))}checkTargetScore(e){return this.targetScore!==void 0&&e>=this.targetScore}updateResourceUsage(e,t=0){this.stats.resourceUsage.totalTime=Date.now()-e,this.stats.resourceUsage.totalTokens+=t,this.stats.totalCalls>0&&(this.stats.resourceUsage.avgLatencyPerEval=this.stats.resourceUsage.totalTime/this.stats.totalCalls)}triggerEarlyStopping(e,t){this.stats.earlyStopped=!0,this.stats.earlyStopping={bestScoreRound:t,patienceExhausted:e.includes("improvement"),reason:e},this.recordEarlyStoppingMetrics(e,"unknown"),this.onEarlyStop&&this.onEarlyStop(e,this.stats),_optionalChain([this, 'access', _923 => _923.getOptimizerLogger, 'call', _924 => _924(), 'optionalCall', _925 => _925({name:"EarlyStopping",value:{reason:e,finalScore:_nullishCoalesce(this.stats.bestScore, () => (0)),round:t}})])}getValidationSet(e){return _optionalChain([e, 'optionalAccess', _926 => _926.overrideValidationSet])||this.validationSet||this.examples.slice(0,Math.floor(this.examples.length*.2))}getAIService(e=!1,t){return e&&_optionalChain([t, 'optionalAccess', _927 => _927.overrideTeacherAI])?t.overrideTeacherAI:e&&this.teacherAI?this.teacherAI:this.studentAI}hasTeacherAI(e){return _optionalChain([e, 'optionalAccess', _928 => _928.overrideTeacherAI])!==void 0||this.teacherAI!==void 0}getTeacherOrStudentAI(e){return _optionalChain([e, 'optionalAccess', _929 => _929.overrideTeacherAI])||this.teacherAI||this.studentAI}async executeWithTeacher(e,t=!0,n){let o=this.getAIService(t,n);return await e(o)}async*compileStream(e,t,n){let o=Date.now(),r=this.constructor.name,i=e.getSignature().toString();this.recordOptimizationStart(r,i);let a,l=(m,A,g,f,h,y,x,b={},R)=>{_optionalChain([this, 'access', _930 => _930.getOptimizerLogger, 'call', _931 => _931(R), 'optionalCall', _932 => _932({name:"RoundProgress",value:{round:m,totalRounds:_nullishCoalesce(_optionalChain([R, 'optionalAccess', _933 => _933.maxIterations]), () => (0)),currentScore:A,bestScore:y,configuration:g}})]),this.updateOptimizationProgress(m,A,g,f,h,y,x,b,R)},p=(m,A)=>{a=m,this.triggerEarlyStopping(m,this.currentRound)},c=m=>{_optionalChain([this, 'access', _934 => _934.onProgress, 'optionalCall', _935 => _935(m)]),l(m.round,m.currentScore,m.currentConfiguration||{},r,{},m.bestScore,m.bestConfiguration,m.convergenceInfo,n)},d=await this.compile(e,t,{...n,overrideOnProgress:c,overrideOnEarlyStop:p}),u=Date.now()-o;return this.recordOptimizationComplete(u,!0,r,i),a&&_optionalChain([this, 'access', _936 => _936.getLogger, 'call', _937 => _937(n), 'optionalCall', _938 => _938({name:"Notification",id:"optimization_early_stop",value:`Optimization stopped early due to ${a}`})]),{demos:d.demos,stats:d.stats,bestScore:d.bestScore,finalConfiguration:d.finalConfiguration,scoreHistory:d.scoreHistory,configurationHistory:d.configurationHistory}}async compilePareto(e,t,n){let o=this.constructor.name,r=Date.now(),i=await this.generateWeightedSolutions(e,t,n),a=await this.generateConstraintSolutions(e,t,n),l=[...i,...a],p=this.findParetoFrontier(l),c=this.calculateHypervolume(p);this.updateResourceUsage(r),this.stats.convergenceInfo.converged=!0,this.recordParetoMetrics(p.length,l.length,"base_optimizer",c);let d=p.length>0?Math.max(...p.map(u=>Math.max(...Object.values(u.scores)))):0;return{demos:p.length>0?[...p[0].demos]:void 0,stats:this.stats,bestScore:d,paretoFront:p,hypervolume:c,paretoFrontSize:p.length,finalConfiguration:{paretoFrontSize:p.length,hypervolume:c,strategy:"weighted_combinations_and_constraints",numSolutions:l.length}}}async generateWeightedSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.getAIService(!1,n),r),a=await t({prediction:i,example:r}),l=Object.keys(a),p=this.generateWeightCombinations(l);for(let c=0;c<p.length;c++){let d=p[c],u=async({prediction:m,example:A})=>{let g=await t({prediction:m,example:A}),f=0;for(let[h,y]of Object.entries(g))f+=y*(d[h]||0);return f};try{let m=await this.compile(e,u,{...n,verbose:!1}),A=await this.evaluateWithMultiObjective(e,m,t);o.push({scores:A,demos:m.demos,configuration:{...m.finalConfiguration,weights:d,strategy:"weighted_combination"}})}catch (e6){}}return o}async generateConstraintSolutions(e,t,n){let o=[],r=this.examples[0],i=await e.forward(this.getAIService(!1,n),r),a=await t({prediction:i,example:r}),l=Object.keys(a);for(let p of l){let c=async({prediction:d,example:u})=>{let m=await t({prediction:d,example:u}),A=m[p]||0,g=0;for(let[f,h]of Object.entries(m))f!==p&&h<.3&&(g+=(.3-h)*2);return A-g};try{let d=await this.compile(e,c,{...n,verbose:!1}),u=await this.evaluateWithMultiObjective(e,d,t);o.push({scores:u,demos:d.demos,configuration:{...d.finalConfiguration,primaryObjective:p,strategy:"constraint_based"}})}catch (e7){}}return o}generateWeightCombinations(e){let t=[];for(let o of e){let r={};for(let i of e)r[i]=i===o?1:0;t.push(r)}let n={};for(let o of e)n[o]=1/e.length;if(t.push(n),e.length===2){let[o,r]=e;for(let i=.1;i<=.9;i+=.2){let a=1-i;t.push({[o]:i,[r]:a})}}if(e.length===3){let[o,r,i]=e;t.push({[o]:.5,[r]:.3,[i]:.2},{[o]:.3,[r]:.5,[i]:.2},{[o]:.2,[r]:.3,[i]:.5})}return t}async evaluateWithMultiObjective(e,t,n){let o=new k(e.getSignature());t.demos&&o.setDemos(t.demos);let r=[];for(let c of this.examples){let d=await o.forward(this.studentAI,c);r.push({prediction:d,example:c})}let i=this.getValidationSet(),a={},l=i.slice(0,Math.min(5,i.length));for(let c of l)try{let d=await o.forward(this.studentAI,c),u=await n({prediction:d,example:c});for(let[m,A]of Object.entries(u))a[m]||(a[m]=[]),a[m].push(A)}catch (e8){}let p={};for(let[c,d]of Object.entries(a))p[c]=d.length>0?d.reduce((u,m)=>u+m,0)/d.length:0;return p}findParetoFrontier(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n],r=!1,i=0;for(let a=0;a<e.length;a++){if(n===a)continue;let l=e[a];if(this.dominates(l.scores,o.scores)){r=!0;break}this.dominates(o.scores,l.scores)&&i++}r||t.push({demos:o.demos||[],scores:o.scores,configuration:o.configuration,dominatedSolutions:i})}return t}dominates(e,t){let n=Object.keys(e),o=!0,r=!1;for(let i of n){let a=e[i]||0,l=t[i]||0;if(a<l){o=!1;break}a>l&&(r=!0)}return o&&r}calculateHypervolume(e){if(e.length===0)return;let t=e[0],n=Object.keys(t.scores);if(n.length===2){let[o,r]=n,i=0,a=[...e].sort((p,c)=>(c.scores[o]||0)-(p.scores[o]||0)),l=0;for(let p of a){let c=p.scores[o]||0,d=p.scores[r]||0;i+=c*(d-l),l=Math.max(l,d)}return i}}async saveCheckpoint(e,t,n,o,r={},i){let a=_optionalChain([i, 'optionalAccess', _939 => _939.overrideCheckpointSave])||this.checkpointSave;if(!a)return;let l=Date.now(),p=!1,c;try{let d={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:o,scoreHistory:[...this.scoreHistory],configurationHistory:[...this.configurationHistory],stats:{...this.stats},optimizerState:r,examples:this.examples,validationSet:this.validationSet};c=await a(d),p=!0}catch(d){throw p=!1,d}finally{let d=Date.now()-l;this.recordCheckpointMetrics("save",d,p,e)}return c}async loadCheckpoint(e,t){let n=_optionalChain([t, 'optionalAccess', _940 => _940.overrideCheckpointLoad])||this.checkpointLoad;if(!n)return null;let o=Date.now(),r=!1,i=null;try{i=await n(e),r=i!==null}catch(a){throw r=!1,a}finally{let a=Date.now()-o;this.recordCheckpointMetrics("load",a,r,"unknown")}return i}restoreFromCheckpoint(e){this.currentRound=e.currentRound,this.scoreHistory=[...e.scoreHistory],this.configurationHistory=[...e.configurationHistory],this.stats={...e.stats}}shouldSaveCheckpoint(e,t){let n=_optionalChain([t, 'optionalAccess', _941 => _941.overrideCheckpointInterval])||this.checkpointInterval;return n!==void 0&&e%n===0}async updateOptimizationProgress(e,t,n,o,r,i,a,l={},p){this.currentRound=e,this.scoreHistory.push(t),this.configurationHistory.push(n),this.shouldSaveCheckpoint(e,p)&&await this.saveCheckpoint(o,r,i,a,l,p),_optionalChain([this, 'access', _942 => _942.getOptimizerLogger, 'call', _943 => _943(p), 'optionalCall', _944 => _944({name:"RoundProgress",value:{round:e,totalRounds:_nullishCoalesce(_optionalChain([p, 'optionalAccess', _945 => _945.maxIterations]), () => (0)),currentScore:t,bestScore:i,configuration:n}})])}async saveFinalCheckpoint(e,t,n,o,r={},i){_optionalChain([i, 'optionalAccess', _946 => _946.saveCheckpointOnComplete])!==!1&&await this.saveCheckpoint(e,t,n,o,{...r,final:!0},i)}getLogger(e){if(this.isLoggingEnabled(e))return this.logger?this.logger:this.studentAI.getLogger()}isLoggingEnabled(e){return _optionalChain([e, 'optionalAccess', _947 => _947.verbose])!==void 0?e.verbose:_nullishCoalesce(this.verbose, () => (!0))}recordOptimizationStart(e,t){if(this.metricsInstruments){if(t){let n=(t.match(/input:/g)||[]).length,o=(t.match(/output:/g)||[]).length;Pi(this.metricsInstruments,n,o,this.examples.length,this.getValidationSet().length,e)}Gi(this.metricsInstruments,e,this.targetScore,void 0)}}recordOptimizationComplete(e,t,n,o){if(!this.metricsInstruments)return;Ti(this.metricsInstruments,e,t,n,o),ki(this.metricsInstruments,e,n);let r=_nullishCoalesce(_optionalChain([this, 'access', _948 => _948.costTracker, 'optionalAccess', _949 => _949.getCurrentCost, 'call', _950 => _950()]), () => (0)),i=_nullishCoalesce(_optionalChain([this, 'access', _951 => _951.costTracker, 'optionalAccess', _952 => _952.getTotalTokens, 'call', _953 => _953()]), () => (0));Si(this.metricsInstruments,i,r,n)}recordConvergenceMetrics(e,t,n,o,r){this.metricsInstruments&&vi(this.metricsInstruments,e,t,n,o,r)}recordEarlyStoppingMetrics(e,t){this.metricsInstruments&&Oi(this.metricsInstruments,e,t)}recordTeacherStudentMetrics(e,t,n){this.metricsInstruments&&Ei(this.metricsInstruments,e,t,n)}recordCheckpointMetrics(e,t,n,o){this.metricsInstruments&&Mi(this.metricsInstruments,e,t,n,o)}recordParetoMetrics(e,t,n,o){this.metricsInstruments&&_i(this.metricsInstruments,e,t,n,o)}recordPerformanceMetrics(e,t,n){this.metricsInstruments&&Fi(this.metricsInstruments,e,t,n)}isOptimizerLoggingEnabled(e){return this.debugOptimizer||(_nullishCoalesce(_nullishCoalesce(_optionalChain([e, 'optionalAccess', _954 => _954.verbose]), () => (this.verbose)), () => (!1)))}getOptimizerLogger(e){if(this.isOptimizerLoggingEnabled(e))return _nullishCoalesce(this.optimizerLogger, () => (qn))}getStats(){return{...this.stats}}reset(){this.stats=this.initializeStats(),_optionalChain([this, 'access', _955 => _955.costTracker, 'optionalAccess', _956 => _956.reset, 'call', _957 => _957()]),this.currentRound=0,this.scoreHistory=[],this.configurationHistory=[]}}, _class36);var De= (_class37 =class extends oe{__init121() {this.traces=[]}constructor(e){super(e);_class37.prototype.__init121.call(this);;let t=e.options||{};this.maxRounds=_nullishCoalesce(t.maxRounds, () => (3)),this.maxDemos=_nullishCoalesce(t.maxDemos, () => (4)),this.maxExamples=_nullishCoalesce(t.maxExamples, () => (16)),this.batchSize=_nullishCoalesce(t.batchSize, () => (1)),this.earlyStoppingPatience=_nullishCoalesce(t.earlyStoppingPatience, () => (0)),this.costMonitoring=_nullishCoalesce(t.costMonitoring, () => (!1)),this.maxTokensPerGeneration=_nullishCoalesce(t.maxTokensPerGeneration, () => (0)),this.verboseMode=_nullishCoalesce(t.verboseMode, () => (!0)),this.debugMode=_nullishCoalesce(t.debugMode, () => (!1))}async compileRound(e,t,n,o){let r=Date.now(),i=_nullishCoalesce(_optionalChain([o, 'optionalAccess', _958 => _958.maxDemos]), () => (this.maxDemos)),a={modelConfig:{temperature:.7}};this.maxTokensPerGeneration>0&&(a.modelConfig.max_tokens=this.maxTokensPerGeneration);let l=Ui(this.examples,this.maxExamples),p=this.traces.length;for(let c=0;c<l.length;c+=this.batchSize){c>0&&(a.modelConfig.temperature=.7+.001*c);let d=l.slice(c,c+this.batchSize);for(let u of d){if(!u)continue;let m=l.filter(f=>f!==u);e.setExamples(m);let A=this.getTeacherOrStudentAI();this.stats.totalCalls++;let g;try{g=await e.forward(A,u,a),this.costMonitoring&&(this.stats.estimatedTokenUsage+=JSON.stringify(u).length/4+JSON.stringify(g).length/4),await n({prediction:g,example:u})>=.5&&(this.traces=[...this.traces,...e.getTraces()],this.stats.successfulDemos++)}catch (e9){g={}}if(this.traces.length>=i)return}}if(this.earlyStoppingPatience>0){let d=this.traces.length-p;if(!this.stats.earlyStopping)this.stats.earlyStopping={bestScoreRound:d>0?t:0,patienceExhausted:!1,reason:"No improvement detected"};else if(d>0)this.stats.earlyStopping.bestScoreRound=t;else if(t-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){let o=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _959 => _959.maxIterations]), () => (this.maxRounds));this.traces=[],this.reset();for(let a=0;a<o&&(await this.compileRound(e,a,t,n),!this.stats.earlyStopped);a++);if(this.traces.length===0)throw new Error("No demonstrations found. Either provide more examples or improve the existing ones.");let r=Di(this.traces),i=0;return this.traces.length>0&&(i=this.stats.successfulDemos/Math.max(1,this.stats.totalCalls)),{demos:r,stats:this.stats,bestScore:i,finalConfiguration:{maxRounds:this.maxRounds,maxDemos:this.maxDemos,batchSize:this.batchSize,successRate:i}}}}, _class37);function Di(s){let e=new Map;for(let n of s)if(e.has(n.programId)){let o=e.get(n.programId);o&&o.push(n.trace)}else e.set(n.programId,[n.trace]);let t=[];return e.forEach((n,o)=>{t.push({traces:n,programId:o})}),t}var Ui=(s,e)=>{let t=[...s];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1)),r=t[n],i=t[o];if(!r||!i)throw new Error("Invalid array elements");[t[n],t[o]]=[i,r]}return t.slice(0,e)};var zn= (_class38 =class extends oe{__init122() {this.miproConfigHistory=[]}__init123() {this.surrogateModel=new Map}constructor(e){super(e);_class38.prototype.__init122.call(this);_class38.prototype.__init123.call(this);;let t=e.options||{};this.numCandidates=_nullishCoalesce(t.numCandidates, () => (5)),this.initTemperature=_nullishCoalesce(t.initTemperature, () => (.7)),this.maxBootstrappedDemos=_nullishCoalesce(t.maxBootstrappedDemos, () => (3)),this.maxLabeledDemos=_nullishCoalesce(t.maxLabeledDemos, () => (4)),this.numTrials=_nullishCoalesce(t.numTrials, () => (30)),this.minibatch=_nullishCoalesce(t.minibatch, () => (!0)),this.minibatchSize=_nullishCoalesce(t.minibatchSize, () => (25)),this.minibatchFullEvalSteps=_nullishCoalesce(t.minibatchFullEvalSteps, () => (10)),this.programAwareProposer=_nullishCoalesce(t.programAwareProposer, () => (!0)),this.dataAwareProposer=_nullishCoalesce(t.dataAwareProposer, () => (!0)),this.viewDataBatchSize=_nullishCoalesce(t.viewDataBatchSize, () => (10)),this.tipAwareProposer=_nullishCoalesce(t.tipAwareProposer, () => (!0)),this.fewshotAwareProposer=_nullishCoalesce(t.fewshotAwareProposer, () => (!0)),this.earlyStoppingTrials=_nullishCoalesce(t.earlyStoppingTrials, () => (5)),this.minImprovementThreshold=_nullishCoalesce(t.minImprovementThreshold, () => (.01)),this.bayesianOptimization=_nullishCoalesce(t.bayesianOptimization, () => (!1)),this.acquisitionFunction=_nullishCoalesce(t.acquisitionFunction, () => ("expected_improvement")),this.explorationWeight=_nullishCoalesce(t.explorationWeight, () => (.1)),this.sampleCount=_nullishCoalesce(t.sampleCount, () => (1)),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}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 o=`
141
247
  Analyze this language model program and provide a concise summary of its purpose and structure.
142
248
 
143
249
  Program Signature: ${e.getSignature()}
@@ -147,7 +253,7 @@ Provide a 2-3 sentence summary focusing on:
147
253
  2. The input-output relationship
148
254
  3. Any special constraints or requirements
149
255
 
150
- Summary:`;try{let r=await t.chat({chatPrompt:[{role:"user",content:o}]});return"results"in r&&_optionalChain([r, 'access', _1019 => _1019.results, 'access', _1020 => _1020[0], 'optionalAccess', _1021 => _1021.content, 'optionalAccess', _1022 => _1022.trim, 'call', _1023 => _1023()])||"General language model program"}catch (e7){return"General language model program"}}async generateDatasetSummary(e,t){if(e.length===0)return"No examples available";let n=Math.min(this.viewDataBatchSize,e.length),i=`
256
+ Summary:`;try{let r=await t.chat({chatPrompt:[{role:"user",content:o}]});return"results"in r&&_optionalChain([r, 'access', _960 => _960.results, 'access', _961 => _961[0], 'optionalAccess', _962 => _962.content, 'optionalAccess', _963 => _963.trim, 'call', _964 => _964()])||"General language model program"}catch (e10){return"General language model program"}}async generateDatasetSummary(e,t){if(e.length===0)return"No examples available";let n=Math.min(this.viewDataBatchSize,e.length),i=`
151
257
  Analyze this dataset and provide a concise summary of its characteristics.
152
258
 
153
259
  Sample Examples:
@@ -159,7 +265,7 @@ Provide a 2-3 sentence summary focusing on:
159
265
  2. Common patterns or structures in the examples
160
266
  3. Key challenges or requirements for processing this data
161
267
 
162
- Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:i}]});return"results"in a&&_optionalChain([a, 'access', _1024 => _1024.results, 'access', _1025 => _1025[0], 'optionalAccess', _1026 => _1026.content, 'optionalAccess', _1027 => _1027.trim, 'call', _1028 => _1028()])||"General dataset"}catch (e8){return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:o,datasetSummary:r,previousInstructions:i=[]}){let a="";this.programAwareProposer&&o&&(a+=`
268
+ Dataset Summary:`;try{let a=await t.chat({chatPrompt:[{role:"user",content:i}]});return"results"in a&&_optionalChain([a, 'access', _965 => _965.results, 'access', _966 => _966[0], 'optionalAccess', _967 => _967.content, 'optionalAccess', _968 => _968.trim, 'call', _969 => _969()])||"General dataset"}catch (e11){return"General dataset"}}async generateInstruction({tip:e,candidateIndex:t,ai:n,programSummary:o,datasetSummary:r,previousInstructions:i=[]}){let a="";this.programAwareProposer&&o&&(a+=`
163
269
  Program Context: ${o}`),this.dataAwareProposer&&r&&(a+=`
164
270
  Dataset Context: ${r}`),this.fewshotAwareProposer&&i.length>0&&(a+=`
165
271
  Previous Instructions (avoid repeating): ${i.slice(-3).join("; ")}`);let l=`
@@ -177,8 +283,8 @@ Requirements:
177
283
  5. Keep it concise but comprehensive
178
284
 
179
285
  Generate a single, well-crafted instruction:
180
- Instruction:`;try{let d=await n.chat({chatPrompt:[{role:"user",content:l}]});if("results"in d){let u=_optionalChain([d, 'access', _1029 => _1029.results, 'access', _1030 => _1030[0], 'optionalAccess', _1031 => _1031.content, 'optionalAccess', _1032 => _1032.trim, 'call', _1033 => _1033()]);if(u&&u.length>10)return u}}catch(d){this.isLoggingEnabled()&&_optionalChain([this, 'access', _1034 => _1034.getLogger, 'call', _1035 => _1035(), 'optionalCall', _1036 => _1036(`Failed to generate AI instruction: ${d}`,{tags:["optimizer","warning"]})])}let p=["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."],c=p[t%p.length]||p[0];return e&&(c=`${c} ${e}`),c}async proposeInstructionCandidates(e,t){let n=[],o=this.getTeacherOrStudentAI(t),r,i;this.programAwareProposer&&(r=await this.generateProgramSummary(e,o),this.isLoggingEnabled(t)&&_optionalChain([this, 'access', _1037 => _1037.getLogger, 'call', _1038 => _1038(t), 'optionalCall', _1039 => _1039(`Program summary: ${r}`,{tags:["optimizer","config"]})])),this.dataAwareProposer&&(i=await this.generateDatasetSummary(this.examples,o),this.isLoggingEnabled(t)&&_optionalChain([this, 'access', _1040 => _1040.getLogger, 'call', _1041 => _1041(t), 'optionalCall', _1042 => _1042(`Dataset summary: ${i}`,{tags:["optimizer","config"]})]));let a=this.tipAwareProposer?this.generateTips():[];for(let l=0;l<this.numCandidates;l++){let p=a.length>0?l%a.length:-1,c=p>=0?a[p]:void 0,d=await this.generateInstruction({tip:c,candidateIndex:l,ai:o,programSummary:r,datasetSummary:i,previousInstructions:n});n.push(d)}return n}async bootstrapFewShotExamples(e,t){return this.isLoggingEnabled()&&_optionalChain([this, 'access', _1043 => _1043.getLogger, 'call', _1044 => _1044(), 'optionalCall', _1045 => _1045("Bootstrapping few-shot examples...",{tags:["optimizer","phase"]})]),(await new qe({studentAI:this.studentAI,examples:this.examples,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.isLoggingEnabled()}}).compile(e,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(){let e=[],t=new Set;for(;t.size<this.maxLabeledDemos&&t.size<this.examples.length;){let n=Math.floor(Math.random()*this.examples.length);if(!t.has(n)){t.add(n);let o=this.examples[n];o&&e.push(o)}}return e}async runOptimization(e,t,n,o,r,i,a){let l={instruction:o[0]||"",bootstrappedDemos:Math.min(1,t.length),labeledExamples:Math.min(1,n.length)},p=0,c=0,d=[],u=0;if(this.resumeFromCheckpoint){let m=await this.loadCheckpoint(this.resumeFromCheckpoint,a);m&&m.optimizerType==="MiPRO"&&(this.isLoggingEnabled(a)&&_optionalChain([this, 'access', _1046 => _1046.getLogger, 'call', _1047 => _1047(a), 'optionalCall', _1048 => _1048(`Resuming from checkpoint at round ${m.currentRound}`,{tags:["optimizer","checkpoint"]})]),this.restoreFromCheckpoint(m),u=m.currentRound,p=m.bestScore,l=m.bestConfiguration||l,c=_optionalChain([m, 'access', _1049 => _1049.stats, 'access', _1050 => _1050.convergenceInfo, 'optionalAccess', _1051 => _1051.stagnationRounds])||0)}this.isLoggingEnabled(a)&&_optionalChain([this, 'access', _1052 => _1052.getLogger, 'call', _1053 => _1053(a), 'optionalCall', _1054 => _1054(`Running optimization trials (${this.numTrials} total)`,{tags:["optimizer","phase"]})]);for(let m=u;m<this.numTrials;m++){let A;this.bayesianOptimization&&this.miproConfigHistory.length>2?A=await this.selectConfigurationViaBayesianOptimization(o,t,n):A={instruction:o[m%o.length]||o[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)};let g=await this.evaluateConfig(e,A,t,n,r,i,m+1);this.updateSurrogateModel(A,g),d.push(g);let f=g-p;if(f>this.minImprovementThreshold?(p=g,l=A,c=0,this.isLoggingEnabled(a)&&_optionalChain([this, 'access', _1055 => _1055.getLogger, 'call', _1056 => _1056(a), 'optionalCall', _1057 => _1057(`Trial ${m+1}/${this.numTrials}: New best score ${p.toFixed(3)}`,{tags:["optimizer","progress"]})])):c++,await this.updateOptimizationProgress(m+1,g,A,"MiPRO",this.getConfiguration(),p,l,{stagnationRounds:c,bootstrappedDemos:t.length,labeledExamples:n.length,instructions:o.length},a),this.onProgress&&this.onProgress({round:m+1,totalRounds:this.numTrials,currentScore:g,bestScore:p,tokensUsed:this.stats.resourceUsage.totalTokens,timeElapsed:Date.now(),successfulExamples:this.stats.successfulDemos,totalExamples:this.examples.length,currentConfiguration:A,convergenceInfo:{improvement:f,stagnationRounds:c,isConverging:c<this.earlyStoppingTrials}}),ue(m+1,this.numTrials,Math.round(p*100),0,"Running MIPROv2 optimization",30),this.checkCostLimits()){this.triggerEarlyStopping("Cost limit reached",m+1);break}if(c>=this.earlyStoppingTrials){this.triggerEarlyStopping(`No improvement for ${this.earlyStoppingTrials} trials`,m-c+1);break}if(this.checkTargetScore(p)){this.triggerEarlyStopping(`Target score ${this.targetScore} reached`,m+1);break}}return this.stats.convergenceInfo.stagnationRounds=c,this.stats.convergenceInfo.finalImprovement=d.length>1?p-d[0]:0,this.stats.convergenceInfo.converged=c<this.earlyStoppingTrials,{bestConfig:l,bestScore:p}}async evaluateConfig(e,t,n,o,r,i,a=0){let l={...e};this.applyConfigToProgram(l,t,n,o);let p=0,c=0,d;if(this.minibatch){let A=Math.min(this.minibatchSize,r.length);a%this.minibatchFullEvalSteps===0||a>this.numTrials*.8?d=Math.min(r.length,A*2):d=Math.max(3,Math.min(A,r.length))}else d=r.length;let m=this.shuffleArray([...Array(r.length).keys()]).slice(0,d).map(A=>r[A]);for(let A of m)try{let g=await l.forward(this.studentAI,A,this.sampleCount>1?{sampleCount:this.sampleCount,resultPicker:Ni()}:void 0),f=await i({prediction:g,example:A});p+=f,c++,this.stats.totalCalls++}catch (e9){}return c>0?p/c:0}shuffleArray(e){let t=[...e];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1));[t[n],t[o]]=[t[o],t[n]]}return t}applyConfigToProgram(e,t,n,o){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(o.slice(0,t.labeledExamples))}async compile(e,t,n){let o=Date.now();this.setupRandomSeed();let r=n;_optionalChain([r, 'optionalAccess', _1058 => _1058.auto])&&this.configureAuto(r.auto);let i=this.getValidationSet(n)||(_nullishCoalesce(_optionalChain([r, 'optionalAccess', _1059 => _1059.validationExamples]), () => (this.examples.slice(0,Math.floor(this.examples.length*.2)))));this.isLoggingEnabled(n)&&(_optionalChain([this, 'access', _1060 => _1060.getLogger, 'call', _1061 => _1061(n), 'optionalCall', _1062 => _1062(`Starting MIPROv2 optimization with ${this.numTrials} trials`,{tags:["optimizer","start"]})]),_optionalChain([this, 'access', _1063 => _1063.getLogger, 'call', _1064 => _1064(n), 'optionalCall', _1065 => _1065(`Using ${this.examples.length} examples for training and ${i.length} for validation`,{tags:["optimizer","config"]})]),this.teacherAI&&_optionalChain([this, 'access', _1066 => _1066.getLogger, 'call', _1067 => _1067(n), 'optionalCall', _1068 => _1068("Using separate teacher model for instruction generation",{tags:["optimizer","config"]})]));let a=[];this.maxBootstrappedDemos>0&&(a=await this.bootstrapFewShotExamples(e,t),this.isLoggingEnabled(n)&&_optionalChain([this, 'access', _1069 => _1069.getLogger, 'call', _1070 => _1070(n), 'optionalCall', _1071 => _1071(`Generated ${a.length} bootstrapped demonstrations`,{tags:["optimizer","result"]})]));let l=[];this.maxLabeledDemos>0&&(l=this.selectLabeledExamples(),this.isLoggingEnabled(n)&&_optionalChain([this, 'access', _1072 => _1072.getLogger, 'call', _1073 => _1073(n), 'optionalCall', _1074 => _1074(`Selected ${l.length} labeled examples from training set`,{tags:["optimizer","result"]})]));let p=await this.proposeInstructionCandidates(e,n);this.isLoggingEnabled(n)&&(_optionalChain([this, 'access', _1075 => _1075.getLogger, 'call', _1076 => _1076(n), 'optionalCall', _1077 => _1077(`Generated ${p.length} instruction candidates`,{tags:["optimizer","result"]})]),this.hasTeacherAI(n)&&_optionalChain([this, 'access', _1078 => _1078.getLogger, 'call', _1079 => _1079(n), 'optionalCall', _1080 => _1080("Using teacher AI for instruction generation",{tags:["optimizer","config"]})]));let{bestConfig:c,bestScore:d}=await this.runOptimization(e,a,l,p,i,t,n);this.isLoggingEnabled(n)&&(_optionalChain([this, 'access', _1081 => _1081.getLogger, 'call', _1082 => _1082(n), 'optionalCall', _1083 => _1083(`Optimization complete. Best score: ${d}`,{tags:["optimizer","complete"]})]),_optionalChain([this, 'access', _1084 => _1084.getLogger, 'call', _1085 => _1085(n), 'optionalCall', _1086 => _1086(`Best configuration: ${JSON.stringify(c)}`,{tags:["optimizer","result"]})])),this.checkTargetScore(d)&&this.triggerEarlyStopping(`Target score ${this.targetScore} reached with score ${d}`,this.numTrials);let u;"getSignature"in e&&typeof e.getSignature=="function"?u=e.getSignature():u="input -> output";let m=new S(u);return this.applyConfigToAxGen(m,c,a,l),this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.stats.convergenceInfo.finalImprovement=d,await this.saveFinalCheckpoint("MiPRO",this.getConfiguration(),d,c,{bootstrappedDemos:a.length,labeledExamples:l.length,instructions:p.length,optimizedGen:!!m},n),{demos:a,stats:this.stats,bestScore:d,optimizedGen:m,finalConfiguration:{instruction:c.instruction,bootstrappedDemos:c.bootstrappedDemos,labeledExamples:c.labeledExamples,numCandidates:this.numCandidates,numTrials:this.numTrials,sampleCount:this.sampleCount}}}applyConfigToAxGen(e,t,n,o){"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(o.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.miproConfigHistory=[],this.surrogateModel.clear(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=super.validateProgram(e);return this.examples.length<this.maxBootstrappedDemos+this.maxLabeledDemos&&(t.issues.push(`Not enough examples: need at least ${this.maxBootstrappedDemos+this.maxLabeledDemos}, got ${this.examples.length}`),t.suggestions.push("Reduce maxBootstrappedDemos or maxLabeledDemos, or provide more examples")),this.getValidationSet().length<5&&(t.issues.push("Validation set too small for reliable MiPRO optimization"),t.suggestions.push("Provide more examples or a larger validation set")),{isValid:t.issues.length===0,issues:t.issues,suggestions:t.suggestions}}encodeConfiguration(e){return`${e.instruction.length}_${e.bootstrappedDemos}_${e.labeledExamples}`}updateSurrogateModel(e,t){this.miproConfigHistory.push({config:{...e},score:t});let n=this.encodeConfiguration(e),o=this.miproConfigHistory.filter(r=>this.encodeConfiguration(r.config)===n);if(o.length>0){let r=o.map(l=>l.score),i=r.reduce((l,p)=>l+p,0)/r.length,a=r.length>1?r.reduce((l,p)=>l+(p-i)**2,0)/(r.length-1):.1;this.surrogateModel.set(n,{mean:i,variance:a})}}predictPerformance(e){let t=this.encodeConfiguration(e);if(this.surrogateModel.has(t))return this.surrogateModel.get(t);if(this.miproConfigHistory.length>0){let n=this.miproConfigHistory.map(i=>{let a=Math.abs(i.config.bootstrappedDemos-e.bootstrappedDemos)+Math.abs(i.config.labeledExamples-e.labeledExamples);return{score:i.score,similarity:1/(1+a)}}),o=n.reduce((i,a)=>i+a.similarity,0);return{mean:n.reduce((i,a)=>i+a.score*a.similarity,0)/o,variance:.2}}return{mean:.5,variance:.3}}calculateAcquisitionValue(e){let t=this.predictPerformance(e),{mean:n,variance:o}=t,r=Math.sqrt(o),i=this.miproConfigHistory.length>0?Math.max(...this.miproConfigHistory.map(a=>a.score)):0;switch(this.acquisitionFunction){case"expected_improvement":{let a=n-i;if(r===0)return Math.max(0,a);let l=a/r,p=.5*(1+this.erf(l/Math.sqrt(2))),c=Math.exp(-.5*l*l)/Math.sqrt(2*Math.PI);return a*p+r*c}case"upper_confidence_bound":return n+this.explorationWeight*r;case"probability_improvement":{let a=n-i;if(r===0)return a>0?1:0;let l=a/r;return .5*(1+this.erf(l/Math.sqrt(2)))}default:return n}}erf(e){let t=.254829592,n=-.284496736,o=1.421413741,r=-1.453152027,i=1.061405429,a=.3275911,l=e>=0?1:-1,p=Math.abs(e),c=1/(1+a*p),d=1-((((i*c+r)*c+o)*c+n)*c+t)*c*Math.exp(-p*p);return l*d}async selectConfigurationViaBayesianOptimization(e,t,n){let o=[],r=Math.min(20,e.length*3);for(let i=0;i<r;i++){let a={instruction:e[i%e.length]||e[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)},l=this.calculateAcquisitionValue(a);o.push({config:a,acquisitionValue:l})}return o.sort((i,a)=>a.acquisitionValue-i.acquisitionValue),o[0].config}}, _class38),Ni=()=>async s=>{if(s.type==="fields"){let e={};for(let{index:o,sample:r}of s.results){let i=JSON.stringify(r);e[i]||(e[i]={count:0,index:o}),e[i].count+=1}let t,n=-1;for(let[o,r]of Object.entries(e))r.count>n&&(n=r.count,t=o);return _nullishCoalesce(_optionalChain([e, 'access', _1087 => _1087[t], 'optionalAccess', _1088 => _1088.index]), () => (0))}return _nullishCoalesce(_optionalChain([s, 'access', _1089 => _1089.results, 'access', _1090 => _1090[0], 'optionalAccess', _1091 => _1091.index]), () => (0))};function Li(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=_nullishCoalesce(s[n], () => ("")),n<e.length){let o=e[n];if(Yn(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let c=r[1];o.isOptional&&(c+="?"),o.isInternal&&(c+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${c}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=Ct(l)}else if(Kn(o))t+=Jn(o);else if(typeof o=="string"||o instanceof P)t+=qr(o);else throw new Error("Unsupported template interpolation value")}return new P(t)}function Bi(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=_nullishCoalesce(s[n], () => ("")),n<e.length){let o=e[n];if(Yn(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let c=r[1];o.isOptional&&(c+="?"),o.isInternal&&(c+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${c}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=Ct(l)}else if(Kn(o))t+=Jn(o);else if(typeof o=="string"||o instanceof P)t+=qr(o);else throw new Error("Unsupported template interpolation value")}return new S(t)}function qr(s){if(typeof s=="string")return s;if(Yn(s))return Ct(s);if(Kn(s))return Jn(s);if(s instanceof P){let e=s.toString(),t=e.indexOf(" -> ");return t!==-1?e.substring(t+4):e}throw new Error(`Unsupported template value type: ${typeof s}`)}function Ct(s){let e=s.type;return s.isArray&&(e+="[]"),s.options&&s.options.length>0&&s.type==="class"&&(e+=` "${s.options.join(", ")}"`),s.description&&(e+=` "${s.description}"`),e}function Jn(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${Ct(s.type)}`),s.description&&!_optionalChain([s, 'access', _1092 => _1092.type, 'optionalAccess', _1093 => _1093.description])&&(e+=` "${s.description}"`),e}function Yn(s){return s!==null&&typeof s=="object"&&s!==void 0&&"type"in s&&typeof s.type=="string"}function Kn(s){return s!==null&&typeof s=="object"&&s!==void 0&&"name"in s&&typeof s.name=="string"}var $i={string:s=>({type:"string",description:s}),number:s=>({type:"number",description:s}),boolean:s=>({type:"boolean",description:s}),date:s=>({type:"date",description:s}),datetime:s=>({type:"datetime",description:s}),json:s=>({type:"json",description:s}),image:s=>({type:"image",description:s}),audio:s=>({type:"audio",description:s}),class:(s,e)=>({type:"class",options:s,description:e}),code:(s,e)=>({type:"code",options:[s],description:e}),array:s=>({...s,isArray:!0}),optional:s=>({...s,isOptional:!0}),internal:s=>({...s,isInternal:!0})};var Qn=class{analyzeMappingDependencies(e,t){let n=[],o=e.toString(),r=Array.from(o.matchAll(/state\.(\w+)/g));for(let i of r)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch (e10){}return n}createDependencyTracker(e){return new Proxy({},{get(t,n){return typeof n=="string"&&!e.includes(n)&&e.push(n),new Proxy({},{get:()=>{}})}})}},Xn= (_class39 =class{constructor() { _class39.prototype.__init116.call(this);_class39.prototype.__init117.call(this);_class39.prototype.__init118.call(this);_class39.prototype.__init119.call(this); }__init116() {this.steps=[]}__init117() {this.parallelGroups=[]}__init118() {this.analyzer=new Qn}__init119() {this.initialFields=new Set}addExecutionStep(e,t,n){let o=[],r=[],i="other";t&&n?(i="execute",o=this.analyzer.analyzeMappingDependencies(n,t),r=[`${t}Result`]):e.toString().includes("transform(")&&(i="map",o=this.getAllProducedFields());let a={type:i,nodeName:t,dependencies:o,produces:r,stepFunction:e,stepIndex:this.steps.length};this.steps.push(a)}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 o=[];for(let r of this.steps){if(e.has(r.stepIndex))continue;(r.dependencies.length===0||r.dependencies.every(a=>t.has(a)))&&(o.push(r),e.add(r.stepIndex))}if(o.length>0){for(let r of o)r.produces.forEach(i=>t.add(i));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(){let e=[];for(let t of this.parallelGroups)if(t.steps.length===1){let n=t.steps[0];n&&e.push(n.stepFunction)}else if(t.steps.length>1){let n=async(o,r)=>{let i=t.steps.map(p=>p.stepFunction(o,r)),a=await Promise.all(i),l=o;for(let p of a)l={...l,...p};return l};e.push(n)}return e}getExecutionPlan(){return{totalSteps:this.steps.length,parallelGroups:this.parallelGroups.length,maxParallelism:Math.max(...this.parallelGroups.map(e=>e.steps.length),0),steps:this.steps,groups:this.parallelGroups}}}, _class39),Zn= exports.AxFlow = (_class40 =class extends ee{__init120() {this.nodes=new Map}__init121() {this.flowDefinition=[]}__init122() {this.nodeGenerators=new Map}__init123() {this.loopStack=[]}__init124() {this.stepLabels=new Map}__init125() {this.branchContext=null}__init126() {this.executionPlanner=new Xn}constructor(e="userInput:string -> flowOutput:string",t){super(e);_class40.prototype.__init120.call(this);_class40.prototype.__init121.call(this);_class40.prototype.__init122.call(this);_class40.prototype.__init123.call(this);_class40.prototype.__init124.call(this);_class40.prototype.__init125.call(this);_class40.prototype.__init126.call(this);,this.autoParallelConfig={enabled:_optionalChain([t, 'optionalAccess', _1094 => _1094.autoParallel])!==!1}}node(e,t,n){if(t instanceof S)this.nodes.set(e,{inputs:{},outputs:{}}),this.nodeGenerators.set(e,t);else if(t instanceof P)this.nodes.set(e,{inputs:{},outputs:{}}),this.nodeGenerators.set(e,new S(t,n));else if(typeof t=="function"&&t.prototype instanceof ee){this.nodes.set(e,{inputs:{},outputs:{}});let o=new t;this.nodeGenerators.set(e,o)}else if(typeof t=="string"){let o=t;if(!o)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}}),this.nodeGenerators.set(e,new S(o,n))}else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxGen instance, or class extending AxProgram`);return this}n(e,t,n){return this.node(e,t,n)}map(e){let t=n=>e(n);if(_optionalChain([this, 'access', _1095 => _1095.branchContext, 'optionalAccess', _1096 => _1096.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);return this}m(e){return this.map(e)}label(e){if(_optionalChain([this, 'access', _1097 => _1097.branchContext, 'optionalAccess', _1098 => _1098.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 o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);let r=async(i,a)=>{let l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1099 => _1099.ai]), () => (a.mainAi)),p=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1100 => _1100.options]), () => (a.mainOptions)),c=t(i),d=_optionalChain([p, 'optionalAccess', _1101 => _1101.traceLabel])?`Node:${e} (${p.traceLabel})`:`Node:${e}`,u=await o.forward(l,c,{...p,traceLabel:d});return{...i,[`${e}Result`]:u}};if(_optionalChain([this, 'access', _1102 => _1102.branchContext, 'optionalAccess', _1103 => _1103.currentBranchValue])!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,e,t);return this}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;return this.branchContext=null,this.flowDefinition.push(async(t,n)=>{let o=e.predicate(t),r=e.branches.get(o);if(!r)return t;let i=t;for(let a of r)i=await a(i,n);return i}),this}mg(){return this.merge()}parallel(e){let t=async(n,o)=>{let r=e.map(async a=>{let l=new eo(this.nodeGenerators);return await a(l).executeSteps(n,o)}),i=await Promise.all(r);return{...n,_parallelResults:i}};return this.flowDefinition.push(t),{merge:(n,o)=>(this.flowDefinition.push(r=>{let i=r._parallelResults;if(!Array.isArray(i))throw new Error("No parallel results found for merge");let a=o(...i),l={...r};return l._parallelResults=void 0,l[n]=a,l}),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 o=this.stepLabels.get(t),r=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,p=1,c=`_feedback_${t}_iterations`;for(typeof l[c]!="number"&&(l={...l,[c]:1});e(l)&&p<n;){p++,l={...l,[c]:p};for(let d=o;d<r;d++){let u=this.flowDefinition[d];u&&(l=await u(l,a))}}return l}),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 o=Object.assign(r=>r,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(o),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,o=t._maxIterations,r=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,p=0;for(;n(l)&&p<o;){p++;for(let c of r)l=await c(l,a)}if(p>=o&&n(l))throw new Error(`While loop exceeded maximum iterations (${o}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this}end(){return this.endWhile()}async forward(e,t,n){let o={...t},r={mainAi:e,mainOptions:n};if(_optionalChain([n, 'optionalAccess', _1104 => _1104.autoParallel])!==!1&&this.autoParallelConfig.enabled){this.executionPlanner.setInitialFields(Object.keys(t));let a=this.executionPlanner.createOptimizedExecution();for(let l of a)o=await l(o,r)}else for(let a of this.flowDefinition)o=await a(o,r);return o}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}}}, _class40),eo= (_class41 =class{constructor(e){;_class41.prototype.__init127.call(this);this.nodeGenerators=e}__init127() {this.steps=[]}execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1105 => _1105.ai]), () => (i.mainAi)),l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1106 => _1106.options]), () => (i.mainOptions)),p=t(r),c=_optionalChain([l, 'optionalAccess', _1107 => _1107.traceLabel])?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d=await o.forward(a,p,{...l,traceLabel:c});return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}}, _class41),to= exports.AxFlowTypedSubContextImpl = (_class42 =class{constructor(e){;_class42.prototype.__init128.call(this);this.nodeGenerators=e}__init128() {this.steps=[]}execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1108 => _1108.ai]), () => (i.mainAi)),l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1109 => _1109.options]), () => (i.mainOptions)),p=t(r),c=_optionalChain([l, 'optionalAccess', _1110 => _1110.traceLabel])?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d=await o.forward(a,p,{...l,traceLabel:c});return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}}, _class42);var no= (_class43 =class{__init129() {this.containerId=null}constructor(e="http://localhost:2375"){;_class43.prototype.__init129.call(this);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:o}){let r=t.map(p=>`${p.hostPath}:${p.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:r},Labels:{}};o&&(i.Labels["com.example.tag"]=o);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});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:o}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===o);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),p=i[l];if(p)return await this.connectToContainer(p.Id),{Id:p.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:o})).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 o=[],r=await this.listContainers(!0),i=e?r.filter(a=>a.Labels["com.example.tag"]===e):r;for(let a of i){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}o.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}o.push({Id:a.Id,Action:"removed"})}}return o}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(console.log("Executing command:",e),!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 o=await n.json(),r=await this.fetchDockerAPI(`/exec/${o.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!r.ok)throw new Error(`Failed to start exec instance: ${r.statusText}`);return await r.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(r=>setTimeout(r,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)}}}, _class43);var oo=class{constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let o=(await this.aiService.embed({texts:[e]},{sessionId:_optionalChain([t, 'optionalAccess', _1111 => _1111.sessionId]),abortSignal:_optionalChain([t, 'optionalAccess', _1112 => _1112.abortSignal])})).embeddings.at(0);if(!o)throw new Error("Failed to embed text");return this.func.length===2?this.func(o,t):this.func(o)}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 ro= (_class44 =class{constructor(e,t={}){;_class44.prototype.__init130.call(this);_class44.prototype.__init131.call(this);_class44.prototype.__init132.call(this);this.transport=e;this.options=t;this.logger=_nullishCoalesce(t.logger, () => ((n=>console.log(n))))}__init130() {this.functions=[]}__init131() {this.activeRequests=new Map}__init132() {this.capabilities={}}async init(){"connect"in this.transport&&await _optionalChain([this, 'access', _1113 => _1113.transport, 'access', _1114 => _1114.connect, 'optionalCall', _1115 => _1115()]);let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");if(this.functions=e.tools.map(t=>{let n=_optionalChain([this, 'access', _1116 => _1116.options, 'access', _1117 => _1117.functionOverrides, 'optionalAccess', _1118 => _1118.find, 'call', _1119 => _1119(r=>r.name===t.name)]),o=t.inputSchema.properties?{properties:t.inputSchema.properties,required:_nullishCoalesce(t.inputSchema.required, () => ([])),type:t.inputSchema.type}:void 0;return{name:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1120 => _1120.updates, 'access', _1121 => _1121.name]), () => (t.name)),description:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1122 => _1122.updates, 'access', _1123 => _1123.description]), () => (t.description)),parameters:o,func:async r=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:r});return i}}}),this.options.debug){this.logger(`> Discovered ${this.functions.length} functions:`,{tags:["discovery"]});for(let t of this.functions)this.logger(` - ${t.name}: ${t.description}`,{tags:["discovery"]})}}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),o=await Promise.race([t,n]),{result:r}=o;if(typeof r!="object"||r===null||Object.keys(r).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(r)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=B(),o={jsonrpc:"2.0",id:n,method:e,params:t},r=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(o).then(p=>{if(this.activeRequests.delete(n),p!==null&&typeof p=="object"&&"error"in p){let c=p;l(new Error(`RPC Error ${c.error.code}: ${c.error.message}`))}else p!==null&&typeof p=="object"&&"result"in p?a({result:p.result}):l(new Error("Invalid response no result or error"))}).catch(p=>{this.activeRequests.delete(n),l(p)})}),{result:i}=await r;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t};this.options.debug&&this.logger(`\u27A1\uFE0F Sending notification: ${JSON.stringify(n,null,2)}`,{tags:["requestStart"]}),await this.transport.sendNotification(n)}}, _class44);var so= (_class45 =class{__init133() {this.endpoint=null}constructor(e){;_class45.prototype.__init133.call(this);this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let r=JSON.parse(n.data);if(!r.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=r.uri,e()}catch(o){t(o)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}, _class45),io= exports.AxMCPStreambleHTTPTransport = (_class46 =class{__init134() {this.pendingRequests=new Map}constructor(e,t){;_class46.prototype.__init134.call(this);this.mcpEndpoint=e,this.customHeaders={..._optionalChain([t, 'optionalAccess', _1124 => _1124.headers])},_optionalChain([t, 'optionalAccess', _1125 => _1125.authorization])&&(this.customHeaders.Authorization=t.authorization)}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"}),o=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(o.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=r=>{try{let i=JSON.parse(r.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},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.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(),o=new TextDecoder,r="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}r+=o.decode(l,{stream:!0});let p=r.split(`
181
- `);r=p.pop()||"";for(let c of p)if(c.startsWith("data: ")){let d=c.slice(6);if(d==="[DONE]")return;try{let u=JSON.parse(d);this.messageHandler&&this.messageHandler(u)}catch(u){console.error("Failed to parse SSE data:",u)}}await i()}catch(a){throw n.releaseLock(),a}};await i()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);let o=n.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let r=n.headers.get("Content-Type");if(_optionalChain([r, 'optionalAccess', _1126 => _1126.includes, 'call', _1127 => _1127("text/event-stream")]))return this.handleSSEResponse(n,e.id);if(_optionalChain([r, 'optionalAccess', _1128 => _1128.includes, 'call', _1129 => _1129("application/json")]))return n.json();throw new Error(`Unexpected content type: ${r}`)}async handleSSEResponse(e,t){return new Promise((n,o)=>{let r=_optionalChain([e, 'access', _1130 => _1130.body, 'optionalAccess', _1131 => _1131.getReader, 'call', _1132 => _1132()]);if(!r){o(new Error("No response body reader available"));return}let i=new TextDecoder,a="",l=async()=>{try{let{done:p,value:c}=await r.read();if(p){r.releaseLock();return}a+=i.decode(c,{stream:!0});let d=a.split(`
182
- `);a=d.pop()||"";for(let u of d)if(u.startsWith("data: ")){let m=u.slice(6);if(m==="[DONE]")return;try{let A=JSON.parse(m);if("id"in A&&A.id===t){n(A);return}this.messageHandler&&this.messageHandler(A)}catch(A){console.error("Failed to parse SSE data:",A)}}await l()}catch(p){r.releaseLock(),o(p)}};l().catch(o)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);n.status!==202&&console.warn(`Unexpected status for notification: ${n.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)}}, _class46);function qi(s,e,t,n,o){let r={...s};if(r.parameters){let i=r.parameters.properties?Object.keys(r.parameters.properties):[],l=t.filter(p=>i.includes(p)).filter(p=>p!=="model").filter(p=>!o.excludeFieldsFromPassthrough.includes(p));if(l.length>0){r.parameters=ji(r.parameters,l);let p=r.func;r.func=async(c,d)=>{let u={};if(Array.isArray(e)){let A=e.filter(g=>g.role==="user").pop();A&&(u=Hr(A.values,l))}else u=Hr(e,l);let m={...c,...u};if(o.debug&&l.length>0){let A=_optionalChain([d, 'optionalAccess', _1133 => _1133.ai]);A&&A.getLogger()(`Function Params: ${JSON.stringify(m,null,2)}`,{tags:["functionArg"]})}return await p(m,d)}}return r}return n&&!o.disableSmartModelRouting&&o.canConfigureSmartModelRouting&&(r.parameters=Vr(r.parameters,n)),r}var zr=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),jr=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),ao= exports.AxAgent =class{constructor({ai:e,name:t,description:n,definition:o,signature:r,agents:i,functions:a},l){let{disableSmartModelRouting:p,excludeFieldsFromPassthrough:c,debug:d}=_nullishCoalesce(l, () => ({}));if(this.ai=e,this.agents=i,this.functions=a,this.disableSmartModelRouting=p,this.excludeFieldsFromPassthrough=_nullishCoalesce(c, () => ([])),this.debug=d,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw zr;if(o&&o.length<100)throw jr;this.program=new S(r,{...l,description:_nullishCoalesce(o, () => (n))});for(let m of _nullishCoalesce(i, () => ([])))this.program.register(m);this.name=t,this.func={name:zi(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let u=_optionalChain([e, 'optionalAccess', _1134 => _1134.getModelList, 'call', _1135 => _1135()]);u&&!this.disableSmartModelRouting&&(this.func.parameters=Vr(this.func.parameters,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,o)=>{let{model:r,...i}=n,a=_nullishCoalesce(this.ai, () => (_optionalChain([o, 'optionalAccess', _1136 => _1136.ai])));if(!a)throw new Error("AI service is required to run the agent");let l=this.getDebug(a,o);l&&a.getLogger()(`\u{1F916} Agent ${this.name} starting...`,{tags:["start"]});let p=await e(a,i,{...o,model:r});l&&a.getLogger()(`\u{1F916} Agent ${this.name} completed.`,{tags:["end"]});let d=this.program.getSignature().getOutputFields();return Object.keys(p).map(m=>{let A=d.find(g=>g.name===m);return A?`${A.title}: ${p[m]}`:`${m}: ${p[m]}`}).join(`
183
- `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let o=_nullishCoalesce(this.ai, () => (e)),r=_optionalChain([o, 'optionalAccess', _1137 => _1137.getModelList, 'call', _1138 => _1138()]),a=this.program.getSignature().getInputFields().map(d=>d.name),l=this.getDebug(o,n),p=_optionalChain([this, 'access', _1139 => _1139.agents, 'optionalAccess', _1140 => _1140.map, 'call', _1141 => _1141(d=>{let u=d.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:u.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:u.canConfigureSmartModelRouting};return qi(d.getFunction(),t,a,r,m)})]),c=[..._nullishCoalesce(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1142 => _1142.functions]), () => (this.functions)), () => ([])),..._nullishCoalesce(p, () => ([]))];return{ai:o,functions:c,debug:l}}async forward(e,t,n){let{ai:o,functions:r,debug:i}=this.init(e,t,n);return await this.program.forward(o,t,{...n,debug:i,functions:r})}async*streamingForward(e,t,n){let{ai:o,functions:r,debug:i}=this.init(e,t,n);return yield*this.program.streamingForward(o,t,{...n,debug:i,functions:r})}setDescription(e){if(!e||e.length<20)throw zr;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw jr;this.program.getSignature().setDescription(e)}getDebug(e,t){return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _1143 => _1143.debug]), () => (this.debug)), () => (_optionalChain([e, 'optionalAccess', _1144 => _1144.getOptions, 'call', _1145 => _1145(), 'optionalAccess', _1146 => _1146.debug]))), () => (!1))}};function zi(s){return s.split(/[^a-zA-Z0-9]/).map((n,o)=>{let r=n.toLowerCase();return o>0&&r&&r[0]?r[0].toUpperCase()+r.slice(1):r}).join("")}function Vr(s,e){let t=s?structuredClone(s):{type:"object",properties:{},required:[]};if(_optionalChain([t, 'access', _1147 => _1147.properties, 'optionalAccess', _1148 => _1148.model]))return t;let n={type:"string",enum:e.map(i=>i.key),description:`The AI model to use for this function call. Available options: ${e.map(i=>`\`${i.key}\` ${i.description}`).join(", ")}`},o={..._nullishCoalesce(t.properties, () => ({})),model:n},r=[..._nullishCoalesce(t.required, () => ([])),"model"];return{...t,properties:o,required:r}}function ji(s,e){let t=structuredClone(s);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(o=>!e.includes(o));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Hr(s,e){let t={};for(let n of e)n in s&&(t[n]=s[n]);return t}var ze=class extends S{constructor(e,t){let n=new P(e);n.setOutputFields([{name:"reason",description:"Let's work this out in a step by step way in order to ensure we have the right answer.",isInternal:_optionalChain([t, 'optionalAccess', _1149 => _1149.setVisibleReasoning])!==!0},...n.getOutputFields()]),super(n,t)}};var lo=class extends ze{constructor(e,t){super('"Answer questions with short factoid answers." context:string[] "may contain relevant facts", question -> answer',t),this.maxHops=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _1150 => _1150.maxHops]), () => (3));let o=new P('"Write a simple search query that will help answer a complex question." context?:string[] "may contain relevant facts", question -> query "question to further our understanding"');this.genQuery=new S(o),this.queryFn=e}async forward(e,t,n){let o;if(Array.isArray(t)){let l=t.filter(p=>p.role==="user").pop();if(!l)throw new Error("No user message found in values array");o=l.values.question}else o=t.question;let r=0,i=[];for(;r<this.maxHops;){let l=await this.genQuery.forward(e,{context:i,question:o}),p=await this.queryFn(l.query);i=$e.dedup([...i,p]),r++}return await super.forward(e,{context:i,question:o},n)}};exports.AxAI = gn; exports.AxAIAnthropic = he; exports.AxAIAnthropicModel = Ye; exports.AxAIAnthropicVertexModel = Ut; exports.AxAIAzureOpenAI = be; exports.AxAICohere = Re; exports.AxAICohereEmbedModel = Ze; exports.AxAICohereModel = Xe; exports.AxAIDeepSeek = Ce; exports.AxAIDeepSeekModel = et; exports.AxAIGoogleGemini = Te; exports.AxAIGoogleGeminiEmbedModel = Jt; exports.AxAIGoogleGeminiEmbedTypes = Wo; exports.AxAIGoogleGeminiModel = tt; exports.AxAIGoogleGeminiSafetyCategory = Yt; exports.AxAIGoogleGeminiSafetyThreshold = Kt; exports.AxAIGrok = hn; exports.AxAIGrokEmbedModels = tr; exports.AxAIGrokModel = lt; exports.AxAIGroq = ve; exports.AxAIGroqModel = nt; exports.AxAIHuggingFace = Oe; exports.AxAIHuggingFaceModel = tn; exports.AxAIMistral = Se; exports.AxAIMistralEmbedModels = Qo; exports.AxAIMistralModel = ot; exports.AxAIOllama = ke; exports.AxAIOpenAI = Ie; exports.AxAIOpenAIBase = M; exports.AxAIOpenAIEmbedModel = xe; exports.AxAIOpenAIModel = Qe; exports.AxAIOpenAIResponses = Ee; exports.AxAIOpenAIResponsesBase = rt; exports.AxAIOpenAIResponsesImpl = Me; exports.AxAIOpenAIResponsesModel = fe; exports.AxAIRefusalError = v; exports.AxAIReka = Pe; exports.AxAIRekaModel = it; exports.AxAIServiceAbortedError = me; exports.AxAIServiceAuthenticationError = ne; exports.AxAIServiceError = U; exports.AxAIServiceNetworkError = X; exports.AxAIServiceResponseError = Q; exports.AxAIServiceStatusError = le; exports.AxAIServiceStreamTerminatedError = Y; exports.AxAIServiceTimeoutError = pe; exports.AxAITogether = _e; exports.AxAgent = ao; exports.AxApacheTika = qn; exports.AxAssertionError = re; exports.AxBalancer = jt; exports.AxBaseAI = E; exports.AxBaseOptimizer = ae; exports.AxBootstrapFewShot = qe; exports.AxChainOfThought = ze; exports.AxDB = In; exports.AxDBBase = $; exports.AxDBCloudflare = Fe; exports.AxDBManager = Rn; exports.AxDBMemory = oe; exports.AxDBPinecone = Ge; exports.AxDBWeaviate = De; exports.AxDefaultCostTracker = Rt; exports.AxDefaultResultReranker = $n; exports.AxDockerSession = no; exports.AxEmbeddingAdapter = oo; exports.AxEvalUtil = Ii; exports.AxFlow = Zn; exports.AxFlowTypedSubContextImpl = to; exports.AxFunctionError = ct; exports.AxFunctionProcessor = dt; exports.AxGen = S; exports.AxGenerateError = yt; exports.AxHFDataLoader = Vn; exports.AxInstanceRegistry = Be; exports.AxLLMRequestTypeValues = Ao; exports.AxMCPClient = ro; exports.AxMCPHTTPSSETransport = so; exports.AxMCPStreambleHTTPTransport = io; exports.AxMemory = Ne; exports.AxMiPRO = Wn; exports.AxMockAIService = sn; exports.AxMultiServiceRouter = an; exports.AxProgram = ee; exports.AxPromptTemplate = de; exports.AxRAG = lo; exports.AxRateLimiterTokenUsage = we; exports.AxSignature = P; exports.AxSimpleClassifier = jn; exports.AxSimpleClassifierClass = zn; exports.AxSpanKindValues = ho; exports.AxStringUtil = $e; exports.AxTestPrompt = Hn; exports.ax = Bi; exports.axAIAnthropicDefaultConfig = $o; exports.axAIAnthropicVertexDefaultConfig = rs; exports.axAIAzureOpenAIBestConfig = us; exports.axAIAzureOpenAICreativeConfig = ps; exports.axAIAzureOpenAIDefaultConfig = zo; exports.axAIAzureOpenAIFastConfig = cs; exports.axAICohereCreativeConfig = ms; exports.axAICohereDefaultConfig = Ho; exports.axAIDeepSeekCodeConfig = As; exports.axAIDeepSeekDefaultConfig = Vo; exports.axAIGoogleGeminiDefaultConfig = Yo; exports.axAIGoogleGeminiDefaultCreativeConfig = hs; exports.axAIGrokBestConfig = ks; exports.axAIGrokDefaultConfig = xn; exports.axAIHuggingFaceCreativeConfig = ys; exports.axAIHuggingFaceDefaultConfig = Ko; exports.axAIMistralBestConfig = Is; exports.axAIMistralDefaultConfig = rn; exports.axAIOllamaDefaultConfig = Xo; exports.axAIOllamaDefaultCreativeConfig = bs; exports.axAIOpenAIBestConfig = $t; exports.axAIOpenAICreativeConfig = qt; exports.axAIOpenAIDefaultConfig = ce; exports.axAIOpenAIFastConfig = zt; exports.axAIOpenAIResponsesBestConfig = Cs; exports.axAIOpenAIResponsesCreativeConfig = Ts; exports.axAIOpenAIResponsesDefaultConfig = st; exports.axAIRekaBestConfig = ws; exports.axAIRekaCreativeConfig = vs; exports.axAIRekaDefaultConfig = at; exports.axAIRekaFastConfig = Os; exports.axAITogetherDefaultConfig = er; exports.axBaseAIDefaultConfig = w; exports.axBaseAIDefaultCreativeConfig = F; exports.axCheckMetricsHealth = Us; exports.axCreateDefaultColorLogger = St; exports.axCreateDefaultTextLogger = Zr; exports.axCreateOptimizerLogger = fo; exports.axDefaultMetricsConfig = sr; exports.axDefaultOptimizerLogger = kt; exports.axDefaultOptimizerMetricsConfig = $r; exports.axGetMetricsConfig = Bs; exports.axGetOptimizerMetricsConfig = Ci; exports.axGlobals = k; exports.axModelInfoAnthropic = Ke; exports.axModelInfoCohere = Ht; exports.axModelInfoDeepSeek = Wt; exports.axModelInfoGoogleGemini = Qt; exports.axModelInfoGrok = An; exports.axModelInfoGroq = Zt; exports.axModelInfoHuggingFace = en; exports.axModelInfoMistral = on; exports.axModelInfoOpenAI = ye; exports.axModelInfoOpenAIResponses = Lt; exports.axModelInfoReka = pn; exports.axModelInfoTogether = un; exports.axSpanAttributes = C; exports.axSpanEvents = j; exports.axUpdateMetricsConfig = Ls; exports.axUpdateOptimizerMetricsConfig = Ri; exports.axValidateChatRequestMessage = dn; exports.axValidateChatResponseResult = mn; exports.f = $i; exports.s = Li;
286
+ Instruction:`;try{let d=await n.chat({chatPrompt:[{role:"user",content:l}]});if("results"in d){let u=_optionalChain([d, 'access', _970 => _970.results, 'access', _971 => _971[0], 'optionalAccess', _972 => _972.content, 'optionalAccess', _973 => _973.trim, 'call', _974 => _974()]);if(u&&u.length>10)return u}}catch (e12){}let p=["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."],c=p[t%p.length]||p[0];return e&&(c=`${c} ${e}`),c}async proposeInstructionCandidates(e,t){let n=[],o=this.getTeacherOrStudentAI(t),r,i;this.dataAwareProposer&&(i=await this.generateDatasetSummary(this.examples,o));let a=this.tipAwareProposer?this.generateTips():[];for(let l=0;l<this.numCandidates;l++){let p=a.length>0?l%a.length:-1,c=p>=0?a[p]:void 0,d=await this.generateInstruction({tip:c,candidateIndex:l,ai:o,programSummary:r,datasetSummary:i,previousInstructions:n});n.push(d)}return n}async bootstrapFewShotExamples(e,t){return(await new De({studentAI:this.studentAI,examples:this.examples,options:{maxDemos:this.maxBootstrappedDemos,maxRounds:3,verboseMode:this.isLoggingEnabled()}}).compile(e,t,{maxDemos:this.maxBootstrappedDemos})).demos||[]}selectLabeledExamples(){let e=[],t=new Set;for(;t.size<this.maxLabeledDemos&&t.size<this.examples.length;){let n=Math.floor(Math.random()*this.examples.length);if(!t.has(n)){t.add(n);let o=this.examples[n];o&&e.push(o)}}return e}async runOptimization(e,t,n,o,r,i,a){let l={instruction:o[0]||"",bootstrappedDemos:Math.min(1,t.length),labeledExamples:Math.min(1,n.length)},p=0,c=0,d=[],u=0;if(this.resumeFromCheckpoint){let m=await this.loadCheckpoint(this.resumeFromCheckpoint,a);m&&m.optimizerType==="MiPRO"&&(this.restoreFromCheckpoint(m),u=m.currentRound,p=m.bestScore,l=m.bestConfiguration||l,c=_optionalChain([m, 'access', _975 => _975.stats, 'access', _976 => _976.convergenceInfo, 'optionalAccess', _977 => _977.stagnationRounds])||0)}for(let m=u;m<this.numTrials;m++){let A;this.bayesianOptimization&&this.miproConfigHistory.length>2?A=await this.selectConfigurationViaBayesianOptimization(o,t,n):A={instruction:o[m%o.length]||o[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)};let g=await this.evaluateConfig(e,A,t,n,r,i,m+1);this.updateSurrogateModel(A,g),d.push(g);let f=g-p;if(f>this.minImprovementThreshold?(p=g,l=A,c=0):c++,await this.updateOptimizationProgress(m+1,g,A,"MiPRO",this.getConfiguration(),p,l,{stagnationRounds:c,bootstrappedDemos:t.length,labeledExamples:n.length,instructions:o.length},a),this.onProgress&&this.onProgress({round:m+1,totalRounds:this.numTrials,currentScore:g,bestScore:p,tokensUsed:this.stats.resourceUsage.totalTokens,timeElapsed:Date.now(),successfulExamples:this.stats.successfulDemos,totalExamples:this.examples.length,currentConfiguration:A,convergenceInfo:{improvement:f,stagnationRounds:c,isConverging:c<this.earlyStoppingTrials}}),this.checkCostLimits()){this.triggerEarlyStopping("Cost limit reached",m+1);break}if(c>=this.earlyStoppingTrials){this.triggerEarlyStopping(`No improvement for ${this.earlyStoppingTrials} trials`,m-c+1);break}if(this.checkTargetScore(p)){this.triggerEarlyStopping(`Target score ${this.targetScore} reached`,m+1);break}}return this.stats.convergenceInfo.stagnationRounds=c,this.stats.convergenceInfo.finalImprovement=d.length>1?p-d[0]:0,this.stats.convergenceInfo.converged=c<this.earlyStoppingTrials,{bestConfig:l,bestScore:p}}async evaluateConfig(e,t,n,o,r,i,a=0){let l=new k(e.getSignature());this.applyConfigToProgram(l,t,n,o);let p=0,c=0,d;if(this.minibatch){let A=Math.min(this.minibatchSize,r.length);a%this.minibatchFullEvalSteps===0||a>this.numTrials*.8?d=Math.min(r.length,A*2):d=Math.max(3,Math.min(A,r.length))}else d=r.length;let m=this.shuffleArray([...Array(r.length).keys()]).slice(0,d).map(A=>r[A]);for(let A of m)try{let g=await l.forward(this.studentAI,A,this.sampleCount>1?{sampleCount:this.sampleCount,resultPicker:Ni()}:void 0),f=await i({prediction:g,example:A});p+=f,c++,this.stats.totalCalls++}catch (e13){}return c>0?p/c:0}shuffleArray(e){let t=[...e];for(let n=t.length-1;n>0;n--){let o=Math.floor(Math.random()*(n+1));[t[n],t[o]]=[t[o],t[n]]}return t}applyConfigToProgram(e,t,n,o){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(o.slice(0,t.labeledExamples))}async compile(e,t,n){let o=Date.now();this.setupRandomSeed();let r=n;_optionalChain([r, 'optionalAccess', _978 => _978.auto])&&this.configureAuto(r.auto);let i=this.getValidationSet(n)||(_nullishCoalesce(_optionalChain([r, 'optionalAccess', _979 => _979.validationExamples]), () => (this.examples.slice(0,Math.floor(this.examples.length*.2))))),a=[];this.maxBootstrappedDemos>0&&(a=await this.bootstrapFewShotExamples(e,t));let l=[];this.maxLabeledDemos>0&&(l=this.selectLabeledExamples());let p=await this.proposeInstructionCandidates(e,n),{bestConfig:c,bestScore:d}=await this.runOptimization(e,a,l,p,i,t,n);this.checkTargetScore(d)&&this.triggerEarlyStopping(`Target score ${this.targetScore} reached with score ${d}`,this.numTrials);let u;"getSignature"in e&&typeof e.getSignature=="function"?u=e.getSignature():u="input -> output";let m=new k(u);return this.applyConfigToAxGen(m,c,a,l),this.updateResourceUsage(o),this.stats.convergenceInfo.converged=!0,this.stats.convergenceInfo.finalImprovement=d,await this.saveFinalCheckpoint("MiPRO",this.getConfiguration(),d,c,{bootstrappedDemos:a.length,labeledExamples:l.length,instructions:p.length,optimizedGen:!!m},n),{demos:a,stats:this.stats,bestScore:d,optimizedGen:m,finalConfiguration:{instruction:c.instruction,bootstrappedDemos:c.bootstrappedDemos,labeledExamples:c.labeledExamples,numCandidates:this.numCandidates,numTrials:this.numTrials,sampleCount:this.sampleCount}}}applyConfigToAxGen(e,t,n,o){"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(o.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.miproConfigHistory=[],this.surrogateModel.clear(),this.stats.convergenceInfo.convergenceThreshold=this.minImprovementThreshold}validateProgram(e){let t=[],n=[];return this.examples.length<this.maxBootstrappedDemos+this.maxLabeledDemos&&(t.push(`Not enough examples: need at least ${this.maxBootstrappedDemos+this.maxLabeledDemos}, got ${this.examples.length}`),n.push("Reduce maxBootstrappedDemos or maxLabeledDemos, or provide more examples")),this.getValidationSet().length<5&&(t.push("Validation set too small for reliable MiPRO optimization"),n.push("Provide more examples or a larger validation set")),{isValid:t.length===0,issues:t,suggestions:n}}encodeConfiguration(e){return`${e.instruction.length}_${e.bootstrappedDemos}_${e.labeledExamples}`}updateSurrogateModel(e,t){this.miproConfigHistory.push({config:{...e},score:t});let n=this.encodeConfiguration(e),o=this.miproConfigHistory.filter(r=>this.encodeConfiguration(r.config)===n);if(o.length>0){let r=o.map(l=>l.score),i=r.reduce((l,p)=>l+p,0)/r.length,a=r.length>1?r.reduce((l,p)=>l+(p-i)**2,0)/(r.length-1):.1;this.surrogateModel.set(n,{mean:i,variance:a})}}predictPerformance(e){let t=this.encodeConfiguration(e);if(this.surrogateModel.has(t))return this.surrogateModel.get(t);if(this.miproConfigHistory.length>0){let n=this.miproConfigHistory.map(i=>{let a=Math.abs(i.config.bootstrappedDemos-e.bootstrappedDemos)+Math.abs(i.config.labeledExamples-e.labeledExamples);return{score:i.score,similarity:1/(1+a)}}),o=n.reduce((i,a)=>i+a.similarity,0);return{mean:n.reduce((i,a)=>i+a.score*a.similarity,0)/o,variance:.2}}return{mean:.5,variance:.3}}calculateAcquisitionValue(e){let t=this.predictPerformance(e),{mean:n,variance:o}=t,r=Math.sqrt(o),i=this.miproConfigHistory.length>0?Math.max(...this.miproConfigHistory.map(a=>a.score)):0;switch(this.acquisitionFunction){case"expected_improvement":{let a=n-i;if(r===0)return Math.max(0,a);let l=a/r,p=.5*(1+this.erf(l/Math.sqrt(2))),c=Math.exp(-.5*l*l)/Math.sqrt(2*Math.PI);return a*p+r*c}case"upper_confidence_bound":return n+this.explorationWeight*r;case"probability_improvement":{let a=n-i;if(r===0)return a>0?1:0;let l=a/r;return .5*(1+this.erf(l/Math.sqrt(2)))}default:return n}}erf(e){let t=.254829592,n=-.284496736,o=1.421413741,r=-1.453152027,i=1.061405429,a=.3275911,l=e>=0?1:-1,p=Math.abs(e),c=1/(1+a*p),d=1-((((i*c+r)*c+o)*c+n)*c+t)*c*Math.exp(-p*p);return l*d}async selectConfigurationViaBayesianOptimization(e,t,n){let o=[],r=Math.min(20,e.length*3);for(let i=0;i<r;i++){let a={instruction:e[i%e.length]||e[0]||"",bootstrappedDemos:Math.min(Math.floor(Math.random()*(t.length+1)),this.maxBootstrappedDemos),labeledExamples:Math.min(Math.floor(Math.random()*(n.length+1)),this.maxLabeledDemos)},l=this.calculateAcquisitionValue(a);o.push({config:a,acquisitionValue:l})}return o.sort((i,a)=>a.acquisitionValue-i.acquisitionValue),o[0].config}}, _class38),Ni=()=>async s=>{if(s.type==="fields"){let e={};for(let{index:o,sample:r}of s.results){let i=JSON.stringify(r);e[i]||(e[i]={count:0,index:o}),e[i].count+=1}let t,n=-1;for(let[o,r]of Object.entries(e))r.count>n&&(n=r.count,t=o);return _nullishCoalesce(_optionalChain([e, 'access', _980 => _980[t], 'optionalAccess', _981 => _981.index]), () => (0))}return _nullishCoalesce(_optionalChain([s, 'access', _982 => _982.results, 'access', _983 => _983[0], 'optionalAccess', _984 => _984.index]), () => (0))};function $i(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=_nullishCoalesce(s[n], () => ("")),n<e.length){let o=e[n];if(Hn(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let c=r[1];o.isOptional&&(c+="?"),o.isInternal&&(c+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${c}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=It(l)}else if(Vn(o))t+=jn(o);else if(typeof o=="string"||o instanceof S)t+=Wr(o);else throw new Error("Unsupported template interpolation value")}return new S(t)}function Li(s,...e){let t="";for(let n=0;n<s.length;n++)if(t+=_nullishCoalesce(s[n], () => ("")),n<e.length){let o=e[n];if(Hn(o)){let r=t.match(/(\w+)\s*:\s*$/);if(r&&(o.isOptional||o.isInternal)){let c=r[1];o.isOptional&&(c+="?"),o.isInternal&&(c+="!"),t=t.replace(/(\w+)(\s*:\s*)$/,`${c}$2`)}let{isOptional:i,isInternal:a,...l}=o;t+=It(l)}else if(Vn(o))t+=jn(o);else if(typeof o=="string"||o instanceof S)t+=Wr(o);else throw new Error("Unsupported template interpolation value")}return new k(t)}function Wr(s){if(typeof s=="string")return s;if(Hn(s))return It(s);if(Vn(s))return jn(s);if(s instanceof S){let e=s.toString(),t=e.indexOf(" -> ");return t!==-1?e.substring(t+4):e}throw new Error(`Unsupported template value type: ${typeof s}`)}function It(s){let e=s.type;return s.isArray&&(e+="[]"),s.options&&s.options.length>0&&s.type==="class"&&(e+=` "${s.options.join(", ")}"`),s.description&&(e+=` "${s.description}"`),e}function jn(s){let e=s.name;return s.isOptional&&(e+="?"),s.isInternal&&(e+="!"),s.type&&(e+=`:${It(s.type)}`),s.description&&!_optionalChain([s, 'access', _985 => _985.type, 'optionalAccess', _986 => _986.description])&&(e+=` "${s.description}"`),e}function Hn(s){return s!==null&&typeof s=="object"&&s!==void 0&&"type"in s&&typeof s.type=="string"}function Vn(s){return s!==null&&typeof s=="object"&&s!==void 0&&"name"in s&&typeof s.name=="string"}var Bi={string:s=>({type:"string",description:s}),number:s=>({type:"number",description:s}),boolean:s=>({type:"boolean",description:s}),date:s=>({type:"date",description:s}),datetime:s=>({type:"datetime",description:s}),json:s=>({type:"json",description:s}),image:s=>({type:"image",description:s}),audio:s=>({type:"audio",description:s}),class:(s,e)=>({type:"class",options:s,description:e}),code:(s,e)=>({type:"code",options:[s],description:e}),array:s=>({...s,isArray:!0}),optional:s=>({...s,isOptional:!0}),internal:s=>({...s,isInternal:!0})};var Ue=class{analyzeMappingDependencies(e,t){if(!e||typeof e!="function")return[];let n=[];try{let o=e.toString(),r=Array.from(o.matchAll(/state\.(\w+)/g));for(let i of r)i[1]&&!n.includes(i[1])&&n.push(i[1]);if(n.length===0)try{let i=this.createDependencyTracker(n);e(i)}catch (e14){}}catch(o){console.debug("Dependency analysis failed:",o)}return n}createTrackingProxy(e,t){let n=this;return new Proxy(e,{get(o,r){typeof r=="string"&&!t.includes(r)&&t.push(r);let i=o[r];return i&&typeof i=="object"?n.createTrackingProxy(i,t):i},has(o,r){return typeof r=="string"&&!t.includes(r)&&t.push(r),r in o}})}parseStaticDependencies(e){let t=[];try{let n=Array.from(e.matchAll(/state\.(\w+)/g));for(let i of n)i[1]&&!t.includes(i[1])&&t.push(i[1]);let o=Array.from(e.matchAll(/\$\{state\.(\w+)\}/g));for(let i of o)i[1]&&!t.includes(i[1])&&t.push(i[1]);let r=Array.from(e.matchAll(/\{\s*(\w+)(?:\s*,\s*(\w+))*\s*\}\s*=\s*state/g));for(let i of r)for(let a=1;a<i.length;a++)i[a]&&!t.includes(i[a])&&t.push(i[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:()=>{}})}})}};var Ne= (_class39 =class{constructor() { _class39.prototype.__init124.call(this);_class39.prototype.__init125.call(this);_class39.prototype.__init126.call(this);_class39.prototype.__init127.call(this); }__init124() {this.steps=[]}__init125() {this.parallelGroups=[]}__init126() {this.analyzer=new Ue}__init127() {this.initialFields=new Set}addExecutionStep(e,t,n,o,r,i){let a=[],l=[],p=o||"other";if(t&&n)p="execute",a=this.analyzer.analyzeMappingDependencies(n,t),l=[`${t}Result`];else if(p==="map"&&r)l=this.analyzeMapTransformation(r),a=this.getAllProducedFields();else if(p==="merge"){if(_optionalChain([i, 'optionalAccess', _987 => _987.resultKey]))l=[i.resultKey];else{let u=this.analyzeBranchMergeFields();l=u.length>0?u:["_mergedResult"]}e.toString().includes("_parallelResults")?a=["_parallelResults"]:a=this.getAllProducedFields()}else e.toString().includes("transform(")?(p="map",a=this.getAllProducedFields(),l=["_mapResult"]):e.toString().includes("_parallelResults")&&(l=["_parallelResults"],a=this.getAllProducedFields());let c={type:p,nodeName:t,dependencies:a,produces:l,stepFunction:e,stepIndex:this.steps.length};this.steps.push(c)}analyzeMapTransformation(e){try{let t=this.createMockState(),n=e(t);if(n&&typeof n=="object"&&!Array.isArray(n))return Object.keys(n)}catch(t){console.debug("Map transformation analysis failed:",t)}return["_mapResult"]}createMockState(){let e={};for(let t of this.initialFields)e[t]=this.createMockValue(t);for(let t of this.steps)for(let n of t.produces)n.endsWith("Result")?e[n]={text:"mockText",value:"mockValue",result:"mockResult",data:"mockData",processedText:"mockProcessedText",sentimentValue:"mockSentiment",confidenceScore:.8,isComplex:!1,mockValue:"mockValue"}: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 o=[];for(let r of this.steps){if(e.has(r.stepIndex))continue;if(r.dependencies.length===0||r.dependencies.every(a=>t.has(a))){if(r.type==="merge"&&o.length>0)continue;if(o.push(r),e.add(r.stepIndex),r.type==="merge")break}}if(o.length>0){for(let r of o)r.produces.forEach(i=>t.add(i));this.parallelGroups.push({level:n,steps:o}),n++}else{let r=this.steps.filter(i=>!e.has(i.stepIndex));if(r.length>0){let i=r[0];e.add(i.stepIndex),i.produces.forEach(a=>t.add(a)),this.parallelGroups.push({level:n,steps:[i]}),n++}else break}}}getAllProducedFields(){let e=[];for(let t of this.steps)e.push(...t.produces);return e}createOptimizedExecution(){let e=[];for(let t of this.parallelGroups)if(t.steps.length===1){let n=t.steps[0];n&&e.push(n.stepFunction)}else if(t.steps.length>1){let n=async(o,r)=>{let i=t.steps.map(c=>c.stepFunction(o,r)),a=await Promise.all(i);if(a.some(c=>c&&typeof c=="object"&&"_parallelResults"in c))return a.find(d=>d&&typeof d=="object"&&"_parallelResults"in d)||o;let p=o;for(let c of a)p={...p,...c};return p};e.push(n)}return e}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}}}, _class39);var $e= (_class40 =class{constructor(e){;_class40.prototype.__init128.call(this);this.nodeGenerators=e}__init128() {this.steps=[]}execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _988 => _988.ai]), () => (i.mainAi)),l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _989 => _989.options]), () => (i.mainOptions)),p=t(r),c=_optionalChain([l, 'optionalAccess', _990 => _990.traceLabel])?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,p,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}}, _class40),Wn= exports.AxFlowTypedSubContextImpl = (_class41 =class{constructor(e){;_class41.prototype.__init129.call(this);this.nodeGenerators=e}__init129() {this.steps=[]}execute(e,t,n){let o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);return this.steps.push(async(r,i)=>{let a=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _991 => _991.ai]), () => (i.mainAi)),l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _992 => _992.options]), () => (i.mainOptions)),p=t(r),c=_optionalChain([l, 'optionalAccess', _993 => _993.traceLabel])?`Node:${e} (${l.traceLabel})`:`Node:${e}`,d;if("forward"in o&&typeof o.forward=="function")d=await o.forward(a,p,{...l,traceLabel:c});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...r,[`${e}Result`]:d}}),this}map(e){return this.steps.push(t=>e(t)),this}async executeSteps(e,t){let n=e;for(let o of this.steps)n=await o(n,t);return n}}, _class41);var Jn= (_class42 =class{__init130() {this.nodes=new Map}__init131() {this.flowDefinition=[]}__init132() {this.nodeGenerators=new Map}__init133() {this.loopStack=[]}__init134() {this.stepLabels=new Map}__init135() {this.branchContext=null}__init136() {this.executionPlanner=new Ne}toCamelCase(e){return e.replace(/_([a-z])/g,(t,n)=>n.toUpperCase())}inferSignatureFromFlow(){if(this.nodeGenerators.size===0){let c=new S;return c.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),c.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),c}let e=this.executionPlanner.getExecutionPlan(),t=new Set,n=new Set;for(let c of e.steps)c.produces.forEach(d=>t.add(d)),c.dependencies.forEach(d=>n.add(d));let o=new Set;for(let c of n)t.has(c)||o.add(c);let r=new Set,i=e.steps[e.steps.length-1];if(i&&(i.type==="map"||i.type==="merge")){if(i.produces.forEach(c=>{c.startsWith("_")||r.add(c)}),i.type==="merge"&&i.produces.includes("_mergedResult"))for(let c of e.steps)c.type==="execute"&&c.produces.length>0&&c.produces.forEach(d=>r.add(d))}else for(let c of t){let d=!1;for(let u of e.steps)if(u.dependencies.includes(c)){d=!0;break}if(!d)if(c.endsWith("Result")){let u=c.replace("Result",""),m=this.nodeGenerators.get(u);if(m){let A=m.getSignature(),f=new S(A).getOutputFields();for(let h of f)r.add(h.name)}else r.add(c)}else r.add(c)}if(o.size===0&&r.size===0){let c=[],d=[];for(let[m,A]of this.nodeGenerators){let g=A.getSignature(),f=new S(g);for(let h of f.getInputFields()){let y=this.toCamelCase(`${m}_${h.name}`);c.push({name:y,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}for(let h of f.getOutputFields()){let y=this.toCamelCase(`${m}_${h.name}`);d.push({name:y,type:h.type,description:h.description,isOptional:h.isOptional,isInternal:h.isInternal})}}let u=new S;return c.length>0?u.setInputFields(c):u.addInputField({name:"userInput",type:{name:"string"},description:"User input to the flow"}),d.length>0?u.setOutputFields(d):u.addOutputField({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),u}let a=new S,l=[];for(let c of o)l.push({name:c,type:{name:"string"},description:`Input field: ${c}`});l.length===0&&l.push({name:"userInput",type:{name:"string"},description:"User input to the flow"});let p=[];for(let c of r)c.startsWith("_")||p.push({name:c,type:{name:"string"},description:`Output field: ${c}`});return p.length===0&&p.push({name:"flowOutput",type:{name:"string"},description:"Output from the flow"}),a.setInputFields(l),a.setOutputFields(p),a}constructor(e){;_class42.prototype.__init130.call(this);_class42.prototype.__init131.call(this);_class42.prototype.__init132.call(this);_class42.prototype.__init133.call(this);_class42.prototype.__init134.call(this);_class42.prototype.__init135.call(this);_class42.prototype.__init136.call(this);this.autoParallelConfig={enabled:_optionalChain([e, 'optionalAccess', _994 => _994.autoParallel])!==!1}}ensureProgram(){let e=this.inferSignatureFromFlow();this.program=new te(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(){return this.ensureProgram(),this.program.getTraces()}setDemos(e){this.ensureProgram(),this.program.setDemos(e)}getUsage(){return this.ensureProgram(),this.program.getUsage()}resetUsage(){this.ensureProgram(),this.program.resetUsage()}async*streamingForward(e,t,n){yield{version:1,index:0,delta:await this.forward(e,t,n)}}async forward(e,t,n){let o;if(Array.isArray(t)){let l=t.filter(p=>p.role==="user").pop();if(!l)throw new Error("No user message found in values array");o=l.values}else o=t;this.nodeGenerators.size>0&&this.ensureProgram();let r={...o},i={mainAi:e,mainOptions:n};if(_optionalChain([n, 'optionalAccess', _995 => _995.autoParallel])!==!1&&this.autoParallelConfig.enabled){this.executionPlanner.setInitialFields(Object.keys(o));let l=this.executionPlanner.createOptimizedExecution();for(let p of l)r=await p(r,i)}else for(let l of this.flowDefinition)r=await l(r,i);return r}node(e,t,n){if(typeof t=="string"||t instanceof S){let o=t;if(!o)throw new Error(`Invalid signature for node '${e}': signature cannot be empty`);this.nodes.set(e,{inputs:{},outputs:{}}),this.nodeGenerators.set(e,new k(o,n))}else if(typeof t=="function"){this.nodes.set(e,{inputs:{},outputs:{}});let o=new t;this.nodeGenerators.set(e,o)}else if(t&&typeof t=="object"&&"forward"in t)this.nodes.set(e,{inputs:{},outputs:{}}),this.nodeGenerators.set(e,t);else throw new Error(`Invalid second argument for node '${e}': expected string, AxSignature, AxProgrammable instance, or constructor function`);return this.ensureProgram(),this}n(e,t,n){return this.node(e,t,n)}map(e){let t=n=>e(n);if(_optionalChain([this, 'access', _996 => _996.branchContext, 'optionalAccess', _997 => _997.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}m(e){return this.map(e)}label(e){if(_optionalChain([this, 'access', _998 => _998.branchContext, 'optionalAccess', _999 => _999.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 o=this.nodeGenerators.get(e);if(!o)throw new Error(`Node program for '${e}' not found.`);let r=async(i,a)=>{let l=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1000 => _1000.ai]), () => (a.mainAi)),p=_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1001 => _1001.options]), () => (a.mainOptions)),c=t(i),d=_optionalChain([p, 'optionalAccess', _1002 => _1002.traceLabel])?`Node:${e} (${p.traceLabel})`:`Node:${e}`,u;if("forward"in o&&typeof o.forward=="function")u=await o.forward(l,c,{...p,traceLabel:d});else throw new Error(`Node program for '${e}' does not have a forward method`);return{...i,[`${e}Result`]:u}};if(_optionalChain([this, 'access', _1003 => _1003.branchContext, 'optionalAccess', _1004 => _1004.currentBranchValue])!==void 0){let i=this.branchContext.branches.get(this.branchContext.currentBranchValue)||[];i.push(r),this.branchContext.branches.set(this.branchContext.currentBranchValue,i)}else this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,e,t);return this.ensureProgram(),this}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,o)=>{let r=e.predicate(n),i=e.branches.get(r);if(!i)return n;let a=n;for(let l of i)a=await l(a,o);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,o)=>{let r=e.map(async a=>{let l=new $e(this.nodeGenerators);return await a(l).executeSteps(n,o)}),i=await Promise.all(r);return{...n,_parallelResults:i}};return this.flowDefinition.push(t),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(t,void 0,void 0,"other",void 0,void 0),this.ensureProgram(),{merge:(n,o)=>{let r=i=>{let a=i._parallelResults;if(!Array.isArray(a))throw new Error("No parallel results found for merge");let l=o(...a),p={...i};return p._parallelResults=void 0,p[n]=l,p};return this.flowDefinition.push(r),this.autoParallelConfig.enabled&&this.executionPlanner.addExecutionStep(r,void 0,void 0,"merge",void 0,{resultKey:n,mergeFunction:o}),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 o=this.stepLabels.get(t),r=this.flowDefinition.length;return this.flowDefinition.push(async(i,a)=>{let l=i,p=1,c=`_feedback_${t}_iterations`;for(typeof l[c]!="number"&&(l={...l,[c]:1});e(l)&&p<n;){p++,l={...l,[c]:p};for(let d=o;d<r;d++){let u=this.flowDefinition[d];u&&(l=await u(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 o=Object.assign(r=>r,{_condition:e,_maxIterations:t,_isLoopStart:!0});return this.flowDefinition.push(o),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,o=t._maxIterations,r=this.flowDefinition.splice(e+1);return this.flowDefinition[e]=async(i,a)=>{let l=i,p=0;for(;n(l)&&p<o;){p++;for(let c of r)l=await c(l,a)}if(p>=o&&n(l))throw new Error(`While loop exceeded maximum iterations (${o}). Consider increasing maxIterations or ensuring the loop condition eventually becomes false.`);return l},this.nodeGenerators.size>0&&this.ensureProgram(),this}end(){return this.endWhile()}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()}}, _class42);var Yn= (_class43 =class{__init137() {this.containerId=null}constructor(e="http://localhost:2375"){;_class43.prototype.__init137.call(this);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:o}){let r=t.map(p=>`${p.hostPath}:${p.containerPath}`);n||await this.pullImage(e);let i={Image:e,Tty:!0,OpenStdin:!1,AttachStdin:!1,AttachStdout:!1,AttachStderr:!1,HostConfig:{Binds:r},Labels:{}};o&&(i.Labels["com.example.tag"]=o);let a=await this.fetchDockerAPI("/containers/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});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:o}){let i=(await this.listContainers(!0)).filter(l=>l.Labels&&l.Labels["com.example.tag"]===o);if(i&&i.length>0){let l=Math.floor(Math.random()*i.length),p=i[l];if(p)return await this.connectToContainer(p.Id),{Id:p.Id,isNew:!1}}return{Id:(await this.createContainer({imageName:e,volumes:t,doNotPullImage:n,tag:o})).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 o=[],r=await this.listContainers(!0),i=e?r.filter(a=>a.Labels["com.example.tag"]===e):r;for(let a of i){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}o.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}o.push({Id:a.Id,Action:"removed"})}}return o}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(console.log("Executing command:",e),!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 o=await n.json(),r=await this.fetchDockerAPI(`/exec/${o.Id}/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({Detach:!1,Tty:!1})});if(!r.ok)throw new Error(`Failed to start exec instance: ${r.statusText}`);return await r.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(r=>setTimeout(r,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)}}}, _class43);var Kn=class{constructor({ai:e,info:t,func:n}){this.aiService=e,this.info=t,this.func=n}async embedAdapter(e,t){let o=(await this.aiService.embed({texts:[e]},{sessionId:_optionalChain([t, 'optionalAccess', _1005 => _1005.sessionId]),abortSignal:_optionalChain([t, 'optionalAccess', _1006 => _1006.abortSignal])})).embeddings.at(0);if(!o)throw new Error("Failed to embed text");return this.func.length===2?this.func(o,t):this.func(o)}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 Qn= (_class44 =class{constructor(e,t={}){;_class44.prototype.__init138.call(this);_class44.prototype.__init139.call(this);_class44.prototype.__init140.call(this);this.transport=e;this.options=t;this.logger=_nullishCoalesce(t.logger, () => ((n=>{console.log(typeof n=="string"?n:JSON.stringify(n,null,2))})))}__init138() {this.functions=[]}__init139() {this.activeRequests=new Map}__init140() {this.capabilities={}}async init(){"connect"in this.transport&&await _optionalChain([this, 'access', _1007 => _1007.transport, 'access', _1008 => _1008.connect, 'optionalCall', _1009 => _1009()]);let{result:e}=await this.sendRequest("initialize",{protocolVersion:"2024-11-05",capabilities:{roots:{listChanged:!0},sampling:{}},clientInfo:{name:"AxMCPClient",version:"1.0.0"}}),t="2024-11-05";if(e.protocolVersion!==t)throw new Error(`Protocol version mismatch. Expected ${t} but got ${e.protocolVersion}`);e.capabilities.tools&&(this.capabilities.tools=!0),e.capabilities.resources&&(this.capabilities.resources=!0),e.capabilities.prompts&&(this.capabilities.prompts=!0),await this.sendNotification("notifications/initialized"),await this.discoverFunctions()}async discoverFunctions(){if(!this.capabilities.tools)throw new Error("Tools are not supported");let{result:e}=await this.sendRequest("tools/list");this.functions=e.tools.map(t=>{let n=_optionalChain([this, 'access', _1010 => _1010.options, 'access', _1011 => _1011.functionOverrides, 'optionalAccess', _1012 => _1012.find, 'call', _1013 => _1013(r=>r.name===t.name)]),o=t.inputSchema.properties?{properties:t.inputSchema.properties,required:_nullishCoalesce(t.inputSchema.required, () => ([])),type:t.inputSchema.type}:void 0;return{name:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1014 => _1014.updates, 'access', _1015 => _1015.name]), () => (t.name)),description:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1016 => _1016.updates, 'access', _1017 => _1017.description]), () => (t.description)),parameters:o,func:async r=>{let{result:i}=await this.sendRequest("tools/call",{name:t.name,arguments:r});return i}}})}async ping(e=3e3){let t=this.sendRequest("ping"),n=new Promise((i,a)=>setTimeout(()=>a(new Error("Ping response timeout exceeded")),e)),o=await Promise.race([t,n]),{result:r}=o;if(typeof r!="object"||r===null||Object.keys(r).length!==0)throw new Error(`Unexpected ping response: ${JSON.stringify(r)}`)}toFunction(){return this.functions}cancelRequest(e){if(this.activeRequests.has(e)){this.sendNotification("notifications/cancelled",{requestId:e,reason:"Client cancelled request"});let t=this.activeRequests.get(e);t&&t.reject(new Error(`Request ${e} cancelled`)),this.activeRequests.delete(e)}}async sendRequest(e,t={}){let n=q(),o={jsonrpc:"2.0",id:n,method:e,params:t},r=new Promise((a,l)=>{this.activeRequests.set(n,{reject:l}),this.transport.send(o).then(p=>{if(this.activeRequests.delete(n),p!==null&&typeof p=="object"&&"error"in p){let c=p;l(new Error(`RPC Error ${c.error.code}: ${c.error.message}`))}else p!==null&&typeof p=="object"&&"result"in p?a({result:p.result}):l(new Error("Invalid response no result or error"))}).catch(p=>{this.activeRequests.delete(n),l(p)})}),{result:i}=await r;return{id:n,result:i}}async sendNotification(e,t={}){let n={jsonrpc:"2.0",method:e,params:t},{debug:o}=this.options;if(o){let r={name:"Notification",id:"mcp_notification",value:`Sending notification: ${JSON.stringify(n,null,2)}`};this.logger(r)}await this.transport.sendNotification(n)}}, _class44);var Xn= (_class45 =class{__init141() {this.endpoint=null}constructor(e){;_class45.prototype.__init141.call(this);this.sseUrl=e}async connect(){return new Promise((e,t)=>{this.eventSource=new EventSource(this.sseUrl),this.eventSource.addEventListener("endpoint",n=>{try{let r=JSON.parse(n.data);if(!r.uri)throw new Error("Endpoint URI missing in SSE event data");this.endpoint=r.uri,e()}catch(o){t(o)}}),this.eventSource.onerror=()=>{t(new Error("Failed to establish SSE connection"))}})}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`);return t.json()}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)})}}, _class45),Zn= exports.AxMCPStreambleHTTPTransport = (_class46 =class{__init142() {this.pendingRequests=new Map}constructor(e,t){;_class46.prototype.__init142.call(this);this.mcpEndpoint=e,this.customHeaders={..._optionalChain([t, 'optionalAccess', _1018 => _1018.headers])},_optionalChain([t, 'optionalAccess', _1019 => _1019.authorization])&&(this.customHeaders.Authorization=t.authorization)}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"}),o=new URL(this.mcpEndpoint);if(Object.keys(this.customHeaders).length>0){this.openListeningStreamWithFetch(n).then(e).catch(t);return}this.eventSource=new EventSource(o.toString()),this.eventSource.onopen=()=>{e()},this.eventSource.onmessage=r=>{try{let i=JSON.parse(r.data);this.messageHandler&&this.messageHandler(i)}catch(i){console.error("Failed to parse SSE message:",i)}},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.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(),o=new TextDecoder,r="",i=async()=>{try{let{done:a,value:l}=await n.read();if(a){n.releaseLock();return}r+=o.decode(l,{stream:!0});let p=r.split(`
287
+ `);r=p.pop()||"";for(let c of p)if(c.startsWith("data: ")){let d=c.slice(6);if(d==="[DONE]")return;try{let u=JSON.parse(d);this.messageHandler&&this.messageHandler(u)}catch(u){console.error("Failed to parse SSE data:",u)}}await i()}catch(a){throw n.releaseLock(),a}};await i()}async send(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);let o=n.headers.get("Mcp-Session-Id");o&&(this.sessionId=o);let r=n.headers.get("Content-Type");if(_optionalChain([r, 'optionalAccess', _1020 => _1020.includes, 'call', _1021 => _1021("text/event-stream")]))return this.handleSSEResponse(n,e.id);if(_optionalChain([r, 'optionalAccess', _1022 => _1022.includes, 'call', _1023 => _1023("application/json")]))return n.json();throw new Error(`Unexpected content type: ${r}`)}async handleSSEResponse(e,t){return new Promise((n,o)=>{let r=_optionalChain([e, 'access', _1024 => _1024.body, 'optionalAccess', _1025 => _1025.getReader, 'call', _1026 => _1026()]);if(!r){o(new Error("No response body reader available"));return}let i=new TextDecoder,a="",l=async()=>{try{let{done:p,value:c}=await r.read();if(p){r.releaseLock();return}a+=i.decode(c,{stream:!0});let d=a.split(`
288
+ `);a=d.pop()||"";for(let u of d)if(u.startsWith("data: ")){let m=u.slice(6);if(m==="[DONE]")return;try{let A=JSON.parse(m);if("id"in A&&A.id===t){n(A);return}this.messageHandler&&this.messageHandler(A)}catch(A){console.error("Failed to parse SSE data:",A)}}await l()}catch(p){r.releaseLock(),o(p)}};l().catch(o)})}async sendNotification(e){let t=this.buildHeaders({"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),n=await fetch(this.mcpEndpoint,{method:"POST",headers:t,body:JSON.stringify(e)});if(!n.ok)throw n.status===404&&this.sessionId?(this.sessionId=void 0,new Error("Session expired. Please reinitialize.")):new Error(`HTTP error ${n.status}: ${n.statusText}`);n.status!==202&&console.warn(`Unexpected status for notification: ${n.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)}}, _class46);function qi(s,e,t,n,o){let r={...s};if(r.parameters){let i=r.parameters.properties?Object.keys(r.parameters.properties):[],l=t.filter(p=>i.includes(p)).filter(p=>p!=="model").filter(p=>!o.excludeFieldsFromPassthrough.includes(p));if(l.length>0){r.parameters=ji(r.parameters,l);let p=r.func;r.func=async(c,d)=>{let u={};if(Array.isArray(e)){let A=e.filter(g=>g.role==="user").pop();A&&(u=Kr(A.values,l))}else u=Kr(e,l);let m={...c,...u};return await p(m,d)}}return r}return n&&!o.disableSmartModelRouting&&o.canConfigureSmartModelRouting&&(r.parameters=Qr(r.parameters,n)),r}var Jr=new Error("Agent description must be at least 20 characters (explain in detail what the agent does)"),Yr=new Error("Agent definition is the prompt you give to the LLM for the agent. It must be detailed and at least 100 characters"),eo= exports.AxAgent =class{constructor({ai:e,name:t,description:n,definition:o,signature:r,agents:i,functions:a},l){let{disableSmartModelRouting:p,excludeFieldsFromPassthrough:c,debug:d}=_nullishCoalesce(l, () => ({}));if(this.ai=e,this.agents=i,this.functions=a,this.disableSmartModelRouting=p,this.excludeFieldsFromPassthrough=_nullishCoalesce(c, () => ([])),this.debug=d,!t||t.length<5)throw new Error("Agent name must be at least 10 characters (more descriptive)");if(!n||n.length<20)throw Jr;if(o&&o.length<100)throw Yr;this.program=new k(r,{...l,description:_nullishCoalesce(o, () => (n))});for(let m of _nullishCoalesce(i, () => ([])))this.program.register(m);this.name=t,this.func={name:zi(this.name),description:n,parameters:this.program.getSignature().toJSONSchema(),func:()=>this.forward};let u=_optionalChain([e, 'optionalAccess', _1027 => _1027.getModelList, 'call', _1028 => _1028()]);u&&!this.disableSmartModelRouting&&(this.func.parameters=Qr(this.func.parameters,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,o)=>{let{model:r,...i}=n,a=_nullishCoalesce(this.ai, () => (_optionalChain([o, 'optionalAccess', _1029 => _1029.ai])));if(!a)throw new Error("AI service is required to run the agent");let l=await e(a,i,{...o,model:r}),c=this.program.getSignature().getOutputFields();return Object.keys(l).map(u=>{let m=c.find(A=>A.name===u);return m?`${m.title}: ${l[u]}`:`${u}: ${l[u]}`}).join(`
289
+ `)};return{...this.func,func:t}}getFeatures(){return{canConfigureSmartModelRouting:this.ai===void 0,excludeFieldsFromPassthrough:this.excludeFieldsFromPassthrough}}init(e,t,n){let o=_nullishCoalesce(this.ai, () => (e)),r=_optionalChain([o, 'optionalAccess', _1030 => _1030.getModelList, 'call', _1031 => _1031()]),a=this.program.getSignature().getInputFields().map(d=>d.name),l=this.getDebug(o,n),p=_optionalChain([this, 'access', _1032 => _1032.agents, 'optionalAccess', _1033 => _1033.map, 'call', _1034 => _1034(d=>{let u=d.getFeatures(),m={debug:l,disableSmartModelRouting:!!this.disableSmartModelRouting,excludeFieldsFromPassthrough:u.excludeFieldsFromPassthrough,canConfigureSmartModelRouting:u.canConfigureSmartModelRouting};return qi(d.getFunction(),t,a,r,m)})]),c=[..._nullishCoalesce(_nullishCoalesce(_optionalChain([n, 'optionalAccess', _1035 => _1035.functions]), () => (this.functions)), () => ([])),..._nullishCoalesce(p, () => ([]))];return{ai:o,functions:c,debug:l}}async forward(e,t,n){let{ai:o,functions:r,debug:i}=this.init(e,t,n);return await this.program.forward(o,t,{...n,debug:i,functions:r})}async*streamingForward(e,t,n){let{ai:o,functions:r,debug:i}=this.init(e,t,n);return yield*this.program.streamingForward(o,t,{...n,debug:i,functions:r})}setDescription(e){if(!e||e.length<20)throw Jr;this.program.getSignature().setDescription(e),this.func.description=e}setDefinition(e){if(!e||e.length<100)throw Yr;this.program.setDescription(e),this.func.description=e}getSignature(){return this.program.getSignature()}setSignature(e){this.program.setSignature(e)}getDebug(e,t){return _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(_optionalChain([t, 'optionalAccess', _1036 => _1036.debug]), () => (this.debug)), () => (_optionalChain([e, 'optionalAccess', _1037 => _1037.getOptions, 'call', _1038 => _1038(), 'optionalAccess', _1039 => _1039.debug]))), () => (!1))}};function zi(s){return s.split(/[^a-zA-Z0-9]/).map((n,o)=>{let r=n.toLowerCase();return o>0&&r&&r[0]?r[0].toUpperCase()+r.slice(1):r}).join("")}function Qr(s,e){let t=s?structuredClone(s):{type:"object",properties:{},required:[]};if(_optionalChain([t, 'access', _1040 => _1040.properties, 'optionalAccess', _1041 => _1041.model]))return t;let n={type:"string",enum:e.map(i=>i.key),description:`The AI model to use for this function call. Available options: ${e.map(i=>`\`${i.key}\` ${i.description}`).join(", ")}`},o={..._nullishCoalesce(t.properties, () => ({})),model:n},r=[..._nullishCoalesce(t.required, () => ([])),"model"];return{...t,properties:o,required:r}}function ji(s,e){let t=structuredClone(s);if(t.properties)for(let n of e)delete t.properties[n];if(Array.isArray(t.required)){let n=t.required.filter(o=>!e.includes(o));Object.defineProperty(t,"required",{value:n,writable:!0,configurable:!0})}return t}function Kr(s,e){let t={};for(let n of e)n in s&&(t[n]=s[n]);return t}var Le=class extends k{constructor(e,t){let n=new S(e);n.setOutputFields([{name:"reason",description:"Let's work this out in a step by step way in order to ensure we have the right answer.",isInternal:_optionalChain([t, 'optionalAccess', _1042 => _1042.setVisibleReasoning])!==!0},...n.getOutputFields()]),super(n,t)}};var to=class extends Le{constructor(e,t){super('"Answer questions with short factoid answers." context:string[] "may contain relevant facts", question -> answer',t),this.maxHops=_nullishCoalesce(_optionalChain([t, 'optionalAccess', _1043 => _1043.maxHops]), () => (3));let o=new S('"Write a simple search query that will help answer a complex question." context?:string[] "may contain relevant facts", question -> query "question to further our understanding"');this.genQuery=new k(o),this.queryFn=e}async forward(e,t,n){let o;if(Array.isArray(t)){let l=t.filter(p=>p.role==="user").pop();if(!l)throw new Error("No user message found in values array");o=l.values.question}else o=t.question;let r=0,i=[];for(;r<this.maxHops;){let l=await this.genQuery.forward(e,{context:i,question:o}),p=await this.queryFn(l.query);i=Ge.dedup([...i,p]),r++}return await super.forward(e,{context:i,question:o},n)}};exports.AxAI = pn; exports.AxAIAnthropic = ce; exports.AxAIAnthropicModel = Ve; exports.AxAIAnthropicVertexModel = _t; exports.AxAIAzureOpenAI = Ae; exports.AxAICohere = he; exports.AxAICohereEmbedModel = Ke; exports.AxAICohereModel = Ye; exports.AxAIDeepSeek = xe; exports.AxAIDeepSeekModel = Qe; exports.AxAIGoogleGemini = fe; exports.AxAIGoogleGeminiEmbedModel = zt; exports.AxAIGoogleGeminiEmbedTypes = Yo; exports.AxAIGoogleGeminiModel = Xe; exports.AxAIGoogleGeminiSafetyCategory = jt; exports.AxAIGoogleGeminiSafetyThreshold = Ht; exports.AxAIGrok = un; exports.AxAIGrokEmbedModels = or; exports.AxAIGrokModel = st; exports.AxAIGroq = Ie; exports.AxAIGroqModel = Ze; exports.AxAIHuggingFace = be; exports.AxAIHuggingFaceModel = Kt; exports.AxAIMistral = Re; exports.AxAIMistralEmbedModels = Zo; exports.AxAIMistralModel = et; exports.AxAIOllama = Ce; exports.AxAIOpenAI = ge; exports.AxAIOpenAIBase = M; exports.AxAIOpenAIEmbedModel = ue; exports.AxAIOpenAIModel = Je; exports.AxAIOpenAIResponses = Te; exports.AxAIOpenAIResponsesBase = tt; exports.AxAIOpenAIResponsesImpl = we; exports.AxAIOpenAIResponsesModel = de; exports.AxAIRefusalError = O; exports.AxAIReka = ve; exports.AxAIRekaModel = ot; exports.AxAIServiceAbortedError = le; exports.AxAIServiceAuthenticationError = Q; exports.AxAIServiceError = U; exports.AxAIServiceNetworkError = Y; exports.AxAIServiceResponseError = J; exports.AxAIServiceStatusError = re; exports.AxAIServiceStreamTerminatedError = W; exports.AxAIServiceTimeoutError = se; exports.AxAITogether = Oe; exports.AxAgent = eo; exports.AxApacheTika = Un; exports.AxAssertionError = Z; exports.AxBalancer = $t; exports.AxBaseAI = _; exports.AxBaseOptimizer = oe; exports.AxBootstrapFewShot = De; exports.AxChainOfThought = Le; exports.AxDB = An; exports.AxDBBase = z; exports.AxDBCloudflare = Se; exports.AxDBManager = xn; exports.AxDBMemory = X; exports.AxDBPinecone = ke; exports.AxDBWeaviate = Ee; exports.AxDefaultCostTracker = yt; exports.AxDefaultResultReranker = Dn; exports.AxDockerSession = Yn; exports.AxEmbeddingAdapter = Kn; exports.AxEvalUtil = yi; exports.AxFlow = Jn; exports.AxFlowDependencyAnalyzer = Ue; exports.AxFlowExecutionPlanner = Ne; exports.AxFlowSubContextImpl = $e; exports.AxFlowTypedSubContextImpl = Wn; exports.AxFunctionError = ct; exports.AxFunctionProcessor = dt; exports.AxGen = k; exports.AxGenerateError = ht; exports.AxHFDataLoader = Bn; exports.AxInstanceRegistry = Fe; exports.AxLLMRequestTypeValues = co; exports.AxMCPClient = Qn; exports.AxMCPHTTPSSETransport = Xn; exports.AxMCPStreambleHTTPTransport = Zn; exports.AxMemory = _e; exports.AxMiPRO = zn; exports.AxMockAIService = en; exports.AxMultiServiceRouter = tn; exports.AxProgram = te; exports.AxPromptTemplate = ae; exports.AxRAG = to; exports.AxRateLimiterTokenUsage = ye; exports.AxSignature = S; exports.AxSimpleClassifier = $n; exports.AxSimpleClassifierClass = Nn; exports.AxSpanKindValues = uo; exports.AxStringUtil = Ge; exports.AxTestPrompt = Ln; exports.ax = Li; exports.axAIAnthropicDefaultConfig = zo; exports.axAIAnthropicVertexDefaultConfig = as; exports.axAIAzureOpenAIBestConfig = gs; exports.axAIAzureOpenAICreativeConfig = ds; exports.axAIAzureOpenAIDefaultConfig = Ho; exports.axAIAzureOpenAIFastConfig = ms; exports.axAICohereCreativeConfig = hs; exports.axAICohereDefaultConfig = Wo; exports.axAIDeepSeekCodeConfig = fs; exports.axAIDeepSeekDefaultConfig = Jo; exports.axAIGoogleGeminiDefaultConfig = Qo; exports.axAIGoogleGeminiDefaultCreativeConfig = ys; exports.axAIGrokBestConfig = _s; exports.axAIGrokDefaultConfig = dn; exports.axAIHuggingFaceCreativeConfig = Rs; exports.axAIHuggingFaceDefaultConfig = Xo; exports.axAIMistralBestConfig = Cs; exports.axAIMistralDefaultConfig = Zt; exports.axAIOllamaDefaultConfig = er; exports.axAIOllamaDefaultCreativeConfig = ws; exports.axAIOpenAIBestConfig = Dt; exports.axAIOpenAICreativeConfig = Ut; exports.axAIOpenAIDefaultConfig = ie; exports.axAIOpenAIFastConfig = Nt; exports.axAIOpenAIResponsesBestConfig = vs; exports.axAIOpenAIResponsesCreativeConfig = Os; exports.axAIOpenAIResponsesDefaultConfig = nt; exports.axAIRekaBestConfig = Ss; exports.axAIRekaCreativeConfig = ks; exports.axAIRekaDefaultConfig = rt; exports.axAIRekaFastConfig = Es; exports.axAITogetherDefaultConfig = nr; exports.axBaseAIDefaultConfig = v; exports.axBaseAIDefaultCreativeConfig = F; exports.axCheckMetricsHealth = Us; exports.axCreateDefaultColorLogger = po; exports.axCreateDefaultOptimizerColorLogger = Hr; exports.axCreateDefaultOptimizerTextLogger = Ii; exports.axCreateDefaultTextLogger = os; exports.axDefaultMetricsConfig = rr; exports.axDefaultOptimizerLogger = qn; exports.axDefaultOptimizerMetricsConfig = Vr; exports.axGetMetricsConfig = Ls; exports.axGetOptimizerMetricsConfig = Ci; exports.axGlobals = E; exports.axModelInfoAnthropic = We; exports.axModelInfoCohere = Lt; exports.axModelInfoDeepSeek = qt; exports.axModelInfoGoogleGemini = Vt; exports.axModelInfoGrok = cn; exports.axModelInfoGroq = Jt; exports.axModelInfoHuggingFace = Yt; exports.axModelInfoMistral = Xt; exports.axModelInfoOpenAI = me; exports.axModelInfoOpenAIResponses = Ft; exports.axModelInfoReka = on; exports.axModelInfoTogether = sn; exports.axSpanAttributes = w; exports.axSpanEvents = V; exports.axUpdateMetricsConfig = $s; exports.axUpdateOptimizerMetricsConfig = Ri; exports.axValidateChatRequestMessage = an; exports.axValidateChatResponseResult = ln; exports.f = Bi; exports.s = $i;
184
290
  //# sourceMappingURL=index.cjs.map