@ax-llm/ax 23.0.11 → 23.0.12
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 +2 -2
- package/index.cjs.map +1 -1
- package/index.global.js +2 -2
- package/index.global.js.map +1 -1
- package/index.js +19 -19
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/skills/ax-agent-context.md +1 -1
- package/skills/ax-agent-memory-skills.md +1 -1
- package/skills/ax-agent-observability.md +1 -1
- package/skills/ax-agent-optimize.md +1 -1
- package/skills/ax-agent-rlm.md +1 -1
- package/skills/ax-agent.md +1 -1
- package/skills/ax-ai.md +1 -1
- package/skills/ax-audio.md +1 -1
- package/skills/ax-flow.md +1 -1
- package/skills/ax-gen.md +1 -1
- package/skills/ax-gepa.md +1 -1
- package/skills/ax-llm.md +1 -1
- package/skills/ax-mcp.md +1 -1
- package/skills/ax-playbook.md +1 -1
- package/skills/ax-refine.md +1 -1
- package/skills/ax-signature.md +1 -1
package/index.js
CHANGED
|
@@ -342,10 +342,10 @@ ${this.contentToText(a.content)}
|
|
|
342
342
|
`:"")+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(`
|
|
343
343
|
`)?`
|
|
344
344
|
`:"")+o;break;case"id":this.currentEvent.id=o;break;case"retry":{let i=Number.parseInt(o,10);Number.isNaN(i)||(this.currentEvent.retry=i);break}}}processEvent(e){if(this.currentEvent.rawData){if(this.currentEvent.event||(this.currentEvent.event="message"),this.currentEvent.rawData.trim()==="[DONE]"){this.currentEvent={rawData:""};return}try{let t=this.dataParser(this.currentEvent.rawData);e.enqueue(t)}catch(t){this.onError(t,this.currentEvent.rawData)}this.currentEvent={rawData:""}}}};var _l=class{decoder;constructor(){this.decoder=new TextDecoder}transform(e,t){if(!(e instanceof ArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("Input data must be a BufferSource");let n=this.decoder.decode(e,{stream:!0});n.length!==0&&t.enqueue(n)}flush(e){let t=this.decoder.decode();t.length!==0&&e.enqueue(t)}},Vs=class extends TransformStream{constructor(){super(new _l)}};var Ll={maxRetries:3,initialDelayMs:1e3,maxDelayMs:6e4,backoffFactor:2,retryableStatusCodes:[500,408,429,502,503,504,529]},nR=globalThis.TextDecoderStream??Vs,gt=class extends Error{constructor(t,n,o,i,s={},a=!0){super(t);this.url=n;this.requestBody=o;this.responseBody=i;this.name="AxAIServiceError",this.timestamp=new Date().toISOString(),this.errorId=ze(),this.context=s,this.includeRequestBodyInErrors=a,this.stack=this.toString()}timestamp;errorId;context;includeRequestBodyInErrors;toString(){let t=[`${this.name}: ${this.message}`,`URL: ${this.url}`];return this.includeRequestBodyInErrors&&t.push(`Request Body: ${JSON.stringify(this.requestBody,null,2)}`),t.push(`Response Body: ${JSON.stringify(this.responseBody,null,2)}`,`Context: ${JSON.stringify(this.context,null,2)}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`),t.join(`
|
|
345
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Qe=class extends gt{constructor(t,n,o,i,s,a,c,l=!0){let u=c?` (after ${c} retries)`:"";super(`HTTP ${t} - ${n}${u}`,o,i,{httpStatus:t,httpStatusText:n,responseBody:s,...a},{},l);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},tt=class extends gt{constructor(t,n,o,i,s,a=!0){super(`Network Error: ${t.message}`,n,o,i,{originalErrorName:t.name,originalErrorStack:t.stack,...s},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},bn=class extends gt{constructor(e,t,n,o,i=!0){super(e,t,n,void 0,o,i),this.name="AxAIServiceResponseError"}},kt=class extends gt{constructor(t,n,o,i,s=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...i},s);this.lastChunk=o;this.name="AxAIServiceStreamTerminatedError"}},yt=class extends gt{constructor(e,t,n,o,i=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o},i),this.name="AxAIServiceTimeoutError"}},Hs=class extends Qe{constructor(e,t,n,o,i,s,a=!0){super(e,t,n,o,i,s,void 0,a),this.name="AxTokenLimitError"}},
|
|
345
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},Qe=class extends gt{constructor(t,n,o,i,s,a,c,l=!0){let u=c?` (after ${c} retries)`:"";super(`HTTP ${t} - ${n}${u}`,o,i,{httpStatus:t,httpStatusText:n,responseBody:s,...a},{},l);this.status=t;this.statusText=n;this.name="AxAIServiceStatusError"}},tt=class extends gt{constructor(t,n,o,i,s,a=!0){super(`Network Error: ${t.message}`,n,o,i,{originalErrorName:t.name,originalErrorStack:t.stack,...s},a);this.originalError=t;this.name="AxAIServiceNetworkError",this.stack=t.stack}},bn=class extends gt{constructor(e,t,n,o,i=!0){super(e,t,n,void 0,o,i),this.name="AxAIServiceResponseError"}},kt=class extends gt{constructor(t,n,o,i,s=!0){super("Stream terminated unexpectedly by remote host",t,n,void 0,{lastChunk:o,...i},s);this.lastChunk=o;this.name="AxAIServiceStreamTerminatedError"}},yt=class extends gt{constructor(e,t,n,o,i=!0){super(`Request timed out after ${t}ms`,e,n,void 0,{timeoutMs:t,...o},i),this.name="AxAIServiceTimeoutError"}},Hs=class extends Qe{constructor(e,t,n,o,i,s,a=!0){super(e,t,n,o,i,s,void 0,a),this.name="AxTokenLimitError"}},_e=class extends gt{constructor(e,t,n,o,i=!0){super(`Request aborted${t?`: ${t}`:""}`,e,n,void 0,{abortReason:t,...o},i),this.name="AxAIServiceAbortedError"}},It=class extends gt{constructor(e,t,n,o,i=!0){super("Authentication failed",e,t,n,o,i),this.name="AxAIServiceAuthenticationError"}},Ke=class extends Error{constructor(t,n,o,i,s){super(`Model refused to fulfill request: ${t}`);this.refusalMessage=t;this.model=n;this.requestId=o;this.category=i;this.explanation=s;this.name="AxAIRefusalError",this.timestamp=new Date().toISOString(),this.errorId=ze()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Refusal: ${this.refusalMessage}`,this.model?`Model: ${this.model}`:"",this.requestId?`Request ID: ${this.requestId}`:"",this.category?`Category: ${this.category}`:"",this.explanation?`Explanation: ${this.explanation}`:"",`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].filter(Boolean).join(`
|
|
346
346
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},At=class extends Error{constructor(t,n,o=!1){super(`${t} not supported by ${n}${o?" (fallback available)":""}`);this.mediaType=t;this.provider=n;this.fallbackAvailable=o;this.name="AxMediaNotSupportedError",this.timestamp=new Date().toISOString(),this.errorId=ze()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Media Type: ${this.mediaType}`,`Provider: ${this.provider}`,`Fallback Available: ${this.fallbackAvailable}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
347
347
|
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}},on=class extends Error{constructor(t,n,o){super(`Failed to process ${n} during ${o}: ${t.message}`);this.originalError=t;this.contentType=n;this.processingStep=o;this.name="AxContentProcessingError",this.timestamp=new Date().toISOString(),this.errorId=ze()}timestamp;errorId;toString(){return[`${this.name}: ${this.message}`,`Content Type: ${this.contentType}`,`Processing Step: ${this.processingStep}`,`Original Error: ${this.originalError.message}`,`Timestamp: ${this.timestamp}`,`Error ID: ${this.errorId}`].join(`
|
|
348
|
-
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function Nl(r){try{return r.headers.get("content-type")?.includes("application/json")?await r.json():await r.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Dg(r,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**r)*(.75+Math.random()*.5)}function rR(r){if(!r)return;let e=Number(r);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(r);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function oR(){return{startTime:Date.now(),retryCount:0}}function jg(r){r.retryCount++,r.lastRetryTime=Date.now()}function Gg(r,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:r instanceof tt&&!(r instanceof It)}var Ks=async(r,e)=>{if(r.localCall)return await r.localCall(e,r.stream);if(!r.url)throw new Error("API URL is required when localCall is not provided");let t={...Ll,...r.retry},n=r.timeout,o=oR(),i=r.verbose??!1,s=r.includeRequestBodyInErrors??!0,a=r.method??(r.put?"PUT":"POST"),c,l=new URL(r.url),u=`${[l.pathname,r.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,d=new URL(u,l);if(r.corsProxy){let g=d.href;d=new URL(`${r.corsProxy}?url=${encodeURIComponent(g)}`)}let p=ze();if(r.validateRequest&&!await r.validateRequest(e))throw new bn("Invalid request data",d.href,e,{validation:"request"},s);r.span?.setAttributes({"http.request.method":a,"url.full":d.href,"request.id":p,"request.startTime":o.startTime});let m=0;for(;;){let g=new AbortController;if(r.abortSignal){if(r.abortSignal.aborted)throw new
|
|
348
|
+
`)}[Symbol.for("nodejs.util.inspect.custom")](t,n){return this.toString()}};async function Nl(r){try{return r.headers.get("content-type")?.includes("application/json")?await r.json():await r.clone().text()}catch(e){return`[ReadableStream - read failed: ${e.message}]`}}function Dg(r,e){return Math.min(e.maxDelayMs,e.initialDelayMs*e.backoffFactor**r)*(.75+Math.random()*.5)}function rR(r){if(!r)return;let e=Number(r);if(!Number.isNaN(e))return e*1e3;let t=Date.parse(r);if(!Number.isNaN(t)){let n=t-Date.now();return Math.max(0,n)}}function oR(){return{startTime:Date.now(),retryCount:0}}function jg(r){r.retryCount++,r.lastRetryTime=Date.now()}function Gg(r,e,t,n){return t>=n.maxRetries?!1:e&&n.retryableStatusCodes.includes(e)?!0:r instanceof tt&&!(r instanceof It)}var Ks=async(r,e)=>{if(r.localCall)return await r.localCall(e,r.stream);if(!r.url)throw new Error("API URL is required when localCall is not provided");let t={...Ll,...r.retry},n=r.timeout,o=oR(),i=r.verbose??!1,s=r.includeRequestBodyInErrors??!0,a=r.method??(r.put?"PUT":"POST"),c,l=new URL(r.url),u=`${[l.pathname,r.name].filter(Boolean).join("/").replace(/\/+/g,"/")}${l.search}`,d=new URL(u,l);if(r.corsProxy){let g=d.href;d=new URL(`${r.corsProxy}?url=${encodeURIComponent(g)}`)}let p=ze();if(r.validateRequest&&!await r.validateRequest(e))throw new bn("Invalid request data",d.href,e,{validation:"request"},s);r.span?.setAttributes({"http.request.method":a,"url.full":d.href,"request.id":p,"request.startTime":o.startTime});let m=0;for(;;){let g=new AbortController;if(r.abortSignal){if(r.abortSignal.aborted)throw new _e(d.href,r.abortSignal.reason,e,{metrics:o},s);let h=()=>{g.abort(r.abortSignal.reason||"User aborted request")};r.abortSignal.addEventListener("abort",h,{once:!0});let x=g.abort.bind(g);g.abort=f=>{r.abortSignal.removeEventListener("abort",h),x(f)}}n&&(c=setTimeout(()=>{g.abort("Request timeout")},n));try{i&&console.log(`
|
|
349
349
|
--- [AxAI API Request] ---
|
|
350
350
|
`,`URL: ${d.href}
|
|
351
351
|
`,`Method: ${a}
|
|
@@ -365,7 +365,7 @@ Body:`,JSON.stringify(e,null,2),`
|
|
|
365
365
|
`),!h.body)throw new bn("Response body is null",d.href,e,{metrics:o},s);let y,A=0;if(typeof window<"u"&&typeof EventSource<"u")return new ReadableStream({start(F){let k=h.body.getReader(),O=new TextDecoder,$="",N=I=>{if(!I.trim())return!1;let _=I.split(`
|
|
366
366
|
`),S="",H="message";for(let L of _)L.startsWith("data: ")?S=L.slice(6):L.startsWith("event: ")&&(H=L.slice(7));if(!S)return!1;if(S==="[DONE]")return F.close(),!0;try{let L=JSON.parse(S);y=L,A++,o.streamChunks=A,o.lastChunkTime=Date.now(),F.enqueue(L),r.span?.addEvent("stream.chunk",{"stream.chunks":A,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount,"sse.event.type":H})}catch(L){i&&console.warn("Skipping non-JSON SSE data:",S,L)}return!1};async function V(){try{for(;;){let{done:I,value:_}=await k.read();if(I){let H=!1;$.length>0&&(H=N($),$=""),H||F.close();break}$+=O.decode(_,{stream:!0});let S=$.split(`
|
|
367
367
|
|
|
368
|
-
`);$=S.pop()||"";for(let H of S)if(N(H))return}}catch(I){let _=I,S={...o,streamDuration:Date.now()-o.startTime};_.name==="AbortError"||_.message?.includes("aborted")?F.error(new kt(d.href,e,y,{streamMetrics:S},s)):F.error(new tt(_,d.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:S},s))}finally{k.releaseLock()}}V()}});let w=new TransformStream({transform(F,k){y=F,A++,o.streamChunks=A,o.lastChunkTime=Date.now(),k.enqueue(F),r.span?.addEvent("stream.chunk",{"stream.chunks":A,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})}}),v=!1;return new ReadableStream({start(F){let k=h.body.pipeThrough(new nR).pipeThrough(new qs).pipeThrough(w).getReader();async function O(){try{for(;;){let{done:$,value:N}=await k.read();if($){v||(v=!0,F.close());break}if(v)break;F.enqueue(N)}}catch($){let N=$,V={...o,streamDuration:Date.now()-o.startTime};
|
|
368
|
+
`);$=S.pop()||"";for(let H of S)if(N(H))return}}catch(I){let _=I,S={...o,streamDuration:Date.now()-o.startTime};_.name==="AbortError"||_.message?.includes("aborted")?F.error(r.abortSignal?.aborted?new _e(d.href,r.abortSignal.reason,e,{streamMetrics:S},s):new kt(d.href,e,y,{streamMetrics:S},s)):F.error(new tt(_,d.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:S},s))}finally{k.releaseLock()}}V()}});let w=new TransformStream({transform(F,k){y=F,A++,o.streamChunks=A,o.lastChunkTime=Date.now(),k.enqueue(F),r.span?.addEvent("stream.chunk",{"stream.chunks":A,"stream.duration":Date.now()-o.startTime,"response.retries":o.retryCount})}}),v=!1;return new ReadableStream({start(F){let k=h.body.pipeThrough(new nR).pipeThrough(new qs).pipeThrough(w).getReader();async function O(){try{for(;;){let{done:$,value:N}=await k.read();if($){v||(v=!0,F.close());break}if(v)break;F.enqueue(N)}}catch($){let N=$,V={...o,streamDuration:Date.now()-o.startTime};N.name==="AbortError"||N.message?.includes("aborted")?F.error(r.abortSignal?.aborted?new _e(d.href,r.abortSignal.reason,e,{streamMetrics:V},s):new kt(d.href,e,y,{streamMetrics:V},s)):N instanceof TypeError&&N.message.includes("cancelled")?F.error(new kt(d.href,e,y,{streamMetrics:V,cancelReason:"Stream cancelled by client"},s)):F.error(new tt(N,d.href,e,"[ReadableStream - consumed during streaming]",{streamMetrics:V},s))}finally{c&&clearTimeout(c),k.releaseLock()}}O()},cancel(){v=!0}})}catch(h){if(h instanceof Error&&h.name==="AbortError")throw r.abortSignal?.aborted?new _e(d.href,r.abortSignal.reason,e,{metrics:o},s):new yt(d.href,n||0,e,{metrics:o},s);let x=h;if(!(h instanceof gt)&&h instanceof Error&&(x=new tt(h,d.href,e,void 0,{metrics:o},s)),r.span?.isRecording()&&(r.span.recordException(x),r.span.setAttributes({"error.time":Date.now()-o.startTime,"error.retries":o.retryCount})),x instanceof tt&&Gg(x,void 0,m,t)){let f=Dg(m,t);m++,jg(o),r.span?.addEvent("retry",{attempt:m,delay:f,error:x.message,"metrics.startTime":o.startTime,"metrics.retryCount":o.retryCount,"metrics.lastRetryTime":o.lastRetryTime}),await new Promise(y=>setTimeout(y,f));continue}throw x instanceof gt&&(x.context.metrics=o),x}finally{c!==void 0&&clearTimeout(c)}}};var sr=class extends Error{constructor({message:e}){super(e),this.name="AxAssertionError"}getFixingInstructions=()=>{let e=this.message.trim();return[{name:"error",title:"Follow these instructions",description:e+(e.endsWith(".")?"":".")}]};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},Rn=class extends Error{constructor({message:e}){super(e),this.name="AxStreamingAssertionError"}getFixingInstructions=()=>{let e=this.message.trim();return[{name:"error",title:"Follow these instructions",description:e+(e.endsWith(".")?"":".")}]};toString(){return`${this.name}: ${this.message}`}[Symbol.for("nodejs.util.inspect.custom")](e,t){return this.toString()}},$r=async(r,e)=>{for(let t of r){let{fn:n,message:o}=t,i=await n(e);if(!(i===void 0||i===!0))throw typeof i=="string"?new sr({message:i}):o?new sr({message:o}):new Error("Assertion failed without message")}},Ws=async(r,e,t,n=!1)=>{if(!e.currField||e.s===-1||r.length===0)return;let o=r.filter(s=>s.fieldName===e.currField?.name);if(o.length===0)return;let i=t.substring(e.s);for(let s of o){let{message:a,fn:c}=s,l=await c(i,n);if(!(l===void 0||l===!0))throw typeof l=="string"?new Rn({message:l}):new Rn({message:a??`Streaming assertion failed for field '${s.fieldName}'. Output was stopped.`})}};var iR=r=>typeof r=="object"&&r!==null,sR=r=>iR(r)&&(typeof r.data=="string"||typeof r.id=="string"),aR=r=>r.getOutputFields().filter(e=>e.type?.name==="audio"&&e.type?.isArray!==!0);async function Uo(r,e,t,n){let o=aR(e);if(o.length===0)return t;let i=n?.speech,s;for(let a of o){let c=t[a.name];if(c==null||sR(c)||typeof c!="string")continue;let l={...i?.speak??{},...i?.fields?.[a.name]??{},text:c},u=await r.speak(l,n);s??={...t},s[a.name]={...u,transcript:u.transcript??c}}return s??t}var Bg=new WeakMap;function*$l(r,e,t,n,o,i){let{name:s,isInternal:a}=e,{isArray:c,name:l}=e.type??{};if(a||c||l&&l!=="string"&&l!=="code")return;let u=o.streamedIndex[s]??0,d=u===0,p=(t<0?0:t)+u,m=r.substring(p,n);if(m.length===0)return;let g=m.replace(/\s+$/,"");o.currField?.type?.name==="code"&&(g=g.replace(/\s*```\s*$/,""));let h=d?g.trimStart():g;o.currField?.type?.name==="code"&&(h=h.replace(/^[ ]*```[a-zA-Z0-9]*\n\s*/,"")),h.length>0&&(yield{index:i,delta:{[s]:h}},o.streamedIndex[s]=u+g.length)}function*Do(r,e,t,n,o){for(let s of n.prevFields??[]){let{field:a,s:c,e:l}=s;yield*$l(e,a,c,l,n,o)}if(n.prevFields=void 0,n.inAssumedField&&!(r.getOutputFields().filter(c=>!c.isInternal).length===1)||!n.currField||n.currField.isInternal)return;yield*$l(e,n.currField,n.s,e.length,n,o);let i=cR(r);for(let s of Object.keys(t)){let a=i.get(s);if(!a||a.isInternal)continue;let c=t[s];if(Array.isArray(c)){let u=n.streamedIndex?.[s]??0,d=c.slice(u);d&&d.length>0&&(yield{index:o,delta:{[s]:d}},n.streamedIndex[s]=u+d.length);continue}let l=typeof c=="string"?c:void 0;if(!n.streamedIndex[s])yield{index:o,delta:{[s]:c}},n.streamedIndex[s]=l?l.length:1;else if(l){let u=n.streamedIndex[s];if(l.length>u){let d=l.substring(u);yield{index:o,delta:{[s]:d}},n.streamedIndex[s]=l.length}}}}function cR(r){let e=r.hash(),t=Bg.get(r);if(t?.hash===e)return t.fieldMap;let n=new Map(r.getOutputFields().map(o=>[o.name,o]));return Bg.set(r,{hash:e,fieldMap:n}),n}function Gn(r,e){if(typeof r!="string")throw ol(e,String(r),"URL must be a string");try{new URL(r)}catch{throw ol(e,r,"Invalid URL format. Expected a valid URL like https://example.com")}}function Jt(r,e){if(typeof r!="string")return;let t=e.type;if(t){if(t.minLength!==void 0&&r.length<t.minLength)throw Pr(e,r,"minLength",t.minLength);if(t.maxLength!==void 0&&r.length>t.maxLength)throw Pr(e,r,"maxLength",t.maxLength);if(t.pattern!==void 0&&!new RegExp(t.pattern).test(r))throw Pr(e,r,"pattern",t.pattern);if(t.format==="email"&&!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r))throw Pr(e,r,"format","valid email address");if(t.format==="uri"||t.format==="url")try{new URL(r)}catch{throw Pr(e,r,"format","valid URL")}}}function Yt(r,e){if(typeof r!="number")return;let t=e.type;if(t){if(t.minimum!==void 0&&r<t.minimum)throw il(e,r,"minimum",t.minimum);if(t.maximum!==void 0&&r>t.maximum)throw il(e,r,"maximum",t.maximum)}}var zg=(r,e,t=!1)=>{switch(r.type?.name){case"code":return Js(String(e));case"string":return typeof e=="string"?e:String(e);case"number":{let n=Number(e);if(Number.isNaN(n)){if(r.isOptional&&!t)return;throw new Error("Invalid number")}return n}case"boolean":{if(typeof e=="boolean")return e;let n=String(e).toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(r.isOptional&&!t)return;throw new Error("Invalid boolean")}case"date":return cg(r,String(e),t);case"dateRange":return mg(r,e,t);case"datetime":return gg(r,String(e),t);case"datetimeRange":return hg(r,e,t);case"class":{let n=String(e);if(r.type.options&&!r.type.options.includes(n)){if(r.isOptional)return;throw new Error(`Invalid class '${e}', expected one of the following: ${r.type.options.join(", ")}`)}return n}default:return e}};function Ur(r,e){if(!e||e===""||/^(null|undefined)\s*$/i.test(e)){if(r.isOptional)return;throw wo(r)}let t;if(r.type?.name==="json"&&!r.type?.isArray)try{let o=Js(e);return t=JSON.parse(o),t}catch(o){if(r.schema)return So(r.schema,r.name,e);throw ws(r,o.message)}if(r.type?.isArray)try{try{t=JSON.parse(e)}catch{t=qm(e)}if(!Array.isArray(t))throw new Error("Expected an array")}catch(o){let i=o.message;if(i.includes("no valid list items found")||i==="Expected an array")t=[e];else throw Em(r,i)}try{if(Array.isArray(t)){for(let[o,i]of t.entries())if(i!==void 0){let s=typeof i=="string"?i.trim():i;if(typeof s=="string"&&(r.type?.name==="object"||r.type?.name==="json"))try{let a=Js(s);s=JSON.parse(a)}catch{}t[o]=zg(r,s,!0)}}else t=zg(r,e)}catch(o){throw Om(r,e,o.message)}if(typeof t=="string"&&t==="")return;let n=r.type;if(n&&t!==void 0&&(n.name==="url"&&!n.isArray&&Gn(t,r),(n.name==="string"||n.name==="code")&&Jt(t,r),n.name==="number"&&Yt(t,r),n.isArray&&Array.isArray(t)))for(let o of t)o!==void 0&&(n.name==="url"?Gn(o,r):n.name==="string"||n.name==="code"?Jt(o,r):n.name==="number"&&Yt(o,r));return r.schema&&t!==void 0&&(t=So(r.schema,r.name,t)),t}var Js=r=>{let t=/```([A-Za-z]*)\s*([\s\S]*?)\s*```/g.exec(r);return t?t.length===3?t[2]:t.length===2?t[1]:r:r};var jo=(r,e,t,n)=>{let o=n?.strictMode??!1,i=n?.treatAllFieldsOptional??!1,s=n?.treatAllFieldsOptional??!1,a={extractedFields:[],streamedIndex:{},s:-1};Ys(r,e,a,t,{strictMode:o,skipEarlyFail:s,treatAllFieldsOptional:i}),Qs(r,e,a,t,{strictMode:o,treatAllFieldsOptional:i,forceFinalize:!0});for(let c of r.getOutputFields())c.isInternal&&delete e[c.name]},Ul=(r,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 Mm(n)},Ys=(r,e,t,n,{strictMode:o,skipEarlyFail:i}={})=>{let s=r.getOutputFields(),a;for(;;){let c=new Set;t.currFieldIndex!==void 0&&!t.inAssumedField&&c.add(t.currFieldIndex);let l=s.map((g,h)=>({field:g,index:h})).filter(({index:g})=>!c.has(g)),u,d,p=-1,m=0;for(let{index:g,field:h}of l){let f=`${(t.extractedFields.length===0?"":`
|
|
369
369
|
`)+h.title}:`,y=Vm(n,f,t.s);if(y===-2||y===-3||y===-4)return!0;y>=0&&(p===-1||y<p)&&(p=y,m=f.length,u=g,d=h)}if(p===-1){if(i)return;if(!o&&t.currField===void 0&&t.extractedFields.length===0&&s.length===1){t.inAssumedField=!0,t.currField=s[0],t.currFieldIndex=0,t.s=0,t.extractedFields.includes(s[0])||t.extractedFields.push(s[0]),t.streamedIndex[s[0].name]===void 0&&(t.streamedIndex[s[0].name]=0);return}if(o&&t.currField===void 0&&t.extractedFields.length===0){let g=s.find(h=>!h.isOptional);if(g)throw Rs(g)}break}if(a&&d&&a.name!==d.name)throw Rs(a);if(t.currField!==void 0&&t.inAssumedField&&(t.inAssumedField=!1,t.streamedIndex[t.currField.name]=0,t.currField=void 0),t.currField){let g=n.substring(t.s,p).trim(),h=Ur(t.currField,g);h!==void 0&&(e[t.currField.name]=h),t.prevFields?t.prevFields?.push({field:t.currField,s:t.s,e:p}):t.prevFields=[{field:t.currField,s:t.s,e:p}]}t.s=p+m,d!==void 0&&u!==void 0&&(t.currField=d,t.currFieldIndex=u),d&&!t.extractedFields.includes(d)&&t.extractedFields.push(d),d&&t.streamedIndex[d.name]===void 0&&(t.streamedIndex[d.name]=0)}},Qs=(r,e,t,n,o)=>{let i=o?.strictMode??!1,s=o?.treatAllFieldsOptional??!1,a=o?.deferRequiredCheckForStreaming??!1,c=o?.forceFinalize??!1;if(t.currField){let l=n.length,u=r.getOutputFields();for(let m of u){if(m.name===t.currField.name)continue;let g=`
|
|
370
370
|
${m.title}:`,h=n.indexOf(g,t.s);h!==-1&&h<l&&(l=h)}let d=n.substring(t.s,l).trim(),p=Ur(t.currField,d);p!==void 0&&(e[t.currField.name]=p)}if(i&&!t.currField&&t.extractedFields.length===0&&n.trim()){let u=r.getOutputFields().find(d=>!d.isOptional);if(u)throw Rs(u)}if(lR(r,e,n),!s){let l=t.currField!==void 0||(t.extractedFields?.length??0)>0;i||c?Ul(t,e,r.getOutputFields()):l||Ul(t,e,r.getOutputFields())}},lR=(r,e,t)=>{let n=r.getOutputFields();if(n.length===1){let i=n[0];if(i){let s=`${i.title}:`,a=t.indexOf(s);if(a!==-1){let c=a+s.length,l=`
|
|
371
371
|
${i.title}:`,u=t.indexOf(l,c),d=t.substring(c,u===-1?t.length:u).trim();if(d)try{let p=Ur(i,d);if(p!==void 0){e[i.name]=p;return}}catch{}}}}let o=t.split(`
|
|
@@ -391,12 +391,12 @@ ${JSON.stringify(c)}
|
|
|
391
391
|
`),e.content&&(t+=e.content),e.functionCalls?.length)for(let n of e.functionCalls){let o={name:n.function.name,arguments:n.function.params??{}};t+=`
|
|
392
392
|
<tool_call>
|
|
393
393
|
${JSON.stringify(o)}
|
|
394
|
-
</tool_call>`}return{role:"assistant",content:t.trim()}}async forwardSendRequest({ai:e,values:t,mem:n,options:o,traceContext:i,functions:s,functionCall:a,stepIndex:c,preRenderedPrompt:l}){let{sessionId:u,promptCacheKey:d,model:p,rateLimiter:m,stream:g,thinkingTokenBudget:h,showThoughts:x}=o??{},f=await Wl(n,u,{resultPicker:o?.resultPicker}),{prompt:y,promptMetrics:A}=l??await this.renderPromptWithMetricsForInternalUse(e,t,{...o,sessionId:u},s),b=n?.history(f,u)??y;if(b!==y&&b.length>0&&y.length>0){let D=y.find(j=>j.role==="system");if(D){let j=b.findIndex(J=>J.role==="system");j!==-1&&(b[j]=D)}}if(b.length===0)throw new Error("No chat prompt found");let w={...o?.modelConfig,...o?.sampleCount?{n:o.sampleCount}:{},...o?.sampleCount&&o?.modelConfig?.temperature===1?{temperature:.8}:{}},v=this.isDebug(e,o),F=c===0,k=this.getLogger(e,o),O=v?(()=>{if(!A){let B=Je(b.filter(K=>K.role!=="system"));return{systemPromptCharacters:Je(b.filter(K=>K.role==="system")),exampleChatContextCharacters:0,mutableChatContextCharacters:B,chatContextCharacters:B,totalPromptCharacters:Je(b)}}let D=b.slice(y.length),j=Je(D),J=A.mutableChatContextCharacters+j,z=A.exampleChatContextCharacters+J;return{systemPromptCharacters:A.systemPromptCharacters,exampleChatContextCharacters:A.exampleChatContextCharacters,mutableChatContextCharacters:J,chatContextCharacters:z,totalPromptCharacters:A.systemPromptCharacters+z}})():void 0,$={},N=s.filter(D=>D.name!==vn);s=this.signatureToolCallingManager?[]:s;let V,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(p)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${p}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);V={type:"json_schema",schema:{name:"output",strict:!0,schema:Kt(I,"Schema",{flexibleJsonFieldsAsString:!0,strictStructuredOutputs:!0})}}}let S=this.getEffectiveContextCache(e,o),H=S?.cacheBreakpoint??"after-examples",L=e.getFeatures?.(p)?.caching?.cacheBreakpoints===!1,W=!!S&&e.getName()==="GoogleGeminiAI"&&e.getFeatures?.(p)?.caching?.supported===!0,U=S&&(W||L||H==="after-functions"||H==="after-examples"),Y=s?.length&&U?s.map((D,j)=>({...D,cache:j===s.length-1})):s,C=await e.chat({chatPrompt:b,functions:Y,functionCall:a,modelConfig:w,model:p,responseFormat:V},{sessionId:u,promptCacheKey:d??this.options?.promptCacheKey,rateLimiter:m,stream:g,debug:v,debugHideSystemPrompt:o?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!F,thinkingTokenBudget:h,showThoughts:x,traceContext:i,abortSignal:Ye(o?.abortSignal,fe.abortSignal),stepIndex:c,logger:k,functionCallMode:o?.functionCallMode??this.options?.functionCallMode??"auto",contextCache:S,retry:o?.retry??this.options?.retry,customLabels:o?.customLabels,usageContext:Fo(this.options?.usageContext,o?.usageContext)});C instanceof ReadableStream?C=C.pipeThrough(new TransformStream({transform:(j,J)=>{this.captureChatResponseLogMetadata($,j),J.enqueue(j)}})):this.captureChatResponseLogMetadata($,C);let T=this.normalizeChatMessages(b,N),E=String(p??e.getLastUsedChatModel?.()??"");if(C instanceof ReadableStream)this.chatLog.push({model:E,messages:T,...$});else{for(let D of C.results)T.push(this.buildAssistantLogMessage(D));this.chatLog.push({model:E,messages:T,...$,modelUsage:C.modelUsage})}return{res:C,debugPromptMetrics:O,responseMetadata:$}}async*forwardCore({ai:e,values:t,mem:n,options:o,stepIndex:i,span:s,traceContext:a,states:c,stopFunctionNames:l,stepContext:u,preRenderedPrompt:d}){let{sessionId:p,functions:m}=o??{},g=o?.functionResultFormatter??this.options?.functionResultFormatter,h=o?.functionCall??this.options?.functionCall,x=this.signatureToolCallingManager,f=o?.strictMode??!1,y=o.model,A=this.usage,b=i===0,w=this.isDebug(e,o),v=this.getLogger(e,o),F=o?.tracer??this.options?.tracer??e.getOptions().tracer??fe.tracer,{functions:k,functionCall:O}=Jg(m,h,b,o);this.structuredOutputFunctionFallback&&k.filter(_=>_.name!==vn).length===0&&(O={type:"function",function:{name:vn}});let{res:$,debugPromptMetrics:N,responseMetadata:V}=await this.forwardSendRequest({ai:e,values:t,mem:n,options:o,traceContext:a,functions:k,functionCall:O,stepIndex:i,preRenderedPrompt:d});if($ instanceof ReadableStream){yield*Kl({ai:e,model:y,res:$,mem:n,sessionId:p,traceId:s?s.spanContext?.().traceId:void 0,traceContext:a,tracer:F,functions:k,strictMode:f,span:s,states:c,usage:A,streamingAsserts:this.streamingAsserts,asserts:this.asserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,parseJsonStringFields:this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback,logger:v,debugPromptMetrics:N,onFunctionCall:o.onFunctionCall,mcpExecutionContext:o._mcpExecutionContext,eventContext:o.eventContext,debug:w,functionResultFormatter:g,signatureToolCallingManager:x,stopFunctionNames:l,disableMemoryCleanup:o.disableMemoryCleanup,stepContext:u,abortSignal:o.abortSignal});let I=this.chatLog[this.chatLog.length-1];if(I){this.applyChatResponseLogMetadata(I,V);for(let _ of c)I.messages.push(this.buildAssistantLogMessage({index:_.index,content:_.content||void 0,functionCalls:_.functionCalls.length>0?_.functionCalls:void 0}));this.usage.length>0&&(I.modelUsage=this.usage[this.usage.length-1])}}else yield*Hl({ai:e,model:y,res:$,mem:n,sessionId:p,traceId:s?s.spanContext?.().traceId:void 0,traceContext:a,tracer:F,functions:k,span:s,strictMode:f,states:c,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,parseJsonStringFields:this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback,logger:v,debugPromptMetrics:N,onFunctionCall:o.onFunctionCall,mcpExecutionContext:o._mcpExecutionContext,eventContext:o.eventContext,debug:w,functionResultFormatter:g,signatureToolCallingManager:x,stopFunctionNames:l,disableMemoryCleanup:o.disableMemoryCleanup,stepContext:u,abortSignal:o.abortSignal})}async*_forward2(e,t,n,o,i,s){this.signatureToolCallingManager=void 0,this.chatLog=[];let a=o?.stopFunction??this.options?.stopFunction,c=Array.isArray(a)?a.map(K=>K.toLowerCase()):a?[a.toLowerCase()]:void 0,l=o.maxRetries??this.options?.maxRetries??3,u=o.maxSteps??this.options?.maxSteps??25,d=o.mem??this.options?.mem??new jn,p=o.functions?wn(o.functions):[...this.functions],m=o._mcpExecutionContext?.getCatalogRevision(),g=new ua(u),h;if(o.selfTuning){if(h=o.selfTuning===!0?{model:!0,thinkingBudget:!0}:o.selfTuning,h.model!==!1){let oe=e.getModelList()?.filter(se=>"model"in se);if(!oe||oe.length<2)throw new Error("Self-tuning with model selection requires the AI service to have a `models` list with at least 2 chat models. Either configure models on your AI service or disable model selection with `selfTuning: { model: false }`.")}let K=Jl(e,h,o.model?String(o.model):void 0);p.push(K)}let x={...o},f=o.stepHooks,y=p&&p.length>0,A=o.functionCallMode??this.options?.functionCallMode??"auto";y&&A==="prompt"&&(this.signatureToolCallingManager=new cr(p)),y&&A==="auto"&&!e.getFeatures(o.model).functions&&(this.signatureToolCallingManager=new cr(p));let b,w,v=this.options?.promptTemplate??ir;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let F=this.signature.hasComplexFields(),k=e.getFeatures?.(o.model),O=o.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=F&&(O==="function"||O==="auto"&&!k?.structuredOutputs),this.structuredOutputFunctionFallback){let K={name:vn,description:"Return the final result. Call this function with the complete output data.",parameters:Kt(this.signature.getOutputFields()),func:async()=>"done"};p.push(K),c=[...c??[],vn.toLowerCase()]}let $=e.getFeatures?.(o.model)?.caching?.cacheBreakpoints===!1,N=this.getEffectiveContextCache(e,o),V={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,contextCache:N,ignoreBreakpoints:$,includeOptionalInputFieldsInSystemPrompt:o.includeOptionalInputFieldsInSystemPrompt??this.options?.includeOptionalInputFieldsInSystemPrompt,structuredOutputFunctionName:this.structuredOutputFunctionFallback?vn:void 0,customTemplate:o.customTemplate??this.options?.customTemplate},I=this.getInstruction();this.promptTemplate=new v(this.signature,V),I!==void 0&&I.trim().length>0&&this.promptTemplate.setInstruction(I);let _=performance.now(),S="renderWithMetrics"in this.promptTemplate&&typeof this.promptTemplate.renderWithMetrics=="function"?this.promptTemplate.renderWithMetrics(t,{examples:this.examples,demos:this.demos}):{chatPrompt:this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})},H=S.chatPrompt,L=H.findIndex(K=>K.role!=="system"),W=L===-1?H.length:L,U=o._mcpContextPrompt?.length?[...H.slice(0,W),...o._mcpContextPrompt,...H.slice(W)]:H,Y="promptMetrics"in S?S.promptMetrics:void 0,C=performance.now()-_,T=this.getMetricsInstruments(),E=this.getMergedCustomLabels(e,o);T&&bs(T,"prompt_render",C,this.getSignatureName(),E);let D=performance.now();d.addRequest(U,o.sessionId);let j=performance.now()-D;T&&bs(T,"memory_update",j,this.getSignatureName(),E);let J=new Map;n.forEach(K=>{J.set(K.index,{})});let z=()=>{let K=g._consumePendingOptions();if(K){let{modelConfig:se,...me}=K;x={...x,...me},se&&(x.modelConfig={...x.modelConfig,...se})}let ie=g._consumeFunctionsToAdd();if(ie){let se=wn(ie);for(let me of se)p.some(Z=>Z.name===me.name)||p.push(me)}let oe=g._consumeFunctionsToRemove();if(oe){let se=new Set(oe.map(me=>me.toLowerCase()));for(let me=p.length-1;me>=0;me--)se.has(p[me].name.toLowerCase())&&p.splice(me,1)}},B=Ye(o?.abortSignal,fe.abortSignal);e:for(let K=0;K<u;K++){g._beginStep(K),z();let ie=o._mcpExecutionContext?.getCatalogRevision();if(ie!==void 0&&ie!==m){for(let se=p.length-1;se>=0;se--)p[se]?.componentId?.startsWith("mcp:")&&p.splice(se,1);p.push(...o._mcpExecutionContext.getToolBindings()),m=ie}if(h&&h.model!==!1){let se=p.findIndex(me=>me.name==="adjustGeneration");if(se!==-1){let me=x.model?String(x.model):void 0;p[se]=Jl(e,h,me)}}if(g._isStopRequested)break;if(B?.aborted)throw new Ne("between-steps",B.reason??"Aborted between steps");if(f?.beforeStep&&(await f.beforeStep(g),z(),g._isStopRequested))break;let oe=l;for(let se=0;se<=oe;se++)try{let me=l+1;for(let Be=0;Be<me;Be++){n.forEach(de=>{de.content="",de.values={},de.functionCalls=[],de.functionsExecuted=new Set,de.xstate={extractedFields:[],streamedIndex:{},s:-1},de.structuredAccumulator=void 0}),Be>0&&J.forEach((de,Ve)=>{J.set(Ve,{})});let ut=new Map;n.forEach(de=>{ut.set(de.index,{})});try{let de=this.forwardCore({options:{...x,functions:p},ai:e,values:t,mem:d,stepIndex:K,span:i,traceContext:s,states:n,stopFunctionNames:c,stepContext:g,preRenderedPrompt:K===0&&Be===0&&!f?.beforeStep?{prompt:U,promptMetrics:Y}:void 0}),Ve=!1;try{for await(let ne of de)if(ne!==void 0){let ve=ne.index,ke=ne.delta,He=ut.get(ve)??{},we=J.get(ve)??{},Ie={},Ue=!1;for(let X of Object.keys(ke)){let he=ke[X],Ce=He[X],Le;typeof he=="string"&&(typeof Ce=="string"||Ce===void 0)?Le=(Ce??"")+he:Array.isArray(he)&&(Array.isArray(Ce)||Ce===void 0)?Le=[...Ce??[],...he]:Le=he,He[X]=Le;let re=Le,De=we[X];if(typeof re=="string"&&typeof De=="string")if(re.startsWith(De)){let ye=re.slice(De.length);ye&&(Ie[X]=ye,Ue=!0,we[X]=re)}else De.startsWith(re)||re!==De&&(Ie[X]=re,Ue=!0,we[X]=re);else if(Array.isArray(re)&&Array.isArray(De)){if(re.length>De.length){let ye=re.slice(De.length);Ie[X]=ye,Ue=!0,we[X]=re}}else zo(re,De)||(Ie[X]=re,Ue=!0,we[X]=re)}Ue&&(yield{version:Be,index:ne.index,delta:Ie})}}catch(ne){if(ne instanceof Gr){if(Ve=!0,this.structuredOutputFunctionFallback){let ve=ne.calls.find(ke=>ke.func.name===vn);if(ve?.args){let ke=ve.args;Dr(this.signature,ke);let He=this.signature.getOutputFields();for(let we of n)for(let Ie of He)Ie.name in ke&&(we.values[Ie.name]=ke[Ie.name]);if(this.fieldProcessors.length>0)for(let we of n)await jr(this.fieldProcessors,we.values,d,o.sessionId);for(let we of n)await $r(this.asserts,we.values);for(let we of n){let Ie={};for(let Ue of He)Ue.name in we.values&&!Ue.isInternal&&(Ie[Ue.name]=we.values[Ue.name]);yield{version:Be,index:we.index,delta:Ie}}}}}else throw ne}if(this.usage.length>0){let ne=this.usage[this.usage.length-1];ne?.tokens&&g._addUsage(ne.tokens.promptTokens??0,ne.tokens.completionTokens??0,ne.tokens.totalTokens??0)}n.some(ne=>ne.functionsExecuted.size>0)&&f?.afterFunctionExecution&&(await f.afterFunctionExecution(g),z());let at=Ve||g._isStopRequested?!1:Bl(d,c,n,x?.sessionId);if(f?.afterStep&&(await f.afterStep(g),z()),at&&!g._isStopRequested&&!B?.aborted){let ne=this.getMetricsInstruments();ne&&Cs(ne,K+1,u,this.getSignatureName(),E);continue e}if(B?.aborted)throw new Ne("mid-step",B.reason??"Aborted");o?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",o.sessionId),d.removeByTag("correction",o.sessionId),d.removeByTag("error",o.sessionId));let dt=this.getMetricsInstruments();if(dt){Cs(dt,K+1,u,this.getSignatureName(),E);let ne=new Set;n.forEach(ve=>{ve.functionsExecuted.forEach(ke=>ne.add(ke))}),ne.size>0&&Sm(dt,!0,ne.size,!0,!1,this.getSignatureName(),E),km(dt,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),E)}return}catch(de){if(de instanceof Ne)throw de;w=de;let Ve,Ae=this.isDebug(e,o),at=this.getLogger(e,o),dt=this.getMetricsInstruments(),ne=this.getSignatureName(),ve={error:de,errCount:Be,logger:at,metricsInstruments:dt,signatureName:ne,span:i,debug:Ae,customLabels:E};if(i?.recordException(de),de instanceof xe)Ve=vs(ve),b=de;else if(de instanceof sr)Ve=vs(ve),b=de;else if(de instanceof Rn)Ve=vs(ve),b=de;else if(de instanceof Ke)$m(ve);else{if(de instanceof kt)throw de;{let ke=de,He=ke instanceof Qe&&ke.status>=500&&ke.status<600,we=ke instanceof tt,Ie=ke instanceof yt;throw He||we||Ie?de:da(de,e,this.signature)}}if(Ve&&(d.addTag("error",o.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(Ve)}],o.sessionId),d.addTag("correction",o.sessionId),this.signature.hasComplexFields()))for(let He of n)He.content="",He.values={},He.xstate={extractedFields:[],streamedIndex:{},s:-1},He.structuredAccumulator=void 0}}let Z=this.getMetricsInstruments();throw Z&&rl(Z,l,!1,l,this.getSignatureName(),E),b instanceof Rn?da(b,e,this.signature):da(new Error(`Unable to fix validation error: ${(b??w)?.message??(b??w)?.toString()??"unknown error"}
|
|
394
|
+
</tool_call>`}return{role:"assistant",content:t.trim()}}async forwardSendRequest({ai:e,values:t,mem:n,options:o,traceContext:i,functions:s,functionCall:a,stepIndex:c,preRenderedPrompt:l}){let{sessionId:u,promptCacheKey:d,model:p,rateLimiter:m,stream:g,thinkingTokenBudget:h,showThoughts:x}=o??{},f=await Wl(n,u,{resultPicker:o?.resultPicker}),{prompt:y,promptMetrics:A}=l??await this.renderPromptWithMetricsForInternalUse(e,t,{...o,sessionId:u},s),b=n?.history(f,u)??y;if(b!==y&&b.length>0&&y.length>0){let D=y.find(j=>j.role==="system");if(D){let j=b.findIndex(J=>J.role==="system");j!==-1&&(b[j]=D)}}if(b.length===0)throw new Error("No chat prompt found");let w={...o?.modelConfig,...o?.sampleCount?{n:o.sampleCount}:{},...o?.sampleCount&&o?.modelConfig?.temperature===1?{temperature:.8}:{}},v=this.isDebug(e,o),F=c===0,k=this.getLogger(e,o),O=v?(()=>{if(!A){let B=Je(b.filter(K=>K.role!=="system"));return{systemPromptCharacters:Je(b.filter(K=>K.role==="system")),exampleChatContextCharacters:0,mutableChatContextCharacters:B,chatContextCharacters:B,totalPromptCharacters:Je(b)}}let D=b.slice(y.length),j=Je(D),J=A.mutableChatContextCharacters+j,z=A.exampleChatContextCharacters+J;return{systemPromptCharacters:A.systemPromptCharacters,exampleChatContextCharacters:A.exampleChatContextCharacters,mutableChatContextCharacters:J,chatContextCharacters:z,totalPromptCharacters:A.systemPromptCharacters+z}})():void 0,$={},N=s.filter(D=>D.name!==vn);s=this.signatureToolCallingManager?[]:s;let V,I=this.signature.getOutputFields();if(this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback){if(!e.getFeatures(p)?.structuredOutputs)throw new Error(`Complex structured outputs (object/array types) require a provider that supports structured outputs. Current provider/model (${p}) does not support this feature. Supported providers: OpenAI (GPT-4o, GPT-4.1+), Google Gemini, Anthropic (Sonnet/Opus).`);V={type:"json_schema",schema:{name:"output",strict:!0,schema:Kt(I,"Schema",{flexibleJsonFieldsAsString:!0,strictStructuredOutputs:!0})}}}let S=this.getEffectiveContextCache(e,o),H=S?.cacheBreakpoint??"after-examples",L=e.getFeatures?.(p)?.caching?.cacheBreakpoints===!1,W=!!S&&e.getName()==="GoogleGeminiAI"&&e.getFeatures?.(p)?.caching?.supported===!0,U=S&&(W||L||H==="after-functions"||H==="after-examples"),Y=s?.length&&U?s.map((D,j)=>({...D,cache:j===s.length-1})):s,C=await e.chat({chatPrompt:b,functions:Y,functionCall:a,modelConfig:w,model:p,responseFormat:V},{sessionId:u,promptCacheKey:d??this.options?.promptCacheKey,rateLimiter:m,stream:g,debug:v,debugHideSystemPrompt:o?.debugHideSystemPrompt??this.options?.debugHideSystemPrompt??!F,thinkingTokenBudget:h,showThoughts:x,traceContext:i,abortSignal:Ye(o?.abortSignal,fe.abortSignal),stepIndex:c,logger:k,functionCallMode:o?.functionCallMode??this.options?.functionCallMode??"auto",contextCache:S,retry:o?.retry??this.options?.retry,customLabels:o?.customLabels,usageContext:Fo(this.options?.usageContext,o?.usageContext)});C instanceof ReadableStream?C=C.pipeThrough(new TransformStream({transform:(j,J)=>{this.captureChatResponseLogMetadata($,j),J.enqueue(j)}})):this.captureChatResponseLogMetadata($,C);let T=this.normalizeChatMessages(b,N),E=String(p??e.getLastUsedChatModel?.()??"");if(C instanceof ReadableStream)this.chatLog.push({model:E,messages:T,...$});else{for(let D of C.results)T.push(this.buildAssistantLogMessage(D));this.chatLog.push({model:E,messages:T,...$,modelUsage:C.modelUsage})}return{res:C,debugPromptMetrics:O,responseMetadata:$}}async*forwardCore({ai:e,values:t,mem:n,options:o,stepIndex:i,span:s,traceContext:a,states:c,stopFunctionNames:l,stepContext:u,preRenderedPrompt:d}){let{sessionId:p,functions:m}=o??{},g=o?.functionResultFormatter??this.options?.functionResultFormatter,h=o?.functionCall??this.options?.functionCall,x=this.signatureToolCallingManager,f=o?.strictMode??!1,y=o.model,A=this.usage,b=i===0,w=this.isDebug(e,o),v=this.getLogger(e,o),F=o?.tracer??this.options?.tracer??e.getOptions().tracer??fe.tracer,{functions:k,functionCall:O}=Jg(m,h,b,o);this.structuredOutputFunctionFallback&&k.filter(_=>_.name!==vn).length===0&&(O={type:"function",function:{name:vn}});let{res:$,debugPromptMetrics:N,responseMetadata:V}=await this.forwardSendRequest({ai:e,values:t,mem:n,options:o,traceContext:a,functions:k,functionCall:O,stepIndex:i,preRenderedPrompt:d});if($ instanceof ReadableStream){yield*Kl({ai:e,model:y,res:$,mem:n,sessionId:p,traceId:s?s.spanContext?.().traceId:void 0,traceContext:a,tracer:F,functions:k,strictMode:f,span:s,states:c,usage:A,streamingAsserts:this.streamingAsserts,asserts:this.asserts,fieldProcessors:this.fieldProcessors,streamingFieldProcessors:this.streamingFieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,parseJsonStringFields:this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback,logger:v,debugPromptMetrics:N,onFunctionCall:o.onFunctionCall,mcpExecutionContext:o._mcpExecutionContext,eventContext:o.eventContext,debug:w,functionResultFormatter:g,signatureToolCallingManager:x,stopFunctionNames:l,disableMemoryCleanup:o.disableMemoryCleanup,stepContext:u,abortSignal:o.abortSignal});let I=this.chatLog[this.chatLog.length-1];if(I){this.applyChatResponseLogMetadata(I,V);for(let _ of c)I.messages.push(this.buildAssistantLogMessage({index:_.index,content:_.content||void 0,functionCalls:_.functionCalls.length>0?_.functionCalls:void 0}));this.usage.length>0&&(I.modelUsage=this.usage[this.usage.length-1])}}else yield*Hl({ai:e,model:y,res:$,mem:n,sessionId:p,traceId:s?s.spanContext?.().traceId:void 0,traceContext:a,tracer:F,functions:k,span:s,strictMode:f,states:c,usage:A,asserts:this.asserts,fieldProcessors:this.fieldProcessors,thoughtFieldName:this.thoughtFieldName,excludeContentFromTrace:this.excludeContentFromTrace,signature:this.signature,parseJsonStringFields:this.signature.hasComplexFields()&&!this.structuredOutputFunctionFallback,logger:v,debugPromptMetrics:N,onFunctionCall:o.onFunctionCall,mcpExecutionContext:o._mcpExecutionContext,eventContext:o.eventContext,debug:w,functionResultFormatter:g,signatureToolCallingManager:x,stopFunctionNames:l,disableMemoryCleanup:o.disableMemoryCleanup,stepContext:u,abortSignal:o.abortSignal})}async*_forward2(e,t,n,o,i,s){this.signatureToolCallingManager=void 0,this.chatLog=[];let a=o?.stopFunction??this.options?.stopFunction,c=Array.isArray(a)?a.map(K=>K.toLowerCase()):a?[a.toLowerCase()]:void 0,l=o.maxRetries??this.options?.maxRetries??3,u=o.maxSteps??this.options?.maxSteps??25,d=o.mem??this.options?.mem??new jn,p=o.functions?wn(o.functions):[...this.functions],m=o._mcpExecutionContext?.getCatalogRevision(),g=new ua(u),h;if(o.selfTuning){if(h=o.selfTuning===!0?{model:!0,thinkingBudget:!0}:o.selfTuning,h.model!==!1){let oe=e.getModelList()?.filter(se=>"model"in se);if(!oe||oe.length<2)throw new Error("Self-tuning with model selection requires the AI service to have a `models` list with at least 2 chat models. Either configure models on your AI service or disable model selection with `selfTuning: { model: false }`.")}let K=Jl(e,h,o.model?String(o.model):void 0);p.push(K)}let x={...o},f=o.stepHooks,y=p&&p.length>0,A=o.functionCallMode??this.options?.functionCallMode??"auto";y&&A==="prompt"&&(this.signatureToolCallingManager=new cr(p)),y&&A==="auto"&&!e.getFeatures(o.model).functions&&(this.signatureToolCallingManager=new cr(p));let b,w,v=this.options?.promptTemplate??ir;this.signatureToolCallingManager&&(this.signature=this.signatureToolCallingManager.processSignature(this.signature),this.setSignature(this.signature));let F=this.signature.hasComplexFields(),k=e.getFeatures?.(o.model),O=o.structuredOutputMode??this.options?.structuredOutputMode??"auto";if(this.structuredOutputFunctionFallback=F&&(O==="function"||O==="auto"&&!k?.structuredOutputs),this.structuredOutputFunctionFallback){let K={name:vn,description:"Return the final result. Call this function with the complete output data.",parameters:Kt(this.signature.getOutputFields()),func:async()=>"done"};p.push(K),c=[...c??[],vn.toLowerCase()]}let $=e.getFeatures?.(o.model)?.caching?.cacheBreakpoints===!1,N=this.getEffectiveContextCache(e,o),V={functions:this.signatureToolCallingManager?[]:p,thoughtFieldName:this.thoughtFieldName,contextCache:N,ignoreBreakpoints:$,includeOptionalInputFieldsInSystemPrompt:o.includeOptionalInputFieldsInSystemPrompt??this.options?.includeOptionalInputFieldsInSystemPrompt,structuredOutputFunctionName:this.structuredOutputFunctionFallback?vn:void 0,customTemplate:o.customTemplate??this.options?.customTemplate},I=this.getInstruction();this.promptTemplate=new v(this.signature,V),I!==void 0&&I.trim().length>0&&this.promptTemplate.setInstruction(I);let _=performance.now(),S="renderWithMetrics"in this.promptTemplate&&typeof this.promptTemplate.renderWithMetrics=="function"?this.promptTemplate.renderWithMetrics(t,{examples:this.examples,demos:this.demos}):{chatPrompt:this.promptTemplate.render(t,{examples:this.examples,demos:this.demos})},H=S.chatPrompt,L=H.findIndex(K=>K.role!=="system"),W=L===-1?H.length:L,U=o._mcpContextPrompt?.length?[...H.slice(0,W),...o._mcpContextPrompt,...H.slice(W)]:H,Y="promptMetrics"in S?S.promptMetrics:void 0,C=performance.now()-_,T=this.getMetricsInstruments(),E=this.getMergedCustomLabels(e,o);T&&bs(T,"prompt_render",C,this.getSignatureName(),E);let D=performance.now();d.addRequest(U,o.sessionId);let j=performance.now()-D;T&&bs(T,"memory_update",j,this.getSignatureName(),E);let J=new Map;n.forEach(K=>{J.set(K.index,{})});let z=()=>{let K=g._consumePendingOptions();if(K){let{modelConfig:se,...me}=K;x={...x,...me},se&&(x.modelConfig={...x.modelConfig,...se})}let ie=g._consumeFunctionsToAdd();if(ie){let se=wn(ie);for(let me of se)p.some(Z=>Z.name===me.name)||p.push(me)}let oe=g._consumeFunctionsToRemove();if(oe){let se=new Set(oe.map(me=>me.toLowerCase()));for(let me=p.length-1;me>=0;me--)se.has(p[me].name.toLowerCase())&&p.splice(me,1)}},B=Ye(o?.abortSignal,fe.abortSignal);e:for(let K=0;K<u;K++){g._beginStep(K),z();let ie=o._mcpExecutionContext?.getCatalogRevision();if(ie!==void 0&&ie!==m){for(let se=p.length-1;se>=0;se--)p[se]?.componentId?.startsWith("mcp:")&&p.splice(se,1);p.push(...o._mcpExecutionContext.getToolBindings()),m=ie}if(h&&h.model!==!1){let se=p.findIndex(me=>me.name==="adjustGeneration");if(se!==-1){let me=x.model?String(x.model):void 0;p[se]=Jl(e,h,me)}}if(g._isStopRequested)break;if(B?.aborted)throw new _e("between-steps",B.reason??"Aborted between steps");if(f?.beforeStep&&(await f.beforeStep(g),z(),g._isStopRequested))break;let oe=l;for(let se=0;se<=oe;se++)try{let me=l+1;for(let Be=0;Be<me;Be++){n.forEach(de=>{de.content="",de.values={},de.functionCalls=[],de.functionsExecuted=new Set,de.xstate={extractedFields:[],streamedIndex:{},s:-1},de.structuredAccumulator=void 0}),Be>0&&J.forEach((de,Ve)=>{J.set(Ve,{})});let ut=new Map;n.forEach(de=>{ut.set(de.index,{})});try{let de=this.forwardCore({options:{...x,functions:p},ai:e,values:t,mem:d,stepIndex:K,span:i,traceContext:s,states:n,stopFunctionNames:c,stepContext:g,preRenderedPrompt:K===0&&Be===0&&!f?.beforeStep?{prompt:U,promptMetrics:Y}:void 0}),Ve=!1;try{for await(let ne of de)if(ne!==void 0){let ve=ne.index,ke=ne.delta,He=ut.get(ve)??{},we=J.get(ve)??{},Ie={},Ue=!1;for(let X of Object.keys(ke)){let he=ke[X],Ce=He[X],Le;typeof he=="string"&&(typeof Ce=="string"||Ce===void 0)?Le=(Ce??"")+he:Array.isArray(he)&&(Array.isArray(Ce)||Ce===void 0)?Le=[...Ce??[],...he]:Le=he,He[X]=Le;let re=Le,De=we[X];if(typeof re=="string"&&typeof De=="string")if(re.startsWith(De)){let ye=re.slice(De.length);ye&&(Ie[X]=ye,Ue=!0,we[X]=re)}else De.startsWith(re)||re!==De&&(Ie[X]=re,Ue=!0,we[X]=re);else if(Array.isArray(re)&&Array.isArray(De)){if(re.length>De.length){let ye=re.slice(De.length);Ie[X]=ye,Ue=!0,we[X]=re}}else zo(re,De)||(Ie[X]=re,Ue=!0,we[X]=re)}Ue&&(yield{version:Be,index:ne.index,delta:Ie})}}catch(ne){if(ne instanceof Gr){if(Ve=!0,this.structuredOutputFunctionFallback){let ve=ne.calls.find(ke=>ke.func.name===vn);if(ve?.args){let ke=ve.args;Dr(this.signature,ke);let He=this.signature.getOutputFields();for(let we of n)for(let Ie of He)Ie.name in ke&&(we.values[Ie.name]=ke[Ie.name]);if(this.fieldProcessors.length>0)for(let we of n)await jr(this.fieldProcessors,we.values,d,o.sessionId);for(let we of n)await $r(this.asserts,we.values);for(let we of n){let Ie={};for(let Ue of He)Ue.name in we.values&&!Ue.isInternal&&(Ie[Ue.name]=we.values[Ue.name]);yield{version:Be,index:we.index,delta:Ie}}}}}else throw ne}if(this.usage.length>0){let ne=this.usage[this.usage.length-1];ne?.tokens&&g._addUsage(ne.tokens.promptTokens??0,ne.tokens.completionTokens??0,ne.tokens.totalTokens??0)}n.some(ne=>ne.functionsExecuted.size>0)&&f?.afterFunctionExecution&&(await f.afterFunctionExecution(g),z());let at=Ve||g._isStopRequested?!1:Bl(d,c,n,x?.sessionId);if(f?.afterStep&&(await f.afterStep(g),z()),at&&!g._isStopRequested&&!B?.aborted){let ne=this.getMetricsInstruments();ne&&Cs(ne,K+1,u,this.getSignatureName(),E);continue e}if(B?.aborted)throw new _e("mid-step",B.reason??"Aborted");o?.disableMemoryCleanup||(d.removeByTag("invalid-assistant",o.sessionId),d.removeByTag("correction",o.sessionId),d.removeByTag("error",o.sessionId));let dt=this.getMetricsInstruments();if(dt){Cs(dt,K+1,u,this.getSignatureName(),E);let ne=new Set;n.forEach(ve=>{ve.functionsExecuted.forEach(ke=>ne.add(ke))}),ne.size>0&&Sm(dt,!0,ne.size,!0,!1,this.getSignatureName(),E),km(dt,this.fieldProcessors.length,this.streamingFieldProcessors.length,this.getSignatureName(),E)}return}catch(de){if(de instanceof _e)throw de;w=de;let Ve,Ae=this.isDebug(e,o),at=this.getLogger(e,o),dt=this.getMetricsInstruments(),ne=this.getSignatureName(),ve={error:de,errCount:Be,logger:at,metricsInstruments:dt,signatureName:ne,span:i,debug:Ae,customLabels:E};if(i?.recordException(de),de instanceof xe)Ve=vs(ve),b=de;else if(de instanceof sr)Ve=vs(ve),b=de;else if(de instanceof Rn)Ve=vs(ve),b=de;else if(de instanceof Ke)$m(ve);else{if(de instanceof kt)throw de;{let ke=de,He=ke instanceof Qe&&ke.status>=500&&ke.status<600,we=ke instanceof tt,Ie=ke instanceof yt;throw He||we||Ie?de:da(de,e,this.signature)}}if(Ve&&(d.addTag("error",o.sessionId),d.addRequest([{role:"user",content:this.promptTemplate.renderExtraFields(Ve)}],o.sessionId),d.addTag("correction",o.sessionId),this.signature.hasComplexFields()))for(let He of n)He.content="",He.values={},He.xstate={extractedFields:[],streamedIndex:{},s:-1},He.structuredAccumulator=void 0}}let Z=this.getMetricsInstruments();throw Z&&rl(Z,l,!1,l,this.getSignatureName(),E),b instanceof Rn?da(b,e,this.signature):da(new Error(`Unable to fix validation error: ${(b??w)?.message??(b??w)?.toString()??"unknown error"}
|
|
395
395
|
|
|
396
396
|
LLM Output:
|
|
397
397
|
${n.map(Be=>Be.content).join(`
|
|
398
398
|
---
|
|
399
|
-
`)}`),e,this.signature)}catch(me){let Z=me,Be=Z instanceof Qe&&Z.status>=500&&Z.status<600,ut=Z instanceof tt,de=Z instanceof yt,Ve=Z instanceof kt;if((Be||ut||de||Ve)&&se<oe){let at=this.isDebug(e,o),dt=this.getLogger(e,o),ke=Math.min(6e4,1e3*Math.pow(2,se));at&&dt&&dt({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${se+1}/${oe+1}): ${Z.message}. Retrying in ${ke}ms...`}),i?.addEvent("infrastructure.retry",{attempt:se+1,maxRetries:oe,delay:ke,errorType:Z instanceof Qe?"status_error":Z instanceof tt?"network_error":Z instanceof yt?"timeout_error":"stream_terminated",errorMessage:Z.message}),await new Promise((He,we)=>{let Ie=!1,Ue,X=()=>{B&&Ue&&B.removeEventListener("abort",Ue)},Ce=setTimeout(()=>{Ie||(Ie=!0,X(),He())},ke);if(B){if(Ue=()=>{Ie||(Ie=!0,clearTimeout(Ce),X(),we(new
|
|
399
|
+
`)}`),e,this.signature)}catch(me){let Z=me,Be=Z instanceof Qe&&Z.status>=500&&Z.status<600,ut=Z instanceof tt,de=Z instanceof yt,Ve=Z instanceof kt;if((Be||ut||de||Ve)&&se<oe){let at=this.isDebug(e,o),dt=this.getLogger(e,o),ke=Math.min(6e4,1e3*Math.pow(2,se));at&&dt&&dt({name:"Notification",id:"infrastructure-retry",value:`Infrastructure error (attempt ${se+1}/${oe+1}): ${Z.message}. Retrying in ${ke}ms...`}),i?.addEvent("infrastructure.retry",{attempt:se+1,maxRetries:oe,delay:ke,errorType:Z instanceof Qe?"status_error":Z instanceof tt?"network_error":Z instanceof yt?"timeout_error":"stream_terminated",errorMessage:Z.message}),await new Promise((He,we)=>{let Ie=!1,Ue,X=()=>{B&&Ue&&B.removeEventListener("abort",Ue)},Ce=setTimeout(()=>{Ie||(Ie=!0,X(),He())},ke);if(B){if(Ue=()=>{Ie||(Ie=!0,clearTimeout(Ce),X(),we(new _e("infrastructure-retry-backoff",B.reason?String(B.reason):"Aborted during retry backoff")))},B.aborted){Ue();return}B.addEventListener("abort",Ue,{once:!0})}});continue}throw me}}throw T&&Cs(T,u,u,this.getSignatureName(),E),da(new Error(`Max steps reached: ${u}`),e,this.signature)}validateInputs(e){let t=this.signature.getInputFields();for(let n of t){if(n.isInternal)continue;let o=e[n.name];if(n.isOptional&&o===void 0)continue;let i=n.type;if(i&&(i.name==="url"&&Gn(o,n),i.name,i.name,(i.name==="string"||i.name==="code")&&Jt(o,n),i.name==="number"&&Yt(o,n),i.name==="object"&&i.fields&&typeof o=="object"&&o!==null&&this.validateObjectFields(o,i.fields,n.name),i.isArray&&Array.isArray(o)))for(let s=0;s<o.length;s++){let a=o[s];i.name==="string"||i.name==="code"?Jt(a,n):i.name==="number"?Yt(a,n):i.fields&&typeof a=="object"&&a!==null&&this.validateObjectFields(a,i.fields,`${n.name}[${s}]`)}}}validateObjectFields(e,t,n){for(let[o,i]of Object.entries(t)){let s=e[o];if(i.isOptional&&s===void 0)continue;let a={name:`${n}.${o}`,type:{name:i.type,isArray:i.isArray,options:i.options?[...i.options]:void 0,fields:i.fields,minLength:i.minLength,maxLength:i.maxLength,minimum:i.minimum,maximum:i.maximum,pattern:i.pattern,format:i.format},description:i.description,isOptional:i.isOptional};if(i.type==="string"||i.type==="code"?Jt(s,a):i.type==="number"?Yt(s,a):i.type==="object"&&i.fields&&typeof s=="object"&&s!==null&&this.validateObjectFields(s,i.fields,a.name),i.isArray&&Array.isArray(s))for(let c=0;c<s.length;c++){let l=s[c];i.type==="string"||i.type==="code"?Jt(l,a):i.type==="number"?Yt(l,a):i.fields&&typeof l=="object"&&l!==null&&this.validateObjectFields(l,i.fields,`${a.name}[${c}]`)}}}async*_forward1(e,t,n){this.validateInputs(t);let o=new AbortController;this.activeAbortControllers.add(o),this._stopRequested&&o.abort("Stopped by user (pre-forward)");let i=Ye(o.signal,Ye(n?.abortSignal,fe.abortSignal)),s=i?{...n,abortSignal:i}:n;try{let a=performance.now(),c=this.createStates(n.sampleCount??1),l=performance.now()-a,u=this.getMetricsInstruments(),d=this.getMergedCustomLabels(e,n);u&&bs(u,"state_creation",l,this.getSignatureName(),d);let p=n?.tracer??this.options?.tracer??e.getOptions().tracer??fe.tracer,m=this.functions;n?.functions&&(m=wn(n.functions,this.functions));let g=await Lt(n,this.options);g&&(m=[...m??[],...g.getToolBindings()]);let h=g?await g.resolveContextPrompt(n.mcpContext??this.options?.mcpContext):void 0,x=g?{...s,_mcpExecutionContext:g,...h?.length?{_mcpContextPrompt:h}:{}}:s;if(!p){yield*this._forward2(e,t,c,{...x,functions:m});return}let f=m?.map(k=>k.name).join(","),y={signature:JSON.stringify(this.signature.toJSON(),null,2),...this.examples?{examples:JSON.stringify(this.examples,null,2)}:{},...f?{provided_functions:f}:{},...n?.model?{model:n.model}:{},...n?.thinkingTokenBudget?{thinking_token_budget:n.thinkingTokenBudget}:{},...n?.showThoughts?{show_thoughts:n.showThoughts}:{},...n?.maxSteps?{max_steps:n.maxSteps}:{},...n?.maxRetries?{max_retries:n.maxRetries}:{}},A=this.traceLabel&&n.traceLabel?`${this.traceLabel} > ${n.traceLabel}`:n.traceLabel??this.traceLabel,b=A?`AxGen > ${A}`:"AxGen",w=p.startSpan(b,{kind:PR.SERVER,attributes:y}),v=TR.active(),F=ER.setSpan(v,w);try{if(this.excludeContentFromTrace||w.addEvent("input",{content:JSON.stringify(t,null,2)}),yield*this._forward2(e,t,c,{...x,functions:m},w,F),!this.excludeContentFromTrace){let k=c.map($=>$.values),O=k.length===1?k[0]:k;w.addEvent("output",{content:JSON.stringify(O,null,2)})}}catch(k){let O=k instanceof Error?k:new Error(String(k));throw w.recordException(O),w.setStatus({code:MR.ERROR,message:O.message}),k}finally{w.end()}}finally{this.activeAbortControllers.delete(o),this._stopRequested=!1}}async forward(e,t,n){let o=n?.cachingFunction??this.options?.cachingFunction??fe.cachingFunction,i=(()=>{if(!o)return;let p=this.signature.getInputFields().map(m=>m.name);return this.computeCacheKey(t,p)})();if(o&&i){let p=await o(i);if(p!==void 0)return await Uo(e,this.signature,p,n)}let s=performance.now(),a=this.getSignatureName(),c=n?.stream??!1,l=!1,u=0,d=!1;try{let p=this.getMetricsInstruments(),m=this.getMergedCustomLabels(e,n);p&&Pm(p,this.signature.getInputFields().length,this.signature.getOutputFields().length,this.examples?.length??0,this.demos?.length??0,a,m);let g=this._forward1(e,t,n??{}),h=[],x=0,f=0;for await(let k of g)k.version!==x&&(h=[]),x=k.version,h=al(h,k),f++;u=x;let y=performance.now();d=!!n?.resultPicker;let A=await ca(h,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),b=performance.now()-y,w=h[A],v=await Uo(e,this.signature,w?.delta??{},n),F=t??{};if(this.trace={...F,...v},d&&this.isDebug(e,n)){let k=this.getLogger(e,n);nm(h.length,A,b,k)}if(l=!0,p&&(Tm(p,h.length,d,d?b:void 0,a,m),Im(p,c,f,void 0,a,m)),o&&i)try{await o(i,v)}catch{}return v}catch(p){throw l=!1,p}finally{let p=performance.now()-s,m=this.getMetricsInstruments(),g=this.getMergedCustomLabels(e,n);m&&(Rm(m,p,l,a,e.getName(),n?.model?String(n.model):void 0,g),u>0&&rl(m,u,l,n?.maxRetries??this.options?.maxRetries??3,a,g))}}async*streamingForward(e,t,n){let o=n?.cachingFunction??this.options?.cachingFunction??fe.cachingFunction,i=(()=>{if(!o)return;let d=this.signature.getInputFields().map(p=>p.name);return this.computeCacheKey(t,d)})();if(o&&i){let d;try{d=await o(i)}catch{}if(d!==void 0){yield{version:0,index:0,delta:await Uo(e,this.signature,d,n)};return}}if(!n?.resultPicker){yield*this._forward1(e,t,{...n,stream:!0});return}let s=this._forward1(e,t,{...n,stream:!0}),a=[],c=0;for await(let d of s)d.version!==c&&(a=[]),c=d.version,a=al(a,d);let l=await ca(a,{resultPicker:n?.resultPicker},n?.mem,n?.sessionId),u=a[l];if(u){let d=await Uo(e,this.signature,u.delta,n);if(o&&i)try{await o(i,d)}catch{}yield{version:c,index:l,delta:d}}}setExamples(e,t){super.setExamples(e,t)}isDebug(e,t){return t?.debug??this.options?.debug??e.getOptions().debug??fe.debug??!1}getLogger(e,t){return t?.logger??this.options?.logger??e.getOptions().logger??fe.logger??e.getLogger()}computeCacheKey(e,t){let n=Rt("sha256");n.update(this.signature.hash()??"");let o=s=>{let a=typeof s;if(n.update(`|${a}|`),s==null){n.update("null");return}if(a==="string"||a==="number"||a==="boolean"){n.update(String(s));return}if(Array.isArray(s)){n.update("[");for(let c of s)o(c);n.update("]");return}if(typeof s=="object"&&s!==null&&"mimeType"in s&&"data"in s){let c=s;n.update(c.mimeType??"");let l=Rt("sha256").update(c.data??"").digest("hex");n.update(l);return}if(typeof s=="object"){let c=s,l=Object.keys(c).sort();for(let u of l)n.update(`{${u}}`),o(c[u]);return}n.update(String(s))},i=t.map(s=>e?.[s]);for(let s of i)o(s);return n.digest("hex")}},pa=class extends Error{details;constructor(e,t,n){super(e),this.name="AxGenerateError",this.details=t,n?.cause&&(this.cause=n.cause)}toJSON(){let e=this.cause;return{name:this.name,message:this.message,details:this.details,cause:e?{name:e.name,message:e.message,stack:e.stack}:void 0,stack:this.stack}}};function da(r,e,t){let n=r instanceof Error?r:new Error(String(r));if(n instanceof _e||n instanceof Rn)return n;let o=(n.message||"").toLowerCase();if(o.includes("at least")||o.includes("at most")||o.includes("must match pattern")||o.includes("invalid url")||o.includes("required")||o.includes("missing")||o.includes("valid email")||o.includes("number must be")||n.name==="ValidationError"||n.name==="AxAssertionError")return n;let s=e.getLastUsedChatModel(),a=e.getLastUsedModelConfig(),c={model:s,maxTokens:a?.maxTokens,streaming:a?.stream??!1,signature:{input:t.getInputFields(),output:t.getOutputFields(),description:t.getDescription()}};return new pa(`Generate failed: ${n.message}`,c,{cause:n})}var OR=4e3,ha=[{name:"context_roadmap",title:"CONTEXT ROADMAP",slug:"cr",description:"Index of what the context contains and where to find it."},{name:"context_understanding",title:"CONTEXT UNDERSTANDING",slug:"cu",description:"High-level understanding of the context: what it is, how it's organized, and what matters."},{name:"domain_constants",title:"DOMAIN CONSTANTS",slug:"dc",description:"Exact parameters, formulas, thresholds, reference values, enum sets, and output field requirements defined by the context."},{name:"parsing_schema",title:"PARSING SCHEMA",slug:"ps",description:"How to parse and navigate the context's format."},{name:"reusable_results",title:"REUSABLE RESULTS",slug:"rr",description:"Reusable knowledge about the context."},{name:"error_patterns",title:"ERROR PATTERNS",slug:"ep",description:"Concrete failure modes observed while processing this context."}],FR=new Map(ha.map(r=>[r.name,r])),_R=new Map(ha.map(r=>[df(r.title),r])),Zl=/^\[([^\]]+)]\s*(.*)$/,Ql=/-(\d+)$/;function uf(){return`${ha.map(({title:r,description:e})=>`## ${r}
|
|
400
400
|
(${e})`).join(`
|
|
401
401
|
|
|
402
402
|
`)}
|
|
@@ -747,7 +747,7 @@ Use the input field named "criteria" as the task-specific rubric for success.
|
|
|
747
747
|
`.trim(),t=r?.trim();return t?`${e}
|
|
748
748
|
|
|
749
749
|
Additional Evaluation Guidance:
|
|
750
|
-
${t}`:e}function nx(r){let{criteria:e,description:t,randomizeOrder:n,...o}=r;return{...o,maxSteps:1}}function rx(r){let e=r.toLowerCase();return e==="excellent"?1:e==="good"?.8:e==="acceptable"?.5:e==="poor"?.2:e==="unacceptable"?0:.5}function Yh(r,e){return e.qualifiedName===r||e.name===r||e.qualifiedName.endsWith(`.${r}`)}function ox(r,e,t){let n=Math.max(0,Math.min(1,r)),o=e.expectedActions??[];if(o.length>0){let s=o.filter(a=>t.functionCalls.some(c=>Yh(a,c))).length;n*=.5+.5*(s/o.length)}return(e.forbiddenActions??[]).some(s=>t.functionCalls.some(a=>Yh(s,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function ix(r,e){let t=new Set(r.map(o=>o.id));if(e==="actor"){let o=[...t].filter(i=>i.endsWith(".actor"));if(o.length===0)throw new Error("AxAgent.optimize(): no actor target is available");return o.sort()}if(e==="responder"){let o=[...t].filter(s=>s.endsWith(".responder")).find(s=>s.startsWith("task."));if(o)return[o];if(t.has("root.responder"))return["root.responder"];let i=[...t].filter(s=>s.endsWith(".responder"));if(i.length===0)throw new Error("AxAgent.optimize(): no responder target is available");return[i.sort()[0]]}if(e==="all"){let o=[...t].filter(i=>(i.startsWith("ctx.")||i.startsWith("task."))&&(i.endsWith(".actor")||i.endsWith(".responder")));return(o.length>0?o:[...t]).sort()}let n=[...e];for(let o of n)if(!t.has(o))throw new Error(`AxAgent.optimize(): unknown target program ID "${o}"`);return n}var Cv='Your previous Javascript Code value did not satisfy the executable-code turn contract. On this turn, set Javascript Code to runnable JavaScript only: use console.log(...) for inspection, await final("...", { ... }) when complete, or await askClarification(...) when blocked. Do not emit plain task:/evidence: labels or prose as the Javascript Code value.';function bv(r){return`[POLICY] ${r} must contain at most one fenced code block. No code from the previous turn was executed.`}function Rv(r){return`Your previous ${r} value contained multiple fenced code blocks, so none of them were executed. On this turn, put every executable statement in one ${r} value with at most one fence.`}function wv(r,e){let t=r[r.length-1]?.messages;if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(o?.role!=="assistant")continue;let i=o.content.replace(/<think>[\s\S]*?<\/think>/g,"").replace(/[^\n]*<\/think>/g,"").trim(),s=`${e}:`,a=i.indexOf(s);return a>=0?i.slice(a+s.length).trim():i}}function vv(r){let e=!1,t=0;for(let n of r.split(/\r?\n/)){let o=n.match(/```([A-Za-z0-9_-]+)?[ \t]*$/);if(!o)continue;let i=o[1]!==void 0;if(e&&!i){e=!1;continue}if(t++,t>1)return!0;e=!0}return!1}async function sx(r,e,t,n,o,i){let{s,ai:a,rlm:c,runtimeContext:l,inputState:u,completionState:d,guidanceState:p,actionLogEntries:m,actorMergedOptions:g,summaryForwardOptions:h,functionCallRecords:x,explicitActorDebugHideSystemPrompt:f,contextStage:y,contextThreshold:A,mutableState:b,helpers:w}=r,{refreshActorInstruction:v,buildActorPromptValues:F,measureActorPromptChars:k,renderActionLogParts:O,renderActionLogPartsWithReplayMode:$,resetActorModelErrorState:N,noteActorTurnErrorState:V,syncDiscoveredActorModelNamespaces:I,refreshCheckpointSummary:_}=w,S=v();await o(),u.recomputeTurnInputs(!0);for(let re of u.drainAutoPromotionEvents())await ht(s.onContextEvent,{kind:"field_auto_promoted",stage:y,turn:e+1,...re});await _(m.length)&&N();let H=O(),L=H.summary||void 0,W=H.history||"(no actions yet)",U=mr(p.entries),Y=await k(W,U,b.runtimeStateSummary,L),C=Y.systemPromptCharacters+Y.exampleChatContextCharacters,T=lr(l.effectiveContextConfig.targetPromptChars,C),E=!!b.checkpointState,D=nu({mutablePromptChars:Y.mutableChatContextCharacters,effectiveBudgetChars:T,checkpointActive:E}),j=l.effectiveContextConfig.contextHygiene?.pressureMode,J=l.effectiveContextConfig.contextHygiene?.defaultMode??"none";if(D!=="ok"&&j&&j!==J){let re=b.checkpointState,De=$(l.effectiveContextConfig.actionReplay,re?.summary,re?.turns,j),ye=De.history||"(no actions yet)",Te=De.summary||void 0,$e=await k(ye,U,b.runtimeStateSummary,Te);$e.mutableChatContextCharacters<Y.mutableChatContextCharacters&&(H=De,W=ye,L=Te,Y=$e,C=Y.systemPromptCharacters+Y.exampleChatContextCharacters,T=lr(l.effectiveContextConfig.targetPromptChars,C),D=nu({mutablePromptChars:Y.mutableChatContextCharacters,effectiveBudgetChars:T,checkpointActive:E}))}let z=l.effectiveContextConfig.preset!=="full"?If(D):void 0;for(let re of H.compactions)await ht(s.onContextEvent,{kind:"action_compacted",stage:y,turn:re.turn,mode:re.mode,reason:re.reason,originalChars:re.originalChars,renderedChars:re.renderedChars});await ht(s.onContextEvent,{kind:"budget_check",stage:y,turn:e+1,pressure:D,mutablePromptChars:Y.mutableChatContextCharacters,fixedPromptChars:C,effectiveBudgetChars:T,targetPromptChars:l.effectiveContextConfig.targetPromptChars,checkpointActive:E,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length}),A&&Y.mutableChatContextCharacters>lr(A,C)&&(W+="\n\n[HINT: Actor prompt is large. Call `const state = await inspectRuntime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let B=g;if(s.executorModelPolicy){I();let re=Sf(s.executorModelPolicy,Aa(b.actorModelState),an(b.actorModelState));B=re!==void 0?{...g,model:re}:g}let K=f??(e>0&&S===b.lastDebugLoggedActorInstruction);B={...B,debugHideSystemPrompt:K};let ie=s.actorProgram.getUsage()?.length??0,oe=c.actorTurnCallback,se=await s.actorProgram.forward(a,F(W,U,b.runtimeStateSummary,L,z),B);K||(b.lastDebugLoggedActorInstruction=S);let me=oe?s.actorProgram.getUsage()?.slice(ie):void 0,Z=B.model!==void 0?String(B.model):void 0,Be=s.actorProgram.getChatLog(),ut=oe?Th(Be):void 0;e===0&&(b.restoreNotice=void 0);let de=s.runtimeCodeFieldName??"javascriptCode",Ve=s.runtimeCodeFieldTitle??"Javascript Code",Ae=se[de],at=Ae?.trim(),ne=wv(Be,Ve)?.trim()??at,ve=typeof ne=="string"&&vv(ne);if(ve)Ae=ne;else{if(!Ae||!at)return{shouldBreak:!0,shouldContinue:!1};Ae=ex(at)}se[de]=Ae,d.payload=void 0;let ke=x?.length??0;if(ve||s.enforceIncrementalConsoleTurns){let re=ve?{violation:bv(Ve)}:ph(Ae);if(re?.autoSplitDiscoveryCode&&await l.executeActorCode(re.autoSplitDiscoveryCode),re?.violation){let De=re.violation,ye=m.length+1;return wu(p.entries,{turn:ye,guidance:ve?Rv(Ve):Cv,triggeredBy:"runtime policy"}),m.push({turn:ye,code:Ae,output:De,tags:["error"],...(()=>{let Te=x?.slice(ke)??[];return Te.length>0?{_functionCalls:Te}:{}})()}),oe&&await oe({stage:y,turn:ye,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length,executorResult:se,code:Ae,result:void 0,output:De,isError:!0,thought:typeof se.thought=="string"?se.thought:void 0,usage:me,model:Z,chatLogMessages:ut}),await gu(m,m.length-1,l.effectiveContextConfig,a,h,{stage:y,onContextEvent:s.onContextEvent}),V(!0),await _(ye)&&N(),{shouldBreak:!1,shouldContinue:!0}}}s.inputUpdateCallback&&await l.syncRuntimeInputsToSession();let He,we,Ie;try{let re=await l.executeActorCode(Ae);He=re.result,we=re.output,Ie=re.isError}catch(re){if(re instanceof et||re instanceof
|
|
750
|
+
${t}`:e}function nx(r){let{criteria:e,description:t,randomizeOrder:n,...o}=r;return{...o,maxSteps:1}}function rx(r){let e=r.toLowerCase();return e==="excellent"?1:e==="good"?.8:e==="acceptable"?.5:e==="poor"?.2:e==="unacceptable"?0:.5}function Yh(r,e){return e.qualifiedName===r||e.name===r||e.qualifiedName.endsWith(`.${r}`)}function ox(r,e,t){let n=Math.max(0,Math.min(1,r)),o=e.expectedActions??[];if(o.length>0){let s=o.filter(a=>t.functionCalls.some(c=>Yh(a,c))).length;n*=.5+.5*(s/o.length)}return(e.forbiddenActions??[]).some(s=>t.functionCalls.some(a=>Yh(s,a)))&&(n*=.2),Math.max(0,Math.min(1,n))}function ix(r,e){let t=new Set(r.map(o=>o.id));if(e==="actor"){let o=[...t].filter(i=>i.endsWith(".actor"));if(o.length===0)throw new Error("AxAgent.optimize(): no actor target is available");return o.sort()}if(e==="responder"){let o=[...t].filter(s=>s.endsWith(".responder")).find(s=>s.startsWith("task."));if(o)return[o];if(t.has("root.responder"))return["root.responder"];let i=[...t].filter(s=>s.endsWith(".responder"));if(i.length===0)throw new Error("AxAgent.optimize(): no responder target is available");return[i.sort()[0]]}if(e==="all"){let o=[...t].filter(i=>(i.startsWith("ctx.")||i.startsWith("task."))&&(i.endsWith(".actor")||i.endsWith(".responder")));return(o.length>0?o:[...t]).sort()}let n=[...e];for(let o of n)if(!t.has(o))throw new Error(`AxAgent.optimize(): unknown target program ID "${o}"`);return n}var Cv='Your previous Javascript Code value did not satisfy the executable-code turn contract. On this turn, set Javascript Code to runnable JavaScript only: use console.log(...) for inspection, await final("...", { ... }) when complete, or await askClarification(...) when blocked. Do not emit plain task:/evidence: labels or prose as the Javascript Code value.';function bv(r){return`[POLICY] ${r} must contain at most one fenced code block. No code from the previous turn was executed.`}function Rv(r){return`Your previous ${r} value contained multiple fenced code blocks, so none of them were executed. On this turn, put every executable statement in one ${r} value with at most one fence.`}function wv(r,e){let t=r[r.length-1]?.messages;if(t)for(let n=t.length-1;n>=0;n--){let o=t[n];if(o?.role!=="assistant")continue;let i=o.content.replace(/<think>[\s\S]*?<\/think>/g,"").replace(/[^\n]*<\/think>/g,"").trim(),s=`${e}:`,a=i.indexOf(s);return a>=0?i.slice(a+s.length).trim():i}}function vv(r){let e=!1,t=0;for(let n of r.split(/\r?\n/)){let o=n.match(/```([A-Za-z0-9_-]+)?[ \t]*$/);if(!o)continue;let i=o[1]!==void 0;if(e&&!i){e=!1;continue}if(t++,t>1)return!0;e=!0}return!1}async function sx(r,e,t,n,o,i){let{s,ai:a,rlm:c,runtimeContext:l,inputState:u,completionState:d,guidanceState:p,actionLogEntries:m,actorMergedOptions:g,summaryForwardOptions:h,functionCallRecords:x,explicitActorDebugHideSystemPrompt:f,contextStage:y,contextThreshold:A,mutableState:b,helpers:w}=r,{refreshActorInstruction:v,buildActorPromptValues:F,measureActorPromptChars:k,renderActionLogParts:O,renderActionLogPartsWithReplayMode:$,resetActorModelErrorState:N,noteActorTurnErrorState:V,syncDiscoveredActorModelNamespaces:I,refreshCheckpointSummary:_}=w,S=v();await o(),u.recomputeTurnInputs(!0);for(let re of u.drainAutoPromotionEvents())await ht(s.onContextEvent,{kind:"field_auto_promoted",stage:y,turn:e+1,...re});await _(m.length)&&N();let H=O(),L=H.summary||void 0,W=H.history||"(no actions yet)",U=mr(p.entries),Y=await k(W,U,b.runtimeStateSummary,L),C=Y.systemPromptCharacters+Y.exampleChatContextCharacters,T=lr(l.effectiveContextConfig.targetPromptChars,C),E=!!b.checkpointState,D=nu({mutablePromptChars:Y.mutableChatContextCharacters,effectiveBudgetChars:T,checkpointActive:E}),j=l.effectiveContextConfig.contextHygiene?.pressureMode,J=l.effectiveContextConfig.contextHygiene?.defaultMode??"none";if(D!=="ok"&&j&&j!==J){let re=b.checkpointState,De=$(l.effectiveContextConfig.actionReplay,re?.summary,re?.turns,j),ye=De.history||"(no actions yet)",Te=De.summary||void 0,$e=await k(ye,U,b.runtimeStateSummary,Te);$e.mutableChatContextCharacters<Y.mutableChatContextCharacters&&(H=De,W=ye,L=Te,Y=$e,C=Y.systemPromptCharacters+Y.exampleChatContextCharacters,T=lr(l.effectiveContextConfig.targetPromptChars,C),D=nu({mutablePromptChars:Y.mutableChatContextCharacters,effectiveBudgetChars:T,checkpointActive:E}))}let z=l.effectiveContextConfig.preset!=="full"?If(D):void 0;for(let re of H.compactions)await ht(s.onContextEvent,{kind:"action_compacted",stage:y,turn:re.turn,mode:re.mode,reason:re.reason,originalChars:re.originalChars,renderedChars:re.renderedChars});await ht(s.onContextEvent,{kind:"budget_check",stage:y,turn:e+1,pressure:D,mutablePromptChars:Y.mutableChatContextCharacters,fixedPromptChars:C,effectiveBudgetChars:T,targetPromptChars:l.effectiveContextConfig.targetPromptChars,checkpointActive:E,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length}),A&&Y.mutableChatContextCharacters>lr(A,C)&&(W+="\n\n[HINT: Actor prompt is large. Call `const state = await inspectRuntime()` for a compact snapshot of current variables instead of re-reading old outputs.]");let B=g;if(s.executorModelPolicy){I();let re=Sf(s.executorModelPolicy,Aa(b.actorModelState),an(b.actorModelState));B=re!==void 0?{...g,model:re}:g}let K=f??(e>0&&S===b.lastDebugLoggedActorInstruction);B={...B,debugHideSystemPrompt:K};let ie=s.actorProgram.getUsage()?.length??0,oe=c.actorTurnCallback,se=await s.actorProgram.forward(a,F(W,U,b.runtimeStateSummary,L,z),B);K||(b.lastDebugLoggedActorInstruction=S);let me=oe?s.actorProgram.getUsage()?.slice(ie):void 0,Z=B.model!==void 0?String(B.model):void 0,Be=s.actorProgram.getChatLog(),ut=oe?Th(Be):void 0;e===0&&(b.restoreNotice=void 0);let de=s.runtimeCodeFieldName??"javascriptCode",Ve=s.runtimeCodeFieldTitle??"Javascript Code",Ae=se[de],at=Ae?.trim(),ne=wv(Be,Ve)?.trim()??at,ve=typeof ne=="string"&&vv(ne);if(ve)Ae=ne;else{if(!Ae||!at)return{shouldBreak:!0,shouldContinue:!1};Ae=ex(at)}se[de]=Ae,d.payload=void 0;let ke=x?.length??0;if(ve||s.enforceIncrementalConsoleTurns){let re=ve?{violation:bv(Ve)}:ph(Ae);if(re?.autoSplitDiscoveryCode&&await l.executeActorCode(re.autoSplitDiscoveryCode),re?.violation){let De=re.violation,ye=m.length+1;return wu(p.entries,{turn:ye,guidance:ve?Rv(Ve):Cv,triggeredBy:"runtime policy"}),m.push({turn:ye,code:Ae,output:De,tags:["error"],...(()=>{let Te=x?.slice(ke)??[];return Te.length>0?{_functionCalls:Te}:{}})()}),oe&&await oe({stage:y,turn:ye,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length,executorResult:se,code:Ae,result:void 0,output:De,isError:!0,thought:typeof se.thought=="string"?se.thought:void 0,usage:me,model:Z,chatLogMessages:ut}),await gu(m,m.length-1,l.effectiveContextConfig,a,h,{stage:y,onContextEvent:s.onContextEvent}),V(!0),await _(ye)&&N(),{shouldBreak:!1,shouldContinue:!0}}}s.inputUpdateCallback&&await l.syncRuntimeInputsToSession();let He,we,Ie;try{let re=await l.executeActorCode(Ae);He=re.result,we=re.output,Ie=re.isError}catch(re){if(re instanceof et||re instanceof _e||s.shouldBubbleUserError(re)){let De=re instanceof Error?re:new Error(String(re));oe&&await oe({stage:y,turn:m.length+1,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length,executorResult:se,code:Ae,result:void 0,output:th(De,l.effectiveContextConfig.maxRuntimeChars),isError:re instanceof _e||s.shouldBubbleUserError(re),thought:typeof se.thought=="string"?se.thought:void 0,usage:me,model:Z,chatLogMessages:ut})}throw re}let Ue=d.payload,X=Ue?.type==="guide_agent"?Ue:void 0;if(X){let re=m.length+1;wu(p.entries,{turn:re,guidance:X.guidance,...X.triggeredBy?{triggeredBy:X.triggeredBy}:{}}),He=void 0,we=Pa(X),Ie=!1}let he=l.consumeDiscoveryTurnArtifacts();Ie||(we=kh(we,he.texts),we=Ih(we,he.summary));let Ce=m.length+1,Le=X?Ph(X):Ae;return m.push({turn:Ce,code:Le,output:we,tags:Ie?["error"]:[],...(()=>{let re=x?.slice(ke)??[];return re.length>0?{_functionCalls:re}:{}})()}),oe&&await oe({stage:y,turn:Ce,actionLogEntryCount:m.length,guidanceLogEntryCount:p.entries.length,executorResult:se,code:Ae,result:He,output:we,isError:Ie,thought:typeof se.thought=="string"?se.thought:void 0,usage:me,model:Z,chatLogMessages:ut}),await gu(m,m.length-1,l.effectiveContextConfig,a,h,{stage:y,onContextEvent:s.onContextEvent}),Ie||(b.runtimeStateSummary=await l.captureRuntimeStateSummary()),V(Ie),await _(Ce)&&N(),d.payload&&"guidance"in d.payload?(d.payload=void 0,{shouldBreak:!1,shouldContinue:!0}):d.payload?{shouldBreak:!0,shouldContinue:!1}:{shouldBreak:!1,shouldContinue:!1}}var _a="failures_to_avoid",ax=240,Sv=200,ku=12,kv=300;function Vr(r,e){let t=r.replace(/\s+/g," ").trim();return t.length>e?`${t.slice(0,e-1)}\u2026`:t}function Iv(r){let e=r.split(`
|
|
751
751
|
`).map(t=>t.trim()).filter(Boolean);return e.find(t=>/\b\w+Error:/.test(t)&&!t.startsWith("["))??e.find(t=>!t.startsWith("[")&&!t.startsWith("..."))??Tt(r)}function Tv(r){let e=r.map(t=>({turn:t.turn,code:t.code,output:t.output,tags:[...t.tags],...t.producedVars?{producedVars:[...t.producedVars]}:{},...t.stepKind?{stepKind:t.stepKind}:{}}));for(let t=0;t+1<e.length;t++){let n=e[t],o=e[t+1];n&&o&&pu(n,o)}return new Set(e.filter(t=>t.tags.includes("dead-end")).map(t=>t.turn))}function Fa(r,e){let t=`${e.kind}\0${e.signature}`,n=r.get(t);if(n){n.occurrences+=1;return}r.set(t,{...e,occurrences:1})}function cx(r,e){try{return Pv(r,e)}catch{return}}function Pv(r,e){if(r.length===0)return;let t=Tv(r),n=new Map;if(r.forEach((o,i)=>{if(o.tags.includes("error")){let s=Tt(o.output),a=Vr(Iv(o.output),Sv),c=o.code?Vr(o.code,ax):void 0,l=r.slice(i+1),u=l.find(p=>!p.tags.includes("error")),d=l.some(p=>p.tags.includes("error")&&Tt(p.output)===s);if(u&&!d){let p=u.summary??Vr(u.code,120);Fa(n,{kind:"resolved_error",turn:o.turn,signature:s,detail:p?`${a} \u2014 resolved by: ${p}`:a,resolvedByTurn:u.turn,...c?{code:c}:{}})}else t.has(o.turn)?Fa(n,{kind:"dead_end",turn:o.turn,signature:s,detail:a,...c?{code:c}:{}}):Fa(n,{kind:"error_turn",turn:o.turn,signature:s,detail:a,...c?{code:c}:{}})}for(let s of o._functionCalls??[]){if(!s.error)continue;let a=Vr(s.error,120);Fa(n,{kind:"tool_error",turn:o.turn,signature:`${s.qualifiedName}: ${a.slice(0,60)}`,detail:`${s.qualifiedName} failed: ${a}`,...s.arguments!==void 0?{code:Vr(Mv(s.arguments),ax)}:{}})}}),n.size!==0)return{stage:e,signals:[...n.values()]}}function Mv(r){try{return JSON.stringify(r)??String(r)}catch{return String(r)}}function Na(r){let e=new Map;for(let t of r)for(let n of t?.signals??[]){let o=`${n.kind}\0${n.signature}`,i=e.get(o);i?i.occurrences+=n.occurrences:e.set(o,{...n})}return[...e.values()]}function lx(r,e){let t=r.slice(0,ku),n=t.map(i=>{let s=i.occurrences>1?` (x${i.occurrences})`:"",a=i.resolvedByTurn!==void 0?` [resolved in turn ${i.resolvedByTurn}]`:"",c=i.code?`
|
|
752
752
|
failing code: ${i.code}`:"";return`- (${i.kind}${s}) [${i.signature}] ${i.detail}${a}${c}`}),o=r.length>t.length?`
|
|
753
753
|
(${r.length-t.length} more signals omitted)`:"";return`The agent run for task "${Vr(e,kv)}" produced these failure signals:
|
|
@@ -778,13 +778,13 @@ ${Q}
|
|
|
778
778
|
);`:`return (
|
|
779
779
|
${Q}
|
|
780
780
|
);`},U=R=>{try{return new n(R),!0}catch{return!1}},Y=R=>{let P=R.split(`
|
|
781
|
-
`),G=S(P);if(G<0)return R;let M=new Set;for(let Q=G;Q>=0;Q-=1){let ee=P[Q]??"";if(!ee.trim()||_(ee))continue;let te=W(P,Q,G);if(te&&!M.has(te)&&(M.add(te),U(te)))return te}return R},C=R=>{let P=c.exec(R);return P&&(P[1]||"").trim()||R},T=R=>{let P=[],G=R.length,M=0,Q=0,ee=0,te=pe=>pe>="a"&&pe<="z"||pe>="A"&&pe<="Z"||pe>="0"&&pe<="9"||pe==="_"||pe==="$",be=pe=>{if(M++,pe==="`"){let ge=0;for(;M<G;){let
|
|
781
|
+
`),G=S(P);if(G<0)return R;let M=new Set;for(let Q=G;Q>=0;Q-=1){let ee=P[Q]??"";if(!ee.trim()||_(ee))continue;let te=W(P,Q,G);if(te&&!M.has(te)&&(M.add(te),U(te)))return te}return R},C=R=>{let P=c.exec(R);return P&&(P[1]||"").trim()||R},T=R=>{let P=[],G=R.length,M=0,Q=0,ee=0,te=pe=>pe>="a"&&pe<="z"||pe>="A"&&pe<="Z"||pe>="0"&&pe<="9"||pe==="_"||pe==="$",be=pe=>{if(M++,pe==="`"){let ge=0;for(;M<G;){let Ne=R[M];if(Ne==="\\"){M+=2;continue}if(ge>0){Ne==="{"?ge++:Ne==="}"&&ge--,M++;continue}if(Ne==="$"&&M+1<G&&R[M+1]==="{"){ge++,M+=2;continue}if(Ne==="`"){M++;return}M++}}else for(;M<G;){let ge=R[M];if(ge==="\\"){M+=2;continue}if(ge===pe){M++;return}M++}},Re=()=>{for(M+=2;M<G&&R[M]!==`
|
|
782
782
|
`;)M++},ce=()=>{for(M+=2;M<G;){if(R[M]==="*"&&M+1<G&&R[M+1]==="/"){M+=2;return}M++}},Se=()=>{let pe=M;for(;M<G&&te(R[M]);)M++;return R.slice(pe,M)},le=()=>{let pe=M;for(;M<G;){let ge=R[M];if(ge===" "||ge===" "||ge===`
|
|
783
|
-
`||ge==="\r"){M++;continue}if(ge==="/"&&M+1<G){if(R[M+1]==="/"){Re();continue}if(R[M+1]==="*"){ce();continue}}break}return M>pe},Pe=pe=>{let ge=1;for(;M<G&&ge>0;){if(le(),M>=G)return;let
|
|
784
|
-
`&&pe===0){let
|
|
785
|
-
`||
|
|
783
|
+
`||ge==="\r"){M++;continue}if(ge==="/"&&M+1<G){if(R[M+1]==="/"){Re();continue}if(R[M+1]==="*"){ce();continue}}break}return M>pe},Pe=pe=>{let ge=1;for(;M<G&&ge>0;){if(le(),M>=G)return;let Ne=R[M];if(Ne===pe){ge--,M++;continue}if(Ne==="{"||Ne==="["){let Nt=Ne==="{"?"}":"]";M++,ge++,M--,ge--,M++,Pe(Nt);continue}if(Ne==="."&&M+2<G&&R[M+1]==="."&&R[M+2]==="."){if(M+=3,le(),M<G&&te(R[M])){let Nt=Se();Nt&&P.push(Nt)}continue}if(Ne===","){M++;continue}if(Ne==="="){M++;let Nt=0;for(;M<G;){let mt=R[M];if(mt==="'"||mt==='"'||mt==="`"){be(mt);continue}if(mt==="("||mt==="["||mt==="{"){Nt++,M++;continue}if(mt===")"||mt==="]"||mt==="}"){if(Nt>0){Nt--,M++;continue}break}if(mt===","&&Nt===0)break;M++}continue}if(te(Ne)){let Nt=Se();if(le(),M<G&&R[M]===":"){if(M++,le(),M<G){let mt=R[M];if(mt==="{"||mt==="["){let ps=mt==="{"?"}":"]";M++,Pe(ps)}else if(te(mt)){let ps=Se();ps&&P.push(ps)}}}else Nt&&P.push(Nt);continue}M++}},We=()=>{let pe=0;for(;M<G;){let ge=R[M];if(ge==="'"||ge==='"'||ge==="`"){be(ge);continue}if(ge==="/"&&M+1<G){if(R[M+1]==="/"){Re();continue}if(R[M+1]==="*"){ce();continue}}if(ge==="("||ge==="["||ge==="{"){pe++,M++;continue}if(ge===")"||ge==="]"||ge==="}"){if(pe>0){pe--,M++;continue}return!1}if(ge===","&&pe===0)return M++,!0;if(ge===";"&&pe===0)return M++,!1;if(ge===`
|
|
784
|
+
`&&pe===0){let Ne=M;return M++,le(),M<G&&R[M]===","?(M++,!0):(M=Ne,!1)}M++}return!1},it=()=>{for(;M<G;){if(le(),M>=G)return;let pe=R[M];if(pe==="{"){if(M++,Pe("}"),!We())return;continue}if(pe==="["){if(M++,Pe("]"),!We())return;continue}if(te(pe)){let ge=Se();if(ge&&P.push(ge),!We())return;continue}return}},je=pe=>{if(pe===0)return!0;let ge=pe-1;for(;ge>=0;){let Ne=R[ge];if(Ne===" "||Ne===" "||Ne==="\r"){ge--;continue}return Ne===`
|
|
785
|
+
`||Ne===";"||Ne==="{"||Ne==="}"}return!0};for(;M<G;){let pe=R[M];if(pe==="'"||pe==='"'||pe==="`"){be(pe);continue}if(pe==="/"&&M+1<G){if(R[M+1]==="/"){Re();continue}if(R[M+1]==="*"){ce();continue}}if(pe==="{"){Q++,M++;continue}if(pe==="}"){Q--,M++;continue}if(pe==="("){ee++,M++;continue}if(pe===")"){ee--,M++;continue}if(Q===0&&ee===0&&te(pe)){let ge=M,Ne=Se();if((Ne==="var"||Ne==="let"||Ne==="const")&&M<G&&(R[M]===" "||R[M]===" "||R[M]===`
|
|
786
786
|
`)&&je(ge)){it();continue}continue}M++}let _t=new Set,en=[];for(let pe of P)_t.has(pe)||(_t.add(pe),en.push(pe));return en},E=R=>R.length===0?"":`
|
|
787
|
-
${R.map(G=>`try { globalThis[${JSON.stringify(G)}] = ${G}; } catch {}`).join(" ")} void 0;`,D=R=>{if(typeof R=="string")return R;try{return JSON.stringify(R,null,2)}catch{return String(R)}},j=(R,P)=>{let G=e.console&&typeof e.console=="object"?e.console:null,M=G?.[R],Q=typeof M=="function"?(...te)=>M.apply(G,te):null,ee=(...te)=>{P.push(te.map(D).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[R]=ee,()=>{if(!(!e.console||typeof e.console!="object")){if(Q){e.console[R]=Q;return}try{delete e.console[R]}catch{e.console[R]=void 0}}}},J=R=>{let P=[];return Ie&&(P.push(j("log",R)),P.push(j("info",R)),P.push(j("warn",R)),P.push(j("error",R))),P},z=()=>{let R=[],P=J(R),G=e.print;return we===s&&(e.print=(...Q)=>{R.push(Q.map(D).join(" "))}),{output:R,cleanup:()=>{for(let Q of P)try{Q()}catch{}if(we===s)if(G===void 0)try{delete e.print}catch{e.print=void 0}else e.print=G}}},B=R=>{for(let P of R)try{Object.defineProperty(e,P,{value:void 0,writable:!1,configurable:!1})}catch{}},K=R=>{let P=new Set(Array.isArray(R)?R:[]);for(let[G,M]of Object.entries(l))P.has(G)||B(M)},ie=R=>{g&&!R&&B(["process","require"])},oe=["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","fs/promises","http","http2","https","inspector","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","test","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib"],se=new Set(oe),me=R=>{let P=String(R);return P.startsWith("node:")?{kind:"builtin",name:P.slice(5)}:se.has(P)?{kind:"builtin",name:P}:/^(https?:|file:|\.\.?\/|\/)/.test(P)?{kind:"url",name:P}:{kind:"userland",name:P}},Z=R=>{let P=new Set,G=new Set,M=new Set;for(let Q of R){let ee=me(Q);if(ee.kind==="builtin")P.add(ee.name);else if(ee.kind==="userland"){if(se.has(ee.name))throw new Error(`allowedModules entry '${Q}' is ambiguous: it matches a Node builtin. Use 'node:${ee.name}' to allow the builtin, or a different name for a userland package.`);G.add(ee.name)}else M.add(ee.name)}return{builtins:P,userland:G,urls:M}},Be=()=>{let R=Z(F??[]);return async(P,G)=>{let M=me(String(P));if(M.kind==="builtin"&&R.builtins.has(M.name)){if(typeof d!="function")throw new Error(`Module '${P}' cannot be loaded: no module loader`);return d(`node:${M.name}`)}if(M.kind==="userland"&&R.userland.has(M.name)){if(typeof d!="function")throw new Error(`Module '${P}' cannot be loaded: no module loader`);return d(M.name)}throw M.kind==="url"&&R.urls.has(M.name)?new Error(`URL-specifier imports are not yet supported in this sandbox: '${P}'`):new Error(`dynamic import of '${P}' is not allowed in this sandbox`)}},ut=R=>{let P=k,G=R.runInThisContext,M=e.Function,Q=Object.getPrototypeOf(async()=>{}).constructor,ee=Object.getPrototypeOf(function*(){}).constructor,te=Object.getPrototypeOf(async function*(){}).constructor,be={sync:M,async:Q,gen:ee,asyncGen:te},Re=(je,_t,en)=>{let pe=be[je];pe(..._t,en);let ge=_t.join(", "),
|
|
787
|
+
${R.map(G=>`try { globalThis[${JSON.stringify(G)}] = ${G}; } catch {}`).join(" ")} void 0;`,D=R=>{if(typeof R=="string")return R;try{return JSON.stringify(R,null,2)}catch{return String(R)}},j=(R,P)=>{let G=e.console&&typeof e.console=="object"?e.console:null,M=G?.[R],Q=typeof M=="function"?(...te)=>M.apply(G,te):null,ee=(...te)=>{P.push(te.map(D).join(" "))};return(!e.console||typeof e.console!="object")&&(e.console={}),e.console[R]=ee,()=>{if(!(!e.console||typeof e.console!="object")){if(Q){e.console[R]=Q;return}try{delete e.console[R]}catch{e.console[R]=void 0}}}},J=R=>{let P=[];return Ie&&(P.push(j("log",R)),P.push(j("info",R)),P.push(j("warn",R)),P.push(j("error",R))),P},z=()=>{let R=[],P=J(R),G=e.print;return we===s&&(e.print=(...Q)=>{R.push(Q.map(D).join(" "))}),{output:R,cleanup:()=>{for(let Q of P)try{Q()}catch{}if(we===s)if(G===void 0)try{delete e.print}catch{e.print=void 0}else e.print=G}}},B=R=>{for(let P of R)try{Object.defineProperty(e,P,{value:void 0,writable:!1,configurable:!1})}catch{}},K=R=>{let P=new Set(Array.isArray(R)?R:[]);for(let[G,M]of Object.entries(l))P.has(G)||B(M)},ie=R=>{g&&!R&&B(["process","require"])},oe=["assert","async_hooks","buffer","child_process","cluster","console","constants","crypto","dgram","diagnostics_channel","dns","domain","events","fs","fs/promises","http","http2","https","inspector","module","net","os","path","path/posix","path/win32","perf_hooks","process","punycode","querystring","readline","readline/promises","repl","stream","stream/consumers","stream/promises","stream/web","string_decoder","sys","test","timers","timers/promises","tls","trace_events","tty","url","util","util/types","v8","vm","wasi","worker_threads","zlib"],se=new Set(oe),me=R=>{let P=String(R);return P.startsWith("node:")?{kind:"builtin",name:P.slice(5)}:se.has(P)?{kind:"builtin",name:P}:/^(https?:|file:|\.\.?\/|\/)/.test(P)?{kind:"url",name:P}:{kind:"userland",name:P}},Z=R=>{let P=new Set,G=new Set,M=new Set;for(let Q of R){let ee=me(Q);if(ee.kind==="builtin")P.add(ee.name);else if(ee.kind==="userland"){if(se.has(ee.name))throw new Error(`allowedModules entry '${Q}' is ambiguous: it matches a Node builtin. Use 'node:${ee.name}' to allow the builtin, or a different name for a userland package.`);G.add(ee.name)}else M.add(ee.name)}return{builtins:P,userland:G,urls:M}},Be=()=>{let R=Z(F??[]);return async(P,G)=>{let M=me(String(P));if(M.kind==="builtin"&&R.builtins.has(M.name)){if(typeof d!="function")throw new Error(`Module '${P}' cannot be loaded: no module loader`);return d(`node:${M.name}`)}if(M.kind==="userland"&&R.userland.has(M.name)){if(typeof d!="function")throw new Error(`Module '${P}' cannot be loaded: no module loader`);return d(M.name)}throw M.kind==="url"&&R.urls.has(M.name)?new Error(`URL-specifier imports are not yet supported in this sandbox: '${P}'`):new Error(`dynamic import of '${P}' is not allowed in this sandbox`)}},ut=R=>{let P=k,G=R.runInThisContext,M=e.Function,Q=Object.getPrototypeOf(async()=>{}).constructor,ee=Object.getPrototypeOf(function*(){}).constructor,te=Object.getPrototypeOf(async function*(){}).constructor,be={sync:M,async:Q,gen:ee,asyncGen:te},Re=(je,_t,en)=>{let pe=be[je];pe(..._t,en);let ge=_t.join(", "),Ne=je==="sync"?`(function anonymous(${ge}) {
|
|
788
788
|
${en}
|
|
789
789
|
})`:je==="async"?`(async function anonymous(${ge}) {
|
|
790
790
|
${en}
|
|
@@ -792,7 +792,7 @@ ${en}
|
|
|
792
792
|
${en}
|
|
793
793
|
})`:`(async function* anonymous(${ge}) {
|
|
794
794
|
${en}
|
|
795
|
-
})`;return G(
|
|
795
|
+
})`;return G(Ne,{importModuleDynamically:P})},ce=je=>function(..._t){let en=_t.length>0?String(_t[_t.length-1]):"",pe=_t.slice(0,-1).map(String);return Re(je,pe,en)},Se=ce("sync"),le=ce("async"),Pe=ce("gen"),We=ce("asyncGen");try{Object.defineProperty(e,"Function",{value:Se,writable:!1,configurable:!1})}catch{}try{Object.defineProperty(M.prototype,"constructor",{value:Se,writable:!1,configurable:!1})}catch{}try{Object.defineProperty(Q.prototype,"constructor",{value:le,writable:!1,configurable:!1})}catch{}try{Object.defineProperty(ee.prototype,"constructor",{value:Pe,writable:!1,configurable:!1})}catch{}try{Object.defineProperty(te.prototype,"constructor",{value:We,writable:!1,configurable:!1})}catch{}let it=je=>G(String(je),{importModuleDynamically:P});try{Object.defineProperty(e,"eval",{value:it,writable:!1,configurable:!1})}catch{}},de=()=>{try{Object.defineProperty(Error,"stackTraceLimit",{value:10,writable:!1,configurable:!1})}catch{}let R=[Object,Object.prototype,Function,Function.prototype,Array,Array.prototype,Promise,Promise.prototype,String,String.prototype,Number,Number.prototype,Boolean,Boolean.prototype,Symbol,Symbol.prototype,RegExp,RegExp.prototype,Date,Date.prototype,Map,Map.prototype,Set,Set.prototype,WeakMap,WeakMap.prototype,WeakSet,WeakSet.prototype,Error,TypeError,RangeError,SyntaxError,ReferenceError,EvalError,URIError,Reflect,Math,JSON,ArrayBuffer,ArrayBuffer.prototype,DataView,DataView.prototype,Int8Array,Int8Array.prototype,Uint8Array,Uint8Array.prototype,Uint8ClampedArray,Uint8ClampedArray.prototype,Int16Array,Int16Array.prototype,Uint16Array,Uint16Array.prototype,Int32Array,Int32Array.prototype,Uint32Array,Uint32Array.prototype,Float32Array,Float32Array.prototype,Float64Array,Float64Array.prototype],P=["BigInt","BigInt64Array","BigUint64Array","SharedArrayBuffer","Atomics","Proxy","WeakRef","FinalizationRegistry","AggregateError","URL","URLSearchParams","Intl"],G=new Set(["AggregateError"]);for(let M of P)try{let Q=e[M];if(Q&&(R.push(Q),!G.has(M))){let ee=Q.prototype;ee&&R.push(ee)}}catch{}try{R.push(Object.getPrototypeOf([][Symbol.iterator]()))}catch{}try{R.push(Object.getPrototypeOf(new Map()[Symbol.iterator]()))}catch{}try{R.push(Object.getPrototypeOf(new Set()[Symbol.iterator]()))}catch{}try{R.push(Object.getPrototypeOf(""[Symbol.iterator]()))}catch{}try{R.push(Object.getPrototypeOf(function*(){}).prototype)}catch{}try{R.push(Object.getPrototypeOf(async function*(){}).prototype)}catch{}for(let M of R)if(M)try{Object.freeze(M)}catch{}},Ve=r.maxErrorCauseDepth,Ae=(R,P=0,G=new Set)=>{if(P>Ve)return{name:"Error",message:"[cause chain truncated]"};if(R&&typeof R=="object"){if(G.has(R))return{name:"Error",message:"[circular]"};G.add(R)}let M=R,Q=M?.name!=null?String(M.name):"Error",ee=M?.message!=null?String(M.message):ne(R),te=typeof M?.stack=="string"?M.stack:void 0,be;if(typeof M?.cause<"u"&&P<Ve)try{let ce=M.cause;ce instanceof Error||ce&&typeof ce=="object"&&("message"in ce||"name"in ce)?be=Ae(ce,P+1,G):be={name:"Error",message:ne(ce)}}catch{be={name:"Error",message:ne(M.cause)}}let Re={name:Q,message:ee};if(te!==void 0&&(Re.stack=te),be!==void 0&&(Re.cause=be),typeof M?.data<"u")try{Re.data=typeof structuredClone=="function"?structuredClone(M.data):M.data}catch{}return Re},at=R=>{if(typeof R=="string")return new Error(R);if(!R||typeof R!="object")return new Error(String(R));let P=R,G=new Error(P.message!=null?String(P.message):"");return G.name=P.name!=null?String(P.name):"Error",typeof P.stack=="string"&&(G.stack=P.stack),P.cause!==void 0&&(G.cause=at(P.cause)),P.data!==void 0&&(G.data=P.data),G},dt=R=>{let P=globalThis.AggregateError,G=typeof P=="function"&&R instanceof P;return R instanceof SyntaxError||R instanceof TypeError||R instanceof RangeError||R instanceof ReferenceError||G||R instanceof EvalError||R instanceof URIError},ne=R=>{if(R==null||typeof R!="object")return String(R);try{return JSON.stringify(R,null,2)}catch{return String(R)}},ve=(R,P,G=0)=>{let M=R,Q=M?.name!=null?String(M.name):"Error",ee=M?.message!=null?String(M.message):ne(R),te=[`${Q}: ${ee}`],be;if(typeof M?.stack=="string"){let Re=M.stack.match(/<anonymous>:(\d+):(\d+)/);Re&&(be=Math.max(1,Number(Re[1])-G),te.push(` at line ${be}, column ${Re[2]}`))}if(P&&be!==void 0&&be>=1&&be<=P.split(`
|
|
796
796
|
`).length){let Re=P.split(`
|
|
797
797
|
`),ce=Math.max(0,be-2),Se=Math.min(Re.length,be+1),Pe=Re.slice(ce,Se).map((We,it)=>` ${String(ce+it+1).padStart(3)}| ${We}`).join(`
|
|
798
798
|
`);te.push(`Source:
|
|
@@ -806,11 +806,11 @@ ${te}
|
|
|
806
806
|
`,t="";return e.includes("__name")&&(t+=`var __name=(fn,_n)=>fn;
|
|
807
807
|
`),t?`${t}${e}`:e}var $u=(r,e)=>{let t={},n=new Map,o=0,i=new WeakMap,s=(a,c)=>{if(typeof a=="function"){let g=`fn_${e?.nextFnId?e.nextFnId():++o}_${c||"root"}`;return n.set(g,a),{[Ou]:g}}if(!a||typeof a!="object")return a;if(i.has(a))return i.get(a);if(Array.isArray(a)){let m=[];i.set(a,m);for(let g=0;g<a.length;g+=1)m[g]=s(a[g],`${c}[${g}]`);return m}let l=Object.getPrototypeOf(a);if(!(l===Object.prototype||l===null))return a;let d=a,p={};i.set(a,p);for(let[m,g]of Object.entries(d))p[m]=s(g,c?`${c}.${m}`:m);return p};if(r)for(let[a,c]of Object.entries(r))t[a]=s(c,a);return{serializableGlobals:t,fnMap:n}},Uu=r=>{if(typeof structuredClone=="function")try{structuredClone(r)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Error(`RLM globals must be structured-cloneable: ${t}`)}},_u=r=>!!r&&/[A-Za-z0-9_$]/.test(r),Nu=r=>!!r&&/[A-Za-z_$]/.test(r),wx=(r,e)=>{let t=new Set(e);for(let m of qo(r))if(t.has(m))return m;let n=Sn(r),o=n.length,i=0,s=0,a=0,c=m=>{let g=m;for(;g<o&&/\s/.test(n[g]??"");)g++;return g},l=m=>{let g=m;for(;g>=0&&/\s/.test(n[g]??"");)g--;return g},u=m=>{let g=l(m-1);if(g<0)return!0;let h=n[g];return h===`
|
|
808
808
|
`||h===";"||h==="{"||h==="}"},d=()=>{let m=i;for(;i<o&&_u(n[i]);)i++;return n.slice(m,i)},p=m=>{let g=n.slice(m,m+2);return n.slice(m,m+3)==="==="||g==="=="||g==="=>"?!1:n[m]==="="||["+=","-=","*=","/=","%=","&=","|=","^=","&&=","||=","??=","**=","<<=",">>=",">>>="].some(x=>n.startsWith(x,m))};for(;i<o;){let m=n[i];if(m==="{"){s++,i++;continue}if(m==="}"){s--,i++;continue}if(m==="("){a++,i++;continue}if(m===")"){a--,i++;continue}if(s===0&&a===0&&Nu(m)){let g=i,h=d();if((h==="function"||h==="class")&&u(g)){let x=c(i);if(Nu(n[x])){let f=x+1;for(;f<o&&_u(n[f]);)f++;let y=n.slice(x,f);if(t.has(y))return y}continue}if(h==="async"&&u(g)){let x=c(i);if(n.startsWith("function",x)){let f=c(x+8);if(Nu(n[f])){let y=f+1;for(;y<o&&_u(n[y]);)y++;let A=n.slice(f,y);if(t.has(A))return A}}continue}if(t.has(h)){let x=l(g-1),f=x>=0?n[x]:void 0,y=c(i),A=f==="."||f==="?"||f==="["&&n[y]==="]",b=n.startsWith("++",y)||n.startsWith("--",y)||x>0&&(n.slice(x-1,x+1)==="++"||n.slice(x-1,x+1)==="--");if(!A&&(b||p(y)))return h}continue}i++}};function Lu(r){if(r==null||typeof r!="object")return String(r);try{return JSON.stringify(r,null,2)}catch{return String(r)}}function Du(r,e=Fu,t=0,n=new Set){if(t>e)return{name:"Error",message:"[cause chain truncated]"};if(r!==null&&typeof r=="object"){if(n.has(r))return{name:"Error",message:"[circular]"};n.add(r)}let o=r!==null&&typeof r=="object"&&r.name!=null?String(r.name):"Error",i=r!==null&&typeof r=="object"&&r.message!=null?String(r.message):Lu(r),s=r!==null&&typeof r=="object"&&typeof r.stack=="string"?r.stack:void 0,a,c=r;if(c&&typeof c=="object"&&c.cause!==void 0&&t<e)try{let d=c.cause;d instanceof Error||d!==null&&typeof d=="object"&&("message"in d||"name"in d)?a=Du(d,e,t+1,n):a={name:"Error",message:Lu(d)}}catch{a={name:"Error",message:Lu(c.cause)}}let l={name:o,message:i};s!==void 0&&(l.stack=s),a!==void 0&&(l.cause=a);let u=r;if(u&&typeof u=="object"&&"data"in u&&u.data!==void 0)try{typeof structuredClone=="function"?l.data=structuredClone(u.data):l.data=u.data}catch{}return l}function ju(r){if(typeof r=="string")return new Error(r);if(!r||typeof r!="object")return new Error(String(r));let e=r.message!=null?String(r.message):"Unknown error",t=new Error(e);return t.name=r.name!=null?String(r.name):"Error",typeof r.stack=="string"&&(t.stack=r.stack),r.cause!==void 0&&(t.cause=ju(r.cause)),r.data!==void 0&&(t.data=r.data),t}function Nv(r){if(!r||typeof r!="object")return!1;let e=r;return typeof e.name=="string"&&typeof e.type=="string"&&(e.ctor===void 0||typeof e.ctor=="string")&&(e.size===void 0||typeof e.size=="string")&&(e.preview===void 0||typeof e.preview=="string")&&(e.restorable===void 0||typeof e.restorable=="boolean")}function vx(r){if(!r||typeof r!="object")return{version:1,entries:[],bindings:{}};let e=r,t=Array.isArray(e.entries)?e.entries:[],n=e.bindings&&typeof e.bindings=="object"?e.bindings:{};return{version:1,entries:t.filter(Nv),bindings:n}}var Bu=()=>typeof Worker<"u"&&typeof Blob<"u"&&typeof URL<"u"&&typeof URL.createObjectURL=="function",Ix=()=>!!globalThis.process?.versions?.bun,Hr=()=>typeof process<"u"&&!!process.versions?.node&&!Ix(),Lv=()=>!!globalThis.Deno?.version?.deno,$v=()=>globalThis.Deno?.version?.deno??null,Uv=r=>{let e=/^(\d+)\.(\d+)\.(\d+)$/.exec(r.trim());return e?{major:Number(e[1]),minor:Number(e[2]),patch:Number(e[3])}:null},Sx=r=>Number.isFinite(r)?Math.max(1,Math.min(bx,Math.floor(r))):Eu,Dv=()=>{if(!Hr())return null;let e=globalThis.process?.getBuiltinModule;if(typeof e!="function")return null;let n=e("node:os")?.availableParallelism;if(typeof n!="function")return null;let o=n();return Number.isFinite(o)&&o>0?o:null},Tx=r=>{if(r!==void 0)return Sx(r);let e=Dv();return e?Sx(Math.ceil(e/2)):Eu},Px=r=>r?.debugNodeWorkerPool?!0:(globalThis.process?.env??{}).AX_RLM_DEBUG_NODE_POOL==="1",jv=(r,e,t)=>{let n=$v(),o=n?Uv(n):null;if(o?o.major>=1:!0)try{return new Worker(r,{type:"module",deno:{permissions:Ax(e,{allowDenoRemoteImport:t})}})}catch{}return new Worker(r,{type:"module"})},Gv=r=>new Worker(r,{smol:!0}),zu=(r,e,t)=>{let n=new Blob([r],{type:"application/javascript"}),o=URL.createObjectURL(n),i=Lv()?jv(o,e,t):Ix()?Gv(o):new Worker(o),s=!1,a=()=>{s||(URL.revokeObjectURL(o),s=!0)},c={postMessage:l=>i.postMessage(l),terminate:()=>{i.terminate(),a()},onmessage:null,onerror:null};return i.onmessage=l=>{c.onmessage?.({data:l.data})},i.onerror=l=>{c.onerror?.(new Error(l.message||"Worker error"))},c},$a=async(r,e,t)=>{let n="node:worker_threads",{Worker:o}=await import(n),i={eval:!0};e&&e.length>0&&(i.execArgv=[...e]),t&&(i.resourceLimits=t);let s=new o(r,i),a=null,c=null,l=!1;s.on("error",d=>{c?c(d):a=d}),s.on("exit",d=>{if(l=!0,d!==0&&!a){let p=new Error(`Worker exited with code ${d}`);c?c(p):a=p}}),s.on("message",d=>{u.onmessage?.({data:d})});let u={postMessage:d=>s.postMessage(d),terminate:()=>{s.terminate()},ref:()=>{s.ref()},unref:()=>{s.unref()},onmessage:null,get onerror(){return c},set onerror(d){if(c=d,d&&a){let p=a;a=null,d(p)}},get exited(){return l}};return u},Gu=class{source;maxSize;execArgv;resourceLimits;idle=[];pendingCreates=0;constructor(e,t,n,o){this.source=e,this.maxSize=t,this.execArgv=n,this.resourceLimits=o}warm(){if(Hr())for(;this.idle.length+this.pendingCreates<this.maxSize;)this.pendingCreates+=1,$a(this.source,this.execArgv,this.resourceLimits).then(e=>{e.onmessage=null,e.onerror=null,e.unref?.(),this.idle.push(e)}).catch(()=>{}).finally(()=>{this.pendingCreates-=1})}async acquire(){for(;this.idle.length>0;){let e=this.idle.pop();if(!e.exited)return e.ref?.(),this.warm(),e}return this.warm(),$a(this.source,this.execArgv,this.resourceLimits)}release(e){e.onmessage=null,e.onerror=null,e.terminate(),this.warm()}},kx=new Map,Bv=(r,e,t,n,o)=>`${e}:${t}:${n}:${o}:${r}`,Mx=(r,e,t,n,o)=>{let i=La(n??[]),s=La(o??{}),a=Bv(r,e,t,i,s),c=kx.get(a);if(c)return c;let l=new Gu(r,e,n,o);return kx.set(a,l),l};var Kr=class{language="JavaScript";timeout;permissions;allowUnsafeNodeHostAccess;nodeWorkerPoolSize;debugNodeWorkerPool;outputMode;captureConsole;blockDynamicImport;allowedModules;freezeIntrinsics;blockShadowRealm;lockWorkerIPC;preventGlobalThisExtensions;useNodePermissionModel;nodePermissionAllowlist;resourceLimits;allowDenoRemoteImport;constructor(e){this.timeout=e?.timeout??9e5,this.permissions=e?.permissions??[],this.allowUnsafeNodeHostAccess=e?.allowUnsafeNodeHostAccess??!1,this.outputMode=e?.outputMode??"stdout",this.captureConsole=e?.captureConsole??this.outputMode==="stdout",this.nodeWorkerPoolSize=Tx(e?.nodeWorkerPoolSize),this.debugNodeWorkerPool=Px(e),this.blockDynamicImport=e?.blockDynamicImport??!0,this.allowedModules=e?.allowedModules??[],this.freezeIntrinsics=e?.freezeIntrinsics??!0,this.blockShadowRealm=e?.blockShadowRealm??!0,this.lockWorkerIPC=e?.lockWorkerIPC??!0,this.preventGlobalThisExtensions=e?.preventGlobalThisExtensions??!1,this.useNodePermissionModel=e?.useNodePermissionModel??"auto",this.nodePermissionAllowlist=e?.nodePermissionAllowlist,this.resourceLimits=e?.resourceLimits,this.allowDenoRemoteImport=e?.allowDenoRemoteImport??!1}computeNodeExecArgv(){return yx({mode:this.useNodePermissionModel,permissions:this.permissions,nodePermissionAllowlist:this.nodePermissionAllowlist})}computeSecurityPostureHash(){return Cx({permissions:this.permissions,allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,blockDynamicImport:this.blockDynamicImport,allowedModules:this.allowedModules,freezeIntrinsics:this.freezeIntrinsics,blockShadowRealm:this.blockShadowRealm,lockWorkerIPC:this.lockWorkerIPC,preventGlobalThisExtensions:this.preventGlobalThisExtensions})}getUsageInstructions(){return["Don't wrap async code in (async()=>{ ... })() \u2014 the runtime automatically handles async execution.","State is session-scoped: all top-level declarations (`var`, `let`, `const`) persist across calls.","Bare assignment (e.g. `x = 1`) also persists via `globalThis`.",...this.outputMode==="stdout"?["Use `console.log(...)` output is captured as the execution result so use it to inspect intermediate values between steps instead of `return`."]:["Use `return` or a trailing expression to produce the execution result."]].map(t=>`- ${t}`).join(`
|
|
809
|
-
`)}createSession(e,t){let n=Rx(),o=Hr()?this.computeNodeExecArgv():void 0,i=this.computeSecurityPostureHash(),s=Hr()?Mx(n,this.nodeWorkerPoolSize,i,o,this.resourceLimits):null;s&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),s?.warm();let a=null,c=null,l=null,u=!1,d=this.timeout,p=0,m=t?.shouldBubbleError,g=null,{serializableGlobals:h,fnMap:x}=$u(e,{nextFnId:()=>++p});Uu(h);let f=new Map,y=0,A=[],b=null,w=I=>{let _=I.data;if(!_||typeof _!="object"||!("type"in _)||_.type===void 0)return;let S=_;if(S.type==="result"){if(typeof S.id!="number")return;let H=f.get(S.id);if(H)if(f.delete(S.id),S.error!==void 0)if(g){let L=g;g=null,H.reject(L)}else H.reject(ju(S.error));else H.resolve(S.value);return}if(S.type==="fn-call"){if(typeof S.id!="number"||typeof S.name!="string")return;let H=x.get(S.name);if(!H){a?.postMessage({type:"fn-result",id:S.id,error:`Function "${S.name}" not found`});return}Promise.resolve().then(()=>H(...S.args??[])).then(L=>{try{a?.postMessage({type:"fn-result",id:S.id,value:L})}catch{a?.postMessage({type:"fn-result",id:S.id,value:String(L)})}}).catch(L=>{m?.(L)&&(g=L),a?.postMessage({type:"fn-result",id:S.id,error:Du(L)})})}},v=()=>{a&&(c==="node"&&s?s.release(a):a.terminate(),a=null,c=null),l=null},F=()=>{u=!0,v();for(let I of A)!I.started&&!I.settled&&(I.settled=!0,I.signal&&I.onAbort&&I.signal.removeEventListener("abort",I.onAbort),I.reject(new Error("Worker terminated")));A.length=0;for(let I of f.values())I.reject(new Error("Worker terminated"));f.clear()},k=I=>{v();for(let _ of f.values())_.reject(I);f.clear()},O=I=>{I.postMessage({type:"init",globals:h,fnNames:[...x.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole,blockDynamicImport:this.blockDynamicImport,blockShadowRealm:this.blockShadowRealm,freezeIntrinsics:this.freezeIntrinsics,lockWorkerIPC:this.lockWorkerIPC,preventGlobalThisExtensions:this.preventGlobalThisExtensions,allowedModules:[...this.allowedModules]})};if(Bu()){a=zu(n,this.permissions,this.allowDenoRemoteImport),c="browser",a.onmessage=w,a.onerror=k;try{O(a)}catch(I){throw F(),I}}let $=async()=>{if(!a){if(u)throw new Error("Session is closed");if(Bu()){a=zu(n,this.permissions,this.allowDenoRemoteImport),c="browser",a.onmessage=w,a.onerror=k;try{O(a)}catch(I){throw F(),I}return}if(!Hr())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");l||(l=(s?s.acquire():$a(n,o,this.resourceLimits)).then(I=>{if(u)throw s?s.release(I):I.terminate(),new Error("Session is closed");a=I,c="node",a.onmessage=w,a.onerror=k;try{O(a)}catch(_){throw s?s.release(I):I.terminate(),a=null,c=null,_}})),await l}},N=(I,_)=>{if(u)return Promise.reject(new Error("Session is closed"));let S=_.signal;if(S?.aborted)return Promise.reject(new Error(`Aborted: ${S.reason??"execution aborted"}`));let H=++y;return new Promise((L,W)=>{let U=L,Y=W,C,T=()=>{};if(f.set(H,{resolve:E=>{C&&clearTimeout(C),T(),U(E)},reject:E=>{C&&clearTimeout(C),T(),Y(E)}}),S){let E=()=>{clearTimeout(C),f.delete(H),F(),Y(new Error(`Aborted: ${S.reason??"execution aborted"}`))};S.addEventListener("abort",E,{once:!0}),T=()=>{S.removeEventListener("abort",E)}}$().then(()=>{if(!a)throw new Error("Worker unavailable");C=setTimeout(()=>{f.delete(H),v();for(let E of f.values())E.reject(new Error("Worker terminated"));f.clear(),W(new Error(_.timeoutMessage))},d),a.postMessage({...I,id:H})}).catch(E=>{f.get(H)&&(f.delete(H),clearTimeout(C),T(),Y(E))})})},V=(I,_)=>u?Promise.reject(new Error("Session is closed")):I?.aborted?Promise.reject(new Error(`Aborted: ${I.reason??"execution aborted"}`)):new Promise((S,H)=>{let L={started:!1,settled:!1,signal:I,resolve:S,reject:H,operation:_};if(I){let U=()=>{if(L.settled)return;L.settled=!0;let Y=A.indexOf(L);Y!==-1&&A.splice(Y,1),I.removeEventListener("abort",U),H(new Error(`Aborted: ${I.reason??"execution aborted"}`))};L.onAbort=U,I.addEventListener("abort",U,{once:!0})}A.push(L);let W=()=>{if(b)return;let U=A.find(C=>!C.started&&!C.settled);if(!U)return;let Y=()=>{b=null,W()};b=(async()=>{if(!U.settled){if(u){U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(new Error("Worker terminated"));return}if(U.signal?.aborted){U.settled=!0,U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(new Error(`Aborted: ${U.signal.reason??"execution aborted"}`));return}U.started=!0;try{let C=await U.operation();if(U.settled)return;U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.resolve(C)}catch(C){if(U.settled)return;U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(C)}finally{let C=A.indexOf(U);C!==-1&&A.splice(C,1),Y()}}})().catch(()=>{Y()})};W()});return{execute(I,_){if(u)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(I))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let S=_?.reservedNames;if(S){let H=wx(I,S);if(H)return Promise.resolve(`[ERROR] Cannot assign to, redeclare, or shadow reserved runtime variable '${H}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${H}\`.`)}return V(_?.signal,()=>N({type:"execute",code:I},{signal:_?.signal,timeoutMessage:"Execution timed out"}))},inspectGlobals(I){return u?Promise.reject(new Error("Session is closed")):V(I?.signal,()=>N({type:"inspect-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global inspection timed out"}).then(_=>typeof _=="string"?_:_===void 0?"":JSON.stringify(_)))},snapshotGlobals(I){return u?Promise.reject(new Error("Session is closed")):V(I?.signal,()=>N({type:"snapshot-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global snapshot timed out"}).then(vx))},async patchGlobals(I,_){if(!I||typeof I!="object"||Array.isArray(I))throw new Error("patchGlobals expects an object");let{serializableGlobals:S,fnMap:H}=$u(I,{nextFnId:()=>++p});if(Uu(S),Object.keys(S).length!==0){await V(_?.signal,()=>N({type:"update-globals",globals:S},{signal:_?.signal,timeoutMessage:"Global patch timed out"}));for(let[L,W]of Object.entries(S))h[L]=W;for(let[L,W]of H.entries())x.set(L,W)}},close(){F()}}}toFunction(){return{name:"javascriptInterpreter",description:"Execute JavaScript code in a persistent session and return output.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute."}},required:["code"]},func:async({code:e},t)=>{let n=this.createSession();try{return await n.execute(e,{signal:t?.abortSignal})}finally{n.close()}}}}};function zv(r){return new Kr(r)}function Ex(r,e,t){let n=r,{ai:o,judgeAI:i,agentIdentity:s,signature:a}=e;n.stagePolicy=cn(t.stageVariant);let{debug:c,contextFields:l=[],runtime:u,maxSubAgentCalls:d,maxBatchedLlmQueryConcurrency:p,maxTurns:m,maxRuntimeChars:g,maxEvidenceChars:h,contextPolicy:x,summarizerOptions:f,actorTurnCallback:y,agentStatusCallback:A,mode:b,executorModelPolicy:w,recursionOptions:v,executorOptions:F,responderOptions:k,judgeOptions:O,inputUpdateCallback:$,bubbleErrors:N,onFunctionCall:V,onContextEvent:I,contextMapText:_}=t;n.ai=o,n.judgeAI=i,n.agentIdentity=s?{...s}:void 0,n.autoUpgrade=xa(t.autoUpgrade),n.functionDiscoveryEnabled=t.functionDiscovery??!1;let S=t.relevanceRanking,H=S===void 0?!0:S!==!1;n._relevanceRankingChoice=H,n.relevanceRankingOptions=typeof S=="object"&&S!==null?S:{},n.moduleHintEnabled=n.functionDiscoveryEnabled&&H;let L=Array.isArray(t.skillsCatalog)?t.skillsCatalog.slice():void 0;n.skillsCatalog=L,n.onSkillsSearch=t.onSkillsSearch??(L&&L.length>0?Hh(L):void 0),n.skillsHintEnabled=H&&Array.isArray(L)&&L.length>0,n.onLoadedSkills=t.onLoadedSkills,n.onUsedSkills=t.onUsedSkills;let W=Array.isArray(t.memoriesCatalog)?t.memoriesCatalog.slice():void 0;n.memoriesCatalog=W,n.onMemoriesSearch=t.onMemoriesSearch??(W&&W.length>0?$h(W):void 0),n.onLoadedMemories=t.onLoadedMemories,n.onUsedMemories=t.onUsedMemories,n.memoryUsageTrackingEnabled=typeof n.onMemoriesSearch=="function"&&typeof t.onUsedMemories=="function",n.memoriesHintEnabled=H&&Array.isArray(W)&&W.length>0,n.relevanceHintsEnabled=n.moduleHintEnabled||n.skillsHintEnabled||n.memoriesHintEnabled,n.skillUsageTrackingEnabled=typeof t.onUsedSkills=="function",n.usageTrackingEnabled=n.memoryUsageTrackingEnabled||n.skillUsageTrackingEnabled,n.currentSkillsPromptState=vu(),n.presetSkills=Array.isArray(t.skills)?t.skills.slice():void 0,n.presetSkills&&n.presetSkills.length>0&&Tn(n.currentSkillsPromptState,n.presetSkills),n.debug=c,n.options=t,n.contextMapText=typeof _=="string"&&_.trim()?_:void 0,n.runtime=u??new Kr;let U=Il(n.runtime);n.runtimeLanguageName=U.languageName,n.runtimeCodeFieldName=U.codeFieldName,n.runtimeCodeFieldTitle=U.codeFieldTitle,n.runtimeCodeFenceLanguage=U.codeFenceLanguage,n.isJavaScriptRuntime=U.isJavaScript,n.runtimeUsageInstructions=n.runtime.getUsageInstructions(),n.enforceIncrementalConsoleTurns=dh(n.runtimeUsageInstructions,{isJavaScriptRuntime:n.isJavaScriptRuntime});let Y=n._reservedAgentFunctionNamespaces(),C=hh(t.functions,Y);n.agentFunctions=C.functions,n.agents=C.agents,n._mergeAgentFunctionModuleMetadata(C.moduleMetadata),n.directRespondEnabled=xf(t.directResponse)!=="off",n.directRespondStatic=C.functions.length===0&&C.agents.length===0,t.functionDiscovery===void 0&&n.autoUpgrade.functionDiscovery.enabled&&!n.agentFunctions.some(ye=>(ye.namespace??"utils")===In)&&Rh(n.agentFunctions)>n.autoUpgrade.functionDiscovery.aboveFunctionDocChars&&(n.functionDiscoveryEnabled=!0,n.moduleHintEnabled=H,n.relevanceHintsEnabled=n.moduleHintEnabled||n.skillsHintEnabled||n.memoriesHintEnabled);let{functions:T,functionDiscovery:E,autoUpgrade:D,directResponse:j,relevanceRanking:J,skills:z,skillsCatalog:B,memoriesCatalog:K,onSkillsSearch:ie,onLoadedSkills:oe,onUsedSkills:se,onMemoriesSearch:me,onLoadedMemories:Z,onUsedMemories:Be,judgeOptions:ut,inputUpdateCallback:de,executorModelPolicy:Ve,maxRuntimeChars:Ae,maxEvidenceChars:at,summarizerOptions:dt,actorTurnCallback:ne,onFunctionCall:ve,onContextEvent:ke,contextMap:He,contextMapText:we,description:Ie,mem:Ue,...X}=t;n.program=new Ee(a,X);let he=n.program.getSignature().getInputFields(),Ce=ch(l,he,1200);n.contextPromptConfigByField=Ce.promptConfigByField,n.rlmConfig={contextFields:Ce.contextFieldNames,promptLevel:t.promptLevel,runtime:n.runtime,maxSubAgentCalls:d,maxBatchedLlmQueryConcurrency:p,maxTurns:m,maxRuntimeChars:g,maxEvidenceChars:h,contextPolicy:x,summarizerOptions:f,actorTurnCallback:y,onContextEvent:I,agentStatusCallback:A,mode:b},n.recursionForwardOptions=v,n.bubbleErrors=N;let{description:Le,...re}=F??{};if(n.executorDescription=Le,n.executorModelPolicy=bf(w),n.executorForwardOptions=re,n.judgeOptions=O?{...O}:void 0,n.inputUpdateCallback=$,n.agentStatusCallback=A,n.onFunctionCall=V,n.onContextEvent=I,n.stagePolicy.ownsChildAgents)for(let ye of n.agents??[]){let Te=ye.getFunction().name;n.program.register(ye,Te)}else n.agents=void 0;s&&(n.func={name:Ta(s.name),description:s.description,parameters:n._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let De=[...n.agentFunctions];for(let ye of De){if(!ye.parameters)throw new Error(`Agent function "${ye.name}" must define parameters schema for agent runtime usage.`);if(ye.examples){for(let[Te,$e]of ye.examples.entries())if(!$e.code.trim())throw new Error(`Agent function "${ye.name}" example at index ${Te} must define non-empty code`)}}n._validateConfiguredSignature(n.program.getSignature()),n._validateAgentFunctionNamespaces(De),n._buildSplitPrograms(),n.program.register(n.actorProgram,"actor")}function qu(r){let e=r;if(!e.actorDefinitionBuildOptions)return e.baseActorDefinition;let t={...e.actorDefinitionBuildOptions,templateOverride:e._actorTemplateOverrides?.get(e._actorTemplateId()),primitiveOverrides:Nr(e.runtime,e._primitiveOverrides)};return(e.stagePolicy??cn(e.options?.stageVariant)).templateId==="rlm/distiller.md"?Eo(e.actorDefinitionBaseDescription,e.actorDefinitionContextFields,t):Oo(e.actorDefinitionBaseDescription,e.actorDefinitionContextFields,e.actorDefinitionResponderOutputFields,t)}function Ox(r){return qu(r).trim()}function Fx(r){return!1}function _x(r){return r.namedProgramInstances().map(t=>({id:t.id,signature:t.signature,program:t.program}))}function Nx(r){let{s:e,sessionRef:t,effectiveAbortSignal:n,protectedRuntimeNames:o,completionState:i,getMaxRuntimeChars:s,waitForCompletionSignal:a,detectCompletionSignalCalls:c,createSession:l}=r;return{executeActorCode:async p=>{let m={result:void 0,output:Yo(void 0,s()),isError:!1};try{let g=await t.current.execute(p,{signal:n,reservedNames:o});return i.payload||c&&Sa(p)&&xu(g)&&(await a(),i.payload)?m:{result:g,output:Yo(g,s()),isError:!1}}catch(g){if(g instanceof vt||i.payload)return m;if(g instanceof et||g instanceof Ne||e.shouldBubbleUserError(g))throw g;if(n?.aborted)throw new Ne("rlm-session",n.reason??"Aborted");if(g instanceof Error&&(g.name==="AbortError"||g.message.startsWith("Aborted")))throw g;if(sh(g)){let x=s();return{result:void 0,output:xt(`${Wo}
|
|
809
|
+
`)}createSession(e,t){let n=Rx(),o=Hr()?this.computeNodeExecArgv():void 0,i=this.computeSecurityPostureHash(),s=Hr()?Mx(n,this.nodeWorkerPoolSize,i,o,this.resourceLimits):null;s&&this.debugNodeWorkerPool&&console.debug(`[AxJSRuntime] Node worker pool size: ${this.nodeWorkerPoolSize}`),s?.warm();let a=null,c=null,l=null,u=!1,d=this.timeout,p=0,m=t?.shouldBubbleError,g=null,{serializableGlobals:h,fnMap:x}=$u(e,{nextFnId:()=>++p});Uu(h);let f=new Map,y=0,A=[],b=null,w=I=>{let _=I.data;if(!_||typeof _!="object"||!("type"in _)||_.type===void 0)return;let S=_;if(S.type==="result"){if(typeof S.id!="number")return;let H=f.get(S.id);if(H)if(f.delete(S.id),S.error!==void 0)if(g){let L=g;g=null,H.reject(L)}else H.reject(ju(S.error));else H.resolve(S.value);return}if(S.type==="fn-call"){if(typeof S.id!="number"||typeof S.name!="string")return;let H=x.get(S.name);if(!H){a?.postMessage({type:"fn-result",id:S.id,error:`Function "${S.name}" not found`});return}Promise.resolve().then(()=>H(...S.args??[])).then(L=>{try{a?.postMessage({type:"fn-result",id:S.id,value:L})}catch{a?.postMessage({type:"fn-result",id:S.id,value:String(L)})}}).catch(L=>{m?.(L)&&(g=L),a?.postMessage({type:"fn-result",id:S.id,error:Du(L)})})}},v=()=>{a&&(c==="node"&&s?s.release(a):a.terminate(),a=null,c=null),l=null},F=()=>{u=!0,v();for(let I of A)!I.started&&!I.settled&&(I.settled=!0,I.signal&&I.onAbort&&I.signal.removeEventListener("abort",I.onAbort),I.reject(new Error("Worker terminated")));A.length=0;for(let I of f.values())I.reject(new Error("Worker terminated"));f.clear()},k=I=>{v();for(let _ of f.values())_.reject(I);f.clear()},O=I=>{I.postMessage({type:"init",globals:h,fnNames:[...x.keys()],permissions:[...this.permissions],allowUnsafeNodeHostAccess:this.allowUnsafeNodeHostAccess,outputMode:this.outputMode,captureConsole:this.captureConsole,blockDynamicImport:this.blockDynamicImport,blockShadowRealm:this.blockShadowRealm,freezeIntrinsics:this.freezeIntrinsics,lockWorkerIPC:this.lockWorkerIPC,preventGlobalThisExtensions:this.preventGlobalThisExtensions,allowedModules:[...this.allowedModules]})};if(Bu()){a=zu(n,this.permissions,this.allowDenoRemoteImport),c="browser",a.onmessage=w,a.onerror=k;try{O(a)}catch(I){throw F(),I}}let $=async()=>{if(!a){if(u)throw new Error("Session is closed");if(Bu()){a=zu(n,this.permissions,this.allowDenoRemoteImport),c="browser",a.onmessage=w,a.onerror=k;try{O(a)}catch(I){throw F(),I}return}if(!Hr())throw new Error("No worker runtime available: Web Worker is unavailable in this environment");l||(l=(s?s.acquire():$a(n,o,this.resourceLimits)).then(I=>{if(u)throw s?s.release(I):I.terminate(),new Error("Session is closed");a=I,c="node",a.onmessage=w,a.onerror=k;try{O(a)}catch(_){throw s?s.release(I):I.terminate(),a=null,c=null,_}})),await l}},N=(I,_)=>{if(u)return Promise.reject(new Error("Session is closed"));let S=_.signal;if(S?.aborted)return Promise.reject(new Error(`Aborted: ${S.reason??"execution aborted"}`));let H=++y;return new Promise((L,W)=>{let U=L,Y=W,C,T=()=>{};if(f.set(H,{resolve:E=>{C&&clearTimeout(C),T(),U(E)},reject:E=>{C&&clearTimeout(C),T(),Y(E)}}),S){let E=()=>{clearTimeout(C),f.delete(H),F(),Y(new Error(`Aborted: ${S.reason??"execution aborted"}`))};S.addEventListener("abort",E,{once:!0}),T=()=>{S.removeEventListener("abort",E)}}$().then(()=>{if(!a)throw new Error("Worker unavailable");C=setTimeout(()=>{f.delete(H),v();for(let E of f.values())E.reject(new Error("Worker terminated"));f.clear(),W(new Error(_.timeoutMessage))},d),a.postMessage({...I,id:H})}).catch(E=>{f.get(H)&&(f.delete(H),clearTimeout(C),T(),Y(E))})})},V=(I,_)=>u?Promise.reject(new Error("Session is closed")):I?.aborted?Promise.reject(new Error(`Aborted: ${I.reason??"execution aborted"}`)):new Promise((S,H)=>{let L={started:!1,settled:!1,signal:I,resolve:S,reject:H,operation:_};if(I){let U=()=>{if(L.settled)return;L.settled=!0;let Y=A.indexOf(L);Y!==-1&&A.splice(Y,1),I.removeEventListener("abort",U),H(new Error(`Aborted: ${I.reason??"execution aborted"}`))};L.onAbort=U,I.addEventListener("abort",U,{once:!0})}A.push(L);let W=()=>{if(b)return;let U=A.find(C=>!C.started&&!C.settled);if(!U)return;let Y=()=>{b=null,W()};b=(async()=>{if(!U.settled){if(u){U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(new Error("Worker terminated"));return}if(U.signal?.aborted){U.settled=!0,U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(new Error(`Aborted: ${U.signal.reason??"execution aborted"}`));return}U.started=!0;try{let C=await U.operation();if(U.settled)return;U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.resolve(C)}catch(C){if(U.settled)return;U.settled=!0,U.signal&&U.onAbort&&U.signal.removeEventListener("abort",U.onAbort),U.reject(C)}finally{let C=A.indexOf(U);C!==-1&&A.splice(C,1),Y()}}})().catch(()=>{Y()})};W()});return{execute(I,_){if(u)return Promise.reject(new Error("Session is closed"));if(/['"]use strict['"]/.test(I))return Promise.resolve('[ERROR] "use strict" is not allowed in the runtime session. Remove it and try again.');let S=_?.reservedNames;if(S){let H=wx(I,S);if(H)return Promise.resolve(`[ERROR] Cannot assign to, redeclare, or shadow reserved runtime variable '${H}'. Use a different local variable name (for example: \`ctx\`) or access the original via \`inputs.${H}\`.`)}return V(_?.signal,()=>N({type:"execute",code:I},{signal:_?.signal,timeoutMessage:"Execution timed out"}))},inspectGlobals(I){return u?Promise.reject(new Error("Session is closed")):V(I?.signal,()=>N({type:"inspect-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global inspection timed out"}).then(_=>typeof _=="string"?_:_===void 0?"":JSON.stringify(_)))},snapshotGlobals(I){return u?Promise.reject(new Error("Session is closed")):V(I?.signal,()=>N({type:"snapshot-globals",reservedNames:I?.reservedNames},{signal:I?.signal,timeoutMessage:"Global snapshot timed out"}).then(vx))},async patchGlobals(I,_){if(!I||typeof I!="object"||Array.isArray(I))throw new Error("patchGlobals expects an object");let{serializableGlobals:S,fnMap:H}=$u(I,{nextFnId:()=>++p});if(Uu(S),Object.keys(S).length!==0){await V(_?.signal,()=>N({type:"update-globals",globals:S},{signal:_?.signal,timeoutMessage:"Global patch timed out"}));for(let[L,W]of Object.entries(S))h[L]=W;for(let[L,W]of H.entries())x.set(L,W)}},close(){F()}}}toFunction(){return{name:"javascriptInterpreter",description:"Execute JavaScript code in a persistent session and return output.",parameters:{type:"object",properties:{code:{type:"string",description:"JavaScript code to execute."}},required:["code"]},func:async({code:e},t)=>{let n=this.createSession();try{return await n.execute(e,{signal:t?.abortSignal})}finally{n.close()}}}}};function zv(r){return new Kr(r)}function Ex(r,e,t){let n=r,{ai:o,judgeAI:i,agentIdentity:s,signature:a}=e;n.stagePolicy=cn(t.stageVariant);let{debug:c,contextFields:l=[],runtime:u,maxSubAgentCalls:d,maxBatchedLlmQueryConcurrency:p,maxTurns:m,maxRuntimeChars:g,maxEvidenceChars:h,contextPolicy:x,summarizerOptions:f,actorTurnCallback:y,agentStatusCallback:A,mode:b,executorModelPolicy:w,recursionOptions:v,executorOptions:F,responderOptions:k,judgeOptions:O,inputUpdateCallback:$,bubbleErrors:N,onFunctionCall:V,onContextEvent:I,contextMapText:_}=t;n.ai=o,n.judgeAI=i,n.agentIdentity=s?{...s}:void 0,n.autoUpgrade=xa(t.autoUpgrade),n.functionDiscoveryEnabled=t.functionDiscovery??!1;let S=t.relevanceRanking,H=S===void 0?!0:S!==!1;n._relevanceRankingChoice=H,n.relevanceRankingOptions=typeof S=="object"&&S!==null?S:{},n.moduleHintEnabled=n.functionDiscoveryEnabled&&H;let L=Array.isArray(t.skillsCatalog)?t.skillsCatalog.slice():void 0;n.skillsCatalog=L,n.onSkillsSearch=t.onSkillsSearch??(L&&L.length>0?Hh(L):void 0),n.skillsHintEnabled=H&&Array.isArray(L)&&L.length>0,n.onLoadedSkills=t.onLoadedSkills,n.onUsedSkills=t.onUsedSkills;let W=Array.isArray(t.memoriesCatalog)?t.memoriesCatalog.slice():void 0;n.memoriesCatalog=W,n.onMemoriesSearch=t.onMemoriesSearch??(W&&W.length>0?$h(W):void 0),n.onLoadedMemories=t.onLoadedMemories,n.onUsedMemories=t.onUsedMemories,n.memoryUsageTrackingEnabled=typeof n.onMemoriesSearch=="function"&&typeof t.onUsedMemories=="function",n.memoriesHintEnabled=H&&Array.isArray(W)&&W.length>0,n.relevanceHintsEnabled=n.moduleHintEnabled||n.skillsHintEnabled||n.memoriesHintEnabled,n.skillUsageTrackingEnabled=typeof t.onUsedSkills=="function",n.usageTrackingEnabled=n.memoryUsageTrackingEnabled||n.skillUsageTrackingEnabled,n.currentSkillsPromptState=vu(),n.presetSkills=Array.isArray(t.skills)?t.skills.slice():void 0,n.presetSkills&&n.presetSkills.length>0&&Tn(n.currentSkillsPromptState,n.presetSkills),n.debug=c,n.options=t,n.contextMapText=typeof _=="string"&&_.trim()?_:void 0,n.runtime=u??new Kr;let U=Il(n.runtime);n.runtimeLanguageName=U.languageName,n.runtimeCodeFieldName=U.codeFieldName,n.runtimeCodeFieldTitle=U.codeFieldTitle,n.runtimeCodeFenceLanguage=U.codeFenceLanguage,n.isJavaScriptRuntime=U.isJavaScript,n.runtimeUsageInstructions=n.runtime.getUsageInstructions(),n.enforceIncrementalConsoleTurns=dh(n.runtimeUsageInstructions,{isJavaScriptRuntime:n.isJavaScriptRuntime});let Y=n._reservedAgentFunctionNamespaces(),C=hh(t.functions,Y);n.agentFunctions=C.functions,n.agents=C.agents,n._mergeAgentFunctionModuleMetadata(C.moduleMetadata),n.directRespondEnabled=xf(t.directResponse)!=="off",n.directRespondStatic=C.functions.length===0&&C.agents.length===0,t.functionDiscovery===void 0&&n.autoUpgrade.functionDiscovery.enabled&&!n.agentFunctions.some(ye=>(ye.namespace??"utils")===In)&&Rh(n.agentFunctions)>n.autoUpgrade.functionDiscovery.aboveFunctionDocChars&&(n.functionDiscoveryEnabled=!0,n.moduleHintEnabled=H,n.relevanceHintsEnabled=n.moduleHintEnabled||n.skillsHintEnabled||n.memoriesHintEnabled);let{functions:T,functionDiscovery:E,autoUpgrade:D,directResponse:j,relevanceRanking:J,skills:z,skillsCatalog:B,memoriesCatalog:K,onSkillsSearch:ie,onLoadedSkills:oe,onUsedSkills:se,onMemoriesSearch:me,onLoadedMemories:Z,onUsedMemories:Be,judgeOptions:ut,inputUpdateCallback:de,executorModelPolicy:Ve,maxRuntimeChars:Ae,maxEvidenceChars:at,summarizerOptions:dt,actorTurnCallback:ne,onFunctionCall:ve,onContextEvent:ke,contextMap:He,contextMapText:we,description:Ie,mem:Ue,...X}=t;n.program=new Ee(a,X);let he=n.program.getSignature().getInputFields(),Ce=ch(l,he,1200);n.contextPromptConfigByField=Ce.promptConfigByField,n.rlmConfig={contextFields:Ce.contextFieldNames,promptLevel:t.promptLevel,runtime:n.runtime,maxSubAgentCalls:d,maxBatchedLlmQueryConcurrency:p,maxTurns:m,maxRuntimeChars:g,maxEvidenceChars:h,contextPolicy:x,summarizerOptions:f,actorTurnCallback:y,onContextEvent:I,agentStatusCallback:A,mode:b},n.recursionForwardOptions=v,n.bubbleErrors=N;let{description:Le,...re}=F??{};if(n.executorDescription=Le,n.executorModelPolicy=bf(w),n.executorForwardOptions=re,n.judgeOptions=O?{...O}:void 0,n.inputUpdateCallback=$,n.agentStatusCallback=A,n.onFunctionCall=V,n.onContextEvent=I,n.stagePolicy.ownsChildAgents)for(let ye of n.agents??[]){let Te=ye.getFunction().name;n.program.register(ye,Te)}else n.agents=void 0;s&&(n.func={name:Ta(s.name),description:s.description,parameters:n._buildFuncParameters(),func:async()=>{throw new Error("Use getFunction() to get a callable wrapper")}});let De=[...n.agentFunctions];for(let ye of De){if(!ye.parameters)throw new Error(`Agent function "${ye.name}" must define parameters schema for agent runtime usage.`);if(ye.examples){for(let[Te,$e]of ye.examples.entries())if(!$e.code.trim())throw new Error(`Agent function "${ye.name}" example at index ${Te} must define non-empty code`)}}n._validateConfiguredSignature(n.program.getSignature()),n._validateAgentFunctionNamespaces(De),n._buildSplitPrograms(),n.program.register(n.actorProgram,"actor")}function qu(r){let e=r;if(!e.actorDefinitionBuildOptions)return e.baseActorDefinition;let t={...e.actorDefinitionBuildOptions,templateOverride:e._actorTemplateOverrides?.get(e._actorTemplateId()),primitiveOverrides:Nr(e.runtime,e._primitiveOverrides)};return(e.stagePolicy??cn(e.options?.stageVariant)).templateId==="rlm/distiller.md"?Eo(e.actorDefinitionBaseDescription,e.actorDefinitionContextFields,t):Oo(e.actorDefinitionBaseDescription,e.actorDefinitionContextFields,e.actorDefinitionResponderOutputFields,t)}function Ox(r){return qu(r).trim()}function Fx(r){return!1}function _x(r){return r.namedProgramInstances().map(t=>({id:t.id,signature:t.signature,program:t.program}))}function Nx(r){let{s:e,sessionRef:t,effectiveAbortSignal:n,protectedRuntimeNames:o,completionState:i,getMaxRuntimeChars:s,waitForCompletionSignal:a,detectCompletionSignalCalls:c,createSession:l}=r;return{executeActorCode:async p=>{let m={result:void 0,output:Yo(void 0,s()),isError:!1};try{let g=await t.current.execute(p,{signal:n,reservedNames:o});return i.payload||c&&Sa(p)&&xu(g)&&(await a(),i.payload)?m:{result:g,output:Yo(g,s()),isError:!1}}catch(g){if(g instanceof vt||i.payload)return m;if(g instanceof et||g instanceof _e||e.shouldBubbleUserError(g))throw g;if(n?.aborted)throw new _e("rlm-session",n.reason??"Aborted");if(g instanceof Error&&(g.name==="AbortError"||g.message.startsWith("Aborted")))throw g;if(sh(g)){let x=s();return{result:void 0,output:xt(`${Wo}
|
|
810
810
|
${Bn(g,x)}`,x),isError:!0}}if(ka(g))try{t.current=l(),i.payload=void 0;let x=await t.current.execute(p,{signal:n,reservedNames:o}),f=s();return{result:x,output:xt(`${Wo}
|
|
811
|
-
${Yo(x,f)}`,f),isError:!1}}catch(x){if(x instanceof et||x instanceof
|
|
812
|
-
${Bn(x,f)}`,f),isError:!0}}let h=s();return{result:void 0,output:xt(Bn(g,h),h),isError:!0}}},executeTestCode:async p=>{let m=()=>{if(!i.payload)throw new Error("Expected completion payload");return i.payload.type==="guide_agent"?Pa(i.payload):i.payload};try{let g=await t.current.execute(p,{signal:n,reservedNames:o});if(c&&Sa(p)&&xu(g)&&await a(),i.payload)return m();let h=Yo(g,s());if(ah(h))throw new Error(h);return h}catch(g){if((g instanceof vt||i.payload)&&i.payload)return m();throw g}}}}Cn();function Lx(r){let{self:e,ai:t,debug:n,effectiveAbortSignal:o,llmQueryBudgetState:i,maxBatchedLlmQueryConcurrency:s,recursionForwardOptions:a,parentForwardOptions:c,simpleChildSignature:l,llmCallWarnThreshold:u,getMaxRuntimeChars:d}=r,p=e,m=()=>new Ee(l,a),g=async(h,x)=>{if(!Array.isArray(h)&&typeof h=="object"&&h!==null&&"query"in h)return g(h.query,h.context??x);if(o?.aborted)throw new
|
|
813
|
-
[WARNING] ${i.localUsed}/${i.localMax} sub-queries used (${w} remaining). Consolidate remaining work.`}return b};return{llmQuery:g}}function $x(r){let{s:e,inputState:t,stageVariant:n,onUsedMemories:o,onUsedSkills:i}=r,s=new Set,a=Ru(),c=f=>{for(let y of f){let A=y.trim();A&&s.add(A)}},l=(f,y)=>{for(let A of f){let b=A.trim(),w=y[A]??y[b];w&&(e.currentDiscoveryPromptState.modules.set(b,w),a.modules.add(b),a.texts.add(w))}},u=(f,y)=>{for(let A of f){let b=qr(A),w=y[A]??y[b];w&&(e.currentDiscoveryPromptState.functions.set(b,w),a.functions.add(b),a.texts.add(w))}},d=f=>{Tn(e.currentSkillsPromptState,f),typeof e.onLoadedSkills=="function"&&Promise.resolve(e.onLoadedSkills(f)).catch(()=>{})},p=typeof e.onMemoriesSearch=="function",m=p?Ea(Array.isArray(t.currentInputs?.memories)?t.currentInputs.memories:[],[]):[];return p&&(t.currentInputs.memories=m),{noteDiscoveredActorModelNamespaces:c,noteDiscoveredModules:l,noteDiscoveredFunctions:u,noteLoadedSkills:d,noteLoadedMemories:f=>{p&&(m=Ea(m,f),t.currentInputs.memories=m,typeof e.onLoadedMemories=="function"&&Promise.resolve(e.onLoadedMemories(f)).catch(()=>{}))},noteUsed:(f,y)=>{if(e.usageTrackingEnabled===!0){if(p&&e.memoryUsageTrackingEnabled===!0){let A=jh(f,y,m,n);A&&o?.([A])}if(e.skillUsageTrackingEnabled===!0){let A=Wh(f,y,e.currentSkillsPromptState,n);A&&i?.([A])}}},consumeDiscoveryTurnArtifacts:()=>{let f=Sh(a),y=[...a.texts];return a=Ru(),{...f?{summary:f}:{},texts:y}},getCurrentMemories:()=>m,getDiscoveredActorModelNamespaces:()=>[...s]}}function Hv(r){return typeof r.inspectGlobals=="function"?r:void 0}function zn(r){if(typeof r.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return r}function Ux(r){if(typeof r.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return r}function Dx(r){let{sessionRef:e,effectiveAbortSignal:t,inspectReservedNames:n,bootstrapGlobalNames:o,runtimeActionLogEntries:i,allowJavaScriptFallback:s=!0}=r,a,c=async()=>{if(!s)return[];try{let m=await e.current.execute(qf(),{signal:t,reservedNames:n});if(typeof m!="string")return[];let g=JSON.parse(m);return Array.isArray(g)?g.filter(h=>typeof h=="string"&&!o.has(h)):[]}catch{return[]}},l=async()=>(a||(a=await c()),a);return{loadInspectBaselineNames:c,ensureInspectBaselineNames:l,inspectRuntimeState:async()=>{try{let m=Hv(e.current);if(m?.inspectGlobals)return await m.inspectGlobals({signal:t,reservedNames:n});if(!s)return"[runtime state inspection unavailable: runtime session does not implement inspectGlobals()]";let g=await l(),h=zf(n,g),x=await e.current.execute(h,{signal:t,reservedNames:n});return typeof x=="string"?x:String(x)}catch(m){return`[inspectRuntime error: ${m instanceof Error?m.message:String(m)}]`}},renderRuntimeState:(m,g)=>{let h=rh(m);if(!h)return ih(m,g);let x=zr(i);return Jo(h,x,g)},resetInspectBaseline:()=>{a=void 0}}}function Ua(r,e){let t=new Set(e),n={};for(let[i,s]of Object.entries(r.runtimeBindings??{}))t.has(i)||(n[i]=s);let o=(r.runtimeEntries??[]).filter(i=>!t.has(i.name));return{runtimeBindings:n,runtimeEntries:o,actionLogEntries:Mg(r.actionLogEntries),guidanceLogEntries:(r.guidanceLogEntries??[]).map(i=>({turn:i.turn,guidance:i.guidance,...i.triggeredBy?{triggeredBy:i.triggeredBy}:{}})),checkpointState:r.checkpointState,discoveryPromptState:r.discoveryPromptState,skillsPromptState:r.skillsPromptState,provenance:{...r.provenance??{}},actorModelState:Rf(r.actorModelState)}}function jx(r){let{s:e,runtime:t,stagePolicy:n,sharedSession:o,sharedActive:i,effectiveAbortSignal:s,effectiveContextConfig:a,baseMaxRuntimeChars:c,getMaxRuntimeChars:l,llmQueryBudgetState:u,completionState:d,guidanceState:p,completionBindings:m,guardedFinalFunction:g,respondBinding:h,llmQuery:x,toolGlobals:f,runtimeInputs:y,runtimeTopLevelInputAliases:A,refreshRuntimeBindings:b,inspectReservedNames:w,bootstrapGlobals:v,bootstrapGlobalNames:F,runtimeActionLogEntries:k}=r,O,$={get current(){return O},set current(z){O=z}},{inspectRuntimeState:N,renderRuntimeState:V,resetInspectBaseline:I}=Dx({sessionRef:$,effectiveAbortSignal:s,inspectReservedNames:w,bootstrapGlobalNames:F,runtimeActionLogEntries:k,allowJavaScriptFallback:e.isJavaScriptRuntime!==!1}),_=a.stateInspection.enabled?async()=>V(await N()):void 0,S=()=>({llmQuery:x,final:g,askClarification:m.askClarificationFunction,...h?{respond:h}:{},..._?{inspectRuntime:_}:{},...e.agentStatusCallback?{reportSuccess:async z=>{await e.agentStatusCallback(z,"success")},reportFailure:async z=>{await e.agentStatusCallback(z,"failed")}}:{},...f}),H=()=>{I();let z=t.createSession({...A,inputs:y,...v,...S()},{shouldBubbleError:B=>B instanceof et||B instanceof
|
|
811
|
+
${Yo(x,f)}`,f),isError:!1}}catch(x){if(x instanceof et||x instanceof _e||e.shouldBubbleUserError(x))throw x;let f=s();return{result:void 0,output:xt(`${Wo}
|
|
812
|
+
${Bn(x,f)}`,f),isError:!0}}let h=s();return{result:void 0,output:xt(Bn(g,h),h),isError:!0}}},executeTestCode:async p=>{let m=()=>{if(!i.payload)throw new Error("Expected completion payload");return i.payload.type==="guide_agent"?Pa(i.payload):i.payload};try{let g=await t.current.execute(p,{signal:n,reservedNames:o});if(c&&Sa(p)&&xu(g)&&await a(),i.payload)return m();let h=Yo(g,s());if(ah(h))throw new Error(h);return h}catch(g){if((g instanceof vt||i.payload)&&i.payload)return m();throw g}}}}Cn();function Lx(r){let{self:e,ai:t,debug:n,effectiveAbortSignal:o,llmQueryBudgetState:i,maxBatchedLlmQueryConcurrency:s,recursionForwardOptions:a,parentForwardOptions:c,simpleChildSignature:l,llmCallWarnThreshold:u,getMaxRuntimeChars:d}=r,p=e,m=()=>new Ee(l,a),g=async(h,x)=>{if(!Array.isArray(h)&&typeof h=="object"&&h!==null&&"query"in h)return g(h.query,h.context??x);if(o?.aborted)throw new _e("rlm-llm-query",o.reason?String(o.reason):"Aborted");if(!t)throw new Error(Qf);let f=h,y=w=>{if(w==null)return"";let v=d();if(typeof w=="string")return xt(w,v);try{return xt(JSON.stringify(w),v)}catch{return xt(String(w),v)}},A=async(w,v,F=o)=>{if(F?.aborted)throw new _e("rlm-llm-query",F.reason?String(F.reason):"Aborted");let k=v==null||typeof v=="string"&&!v.trim()||typeof v=="object"&&Object.keys(v).length===0?void 0:typeof v=="string"?xt(v,d()):v;if(i.global.used>=i.globalMax)return`[ERROR] Global sub-query budget exhausted (${i.globalMax}/${i.globalMax}). Complete the task using data already gathered or handle remaining work directly in JS.`;if(i.localUsed>=i.localMax)return`[ERROR] Per-agent sub-query budget exhausted (${i.localMax}/${i.localMax}). Complete the task using data already gathered or handle remaining work directly in JS.`;i.global.used++,i.localUsed++;let O=3,$,N=V=>`[ERROR] ${V instanceof Error?V.message:String(V)}. Retry with a simpler query, handle in JS, or proceed with data already gathered.`;for(let V=0;V<O;V++)try{let I=m(),{ai:_,...S}=a,H=_??t,L=No({...c,...S,abortSignal:F,debug:n}),W=await I.forward(H,{task:w,...k!==void 0?{context:k}:{}},L);return y(W.answer)}catch(I){if(I instanceof _e||I instanceof et||p.shouldBubbleUserError(I))throw I;if($=I,!nh(I)||V>=O-1)return N(I);let _=Math.min(6e4,1e3*Math.pow(2,V));await new Promise((S,H)=>{let L=!1,W,U=()=>{F&&W&&F.removeEventListener("abort",W)},C=setTimeout(()=>{L||(L=!0,U(),S())},_);if(F){if(W=()=>{L||(L=!0,clearTimeout(C),U(),H(new _e("rlm-llm-query-retry-backoff",F.reason?String(F.reason):"Aborted during retry backoff")))},F.aborted){W();return}F.addEventListener("abort",W,{once:!0})}})}return N($)};if(Array.isArray(h)){let w=new AbortController,v=Ye(o,w.signal)??w.signal,F;try{return await uh(h,s,async k=>{try{return await A(k.query,k.context,v)}catch(O){if(O instanceof _e||O instanceof et)throw(O instanceof et||!F)&&(F=O),w.signal.aborted||w.abort(O instanceof et?"Child clarification":O.message),F;if(p.shouldBubbleUserError(O))throw w.signal.aborted||w.abort("User bubble error"),O;return`[ERROR] ${O instanceof Error?O.message:String(O)}`}},v)}finally{}}let b=await A(f,x);if(i.localUsed===u){let w=i.localMax-i.localUsed;return`${b}
|
|
813
|
+
[WARNING] ${i.localUsed}/${i.localMax} sub-queries used (${w} remaining). Consolidate remaining work.`}return b};return{llmQuery:g}}function $x(r){let{s:e,inputState:t,stageVariant:n,onUsedMemories:o,onUsedSkills:i}=r,s=new Set,a=Ru(),c=f=>{for(let y of f){let A=y.trim();A&&s.add(A)}},l=(f,y)=>{for(let A of f){let b=A.trim(),w=y[A]??y[b];w&&(e.currentDiscoveryPromptState.modules.set(b,w),a.modules.add(b),a.texts.add(w))}},u=(f,y)=>{for(let A of f){let b=qr(A),w=y[A]??y[b];w&&(e.currentDiscoveryPromptState.functions.set(b,w),a.functions.add(b),a.texts.add(w))}},d=f=>{Tn(e.currentSkillsPromptState,f),typeof e.onLoadedSkills=="function"&&Promise.resolve(e.onLoadedSkills(f)).catch(()=>{})},p=typeof e.onMemoriesSearch=="function",m=p?Ea(Array.isArray(t.currentInputs?.memories)?t.currentInputs.memories:[],[]):[];return p&&(t.currentInputs.memories=m),{noteDiscoveredActorModelNamespaces:c,noteDiscoveredModules:l,noteDiscoveredFunctions:u,noteLoadedSkills:d,noteLoadedMemories:f=>{p&&(m=Ea(m,f),t.currentInputs.memories=m,typeof e.onLoadedMemories=="function"&&Promise.resolve(e.onLoadedMemories(f)).catch(()=>{}))},noteUsed:(f,y)=>{if(e.usageTrackingEnabled===!0){if(p&&e.memoryUsageTrackingEnabled===!0){let A=jh(f,y,m,n);A&&o?.([A])}if(e.skillUsageTrackingEnabled===!0){let A=Wh(f,y,e.currentSkillsPromptState,n);A&&i?.([A])}}},consumeDiscoveryTurnArtifacts:()=>{let f=Sh(a),y=[...a.texts];return a=Ru(),{...f?{summary:f}:{},texts:y}},getCurrentMemories:()=>m,getDiscoveredActorModelNamespaces:()=>[...s]}}function Hv(r){return typeof r.inspectGlobals=="function"?r:void 0}function zn(r){if(typeof r.patchGlobals!="function")throw new Error("AxCodeSession.patchGlobals() is required when restoring AxAgent state or using inputUpdateCallback");return r}function Ux(r){if(typeof r.snapshotGlobals!="function")throw new Error("AxCodeSession.snapshotGlobals() is required to export AxAgent state");return r}function Dx(r){let{sessionRef:e,effectiveAbortSignal:t,inspectReservedNames:n,bootstrapGlobalNames:o,runtimeActionLogEntries:i,allowJavaScriptFallback:s=!0}=r,a,c=async()=>{if(!s)return[];try{let m=await e.current.execute(qf(),{signal:t,reservedNames:n});if(typeof m!="string")return[];let g=JSON.parse(m);return Array.isArray(g)?g.filter(h=>typeof h=="string"&&!o.has(h)):[]}catch{return[]}},l=async()=>(a||(a=await c()),a);return{loadInspectBaselineNames:c,ensureInspectBaselineNames:l,inspectRuntimeState:async()=>{try{let m=Hv(e.current);if(m?.inspectGlobals)return await m.inspectGlobals({signal:t,reservedNames:n});if(!s)return"[runtime state inspection unavailable: runtime session does not implement inspectGlobals()]";let g=await l(),h=zf(n,g),x=await e.current.execute(h,{signal:t,reservedNames:n});return typeof x=="string"?x:String(x)}catch(m){return`[inspectRuntime error: ${m instanceof Error?m.message:String(m)}]`}},renderRuntimeState:(m,g)=>{let h=rh(m);if(!h)return ih(m,g);let x=zr(i);return Jo(h,x,g)},resetInspectBaseline:()=>{a=void 0}}}function Ua(r,e){let t=new Set(e),n={};for(let[i,s]of Object.entries(r.runtimeBindings??{}))t.has(i)||(n[i]=s);let o=(r.runtimeEntries??[]).filter(i=>!t.has(i.name));return{runtimeBindings:n,runtimeEntries:o,actionLogEntries:Mg(r.actionLogEntries),guidanceLogEntries:(r.guidanceLogEntries??[]).map(i=>({turn:i.turn,guidance:i.guidance,...i.triggeredBy?{triggeredBy:i.triggeredBy}:{}})),checkpointState:r.checkpointState,discoveryPromptState:r.discoveryPromptState,skillsPromptState:r.skillsPromptState,provenance:{...r.provenance??{}},actorModelState:Rf(r.actorModelState)}}function jx(r){let{s:e,runtime:t,stagePolicy:n,sharedSession:o,sharedActive:i,effectiveAbortSignal:s,effectiveContextConfig:a,baseMaxRuntimeChars:c,getMaxRuntimeChars:l,llmQueryBudgetState:u,completionState:d,guidanceState:p,completionBindings:m,guardedFinalFunction:g,respondBinding:h,llmQuery:x,toolGlobals:f,runtimeInputs:y,runtimeTopLevelInputAliases:A,refreshRuntimeBindings:b,inspectReservedNames:w,bootstrapGlobals:v,bootstrapGlobalNames:F,runtimeActionLogEntries:k}=r,O,$={get current(){return O},set current(z){O=z}},{inspectRuntimeState:N,renderRuntimeState:V,resetInspectBaseline:I}=Dx({sessionRef:$,effectiveAbortSignal:s,inspectReservedNames:w,bootstrapGlobalNames:F,runtimeActionLogEntries:k,allowJavaScriptFallback:e.isJavaScriptRuntime!==!1}),_=a.stateInspection.enabled?async()=>V(await N()):void 0,S=()=>({llmQuery:x,final:g,askClarification:m.askClarificationFunction,...h?{respond:h}:{},..._?{inspectRuntime:_}:{},...e.agentStatusCallback?{reportSuccess:async z=>{await e.agentStatusCallback(z,"success")},reportFailure:async z=>{await e.agentStatusCallback(z,"failed")}}:{},...f}),H=()=>{I();let z=t.createSession({...A,inputs:y,...v,...S()},{shouldBubbleError:B=>B instanceof et||B instanceof _e||e.shouldBubbleUserError(B)});return i&&o&&o.replaceSession(z),z};i&&o&&!n.createsSharedSession&&o.session?O=o.session:O=H();let L=i&&o?async()=>{if(n.createsSharedSession){await o.adoptDistillerSession(O,{reservedNames:w,signal:s});return}await o.beginExecutorPhase({phaseGlobals:S(),inputs:{...y},aliasNames:Object.keys(A),signal:s})}:void 0,W=()=>({maxEntries:a.stateSummary.maxEntries&&a.stateSummary.maxEntries>0?a.stateSummary.maxEntries:8,maxChars:a.stateSummary.maxChars&&a.stateSummary.maxChars>0?a.stateSummary.maxChars:void 0}),U=()=>({maxEntries:a.stateSummary.maxEntries&&a.stateSummary.maxEntries>0?a.stateSummary.maxEntries:6,maxChars:a.stateSummary.maxChars&&a.stateSummary.maxChars>0?a.stateSummary.maxChars:Math.min(c,1200)}),Y=Object.keys(v).length>0?eh(v,{...U(),budgetRemaining:Math.max(0,u.localMax-u.localUsed),budgetTotal:u.localMax}):void 0;return{sessionRef:$,createSession:H,prepareSharedSession:L,bootstrapContextSummary:Y,applyBootstrapRuntimeContext:async()=>{if(Object.keys(v).length===0||!a.stateSummary.enabled)return;let z=await N();return V(z,W())||"(no user variables)"},captureRuntimeStateSummary:async()=>{if(!a.stateSummary.enabled)return;let z=await N();return V(z,W())||"(no user variables)"},waitForCompletionSignal:async()=>{if(!d.payload)for(let z=0;z<3&&!d.payload;z++)await new Promise(B=>{setTimeout(B,0)})},restoreRuntimeState:async(z,B)=>{let K=Ua(z,w);return B?.skipBindings!==!0&&await zn(O).patchGlobals(K.runtimeBindings,{signal:s}),e.currentDiscoveryPromptState=pr(K.discoveryPromptState),e.currentSkillsPromptState=ni(K.skillsPromptState),K},exportRuntimeState:async z=>{let K=z?.includeBindings!==!1?await Ux(O).snapshotGlobals({signal:s,reservedNames:w}):{version:1,entries:[],bindings:{}},ie=zr(k);return{version:1,runtimeBindings:K.bindings,runtimeEntries:K.entries,actionLogEntries:Pg(k),...p.entries.length>0?{guidanceLogEntries:p.entries.map(oe=>({turn:oe.turn,guidance:oe.guidance,...oe.triggeredBy?{triggeredBy:oe.triggeredBy}:{}}))}:{},...ei(e.currentDiscoveryPromptState)?{discoveryPromptState:ei(e.currentDiscoveryPromptState)}:{},...Su(e.currentSkillsPromptState)?{skillsPromptState:Su(e.currentSkillsPromptState)}:{},provenance:Eg(ie)}},syncRuntimeInputsToSession:async()=>{if(b(),i&&o?.session){try{await o.mergeInputs({...y},{signal:s}),Object.keys(A).length>0&&await zn(o.session).patchGlobals({...A},{signal:s})}catch(B){throw s?.aborted?new _e("rlm-session",s.reason??"Aborted"):B instanceof Error&&(B.name==="AbortError"||B.message.startsWith("Aborted"))?B:new Error(`Failed to sync runtime inputs: ${Bn(B,l())}`)}return}let z=async B=>{await zn(B).patchGlobals({inputs:{...y},...A},{signal:s})};try{await z(O)}catch(B){if(s?.aborted)throw new _e("rlm-session",s.reason??"Aborted");if(B instanceof Error&&(B.name==="AbortError"||B.message.startsWith("Aborted")))throw B;if(ka(B)){O=H(),await z(O);return}throw new Error(`Failed to sync runtime inputs: ${Bn(B,l())}`)}},close:()=>{o&&o.session===O||O.close()}}}var ln="distilledContext",Vu="__axSharedPhase",Kv="__axInputsPatch",Wr=Kv,Hu="/* ax:host-snippet */";function Da(r){return!!r&&typeof r=="object"&&r.kind==="axEvidenceDescriptor"&&Array.isArray(r.entries)}function Wv(r){return r===null?"null":Array.isArray(r)?"array":typeof r}function Bx(r){try{let e=JSON.stringify(r);return typeof e=="string"?e.length:0}catch{return-1}}function Ku(r){return Bx(r)}var Gx=12;function Jv(r){if(Array.isArray(r)){let e=r[0];if(e&&typeof e=="object"&&!Array.isArray(e)){let t=Object.keys(e).slice(0,Gx);return t.length?{itemKeys:t}:{}}return{}}if(r&&typeof r=="object"){let e=Object.keys(r).slice(0,Gx);return e.length?{keys:e}:{}}return{}}function zx(r){let e=Object.keys(r).map(n=>{let o=r[n],i=Bx(o);return{key:n,type:Wv(o),size:i,...Array.isArray(o)?{length:o.length}:{},...Jv(o)}}),t=0;for(let n of e)n.size>0&&(t+=n.size);return{kind:"axEvidenceDescriptor",totalChars:t,entries:e}}function Wu(r){if(r.entries.length===0)return`Evidence object is available in the runtime as \`inputs.${ln}\` (empty).`;let e=r.entries.map(t=>{let n=t.size>=0?`~${t.size} chars`:"unserializable",o=typeof t.length=="number"?`, ${t.length} items`:"",i=t.itemKeys?.length?`; item keys: ${t.itemKeys.join(", ")}`:t.keys?.length?`; keys: ${t.keys.join(", ")}`:"";return`- \`${t.key}\` (${t.type}${o}, ${n}${i})`});return[`Evidence keys available in the runtime as \`inputs.${ln}\` (~${r.totalChars} chars total):`,...e].join(`
|
|
814
814
|
`)}function Yv(){return`${Hu}
|
|
815
815
|
(() => {
|
|
816
816
|
const __axHostFinal = globalThis.final;
|
|
@@ -1000,7 +1000,7 @@ ${f}`),...h].join(`
|
|
|
1000
1000
|
`)},m=r.REFLECTION_PROMPT_TEMPLATE.replace("<curr_instructions>",e).replace("<inputs_outputs_feedback>",p());try{let h=await c.chat({chatPrompt:[{role:"user",content:m}],model:i?.reflectionModel},{stream:!1});if(typeof h.getReader=="function")throw new Error("Streaming response not expected for reflection");let f=h.results?.[0]?.content;if(typeof f=="string"){let y=this.extractInstructionFromBackticks(f);if(y&&y.length>16){let A=`Iteration feedback: ${a.map(b=>`score=${b.score.toFixed(2)}`).join(", ")}`;return this.feedbackMemory.unshift(A),this.feedbackMemory.length>this.feedbackMemorySize&&this.feedbackMemory.pop(),y}}}catch{}let g=Ut('currentInstruction:string "Current instruction", feedbackSummary?:string "Summarized feedback", recentFeedback?:string[] "Past feedback memory", minibatch:json "Array of {input,prediction,score}" -> newInstruction:string "Improved instruction within 1-6 sentences."');try{let x=(await g.forward(c,{currentInstruction:e,feedbackSummary:this.feedbackMemory[0]||"",recentFeedback:this.feedbackMemory,minibatch:a}))?.newInstruction?.trim();if(x&&x.length>16)return x}catch{}return`${e.trim()} Focus on step-by-step evidence-based reasoning. Avoid hallucinations.`.slice(0,2e3)}extractInstructionFromBackticks(e){let t=e.indexOf("```")+3,n=e.lastIndexOf("```");if(t>=n){let s=e.trim();if(s.startsWith("```")){let a=s.match(/^```\S*\n?/);if(a)return s.slice(a[0].length).trim()}else if(s.endsWith("```"))return s.slice(0,-3).trim();return s}let o=e.slice(t,n),i=o.match(/^\S*\n/);return i&&(o=o.slice(i[0].length)),o.trim()}updateSamplerShuffled(e){let t=Array.from({length:e},(c,l)=>l);for(let c=t.length-1;c>0;c--){let l=Math.floor(this.rand()*(c+1));[t[c],t[l]]=[t[l],t[c]]}for(let c of t)this.samplerState.freq.set(c,(this.samplerState.freq.get(c)??0)+1);let n=this.minibatchSize,o=e%n,i=o===0?0:n-o,s=Array.from({length:e},(c,l)=>l).sort((c,l)=>(this.samplerState.freq.get(c)??0)-(this.samplerState.freq.get(l)??0)),a=[...t];for(let c=0;c<i;c++){let l=s[c%s.length];a.push(l),this.samplerState.freq.set(l,(this.samplerState.freq.get(l)??0)+1)}this.samplerState.shuffled=a,this.samplerState.epoch+=1}nextMinibatchIndices(e,t){this.samplerState.epoch===-1&&(this.samplerState.epoch=0,this.updateSamplerShuffled(e));let n=this.minibatchSize,o=Math.max(1,Math.floor(this.samplerState.shuffled.length/n)),i=Math.floor(t/o);for(;i>=this.samplerState.epoch;)this.updateSamplerShuffled(e);let s=t*n%this.samplerState.shuffled.length;return this.samplerState.shuffled.slice(s,s+n)}rand(){return this.rngState^=this.rngState<<13,this.rngState^=this.rngState>>>17,this.rngState^=this.rngState<<5,(this.rngState>>>0)/4294967296}systemAwareMergeWithSig(e,t,n,o){let i=x=>{let f=[],y=x;for(;y!==void 0;)f.push(y),y=e[y]?.parent;return f},s=i(t),a=i(n),l=s.find(x=>a.includes(x))??t,u=e[l].cfg,d=e[t].cfg,p=e[n].cfg,m={},g=[],h=Array.from(new Set([...Object.keys(u),...Object.keys(d),...Object.keys(p)])).sort();for(let x of h){let f=u[x],y=d[x],A=p[x];if(y===f&&A!==y)m[x]=A,g.push("j");else if(A===f&&y!==A)m[x]=y,g.push("i");else if(y!==A&&y!==f&&A!==f){let b=o(t,n);m[x]=b===t?y:A,g.push(b===t?"i":"j")}else m[x]=y??A??f,g.push("i")}return{cfg:m,descSig:g.join("|")}}generateOptimizationReport(e,t,n,o){let i=e.length>0?e.reduce((u,d)=>{let p=Object.values(u.scores).reduce((g,h)=>g+h,0);return Object.values(d.scores).reduce((g,h)=>g+h,0)>p?d:u}):void 0,s={};if(i)for(let[u,d]of Object.entries(i.scores))s[u]={value:d,percentage:d*100};let a=[];if(e.length>1){let u=[...e].sort((d,p)=>p.dominated-d.dominated).slice(0,3);for(let d of u)a.push({...d.scores})}let c="good",l=[];if(e.length===1)c="single",l.push("Increase numTrials (current seems low)"),l.push("Add more training examples"),l.push("Adjust earlyStoppingTrials");else if(e.length<3)c="limited",l.push("More optimization trials"),l.push("Larger validation set");else{c="good";let u=Object.keys(e[0]?.scores||{});for(let d of u)l.push(`High ${d}: Choose solution with best ${d} score`);l.push("Balanced: Use provided bestScore (average)")}return this.stats.totalCalls<50&&(l.push("Quick run detected - use numTrials: 30+ for production"),l.push("Provide 50+ training examples"),l.push("Use 20+ validation examples")),{summary:"GEPA Multi-Objective Optimization Complete",bestSolution:{overallScore:n??0,objectives:s},paretoFrontier:{solutionCount:e.length,objectiveSpaceCoverage:(t??0)*100,hypervolume:t??0,tradeoffs:a.length>0?a:void 0},statistics:{totalEvaluations:this.stats.totalCalls,candidatesExplored:o,converged:this.stats.convergenceInfo?.converged??!1},recommendations:{status:c,suggestions:l}}}async mergeInstructions(e,t,n){let o=n?.overrideTeacherAI??this.teacherAI??this.studentAI,i=Ut(`instructionA:string "Parent A instruction",
|
|
1001
1001
|
instructionB:string "Parent B instruction",
|
|
1002
1002
|
recentFeedback?:string[] "Past feedback memory"
|
|
1003
|
-
-> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await i.forward(o,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};Cn();import{context as ik,SpanKind as sk,trace as ak}from"@opentelemetry/api";Cn();async function Zr(r,e,t){if(!t||t<=0||t>=r.length){let o=r.map((i,s)=>e(i,s));return Promise.all(o)}let n=new Array(r.length);for(let o=0;o<r.length;o+=t){let s=r.slice(o,o+t).map((c,l)=>{let u=o+l;return e(c,u).then(d=>({result:d,originalIndex:u}))}),a=await Promise.all(s);for(let{result:c,originalIndex:l}of a)n[l]=c}return n}var cd=Symbol("axFlowExplicitDependencies");function xy(r){if(!r||typeof r!="function")return{dependencies:[],isSafe:!0};let e=r[cd];if(Array.isArray(e))return{dependencies:[...e],isSafe:!0};let t=r.toString(),n=qS(t);if(n.length>0)return{dependencies:n,isSafe:!0};let o=zS(t),i=new Set;if(!o)return{dependencies:[],isSafe:!VS(t)};let s=yy(o);for(let a of t.matchAll(new RegExp(`\\b${s}\\.(\\w+)`,"g")))a[1]&&i.add(a[1]);for(let a of t.matchAll(new RegExp(`\\$\\{\\s*${s}\\.(\\w+)`,"g")))a[1]&&i.add(a[1]);for(let a of t.matchAll(new RegExp(`\\{\\s*([\\w\\s,:]+)\\s*\\}\\s*=\\s*${s}\\b`,"g"))){let c=a[1]?.split(",")??[];for(let l of c){let u=l.trim().split(":")[0]?.trim();u&&i.add(u)}}return{dependencies:[...i],isSafe:i.size>0||!HS(t,o)}}function zS(r){let e=r.match(/function[^(]*\(\s*([A-Za-z_$][\w$]*)/);if(e?.[1])return e[1];let t=r.match(/^(?:async\s*)?(?:\(\s*)?([A-Za-z_$][\w$]*)\s*(?:[):=,]|\)\s*=>|=>)/);if(t?.[1])return t[1]}function qS(r){let e=r.match(/function[^(]*\(\s*\{([^}]+)\}/)??r.match(/^(?:async\s*)?\(\s*\{([^}]+)\}/);return e?.[1]?e[1].split(",").map(t=>t.trim().split(":")[0]?.split("=")[0]?.trim()).filter(t=>!!t):[]}function VS(r){return/function[^(]*\(\s*\{/.test(r)||/^(?:async\s*)?\(\s*\{/.test(r)}function HS(r,e){let t=KS(r);return new RegExp(`\\b${yy(e)}\\b`).test(t)}function KS(r){let e=r.indexOf("=>");if(e>=0)return r.slice(e+2);let t=r.indexOf("{");return t>=0?r.slice(t+1):""}function yy(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(r){return{reads:[],writes:[],isBarrier:!1,...r}}function Ay(r,e){return{type:r.kind,nodeName:r.nodeName,dependencies:[...r.reads],produces:[...r.writes],stepIndex:e,isBarrier:r.isBarrier}}function ld(r,e){return r.some(t=>e.includes(t))}function WS(r,e){if(e.isBarrier||e.produces.length===0)return!1;for(let t of r)if(t.isBarrier||ld(e.dependencies,t.produces)||ld(t.dependencies,e.produces)||ld(t.produces,e.produces))return!1;return!0}var Ar=class{planSteps;constructor(e=[]){this.planSteps=e.map((t,n)=>Ay(t,n))}getExecutionPlan(){let e=[],t=[],n=()=>{t.length!==0&&(e.push({level:e.length,steps:t}),t=[])};for(let o of this.planSteps){if(o.isBarrier){n(),e.push({level:e.length,steps:[o]});continue}if(t.length===0||WS(t,o)){t.push(o);continue}n(),t.push(o)}return n(),{totalSteps:this.planSteps.length,parallelGroups:e.length,maxParallelism:e.length===0?1:Math.max(...e.map(o=>o.steps.length),1),steps:this.planSteps,groups:e}}};Cn();function JS(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return[...e.actor??[],...e.responder??[]]}return[]}async function Ry({nodeName:r,nodeProgram:e,ai:t,inputs:n,options:o,recorder:i}){if(!("forward"in e)||typeof e.forward!="function")throw new Error(`Node program for '${r}' does not have a forward method`);let s=o?.traceLabel?`Node:${r} (${o.traceLabel})`:`Node:${r}`,a=await e.forward(t,n,{...o,traceLabel:s});if(i&&"getUsage"in e){let c=e.getUsage;if(typeof c=="function"){let l=JS(c.call(e));l.length>0&&i.recordUsage(r,l)}}if(i&&"getTraces"in e){let c=e.getTraces;if(typeof c=="function"){let l=c.call(e);Array.isArray(l)&&l.length>0&&i.recordTraces(r,l)}}if(i&&"getChatLog"in e){let c=e.getChatLog;if(typeof c=="function"){let l=c.call(e);Array.isArray(l)&&l.length>0&&i.recordChatLog(r,l.map(u=>({...u,name:u.name?`${r}.${u.name}`:r})))}}return a}function Cy(r,e,t,n){r?.({name:"StepStart",timestamp:Date.now(),stepIndex:t,stepType:e.kind,nodeName:e.nodeName,dependencies:[...e.reads],produces:[...e.writes],state:{...n}})}function by(r,e,t,n,o,i){let a=Object.keys(n).filter(l=>!o.includes(l)),c=e.nodeName?`${e.nodeName}Result`:void 0;r?.({name:"StepComplete",timestamp:Date.now(),stepIndex:t,stepType:e.kind,nodeName:e.nodeName,executionTime:i,state:{...n},newFields:a,result:c?n[c]:void 0})}async function ud(r,e,t,n){let o={...e},i=0,s=new Ar(r),a=n.autoParallel?s.getExecutionPlan().groups:r.map((c,l)=>({level:l,steps:[{type:c.kind,nodeName:c.nodeName,dependencies:[...c.reads],produces:[...c.writes],stepIndex:l,isBarrier:!0}]}));for(let c of a){if(c.steps.length===0)continue;if(c.steps.length===1){let g=c.steps[0],h=r[g.stepIndex];if(!h)continue;t.checkAbort(`flow-step-${g.stepIndex}`);let x=Object.keys(o);Cy(n.logger,h,g.stepIndex,o);let f=Date.now();try{o=await h.run(o,t),i++,by(n.logger,h,g.stepIndex,o,x,Date.now()-f)}catch(y){throw n.logger?.({name:"FlowError",timestamp:Date.now(),error:y instanceof Error?y.message:String(y),stepIndex:g.stepIndex,stepType:h.kind,nodeName:h.nodeName,state:{...o}}),y}continue}t.checkAbort(`flow-parallel-group-${c.level}`);let l=o,u=new AbortController,d=t.captureRemoteTasks?.(),p={...t,mainOptions:{...t.mainOptions,abortSignal:Ye(t.mainOptions?.abortSignal,u.signal)},checkAbort:g=>{t.checkAbort(g),dd(u.signal,g)}},m;try{m=await Zr(c.steps,async g=>{let h=r[g.stepIndex];if(!h)return l;let x=Object.keys(l);Cy(n.logger,h,g.stepIndex,l);let f=Date.now();try{let y=await h.run(l,p);return by(n.logger,h,g.stepIndex,y,x,Date.now()-f),y}catch(y){throw n.logger?.({name:"FlowError",timestamp:Date.now(),error:y instanceof Error?y.message:String(y),stepIndex:g.stepIndex,stepType:h.kind,nodeName:h.nodeName,state:{...l}}),u.abort(y),y}},n.batchSize)}catch(g){throw u.abort(g),d!==void 0&&await t.cancelRemoteTasksSince?.(d),g}for(let g of m)o={...o,...g},i++}return{finalState:o,stepsExecuted:i}}function dd(r,e){if(r?.aborted)throw new
|
|
1003
|
+
-> mergedInstruction:string "Merged instruction (1-6 sentences) combining strengths, fixing weaknesses"`);try{let a=(await i.forward(o,{instructionA:e,instructionB:t,recentFeedback:this.feedbackMemory}))?.mergedInstruction?.trim();if(a&&a.length>16)return a}catch{}return(e.length>=t.length?e:t).slice(0,2e3)}};Cn();import{context as ik,SpanKind as sk,trace as ak}from"@opentelemetry/api";Cn();async function Zr(r,e,t){if(!t||t<=0||t>=r.length){let o=r.map((i,s)=>e(i,s));return Promise.all(o)}let n=new Array(r.length);for(let o=0;o<r.length;o+=t){let s=r.slice(o,o+t).map((c,l)=>{let u=o+l;return e(c,u).then(d=>({result:d,originalIndex:u}))}),a=await Promise.all(s);for(let{result:c,originalIndex:l}of a)n[l]=c}return n}var cd=Symbol("axFlowExplicitDependencies");function xy(r){if(!r||typeof r!="function")return{dependencies:[],isSafe:!0};let e=r[cd];if(Array.isArray(e))return{dependencies:[...e],isSafe:!0};let t=r.toString(),n=qS(t);if(n.length>0)return{dependencies:n,isSafe:!0};let o=zS(t),i=new Set;if(!o)return{dependencies:[],isSafe:!VS(t)};let s=yy(o);for(let a of t.matchAll(new RegExp(`\\b${s}\\.(\\w+)`,"g")))a[1]&&i.add(a[1]);for(let a of t.matchAll(new RegExp(`\\$\\{\\s*${s}\\.(\\w+)`,"g")))a[1]&&i.add(a[1]);for(let a of t.matchAll(new RegExp(`\\{\\s*([\\w\\s,:]+)\\s*\\}\\s*=\\s*${s}\\b`,"g"))){let c=a[1]?.split(",")??[];for(let l of c){let u=l.trim().split(":")[0]?.trim();u&&i.add(u)}}return{dependencies:[...i],isSafe:i.size>0||!HS(t,o)}}function zS(r){let e=r.match(/function[^(]*\(\s*([A-Za-z_$][\w$]*)/);if(e?.[1])return e[1];let t=r.match(/^(?:async\s*)?(?:\(\s*)?([A-Za-z_$][\w$]*)\s*(?:[):=,]|\)\s*=>|=>)/);if(t?.[1])return t[1]}function qS(r){let e=r.match(/function[^(]*\(\s*\{([^}]+)\}/)??r.match(/^(?:async\s*)?\(\s*\{([^}]+)\}/);return e?.[1]?e[1].split(",").map(t=>t.trim().split(":")[0]?.split("=")[0]?.trim()).filter(t=>!!t):[]}function VS(r){return/function[^(]*\(\s*\{/.test(r)||/^(?:async\s*)?\(\s*\{/.test(r)}function HS(r,e){let t=KS(r);return new RegExp(`\\b${yy(e)}\\b`).test(t)}function KS(r){let e=r.indexOf("=>");if(e>=0)return r.slice(e+2);let t=r.indexOf("{");return t>=0?r.slice(t+1):""}function yy(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jt(r){return{reads:[],writes:[],isBarrier:!1,...r}}function Ay(r,e){return{type:r.kind,nodeName:r.nodeName,dependencies:[...r.reads],produces:[...r.writes],stepIndex:e,isBarrier:r.isBarrier}}function ld(r,e){return r.some(t=>e.includes(t))}function WS(r,e){if(e.isBarrier||e.produces.length===0)return!1;for(let t of r)if(t.isBarrier||ld(e.dependencies,t.produces)||ld(t.dependencies,e.produces)||ld(t.produces,e.produces))return!1;return!0}var Ar=class{planSteps;constructor(e=[]){this.planSteps=e.map((t,n)=>Ay(t,n))}getExecutionPlan(){let e=[],t=[],n=()=>{t.length!==0&&(e.push({level:e.length,steps:t}),t=[])};for(let o of this.planSteps){if(o.isBarrier){n(),e.push({level:e.length,steps:[o]});continue}if(t.length===0||WS(t,o)){t.push(o);continue}n(),t.push(o)}return n(),{totalSteps:this.planSteps.length,parallelGroups:e.length,maxParallelism:e.length===0?1:Math.max(...e.map(o=>o.steps.length),1),steps:this.planSteps,groups:e}}};Cn();function JS(r){if(Array.isArray(r))return r;if(r&&typeof r=="object"){let e=r;return[...e.actor??[],...e.responder??[]]}return[]}async function Ry({nodeName:r,nodeProgram:e,ai:t,inputs:n,options:o,recorder:i}){if(!("forward"in e)||typeof e.forward!="function")throw new Error(`Node program for '${r}' does not have a forward method`);let s=o?.traceLabel?`Node:${r} (${o.traceLabel})`:`Node:${r}`,a=await e.forward(t,n,{...o,traceLabel:s});if(i&&"getUsage"in e){let c=e.getUsage;if(typeof c=="function"){let l=JS(c.call(e));l.length>0&&i.recordUsage(r,l)}}if(i&&"getTraces"in e){let c=e.getTraces;if(typeof c=="function"){let l=c.call(e);Array.isArray(l)&&l.length>0&&i.recordTraces(r,l)}}if(i&&"getChatLog"in e){let c=e.getChatLog;if(typeof c=="function"){let l=c.call(e);Array.isArray(l)&&l.length>0&&i.recordChatLog(r,l.map(u=>({...u,name:u.name?`${r}.${u.name}`:r})))}}return a}function Cy(r,e,t,n){r?.({name:"StepStart",timestamp:Date.now(),stepIndex:t,stepType:e.kind,nodeName:e.nodeName,dependencies:[...e.reads],produces:[...e.writes],state:{...n}})}function by(r,e,t,n,o,i){let a=Object.keys(n).filter(l=>!o.includes(l)),c=e.nodeName?`${e.nodeName}Result`:void 0;r?.({name:"StepComplete",timestamp:Date.now(),stepIndex:t,stepType:e.kind,nodeName:e.nodeName,executionTime:i,state:{...n},newFields:a,result:c?n[c]:void 0})}async function ud(r,e,t,n){let o={...e},i=0,s=new Ar(r),a=n.autoParallel?s.getExecutionPlan().groups:r.map((c,l)=>({level:l,steps:[{type:c.kind,nodeName:c.nodeName,dependencies:[...c.reads],produces:[...c.writes],stepIndex:l,isBarrier:!0}]}));for(let c of a){if(c.steps.length===0)continue;if(c.steps.length===1){let g=c.steps[0],h=r[g.stepIndex];if(!h)continue;t.checkAbort(`flow-step-${g.stepIndex}`);let x=Object.keys(o);Cy(n.logger,h,g.stepIndex,o);let f=Date.now();try{o=await h.run(o,t),i++,by(n.logger,h,g.stepIndex,o,x,Date.now()-f)}catch(y){throw n.logger?.({name:"FlowError",timestamp:Date.now(),error:y instanceof Error?y.message:String(y),stepIndex:g.stepIndex,stepType:h.kind,nodeName:h.nodeName,state:{...o}}),y}continue}t.checkAbort(`flow-parallel-group-${c.level}`);let l=o,u=new AbortController,d=t.captureRemoteTasks?.(),p={...t,mainOptions:{...t.mainOptions,abortSignal:Ye(t.mainOptions?.abortSignal,u.signal)},checkAbort:g=>{t.checkAbort(g),dd(u.signal,g)}},m;try{m=await Zr(c.steps,async g=>{let h=r[g.stepIndex];if(!h)return l;let x=Object.keys(l);Cy(n.logger,h,g.stepIndex,l);let f=Date.now();try{let y=await h.run(l,p);return by(n.logger,h,g.stepIndex,y,x,Date.now()-f),y}catch(y){throw n.logger?.({name:"FlowError",timestamp:Date.now(),error:y instanceof Error?y.message:String(y),stepIndex:g.stepIndex,stepType:h.kind,nodeName:h.nodeName,state:{...l}}),u.abort(y),y}},n.batchSize)}catch(g){throw u.abort(g),d!==void 0&&await t.cancelRemoteTasksSince?.(d),g}for(let g of m)o={...o,...g},i++}return{finalState:o,stepsExecuted:i}}function dd(r,e){if(r?.aborted)throw new _e(e,r.reason??"Flow aborted")}var wy=r=>{console.log(r)},eo=(r,e=!1)=>{if(e)return"[State hidden]";let t={};for(let[n,o]of Object.entries(r))if(typeof o=="string"&&o.length>100)t[n]=`${o.substring(0,100)}...`;else if(Array.isArray(o)&&o.length>3)t[n]=[...o.slice(0,3),`... (${o.length-3} more)`];else if(typeof o=="object"&&o!==null){let i=JSON.stringify(o);i.length>200?t[n]=`${i.substring(0,200)}...`:t[n]=o}else t[n]=o;return JSON.stringify(t,null,2)},to=r=>r<1e3?`${r.toFixed(1)}ms`:r<6e4?`${(r/1e3).toFixed(2)}s`:`${(r/6e4).toFixed(2)}min`,Ha=(r=wy)=>{let e=new wt,t=e.gray(`${"\u2501".repeat(80)}
|
|
1004
1004
|
`),n=e.gray(`${"\u2500".repeat(40)}
|
|
1005
1005
|
`);return o=>{let i="";switch(o.name){case"FlowStart":i=`
|
|
1006
1006
|
${e.blueBright("\u{1F504} [ AXFLOW START ]")}
|
|
@@ -1250,7 +1250,7 @@ ${e}
|
|
|
1250
1250
|
`,i.description&&(o+=` ${i.description}
|
|
1251
1251
|
`)}),o+=`${e}
|
|
1252
1252
|
`;break}default:o=JSON.stringify(n,null,2)}r(o)}};var Oe={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_RESPONSE_ID:"gen_ai.response.id",LLM_RESPONSE_MODEL:"gen_ai.response.model",LLM_CONVERSATION_ID:"gen_ai.conversation.id",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",AX_SESSION_ID:"ax.session.id",AX_PROVIDER_REQUEST_ID:"ax.provider.request_id",AX_PROVIDER_SESSION_ID:"ax.provider.session_id"},dn={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"};Cn();var Rd=class{buffer;doneCallback;transformFn;constructor(e,t){this.transformFn=e,this.doneCallback=t,this.buffer=t?[]:void 0}async transform(e,t){let n=this.transformFn(e);n&&(t.enqueue(n),this.buffer?.push(n))}async flush(e){await this.doneCallback?.(this.buffer??[]),e.terminate()}},oc=class extends TransformStream{constructor(e,t){super(new Rd(e,t))}};var hi=new Map;function Dk(r){return`${r.providerName}:${r.model}:${r.contentHash}`}function iA(r,e){if(!r?.name||!r.expiresAt)return;let t=Date.parse(r.expiresAt);return Number.isFinite(t)&&t>e?t:void 0}function jk(r){if(!(r instanceof Qe)||r.status!==400&&r.status!==404)return!1;let e=(JSON.stringify(r.responseBody)??"").toLowerCase(),t=e.includes("cachedcontent")||e.includes("cached content")||e.includes("cachedcontents/"),n=e.includes("cache")&&(e.includes("expired")||e.includes("not found")||e.includes("does not exist")||e.includes("invalid"));return t||n}function vd(r){return Array.isArray(r)?r.map(e=>vd(e)):r&&typeof r=="object"?Object.fromEntries(Object.entries(r).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,vd(t)])):r}var Gk=["x-request-id","request-id","x-requestid","x-ms-request-id","x-goog-request-id","x-amzn-requestid","x-amz-request-id"],Bk=["openai-session-id","anthropic-session-id","x-session-id"];function sA(r,e){for(let t of e){let n=r.get(t);if(n)return n}}function ic(r,e){if(!r&&!e)return;let t={};for(let n of[r,e])if(n)for(let[o,i]of Object.entries(n))t[o]={...t[o]??{},...i};return t}function aA(r,e){let t=sA(r,Gk),n=sA(r,Bk),o=t||n?{[e]:{...t?{requestId:t}:{},...n?{sessionId:n}:{}}}:void 0;return{...t?{remoteRequestId:t}:{},...n?{remoteSessionId:n}:{},...o?{providerMetadata:o}:{}}}function cA(r,e){return{remoteRequestId:e.remoteRequestId??r.remoteRequestId,remoteSessionId:e.remoteSessionId??r.remoteSessionId,providerMetadata:ic(r.providerMetadata,e.providerMetadata)}}function wd(r,e,t){r.sessionId=e,t.remoteRequestId&&!r.remoteRequestId&&(r.remoteRequestId=t.remoteRequestId),t.remoteSessionId&&(r.remoteSessionId??=t.remoteSessionId),r.providerMetadata=ic(r.providerMetadata,t.providerMetadata)}function oo(r,e){if(!r?.isRecording())return;let t=e instanceof Error?e:new Error(String(e));r.recordException(t),r.setStatus({code:Uk.ERROR,message:t.message})}function uA(r,e){let t={},n=r.remoteSessionId??r.sessionId;r.remoteId&&(t[Oe.LLM_RESPONSE_ID]=r.remoteId),r.modelUsage?.model&&(t[Oe.LLM_RESPONSE_MODEL]=r.modelUsage.model),n&&(t[Oe.LLM_CONVERSATION_ID]=n),r.sessionId&&(t[Oe.AX_SESSION_ID]=r.sessionId),r.remoteRequestId&&(t[Oe.AX_PROVIDER_REQUEST_ID]=r.remoteRequestId),r.remoteSessionId&&(t[Oe.AX_PROVIDER_SESSION_ID]=r.remoteSessionId),Object.keys(t).length>0&&e.setAttributes(t)}function Sd(r){return JSON.stringify(vd(r))}function dA(r){return typeof r=="string"?r:Sd(r)}function zk(r){return r.functions?.some(e=>e.cache)??!1}function qk(r){if(zk(r))return{functions:r.functions?.map(({cache:e,...t})=>t),functionCall:r.functionCall}}function Vk(r,e){e.type==="text"?r.update(`text:${e.text}`):e.type==="image"?r.update(`image:${e.mimeType}:${e.image.slice(0,100)}`):e.type==="audio"?r.update(`audio:${e.format}:${e.data.slice(0,100)}`):e.type==="file"&&("fileUri"in e?r.update(`file:${e.mimeType}:${e.fileUri}`):r.update(`file:${e.mimeType}:${e.data.slice(0,100)}`))}function Hk(r,e){let t=Rt("sha256"),{chatPrompt:n}=r,o=-1;for(let i=n.length-1;i>=0;i--){let s=n[i];if("cache"in s&&s.cache){o=i;break}}for(let i=0;i<n.length;i++){let s=n[i];if(s.role==="system"){t.update(`system:${s.content}`);continue}if(o>=0&&i<=o)if(s.role==="user"){if(typeof s.content=="string")t.update(`user:${s.content}`);else if(Array.isArray(s.content))for(let a of s.content)Vk(t,a)}else if(s.role==="assistant"){if(s.content&&t.update(`assistant:${s.content}`),s.functionCalls)for(let a of s.functionCalls)t.update(`assistant_function:${a.function.name}:${dA(a.function.params)}`)}else s.role==="function"&&t.update(`function:${s.functionId}:${s.result}`)}return e&&t.update(`tools:${Sd(e)}`),t.digest("hex")}var Ge=()=>structuredClone({temperature:0}),Ot=()=>structuredClone({temperature:.4,frequencyPenalty:.2}),Kk=()=>{let r={};return e=>{let t={},n=!1;for(let[o,i]of Object.entries(e)){if(typeof i!="number")continue;let s=r[o]??0,a=Math.max(0,i-s);i>s&&(r[o]=i),a>0&&(t[o]=a,n=!0)}return n?t:void 0}},Et=class{constructor(e,{name:t,apiURL:n,headers:o,modelInfo:i,defaults:s,options:a={},supportFor:c,models:l}){this.aiImpl=e;this.name=t,this.apiURL=n||"",this.headers=o,this.supportFor=c,this.modelInfo=i,this.models=l,this.id=ze();let u=this.getModel(s.model)??s.model,d=this.getEmbedModel(s.embedModel)??s.embedModel;if(this.defaults={model:u,embedModel:d},!s.model||typeof s.model!="string"||s.model==="")throw new Error("No model defined");this.setOptions(a),l&&Jk(l)}#t;#e=!1;rt;fetch;tracer;meter;timeout;excludeContentFromTrace;models;abortSignal;logger;corsProxy;retry;customLabels;usageContext;contextCache;beta;includeRequestBodyInErrors;modelInfo;modelUsage;embedModelUsage;defaults;lastUsedModelConfig;lastUsedChatModel;lastUsedEmbedModel;apiURL;name;id;headers;supportFor;metrics={latency:{chat:{mean:0,p95:0,p99:0,samples:[]},embed:{mean:0,p95:0,p99:0,samples:[]}},errors:{chat:{count:0,rate:0,total:0},embed:{count:0,rate:0,total:0}}};getEffectiveDebug(e){return e?.debug??this.#t??fe.debug??!1}getEffectiveTracer(e){return e?.tracer??this.tracer??fe.tracer}getEffectiveMeter(e){return e?.meter??this.meter??fe.meter}getEffectiveLogger(e){return e?.logger??this.logger??fe.logger??nA}getEffectiveAbortSignal(e){return Ye(e?.abortSignal,Ye(this.abortSignal,fe.abortSignal))}getMetricsInstruments(e){return om(this.getEffectiveMeter(e))}setName(e){this.name=e}getId(){return this.id}setAPIURL(e){this.apiURL=e}setHeaders(e){this.headers=e}get debug(){return this.getEffectiveDebug()}setOptions(e){this.#t=e.debug,this.#e=e.verbose??!1,this.rt=e.rateLimiter,this.fetch=e.fetch,this.timeout=e.timeout,this.tracer=e.tracer,this.meter=e.meter,this.excludeContentFromTrace=e.excludeContentFromTrace,this.abortSignal=e.abortSignal,this.logger=e.logger,this.corsProxy=e.corsProxy,this.retry=e.retry,this.customLabels=e.customLabels,this.usageContext=e.usageContext?{...e.usageContext,...e.usageContext.attributes?{attributes:{...e.usageContext.attributes}}:{}}:void 0,this.contextCache=e.contextCache,this.beta=e.beta,this.includeRequestBodyInErrors=e.includeRequestBodyInErrors}getOptions(){return{debug:this.getEffectiveDebug(),verbose:this.#e,rateLimiter:this.rt,fetch:this.fetch,tracer:this.getEffectiveTracer(),meter:this.getEffectiveMeter(),timeout:this.timeout,excludeContentFromTrace:this.excludeContentFromTrace,abortSignal:this.getEffectiveAbortSignal(),logger:this.getEffectiveLogger(),corsProxy:this.corsProxy,retry:this.retry,customLabels:this.getMergedCustomLabels(),usageContext:this.usageContext?{...this.usageContext,...this.usageContext.attributes?{attributes:{...this.usageContext.attributes}}:{}}:void 0,contextCache:this.contextCache,beta:this.beta,includeRequestBodyInErrors:this.includeRequestBodyInErrors}}getLogger(){return this.getEffectiveLogger()}getMergedCustomLabels(e){return tr(fe.customLabels,this.customLabels,e)}getMergedUsageContext(e){return Fo(this.usageContext,e?.usageContext)}getModelList(){let e=[];for(let t of this.models??[])t.isInternal||("model"in t&&t.model&&e.push({key:t.key,description:t.description,model:t.model}),"embedModel"in t&&t.embedModel&&e.push({key:t.key,description:t.description,embedModel:t.embedModel}));return e}getName(){return this.name}getFeatures(e){return typeof this.supportFor=="function"?this.supportFor(e??this.defaults.model):this.supportFor}getLastUsedChatModel(){return this.lastUsedChatModel}getLastUsedEmbedModel(){return this.lastUsedEmbedModel}getLastUsedModelConfig(){return this.lastUsedModelConfig}async transcribe(e,t){let n=this.aiImpl;if(n.transcribe)return await n.transcribe(e,{...this.getOptions(),...t??{}});throw new At("Audio transcription",this.name,!1)}async speak(e,t){let n=this.aiImpl;if(n.speak)return await n.speak(e,{...this.getOptions(),...t??{}});throw new At("Audio speech",this.name,!1)}calculatePercentile(e,t){if(e.length===0)return 0;let n=[...e].sort((i,s)=>i-s),o=Math.ceil(t/100*n.length)-1;return n[o]??0}updateLatencyMetrics(e,t,n){let o=this.metrics.latency[e];o.samples.push(t),o.samples.length>1e3&&o.samples.shift(),o.mean=o.samples.reduce((s,a)=>s+a,0)/o.samples.length,o.p95=this.calculatePercentile(o.samples,95),o.p99=this.calculatePercentile(o.samples,99);let i=this.getMetricsInstruments(n);if(i){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n?.customLabels);im(i,e,t,this.name,s,a),sm(i,e,o.mean,o.p95,o.p99,this.name,s,a)}}updateErrorMetrics(e,t,n){let o=this.metrics.errors[e];o.total++,t&&o.count++,o.rate=o.count/o.total;let i=this.getMetricsInstruments(n);if(i){let s=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel,a=this.getMergedCustomLabels(n?.customLabels);lm(i,e,this.name,s,a),t&&am(i,e,this.name,s,a),cm(i,e,o.rate,this.name,s,a)}}recordEstimatedCost(e,t,n,o){if(t<=0)return;let i=this.getMetricsInstruments(o);if(!i)return;let s=this.getMergedCustomLabels(o?.customLabels);mm(i,e,t,this.name,n,s)}recordTokenUsage(e,t,n){let o=this.getMetricsInstruments(n);if(!o||!t)return;let{promptTokens:i,completionTokens:s,totalTokens:a,thoughtsTokens:c,cacheReadTokens:l,cacheCreationTokens:u}=t,d=this.getMergedCustomLabels(n?.customLabels);i&&bo(o,"input",i,this.name,e,d),s&&bo(o,"output",s,this.name,e,d),a&&bo(o,"total",a,this.name,e,d),c&&bo(o,"thoughts",c,this.name,e,d),l&&tl(o,"read",l,this.name,e,d),u&&tl(o,"write",u,this.name,e,d)}calculateRequestSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}calculateResponseSize(e){try{return new TextEncoder().encode(JSON.stringify(e)).length}catch{return 0}}detectMultimodalContent(e){let t=!1,n=!1;if(e.chatPrompt&&Array.isArray(e.chatPrompt)){for(let o of e.chatPrompt)if(o.role==="user"&&Array.isArray(o.content))for(let i of o.content)i.type==="image"?t=!0:i.type==="audio"&&(n=!0)}return{hasImages:t,hasAudio:n}}calculateContextWindowUsage(e,t){if(!t?.tokens?.promptTokens)return 0;let n=lt({model:e,modelInfo:this.modelInfo});return n?.contextWindow?t.tokens.promptTokens/n.contextWindow:0}estimateCostByName(e,t){if(!t?.tokens)return 0;let n=lt({model:e,modelInfo:this.modelInfo});if(!n||!n.promptTokenCostPer1M&&!n.completionTokenCostPer1M)return 0;let{promptTokens:o=0,completionTokens:i=0,thoughtsTokens:s=0,cacheReadTokens:a=0,cacheCreationTokens:c=0,speed:l}=t.tokens,u=o+a+c,d=n.longContextThreshold!==void 0&&u>n.longContextThreshold,p=l==="fast",m=p?n.fastPromptTokenCostPer1M??n.promptTokenCostPer1M??0:d?n.longContextPromptTokenCostPer1M??n.promptTokenCostPer1M??0:n.promptTokenCostPer1M??0,g=p?n.fastCompletionTokenCostPer1M??n.completionTokenCostPer1M??0:d?n.longContextCompletionTokenCostPer1M??n.completionTokenCostPer1M??0:n.completionTokenCostPer1M??0,h=p?n.fastCacheReadTokenCostPer1M??n.cacheReadTokenCostPer1M??m:d?n.longContextCacheReadTokenCostPer1M??n.cacheReadTokenCostPer1M??m:n.cacheReadTokenCostPer1M??m,x=p?n.fastCacheWriteTokenCostPer1M??n.cacheWriteTokenCostPer1M??m:n.cacheWriteTokenCostPer1M??m,f=i+s;return o*m/1e6+f*g/1e6+a*h/1e6+c*x/1e6}recordFunctionCallMetrics(e,t,n){let o=this.getMetricsInstruments(n);if(!(!o||!e))for(let i of e)i&&typeof i=="object"&&"function"in i&&i.function&&typeof i.function=="object"&&"name"in i.function&&dm(o,i.function.name,void 0,this.name,t,this.getMergedCustomLabels(n?.customLabels))}recordTimeoutMetric(e,t){let n=this.getMetricsInstruments(t);if(n){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;hm(n,e,this.name,o,this.getMergedCustomLabels(t?.customLabels))}}recordAbortMetric(e,t){let n=this.getMetricsInstruments(t);if(n){let o=e==="chat"?this.lastUsedChatModel:this.lastUsedEmbedModel;xm(n,e,this.name,o,this.getMergedCustomLabels(t?.customLabels))}}recordChatMetrics(e,t,n){let o=this.getMetricsInstruments(t);if(!o)return;let i=this.lastUsedChatModel,s=this.lastUsedModelConfig,a=this.getMergedCustomLabels(t?.customLabels),c=s?.stream??!1;um(o,"chat",c,this.name,i,a);let{hasImages:l,hasAudio:u}=this.detectMultimodalContent(e);Am(o,l,u,this.name,i,a);let d=Je(e.chatPrompt);gm(o,d,this.name,i,a),pm(o,s?.temperature,s?.maxTokens,this.name,i,a),t?.thinkingTokenBudget&&this.modelUsage?.tokens?.thoughtsTokens&&ym(o,this.modelUsage.tokens.thoughtsTokens,this.name,i,a);let p=this.calculateRequestSize(e);if(Zc(o,"chat",p,this.name,i,a),n&&!c){let m=n,g=this.calculateResponseSize(m);if(el(o,"chat",g,this.name,i,a),m.results)for(let x of m.results)x.functionCalls&&this.recordFunctionCallMetrics(x.functionCalls,this.lastUsedChatModel,t);let h=this.calculateContextWindowUsage(this.lastUsedChatModel,m.modelUsage);h>0&&fm(o,h,this.name,i,a)}}recordEmbedMetrics(e,t,n){let o=this.getMetricsInstruments(n);if(!o)return;let i=this.lastUsedEmbedModel,s=this.getMergedCustomLabels(n?.customLabels),a=this.calculateRequestSize(e);Zc(o,"embed",a,this.name,i,s);let c=this.calculateResponseSize(t);el(o,"embed",c,this.name,i,s)}getMetrics(){return structuredClone(this.metrics)}getEstimatedCost(e){return e?this.estimateCostByName(e.model,e):0}async chat(e,t){let n=performance.now(),o=!1,i,s=this.getModelByKey(e.model),a=s?s.thinkingTokenBudget:void 0,c={...this.beta!==void 0?{beta:this.beta}:void 0,...s?{thinkingTokenBudget:a,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel,beta:s.beta}:void 0,...Object.fromEntries(Object.entries(t??{}).filter(([,l])=>l!==void 0))};try{return i=await this._chat1(e,c),i}catch(l){throw o=!0,l instanceof Error&&(l.message.includes("timeout")||l.name==="TimeoutError"?this.recordTimeoutMetric("chat",c):(l.message.includes("abort")||l.name==="AbortError")&&this.recordAbortMetric("chat",c)),l}finally{let l=performance.now()-n;this.updateLatencyMetrics("chat",l,c),this.updateErrorMetrics("chat",o,c),o||this.recordChatMetrics(e,c,i)}}async _chat1(e,t){let n=this.getModel(e.model)??e.model??this.defaults.model;if(Array.isArray(e.chatPrompt))for(let l of e.chatPrompt)Lo(l);let o=this.getModelByKey(e.model),i={...this.aiImpl.getModelConfig(),...o?o.modelConfig:void 0,...e.modelConfig},s=lt({model:n,modelInfo:this.modelInfo});if(s?.notSupported?.temperature&&"temperature"in i&&delete i.temperature,s?.notSupported?.topP&&"topP"in i&&delete i.topP,s?.isExpensive&&t?.useExpensiveModel!=="yes")throw new Error(`Model ${n} is marked as expensive and requires explicit confirmation. Set useExpensiveModel: "yes" to proceed.`);i.stream=(t?.stream!==void 0?t.stream:i.stream)??!0,this.getFeatures(n).streaming||(i.stream=!1);let c=this.getEffectiveTracer(t);return c?await c.startActiveSpan("AI Chat Request",{kind:oA.SERVER,attributes:{[Oe.LLM_SYSTEM]:this.name,[Oe.LLM_OPERATION_NAME]:"chat",[Oe.LLM_REQUEST_MODEL]:n,[Oe.LLM_REQUEST_MAX_TOKENS]:i.maxTokens??"Not set",[Oe.LLM_REQUEST_TEMPERATURE]:i.temperature,[Oe.LLM_REQUEST_TOP_P]:i.topP??"Not set",[Oe.LLM_REQUEST_TOP_K]:i.topK??"Not set",[Oe.LLM_REQUEST_FREQUENCY_PENALTY]:i.frequencyPenalty??"Not set",[Oe.LLM_REQUEST_PRESENCE_PENALTY]:i.presencePenalty??"Not set",[Oe.LLM_REQUEST_STOP_SEQUENCES]:i.stopSequences?.join(", ")??"Not set",[Oe.LLM_REQUEST_LLM_IS_STREAMING]:i.stream??"Not set",...t?.sessionId?{[Oe.LLM_CONVERSATION_ID]:t.sessionId,[Oe.AX_SESSION_ID]:t.sessionId}:{}}},t?.traceContext??rA.active(),async l=>await this._chat2(n,i,e,t,l)):await this._chat2(n,i,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 retryTransientStreamStart(e,t,n){let o={...Ll,...n},i=this.aiImpl.classifyStreamErrorStatus,s=e,a=0;for(;;){let c=s.getReader(),l=await c.read();if(!l.done){let d=i?.(l.value);if(d!==void 0&&o.retryableStatusCodes.includes(d)&&a<o.maxRetries){await c.cancel().catch(()=>{}),a++;let p=Math.min(o.initialDelayMs*o.backoffFactor**(a-1),o.maxDelayMs);await new Promise(g=>setTimeout(g,p));let m=await t();if(!(m instanceof ReadableStream))return m;s=m;continue}}let u=!1;return new ReadableStream({async pull(d){if(!u){if(u=!0,l.done){d.close();return}d.enqueue(l.value);return}try{let{done:p,value:m}=await c.read();if(p){d.close();return}d.enqueue(m)}catch(p){d.error(p)}},cancel(d){return c.cancel(d)}})}}async _chat2(e,t,n,o,i){if(!this.aiImpl.createChatReq)throw new Error("createChatReq not implemented");let s=this.getEffectiveDebug(o),a=o?.verbose??this.#e,c=this.getEffectiveLogger(o),l=this.getEffectiveAbortSignal(o),u=o?.excludeContentFromTrace??this.excludeContentFromTrace,d;n.functions&&n.functions.length>0&&(d=n.functions.map($=>this.cleanupFunctionSchema($)));let p={...n,model:e,functions:d,modelConfig:t};this.lastUsedChatModel=e,this.lastUsedModelConfig=t,s&&Wp(p.chatPrompt,o?.stepIndex??0,c,o?.debugHideSystemPrompt);let m=this.getFeatures(e).functions,g=o?.functionCallMode??"auto",x=g==="prompt"||g==="auto"&&!m?{...p,chatPrompt:p.chatPrompt.map($=>{if($.role==="assistant"){let{content:N,name:V,cache:I}=$;return{role:"assistant",content:N,name:V,cache:I}}return $.role==="function"?{role:"user",content:$.result}:$}),functions:[]}:p,f=await this.handleContextCaching(e,x,o,i),y={},A=$=>{y=cA(y,aA($.headers,this.name))},b=async($,N)=>Ks({name:$.name,url:$.url??this.apiURL,method:$.method,put:$.put,localCall:$.localCall,headers:await this.buildHeaders($.headers),stream:t.stream,timeout:this.timeout,verbose:a,fetch:this.fetch,span:i,abortSignal:l,corsProxy:this.corsProxy,onResponseMetadata:A,retry:o?.retry??this.retry,includeRequestBodyInErrors:o?.includeRequestBodyInErrors??this.includeRequestBodyInErrors},N),w=async()=>{let[$,N]=await this.aiImpl.createChatReq(x,o);return b($,N)},v=async()=>{if(i?.isRecording()&&Wk(n,i,u),!f?.preparedRequest)return w();let{apiConfig:$,request:N}=f.preparedRequest;try{return await b($,N)}catch(V){if(!f.managedCache||!jk(V))throw V;return await this.invalidateManagedContextCache(f.managedCache,"provider_rejected",i,V.status),i?.addEvent("context_cache.fallback",{reason:"provider_rejected",mode:"uncached",status:V.status}),w()}},F=o?.rateLimiter??this.rt,k=()=>F?F(v,{modelUsage:this.modelUsage}):v(),O;try{O=await k(),t.stream&&O instanceof ReadableStream&&this.aiImpl.classifyStreamErrorStatus&&(O=await this.retryTransientStreamStart(O,k,o?.retry??this.retry))}catch($){throw oo(i,$),i?.isRecording()&&i.end(),$}if(t.stream){if(!this.aiImpl.createChatStreamResp)throw new Error("createChatStreamResp not implemented");let $=this.aiImpl.createChatStreamResp.bind(this),N=Kk(),V=0,I,_,S,H,L=C=>T=>{try{let E=$(T,C);if(E.remoteId?I=E.remoteId:I&&(E.remoteId=I),E.remoteRequestId?_=E.remoteRequestId:_&&(E.remoteRequestId=_),E.remoteSessionId?S=E.remoteSessionId:S&&(E.remoteSessionId=S),H=ic(H,E.providerMetadata),H&&(E.providerMetadata=H),wd(E,o?.sessionId,y),E.remoteRequestId&&(_=E.remoteRequestId),E.remoteSessionId&&(S=E.remoteSessionId),H=ic(H,E.providerMetadata),!E.modelUsage){let D=this.aiImpl.getTokenUsage();D&&(E.modelUsage={ai:this.name,model:e,tokens:D})}if(this.modelUsage=E.modelUsage,E.modelUsage?.tokens){let D=N(E.modelUsage.tokens);if(D){this.recordTokenUsage(E.modelUsage.model,D,o);let j=this.estimateCostByName(E.modelUsage.model,E.modelUsage),J=Math.max(0,j-V);j>V&&(V=j),this.recordEstimatedCost("chat",J,E.modelUsage.model,o)}}return i?.isRecording()&&lA(E,i,u),E}catch(E){throw oo(i,E),i?.isRecording()&&i.end(),E}},W=async C=>{for(let T=C.length-1;T>=0;T--){let E=C[T];if(E?.modelUsage?.tokens){_o("chat",E,this.getMergedUsageContext(o),!0);break}}i?.isRecording()&&i.end(),s&&Yp(C,c)};if(typeof window<"u"){let C=O,T={},E=[];return new ReadableStream({start:D=>{let j=C.getReader(),J=()=>{try{j.cancel().catch(()=>{})}catch{}try{this.recordAbortMetric("chat",o)}catch{}try{i?.isRecording()&&i.end()}catch{}try{D.error(new DOMException("Aborted","AbortError"))}catch{D.error(new Error("Aborted"))}};if(l){if(l.aborted){J();return}l.addEventListener("abort",J,{once:!0})}async function z(){try{for(;;){let{done:B,value:K}=await j.read();if(B){W&&await W(E),D.close();break}let ie=L(T)(K);ie&&(E.push(ie),D.enqueue(ie))}}catch(B){if(oo(i,B),D.error(B),i?.isRecording())try{i.end()}catch{}}finally{if(j.releaseLock(),l)try{l.removeEventListener("abort",J)}catch{}}}z()}})}return O.pipeThrough(new oc(L({}),W))}if(!this.aiImpl.createChatResp)throw new Error("createChatResp not implemented");try{let $=this.aiImpl.createChatResp(O);if(wd($,o?.sessionId,y),!$.modelUsage){let N=this.aiImpl.getTokenUsage();N&&($.modelUsage={ai:this.name,model:e,tokens:N})}return $.modelUsage&&(this.modelUsage=$.modelUsage,this.recordTokenUsage($.modelUsage.model,$.modelUsage.tokens,o),this.recordEstimatedCost("chat",this.estimateCostByName($.modelUsage.model,$.modelUsage),$.modelUsage.model,o)),_o("chat",$,this.getMergedUsageContext(o),!1),i?.isRecording()&&(lA($,i,u),i.end()),s&&Jp($,c),$}catch($){throw oo(i,$),i?.isRecording()&&i.end(),$}}async embed(e,t){let n=performance.now(),o=!1,i,s=this.getModelByKey(e.embedModel),a={...this.beta!==void 0?{beta:this.beta}:void 0,...s?{thinkingTokenBudget:s.thinkingTokenBudget,showThoughts:s.showThoughts,stream:s.stream,debug:s.debug,useExpensiveModel:s.useExpensiveModel,beta:s.beta}:void 0,...t};try{return i=await this._embed1(e,a),i}catch(c){throw o=!0,c instanceof Error&&(c.message.includes("timeout")||c.name==="TimeoutError"?this.recordTimeoutMetric("embed",a):(c.message.includes("abort")||c.name==="AbortError")&&this.recordAbortMetric("embed",a)),c}finally{let c=performance.now()-n;this.updateLatencyMetrics("embed",c,a),this.updateErrorMetrics("embed",o,a),!o&&i&&this.recordEmbedMetrics(e,i,a)}}async _embed1(e,t){let n=this.getEmbedModel(e.embedModel)??e.embedModel??this.defaults.embedModel;if(!n)throw new Error("No embed model defined");let o=this.getEffectiveTracer(t);return o?await o.startActiveSpan("AI Embed Request",{kind:oA.SERVER,attributes:{[Oe.LLM_SYSTEM]:this.name,[Oe.LLM_OPERATION_NAME]:"embeddings",[Oe.LLM_REQUEST_MODEL]:n,...t?.sessionId?{[Oe.LLM_CONVERSATION_ID]:t.sessionId,[Oe.AX_SESSION_ID]:t.sessionId}:{}}},t?.traceContext??rA.active(),async i=>await this._embed2(n,e,t,i)):await this._embed2(n,e,t)}async _embed2(e,t,n,o){if(!this.aiImpl.createEmbedReq)throw new Error("createEmbedReq not implemented");if(!this.aiImpl.createEmbedResp)throw new Error("createEmbedResp not implemented");let i=this.aiImpl.createEmbedReq.bind(this.aiImpl),s=this.getEffectiveDebug(n),a=n?.verbose??this.#e,c=this.getEffectiveLogger(n),l=this.getEffectiveAbortSignal(n),u={...t,embedModel:e};this.lastUsedEmbedModel=e,s&&em(u.texts??[],e,c);let d={},p=f=>{d=cA(d,aA(f.headers,this.name))},m=async()=>{let[f,y]=await i(u,n);return await Ks({name:f.name,url:f.url??this.apiURL,method:f.method,put:f.put,localCall:f.localCall,headers:await this.buildHeaders(f.headers),verbose:a,fetch:this.fetch,timeout:this.timeout,span:o,abortSignal:l,corsProxy:this.corsProxy,onResponseMetadata:p,retry:n?.retry??this.retry,includeRequestBodyInErrors:n?.includeRequestBodyInErrors??this.includeRequestBodyInErrors},y)},g=n?.rateLimiter??this.rt,h;try{h=g?await g(m,{modelUsage:this.embedModelUsage}):await m()}catch(f){throw oo(o,f),o?.isRecording()&&o.end(),f}let x;try{x=this.aiImpl.createEmbedResp(h),wd(x,n?.sessionId,d)}catch(f){throw oo(o,f),o?.isRecording()&&o.end(),f}if(!x.modelUsage){let f=this.aiImpl.getTokenUsage();f&&(x.modelUsage={ai:this.name,model:e,tokens:f})}return this.embedModelUsage=x.modelUsage,x.modelUsage&&(this.recordTokenUsage(x.modelUsage.model,x.modelUsage.tokens,n),this.recordEstimatedCost("embed",this.estimateCostByName(x.modelUsage.model,x.modelUsage),x.modelUsage.model,n)),_o("embed",x,this.getMergedUsageContext(n),!1),o?.isRecording()&&(uA(x,o),x.modelUsage?.tokens&&o.addEvent(dn.GEN_AI_USAGE,{[Oe.LLM_USAGE_INPUT_TOKENS]:x.modelUsage.tokens.promptTokens,[Oe.LLM_USAGE_OUTPUT_TOKENS]:x.modelUsage.tokens.completionTokens??0,[Oe.LLM_USAGE_TOTAL_TOKENS]:x.modelUsage.tokens.totalTokens})),s&&tm(x.embeddings,c),o?.end(),x}async buildHeaders(e={}){return{...await this.headers(),...e}}getModelByKey(e){return e?this.models?.find(n=>n.key===e):void 0}getModel(e){let t=this.getModelByKey(e);return t&&"model"in t?t.model:void 0}getEmbedModel(e){let t=this.getModelByKey(e);return t&&"embedModel"in t?t.embedModel:void 0}async handleContextCaching(e,t,n,o){let i=n?.contextCache;if(!i)return null;let s=this.aiImpl.supportsContextCache?.(e)??!1,a=this.aiImpl.supportsImplicitCaching?.(e)??!1;if(!s&&!a)throw new Error(`Context caching is not supported by this provider/model (${this.getName()}/${e}). Remove the contextCache option or use a provider that supports caching.`);if(!s)return null;let c=i.ttlSeconds??3600,l=i.refreshWindowSeconds??300,u=i.minTokens??2048;if(i.name)return this.useCacheByName(e,t,i.name,n,o);let d=this.getContextCacheToolState(t,i),p=Hk(t,d);if(!p||p===Rt("sha256").digest("hex"))return null;let m={providerName:this.getName(),model:String(e),contentHash:p},g=Dk(m),h=Date.now(),x=i.registry,f=v=>({key:g,cacheName:v,registry:x}),y=!1,A=x?await x.get(g):hi.get(g);if(A&&A.expiresAt>h)if(A.expiresAt-h<l*1e3&&this.aiImpl.buildCacheUpdateTTLOp){let F;try{let O=this.aiImpl.buildCacheUpdateTTLOp(A.cacheName,c);F=await this.executeCacheOperation(O,n,o)}catch(O){o?.addEvent("context_cache.error",{type:"update",error:O instanceof Error?O.message:String(O)})}let k=iA(F,h);if(F&&k!==void 0){let O={cacheName:F.name,expiresAt:k,tokenCount:F.tokenCount??A.tokenCount};return x?await x.set(g,O):hi.set(g,{...O,contentHash:p,lastTouchedAt:h}),this.useCacheByName(e,t,F.name,n,o,f(F.name))}await this.invalidateManagedContextCache(f(A.cacheName),"refresh_failed",o),y=!0}else return this.useCacheByName(e,t,A.cacheName,n,o,f(A.cacheName));if(this.estimateCacheableTokens(t,d)<u)return y&&o?.addEvent("context_cache.fallback",{reason:"refresh_failed",mode:"uncached"}),null;let w;try{w=this.aiImpl.buildCacheCreateOp?.(t,n)}catch(v){o?.addEvent("context_cache.error",{type:"create",error:v instanceof Error?v.message:String(v)})}if(w){let v=await this.executeCacheOperation(w,n,o),F=iA(v,h);if(v&&F!==void 0){let k={cacheName:v.name,expiresAt:F,tokenCount:v.tokenCount};return x?await x.set(g,k):hi.set(g,{...k,contentHash:p,lastTouchedAt:h}),y&&o?.addEvent("context_cache.fallback",{reason:"refresh_failed",mode:"recreate"}),this.useCacheByName(e,t,v.name,n,o,f(v.name))}}return y&&o?.addEvent("context_cache.fallback",{reason:"refresh_failed",mode:"uncached"}),null}async useCacheByName(e,t,n,o,i,s){if(this.aiImpl.prepareCachedChatReq){let a=await this.aiImpl.prepareCachedChatReq(t,o??{},n);return{preparedRequest:{apiConfig:a.apiConfig,request:a.request},managedCache:s}}return null}async invalidateManagedContextCache(e,t,n,o){try{let i=!1;if(e.registry){let s=await e.registry.get(e.key);s?.cacheName===e.cacheName&&(await e.registry.set(e.key,{...s,expiresAt:0}),i=!0)}else hi.get(e.key)?.cacheName===e.cacheName&&(i=hi.delete(e.key));n?.addEvent("context_cache.invalidated",{reason:t,cacheName:e.cacheName,invalidated:i,...o!==void 0?{status:o}:{}})}catch(i){n?.addEvent("context_cache.error",{type:"invalidate",reason:t,error:i instanceof Error?i.message:String(i)})}}getContextCacheToolState(e,t){if(t)return this.aiImpl.getContextCacheToolState?.(e,{contextCache:t})??qk(e)}async executeCacheOperation(e,t,n){let o=t?.verbose??this.#e,i=this.getEffectiveAbortSignal(t);try{n?.addEvent("context_cache.operation",{type:e.type,endpoint:e.apiConfig.name});let s=await Ks({name:e.apiConfig.name,url:e.apiConfig.url??this.apiURL,method:e.apiConfig.method,put:e.apiConfig.put,localCall:e.apiConfig.localCall,headers:await this.buildHeaders(e.apiConfig.headers),stream:!1,timeout:this.timeout,verbose:o,fetch:this.fetch,span:n,abortSignal:i,corsProxy:this.corsProxy,retry:t?.retry??this.retry,includeRequestBodyInErrors:t?.includeRequestBodyInErrors??this.includeRequestBodyInErrors},e.request);return e.parseResponse(s)}catch(s){n?.addEvent("context_cache.error",{type:e.type,error:s instanceof Error?s.message:String(s)});return}}estimateCacheableTokens(e,t){let{chatPrompt:n}=e,o=0;for(let i of n){if(i.role==="system"){o+=i.content.length;continue}if("cache"in i&&i.cache)if(i.role==="user"){if(typeof i.content=="string")o+=i.content.length;else if(Array.isArray(i.content))for(let s of i.content)"cache"in s&&s.cache&&(s.type==="text"?o+=s.text.length:s.type==="image"?o+=1e3:s.type==="audio"?o+=2e3:s.type==="file"&&(o+=500))}else if(i.role==="assistant"){if(i.content&&(o+=i.content.length),i.functionCalls)for(let s of i.functionCalls)o+=s.function.name.length,o+=dA(s.function.params).length}else i.role==="function"&&(o+=i.functionId.length,o+=i.result.length)}return t&&(o+=Sd(t).length),Math.ceil(o/4)}};function Wk(r,e,t){let n=[];if(r.chatPrompt&&Array.isArray(r.chatPrompt)&&r.chatPrompt.length>0)for(let i of r.chatPrompt)switch(i.role){case"system":if(i.content){let s={};t||(s.content=i.content),e.addEvent(dn.GEN_AI_SYSTEM_MESSAGE,s)}break;case"user":if(typeof i.content=="string")n.push(i.content);else if(Array.isArray(i.content))for(let s of i.content)s.type==="text"&&n.push(s.text);break;case"assistant":{let s=i.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params}));if(s&&s.length>0){let a={function_calls:JSON.stringify(s,null,2)};!t&&i.content&&(a.content=i.content),e.addEvent(dn.GEN_AI_ASSISTANT_MESSAGE,a)}else if(i.content){let a={};t||(a.content=i.content),e.addEvent(dn.GEN_AI_ASSISTANT_MESSAGE,a)}break}case"function":{let s={id:i.functionId};t||(s.content=i.result),e.addEvent(dn.GEN_AI_TOOL_MESSAGE,s);break}}let o={};t||(o.content=n.join(`
|
|
1253
|
-
`)),e.addEvent(dn.GEN_AI_USER_MESSAGE,o)}function lA(r,e,t){if(uA(r,e),r.modelUsage?.tokens){let n=r.modelUsage.tokens.thoughtsTokens?{[Oe.LLM_USAGE_THOUGHTS_TOKENS]:r.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(dn.GEN_AI_USAGE,{[Oe.LLM_USAGE_INPUT_TOKENS]:r.modelUsage.tokens.promptTokens,[Oe.LLM_USAGE_OUTPUT_TOKENS]:r.modelUsage.tokens.completionTokens??0,[Oe.LLM_USAGE_TOTAL_TOKENS]:r.modelUsage.tokens.totalTokens,...n})}if(r.results)for(let n=0;n<r.results.length;n++){let o=r.results[n];if(!o||!o.content&&!o.thought&&!o.functionCalls?.length&&!o.finishReason)continue;let i=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};i&&i.length>0?(t||(s.content=o.content),s.tool_calls=i):t||(s.content=o.content??""),e.addEvent(dn.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Jk(r){let e=new Set;for(let t of r){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 Yk=new Set(["us","eu"]),xi=r=>r==="global"?"aiplatform.googleapis.com":Yk.has(r)?`aiplatform.${r}.rep.googleapis.com`:`${r}-aiplatform.googleapis.com`;var yi=(A=>(A.Claude5Sonnet="claude-sonnet-5",A.Claude48Opus="claude-opus-4-8",A.Claude47Opus="claude-opus-4-7",A.Claude46Opus="claude-opus-4-6",A.Claude46Sonnet="claude-sonnet-4-6",A.Claude45Opus="claude-opus-4-5-20251101",A.Claude41Opus="claude-opus-4-1-20250805",A.Claude4Opus="claude-opus-4-20250514",A.Claude4Sonnet="claude-sonnet-4-20250514",A.Claude45Sonnet="claude-sonnet-4-5-20250929",A.Claude45Haiku="claude-haiku-4-5",A.Claude37Sonnet="claude-3-7-sonnet-latest",A.Claude35Sonnet="claude-3-5-sonnet-latest",A.Claude35Haiku="claude-3-5-haiku-latest",A.Claude3Opus="claude-3-opus-latest",A.Claude3Sonnet="claude-3-sonnet-20240229",A.Claude3Haiku="claude-3-haiku-20240307",A.Claude21="claude-2.1",A.ClaudeInstant12="claude-instant-1.2",A))(yi||{}),sc=(f=>(f.Claude5Sonnet="claude-sonnet-5",f.Claude48Opus="claude-opus-4-8",f.Claude47Opus="claude-opus-4-7",f.Claude46Opus="claude-opus-4-6",f.Claude46Sonnet="claude-sonnet-4-6",f.Claude45Opus="claude-opus-4-5@20251101",f.Claude41Opus="claude-opus-4-1@20250805",f.Claude4Opus="claude-opus-4@20250514",f.Claude45Sonnet="claude-sonnet-4-5@20250929",f.Claude4Sonnet="claude-sonnet-4@20250514",f.Claude37Sonnet="claude-3-7-sonnet@20250219",f.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",f.Claude45Haiku="claude-haiku-4-5@20251001",f.Claude35Haiku="claude-3-5-haiku@20241022",f.Claude35Sonnet="claude-3-5-sonnet@20240620",f.Claude3Opus="claude-3-opus@20240229",f.Claude3Haiku="claude-3-haiku@20240307",f))(sc||{});var io=[{name:"claude-sonnet-5",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-5",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-8",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:10,fastCompletionTokenCostPer1M:50,fastCacheReadTokenCostPer1M:1,fastCacheWriteTokenCostPer1M:12.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-8",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-7",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:30,fastCompletionTokenCostPer1M:150,fastCacheReadTokenCostPer1M:3,fastCacheWriteTokenCostPer1M:37.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-7",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:30,fastCompletionTokenCostPer1M:150,fastCacheReadTokenCostPer1M:3,fastCacheWriteTokenCostPer1M:37.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,cacheReadTokenCostPer1M:.08,cacheWriteTokenCostPer1M:1,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,cacheReadTokenCostPer1M:.03,cacheWriteTokenCostPer1M:.3,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,cacheReadTokenCostPer1M:.03,cacheWriteTokenCostPer1M:.3,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 Qk=["structured-outputs-2025-11-13","web-search-2025-03-05"],Xk="fast-mode-2026-02-01",Zk="task-budgets-2026-03-13",fA=(r=[])=>[...new Set([...Qk,...r])].join(", ");function hA(r){switch(r){case"overloaded_error":return 529;case"api_error":return 500;case"rate_limit_error":return 429;case"invalid_request_error":return 400;case"permission_error":return 403;case"not_found_error":return 404;case"request_too_large":return 413;default:return}}function pA(r){if(r.type==="authentication_error")return new It("",void 0,r);let e=hA(r.type);return e!==void 0?new Qe(e,r.type,"",void 0,r):new Ke(r.message)}var eI=r=>r.includes("claude-opus-4-7")||r.includes("claude-opus-4-8"),tI=r=>r.includes("claude-opus-4-8"),nI=r=>r.includes("claude-sonnet-5"),mA=r=>r.includes("claude-opus-4-6")||eI(r)||nI(r),Vn=r=>{if(!r||typeof r!="object")return r;let e={...r},t=Array.isArray(e.type)?e.type:[e.type],n=Array.isArray(e.type)&&e.type.length===2&&e.type.includes("null");if(Array.isArray(e.type)&&e.type.length>1&&!n)return e.type="object",e.additionalProperties=!0,delete e.properties,delete e.required,delete e.items,e;if(e.type==="object"||n&&t.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)return e;e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,(t.includes("number")||t.includes("integer"))&&(delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf),t.includes("string")&&(delete e.minLength,delete e.maxLength,delete e.pattern,delete e.format),t.includes("array")&&(delete e.minItems,delete e.maxItems,delete e.uniqueItems),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([i,s])=>[i,Vn(s)]))),e.items&&(e.items=Vn(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(i=>Vn(i))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(i=>Vn(i))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(i=>Vn(i))),e},xA=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Ge()}),rI=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Ge()}),kd=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n,effort:e.effort,speed:e.speed,taskBudget:e.taskBudget}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=n,i=e.modelConfig?.stream??this.config.stream,s;this.isVertex?s={name:i?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={name:"/messages"};let a;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":a={tool_choice:{type:"auto"}};break;case"required":a={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)a={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let c=e.chatPrompt.some(C=>"cache"in C&&C.cache)||e.functions?.some(C=>C.cache),l=!this.isVertex&&tI(o),u=e.chatPrompt.findIndex(C=>C.role!=="system"),d=u===-1?e.chatPrompt.length:u,p=(l?e.chatPrompt.slice(0,d):e.chatPrompt).filter(C=>C.role==="system"),m=p.map((C,T)=>({type:"text",text:C.content,...C.cache||c&&T===p.length-1?{cache_control:{type:"ephemeral"}}:{}})),g=l?e.chatPrompt.slice(d):e.chatPrompt.filter(C=>C.role!=="system"),h=e.functions?.map((C,T,E)=>{let D={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},j=C.parameters?Vn(C.parameters):void 0;return j===void 0||j&&typeof j=="object"&&Object.keys(j).length===0?j={...D}:j&&typeof j=="object"&&j.type==="object"&&(!("properties"in j)||!j.properties||Object.keys(j.properties).length===0)&&(j={...j,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:C.name,description:C.description,input_schema:j,...C.cache||c&&T===E.length-1?{cache_control:{type:"ephemeral"}}:{}}}),f=(this.config.tools??[]).map(C=>C&&typeof C=="object"&&"type"in C?C:{name:C.name,description:C.description,input_schema:C.input_schema?Vn(C.input_schema):void 0,...C.cache_control?{cache_control:C.cache_control}:{}}),y=[...h??[],...f];y.length===0&&(y=void 0);let A=e.modelConfig?.maxTokens??this.config.maxTokens,b=e.modelConfig?.stopSequences??this.config.stopSequences,w=e.modelConfig?.temperature,v=e.modelConfig?.topP,F=e.modelConfig?.topK??this.config.topK,k=e.modelConfig?.n??this.config.n,O=e.modelConfig?.effort??this.config.effort,$=e.modelConfig?.speed??this.config.speed,N=e.modelConfig?.taskBudget??this.config.taskBudget;if(k&&k>1)throw new Error("Anthropic does not support sampling (n > 1)");let V=C=>C.includes("claude-opus-4-5"),I=mA(o),_,S;if(t?.thinkingTokenBudget){let C=this.config.thinkingTokenBudgetLevels,T=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")_=void 0,S=void 0;else{let E=t.thinkingTokenBudget;if(mA(o))_={type:"adaptive",display:t?.showThoughts===!1?"omitted":"summarized"},S={effort:T?.[E]??"medium"};else if(V(o)){_={type:"enabled",budget_tokens:C?.[E]??1e4};let j=T?.[E]??"medium";j==="max"&&(j="high"),S={effort:j}}else _={type:"enabled",budget_tokens:C?.[E]??1e4}}}if(O){let C=V(o)&&(O==="max"||O==="xhigh")?"high":O;S={...S,effort:C}}if(N){if(N.total<2e4)throw new Error("Anthropic taskBudget.total must be at least 20000 tokens");if(this.isVertex)throw new Error("Anthropic task budgets are only supported on the first-party Anthropic API");S={...S,task_budget:N}}let H=[];if($==="fast"){if(this.isVertex)throw new Error("Anthropic fast mode is only supported on the first-party Anthropic API");H.push(Xk)}N&&H.push(Zk),!this.isVertex&&H.length>0&&(s.headers={"anthropic-beta":fA(H)});let W=iI(g,!!_);if(W.some(C=>C.role==="assistant"&&Array.isArray(C.content)&&C.content.length>0&&C.content[0]?.type==="tool_use")&&(_=void 0,S)){let C={};O&&S.effort&&(C.effort=S.effort),S.task_budget&&(C.task_budget=S.task_budget),S=Object.keys(C).length>0?C:void 0}if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let C=e.responseFormat.schema.schema||e.responseFormat.schema;S={...S,format:{type:"json_schema",schema:Vn(C)}},this.usedStructuredOutput=!0}let Y={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...A?{max_tokens:A}:{},...b&&b.length>0?{stop_sequences:b}:{},...w!==void 0&&!_&&!I?{temperature:w}:{},...v!==void 0&&!I&&(!_||v>=.95)?{top_p:v}:{},...F&&!_&&!I?{top_k:F}:{},...a,...y?{tools:y}:{},...i?{stream:!0}:{},...m.length>0?{system:m}:{},..._?{thinking:_}:{},...S?{output_config:S}:{},...$==="fast"?{speed:"fast"}:{},messages:W};return[s,Y]};createChatResp=e=>{if(e.type==="error")throw pA(e.error);if(e.stop_reason==="refusal"){let u=e.content.filter(m=>m.type==="text").map(m=>"text"in m?m.text:"").join(""),d=e.stop_details??void 0,p=d?.explanation??(u.length>0?u:"Anthropic refused to fulfill this request");throw new Ke(p,e.model,e.id,d?.category,d?.explanation)}let t=gA(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,o="",i=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(o+=u.text??"",Array.isArray(u.citations))for(let d of u.citations)d?.url&&a.push({url:String(d.url),title:typeof d.title=="string"?d.title:void 0,snippet:typeof d.cited_text=="string"?d.cited_text:void 0});break;case"thinking":if(n){let d=u.thinking??"",p=u.signature;s.push({data:d,encrypted:!1,...typeof p=="string"?{signature:p}:{}})}break;case"redacted_thinking":if(n){let d=u.data??"",p=u.signature;s.push({data:d,encrypted:!0,...typeof p=="string"?{signature:p}:{}})}break;case"tool_use":i.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let c={index:0,id:e.id,finishReason:t};o&&(c.content=o),s.length>0&&(c.thoughtBlocks=s,c.thought=s.map(u=>u.data).join("")),i.length>0&&(c.functionCalls=i),a.length>0&&(c.citations=a);let l=[c];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens,speed:e.usage.speed},{results:l,remoteId:e.id}};classifyStreamErrorStatus=e=>e.type==="error"?hA(e.error.type):void 0;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:i}=e;throw pA(i)}let o=0;if(e.type==="message_start"){let{message:i}=e,s=[{index:o,content:"",id:i.id}];return n.remoteId=i.id,this.tokensUsed={promptTokens:i.usage?.input_tokens??0,completionTokens:i.usage?.output_tokens??0,totalTokens:(i.usage?.input_tokens??0)+(i.usage?.output_tokens??0)+(i.usage?.cache_creation_input_tokens??0)+(i.usage?.cache_read_input_tokens??0),cacheCreationTokens:i.usage?.cache_creation_input_tokens,cacheReadTokens:i.usage?.cache_read_input_tokens,speed:i.usage?.speed},{results:s,remoteId:i.id}}if(e.type==="content_block_start"){let{content_block:i}=e;if(i.type==="text"){let s=[];if(Array.isArray(i.citations))for(let a of i.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:o,content:i.text,...s.length?{citations:s}:{}}],remoteId:n.remoteId}}if(i.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:i.thinking,thoughtBlocks:[{data:i.thinking,encrypted:!1}]}]}:{results:[{index:o,content:""}]};if(i.type==="tool_use"&&typeof i.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=i.id;let s=[{id:i.id,type:"function",function:{name:i.name,params:""}}];return{results:[{index:o,functionCalls:s}]}}if(i.type==="web_search_tool_result"||i.type==="server_tool_use")return{results:[{index:o,content:""}]}}if(e.type==="content_block_delta"){let{delta:i}=e;if(i.type==="citations_delta"){let s=i.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:o,content:"",citations:a}],remoteId:n.remoteId}}return{results:[{index:o,content:""}],remoteId:n.remoteId}}if(i.type==="text_delta"){let s=[];if(Array.isArray(i.citations))for(let a of i.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:o,content:i.text,...s.length?{citations:s}:{}}]}}if(i.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:i.thinking,thoughtBlocks:[{data:i.thinking,encrypted:!1}]}]}:{results:[{index:o,content:""}]};if(i.type==="signature_delta")return{results:[{index:o,thoughtBlocks:[{data:"",encrypted:!1,signature:i.signature}]}]};if(i.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:o,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:i.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:i,usage:s}=e;if(this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens,speed:s.speed??this.tokensUsed?.speed},i.stop_reason==="refusal"){let c=i.stop_details??void 0;throw new Ke(c?.explanation??"Anthropic refused to fulfill this request",void 0,n.remoteId,c?.category,c?.explanation)}return{results:[{index:o,content:"",finishReason:gA(i.stop_reason)}]}}return{results:[{index:o,content:""}]}};supportsImplicitCaching=()=>!0},Ai=class r extends Et{static create(e){return new r(e)}constructor({apiKey:e,projectId:t,region:n,config:o,options:i,models:s}){let a=t!==void 0&&n!==void 0,c,l;if(t!==void 0&&n!==void 0){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");c=`https://${xi(n)}/v1/projects/${t}/locations/${n}/publishers/anthropic/`,l=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");c="https://api.anthropic.com/v1",l=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":fA(),"x-api-key":typeof e=="function"?await e():e})}let u={...xA(),...o},d=new kd(u,a),p=g=>{let h=lt({model:g,modelInfo:io,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,x=h?.config;if(!x)return g;let f={};x.maxTokens!==void 0&&(f.maxTokens=x.maxTokens),x.temperature!==void 0&&(f.temperature=x.temperature),x.topP!==void 0&&(f.topP=x.topP),x.topK!==void 0&&(f.topK=x.topK),x.presencePenalty!==void 0&&(f.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(f.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(f.stopSequences=x.stopSequences),x.endSequences!==void 0&&(f.endSequences=x.endSequences),x.stream!==void 0&&(f.stream=x.stream),x.n!==void 0&&(f.n=x.n),x.effort!==void 0&&(f.effort=x.effort),x.speed!==void 0&&(f.speed=x.speed),x.taskBudget!==void 0&&(f.taskBudget=x.taskBudget);let y={...h};Object.keys(f).length>0&&(y.modelConfig={...h.modelConfig??{},...f});let A=x.thinking?.thinkingTokenBudget;if(typeof A=="number"){let b=u.thinkingTokenBudgetLevels,w=[["minimal",b?.minimal??1024],["low",b?.low??5e3],["medium",b?.medium??1e4],["high",b?.high??2e4],["highest",b?.highest??32e3]],v="minimal",F=Number.POSITIVE_INFINITY;for(let[k,O]of w){let $=Math.abs(A-O);$<F&&(F=$,v=k)}y.thinkingTokenBudget=v}return x.thinking?.includeThoughts!==void 0&&(y.showThoughts=!!x.thinking.includeThoughts),y});super(d,{name:"Anthropic",apiURL:c,headers:l,modelInfo:io,defaults:{model:u.model},options:i,supportFor:p,models:m??s})}};function oI(r){return r.content?.length?r.content.map(e=>e.type==="text"?{type:"text",text:e.text}:e.type==="image"?{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.image}}:e.type==="audio"?{type:"text",text:e.transcription??`[MCP audio result: ${e.mimeType??"application/octet-stream"}]`}:e.type==="url"?{type:"text",text:e.cachedContent??[e.title,e.description,e.url].filter(Boolean).join(`
|
|
1253
|
+
`)),e.addEvent(dn.GEN_AI_USER_MESSAGE,o)}function lA(r,e,t){if(uA(r,e),r.modelUsage?.tokens){let n=r.modelUsage.tokens.thoughtsTokens?{[Oe.LLM_USAGE_THOUGHTS_TOKENS]:r.modelUsage.tokens.thoughtsTokens}:{};e.addEvent(dn.GEN_AI_USAGE,{[Oe.LLM_USAGE_INPUT_TOKENS]:r.modelUsage.tokens.promptTokens,[Oe.LLM_USAGE_OUTPUT_TOKENS]:r.modelUsage.tokens.completionTokens??0,[Oe.LLM_USAGE_TOTAL_TOKENS]:r.modelUsage.tokens.totalTokens,...n})}if(r.results)for(let n=0;n<r.results.length;n++){let o=r.results[n];if(!o||!o.content&&!o.thought&&!o.functionCalls?.length&&!o.finishReason)continue;let i=o.functionCalls?.map(a=>({id:a.id,type:a.type,function:a.function.name,arguments:a.function.params})),s={};i&&i.length>0?(t||(s.content=o.content),s.tool_calls=i):t||(s.content=o.content??""),e.addEvent(dn.GEN_AI_CHOICE,{finish_reason:o.finishReason,index:n,message:JSON.stringify(s,null,2)})}}function Jk(r){let e=new Set;for(let t of r){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 Yk=new Set(["us","eu"]),xi=r=>r==="global"?"aiplatform.googleapis.com":Yk.has(r)?`aiplatform.${r}.rep.googleapis.com`:`${r}-aiplatform.googleapis.com`;var yi=(A=>(A.Claude5Sonnet="claude-sonnet-5",A.Claude48Opus="claude-opus-4-8",A.Claude47Opus="claude-opus-4-7",A.Claude46Opus="claude-opus-4-6",A.Claude46Sonnet="claude-sonnet-4-6",A.Claude45Opus="claude-opus-4-5-20251101",A.Claude41Opus="claude-opus-4-1-20250805",A.Claude4Opus="claude-opus-4-20250514",A.Claude4Sonnet="claude-sonnet-4-20250514",A.Claude45Sonnet="claude-sonnet-4-5-20250929",A.Claude45Haiku="claude-haiku-4-5",A.Claude37Sonnet="claude-3-7-sonnet-latest",A.Claude35Sonnet="claude-3-5-sonnet-latest",A.Claude35Haiku="claude-3-5-haiku-latest",A.Claude3Opus="claude-3-opus-latest",A.Claude3Sonnet="claude-3-sonnet-20240229",A.Claude3Haiku="claude-3-haiku-20240307",A.Claude21="claude-2.1",A.ClaudeInstant12="claude-instant-1.2",A))(yi||{}),sc=(f=>(f.Claude5Sonnet="claude-sonnet-5",f.Claude48Opus="claude-opus-4-8",f.Claude47Opus="claude-opus-4-7",f.Claude46Opus="claude-opus-4-6",f.Claude46Sonnet="claude-sonnet-4-6",f.Claude45Opus="claude-opus-4-5@20251101",f.Claude41Opus="claude-opus-4-1@20250805",f.Claude4Opus="claude-opus-4@20250514",f.Claude45Sonnet="claude-sonnet-4-5@20250929",f.Claude4Sonnet="claude-sonnet-4@20250514",f.Claude37Sonnet="claude-3-7-sonnet@20250219",f.Claude35SonnetV2="claude-3-5-sonnet-v2@20241022",f.Claude45Haiku="claude-haiku-4-5@20251001",f.Claude35Haiku="claude-3-5-haiku@20241022",f.Claude35Sonnet="claude-3-5-sonnet@20240620",f.Claude3Opus="claude-3-opus@20240229",f.Claude3Haiku="claude-3-haiku@20240307",f))(sc||{});var io=[{name:"claude-sonnet-5",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:10,cacheReadTokenCostPer1M:.2,cacheWriteTokenCostPer1M:2.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-5",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:10,cacheReadTokenCostPer1M:.2,cacheWriteTokenCostPer1M:2.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-8",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:10,fastCompletionTokenCostPer1M:50,fastCacheReadTokenCostPer1M:1,fastCacheWriteTokenCostPer1M:12.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-8",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-7",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:30,fastCompletionTokenCostPer1M:150,fastCacheReadTokenCostPer1M:3,fastCacheWriteTokenCostPer1M:37.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-7",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,fastPromptTokenCostPer1M:30,fastCompletionTokenCostPer1M:150,fastCacheReadTokenCostPer1M:3,fastCacheWriteTokenCostPer1M:37.5,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-6",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:128e3,contextWindow:1e6,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-6",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5-20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-5@20251101",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:25,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5-20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-5@20250929",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-haiku-4-5",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-haiku-4-5@20251001",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:2e5,supported:{thinkingBudget:!0,showThoughts:!0}},{name:"claude-opus-4-1-20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-1@20250805",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4-20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-opus-4@20250514",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:32e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4-20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-sonnet-4@20250514",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-7-sonnet@20250219",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:64e3,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-sonnet-latest",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet@20240620",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{structuredOutputs:!0}},{name:"claude-3-5-sonnet-v2@20241022",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:8192,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"claude-3-5-haiku-latest",currency:"usd",promptTokenCostPer1M:.8,completionTokenCostPer1M:4,cacheReadTokenCostPer1M:.08,cacheWriteTokenCostPer1M:1,maxTokens:8192},{name:"claude-3-5-haiku@20241022",currency:"usd",promptTokenCostPer1M:1,completionTokenCostPer1M:5,cacheReadTokenCostPer1M:.1,cacheWriteTokenCostPer1M:1.25,maxTokens:8192},{name:"claude-3-opus-latest",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-opus@20240229",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:75,cacheReadTokenCostPer1M:1.5,cacheWriteTokenCostPer1M:18.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-sonnet-20240229",currency:"usd",promptTokenCostPer1M:3,completionTokenCostPer1M:15,cacheReadTokenCostPer1M:.3,cacheWriteTokenCostPer1M:3.75,maxTokens:4096,supported:{structuredOutputs:!0}},{name:"claude-3-haiku-20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,cacheReadTokenCostPer1M:.03,cacheWriteTokenCostPer1M:.3,maxTokens:4096},{name:"claude-3-haiku@20240307",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:1.25,cacheReadTokenCostPer1M:.03,cacheWriteTokenCostPer1M:.3,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 Qk=["structured-outputs-2025-11-13","web-search-2025-03-05"],Xk="fast-mode-2026-02-01",Zk="task-budgets-2026-03-13",fA=(r=[])=>[...new Set([...Qk,...r])].join(", ");function hA(r){switch(r){case"overloaded_error":return 529;case"api_error":return 500;case"rate_limit_error":return 429;case"invalid_request_error":return 400;case"permission_error":return 403;case"not_found_error":return 404;case"request_too_large":return 413;default:return}}function pA(r){if(r.type==="authentication_error")return new It("",void 0,r);let e=hA(r.type);return e!==void 0?new Qe(e,r.type,"",void 0,r):new Ke(r.message)}var eI=r=>r.includes("claude-opus-4-7")||r.includes("claude-opus-4-8"),tI=r=>r.includes("claude-opus-4-8"),nI=r=>r.includes("claude-sonnet-5"),mA=r=>r.includes("claude-opus-4-6")||eI(r)||nI(r),Vn=r=>{if(!r||typeof r!="object")return r;let e={...r},t=Array.isArray(e.type)?e.type:[e.type],n=Array.isArray(e.type)&&e.type.length===2&&e.type.includes("null");if(Array.isArray(e.type)&&e.type.length>1&&!n)return e.type="object",e.additionalProperties=!0,delete e.properties,delete e.required,delete e.items,e;if(e.type==="object"||n&&t.includes("object")){if(!e.properties||Object.keys(e.properties).length===0)return e;e.additionalProperties===void 0&&(e.additionalProperties=!1)}return delete e.optional,(t.includes("number")||t.includes("integer"))&&(delete e.minimum,delete e.maximum,delete e.exclusiveMinimum,delete e.exclusiveMaximum,delete e.multipleOf),t.includes("string")&&(delete e.minLength,delete e.maxLength,delete e.pattern,delete e.format),t.includes("array")&&(delete e.minItems,delete e.maxItems,delete e.uniqueItems),e.properties&&typeof e.properties=="object"&&(e.properties=Object.fromEntries(Object.entries(e.properties).map(([i,s])=>[i,Vn(s)]))),e.items&&(e.items=Vn(e.items)),Array.isArray(e.anyOf)&&(e.anyOf=e.anyOf.map(i=>Vn(i))),Array.isArray(e.allOf)&&(e.allOf=e.allOf.map(i=>Vn(i))),Array.isArray(e.oneOf)&&(e.oneOf=e.oneOf.map(i=>Vn(i))),e},xA=()=>structuredClone({model:"claude-3-7-sonnet-latest",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Ge()}),rI=()=>structuredClone({model:"claude-3-7-sonnet@20250219",maxTokens:4e4,thinkingTokenBudgetLevels:{minimal:1024,low:5e3,medium:1e4,high:2e4,highest:32e3},effortLevelMapping:{minimal:"low",low:"low",medium:"medium",high:"high",highest:"max"},...Ge()}),kd=class{constructor(e,t){this.config=e;this.isVertex=t}tokensUsed;currentPromptConfig;usedStructuredOutput=!1;getTokenUsage(){return this.tokensUsed}getModelConfig(){let{config:e}=this;return{maxTokens:e.maxTokens??4096,temperature:e.temperature,topP:e.topP,topK:e.topK,stream:e.stream,stopSequences:e.stopSequences,endSequences:e.endSequences,presencePenalty:e.presencePenalty,frequencyPenalty:e.frequencyPenalty,n:e.n,effort:e.effort,speed:e.speed,taskBudget:e.taskBudget}}createChatReq=async(e,t)=>{this.currentPromptConfig=t;let n=e.model,o=n,i=e.modelConfig?.stream??this.config.stream,s;this.isVertex?s={name:i?`/models/${n}:streamRawPredict?alt=sse`:`/models/${n}:rawPredict`}:s={name:"/messages"};let a;if(e.functionCall&&e.functions&&e.functions.length>0)if(typeof e.functionCall=="string")switch(e.functionCall){case"auto":a={tool_choice:{type:"auto"}};break;case"required":a={tool_choice:{type:"any"}};break;case"none":throw new Error("functionCall none not supported")}else if("function"in e.functionCall)a={tool_choice:{type:"tool",name:e.functionCall.function.name}};else throw new Error("Invalid function call type, must be string or object");let c=e.chatPrompt.some(C=>"cache"in C&&C.cache)||e.functions?.some(C=>C.cache),l=!this.isVertex&&tI(o),u=e.chatPrompt.findIndex(C=>C.role!=="system"),d=u===-1?e.chatPrompt.length:u,p=(l?e.chatPrompt.slice(0,d):e.chatPrompt).filter(C=>C.role==="system"),m=p.map((C,T)=>({type:"text",text:C.content,...C.cache||c&&T===p.length-1?{cache_control:{type:"ephemeral"}}:{}})),g=l?e.chatPrompt.slice(d):e.chatPrompt.filter(C=>C.role!=="system"),h=e.functions?.map((C,T,E)=>{let D={type:"object",properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]},j=C.parameters?Vn(C.parameters):void 0;return j===void 0||j&&typeof j=="object"&&Object.keys(j).length===0?j={...D}:j&&typeof j=="object"&&j.type==="object"&&(!("properties"in j)||!j.properties||Object.keys(j.properties).length===0)&&(j={...j,properties:{dummy:{type:"string",description:"An optional dummy parameter, do not use"}},required:[]}),{name:C.name,description:C.description,input_schema:j,...C.cache||c&&T===E.length-1?{cache_control:{type:"ephemeral"}}:{}}}),f=(this.config.tools??[]).map(C=>C&&typeof C=="object"&&"type"in C?C:{name:C.name,description:C.description,input_schema:C.input_schema?Vn(C.input_schema):void 0,...C.cache_control?{cache_control:C.cache_control}:{}}),y=[...h??[],...f];y.length===0&&(y=void 0);let A=e.modelConfig?.maxTokens??this.config.maxTokens,b=e.modelConfig?.stopSequences??this.config.stopSequences,w=e.modelConfig?.temperature,v=e.modelConfig?.topP,F=e.modelConfig?.topK??this.config.topK,k=e.modelConfig?.n??this.config.n,O=e.modelConfig?.effort??this.config.effort,$=e.modelConfig?.speed??this.config.speed,N=e.modelConfig?.taskBudget??this.config.taskBudget;if(k&&k>1)throw new Error("Anthropic does not support sampling (n > 1)");let V=C=>C.includes("claude-opus-4-5"),I=mA(o),_,S;if(t?.thinkingTokenBudget){let C=this.config.thinkingTokenBudgetLevels,T=this.config.effortLevelMapping;if(t.thinkingTokenBudget==="none")_=void 0,S=void 0;else{let E=t.thinkingTokenBudget;if(mA(o))_={type:"adaptive",display:t?.showThoughts===!1?"omitted":"summarized"},S={effort:T?.[E]??"medium"};else if(V(o)){_={type:"enabled",budget_tokens:C?.[E]??1e4};let j=T?.[E]??"medium";j==="max"&&(j="high"),S={effort:j}}else _={type:"enabled",budget_tokens:C?.[E]??1e4}}}if(O){let C=V(o)&&(O==="max"||O==="xhigh")?"high":O;S={...S,effort:C}}if(N){if(N.total<2e4)throw new Error("Anthropic taskBudget.total must be at least 20000 tokens");if(this.isVertex)throw new Error("Anthropic task budgets are only supported on the first-party Anthropic API");S={...S,task_budget:N}}let H=[];if($==="fast"){if(this.isVertex)throw new Error("Anthropic fast mode is only supported on the first-party Anthropic API");H.push(Xk)}N&&H.push(Zk),!this.isVertex&&H.length>0&&(s.headers={"anthropic-beta":fA(H)});let W=iI(g,!!_);if(W.some(C=>C.role==="assistant"&&Array.isArray(C.content)&&C.content.length>0&&C.content[0]?.type==="tool_use")&&(_=void 0,S)){let C={};O&&S.effort&&(C.effort=S.effort),S.task_budget&&(C.task_budget=S.task_budget),S=Object.keys(C).length>0?C:void 0}if(this.usedStructuredOutput=!1,e.responseFormat&&e.responseFormat.type==="json_schema"&&e.responseFormat.schema){let C=e.responseFormat.schema.schema||e.responseFormat.schema;S={...S,format:{type:"json_schema",schema:Vn(C)}},this.usedStructuredOutput=!0}let Y={...this.isVertex?{anthropic_version:"vertex-2023-10-16"}:{model:n},...A?{max_tokens:A}:{},...b&&b.length>0?{stop_sequences:b}:{},...w!==void 0&&!_&&!I?{temperature:w}:{},...v!==void 0&&!I&&(!_||v>=.95)?{top_p:v}:{},...F&&!_&&!I?{top_k:F}:{},...a,...y?{tools:y}:{},...i?{stream:!0}:{},...m.length>0?{system:m}:{},..._?{thinking:_}:{},...S?{output_config:S}:{},...$==="fast"?{speed:"fast"}:{},messages:W};return[s,Y]};createChatResp=e=>{if(e.type==="error")throw pA(e.error);if(e.stop_reason==="refusal"){let u=e.content.filter(m=>m.type==="text").map(m=>"text"in m?m.text:"").join(""),d=e.stop_details??void 0,p=d?.explanation??(u.length>0?u:"Anthropic refused to fulfill this request");throw new Ke(p,e.model,e.id,d?.category,d?.explanation)}let t=gA(e.stop_reason),n=this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1,o="",i=[],s=[],a=[];for(let u of e.content)switch(u.type){case"text":if(o+=u.text??"",Array.isArray(u.citations))for(let d of u.citations)d?.url&&a.push({url:String(d.url),title:typeof d.title=="string"?d.title:void 0,snippet:typeof d.cited_text=="string"?d.cited_text:void 0});break;case"thinking":if(n){let d=u.thinking??"",p=u.signature;s.push({data:d,encrypted:!1,...typeof p=="string"?{signature:p}:{}})}break;case"redacted_thinking":if(n){let d=u.data??"",p=u.signature;s.push({data:d,encrypted:!0,...typeof p=="string"?{signature:p}:{}})}break;case"tool_use":i.push({id:u.id,type:"function",function:{name:u.name,params:u.input}});break}let c={index:0,id:e.id,finishReason:t};o&&(c.content=o),s.length>0&&(c.thoughtBlocks=s,c.thought=s.map(u=>u.data).join("")),i.length>0&&(c.functionCalls=i),a.length>0&&(c.citations=a);let l=[c];return this.tokensUsed={promptTokens:e.usage.input_tokens,completionTokens:e.usage.output_tokens,totalTokens:e.usage.input_tokens+e.usage.output_tokens+(e.usage.cache_creation_input_tokens||0)+(e.usage.cache_read_input_tokens||0),cacheCreationTokens:e.usage.cache_creation_input_tokens,cacheReadTokens:e.usage.cache_read_input_tokens,speed:e.usage.speed},{results:l,remoteId:e.id}};classifyStreamErrorStatus=e=>e.type==="error"?hA(e.error.type):void 0;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:i}=e;throw pA(i)}let o=0;if(e.type==="message_start"){let{message:i}=e,s=[{index:o,content:"",id:i.id}];return n.remoteId=i.id,this.tokensUsed={promptTokens:i.usage?.input_tokens??0,completionTokens:i.usage?.output_tokens??0,totalTokens:(i.usage?.input_tokens??0)+(i.usage?.output_tokens??0)+(i.usage?.cache_creation_input_tokens??0)+(i.usage?.cache_read_input_tokens??0),cacheCreationTokens:i.usage?.cache_creation_input_tokens,cacheReadTokens:i.usage?.cache_read_input_tokens,speed:i.usage?.speed},{results:s,remoteId:i.id}}if(e.type==="content_block_start"){let{content_block:i}=e;if(i.type==="text"){let s=[];if(Array.isArray(i.citations))for(let a of i.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:o,content:i.text,...s.length?{citations:s}:{}}],remoteId:n.remoteId}}if(i.type==="thinking")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:i.thinking,thoughtBlocks:[{data:i.thinking,encrypted:!1}]}]}:{results:[{index:o,content:""}]};if(i.type==="tool_use"&&typeof i.id=="string"&&typeof e.index=="number"&&!n.indexIdMap[e.index]){n.indexIdMap[e.index]=i.id;let s=[{id:i.id,type:"function",function:{name:i.name,params:""}}];return{results:[{index:o,functionCalls:s}]}}if(i.type==="web_search_tool_result"||i.type==="server_tool_use")return{results:[{index:o,content:""}]}}if(e.type==="content_block_delta"){let{delta:i}=e;if(i.type==="citations_delta"){let s=i.citation;if(s&&typeof s.url=="string"&&s.url.length>0){let a=[{url:String(s.url),title:typeof s.title=="string"?s.title:void 0,snippet:typeof s.cited_text=="string"?s.cited_text:void 0}];return{results:[{index:o,content:"",citations:a}],remoteId:n.remoteId}}return{results:[{index:o,content:""}],remoteId:n.remoteId}}if(i.type==="text_delta"){let s=[];if(Array.isArray(i.citations))for(let a of i.citations)a?.url&&s.push({url:String(a.url),title:typeof a.title=="string"?a.title:void 0,snippet:typeof a.cited_text=="string"?a.cited_text:void 0});return{results:[{index:o,content:i.text,...s.length?{citations:s}:{}}]}}if(i.type==="thinking_delta")return this.currentPromptConfig?.thinkingTokenBudget!=="none"&&this.currentPromptConfig?.showThoughts!==!1?{results:[{index:o,thought:i.thinking,thoughtBlocks:[{data:i.thinking,encrypted:!1}]}]}:{results:[{index:o,content:""}]};if(i.type==="signature_delta")return{results:[{index:o,thoughtBlocks:[{data:"",encrypted:!1,signature:i.signature}]}]};if(i.type==="input_json_delta"){let s=n.indexIdMap[e.index];if(!s)return{results:[{index:o,content:""}]};let a=[{id:s,type:"function",function:{name:"",params:i.partial_json}}];return{results:[{index:o,functionCalls:a}]}}}if(e.type==="message_delta"){let{delta:i,usage:s}=e;if(this.tokensUsed={promptTokens:this.tokensUsed?.promptTokens??0,completionTokens:s.output_tokens,totalTokens:(this.tokensUsed?.promptTokens??0)+s.output_tokens+(this.tokensUsed?.cacheCreationTokens??0)+(this.tokensUsed?.cacheReadTokens??0),cacheCreationTokens:this.tokensUsed?.cacheCreationTokens,cacheReadTokens:this.tokensUsed?.cacheReadTokens,speed:s.speed??this.tokensUsed?.speed},i.stop_reason==="refusal"){let c=i.stop_details??void 0;throw new Ke(c?.explanation??"Anthropic refused to fulfill this request",void 0,n.remoteId,c?.category,c?.explanation)}return{results:[{index:o,content:"",finishReason:gA(i.stop_reason)}]}}return{results:[{index:o,content:""}]}};supportsImplicitCaching=()=>!0},Ai=class r extends Et{static create(e){return new r(e)}constructor({apiKey:e,projectId:t,region:n,config:o,options:i,models:s}){let a=t!==void 0&&n!==void 0,c,l;if(t!==void 0&&n!==void 0){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");c=`https://${xi(n)}/v1/projects/${t}/locations/${n}/publishers/anthropic/`,l=async()=>({Authorization:`Bearer ${await e()}`,"anthropic-beta":"web-search-2025-03-05"})}else{if(!e)throw new Error("Anthropic API key not set");c="https://api.anthropic.com/v1",l=async()=>({"anthropic-version":"2023-06-01","anthropic-beta":fA(),"x-api-key":typeof e=="function"?await e():e})}let u={...xA(),...o},d=new kd(u,a),p=g=>{let h=lt({model:g,modelInfo:io,models:s});return{functions:!0,streaming:!0,hasThinkingBudget:h?.supported?.thinkingBudget??!1,hasShowThoughts:h?.supported?.showThoughts??!1,structuredOutputs:h?.supported?.structuredOutputs??!1,functionCot:!0,media:{images:{supported:!0,formats:["image/jpeg","image/png","image/gif","image/webp"],maxSize:5*1024*1024,detailLevels:["high","low","auto"]},audio:{supported:!1,formats:[],maxDuration:0},files:{supported:!1,formats:[],maxSize:0,uploadMethod:"none"},urls:{supported:!1,webSearch:!1,contextFetching:!1}},caching:{supported:!0,types:["ephemeral"],cacheBreakpoints:!1},thinking:h?.supported?.thinkingBudget??!1,multiTurn:!0}},m=s?.map(g=>{let h=g,x=h?.config;if(!x)return g;let f={};x.maxTokens!==void 0&&(f.maxTokens=x.maxTokens),x.temperature!==void 0&&(f.temperature=x.temperature),x.topP!==void 0&&(f.topP=x.topP),x.topK!==void 0&&(f.topK=x.topK),x.presencePenalty!==void 0&&(f.presencePenalty=x.presencePenalty),x.frequencyPenalty!==void 0&&(f.frequencyPenalty=x.frequencyPenalty),x.stopSequences!==void 0&&(f.stopSequences=x.stopSequences),x.endSequences!==void 0&&(f.endSequences=x.endSequences),x.stream!==void 0&&(f.stream=x.stream),x.n!==void 0&&(f.n=x.n),x.effort!==void 0&&(f.effort=x.effort),x.speed!==void 0&&(f.speed=x.speed),x.taskBudget!==void 0&&(f.taskBudget=x.taskBudget);let y={...h};Object.keys(f).length>0&&(y.modelConfig={...h.modelConfig??{},...f});let A=x.thinking?.thinkingTokenBudget;if(typeof A=="number"){let b=u.thinkingTokenBudgetLevels,w=[["minimal",b?.minimal??1024],["low",b?.low??5e3],["medium",b?.medium??1e4],["high",b?.high??2e4],["highest",b?.highest??32e3]],v="minimal",F=Number.POSITIVE_INFINITY;for(let[k,O]of w){let $=Math.abs(A-O);$<F&&(F=$,v=k)}y.thinkingTokenBudget=v}return x.thinking?.includeThoughts!==void 0&&(y.showThoughts=!!x.thinking.includeThoughts),y});super(d,{name:"Anthropic",apiURL:c,headers:l,modelInfo:io,defaults:{model:u.model},options:i,supportFor:p,models:m??s})}};function oI(r){return r.content?.length?r.content.map(e=>e.type==="text"?{type:"text",text:e.text}:e.type==="image"?{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.image}}:e.type==="audio"?{type:"text",text:e.transcription??`[MCP audio result: ${e.mimeType??"application/octet-stream"}]`}:e.type==="url"?{type:"text",text:e.cachedContent??[e.title,e.description,e.url].filter(Boolean).join(`
|
|
1254
1254
|
`)}:{type:"text",text:e.extractedText??`[MCP file result: ${e.filename??"file"} (${e.mimeType})]`}):r.result}function iI(r,e){let t=r.map(o=>{switch(o.role){case"system":return{role:"system",content:o.cache?[{type:"text",text:o.content,cache_control:{type:"ephemeral"}}]:o.content};case"function":return{role:"user",content:[{type:"tool_result",content:oI(o),tool_use_id:o.functionId,...o.isError?{is_error:!0}:{},...o.cache?{cache_control:{type:"ephemeral"}}:{}}]};case"user":{if(typeof o.content=="string")return{role:"user",content:o.cache?[{type:"text",text:o.content,cache_control:{type:"ephemeral"}}]:o.content};let i=o.content.map(s=>{switch(s.type){case"text":return{type:"text",text:s.text,...s.cache?{cache_control:{type:"ephemeral"}}:{}};case"image":return{type:"image",source:{type:"base64",media_type:s.mimeType,data:s.image},...s.cache?{cache_control:{type:"ephemeral"}}:{}};default:throw new Error("Invalid content type")}});if(o.cache&&i.length>0){let s=i.length-1,a=i[s];a&&(a.type==="text"||a.type==="image")&&(i[s]={...a,cache_control:{type:"ephemeral"}})}return{role:"user",content:i}}case"assistant":{let i="",s=[],a=o.thoughtBlocks;if(Array.isArray(a)&&a.length>0)for(let c of a)c.encrypted?s.push(c.signature?{type:"redacted_thinking",data:c.data,signature:c.signature}:{type:"redacted_thinking",data:c.data}):s.push(c.signature?{type:"thinking",thinking:c.data,signature:c.signature}:{type:"thinking",thinking:c.data});if(typeof o.content=="string"&&(s.length>0?i=[...s,{type:"text",text:o.content}]:i=o.content),typeof o.functionCalls<"u"&&(i=o.functionCalls.map(c=>{let l={};if(typeof c.function.params=="string"){let u=c.function.params;if(u.trim().length===0)l={};else try{l=JSON.parse(u)}catch{throw new Error(`Failed to parse function params JSON: ${u}`)}}else typeof c.function.params=="object"&&(l=c.function.params);return{type:"tool_use",id:c.id,name:c.function.name,input:l,...o.cache?{cache_control:{type:"ephemeral"}}:{}}}),Array.isArray(i)&&s.length>0&&(i=[...s,...i])),o.cache){if(typeof i=="string")i=[{type:"text",text:i,cache_control:{type:"ephemeral"}}];else if(Array.isArray(i)&&i.length>0){let c=i.length-1,l=i[c];l&&l.type==="text"&&(i[c]={...l,cache_control:{type:"ephemeral"}})}}return{role:"assistant",content:i}}default:throw new Error("Invalid role")}}),n=sI(t);return aI(n)}function sI(r){let e=[];for(let[t,n]of r.entries()){if(n.role!=="assistant"){e.push(n);continue}if(t>0&&r.at(t-1)?.role==="assistant"){let o=e.pop();e.push({...o||{},...n})}else e.push(n)}return e}function aI(r){return r.map(e=>e.role==="assistant"&&typeof e.content=="string"?{...e,content:e.content.replace(/\s+$/,"")}:e)}function gA(r){if(r)switch(r){case"stop_sequence":return"stop";case"max_tokens":case"model_context_window_exceeded":return"length";case"tool_use":return"function_call";case"refusal":return"content_filter";case"end_turn":case"pause_turn":return"stop";default:return"stop"}}var Bt=(r,e,t="audio/mpeg")=>{switch(r){case"wav":return"audio/wav";case"mp3":return"audio/mpeg";case"flac":return"audio/flac";case"opus":return"audio/opus";case"aac":return"audio/aac";case"pcm":case"pcm16":case"raw":return e?`audio/pcm;rate=${e}`:"audio/pcm";case"mulaw":case"ulaw":return e?`audio/basic;rate=${e}`:"audio/basic";case"alaw":return e?`audio/alaw;rate=${e}`:"audio/alaw";case"ogg":return"audio/ogg";default:return t}},Ct=r=>{let e=r?.toLowerCase();if(e){if(e.includes("wav"))return"wav";if(e.includes("mpeg")||e.includes("mp3"))return"mp3";if(e.includes("flac"))return"flac";if(e.includes("opus"))return"opus";if(e.includes("aac"))return"aac";if(e.includes("ogg"))return"ogg";if(e.includes("mulaw"))return"mulaw";if(e.includes("ulaw")||e.includes("basic"))return"ulaw";if(e.includes("alaw"))return"alaw";if(e.includes("pcm16"))return"pcm16";if(e.includes("pcm"))return"pcm"}},cI=r=>{let e=globalThis;if(e.Buffer)return new Uint8Array(e.Buffer.from(r,"base64"));let t=atob(r),n=new Uint8Array(t.length);for(let o=0;o<t.length;o++)n[o]=t.charCodeAt(o);return n},lI=r=>{let e=globalThis;if(e.Buffer)return e.Buffer.from(r).toString("base64");let t="";for(let n of r)t+=String.fromCharCode(n);return btoa(t)},so=r=>{if(r.length===0)return"";if(r.length===1)return r[0]??"";let e=r.map(i=>cI(i)),t=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(t),o=0;for(let i of e)n.set(i,o),o+=i.length;return lI(n)};var uI=r=>{let e=globalThis,t=r.includes(",")?r.slice(r.indexOf(",")+1):r;if(e.Buffer)return new Uint8Array(e.Buffer.from(t,"base64"));let n=atob(t),o=new Uint8Array(n.length);for(let i=0;i<n.length;i++)o[i]=n.charCodeAt(i);return o},dI=r=>{let e=globalThis;if(e.Buffer)return e.Buffer.from(r).toString("base64");let t="";for(let n of r)t+=String.fromCharCode(n);return btoa(t)},pI=async r=>{try{return(r.headers.get("content-type")??"").includes("application/json")?await r.json():await r.text()}catch{return}},yA=async(r,e,t)=>{if(r.ok)return;let n=await pI(r);throw r.status===401||r.status===403?new It(e,t,n):new Qe(r.status,r.statusText,e,t,n)},AA=async(r,e,t,n)=>{try{return await r(e,t)}catch(o){throw new tt(o instanceof Error?o:new Error(String(o)),e,n,void 0)}},CA=(r,e="wav")=>{let t=r.format??Ct(r.mimeType)??e,n=r.mimeType??Bt(t,r.sampleRate);return new Blob([uI(r.data)],{type:n})},bA=(r,e="wav")=>{if(r.filename)return r.filename;let t=r.format??Ct(r.mimeType)??e;return`audio.${t==="pcm16"?"pcm":t}`},RA=r=>{if(typeof r=="string")return{text:r};let e=r,t=Array.isArray(e?.segments)?e.segments.map(o=>({id:o.id,text:String(o.text??""),start:typeof o.start=="number"?o.start:void 0,end:typeof o.end=="number"?o.end:void 0,speaker:o.speaker??o.speaker_id})):void 0,n=Array.isArray(e?.words)?e.words.map(o=>({id:o.id,text:String(o.text??o.word??""),start:typeof o.start=="number"?o.start:void 0,end:typeof o.end=="number"?o.end:void 0,speaker:o.speaker??o.speaker_id})):void 0;return{text:String(e?.text??""),language:typeof e?.language=="string"?e.language:void 0,duration:typeof e?.duration=="number"?e.duration:void 0,segments:t,words:n}},Ci=async({url:r,headers:e,audio:t,fields:n,fetch:o,abortSignal:i})=>{let s=new FormData;for(let[l,u]of Object.entries(n))u!==void 0&&s.append(l,String(u));s.append("file",CA(t),bA(t));let a=await AA(o??globalThis.fetch,r,{method:"POST",headers:e,body:s,signal:i},n);return await yA(a,r,n),(a.headers.get("content-type")??"").includes("text/plain")?{text:await a.text()}:RA(await a.json())},En=async({url:r,headers:e,body:t,format:n,transcript:o,fetch:i,abortSignal:s})=>{let a=await AA(i??globalThis.fetch,r,{method:"POST",headers:{"Content-Type":"application/json",...e},body:JSON.stringify(t),signal:s},t);await yA(a,r,t);let c=a.headers.get("content-type")??"";if(c.includes("application/json")){let d=await a.json(),p=d.audio_data??d.audioData??d.data??d.audio?.data??d.output?.audio?.data??d.candidates?.[0]?.content?.parts?.find(g=>g.inlineData?.data||g.inline_data?.data)?.inlineData?.data??d.candidates?.[0]?.content?.parts?.find(g=>g.inline_data?.data)?.inline_data?.data;if(typeof p!="string")throw new Error("Speech response JSON did not include audio data");let m=typeof d.mimeType=="string"?d.mimeType:typeof d.mime_type=="string"?d.mime_type:d.candidates?.[0]?.content?.parts?.find(g=>g.inlineData?.mimeType)?.inlineData?.mimeType??d.candidates?.[0]?.content?.parts?.find(g=>g.inline_data?.mime_type)?.inline_data?.mime_type??Bt(n);return{data:p,format:n??Ct(m),mimeType:m,transcript:o}}let l=new Uint8Array(await a.arrayBuffer()),u=c||Bt(n);return{data:dI(l),format:n??Ct(u),mimeType:u,transcript:o}};var ao=()=>({output:{enabled:!0,voice:"alloy",format:"wav",includeTranscript:!0}}),ac=()=>({input:{format:"pcm16",mimeType:"audio/pcm;rate=16000",sampleRate:16e3,channels:1},output:{enabled:!0,voice:"Kore",format:"pcm16",mimeType:"audio/pcm;rate=24000",sampleRate:24e3,channels:1,includeTranscript:!0},live:{turnTimeoutMs:3e4}}),bt=(r,e)=>{if(!(!r&&!e))return{input:r?.input||e?.input?{...r?.input,...e?.input}:void 0,output:r?.output||e?.output?{...r?.output,...e?.output}:void 0,live:r?.live||e?.live?{...r?.live,...e?.live}:void 0}},Xt=r=>r?.output?.enabled===!0;var mI=/^gpt-5\.6($|-)/;function pn(r){return mI.test(typeof r=="string"?r:"")}var wA={mode:"explicit"},vA=(r,e,t)=>!t||!pn(r.model)?!1:e?.contextCache!==void 0||r.chatPrompt.some(n=>"cache"in n&&n.cache)||(r.functions?.some(n=>n.cache)??!1),SA=(r,e)=>r?.promptCacheKey??e?.promptCacheKey??r?.sessionId??e?.sessionId,gI=r=>{let e=new Set;for(let t=0;t<r.length;t++){let n=r[t];(t<r.length-1||n&&"cache"in n&&n.cache)&&e.add(t)}return e},fI=r=>{let e=r.content;if(typeof e=="string")return e.length===0?r:{...r,content:[{type:"text",text:e,prompt_cache_breakpoint:wA}]};if(Array.isArray(e)&&e.length>0){let t=e,n=t[t.length-1];return{...r,content:[...t.slice(0,-1),{...n,prompt_cache_breakpoint:wA}]}}return r},kA=(r,e)=>{let t=gI(e),n=0;return{messages:r.map((i,s)=>{if(!t.has(s))return i;let a=fI(i);return a!==i&&n++,a}),markerCount:n}};var Cr=(Z=>(Z.GPT4="gpt-4",Z.GPT41="gpt-4.1",Z.GPT41Mini="gpt-4.1-mini",Z.GPT41Nano="gpt-4.1-nano",Z.GPT4O="gpt-4o",Z.GPT4OMini="gpt-4o-mini",Z.GPTAudio="gpt-audio",Z.GPTAudioMini="gpt-audio-mini",Z.GPTAudio15="gpt-audio-1.5",Z.GPTRealtime15="gpt-realtime-1.5",Z.GPTRealtime2="gpt-realtime-2",Z.GPTRealtimeWhisper="gpt-realtime-whisper",Z.GPTRealtimeTranslate="gpt-realtime-translate",Z.GPT4ChatGPT4O="chatgpt-4o-latest",Z.GPT4Turbo="gpt-4-turbo",Z.GPT35Turbo="gpt-3.5-turbo",Z.GPT35TurboInstruct="gpt-3.5-turbo-instruct",Z.GPT35TextDavinci002="text-davinci-002",Z.GPT3TextBabbage002="text-babbage-002",Z.GPT3TextAda001="text-ada-001",Z.GPT5="gpt-5",Z.GPT5Nano="gpt-5-nano",Z.GPT5Mini="gpt-5-mini",Z.GPT5Chat="gpt-5-chat",Z.GPT5ChatLatest="gpt-5-chat-latest",Z.GPT5Codex="gpt-5-codex",Z.GPT5Pro="gpt-5-pro",Z.GPT51="gpt-5.1",Z.GPT51ChatLatest="gpt-5.1-chat-latest",Z.GPT51Codex="gpt-5.1-codex",Z.GPT51CodexMini="gpt-5.1-codex-mini",Z.GPT51CodexMax="gpt-5.1-codex-max",Z.GPT52="gpt-5.2",Z.GPT52ChatLatest="gpt-5.2-chat-latest",Z.GPT52Codex="gpt-5.2-codex",Z.GPT52Pro="gpt-5.2-pro",Z.GPT54="gpt-5.4",Z.GPT54Mini="gpt-5.4-mini",Z.GPT54Nano="gpt-5.4-nano",Z.GPT55="gpt-5.5",Z.GPT55Pro="gpt-5.5-pro",Z.GPT56="gpt-5.6",Z.GPT56Sol="gpt-5.6-sol",Z.GPT56Terra="gpt-5.6-terra",Z.GPT56Luna="gpt-5.6-luna",Z.O1="o1",Z.O1Mini="o1-mini",Z.O3="o3",Z.O3Mini="o3-mini",Z.O4Mini="o4-mini",Z))(Cr||{}),Hn=(n=>(n.TextEmbeddingAda002="text-embedding-ada-002",n.TextEmbedding3Small="text-embedding-3-small",n.TextEmbedding3Large="text-embedding-3-large",n))(Hn||{});var IA=()=>structuredClone({...Ge(),model:"gpt-audio-mini",embedModel:"text-embedding-3-small",audio:ao(),stream:!1}),Id=r=>r==="gpt-audio"||r==="gpt-audio-mini"||r.startsWith("gpt-audio-"),TA=(r,e)=>{let t=bt(r,e);return Xt(t)?bt(ao(),t):t},hI=r=>{let e=r.format??Ct(r.mimeType);if(e==="wav"||e==="mp3")return e;throw new Error(`OpenAI audio chat input supports only wav and mp3 audio, received ${e??r.mimeType??"unknown format"}`)},xI=r=>{let e=r??"wav";switch(e){case"wav":return"wav";case"mp3":return"mp3";case"flac":return"flac";case"opus":return"opus";case"aac":return"aac";case"pcm16":return"pcm16";case"pcm":return"pcm16";case"ogg":throw new Error("OpenAI audio chat output does not support ogg format");case"raw":case"mulaw":case"ulaw":case"alaw":throw new Error(`OpenAI audio chat output does not support ${e} format`)}},Td=(r,e)=>{let t=r.format??Ct(r.mimeType);return e?.allowPcm16&&(t==="pcm16"||t==="pcm")?{type:"input_audio",input_audio:{data:r.data,format:"pcm16",mimeType:r.mimeType,sampleRate:r.sampleRate,channels:r.channels}}:{type:"input_audio",input_audio:{data:r.data,format:hI(r),mimeType:r.mimeType,sampleRate:r.sampleRate,channels:r.channels}}},Pd=(r,e,t)=>{let n=TA(t,e.modelConfig?.audio);if(!Xt(n))return r;if(e.responseFormat||r.response_format)throw new Error("OpenAI audio chat models do not support structured response formats with audio output");let o=n?.output,i=xI(o?.format);return{...r,modalities:["text","audio"],audio:{voice:o?.voice??"alloy",format:i}}},Md=r=>{if(r?.data)return{id:r.id,data:r.data,transcript:r.transcript,expiresAt:r.expires_at}},Ed=r=>{if(!r)return;let e=r.data??r.delta;if(e)return{id:r.id,data:e,transcript:r.transcript,expiresAt:r.expires_at,isDelta:!0}};var PA={minimal:"low",low:"low",medium:"medium",high:"high",highest:"xhigh"},yI={...PA,highest:"max"},MA={minimal:"minimal",low:"medium",medium:"high",high:"high",highest:"xhigh"};function EA(r){return pn(r)?"none":void 0}function OA(r,e){return e==="none"?EA(r):pn(r)?PA[e]:MA[e]}function FA(r,e){return e==="none"?EA(r):pn(r)?yI[e]:MA[e]}var co=(K=>(K.GPT4="gpt-4",K.GPT41="gpt-4.1",K.GPT41Mini="gpt-4.1-mini",K.GPT41Nano="gpt-4.1-nano",K.GPT4O="gpt-4o",K.GPT4OMini="gpt-4o-mini",K.GPT4ChatGPT4O="chatgpt-4o-latest",K.GPT4Turbo="gpt-4-turbo",K.GPT35Turbo="gpt-3.5-turbo",K.GPT35TurboInstruct="gpt-3.5-turbo-instruct",K.GPT35TextDavinci002="text-davinci-002",K.GPT3TextBabbage002="text-babbage-002",K.GPT3TextAda001="text-ada-001",K.GPT5="gpt-5",K.GPT5Nano="gpt-5-nano",K.GPT5Mini="gpt-5-mini",K.GPT5Chat="gpt-5-chat",K.GPT5ChatLatest="gpt-5-chat-latest",K.GPT5Codex="gpt-5-codex",K.GPT5Pro="gpt-5-pro",K.GPT51="gpt-5.1",K.GPT51ChatLatest="gpt-5.1-chat-latest",K.GPT51Codex="gpt-5.1-codex",K.GPT51CodexMini="gpt-5.1-codex-mini",K.GPT51CodexMax="gpt-5.1-codex-max",K.GPT52="gpt-5.2",K.GPT52ChatLatest="gpt-5.2-chat-latest",K.GPT52Codex="gpt-5.2-codex",K.GPT52Pro="gpt-5.2-pro",K.GPT54="gpt-5.4",K.GPT54Mini="gpt-5.4-mini",K.GPT54Nano="gpt-5.4-nano",K.GPT55="gpt-5.5",K.GPT55Pro="gpt-5.5-pro",K.GPT56="gpt-5.6",K.GPT56Sol="gpt-5.6-sol",K.GPT56Terra="gpt-5.6-terra",K.GPT56Luna="gpt-5.6-luna",K.O1Pro="o1-pro",K.O1="o1",K.O1Mini="o1-mini",K.O3Pro="o3-pro",K.O3="o3",K.O3Mini="o3-mini",K.O4Mini="o4-mini",K))(co||{});var br=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:10,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"gpt-audio",audio:{input:!0,output:!0}},{name:"gpt-audio-mini",audio:{input:!0,output:!0}},{name:"gpt-audio-1.5",audio:{input:!0,output:!0}},{name:"gpt-realtime-1.5",audio:{input:!0,output:!0}},{name:"gpt-realtime-2",audio:{input:!0,output:!0},supported:{thinkingBudget:!0}},{name:"gpt-realtime-whisper",audio:{input:!0,output:!1}},{name:"gpt-realtime-translate",audio:{input:!0,output:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.4",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.4-mini",currency:"usd",promptTokenCostPer1M:.75,completionTokenCostPer1M:4.5,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.4-nano",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:1.25,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0}},{name:"gpt-5.5",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:30,cacheReadTokenCostPer1M:.5,longContextThreshold:272e3,longContextPromptTokenCostPer1M:10,longContextCompletionTokenCostPer1M:45,longContextCacheReadTokenCostPer1M:1,contextWindow:1e6,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0,thinkingBudget:!0}},{name:"gpt-5.5-pro",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:180,longContextThreshold:272e3,longContextPromptTokenCostPer1M:60,longContextCompletionTokenCostPer1M:270,contextWindow:1e6,isExpensive:!0,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0,thinkingBudget:!0}},{name:"gpt-5.6-sol",aliases:["gpt-5.6"],currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:30,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,longContextThreshold:272e3,longContextPromptTokenCostPer1M:10,longContextCompletionTokenCostPer1M:45,longContextCacheReadTokenCostPer1M:1,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0,thinkingBudget:!0}},{name:"gpt-5.6-terra",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:12,cacheReadTokenCostPer1M:.2,cacheWriteTokenCostPer1M:2.5,longContextThreshold:272e3,longContextPromptTokenCostPer1M:4,longContextCompletionTokenCostPer1M:18,longContextCacheReadTokenCostPer1M:.4,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0,thinkingBudget:!0}},{name:"gpt-5.6-luna",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:1.2,cacheReadTokenCostPer1M:.02,cacheWriteTokenCostPer1M:.25,longContextThreshold:272e3,longContextPromptTokenCostPer1M:.4,longContextCompletionTokenCostPer1M:1.8,longContextCacheReadTokenCostPer1M:.04,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{structuredOutputs:!0,thinkingBudget:!0}},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{structuredOutputs:!0}},{name:"o1-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"o3",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{structuredOutputs:!0}},{name:"text-embedding-ada-002",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.1},{name:"text-embedding-3-small",currency:"usd",promptTokenCostPer1M:.02,completionTokenCostPer1M:.02},{name:"text-embedding-3-large",currency:"usd",promptTokenCostPer1M:.13,completionTokenCostPer1M:.13}],bi=[{name:"gpt-4",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:60},{name:"gpt-4.1",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{structuredOutputs:!0}},{name:"gpt-4.1-mini",currency:"usd",promptTokenCostPer1M:.4,completionTokenCostPer1M:1.6,supported:{structuredOutputs:!0}},{name:"gpt-4.1-nano",currency:"usd",promptTokenCostPer1M:.1,completionTokenCostPer1M:.4,supported:{structuredOutputs:!0}},{name:"gpt-4o",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:10,supported:{structuredOutputs:!0}},{name:"gpt-4o-mini",currency:"usd",promptTokenCostPer1M:.15,completionTokenCostPer1M:.6,supported:{structuredOutputs:!0}},{name:"chatgpt-4o-latest",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:15,supported:{structuredOutputs:!0}},{name:"gpt-4-turbo",currency:"usd",promptTokenCostPer1M:10,completionTokenCostPer1M:30,supported:{structuredOutputs:!0}},{name:"gpt-3.5-turbo",currency:"usd",promptTokenCostPer1M:.5,completionTokenCostPer1M:1.5},{name:"gpt-5-nano",currency:"usd",promptTokenCostPer1M:.05,completionTokenCostPer1M:.4,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-pro",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:120,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-chat-latest",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-mini",currency:"usd",promptTokenCostPer1M:.25,completionTokenCostPer1M:2,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.1-codex-max",currency:"usd",promptTokenCostPer1M:1.25,completionTokenCostPer1M:10,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-chat-latest",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-codex",currency:"usd",promptTokenCostPer1M:1.75,completionTokenCostPer1M:14,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.2-pro",currency:"usd",promptTokenCostPer1M:21,completionTokenCostPer1M:168,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.4",currency:"usd",promptTokenCostPer1M:2.5,completionTokenCostPer1M:15,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.4-mini",currency:"usd",promptTokenCostPer1M:.75,completionTokenCostPer1M:4.5,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.4-nano",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:1.25,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.5",currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:30,cacheReadTokenCostPer1M:.5,longContextThreshold:272e3,longContextPromptTokenCostPer1M:10,longContextCompletionTokenCostPer1M:45,longContextCacheReadTokenCostPer1M:1,contextWindow:1e6,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.5-pro",currency:"usd",promptTokenCostPer1M:30,completionTokenCostPer1M:180,longContextThreshold:272e3,longContextPromptTokenCostPer1M:60,longContextCompletionTokenCostPer1M:270,contextWindow:1e6,isExpensive:!0,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.6-sol",aliases:["gpt-5.6"],currency:"usd",promptTokenCostPer1M:5,completionTokenCostPer1M:30,cacheReadTokenCostPer1M:.5,cacheWriteTokenCostPer1M:6.25,longContextThreshold:272e3,longContextPromptTokenCostPer1M:10,longContextCompletionTokenCostPer1M:45,longContextCacheReadTokenCostPer1M:1,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.6-terra",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:12,cacheReadTokenCostPer1M:.2,cacheWriteTokenCostPer1M:2.5,longContextThreshold:272e3,longContextPromptTokenCostPer1M:4,longContextCompletionTokenCostPer1M:18,longContextCacheReadTokenCostPer1M:.4,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"gpt-5.6-luna",currency:"usd",promptTokenCostPer1M:.2,completionTokenCostPer1M:1.2,cacheReadTokenCostPer1M:.02,cacheWriteTokenCostPer1M:.25,longContextThreshold:272e3,longContextPromptTokenCostPer1M:.4,longContextCompletionTokenCostPer1M:1.8,longContextCacheReadTokenCostPer1M:.04,contextWindow:105e4,maxTokens:128e3,notSupported:{temperature:!0,topP:!0},supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o1-pro",currency:"usd",promptTokenCostPer1M:150,completionTokenCostPer1M:600,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o1",currency:"usd",promptTokenCostPer1M:15,completionTokenCostPer1M:60,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-pro",currency:"usd",promptTokenCostPer1M:20,completionTokenCostPer1M:80,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0},isExpensive:!0},{name:"o3",currency:"usd",promptTokenCostPer1M:2,completionTokenCostPer1M:8,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o3-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}},{name:"o4-mini",currency:"usd",promptTokenCostPer1M:1.1,completionTokenCostPer1M:4.4,supported:{thinkingBudget:!0,showThoughts:!0,structuredOutputs:!0}}];var Od=()=>structuredClone({...Ge(),model:"gpt-realtime-2",embedModel:"text-embedding-3-small",audio:bt(ao(),{output:{enabled:!0,voice:"marin",format:"pcm16",includeTranscript:!0},input:{format:"pcm16",mimeType:"audio/pcm",sampleRate:24e3,channels:1},live:{turnTimeoutMs:3e4}}),stream:!1}),_A=()=>structuredClone({...Ge(),model:"gpt-realtime-whisper",embedModel:"text-embedding-3-small",audio:{input:{format:"pcm16",mimeType:"audio/pcm",sampleRate:24e3,channels:1},live:{turnTimeoutMs:3e4}},stream:!1}),lc=r=>r==="gpt-realtime-2"||r==="gpt-realtime"||r==="gpt-realtime-1.5"||r==="gpt-realtime-mini"||r.startsWith("gpt-realtime-"),Kn=r=>r==="gpt-realtime-whisper",uc=(r,e)=>bt(bt(Od().audio,r),e),Fd=(r,e,t)=>Kn(r)?!0:lc(r)&&Xt(uc(e,t)),vi=r=>({name:r.apiName??"openai-realtime-audio",localCall:async(e,t)=>t?TI(r):await NA(r)}),AI=r=>`wss://api.openai.com/v1/${Kn(r)?"realtime/transcription_sessions":"realtime"}?model=${encodeURIComponent(r)}`,CI=({model:r,wsURL:e})=>e?e(String(r)):AI(String(r)),Ri=r=>r.providerName??"OpenAI Realtime",cc=(r,e,t)=>{if(r.addEventListener){r.addEventListener(e,t);return}if(r.on){r.on(e,t);return}r[`on${e}`]=t},bI=r=>{let e=r?.data??r;return typeof e=="string"?JSON.parse(e):e instanceof Uint8Array?JSON.parse(new TextDecoder().decode(e)):e?.toString?JSON.parse(e.toString()):e},RI=r=>{let{apiKey:e,webSocket:t}=r,n=t??globalThis.WebSocket;if(!n)throw new Error(`${Ri(r)} requires a WebSocket constructor. In Node, pass the ws constructor through options.webSocket.`);return new n(CI(r),{headers:{Authorization:`Bearer ${e}`}})},wI=r=>r.messages.flatMap(e=>e.role!=="user"||!Array.isArray(e.content)?[]:e.content.filter(t=>t.type==="input_audio").map(t=>t.input_audio)),vI=r=>{if(!(!("content"in r)||!r.content))return typeof r.content=="string"?r.content:Array.isArray(r.content)?r.content.map(e=>"text"in e?e.text:void 0).filter(e=>!!e).join(`
|
|
1255
1255
|
`):"text"in r.content?r.content.text:void 0},SI=({model:r,request:e,audio:t})=>{let n=e.messages.filter(s=>s.role==="system").map(s=>s.content).join(`
|
|
1256
1256
|
`),o=t.output,i=t.input;return Kn(String(r))?{type:"transcription_session.update",session:{type:"transcription",audio:{input:{format:{type:"audio/pcm",rate:i?.sampleRate??24e3},turn_detection:null,transcription:{model:String(r)}}}}}:{type:"session.update",session:{type:"realtime",model:String(r),output_modalities:["audio"],...n?{instructions:n}:{},audio:{input:{format:{type:"audio/pcm",rate:i?.sampleRate??24e3}},output:{format:{type:"audio/pcm",rate:24e3},voice:typeof o?.voice=="object"?o.voice.id:o?.voice??"marin"}}}}},kI=(r,e)=>{let{model:t,request:n}=e,o=wI(n);for(let i of o){let s=i.format??Ct(i.mimeType);if(s!=="pcm16"&&s!=="pcm")throw new Error(`OpenAI Realtime audio input requires pcm16 audio, received ${s??i.mimeType??"unknown format"}`);r.send(JSON.stringify({type:"input_audio_buffer.append",audio:i.data}))}if(o.length>0&&r.send(JSON.stringify({type:"input_audio_buffer.commit"})),!Kn(String(t))){for(let i of n.messages){if(i.role!=="user")continue;let s=vI(i);s&&r.send(JSON.stringify({type:"conversation.item.create",item:{type:"message",role:"user",content:[{type:"input_text",text:s}]}}))}r.send(JSON.stringify({type:"response.create",response:{output_modalities:["audio"]}}))}},II=({model:r,collected:e,isDelta:t})=>{let n=e.transcriptChunks.join("")||e.inputTranscriptChunks.join(""),o=e.textChunks.join("")||n,i=so(e.audioChunks);return{id:e.responseId??"realtime",object:"chat.completion",created:Math.floor(Date.now()/1e3),model:String(r),choices:[{index:0,message:{role:"assistant",content:o||null,refusal:null,audio:i?{id:e.responseId??"realtime-audio",data:i,transcript:n||void 0}:null},finish_reason:"stop"}],usage:e.usage??{prompt_tokens:0,completion_tokens:0,total_tokens:0},system_fingerprint:"",...t?{__isDelta:!0}:{}}},wi=({model:r,collected:e,finishReason:t})=>({id:e.responseId??"realtime",object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:String(r),choices:[{index:0,delta:{role:"assistant",content:e.textChunks.join("")||e.inputTranscriptChunks.join("")||e.transcriptChunks.join("")||null,audio:e.audioChunks.length>0?{id:e.responseId??"realtime-audio",data:so(e.audioChunks),transcript:e.transcriptChunks.join("")||void 0}:null},finish_reason:t??null}],system_fingerprint:"",...e.usage?{usage:e.usage}:{}}),NA=async(r,e)=>{let t=RI(r),n=r.audio.live?.turnTimeoutMs??3e4,o={audioChunks:[],textChunks:[],transcriptChunks:[],inputTranscriptChunks:[]},i=s=>{r.debug&&console.log(`[${Ri(r).toLowerCase()}] ${s}`)};return await new Promise((s,a)=>{let c=!1,l=!1,u,d=()=>o.audioChunks.length>0||o.textChunks.length>0||o.transcriptChunks.length>0||o.inputTranscriptChunks.length>0,p=()=>{u&&(clearTimeout(u),u=void 0)},m=()=>{p(),u=setTimeout(()=>{i("finishing after output idle"),g()},1500)},g=()=>{if(!c){c=!0,clearTimeout(x),p();try{t.close()}catch{}s(II({model:r.model,collected:o}))}},h=f=>{if(!c){c=!0,clearTimeout(x),p();try{t.close()}catch{}a(f instanceof Error?f:new Error(String(f)))}},x=setTimeout(()=>{h(new Error(`${Ri(r)} turn timed out after ${n}ms`))},n);cc(t,"open",()=>{i("socket open; sending session update"),t.send(JSON.stringify(r.createSessionUpdate?r.createSessionUpdate(r):SI(r)))}),cc(t,"error",f=>{h(f?.error??f?.message??"OpenAI Realtime WebSocket error")}),cc(t,"close",f=>{if(i(`socket close${f?.code?` code=${f.code}`:""}${f?.reason?` reason=${f.reason}`:""}`),!c){if(d()){g();return}h(`${Ri(r)} WebSocket closed before completion${f?.code?` (code ${f.code})`:""}${f?.reason?`: ${f.reason}`:""}`)}}),cc(t,"message",f=>{try{let y=bI(f);if(i(`event ${y.type??"(unknown)"}`),y.type==="error"){h(y.error?.message??`${Ri(r)} error`);return}if(y.type==="session.created"||y.type==="session.updated"||y.type==="transcription_session.updated"||y.type==="transcription_session.created"){l||(l=!0,i("session ready; sending input"),kI(t,r));return}if(typeof y.response_id=="string"&&(o.responseId=y.response_id),typeof y.response?.id=="string"&&(o.responseId=y.response.id),(y.response?.usage||y.usage)&&(o.usage=y.response?.usage??y.usage),y.type==="response.output_audio.delta"||y.type==="response.audio.delta"){let A={audioChunks:[y.delta],textChunks:[],transcriptChunks:[],inputTranscriptChunks:[],responseId:o.responseId};o.audioChunks.push(y.delta),m(),e?.(wi({model:r.model,collected:A}));return}if(y.type==="response.output_text.delta"||y.type==="response.text.delta"){let A={audioChunks:[],textChunks:[y.delta],transcriptChunks:[],inputTranscriptChunks:[],responseId:o.responseId};o.textChunks.push(y.delta),m(),e?.(wi({model:r.model,collected:A}));return}if(y.type==="response.output_audio_transcript.delta"||y.type==="response.audio_transcript.delta"){let A={audioChunks:[],textChunks:[],transcriptChunks:[y.delta],inputTranscriptChunks:[],responseId:o.responseId};o.transcriptChunks.push(y.delta),m(),e?.(wi({model:r.model,collected:A}));return}if(y.type==="conversation.item.input_audio_transcription.delta"){let A={audioChunks:[],textChunks:[],transcriptChunks:[],inputTranscriptChunks:[y.delta],responseId:o.responseId};o.inputTranscriptChunks.push(y.delta),m(),e?.(wi({model:r.model,collected:A}));return}if(y.type==="response.output_audio_transcript.done"||y.type==="response.audio_transcript.done"){typeof y.transcript=="string"&&(o.transcriptChunks=[y.transcript]);return}if(y.type==="response.output_audio.done"||y.type==="response.audio.done"){m();return}if(y.type==="conversation.item.input_audio_transcription.completed"){typeof y.transcript=="string"&&(o.inputTranscriptChunks=[y.transcript]),Kn(String(r.model))&&g();return}if(y.type==="response.done"){g();return}if(y.type==="response.output_item.done"||y.type==="response.content_part.done"){m();return}y.type==="response.completed"&&g()}catch(y){h(y)}})})},TI=r=>new ReadableStream({start(e){NA(r,t=>e.enqueue(t)).then(t=>{e.enqueue(wi({model:r.model,collected:{audioChunks:[],textChunks:[],transcriptChunks:[],inputTranscriptChunks:[],usage:t.usage},finishReason:"stop"})),e.close()}).catch(t=>e.error(t))}});var Wn=r=>{if(!r)return;let e=r.prompt_tokens??r.input_tokens??0,t=r.completion_tokens??r.output_tokens??0,n=r.prompt_tokens_details?.cached_tokens??r.input_tokens_details?.cached_tokens??0,o=r.prompt_tokens_details?.cache_write_tokens??r.input_tokens_details?.cache_write_tokens??0,i=r.completion_tokens_details?.reasoning_tokens??r.output_tokens_details?.reasoning_tokens;return{promptTokens:Math.max(0,e-n-o),completionTokens:t,totalTokens:r.total_tokens??e+t,...i!==void 0?{reasoningTokens:i}:{},...n>0?{cacheReadTokens:n}:{},...o>0?{cacheCreationTokens:o}:{}}};var PI=r=>{let e=["o1","o1-mini","o3","o3-mini","o4-mini","o1-pro","o3-pro"];return e.includes(r)||e.includes(r)},lo=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ge()}),Nd=()=>structuredClone({...lo(),model:"gpt-5"}),Ld=()=>structuredClone({model:"gpt-5-mini",embedModel:"text-embedding-3-small",...Ot()}),$d=()=>({...lo(),model:"gpt-5-nano"}),_d=class{constructor(e,t,n,o,i,s,a,c,l=!1){this.config=e;this.apiKey=t;this.streamingUsage=n;this.options=o;this.chatReqUpdater=i;this.chatRespProcessor=s;this.chatStreamRespProcessor=a;this.realtime=c;this.promptCaching=l}tokensUsed;supportsImplicitCaching=e=>this.promptCaching&&pn(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,endSequences:e.endSequences,topP:e.topP,n:e.n,stream:e.stream}}createChatReq=(e,t)=>{let n=e.model,o=(this.realtime?.resolveAudioConfig??uc)(this.config.audio,e.modelConfig?.audio),i=(this.realtime?.shouldUse??Fd)(n,this.config.audio,e.modelConfig?.audio);if(!e.chatPrompt||e.chatPrompt.length===0)throw new Error("Chat prompt is empty");let s={name:"/chat/completions"},a=e.functions?.map(y=>({type:"function",function:{name:y.name,description:y.description,parameters:y.parameters}})),c=!e.functionCall&&e.functions&&e.functions.length>0?"auto":e.functionCall,l=MI(e,i),u=vA(e,t,this.promptCaching),d,p=0;if(u){let y=kA(l,e.chatPrompt);l=y.messages,p=y.markerCount,d=SA(t,this.options),d||(t.logger??this.options?.logger)?.({name:"Notification",id:"openai-prompt-cache-key-missing",value:"OpenAI prompt caching is enabled but neither promptCacheKey nor sessionId is set. GPT-5.6+ needs a key that is stable per conversation for reliable cache matching."})}let m=e.modelConfig?.frequencyPenalty??this.config.frequencyPenalty,g=e.modelConfig?.stream??this.config.stream,h=this.config.store,x=PI(n),f={model:n,messages:l,...e.responseFormat?{response_format:e.responseFormat.type==="json_schema"?{type:"json_schema",json_schema:e.responseFormat.schema}:e.responseFormat}:this.config?.responseFormat?{response_format:{type:this.config.responseFormat}}:{},...a?{tools:a}:{},...c?{tool_choice:c}:{},...x?{}:{...(e.modelConfig?.maxTokens??this.config.maxTokens)!==void 0?{max_completion_tokens:e.modelConfig?.maxTokens??this.config.maxTokens}:{},...e.modelConfig?.temperature!==void 0?{temperature:e.modelConfig.temperature}:{},...e.modelConfig?.topP!==void 0?{top_p:e.modelConfig.topP}:{},...(e.modelConfig?.n??this.config.n)!==void 0?{n:e.modelConfig?.n??this.config.n}:{},...(e.modelConfig?.presencePenalty??this.config.presencePenalty)!==void 0?{presence_penalty:e.modelConfig?.presencePenalty??this.config.presencePenalty}:{},...m!==void 0?{frequency_penalty:m}:{}},...(e.modelConfig?.stopSequences??this.config.stop)&&(e.modelConfig?.stopSequences??this.config.stop).length>0?{stop:e.modelConfig?.stopSequences??this.config.stop}:{},...this.config.logitBias!==void 0?{logit_bias:this.config.logitBias}:{},...g&&this.streamingUsage?{stream:!0,stream_options:{include_usage:!0}}:{},...p>0?{prompt_cache_options:{mode:"explicit"}}:{},...d?{prompt_cache_key:d}:{},...h?{store:h}:{},...this.config.serviceTier?{service_tier:this.config.serviceTier}:{},...this.config.user?{user:this.config.user}:{}};if(i){if(e.responseFormat||f.response_format)throw new Error(`${this.realtime?.apiName??"OpenAI Realtime"} models do not support structured response formats with audio output or transcription`);let y=(this.realtime?.createApi??vi)({model:n,request:f,apiKey:this.apiKey,audio:o,webSocket:t.webSocket??this.options?.webSocket,debug:t.debug??this.options?.debug});s.name=y.name,s.localCall=y.localCall}else f=Pd(f,e,this.config.audio);return this.config.reasoningEffort&&(f.reasoning_effort=this.config.reasoningEffort),this.config.webSearchOptions&&(f.web_search_options={...this.config.webSearchOptions.searchContextSize&&{search_context_size:this.config.webSearchOptions.searchContextSize},...this.config.webSearchOptions.userLocation&&{user_location:{approximate:{type:"approximate",...this.config.webSearchOptions.userLocation.approximate.city&&{city:this.config.webSearchOptions.userLocation.approximate.city},...this.config.webSearchOptions.userLocation.approximate.country&&{country:this.config.webSearchOptions.userLocation.approximate.country},...this.config.webSearchOptions.userLocation.approximate.region&&{region:this.config.webSearchOptions.userLocation.approximate.region},...this.config.webSearchOptions.userLocation.approximate.timezone&&{timezone:this.config.webSearchOptions.userLocation.approximate.timezone}}}}}),t?.thinkingTokenBudget&&(f.reasoning_effort=OA(n,t.thinkingTokenBudget)),this.chatReqUpdater&&(f=this.chatReqUpdater(f,t)),[s,f]};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:i}=e;if(i)throw i;this.tokensUsed=Wn(n);let a={results:o.map(c=>{if(c.message.refusal)throw new Ke(c.message.refusal,e.model,e.id);let l=LA(c.finish_reason),u=c.message.tool_calls?.map(({id:p,function:{arguments:m,name:g}})=>({id:p,type:"function",function:{name:g,params:m}})),d=Md(c.message.audio);return{index:c.index,id:`${c.index}`,content:c.message.content??d?.transcript??void 0,audio:d,thought:c.message.reasoning_content,citations:c.message.annotations?.filter(p=>p?.type==="url_citation"&&p.url_citation).map(p=>({url:p.url_citation?.url,title:p.url_citation?.title,description:p.url_citation?.description})),functionCalls:u,finishReason:l}}),remoteId:t};return this.chatRespProcessor?this.chatRespProcessor(a):a}createChatStreamResp=(e,t)=>{let{id:n,usage:o,choices:i}=e;this.tokensUsed=Wn(o);let s=t;s.indexIdMap||(s.indexIdMap={});let c={results:i.map(({index:l,delta:{content:u,role:d,refusal:p,audio:m,tool_calls:g,reasoning_content:h,annotations:x},finish_reason:f})=>{if(p)throw new Ke(p,void 0,n);let y=LA(f),A=g?.map(({id:w,index:v,function:{name:F,arguments:k}})=>{typeof w=="string"&&typeof v=="number"&&!s.indexIdMap[v]&&(s.indexIdMap[v]=w);let O=s.indexIdMap[v];return O?{id:O,type:"function",function:{name:F,params:k}}:null}).filter(w=>w!==null),b=Ed(m);return{index:l,content:u??b?.transcript??void 0,role:d,audio:b,thought:h,citations:x?.filter(w=>w?.type==="url_citation"&&w.url_citation).map(w=>({url:w.url_citation?.url,title:w.url_citation?.title,description:w.url_citation?.description})),functionCalls:A,finishReason:y,id:n}}),remoteId:n};return this.chatStreamRespProcessor?this.chatStreamRespProcessor(c,t):c};createEmbedResp(e){let{data:t,usage:n}=e;return this.tokensUsed=Wn(n),{embeddings:t.map(o=>o.embedding)}}},LA=r=>{switch(r){case"stop":return"stop";case"length":return"length";case"content_filter":return"error";case"tool_calls":return"function_call"}};function MI(r,e=!1){return r.chatPrompt.map(n=>{switch(n.role){case"system":return{role:"system",content:n.content};case"user":{let o=Array.isArray(n.content)?n.content.map(i=>{switch(i.type){case"text":return{type:"text",text:i.text};case"image":return{type:"image_url",image_url:{url:`data:${i.mimeType};base64,${i.image}`,details:i.details??"auto"}};case"audio":return Td(i,{allowPcm16:e});default:throw new Error("Invalid content type")}}):n.content;return{role:"user",...n.name?{name:n.name}:{},content:o}}case"assistant":{let o=n.functionCalls?.map(i=>({id:i.id,type:"function",function:{name:i.function.name,arguments:typeof i.function.params=="object"?JSON.stringify(i.function.params):i.function.params}}));if(o&&o.length>0)return{role:"assistant",...n.content?{content:n.content}:{},name:n.name,tool_calls:o};if(n.content===void 0&&!n.audio)throw new Error("Assistant content is required when no tool calls are provided");return{role:"assistant",...n.content!==void 0?{content:n.content}:{},...n.audio?{audio:{id:n.audio.id}}:{},...n.name?{name:n.name}:{}}}case"function":return{role:"tool",content:n.content?.map(o=>o.type==="text"?o.text:o.type==="image"?o.altText??`[MCP image result: ${o.mimeType}]`:o.type==="audio"?o.transcription??`[MCP audio result: ${o.mimeType??"application/octet-stream"}]`:o.type==="url"?o.cachedContent??[o.title,o.description,o.url].filter(Boolean).join(`
|
|
@@ -1321,5 +1321,5 @@ ${b}`:b;else if(y==="id")l=b;else if(y==="retry"){let w=Number.parseInt(b,10);Nu
|
|
|
1321
1321
|
`);o=c.pop()||"";for(let l of c)if(l.startsWith("event: "))i=l.slice(7).trim();else if(l.startsWith("data: ")){let u=l.slice(6);if(i==="endpoint"){let d=u.trim(),p;try{let m=JSON.parse(d);typeof m=="string"?p=m:m&&typeof m=="object"&&"uri"in m&&(p=m.uri)}catch{p=d}if(!p)throw new Error("Endpoint URI missing in SSE event data");/^https?:\/\//i.test(p)||(p=new URL(this.sseUrl).origin+(p.startsWith("/")?p:`/${p}`)),this.endpoint=p,this.endpointReady&&(this.endpointReady.resolve(),this.endpointReady=void 0)}else{let d=u.trim();try{let p=JSON.parse(d);if(p&&typeof p=="object"&&"id"in p){let m=p.id,g=this.pendingRequests.get(m);g?(g.resolve(p),this.pendingRequests.delete(m)):this.messageHandler&&this.messageHandler(p)}else this.messageHandler&&this.messageHandler(p)}catch{}}}else l.trim()===""&&(i=null)}}async connect(){let e=this.buildHeaders({Accept:"text/event-stream"});await this.openSSEWithFetch(e)}async startListening(){return this.streamDone||await this.connect(),{done:this.streamDone??Promise.resolve(),close:()=>this.close()}}async send(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),o=new Promise((a,c)=>{this.pendingRequests.set(e.id,{resolve:a,reject:c})}),i=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:t,body:n});if(i.status===401){let a=i.headers.get("WWW-Authenticate"),c=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:a,currentToken:null});if(!c)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`${c.token.tokenType??"Bearer"} ${c.token.accessToken}`,i=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!i.ok)throw this.pendingRequests.delete(e.id),new Error(`HTTP error ${i.status}: ${i.statusText}`);if(i.headers.get("Content-Type")?.includes("application/json")){let a=await i.json();return this.pendingRequests.delete(e.id),a}return o}async sendNotification(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=this.buildHeaders({"Content-Type":"application/json"}),n=JSON.stringify(e),o=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:t,body:n});if(o.status===401){let i=o.headers.get("WWW-Authenticate"),s=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:i,currentToken:null});if(!s)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`${s.token.tokenType??"Bearer"} ${s.token.accessToken}`,o=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:n})}if(!o.ok)throw new Error(`HTTP error ${o.status}: ${o.statusText}`);o.status!==202&&console.warn(`Unexpected status for notification: ${o.status}`)}async sendResponse(e){if(!this.endpoint)throw new Error("HTTPTransport endpoint is not initialized. Call connect() first.");let t=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e)});if(t.status===401){let n=t.headers.get("WWW-Authenticate"),o=await this.oauthHelper.ensureAccessToken({requestedUrl:this.sseUrl,wwwAuthenticate:n,currentToken:null});if(!o)throw new Error("HTTP 401: Unauthorized");this.customHeaders.Authorization=`${o.token.tokenType??"Bearer"} ${o.token.accessToken}`,t=await this.fetchEndpoint(this.endpoint,{method:"POST",headers:this.buildHeaders({"Content-Type":"application/json"}),body:JSON.stringify(e)})}if(!t.ok)throw new Error(`HTTP error ${t.status}: ${t.statusText}`)}close(){this.eventSource&&(this.eventSource.close(),this.eventSource=void 0),this.sseAbort&&(this.sseAbort.abort(),this.sseAbort=void 0)}};var Up=class{constructor(e,t={}){this.url=e;this.options=t}eraHint="legacy";socket;connectPromise;listeningDone;resolveListening;rejectListening;closing=!1;protocolVersion;handler;pending=new Map;async connect(){if(this.socket?.readyState!==1){if(this.connectPromise)return this.connectPromise;this.connectPromise=new Promise((e,t)=>{let o=(this.options.webSocketFactory??((i,s)=>s===void 0?new WebSocket(i):new WebSocket(i,s)))(this.url,this.options.protocols);this.socket=o,this.closing=!1,this.listeningDone=new Promise((i,s)=>{this.resolveListening=i,this.rejectListening=s}),o.addEventListener("open",()=>e(),{once:!0}),o.addEventListener("error",i=>t(i),{once:!0}),o.addEventListener("message",i=>{this.handlePayload(String(i.data))}),o.addEventListener("close",()=>{for(let i of this.pending.values())i.reject(new Error("MCP WebSocket closed"));this.pending.clear(),this.closing?this.resolveListening?.():this.rejectListening?.(new Error("MCP WebSocket closed")),this.socket=void 0})});try{await this.connectPromise}finally{this.connectPromise=void 0}}}async startListening(){return await this.connect(),{done:this.listeningDone??Promise.resolve(),close:()=>this.close()}}setProtocolVersion(e){this.protocolVersion=e}takeRequestMetadata(){return{retryCount:0}}setMessageHandler(e){this.handler=e}async send(e,t){return this.socket?.readyState!==1&&await this.connect(),new Promise((n,o)=>{let i=()=>{this.pending.delete(e.id),o(t?.signal?.reason??new Error("MCP request aborted"))};if(t?.signal?.aborted)return i();t?.signal?.addEventListener("abort",i,{once:!0}),this.pending.set(e.id,{resolve:s=>{t?.signal?.removeEventListener("abort",i),n(s)},reject:o}),this.socket.send(JSON.stringify(e))})}async sendBatch(e,t){if(this.protocolVersion!=="2025-03-26")throw new Error(`JSON-RPC batching is not allowed for MCP ${this.protocolVersion??"before negotiation"}`);if(e.length===0)throw new Error("MCP batch cannot be empty");if(new Set(e.map(o=>o.id)).size!==e.length)throw new Error("MCP batch request IDs must be unique");this.socket?.readyState!==1&&await this.connect();let n=e.map(o=>new Promise((i,s)=>{let a=()=>{this.pending.delete(o.id),s(t?.signal?.reason??new Error("MCP batch aborted"))};if(t?.signal?.aborted){a();return}t?.signal?.addEventListener("abort",a,{once:!0}),this.pending.set(o.id,{resolve:c=>{t?.signal?.removeEventListener("abort",a),i(c)},reject:s})}));try{this.socket.send(JSON.stringify(e))}catch(o){for(let i of e)this.pending.delete(i.id);throw o}return Promise.all(n)}async sendNotification(e){this.socket?.readyState!==1&&await this.connect(),this.socket.send(JSON.stringify(e))}async sendResponse(e){this.socket?.readyState!==1&&await this.connect(),this.socket.send(JSON.stringify(e))}close(){this.closing=!0,this.socket?.close(1e3,"MCP client closed"),this.socket||this.resolveListening?.()}async handlePayload(e){let t=JSON.parse(e),n=Array.isArray(t)?t:[t];if(Array.isArray(t)&&this.protocolVersion!=="2025-03-26")throw new Error(`JSON-RPC batching is not allowed for MCP ${this.protocolVersion??"before negotiation"}`);for(let o of n){if("id"in o&&!("method"in o)&&o.id!==null){let i=this.pending.get(o.id);if(i){this.pending.delete(o.id),i.resolve(o);continue}}await this.handler?.(o)}}};var kr=class extends Error{constructor(t,n,o){super(`UCP schema validation failed at ${t||"/"}: ${o}`);this.instancePath=t;this.schemaPath=n;this.name="AxUCPSchemaValidationError"}},ds=class{constructor(e={}){this.options=e}documents=new Map;async validate(e,t){let n=await this.loadDocument(t);await this.validateSchema(e,n,{documentUrl:t,document:n,instancePath:"",schemaPath:"#",depth:0})}clearCache(){this.documents.clear()}async loadDocument(e){let t=new URL(e).toString(),n=this.documents.get(t);if(n)return n;if(this.documents.size>=(this.options.maxDocuments??64))throw new Error("UCP schema document limit exceeded");let o=await nt(t,{headers:{Accept:"application/schema+json, application/json"},fetch:this.options.fetch,ssrfProtection:this.options.ssrfProtection,ssrfContext:"mcp-endpoint"});if(!o.ok)throw new Error(`UCP schema fetch failed: ${o.status} ${o.statusText}`);let i=await o.json();if(!i||typeof i!="object"||Array.isArray(i))throw new Error(`UCP schema ${t} is not a JSON object`);return this.documents.set(t,i),i}async resolveReference(e,t){let n=new URL(e,t.documentUrl),o=`${n.origin}${n.pathname}${n.search}`,i=o===t.documentUrl?t.document:await this.loadDocument(o),s=i,a=n.hash.slice(1);if(a){if(!a.startsWith("/"))throw new Error(`Unsupported UCP schema anchor #${a}`);for(let c of a.slice(1).split("/").map(l=>l.replaceAll("~1","/").replaceAll("~0","~"))){if(!s||typeof s!="object"||!(c in s))throw new Error(`Unresolved UCP schema reference ${e}`);s=s[c]}}if(typeof s!="boolean"&&(!s||typeof s!="object"))throw new Error(`UCP schema reference ${e} is not a schema`);return{schema:s,documentUrl:o,document:i,schemaPath:n.hash||"#"}}async validateSchema(e,t,n){if(n.depth>(this.options.maxDepth??128))throw new Error("UCP schema validation depth exceeded");if(t===!0)return;t===!1&&this.fail(n,"boolean schema rejects value");let o=(i,s)=>({...n,instancePath:`${n.instancePath}/${this.escape(i)}`,schemaPath:`${n.schemaPath}/${this.escape(s)}`,depth:n.depth+1});if(typeof t.$ref=="string"){let i=await this.resolveReference(t.$ref,n);await this.validateSchema(e,i.schema,{...n,documentUrl:i.documentUrl,document:i.document,schemaPath:i.schemaPath,depth:n.depth+1})}t.const!==void 0&&!this.deepEqual(e,t.const)&&this.fail(n,"value does not match const"),Array.isArray(t.enum)&&!t.enum.some(i=>this.deepEqual(e,i))&&this.fail(n,"value is not in enum"),t.type!==void 0&&!this.matchesType(e,t.type)&&this.fail(n,`expected type ${JSON.stringify(t.type)}`);for(let i of["allOf"])if(Array.isArray(t[i]))for(let s=0;s<t[i].length;s++)await this.validateSchema(e,t[i][s],o("",`${i}/${s}`));for(let i of["anyOf","oneOf"])if(Array.isArray(t[i])){let s=0;for(let a=0;a<t[i].length;a++)try{await this.validateSchema(e,t[i][a],o("",`${i}/${a}`)),s++}catch(c){if(!(c instanceof kr))throw c}(s===0||i==="oneOf"&&s!==1)&&this.fail(n,`${i} matched ${s} schemas`)}if(t.not!==void 0){let i=!0;try{await this.validateSchema(e,t.not,o("","not"))}catch(s){if(s instanceof kr)i=!1;else throw s}i&&this.fail(n,"value matches forbidden not schema")}if(t.if!==void 0){let i=!0;try{await this.validateSchema(e,t.if,o("","if"))}catch(a){if(a instanceof kr)i=!1;else throw a}let s=i?t.then:t.else;s!==void 0&&await this.validateSchema(e,s,o("",i?"then":"else"))}if(typeof e=="string"&&this.validateString(e,t,n),typeof e=="number"&&this.validateNumber(e,t,n),Array.isArray(e)){if(typeof t.minItems=="number"&&e.length<t.minItems&&this.fail(n,`requires at least ${t.minItems} items`),typeof t.maxItems=="number"&&e.length>t.maxItems&&this.fail(n,`allows at most ${t.maxItems} items`),t.uniqueItems===!0)for(let i=0;i<e.length;i++)e.slice(0,i).some(s=>this.deepEqual(s,e[i]))&&this.fail(n,"array items must be unique");if(t.items!==void 0)for(let i=0;i<e.length;i++)await this.validateSchema(e[i],t.items,o(String(i),"items"))}e&&typeof e=="object"&&!Array.isArray(e)&&await this.validateObject(e,t,n)}async validateObject(e,t,n){let o=Array.isArray(t.required)?t.required:[];for(let a of o)typeof a=="string"&&!Object.hasOwn(e,a)&&this.fail(n,`missing required property ${a}`);let i=t.properties&&typeof t.properties=="object"?t.properties:{},s=t.patternProperties&&typeof t.patternProperties=="object"?t.patternProperties:{};for(let[a,c]of Object.entries(e)){let l=Object.entries(s).filter(([u])=>new RegExp(u).test(a));i[a]!==void 0&&await this.validateSchema(c,i[a],{...n,instancePath:`${n.instancePath}/${this.escape(a)}`,schemaPath:`${n.schemaPath}/properties/${this.escape(a)}`,depth:n.depth+1});for(let[u,d]of l)await this.validateSchema(c,d,{...n,instancePath:`${n.instancePath}/${this.escape(a)}`,schemaPath:`${n.schemaPath}/patternProperties/${this.escape(u)}`,depth:n.depth+1});i[a]===void 0&&l.length===0&&t.additionalProperties===!1&&this.fail(n,`additional property ${a} is not allowed`),i[a]===void 0&&l.length===0&&t.additionalProperties&&typeof t.additionalProperties=="object"&&await this.validateSchema(c,t.additionalProperties,n)}}validateString(e,t,n){if(typeof t.minLength=="number"&&e.length<t.minLength&&this.fail(n,`string is shorter than ${t.minLength}`),typeof t.maxLength=="number"&&e.length>t.maxLength&&this.fail(n,`string is longer than ${t.maxLength}`),typeof t.pattern=="string"&&!new RegExp(t.pattern).test(e)&&this.fail(n,`string does not match ${t.pattern}`),t.format==="uri")try{new URL(e)}catch{this.fail(n,"string is not a URI")}t.format==="date-time"&&Number.isNaN(Date.parse(e))&&this.fail(n,"string is not an RFC 3339 date-time")}validateNumber(e,t,n){typeof t.minimum=="number"&&e<t.minimum&&this.fail(n,`number is below ${t.minimum}`),typeof t.maximum=="number"&&e>t.maximum&&this.fail(n,`number is above ${t.maximum}`),typeof t.exclusiveMinimum=="number"&&e<=t.exclusiveMinimum&&this.fail(n,`number must exceed ${t.exclusiveMinimum}`),typeof t.exclusiveMaximum=="number"&&e>=t.exclusiveMaximum&&this.fail(n,`number must be below ${t.exclusiveMaximum}`)}matchesType(e,t){return(Array.isArray(t)?t:[t]).some(o=>o==="null"?e===null:o==="array"?Array.isArray(e):o==="object"?e!==null&&typeof e=="object"&&!Array.isArray(e):o==="integer"?Number.isInteger(e):typeof e===o)}fail(e,t){throw new kr(e.instancePath,e.schemaPath,t)}escape(e){return e.replaceAll("~","~0").replaceAll("/","~1")}deepEqual(e,t){return JSON.stringify(e)===JSON.stringify(t)}};var Fe=class extends Error{constructor(t,n){super(n);this.code=t;this.name="AxUCPHTTPMessageSignatureError"}};function VC(r){let e="";for(let t of r)e+=String.fromCharCode(t);return btoa(e)}async function HC(r){let e=await Ze().subtle.digest("SHA-256",new TextEncoder().encode(r));return`sha-256=:${VC(new Uint8Array(e))}:`}async function Dp(r,e){let t=new Headers(r.headers);r.body!==void 0&&(t.has("Content-Type")||t.set("Content-Type","application/json"),t.set("Content-Digest",await HC(r.body)));let n=new URL(r.url),o=e.components??["@method","@authority","@path",...n.search?["@query"]:[],...t.has("ucp-agent")?["ucp-agent"]:[],...t.has("idempotency-key")?["idempotency-key"]:[],...r.body!==void 0?["content-digest","content-type"]:[]],i=e.created?.()??Math.floor(Date.now()/1e3),a=[`(${o.map(p=>`"${p}"`).join(" ")})`,`created=${i}`,`keyid="${e.keyId.replaceAll('"','\\"')}"`,...e.algorithm?[`alg="${e.algorithm}"`]:[],...e.nonce?[`nonce="${e.nonce()}"`]:[]].join(";"),c=p=>{if(p==="@method")return r.method.toUpperCase();if(p==="@authority")return n.host;if(p==="@path")return n.pathname;if(p==="@query")return n.search;let m=t.get(p);if(m===null)throw new Error(`UCP signature component is missing: ${p}`);return m},l=[...o.map(p=>`"${p}": ${c(p)}`),`"@signature-params": ${a}`].join(`
|
|
1322
1322
|
`),u=await e.sign(new TextEncoder().encode(l),{signatureInput:a}),d=e.label??"sig1";return{...Object.fromEntries(t.entries()),"Signature-Input":`${d}=${a}`,Signature:`${d}=:${VC(u instanceof Uint8Array?u:new Uint8Array(u))}:`}}function FP(r){try{let e=atob(r);return Uint8Array.from(e,t=>t.charCodeAt(0))}catch{throw new Fe("signature_invalid","UCP signature has invalid base64 encoding")}}function BC(r){let e=r.match(/(?:^|,)\s*([A-Za-z][A-Za-z0-9_-]*)=\(([^)]*)\)((?:;[^,]*)?)/);if(!e?.[1]||e[2]===void 0)throw new Fe("signature_invalid","UCP Signature-Input is malformed");let t=[...e[2].matchAll(/"([^"]+)"/g)].map(a=>a[1]);if(t.length===0)throw new Fe("signature_invalid","UCP Signature-Input has no covered components");let n=e[3]??"",o=new Map;for(let a of n.matchAll(/;([A-Za-z][A-Za-z0-9_-]*)=(?:"((?:\\.|[^"])*)"|(-?\d+)|([^;,\s]+))/g))o.set(a[1],a[2]??a[3]??a[4]);let i=o.get("keyid");if(!i)throw new Fe("signature_invalid","UCP Signature-Input is missing keyid");let s=a=>{let c=o.get(a);if(c===void 0)return;let l=Number(c);if(!Number.isSafeInteger(l))throw new Fe("signature_invalid",`UCP signature parameter ${a} is invalid`);return l};return{label:e[1],components:t,parameters:`(${e[2]})${n}`,keyId:i.replaceAll('\\"','"'),algorithm:o.get("alg"),created:s("created"),expires:s("expires"),nonce:o.get("nonce")}}function zC(r,e){let t=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),n=r.match(new RegExp(`(?:^|,)\\s*${t}=:([A-Za-z0-9+/=]+):`));if(!n?.[1])throw new Fe("signature_invalid",`UCP Signature is missing label ${e}`);return FP(n[1])}async function qC(r,e){if(!e)throw new Fe("digest_mismatch","UCP signed response is missing Content-Digest");let t=await HC(r);if(e!==t)throw new Fe("digest_mismatch","UCP response Content-Digest does not match the raw body")}var Co=class{constructor(e={}){this.options=e}seen=new Set;async verify(e,t){let n=e.headers.get("Signature-Input"),o=e.headers.get("Signature");if(!n||!o){if(!this.options.required)return;throw new Fe("signature_missing","UCP response signature is required")}let i=BC(n),s=zC(o,i.label),a=Math.floor((this.options.now?.()??Date.now())/1e3),c=this.options.clockToleranceSeconds??60;if(i.expires!==void 0&&a>i.expires+c)throw new Fe("signature_expired","UCP response signature has expired");if(i.created!==void 0&&i.created>a+c)throw new Fe("signature_invalid","UCP response signature creation time is in the future");if(this.options.maxAgeSeconds!==void 0&&(i.created===void 0||a-i.created>this.options.maxAgeSeconds+c))throw new Fe("signature_expired","UCP response signature is too old or missing created");if(!i.components.includes("@status"))throw new Fe("signature_invalid","UCP response signature does not cover @status");if(t.body.length>0){if(!i.components.includes("content-digest")||!i.components.includes("content-type"))throw new Fe("signature_invalid","UCP response signature does not cover body digest and content type");await qC(t.body,e.headers.get("Content-Digest"))}let l=t.signingKeys,u=l.find(x=>x.kid===i.keyId);if(!u&&t.refreshSigningKeys&&(l=await t.refreshSigningKeys(),u=l.find(x=>x.kid===i.keyId)),!u)throw new Fe("key_not_found",`UCP signing key ${i.keyId} was not found`);let d=this.normalizeAlgorithm(i.algorithm??u.alg);if(u.alg&&u.alg!==d)throw new Fe("algorithm_unsupported",`UCP signing key algorithm ${u.alg} does not match ${d}`);let p=[...i.components.map(x=>`"${x}": ${this.componentValue(x,e)}`),`"@signature-params": ${i.parameters}`].join(`
|
|
1323
1323
|
`),m=d==="ES256"?"P-256":"P-384",g=d==="ES256"?"SHA-256":"SHA-384",h=!1;try{let x=await Ze().subtle.importKey("jwk",u,{name:"ECDSA",namedCurve:m},!1,["verify"]);h=await Ze().subtle.verify({name:"ECDSA",hash:g},x,s,new TextEncoder().encode(p))}catch{h=!1}if(!h)throw new Fe("signature_invalid","UCP response signature verification failed");if(this.options.replayProtection){let x=i.nonce?`${i.keyId}:nonce:${i.nonce}`:`${i.keyId}:signature:${o}`;if(this.seen.has(x))throw new Fe("signature_replayed","UCP response signature was replayed");this.seen.add(x)}}async verifyRequest(e,t){let n=e.headers.get("Signature-Input"),o=e.headers.get("Signature");if(!n||!o)throw new Fe("signature_missing","UCP request signature is required");let i=BC(n),s=zC(o,i.label),a=Math.floor((this.options.now?.()??Date.now())/1e3),c=this.options.clockToleranceSeconds??60;if(i.expires!==void 0&&a>i.expires+c)throw new Fe("signature_expired","UCP request signature has expired");if(i.created!==void 0&&i.created>a+c)throw new Fe("signature_invalid","UCP request signature creation time is in the future");if(this.options.maxAgeSeconds!==void 0&&(i.created===void 0||a-i.created>this.options.maxAgeSeconds+c))throw new Fe("signature_expired","UCP request signature is too old or missing created");let l=new URL(e.url),d=["@method","@authority","@path",...l.search?["@query"]:[],...t.body.length>0?["content-digest","content-type"]:[]].filter(b=>!i.components.includes(b));if(d.length>0)throw new Fe("signature_invalid",`UCP request signature does not cover ${d.join(", ")}`);t.body.length>0&&await qC(t.body,e.headers.get("Content-Digest"));let p=t.signingKeys,m=p.find(b=>b.kid===i.keyId);if(!m&&t.refreshSigningKeys&&(p=await t.refreshSigningKeys(),m=p.find(b=>b.kid===i.keyId)),!m)throw new Fe("key_not_found",`UCP signing key ${i.keyId} was not found`);let g=this.normalizeAlgorithm(i.algorithm??m.alg);if(m.alg&&m.alg!==g)throw new Fe("algorithm_unsupported",`UCP signing key algorithm ${m.alg} does not match ${g}`);let h=b=>{if(b==="@method")return e.method.toUpperCase();if(b==="@authority")return l.host;if(b==="@path")return l.pathname;if(b==="@query")return l.search;let w=e.headers.get(b);if(w===null)throw new Fe("signature_invalid",`UCP signed request component is missing: ${b}`);return w},x=[...i.components.map(b=>`"${b}": ${h(b)}`),`"@signature-params": ${i.parameters}`].join(`
|
|
1324
|
-
`),f=g==="ES256"?"P-256":"P-384",y=g==="ES256"?"SHA-256":"SHA-384",A=!1;try{let b=await Ze().subtle.importKey("jwk",m,{name:"ECDSA",namedCurve:f},!1,["verify"]);A=await Ze().subtle.verify({name:"ECDSA",hash:y},b,s,new TextEncoder().encode(x))}catch{A=!1}if(!A)throw new Fe("signature_invalid","UCP request signature verification failed");if(this.options.replayProtection){let b=i.nonce?`${i.keyId}:nonce:${i.nonce}`:`${i.keyId}:signature:${o}`;if(this.seen.has(b))throw new Fe("signature_replayed","UCP request signature was replayed");this.seen.add(b)}}clearReplayCache(){this.seen.clear()}normalizeAlgorithm(e){let t=e==="ecdsa-p256-sha256"?"ES256":e==="ecdsa-p384-sha384"?"ES384":e;if(t!=="ES256"&&t!=="ES384"||!(this.options.allowedAlgorithms??["ES256","ES384"]).includes(t))throw new Fe("algorithm_unsupported",`UCP signature algorithm ${String(e)} is unsupported`);return t}componentValue(e,t){if(e==="@status")return String(t.status);let n=t.headers.get(e);if(n===null)throw new Fe("signature_invalid",`UCP signed response component is missing: ${e}`);return n}};var jp="2026-04-08",KC="dev.ucp.shopping",WC=["search_catalog","lookup_catalog","get_product","create_cart","get_cart","update_cart","cancel_cart","create_checkout","get_checkout","update_checkout","complete_checkout","cancel_checkout","get_order"],Gp={search_catalog:"dev.ucp.shopping.catalog.search",lookup_catalog:"dev.ucp.shopping.catalog.lookup",get_product:"dev.ucp.shopping.catalog.lookup",create_cart:"dev.ucp.shopping.cart",get_cart:"dev.ucp.shopping.cart",update_cart:"dev.ucp.shopping.cart",cancel_cart:"dev.ucp.shopping.cart",create_checkout:"dev.ucp.shopping.checkout",get_checkout:"dev.ucp.shopping.checkout",update_checkout:"dev.ucp.shopping.checkout",complete_checkout:"dev.ucp.shopping.checkout",cancel_checkout:"dev.ucp.shopping.checkout",get_order:"dev.ucp.shopping.order"};var Bp=class{constructor(e){this.options=e;this.responseVerifier=e.httpMessageVerification?new Co(e.httpMessageVerification):void 0,this.identityOAuth=e.identityLinkingOAuth?new Yn(e.identityLinkingOAuth):void 0,this.schemaValidator=e.schemaValidation===!1?void 0:new ds({...e.schemaValidation??{},fetch:e.schemaValidation?.fetch??e.mcp?.mtls?.fetch??e.mcp?.fetch,ssrfProtection:e.schemaValidation?.ssrfProtection??e.mcp?.ssrfProtection})}negotiated;mcpClient;mcpTransport;responseVerifier;identityOAuth;identityToken;webhookIds=new Set;schemaValidator;async init(){if(this.negotiated)return;let e=await this.fetchProfile(this.profileURL()),t=this.options.version??jp;if(e.ucp.version!==t&&!e.ucp.supported_versions?.[t])throw new Error(`UCP version ${t} is not supported by business profile ${e.ucp.version}`);let n=e.ucp.version===t?e:await this.fetchProfile(e.ucp.supported_versions[t]),o=this.selectService(n,t),i=this.negotiateCapabilities(n,t);if(this.negotiated={version:t,service:o,capabilities:i,paymentHandlers:n.ucp.payment_handlers??{},signingKeys:n.signing_keys??[],businessProfile:n},o.transport==="mcp"){let s=new Ao(o.endpoint,this.options.mcp);this.mcpTransport=s,this.mcpClient=new cs(s,{namespace:"ucp",era:"legacy"}),this.options.skipMCPInitialization||await this.mcpClient.init()}}getProfile(){if(!this.negotiated)throw new Error("UCP client is not initialized");return this.negotiated}getNamespace(){return(this.options.namespace??"ucp").trim().replace(/[^a-zA-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"")||"ucp"}getEvaluationMode(){return this.options.evaluationMode??"live"}getOperationNames(){let e=this.negotiated?.capabilities,t=new Set(WC.filter(n=>e===void 0||e[Gp[n]]));for(let n of this.mcpClient?.getTools()??[])t.add(n.name);return[...t]}getOperationBindings(){return this.getOperationNames().map(e=>({name:e,namespace:this.getNamespace(),componentId:`ucp:${this.getNamespace()}:${e}`,description:`Execute the negotiated UCP ${e} operation`,parameters:{type:"object",additionalProperties:!0},protocol:{kind:"ucp",namespace:this.getNamespace(),name:e,meta:{version:this.negotiated?.version??this.options.version??jp}},func:(t,n)=>this.call(e,t??{},{signal:n?.abortSignal})}))}getPaymentHandlers(){return this.getProfile().paymentHandlers}getIdentityLinkingConfig(){let t=this.getProfile().capabilities["dev.ucp.common.identity_linking"]?.[0]?.config;return t&&typeof t=="object"?t:void 0}getIdentityLinkingScopes(){return Object.keys(this.getIdentityLinkingConfig()?.scopes??{})}async verifyOrderEvent(e){await this.init();let t=e.headers.get("UCP-Agent")?.match(/(?:^|;)\s*profile="([^"]+)"/)?.[1];if(!t)throw new Error("UCP order event is missing signer profile");if(!new Set([this.profileURL(),...this.options.trustedBusinessProfileUrls??[]]).has(t))throw new Error(`UCP order event profile is not trusted: ${t}`);let o=e.headers.get("Webhook-Id"),i=Number(e.headers.get("Webhook-Timestamp"));if(!o||!Number.isFinite(i))throw new Error("UCP order event is missing webhook identity headers");let s=Math.floor(Date.now()/1e3);if(Math.abs(s-i)>(this.options.webhookMaxAgeSeconds??300))throw new Error("UCP order event timestamp is outside the acceptance window");if(this.webhookIds.has(o))throw new Error(`UCP order event was replayed: ${o}`);let a=await e.clone().text(),c=this.getProfile();await new Co({required:!0,replayProtection:!0}).verifyRequest(e,{body:a,signingKeys:c.signingKeys,refreshSigningKeys:async()=>{let d=await this.fetchProfile(t);return t===this.profileURL()&&(c.signingKeys=d.signing_keys??[],c.businessProfile=d),d.signing_keys??[]}});let u=await this.validateOutcome(JSON.parse(a),"get_order");if(typeof u.id!="string"||typeof u.checkout_id!="string")throw new Error("Invalid UCP order event: missing id or checkout_id");return this.webhookIds.add(o),u}getMCPClient(){return this.options.skipMCPInitialization?void 0:this.mcpClient}async close(){await this.mcpClient?.close()}searchCatalog(e,t){return this.call("search_catalog",{catalog:e},t)}lookupCatalog(e,t){return this.call("lookup_catalog",{catalog:e},t)}getProduct(e,t){return this.call("get_product",{catalog:e},t)}createCart(e,t){return this.call("create_cart",{cart:e},t)}getCart(e,t){return this.call("get_cart",{id:e},t)}updateCart(e,t,n){return this.call("update_cart",{id:e,cart:t},n)}cancelCart(e,t){return this.call("cancel_cart",{id:e},t)}createCheckout(e,t){return this.call("create_checkout",{checkout:e},t)}getCheckout(e,t){return this.call("get_checkout",{id:e},t)}updateCheckout(e,t,n){return this.call("update_checkout",{id:e,checkout:t},n)}completeCheckout(e,t,n){let o=n?t:{},i=n??t;return this.requireIdempotency("complete_checkout",i),this.call("complete_checkout",{id:e,...o},i)}cancelCheckout(e,t){return this.requireIdempotency("cancel_checkout",t),this.call("cancel_checkout",{id:e},t)}getOrder(e,t){return this.call("get_order",{id:e},t)}async call(e,t,n={}){await this.init();let o=this.getProfile(),i={...n,idempotencyKey:n.idempotencyKey??(this.isStateChanging(e)?ze():void 0)},s=this.withAgentMetadata(t,i.idempotencyKey);if(o.service.transport==="mcp"){if(this.options.skipMCPInitialization){if(!this.mcpTransport)throw new Error("UCP MCP transport was not initialized");let c=await this.mcpTransport.send({jsonrpc:"2.0",id:ze(),method:"tools/call",params:{name:e,arguments:s}},{signal:i.signal});return this.outcomeFromMCPResponse(e,c)}if(!this.mcpClient)throw new Error("UCP MCP client was not initialized");let a=await this.mcpClient.callTool(e,s,{signal:i.signal});if(a.isError)throw new Error(`UCP MCP operation ${e} returned isError`);if(!a.structuredContent)throw new Error(`UCP MCP operation ${e} did not return structuredContent`);return this.validateOutcome(a.structuredContent,e)}return this.callREST(e,s,i)}profileURL(){let e=new URL(this.options.profileUrl);return(e.pathname==="/"||e.pathname==="")&&(e.pathname="/.well-known/ucp"),e.toString()}async fetchProfile(e){let t=await nt(e,{headers:this.options.headers,ssrfProtection:this.options.mcp?.ssrfProtection,ssrfContext:"mcp-endpoint"});if(!t.ok)throw new Error(`UCP profile discovery failed: ${t.status}`);let n=await t.json();if(!n.ucp?.version||!n.ucp.services||!n.ucp.capabilities)throw new Error("Invalid UCP profile: missing ucp version/services/capabilities");return n}selectService(e,t){let n=e.ucp.services[KC]??[],o=this.options.transport??"auto",i=n.filter(a=>a.version===t),s=o==="auto"?i.find(a=>a.transport==="mcp")??i.find(a=>a.transport==="rest"):i.find(a=>a.transport===o);if(!s)throw new Error(`No compatible UCP ${o} shopping service found`);return s}negotiateCapabilities(e,t){let n=this.options.platformCapabilities,o=Object.fromEntries(Object.entries(e.ucp.capabilities).flatMap(([i,s])=>{let a=s.filter(l=>l.version===t),c=n?a.filter(l=>n[i]?.some(u=>u.version===l.version)):a;return c.length?[[i,c]]:[]}));for(let[i,s]of Object.entries(o))s.flatMap(c=>c.extends?Array.isArray(c.extends)?c.extends:[c.extends]:[]).some(c=>!o[c])&&delete o[i];return o}withAgentMetadata(e,t){let n=e.meta&&typeof e.meta=="object"?e.meta:{};return{...e,meta:{...n,"ucp-agent":{...n["ucp-agent"],profile:this.options.agentProfile},...t?{"idempotency-key":t}:{}}}}async callREST(e,t,n){let o=this.getProfile(),i=this.restRequest(e,t),s=`${o.service.endpoint.replace(/\/$/,"")}/${i.path}`,a=i.body===void 0?void 0:JSON.stringify(i.body),c={...a===void 0?{}:{"Content-Type":"application/json"},"UCP-Agent":`profile="${this.options.agentProfile.replaceAll('"','\\"')}"`,"Request-Id":ze(),...n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},...this.options.headers};this.options.httpMessageSignature&&(c=await Dp({url:s,method:i.method,headers:c,body:a},this.options.httpMessageSignature)),this.options.signRequest&&(c={...c,...await this.options.signRequest({url:s,method:i.method,headers:c,body:a??""})});let l=await this.options.getIdentityToken?.();l&&(this.identityToken=l),this.identityToken&&(c.Authorization=`${this.identityToken.tokenType??"Bearer"} ${this.identityToken.accessToken}`);let u=()=>nt(s,{method:i.method,headers:c,...a===void 0?{}:{body:a},signal:n.signal,ssrfProtection:this.options.mcp?.ssrfProtection,ssrfContext:"mcp-endpoint"}),d=await u();if((d.status===401||d.status===403)&&this.identityOAuth){let p=await this.identityOAuth.ensureAccessToken({requestedUrl:s,wwwAuthenticate:d.headers.get("WWW-Authenticate"),currentToken:this.identityToken,forceRefresh:this.identityToken!==void 0});p&&(this.identityToken=p.token,c.Authorization=`${p.token.tokenType??"Bearer"} ${p.token.accessToken}`,d=await u())}if(this.responseVerifier&&await this.responseVerifier.verify(d,{body:await d.clone().text(),signingKeys:o.signingKeys,refreshSigningKeys:async()=>{let p=await this.fetchProfile(this.profileURL());return o.signingKeys=p.signing_keys??[],o.businessProfile=p,o.signingKeys}}),await this.options.verifyResponse?.(d.clone(),{profile:o}),!d.ok)throw new Error(`UCP REST operation ${e} failed: ${d.status} ${d.statusText}`);return this.validateOutcome(await d.json(),e)}restRequest(e,t){let n=typeof t.id=="string"?encodeURIComponent(t.id):"",o=s=>t[s]&&typeof t[s]=="object"?t[s]:{};return{search_catalog:{method:"POST",path:"catalog/search",body:o("catalog")},lookup_catalog:{method:"POST",path:"catalog/lookup",body:o("catalog")},get_product:{method:"POST",path:"catalog/product",body:o("catalog")},create_cart:{method:"POST",path:"carts",body:o("cart")},get_cart:{method:"GET",path:`carts/${n}`},update_cart:{method:"PUT",path:`carts/${n}`,body:o("cart")},cancel_cart:{method:"POST",path:`carts/${n}/cancel`,body:{}},create_checkout:{method:"POST",path:"checkout-sessions",body:o("checkout")},get_checkout:{method:"GET",path:`checkout-sessions/${n}`},update_checkout:{method:"PUT",path:`checkout-sessions/${n}`,body:o("checkout")},complete_checkout:{method:"POST",path:`checkout-sessions/${n}/complete`,body:this.operationBody(t)},cancel_checkout:{method:"POST",path:`checkout-sessions/${n}/cancel`,body:{}},get_order:{method:"GET",path:`orders/${n}`}}[e]??{method:"POST",path:e.replaceAll("_","/"),body:{...t}}}async outcomeFromMCPResponse(e,t){if("error"in t)throw new Error(`UCP MCP operation ${e} failed: ${t.error.code} ${t.error.message}`);let n=t.result;if(n.isError)throw new Error(`UCP MCP operation ${e} returned isError`);if(!n.structuredContent)throw new Error(`UCP MCP operation ${e} did not return structuredContent`);return this.validateOutcome(n.structuredContent,e)}requireIdempotency(e,t){if(!t.idempotencyKey)throw new Error(`${e} requires an idempotencyKey`)}isStateChanging(e){return new Set(["create_cart","update_cart","cancel_cart","create_checkout","update_checkout","complete_checkout","cancel_checkout"]).has(e)}operationBody(e){let{id:t,meta:n,...o}=e;return o}async validateAgainstSchema(e,t){if(!this.schemaValidator)throw new Error("UCP schema validation is disabled");await this.schemaValidator.validate(e,t)}async validateOutcome(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid UCP outcome: expected an object");let n=e,o=n.ucp;if(!o||typeof o!="object"||typeof o.version!="string")throw new Error("Invalid UCP outcome: missing ucp.version");if(this.schemaValidator&&t){let i=Gp[t],s=new Set;for(let[a,c]of Object.entries(this.getProfile().capabilities))if(a===i||c.some(u=>{let d=Array.isArray(u.extends)?u.extends:u.extends?[u.extends]:[];return i!==void 0&&d.includes(i)}))for(let u of c)typeof u.schema=="string"&&s.add(u.schema);for(let a of s)await this.schemaValidator.validate(n,a)}return n}};var _P=new wt,zp=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(_P.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)}};export{ai as AxACE,qa as AxACEOptimizedProgram,wc as AxAI,Ai as AxAIAnthropic,yi as AxAIAnthropicModel,sc as AxAIAnthropicVertexModel,ki as AxAIAzureOpenAI,Gi as AxAICohere,pc as AxAICohereEmbedModel,Ti as AxAICohereModel,Bi as AxAIDeepSeek,Mi as AxAIDeepSeekModel,qi as AxAIGoogleGemini,mo as AxAIGoogleGeminiEmbedModel,WA as AxAIGoogleGeminiEmbedTypes,po as AxAIGoogleGeminiModel,Bd as AxAIGoogleGeminiSafetyCategory,zd as AxAIGoogleGeminiSafetyThreshold,Ji as AxAIGrok,QA as AxAIGrokEmbedModels,Di as AxAIGrokModel,Vi as AxAIMistral,YA as AxAIMistralEmbedModels,Fi as AxAIMistralModel,Si as AxAIOpenAI,ft as AxAIOpenAIBase,Hn as AxAIOpenAIEmbedModel,Cr as AxAIOpenAIModel,Hi as AxAIOpenAIResponses,Cc as AxAIOpenAIResponsesBase,co as AxAIOpenAIResponsesModel,Ke as AxAIRefusalError,Ki as AxAIReka,Ni as AxAIRekaModel,Ne as AxAIServiceAbortedError,It as AxAIServiceAuthenticationError,gt as AxAIServiceError,tt as AxAIServiceNetworkError,bn as AxAIServiceResponseError,Qe as AxAIServiceStatusError,kt as AxAIServiceStreamTerminatedError,yt as AxAIServiceTimeoutError,Wi as AxAIWebLLM,$i as AxAIWebLLMModel,gi as AxAgent,et as AxAgentClarificationError,sn as AxAgentContextMap,mi as AxAgentPlaybook,vt as AxAgentProtocolCompletionSignal,oi as AxAgentSharedRuntimeSession,sr as AxAssertionError,Ud as AxBalancer,Et as AxBaseAI,Pn as AxBaseOptimizer,Tc as AxBestOfN,Yi as AxBootstrapFewShot,on as AxContentProcessingError,bd as AxContextMetricsCollector,za as AxDefaultCostTracker,bp as AxDockerSession,Rp as AxEmbeddingAdapter,ET as AxEvalUtil,_n as AxEventBackpressureError,fo as AxEventContinuationNotFoundError,qe as AxEventInputError,ho as AxEventOutcomeUnknownError,Zi as AxEventRouteBuilder,Nc as AxEventRuntime,Xi as AxEventTargetBuilder,ro as AxFlow,Gt as AxFlowMermaidError,rt as AxFluentFieldType,ea as AxFunctionError,ta as AxFunctionProcessor,yr as AxGEPA,ci as AxGEPAComponentSelector,Ee as AxGen,pa as AxGenerateError,Ii as AxInMemoryBalancerStatsStore,ns as AxInMemoryEventStore,rs as AxInMemoryProgramStateStore,Kr as AxJSRuntime,Tu as AxJSRuntimePermission,El as AxMCPAppBridge,cs as AxMCPClient,ls as AxMCPDPoPProofFactory,xp as AxMCPEventSource,zs as AxMCPExecutionContext,$p as AxMCPHTTPSSETransport,ss as AxMCPHTTPStatusError,us as AxMCPOAuthJWTVerifier,qt as AxMCPParamHeaderSchemaError,Nn as AxMCPProtocolError,Np as AxMCPRecordingTransport,Lp as AxMCPReplayTransport,Ao as AxMCPStreamableHTTPTransport,_p as AxMCPStreambleHTTPTransport,Up as AxMCPWebSocketTransport,cp as AxManualEventClock,At as AxMediaNotSupportedError,jn as AxMemory,Yd as AxMockAIService,Qd as AxMultiServiceRouter,un as AxOptimizedProgramImpl,Yr as AxPlaybook,ar as AxProgram,ir as AxPromptTemplate,ep as AxProviderRouter,yp as AxPushEventSource,zp as AxRateLimiterTokenUsage,Pc as AxRefine,On as AxRefineError,Me as AxSignature,Is as AxSignatureBuilder,Gr as AxStopFunctionCallException,Rn as AxStreamingAssertionError,VT as AxStringUtil,ap as AxSynth,Fn as AxSystemEventClock,ip as AxTestPrompt,Ap as AxTimerEventSource,Hs as AxTokenLimitError,Bp as AxUCPClient,Fe as AxUCPHTTPMessageSignatureError,Co as AxUCPHTTPMessageVerifier,kr as AxUCPSchemaValidationError,ds as AxUCPSchemaValidator,Cp as AxUCPWebhookEventSource,Xy as agent,IT as ai,Ut as ax,xA as axAIAnthropicDefaultConfig,rI as axAIAnthropicVertexDefaultConfig,NI as axAIAzureOpenAIBestConfig,FI as axAIAzureOpenAICreativeConfig,$A as axAIAzureOpenAIDefaultConfig,_I as axAIAzureOpenAIFastConfig,QI as axAICohereCreativeConfig,ZA as axAICohereDefaultConfig,nT as axAIDeepSeekCodeConfig,eC as axAIDeepSeekDefaultConfig,cC as axAIGoogleGeminiDefaultConfig,mT as axAIGoogleGeminiDefaultCreativeConfig,tC as axAIGoogleGeminiLiveAudioDefaultConfig,ST as axAIGrokBestConfig,np as axAIGrokDefaultConfig,kT as axAIGrokVoiceDefaultConfig,gT as axAIMistralBestConfig,Jd as axAIMistralDefaultConfig,IA as axAIOpenAIAudioDefaultConfig,Nd as axAIOpenAIBestConfig,Ld as axAIOpenAICreativeConfig,lo as axAIOpenAIDefaultConfig,$d as axAIOpenAIFastConfig,Od as axAIOpenAIRealtimeDefaultConfig,_A as axAIOpenAIRealtimeTranscriptionDefaultConfig,hT as axAIOpenAIResponsesBestConfig,xT as axAIOpenAIResponsesCreativeConfig,bc as axAIOpenAIResponsesDefaultConfig,AT as axAIRekaBestConfig,CT as axAIRekaCreativeConfig,Rc as axAIRekaDefaultConfig,bT as axAIRekaFastConfig,vT as axAIWebLLMCreativeConfig,lC as axAIWebLLMDefaultConfig,yT as axAnalyzeChatPromptRequirements,uo as axAnalyzeRequestRequirements,is as axApplyMCPAuthentication,Pd as axApplyOpenAIChatAudioRequest,Ct as axAudioFormatFromMimeType,bA as axAudioInputFilename,CA as axAudioInputToBlob,Bt as axAudioMimeType,Ge as axBaseAIDefaultConfig,Ot as axBaseAIDefaultCreativeConfig,Eo as axBuildDistillerDefinition,Oo as axBuildExecutorDefinition,Tl as axBuildResponderDefinition,rb as axCheckMetricsHealth,so as axConcatBase64,tA as axCreateDefaultColorLogger,ey as axCreateDefaultOptimizerColorLogger,iS as axCreateDefaultOptimizerTextLogger,$k as axCreateDefaultTextLogger,Ha as axCreateFlowColorLogger,YS as axCreateFlowTextLogger,Hd as axCreateGeminiLiveAudioApi,pC as axCreateGrokRealtimeApi,zv as axCreateJSRuntime,vi as axCreateOpenAIRealtimeApi,QS as axDefaultFlowLogger,bm as axDefaultMetricsConfig,ja as axDefaultOptimizerLogger,ny as axDefaultOptimizerMetricsConfig,bS as axDeserializeOptimizedProgram,_o as axEmitUsageEvent,Ft as axEventErrorMessage,st as axEventId,es as axEventIdentityScope,hp as axEventMatches,xo as axEventScopedCorrelationKey,ts as axEventScopedDedupeKey,fp as axEventSizeBytes,En as axFetchJsonSpeech,Ci as axFetchMultipartTranscription,jI as axGetCompatibilityReport,BI as axGetFormatCompatibility,sb as axGetMetricsConfig,cS as axGetOptimizerMetricsConfig,GI as axGetProvidersWithMediaSupport,YI as axGetSupportedAIModels,fe as axGlobals,ac as axGoogleGeminiLiveAudioDefaults,Xt as axIsAudioOutputEnabled,nC as axIsGeminiLiveAudioModel,rp as axIsGrokVoiceModel,Id as axIsOpenAIChatAudioModel,lc as axIsOpenAIRealtimeModel,Kn as axIsOpenAIRealtimeTranscriptionModel,pP as axMCPAPIKeyAuthentication,Ol as axMCPAppToolMeta,dP as axMCPBasicAuthentication,uP as axMCPBearerAuthentication,Mp as axMCPBuildParamHeaders,vp as axMCPBuildRequestMeta,fP as axMCPChat,No as axMCPChildExecutionOptions,hP as axMCPDecodeHeaderValue,as as axMCPEncodeHeaderValue,tP as axMCPEventRoutes,Uc as axMCPFulfillInputRequests,mP as axMCPHMACAuthentication,IC as axMCPIsPlainHeaderValue,Gc as axMCPParamHeaderBindings,$c as axMCPServerInfoFromMeta,Tp as axMCPToolInputSchemaToFunctionSchema,Bs as axMCPToolVisibleTo,Vd as axMapGeminiLiveAudioPart,Ed as axMapOpenAIChatAudioDelta,Md as axMapOpenAIChatAudioResponse,Td as axMapOpenAIInputAudioPart,bt as axMergeChatAudioConfig,Fo as axMergeUsageContexts,io as axModelInfoAnthropic,Pi as axModelInfoCohere,Ei as axModelInfoDeepSeek,Oi as axModelInfoGoogleGemini,ji as axModelInfoGrok,_i as axModelInfoMistral,br as axModelInfoOpenAI,bi as axModelInfoOpenAIResponses,Li as axModelInfoReka,Ui as axModelInfoWebLLM,Wn as axNormalizeOpenAIUsage,RA as axNormalizeTranscriptionResponse,ao as axOpenAIChatAudioDefaults,er as axOptimizableValidators,_a as axPlaybookFailureSection,Zd as axProcessContentForProvider,fc as axResolveGeminiLiveAudioConfig,op as axResolveGrokRealtimeAudioConfig,Lt as axResolveMCPExecutionContext,TA as axResolveOpenAIChatAudioConfig,uc as axResolveOpenAIRealtimeAudioConfig,Mo as axRuntimePrimitives,jd as axScoreProvidersForRequest,Gd as axSelectOptimalProvider,ry as axSerializeOptimizedProgram,hc as axShouldUseGeminiLiveAudio,dC as axShouldUseGrokRealtime,Fd as axShouldUseOpenAIRealtime,Dp as axSignUCPRequest,Oe as axSpanAttributes,dn as axSpanEvents,GA as axUpdateBalancerRouteStats,ib as axUpdateMetricsConfig,aS as axUpdateOptimizerMetricsConfig,Lo as axValidateChatRequestMessage,Fl as axValidateChatResponseResult,gp as axValidateEventEnvelope,rC as axValidateGeminiLiveAudioInput,KA as axValidateProviderCapabilities,Mu as axWorkerRuntime,$T as bestOfN,bC as eventInput,JT as eventPath,yo as eventRoute,eP as eventRuntime,SC as eventTarget,q as f,gd as flow,db as fn,LT as optimize,US as playbook,UT as refine,KT as runAxEventStoreConformance,RS as s};
|
|
1324
|
+
`),f=g==="ES256"?"P-256":"P-384",y=g==="ES256"?"SHA-256":"SHA-384",A=!1;try{let b=await Ze().subtle.importKey("jwk",m,{name:"ECDSA",namedCurve:f},!1,["verify"]);A=await Ze().subtle.verify({name:"ECDSA",hash:y},b,s,new TextEncoder().encode(x))}catch{A=!1}if(!A)throw new Fe("signature_invalid","UCP request signature verification failed");if(this.options.replayProtection){let b=i.nonce?`${i.keyId}:nonce:${i.nonce}`:`${i.keyId}:signature:${o}`;if(this.seen.has(b))throw new Fe("signature_replayed","UCP request signature was replayed");this.seen.add(b)}}clearReplayCache(){this.seen.clear()}normalizeAlgorithm(e){let t=e==="ecdsa-p256-sha256"?"ES256":e==="ecdsa-p384-sha384"?"ES384":e;if(t!=="ES256"&&t!=="ES384"||!(this.options.allowedAlgorithms??["ES256","ES384"]).includes(t))throw new Fe("algorithm_unsupported",`UCP signature algorithm ${String(e)} is unsupported`);return t}componentValue(e,t){if(e==="@status")return String(t.status);let n=t.headers.get(e);if(n===null)throw new Fe("signature_invalid",`UCP signed response component is missing: ${e}`);return n}};var jp="2026-04-08",KC="dev.ucp.shopping",WC=["search_catalog","lookup_catalog","get_product","create_cart","get_cart","update_cart","cancel_cart","create_checkout","get_checkout","update_checkout","complete_checkout","cancel_checkout","get_order"],Gp={search_catalog:"dev.ucp.shopping.catalog.search",lookup_catalog:"dev.ucp.shopping.catalog.lookup",get_product:"dev.ucp.shopping.catalog.lookup",create_cart:"dev.ucp.shopping.cart",get_cart:"dev.ucp.shopping.cart",update_cart:"dev.ucp.shopping.cart",cancel_cart:"dev.ucp.shopping.cart",create_checkout:"dev.ucp.shopping.checkout",get_checkout:"dev.ucp.shopping.checkout",update_checkout:"dev.ucp.shopping.checkout",complete_checkout:"dev.ucp.shopping.checkout",cancel_checkout:"dev.ucp.shopping.checkout",get_order:"dev.ucp.shopping.order"};var Bp=class{constructor(e){this.options=e;this.responseVerifier=e.httpMessageVerification?new Co(e.httpMessageVerification):void 0,this.identityOAuth=e.identityLinkingOAuth?new Yn(e.identityLinkingOAuth):void 0,this.schemaValidator=e.schemaValidation===!1?void 0:new ds({...e.schemaValidation??{},fetch:e.schemaValidation?.fetch??e.mcp?.mtls?.fetch??e.mcp?.fetch,ssrfProtection:e.schemaValidation?.ssrfProtection??e.mcp?.ssrfProtection})}negotiated;mcpClient;mcpTransport;responseVerifier;identityOAuth;identityToken;webhookIds=new Set;schemaValidator;async init(){if(this.negotiated)return;let e=await this.fetchProfile(this.profileURL()),t=this.options.version??jp;if(e.ucp.version!==t&&!e.ucp.supported_versions?.[t])throw new Error(`UCP version ${t} is not supported by business profile ${e.ucp.version}`);let n=e.ucp.version===t?e:await this.fetchProfile(e.ucp.supported_versions[t]),o=this.selectService(n,t),i=this.negotiateCapabilities(n,t);if(this.negotiated={version:t,service:o,capabilities:i,paymentHandlers:n.ucp.payment_handlers??{},signingKeys:n.signing_keys??[],businessProfile:n},o.transport==="mcp"){let s=new Ao(o.endpoint,this.options.mcp);this.mcpTransport=s,this.mcpClient=new cs(s,{namespace:"ucp",era:"legacy"}),this.options.skipMCPInitialization||await this.mcpClient.init()}}getProfile(){if(!this.negotiated)throw new Error("UCP client is not initialized");return this.negotiated}getNamespace(){return(this.options.namespace??"ucp").trim().replace(/[^a-zA-Z0-9_]+/g,"_").replace(/^_+|_+$/g,"")||"ucp"}getEvaluationMode(){return this.options.evaluationMode??"live"}getOperationNames(){let e=this.negotiated?.capabilities,t=new Set(WC.filter(n=>e===void 0||e[Gp[n]]));for(let n of this.mcpClient?.getTools()??[])t.add(n.name);return[...t]}getOperationBindings(){return this.getOperationNames().map(e=>({name:e,namespace:this.getNamespace(),componentId:`ucp:${this.getNamespace()}:${e}`,description:`Execute the negotiated UCP ${e} operation`,parameters:{type:"object",additionalProperties:!0},protocol:{kind:"ucp",namespace:this.getNamespace(),name:e,meta:{version:this.negotiated?.version??this.options.version??jp}},func:(t,n)=>this.call(e,t??{},{signal:n?.abortSignal})}))}getPaymentHandlers(){return this.getProfile().paymentHandlers}getIdentityLinkingConfig(){let t=this.getProfile().capabilities["dev.ucp.common.identity_linking"]?.[0]?.config;return t&&typeof t=="object"?t:void 0}getIdentityLinkingScopes(){return Object.keys(this.getIdentityLinkingConfig()?.scopes??{})}async verifyOrderEvent(e){await this.init();let t=e.headers.get("UCP-Agent")?.match(/(?:^|;)\s*profile="([^"]+)"/)?.[1];if(!t)throw new Error("UCP order event is missing signer profile");if(!new Set([this.profileURL(),...this.options.trustedBusinessProfileUrls??[]]).has(t))throw new Error(`UCP order event profile is not trusted: ${t}`);let o=e.headers.get("Webhook-Id"),i=Number(e.headers.get("Webhook-Timestamp"));if(!o||!Number.isFinite(i))throw new Error("UCP order event is missing webhook identity headers");let s=Math.floor(Date.now()/1e3);if(Math.abs(s-i)>(this.options.webhookMaxAgeSeconds??300))throw new Error("UCP order event timestamp is outside the acceptance window");if(this.webhookIds.has(o))throw new Error(`UCP order event was replayed: ${o}`);let a=await e.clone().text(),c=this.getProfile();await new Co({required:!0,replayProtection:!0}).verifyRequest(e,{body:a,signingKeys:c.signingKeys,refreshSigningKeys:async()=>{let d=await this.fetchProfile(t);return t===this.profileURL()&&(c.signingKeys=d.signing_keys??[],c.businessProfile=d),d.signing_keys??[]}});let u=await this.validateOutcome(JSON.parse(a),"get_order");if(typeof u.id!="string"||typeof u.checkout_id!="string")throw new Error("Invalid UCP order event: missing id or checkout_id");return this.webhookIds.add(o),u}getMCPClient(){return this.options.skipMCPInitialization?void 0:this.mcpClient}async close(){await this.mcpClient?.close()}searchCatalog(e,t){return this.call("search_catalog",{catalog:e},t)}lookupCatalog(e,t){return this.call("lookup_catalog",{catalog:e},t)}getProduct(e,t){return this.call("get_product",{catalog:e},t)}createCart(e,t){return this.call("create_cart",{cart:e},t)}getCart(e,t){return this.call("get_cart",{id:e},t)}updateCart(e,t,n){return this.call("update_cart",{id:e,cart:t},n)}cancelCart(e,t){return this.call("cancel_cart",{id:e},t)}createCheckout(e,t){return this.call("create_checkout",{checkout:e},t)}getCheckout(e,t){return this.call("get_checkout",{id:e},t)}updateCheckout(e,t,n){return this.call("update_checkout",{id:e,checkout:t},n)}completeCheckout(e,t,n){let o=n?t:{},i=n??t;return this.requireIdempotency("complete_checkout",i),this.call("complete_checkout",{id:e,...o},i)}cancelCheckout(e,t){return this.requireIdempotency("cancel_checkout",t),this.call("cancel_checkout",{id:e},t)}getOrder(e,t){return this.call("get_order",{id:e},t)}async call(e,t,n={}){await this.init();let o=this.getProfile(),i={...n,idempotencyKey:n.idempotencyKey??(this.isStateChanging(e)?ze():void 0)},s=this.withAgentMetadata(t,i.idempotencyKey);if(o.service.transport==="mcp"){if(this.options.skipMCPInitialization){if(!this.mcpTransport)throw new Error("UCP MCP transport was not initialized");let c=await this.mcpTransport.send({jsonrpc:"2.0",id:ze(),method:"tools/call",params:{name:e,arguments:s}},{signal:i.signal});return this.outcomeFromMCPResponse(e,c)}if(!this.mcpClient)throw new Error("UCP MCP client was not initialized");let a=await this.mcpClient.callTool(e,s,{signal:i.signal});if(a.isError)throw new Error(`UCP MCP operation ${e} returned isError`);if(!a.structuredContent)throw new Error(`UCP MCP operation ${e} did not return structuredContent`);return this.validateOutcome(a.structuredContent,e)}return this.callREST(e,s,i)}profileURL(){let e=new URL(this.options.profileUrl);return(e.pathname==="/"||e.pathname==="")&&(e.pathname="/.well-known/ucp"),e.toString()}async fetchProfile(e){let t=await nt(e,{headers:this.options.headers,ssrfProtection:this.options.mcp?.ssrfProtection,ssrfContext:"mcp-endpoint"});if(!t.ok)throw new Error(`UCP profile discovery failed: ${t.status}`);let n=await t.json();if(!n.ucp?.version||!n.ucp.services||!n.ucp.capabilities)throw new Error("Invalid UCP profile: missing ucp version/services/capabilities");return n}selectService(e,t){let n=e.ucp.services[KC]??[],o=this.options.transport??"auto",i=n.filter(a=>a.version===t),s=o==="auto"?i.find(a=>a.transport==="mcp")??i.find(a=>a.transport==="rest"):i.find(a=>a.transport===o);if(!s)throw new Error(`No compatible UCP ${o} shopping service found`);return s}negotiateCapabilities(e,t){let n=this.options.platformCapabilities,o=Object.fromEntries(Object.entries(e.ucp.capabilities).flatMap(([i,s])=>{let a=s.filter(l=>l.version===t),c=n?a.filter(l=>n[i]?.some(u=>u.version===l.version)):a;return c.length?[[i,c]]:[]}));for(let[i,s]of Object.entries(o))s.flatMap(c=>c.extends?Array.isArray(c.extends)?c.extends:[c.extends]:[]).some(c=>!o[c])&&delete o[i];return o}withAgentMetadata(e,t){let n=e.meta&&typeof e.meta=="object"?e.meta:{};return{...e,meta:{...n,"ucp-agent":{...n["ucp-agent"],profile:this.options.agentProfile},...t?{"idempotency-key":t}:{}}}}async callREST(e,t,n){let o=this.getProfile(),i=this.restRequest(e,t),s=`${o.service.endpoint.replace(/\/$/,"")}/${i.path}`,a=i.body===void 0?void 0:JSON.stringify(i.body),c={...a===void 0?{}:{"Content-Type":"application/json"},"UCP-Agent":`profile="${this.options.agentProfile.replaceAll('"','\\"')}"`,"Request-Id":ze(),...n.idempotencyKey?{"Idempotency-Key":n.idempotencyKey}:{},...this.options.headers};this.options.httpMessageSignature&&(c=await Dp({url:s,method:i.method,headers:c,body:a},this.options.httpMessageSignature)),this.options.signRequest&&(c={...c,...await this.options.signRequest({url:s,method:i.method,headers:c,body:a??""})});let l=await this.options.getIdentityToken?.();l&&(this.identityToken=l),this.identityToken&&(c.Authorization=`${this.identityToken.tokenType??"Bearer"} ${this.identityToken.accessToken}`);let u=()=>nt(s,{method:i.method,headers:c,...a===void 0?{}:{body:a},signal:n.signal,ssrfProtection:this.options.mcp?.ssrfProtection,ssrfContext:"mcp-endpoint"}),d=await u();if((d.status===401||d.status===403)&&this.identityOAuth){let p=await this.identityOAuth.ensureAccessToken({requestedUrl:s,wwwAuthenticate:d.headers.get("WWW-Authenticate"),currentToken:this.identityToken,forceRefresh:this.identityToken!==void 0});p&&(this.identityToken=p.token,c.Authorization=`${p.token.tokenType??"Bearer"} ${p.token.accessToken}`,d=await u())}if(this.responseVerifier&&await this.responseVerifier.verify(d,{body:await d.clone().text(),signingKeys:o.signingKeys,refreshSigningKeys:async()=>{let p=await this.fetchProfile(this.profileURL());return o.signingKeys=p.signing_keys??[],o.businessProfile=p,o.signingKeys}}),await this.options.verifyResponse?.(d.clone(),{profile:o}),!d.ok)throw new Error(`UCP REST operation ${e} failed: ${d.status} ${d.statusText}`);return this.validateOutcome(await d.json(),e)}restRequest(e,t){let n=typeof t.id=="string"?encodeURIComponent(t.id):"",o=s=>t[s]&&typeof t[s]=="object"?t[s]:{};return{search_catalog:{method:"POST",path:"catalog/search",body:o("catalog")},lookup_catalog:{method:"POST",path:"catalog/lookup",body:o("catalog")},get_product:{method:"POST",path:"catalog/product",body:o("catalog")},create_cart:{method:"POST",path:"carts",body:o("cart")},get_cart:{method:"GET",path:`carts/${n}`},update_cart:{method:"PUT",path:`carts/${n}`,body:o("cart")},cancel_cart:{method:"POST",path:`carts/${n}/cancel`,body:{}},create_checkout:{method:"POST",path:"checkout-sessions",body:o("checkout")},get_checkout:{method:"GET",path:`checkout-sessions/${n}`},update_checkout:{method:"PUT",path:`checkout-sessions/${n}`,body:o("checkout")},complete_checkout:{method:"POST",path:`checkout-sessions/${n}/complete`,body:this.operationBody(t)},cancel_checkout:{method:"POST",path:`checkout-sessions/${n}/cancel`,body:{}},get_order:{method:"GET",path:`orders/${n}`}}[e]??{method:"POST",path:e.replaceAll("_","/"),body:{...t}}}async outcomeFromMCPResponse(e,t){if("error"in t)throw new Error(`UCP MCP operation ${e} failed: ${t.error.code} ${t.error.message}`);let n=t.result;if(n.isError)throw new Error(`UCP MCP operation ${e} returned isError`);if(!n.structuredContent)throw new Error(`UCP MCP operation ${e} did not return structuredContent`);return this.validateOutcome(n.structuredContent,e)}requireIdempotency(e,t){if(!t.idempotencyKey)throw new Error(`${e} requires an idempotencyKey`)}isStateChanging(e){return new Set(["create_cart","update_cart","cancel_cart","create_checkout","update_checkout","complete_checkout","cancel_checkout"]).has(e)}operationBody(e){let{id:t,meta:n,...o}=e;return o}async validateAgainstSchema(e,t){if(!this.schemaValidator)throw new Error("UCP schema validation is disabled");await this.schemaValidator.validate(e,t)}async validateOutcome(e,t){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("Invalid UCP outcome: expected an object");let n=e,o=n.ucp;if(!o||typeof o!="object"||typeof o.version!="string")throw new Error("Invalid UCP outcome: missing ucp.version");if(this.schemaValidator&&t){let i=Gp[t],s=new Set;for(let[a,c]of Object.entries(this.getProfile().capabilities))if(a===i||c.some(u=>{let d=Array.isArray(u.extends)?u.extends:u.extends?[u.extends]:[];return i!==void 0&&d.includes(i)}))for(let u of c)typeof u.schema=="string"&&s.add(u.schema);for(let a of s)await this.schemaValidator.validate(n,a)}return n}};var _P=new wt,zp=class{options;maxTokens;refillRate;currentTokens;lastRefillTime;constructor(e,t,n){this.maxTokens=e,this.refillRate=t,this.currentTokens=e,this.lastRefillTime=Date.now(),this.options=n}refillTokens(){let e=Date.now(),n=(e-this.lastRefillTime)/1e3*this.refillRate;this.currentTokens=Math.min(this.maxTokens,this.currentTokens+n),this.lastRefillTime=e}async waitUntilTokensAvailable(e){if(this.refillTokens(),this.currentTokens>=e){this.currentTokens-=e;return}return this.options?.debug&&console.log(_P.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)}};export{ai as AxACE,qa as AxACEOptimizedProgram,wc as AxAI,Ai as AxAIAnthropic,yi as AxAIAnthropicModel,sc as AxAIAnthropicVertexModel,ki as AxAIAzureOpenAI,Gi as AxAICohere,pc as AxAICohereEmbedModel,Ti as AxAICohereModel,Bi as AxAIDeepSeek,Mi as AxAIDeepSeekModel,qi as AxAIGoogleGemini,mo as AxAIGoogleGeminiEmbedModel,WA as AxAIGoogleGeminiEmbedTypes,po as AxAIGoogleGeminiModel,Bd as AxAIGoogleGeminiSafetyCategory,zd as AxAIGoogleGeminiSafetyThreshold,Ji as AxAIGrok,QA as AxAIGrokEmbedModels,Di as AxAIGrokModel,Vi as AxAIMistral,YA as AxAIMistralEmbedModels,Fi as AxAIMistralModel,Si as AxAIOpenAI,ft as AxAIOpenAIBase,Hn as AxAIOpenAIEmbedModel,Cr as AxAIOpenAIModel,Hi as AxAIOpenAIResponses,Cc as AxAIOpenAIResponsesBase,co as AxAIOpenAIResponsesModel,Ke as AxAIRefusalError,Ki as AxAIReka,Ni as AxAIRekaModel,_e as AxAIServiceAbortedError,It as AxAIServiceAuthenticationError,gt as AxAIServiceError,tt as AxAIServiceNetworkError,bn as AxAIServiceResponseError,Qe as AxAIServiceStatusError,kt as AxAIServiceStreamTerminatedError,yt as AxAIServiceTimeoutError,Wi as AxAIWebLLM,$i as AxAIWebLLMModel,gi as AxAgent,et as AxAgentClarificationError,sn as AxAgentContextMap,mi as AxAgentPlaybook,vt as AxAgentProtocolCompletionSignal,oi as AxAgentSharedRuntimeSession,sr as AxAssertionError,Ud as AxBalancer,Et as AxBaseAI,Pn as AxBaseOptimizer,Tc as AxBestOfN,Yi as AxBootstrapFewShot,on as AxContentProcessingError,bd as AxContextMetricsCollector,za as AxDefaultCostTracker,bp as AxDockerSession,Rp as AxEmbeddingAdapter,ET as AxEvalUtil,_n as AxEventBackpressureError,fo as AxEventContinuationNotFoundError,qe as AxEventInputError,ho as AxEventOutcomeUnknownError,Zi as AxEventRouteBuilder,Nc as AxEventRuntime,Xi as AxEventTargetBuilder,ro as AxFlow,Gt as AxFlowMermaidError,rt as AxFluentFieldType,ea as AxFunctionError,ta as AxFunctionProcessor,yr as AxGEPA,ci as AxGEPAComponentSelector,Ee as AxGen,pa as AxGenerateError,Ii as AxInMemoryBalancerStatsStore,ns as AxInMemoryEventStore,rs as AxInMemoryProgramStateStore,Kr as AxJSRuntime,Tu as AxJSRuntimePermission,El as AxMCPAppBridge,cs as AxMCPClient,ls as AxMCPDPoPProofFactory,xp as AxMCPEventSource,zs as AxMCPExecutionContext,$p as AxMCPHTTPSSETransport,ss as AxMCPHTTPStatusError,us as AxMCPOAuthJWTVerifier,qt as AxMCPParamHeaderSchemaError,Nn as AxMCPProtocolError,Np as AxMCPRecordingTransport,Lp as AxMCPReplayTransport,Ao as AxMCPStreamableHTTPTransport,_p as AxMCPStreambleHTTPTransport,Up as AxMCPWebSocketTransport,cp as AxManualEventClock,At as AxMediaNotSupportedError,jn as AxMemory,Yd as AxMockAIService,Qd as AxMultiServiceRouter,un as AxOptimizedProgramImpl,Yr as AxPlaybook,ar as AxProgram,ir as AxPromptTemplate,ep as AxProviderRouter,yp as AxPushEventSource,zp as AxRateLimiterTokenUsage,Pc as AxRefine,On as AxRefineError,Me as AxSignature,Is as AxSignatureBuilder,Gr as AxStopFunctionCallException,Rn as AxStreamingAssertionError,VT as AxStringUtil,ap as AxSynth,Fn as AxSystemEventClock,ip as AxTestPrompt,Ap as AxTimerEventSource,Hs as AxTokenLimitError,Bp as AxUCPClient,Fe as AxUCPHTTPMessageSignatureError,Co as AxUCPHTTPMessageVerifier,kr as AxUCPSchemaValidationError,ds as AxUCPSchemaValidator,Cp as AxUCPWebhookEventSource,Xy as agent,IT as ai,Ut as ax,xA as axAIAnthropicDefaultConfig,rI as axAIAnthropicVertexDefaultConfig,NI as axAIAzureOpenAIBestConfig,FI as axAIAzureOpenAICreativeConfig,$A as axAIAzureOpenAIDefaultConfig,_I as axAIAzureOpenAIFastConfig,QI as axAICohereCreativeConfig,ZA as axAICohereDefaultConfig,nT as axAIDeepSeekCodeConfig,eC as axAIDeepSeekDefaultConfig,cC as axAIGoogleGeminiDefaultConfig,mT as axAIGoogleGeminiDefaultCreativeConfig,tC as axAIGoogleGeminiLiveAudioDefaultConfig,ST as axAIGrokBestConfig,np as axAIGrokDefaultConfig,kT as axAIGrokVoiceDefaultConfig,gT as axAIMistralBestConfig,Jd as axAIMistralDefaultConfig,IA as axAIOpenAIAudioDefaultConfig,Nd as axAIOpenAIBestConfig,Ld as axAIOpenAICreativeConfig,lo as axAIOpenAIDefaultConfig,$d as axAIOpenAIFastConfig,Od as axAIOpenAIRealtimeDefaultConfig,_A as axAIOpenAIRealtimeTranscriptionDefaultConfig,hT as axAIOpenAIResponsesBestConfig,xT as axAIOpenAIResponsesCreativeConfig,bc as axAIOpenAIResponsesDefaultConfig,AT as axAIRekaBestConfig,CT as axAIRekaCreativeConfig,Rc as axAIRekaDefaultConfig,bT as axAIRekaFastConfig,vT as axAIWebLLMCreativeConfig,lC as axAIWebLLMDefaultConfig,yT as axAnalyzeChatPromptRequirements,uo as axAnalyzeRequestRequirements,is as axApplyMCPAuthentication,Pd as axApplyOpenAIChatAudioRequest,Ct as axAudioFormatFromMimeType,bA as axAudioInputFilename,CA as axAudioInputToBlob,Bt as axAudioMimeType,Ge as axBaseAIDefaultConfig,Ot as axBaseAIDefaultCreativeConfig,Eo as axBuildDistillerDefinition,Oo as axBuildExecutorDefinition,Tl as axBuildResponderDefinition,rb as axCheckMetricsHealth,so as axConcatBase64,tA as axCreateDefaultColorLogger,ey as axCreateDefaultOptimizerColorLogger,iS as axCreateDefaultOptimizerTextLogger,$k as axCreateDefaultTextLogger,Ha as axCreateFlowColorLogger,YS as axCreateFlowTextLogger,Hd as axCreateGeminiLiveAudioApi,pC as axCreateGrokRealtimeApi,zv as axCreateJSRuntime,vi as axCreateOpenAIRealtimeApi,QS as axDefaultFlowLogger,bm as axDefaultMetricsConfig,ja as axDefaultOptimizerLogger,ny as axDefaultOptimizerMetricsConfig,bS as axDeserializeOptimizedProgram,_o as axEmitUsageEvent,Ft as axEventErrorMessage,st as axEventId,es as axEventIdentityScope,hp as axEventMatches,xo as axEventScopedCorrelationKey,ts as axEventScopedDedupeKey,fp as axEventSizeBytes,En as axFetchJsonSpeech,Ci as axFetchMultipartTranscription,jI as axGetCompatibilityReport,BI as axGetFormatCompatibility,sb as axGetMetricsConfig,cS as axGetOptimizerMetricsConfig,GI as axGetProvidersWithMediaSupport,YI as axGetSupportedAIModels,fe as axGlobals,ac as axGoogleGeminiLiveAudioDefaults,Xt as axIsAudioOutputEnabled,nC as axIsGeminiLiveAudioModel,rp as axIsGrokVoiceModel,Id as axIsOpenAIChatAudioModel,lc as axIsOpenAIRealtimeModel,Kn as axIsOpenAIRealtimeTranscriptionModel,pP as axMCPAPIKeyAuthentication,Ol as axMCPAppToolMeta,dP as axMCPBasicAuthentication,uP as axMCPBearerAuthentication,Mp as axMCPBuildParamHeaders,vp as axMCPBuildRequestMeta,fP as axMCPChat,No as axMCPChildExecutionOptions,hP as axMCPDecodeHeaderValue,as as axMCPEncodeHeaderValue,tP as axMCPEventRoutes,Uc as axMCPFulfillInputRequests,mP as axMCPHMACAuthentication,IC as axMCPIsPlainHeaderValue,Gc as axMCPParamHeaderBindings,$c as axMCPServerInfoFromMeta,Tp as axMCPToolInputSchemaToFunctionSchema,Bs as axMCPToolVisibleTo,Vd as axMapGeminiLiveAudioPart,Ed as axMapOpenAIChatAudioDelta,Md as axMapOpenAIChatAudioResponse,Td as axMapOpenAIInputAudioPart,bt as axMergeChatAudioConfig,Fo as axMergeUsageContexts,io as axModelInfoAnthropic,Pi as axModelInfoCohere,Ei as axModelInfoDeepSeek,Oi as axModelInfoGoogleGemini,ji as axModelInfoGrok,_i as axModelInfoMistral,br as axModelInfoOpenAI,bi as axModelInfoOpenAIResponses,Li as axModelInfoReka,Ui as axModelInfoWebLLM,Wn as axNormalizeOpenAIUsage,RA as axNormalizeTranscriptionResponse,ao as axOpenAIChatAudioDefaults,er as axOptimizableValidators,_a as axPlaybookFailureSection,Zd as axProcessContentForProvider,fc as axResolveGeminiLiveAudioConfig,op as axResolveGrokRealtimeAudioConfig,Lt as axResolveMCPExecutionContext,TA as axResolveOpenAIChatAudioConfig,uc as axResolveOpenAIRealtimeAudioConfig,Mo as axRuntimePrimitives,jd as axScoreProvidersForRequest,Gd as axSelectOptimalProvider,ry as axSerializeOptimizedProgram,hc as axShouldUseGeminiLiveAudio,dC as axShouldUseGrokRealtime,Fd as axShouldUseOpenAIRealtime,Dp as axSignUCPRequest,Oe as axSpanAttributes,dn as axSpanEvents,GA as axUpdateBalancerRouteStats,ib as axUpdateMetricsConfig,aS as axUpdateOptimizerMetricsConfig,Lo as axValidateChatRequestMessage,Fl as axValidateChatResponseResult,gp as axValidateEventEnvelope,rC as axValidateGeminiLiveAudioInput,KA as axValidateProviderCapabilities,Mu as axWorkerRuntime,$T as bestOfN,bC as eventInput,JT as eventPath,yo as eventRoute,eP as eventRuntime,SC as eventTarget,q as f,gd as flow,db as fn,LT as optimize,US as playbook,UT as refine,KT as runAxEventStoreConformance,RS as s};
|
|
1325
1325
|
//# sourceMappingURL=index.js.map
|