@ax-llm/ax 25.3.0 → 25.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.cjs CHANGED
@@ -1,7 +1,7 @@
1
1
  Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});var e=Object.defineProperty,t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};let r=require("@opentelemetry/api");const i={snakeCaseIdentifier:(e=32)=>t=>{let n=t.trim();return n.length===0?`identifier must not be empty`:n.length>e?`identifier must be ≤ ${e} chars`:/^[a-z][a-z0-9_]*$/.test(n)?!0:`identifier must be snake_case (a-z, 0-9, _; starting with a letter)`},preservesPlaceholders:e=>t=>{for(let n of e)if(!t.includes(n))return`must preserve placeholder ${n}`;return!0},nonEmpty:()=>e=>e.trim().length>0||`value must not be empty`};function a(){if(globalThis.crypto)return globalThis.crypto;throw Error(`Web Crypto API not available. Requires modern Node.js, Deno, or a modern browser.`)}function o(){let e=a();if(typeof e.randomUUID==`function`)return e;throw Error(`Web Crypto API randomUUID support not available. Requires modern Node.js, Deno, or a modern browser.`)}function s(){let e=a();if(e.subtle)return e;throw Error(`Web Crypto API subtle.digest support not available. Requires modern Node.js, Deno, or a modern browser.`)}function c(){return o().randomUUID()}async function l(e){let t=new TextEncoder,n=typeof e==`string`?t.encode(e):e,r=await s().subtle.digest(`SHA-256`,n);return Array.from(new Uint8Array(r)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}const u=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),d=(e,t)=>e>>>t|e<<32-t;function f(e){let t=Math.ceil((e.length+9)/64)*64,n=new Uint8Array(t);n.set(e),n[e.length]=128;let r=new DataView(n.buffer),i=e.length*8;r.setUint32(t-8,Math.floor(i/4294967296)),r.setUint32(t-4,i>>>0);let a=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),o=/* @__PURE__ */ new Uint32Array(64);for(let e=0;e<t;e+=64){for(let t=0;t<16;t++)o[t]=r.getUint32(e+t*4);for(let e=16;e<64;e++){let t=o[e-15],n=o[e-2],r=d(t,7)^d(t,18)^t>>>3,i=d(n,17)^d(n,19)^n>>>10;o[e]=o[e-16]+r+o[e-7]+i}let t=a[0],n=a[1],i=a[2],s=a[3],c=a[4],l=a[5],f=a[6],p=a[7];for(let e=0;e<64;e++){let r=d(c,6)^d(c,11)^d(c,25),a=c&l^~c&f,m=p+r+a+u[e]+o[e]|0,h=(d(t,2)^d(t,13)^d(t,22))+(t&n^t&i^n&i)|0;p=f,f=l,l=c,c=s+m|0,s=i,i=n,n=t,t=m+h|0}a[0]+=t,a[1]+=n,a[2]+=i,a[3]+=s,a[4]+=c,a[5]+=l,a[6]+=f,a[7]+=p}let s=``;for(let e of a)s+=e.toString(16).padStart(8,`0`);return s}var p=class{data=``;update(e){return this.data+=e,this}digest(e){if(e!==`hex`)throw Error(`Only hex encoding is supported`);return f(new TextEncoder().encode(this.data))}async digestAsync(){return l(this.data)}};function m(e){if(e!==`sha256`)throw Error(`Only SHA-256 algorithm is supported`);return new p}function h(){return a()}function g(e,t){for(let n of t){let t=e.find(e=>e.id===n.id);t?(typeof n.function.name==`string`&&n.function.name.length>0&&(t.function.name+=n.function.name),typeof n.function.params==`string`&&n.function.params.length>0&&(t.function.params+=n.function.params),typeof n.function.params==`object`&&(t.function.params=n.function.params)):e.push(n)}}const _=(e,t,n,r)=>{n({name:`ChatRequestChatPrompt`,step:t,value:r?e.filter(e=>e.role!==`system`):[...e]})},v=(e,t)=>{e.results&&t({name:`ChatResponseResults`,value:e.results})};function y(e,t){let n=/* @__PURE__ */ new Map;for(let t of e)for(let e of t.results){if(!e)continue;let t=n.get(e.index);t?(e.content&&(t.content=(t.content??``)+e.content),e.thought&&(t.thought=(t.thought??``)+e.thought),e.images&&(t.images=[...t.images??[],...structuredClone(e.images)]),e.phase&&(t.phase=e.phase),e.finishReason&&(t.finishReason=e.finishReason),e.functionCalls&&(t.functionCalls?g(t.functionCalls,structuredClone(e.functionCalls)):t.functionCalls=structuredClone(e.functionCalls))):(t=structuredClone(e),n.set(e.index,t))}for(let e of n.values())t({name:`ChatResponseStreamingDoneResult`,index:e.index,value:e})}const b=(e,t)=>{t({name:`FunctionResults`,value:e})},x=(e,t,n,r)=>{r({name:`FunctionError`,index:t,fixingInstructions:n,error:e})},S=(e,t,n,r)=>{r({name:`ValidationError`,index:t,fixingInstructions:n,error:e})},C=(e,t,n)=>{n({name:`RefusalError`,index:t,error:e})},w=(e,t,n)=>{n({name:`EmbedRequest`,embedModel:t,value:e})},T=(e,t)=>{let n=e.slice(0,3).map(e=>({length:e.length,sample:e.slice(0,5),truncated:e.length>5}));t({name:`EmbedResponse`,totalEmbeddings:e.length,value:n})},E=(e,t,n,r)=>{r({name:`ResultPickerUsed`,sampleCount:e,selectedIndex:t,latency:n})},D=e=>{let t={};for(let[n,r]of Object.entries(e))if(r!=null){let e=String(r);t[n]=e.length>100?e.substring(0,100):e}return t},O=(...e)=>{let t={};for(let n of e)n&&Object.assign(t,n);return t};let k=/* @__PURE__ */ new WeakMap;const A=e=>{if(!e)return;let t=k.get(e);if(t)return t;try{let t=M(e);return k.set(e,t),t}catch{return}},j=e=>new Proxy(e,{get(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?(...t)=>{try{return Reflect.apply(n,e,t)}catch{return}}:n}}),M=e=>{let t={latencyHistogram:e.createHistogram(`ax_llm_request_duration_ms`,{description:`Duration of LLM requests in milliseconds`,unit:`ms`}),errorCounter:e.createCounter(`ax_llm_errors_total`,{description:`Total number of LLM request errors`}),requestCounter:e.createCounter(`ax_llm_requests_total`,{description:`Total number of LLM requests`}),tokenCounter:e.createCounter(`ax_llm_tokens_total`,{description:`Total number of LLM tokens consumed`}),inputTokenCounter:e.createCounter(`ax_llm_input_tokens_total`,{description:`Total number of input/prompt tokens consumed`}),outputTokenCounter:e.createCounter(`ax_llm_output_tokens_total`,{description:`Total number of output/completion tokens generated`}),errorRateGauge:e.createGauge(`ax_llm_error_rate`,{description:`Current error rate as a percentage (0-100)`}),meanLatencyGauge:e.createGauge(`ax_llm_mean_latency_ms`,{description:`Mean latency of LLM requests in milliseconds`,unit:`ms`}),p95LatencyGauge:e.createGauge(`ax_llm_p95_latency_ms`,{description:`95th percentile latency of LLM requests in milliseconds`,unit:`ms`}),p99LatencyGauge:e.createGauge(`ax_llm_p99_latency_ms`,{description:`99th percentile latency of LLM requests in milliseconds`,unit:`ms`}),streamingRequestsCounter:e.createCounter(`ax_llm_streaming_requests_total`,{description:`Total number of streaming LLM requests`}),functionCallsCounter:e.createCounter(`ax_llm_function_calls_total`,{description:`Total number of function/tool calls made`}),functionCallLatencyHistogram:e.createHistogram(`ax_llm_function_call_latency_ms`,{description:`Latency of function calls in milliseconds`,unit:`ms`}),requestSizeHistogram:e.createHistogram(`ax_llm_request_size_bytes`,{description:`Size of LLM request payloads in bytes`,unit:`By`}),responseSizeHistogram:e.createHistogram(`ax_llm_response_size_bytes`,{description:`Size of LLM response payloads in bytes`,unit:`By`}),temperatureGauge:e.createGauge(`ax_llm_temperature_gauge`,{description:`Temperature setting used for LLM requests`}),maxTokensGauge:e.createGauge(`ax_llm_max_tokens_gauge`,{description:`Maximum tokens setting used for LLM requests`}),estimatedCostCounter:e.createCounter(`ax_llm_estimated_cost_total`,{description:`Estimated cost of LLM requests in USD`,unit:`$`}),promptLengthHistogram:e.createHistogram(`ax_llm_prompt_length_chars`,{description:`Length of prompts in characters`}),contextWindowUsageGauge:e.createGauge(`ax_llm_context_window_usage_ratio`,{description:`Context window utilization ratio (0-1)`}),timeoutsCounter:e.createCounter(`ax_llm_timeouts_total`,{description:`Total number of timed out LLM requests`}),abortsCounter:e.createCounter(`ax_llm_aborts_total`,{description:`Total number of aborted LLM requests`}),thinkingBudgetUsageCounter:e.createCounter(`ax_llm_thinking_budget_usage_total`,{description:`Total thinking budget tokens used`}),multimodalRequestsCounter:e.createCounter(`ax_llm_multimodal_requests_total`,{description:`Total number of multimodal requests (with images/audio)`}),cacheReadTokensCounter:e.createCounter(`ax_llm_cache_read_tokens_total`,{description:`Total number of tokens read from cache (prompt caching)`}),cacheWriteTokensCounter:e.createCounter(`ax_llm_cache_write_tokens_total`,{description:`Total number of tokens written to cache (prompt caching)`})};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,j(t)]))},N=(e,t,n,r,i,a)=>{try{if(e.latencyHistogram){let o=D({operation:t,ai_service:r,...i?{model:i}:{},...a});e.latencyHistogram.record(n,o)}}catch(e){console.warn(`Failed to record latency metric:`,e)}},P=(e,t,n,r,i,a,o,s)=>{let c={operation:t,ai_service:a,...o?{model:o}:{},...s};e.meanLatencyGauge&&e.meanLatencyGauge.record(n,c),e.p95LatencyGauge&&e.p95LatencyGauge.record(r,c),e.p99LatencyGauge&&e.p99LatencyGauge.record(i,c)},F=(e,t,n,r,i)=>{try{if(e.errorCounter){let a=D({operation:t,ai_service:n,...r?{model:r}:{},...i});e.errorCounter.add(1,a)}}catch(e){console.warn(`Failed to record error metric:`,e)}},I=(e,t,n,r,i,a)=>{e.errorRateGauge&&e.errorRateGauge.record(n*100,{operation:t,ai_service:r,...i?{model:i}:{},...a})},L=(e,t,n,r,i)=>{e.requestCounter&&e.requestCounter.add(1,{operation:t,ai_service:n,...r?{model:r}:{},...i})},R=(e,t,n,r,i,a)=>{try{let o=D({ai_service:r,...i?{model:i}:{},...a});e.tokenCounter&&e.tokenCounter.add(n,{token_type:t,...o}),t===`input`&&e.inputTokenCounter&&e.inputTokenCounter.add(n,o),t===`output`&&e.outputTokenCounter&&e.outputTokenCounter.add(n,o)}catch(e){console.warn(`Failed to record token metric:`,e)}},ee=(e,t,n,r,i,a)=>{n&&e.streamingRequestsCounter&&e.streamingRequestsCounter.add(1,{operation:t,ai_service:r,...i?{model:i}:{},...a})},te=(e,t,n,r,i,a)=>{let o={function_name:t,...r?{ai_service:r}:{},...i?{model:i}:{},...a};e.functionCallsCounter&&e.functionCallsCounter.add(1,o),n&&e.functionCallLatencyHistogram&&e.functionCallLatencyHistogram.record(n,o)},z=(e,t,n,r,i,a)=>{e.requestSizeHistogram&&e.requestSizeHistogram.record(n,{operation:t,ai_service:r,...i?{model:i}:{},...a})},ne=(e,t,n,r,i,a)=>{e.responseSizeHistogram&&e.responseSizeHistogram.record(n,{operation:t,ai_service:r,...i?{model:i}:{},...a})},re=(e,t,n,r,i,a)=>{let o={...r?{ai_service:r}:{},...i?{model:i}:{},...a};t!==void 0&&e.temperatureGauge&&e.temperatureGauge.record(t,o),n!==void 0&&e.maxTokensGauge&&e.maxTokensGauge.record(n,o)},ie=(e,t,n,r,i,a)=>{e.estimatedCostCounter&&e.estimatedCostCounter.add(n,{operation:t,ai_service:r,...i?{model:i}:{},...a})},B=(e,t,n,r,i)=>{e.promptLengthHistogram&&e.promptLengthHistogram.record(t,{ai_service:n,...r?{model:r}:{},...i})},ae=(e,t,n,r,i)=>{e.contextWindowUsageGauge&&e.contextWindowUsageGauge.record(t,{ai_service:n,...r?{model:r}:{},...i})},V=(e,t,n,r,i)=>{e.timeoutsCounter&&e.timeoutsCounter.add(1,{operation:t,ai_service:n,...r?{model:r}:{},...i})},oe=(e,t,n,r,i)=>{e.abortsCounter&&e.abortsCounter.add(1,{operation:t,ai_service:n,...r?{model:r}:{},...i})},se=(e,t,n,r,i)=>{e.thinkingBudgetUsageCounter&&e.thinkingBudgetUsageCounter.add(t,{ai_service:n,...r?{model:r}:{},...i})},ce=(e,t,n,r,i,a)=>{(t||n)&&e.multimodalRequestsCounter&&e.multimodalRequestsCounter.add(1,{ai_service:r,has_images:t.toString(),has_audio:n.toString(),...i?{model:i}:{},...a})},le=(e,t,n,r,i,a)=>{try{if(n<=0)return;let o=D({ai_service:r,...i?{model:i}:{},...a});t===`read`&&e.cacheReadTokensCounter&&e.cacheReadTokensCounter.add(n,o),t===`write`&&e.cacheWriteTokensCounter&&e.cacheWriteTokensCounter.add(n,o)}catch(e){console.warn(`Failed to record cache token metric:`,e)}},H={signatureStrict:!0,tracer:void 0,meter:void 0,rateLimiter:void 0,logger:void 0,optimizerLogger:void 0,debug:void 0,abortSignal:void 0,customLabels:void 0,onUsage:void 0,cachingFunction:void 0,functionResultFormatter:(e=>typeof e==`string`?e:e==null?``:JSON.stringify(e,null,2))},ue={enabled:!0,enabledCategories:[`generation`,`streaming`,`functions`,`errors`,`performance`],maxLabelLength:100,samplingRate:1};let de=/* @__PURE__ */ new WeakMap,U;const fe=e=>{let t=e??H.meter;if(!t)return;let n=de.get(t);if(!n){try{n=he(t)}catch{return}de.set(t,n)}return t===H.meter&&(U=n),n},pe=e=>new Proxy(e,{get(e,t){let n=Reflect.get(e,t,e);return typeof n==`function`?(...t)=>{try{return Reflect.apply(n,e,t)}catch{return}}:n}}),me=()=>{let e=[];return H.meter||e.push(`Global meter not initialized`),!U&&H.meter&&e.push(`Metrics instruments not created despite available meter`),{healthy:e.length===0,issues:e}},he=e=>{let t={generationLatencyHistogram:e.createHistogram(`ax_gen_generation_duration_ms`,{description:`End-to-end duration of AxGen generation requests`,unit:`ms`}),generationRequestsCounter:e.createCounter(`ax_gen_generation_requests_total`,{description:`Total number of AxGen generation requests`}),generationErrorsCounter:e.createCounter(`ax_gen_generation_errors_total`,{description:`Total number of failed AxGen generations`}),multiStepGenerationsCounter:e.createCounter(`ax_gen_multistep_generations_total`,{description:`Total number of generations that required multiple steps`}),stepsPerGenerationHistogram:e.createHistogram(`ax_gen_steps_per_generation`,{description:`Number of steps taken per generation`}),maxStepsReachedCounter:e.createCounter(`ax_gen_max_steps_reached_total`,{description:`Total number of generations that hit max steps limit`}),validationErrorsCounter:e.createCounter(`ax_gen_validation_errors_total`,{description:`Total number of validation errors encountered`}),errorCorrectionAttemptsHistogram:e.createHistogram(`ax_gen_error_correction_attempts`,{description:`Number of error correction attempts per generation`}),errorCorrectionSuccessCounter:e.createCounter(`ax_gen_error_correction_success_total`,{description:`Total number of successful error corrections`}),errorCorrectionFailureCounter:e.createCounter(`ax_gen_error_correction_failure_total`,{description:`Total number of failed error corrections`}),maxRetriesReachedCounter:e.createCounter(`ax_gen_max_retries_reached_total`,{description:`Total number of generations that hit max retries limit`}),functionsEnabledGenerationsCounter:e.createCounter(`ax_gen_functions_enabled_generations_total`,{description:`Total number of generations with functions enabled`}),functionCallStepsCounter:e.createCounter(`ax_gen_function_call_steps_total`,{description:`Total number of steps that included function calls`}),functionsExecutedPerGenerationHistogram:e.createHistogram(`ax_gen_functions_executed_per_generation`,{description:`Number of unique functions executed per generation`}),functionErrorCorrectionCounter:e.createCounter(`ax_gen_function_error_correction_total`,{description:`Total number of function-related error corrections`}),fieldProcessorsExecutedCounter:e.createCounter(`ax_gen_field_processors_executed_total`,{description:`Total number of field processors executed`}),streamingFieldProcessorsExecutedCounter:e.createCounter(`ax_gen_streaming_field_processors_executed_total`,{description:`Total number of streaming field processors executed`}),streamingGenerationsCounter:e.createCounter(`ax_gen_streaming_generations_total`,{description:`Total number of streaming generations`}),streamingDeltasEmittedCounter:e.createCounter(`ax_gen_streaming_deltas_emitted_total`,{description:`Total number of streaming deltas emitted`}),streamingFinalizationLatencyHistogram:e.createHistogram(`ax_gen_streaming_finalization_duration_ms`,{description:`Duration of streaming response finalization`,unit:`ms`}),samplesGeneratedHistogram:e.createHistogram(`ax_gen_samples_generated`,{description:`Number of samples generated per request`}),resultPickerUsageCounter:e.createCounter(`ax_gen_result_picker_usage_total`,{description:`Total number of times result picker was used`}),resultPickerLatencyHistogram:e.createHistogram(`ax_gen_result_picker_duration_ms`,{description:`Duration of result picker execution`,unit:`ms`}),inputFieldsGauge:e.createGauge(`ax_gen_input_fields`,{description:`Number of input fields in signature`}),outputFieldsGauge:e.createGauge(`ax_gen_output_fields`,{description:`Number of output fields in signature`}),examplesUsedGauge:e.createGauge(`ax_gen_examples_used`,{description:`Number of examples used in generation`}),demosUsedGauge:e.createGauge(`ax_gen_demos_used`,{description:`Number of demos used in generation`}),promptRenderLatencyHistogram:e.createHistogram(`ax_gen_prompt_render_duration_ms`,{description:`Duration of prompt template rendering`,unit:`ms`}),extractionLatencyHistogram:e.createHistogram(`ax_gen_extraction_duration_ms`,{description:`Duration of value extraction from responses`,unit:`ms`}),stateCreationLatencyHistogram:e.createHistogram(`ax_gen_state_creation_duration_ms`,{description:`Duration of state creation for multiple samples`,unit:`ms`}),memoryUpdateLatencyHistogram:e.createHistogram(`ax_gen_memory_update_duration_ms`,{description:`Duration of memory updates during generation`,unit:`ms`})};return Object.fromEntries(Object.entries(t).map(([e,t])=>[e,pe(t)]))};let ge=ue;const _e=e=>{ge={...ge,...e}},ve=()=>({...ge}),ye=e=>{let t={};for(let[n,r]of Object.entries(e))if(r!=null){let e=String(r),i=ge.maxLabelLength;t[n]=e.length>i?e.substring(0,i):e}return t},be=(e,t,n,r,i,a,o)=>{try{let s=ye({success:n.toString(),...r?{signature:r}:{},...i?{ai_service:i}:{},...a?{model:a}:{},...o});e.generationLatencyHistogram&&e.generationLatencyHistogram.record(t,s),e.generationRequestsCounter&&e.generationRequestsCounter.add(1,s),!n&&e.generationErrorsCounter&&e.generationErrorsCounter.add(1,s)}catch(e){console.warn(`Failed to record generation metric:`,e)}},xe=(e,t,n,r,i)=>{try{let a=ye({...r?{signature:r}:{},...i});t>1&&e.multiStepGenerationsCounter&&e.multiStepGenerationsCounter.add(1,a),e.stepsPerGenerationHistogram&&e.stepsPerGenerationHistogram.record(t,a),t>=n&&e.maxStepsReachedCounter&&e.maxStepsReachedCounter.add(1,a)}catch(e){console.warn(`Failed to record multi-step metric:`,e)}},Se=(e,t,n,r)=>{try{let i=ye({error_type:t,...n?{signature:n}:{},...r});t===`validation`&&e.validationErrorsCounter&&e.validationErrorsCounter.add(1,i)}catch(e){console.warn(`Failed to record validation error metric:`,e)}},Ce=(e,t,n)=>{try{let r=ye({error_type:`refusal`,...t?{signature:t}:{},...n});e.validationErrorsCounter&&e.validationErrorsCounter.add(1,r)}catch(e){console.warn(`Failed to record refusal error metric:`,e)}},we=(e,t,n,r,i,a)=>{try{let o=ye({success:n.toString(),...i?{signature:i}:{},...a});e.errorCorrectionAttemptsHistogram&&e.errorCorrectionAttemptsHistogram.record(t,o),n&&e.errorCorrectionSuccessCounter&&e.errorCorrectionSuccessCounter.add(1,o),n||(e.errorCorrectionFailureCounter&&e.errorCorrectionFailureCounter.add(1,o),t>=r&&e.maxRetriesReachedCounter&&e.maxRetriesReachedCounter.add(1,o))}catch(e){console.warn(`Failed to record error correction metric:`,e)}},Te=(e,t,n,r,i=!1,a,o)=>{try{let s=ye({functions_enabled:t.toString(),had_function_calls:r.toString(),...a?{signature:a}:{},...o});t&&e.functionsEnabledGenerationsCounter&&e.functionsEnabledGenerationsCounter.add(1,s),r&&e.functionCallStepsCounter&&e.functionCallStepsCounter.add(1,s),n>0&&e.functionsExecutedPerGenerationHistogram&&e.functionsExecutedPerGenerationHistogram.record(n,s),i&&e.functionErrorCorrectionCounter&&e.functionErrorCorrectionCounter.add(1,s)}catch(e){console.warn(`Failed to record function calling metric:`,e)}},Ee=(e,t,n,r,i)=>{try{let a=ye({...r?{signature:r}:{},...i});t>0&&e.fieldProcessorsExecutedCounter&&e.fieldProcessorsExecutedCounter.add(t,a),n>0&&e.streamingFieldProcessorsExecutedCounter&&e.streamingFieldProcessorsExecutedCounter.add(n,a)}catch(e){console.warn(`Failed to record field processing metric:`,e)}},De=(e,t,n,r,i,a)=>{try{let o=ye({is_streaming:t.toString(),...i?{signature:i}:{},...a});t&&e.streamingGenerationsCounter&&e.streamingGenerationsCounter.add(1,o),n>0&&e.streamingDeltasEmittedCounter&&e.streamingDeltasEmittedCounter.add(n,o),r&&e.streamingFinalizationLatencyHistogram&&e.streamingFinalizationLatencyHistogram.record(r,o)}catch(e){console.warn(`Failed to record streaming metric:`,e)}},Oe=(e,t,n,r,i,a)=>{try{let o=ye({result_picker_used:n.toString(),...i?{signature:i}:{},...a});e.samplesGeneratedHistogram&&e.samplesGeneratedHistogram.record(t,o),n&&e.resultPickerUsageCounter&&e.resultPickerUsageCounter.add(1,o),r&&e.resultPickerLatencyHistogram&&e.resultPickerLatencyHistogram.record(r,o)}catch(e){console.warn(`Failed to record samples metric:`,e)}},ke=(e,t,n,r,i,a,o)=>{try{let s=ye({...a?{signature:a}:{},...o});e.inputFieldsGauge&&e.inputFieldsGauge.record(t,s),e.outputFieldsGauge&&e.outputFieldsGauge.record(n,s),e.examplesUsedGauge&&e.examplesUsedGauge.record(r,s),e.demosUsedGauge&&e.demosUsedGauge.record(i,s)}catch(e){console.warn(`Failed to record signature complexity metrics:`,e)}},Ae=(e,t,n,r,i)=>{try{let a=ye({metric_type:t,...r?{signature:r}:{},...i});switch(t){case`prompt_render`:e.promptRenderLatencyHistogram&&e.promptRenderLatencyHistogram.record(n,a);break;case`extraction`:e.extractionLatencyHistogram&&e.extractionLatencyHistogram.record(n,a);break;case`state_creation`:e.stateCreationLatencyHistogram&&e.stateCreationLatencyHistogram.record(n,a);break;case`memory_update`:e.memoryUpdateLatencyHistogram&&e.memoryUpdateLatencyHistogram.record(n,a)}}catch(e){console.warn(`Failed to record performance metric:`,e)}},je=e=>{let t=(()=>{switch(e?.name){case`string`:return`string`;case`number`:return`number`;case`boolean`:return`boolean`;case`date`:return`date (YYYY-MM-DD, e.g. 2024-05-09)`;case`datetime`:return`datetime (ISO 8601 with timezone, e.g. 2024-05-09T14:30:00Z)`;case`dateRange`:return`date range ({ "start": "YYYY-MM-DD", "end": "YYYY-MM-DD" })`;case`datetimeRange`:return`datetime range ({ "start": "2024-05-09T14:30:00Z", "end": "2024-05-09T15:30:00Z" })`;case`json`:return`JSON object`;case`class`:return`classification class`;case`code`:return`code`;case`object`:return`object`;default:return`string`}})();return e?.isArray?`array of ${t}s`:t};var W=class extends Error{constructor(e){super(e),this.name=`ValidationError`}getFixingInstructions=()=>[{name:`outputError`,title:`Invalid Field`,description:this.message}];toString(){return`${this.name}: ${this.message}`}[Symbol.for(`nodejs.util.inspect.custom`)](e,t){return this.toString()}};const Me=e=>new W(`Required field not found: ${e.map(e=>`'${e.title}' (${je(e.type)})`).join(`, `)}. Add a line starting with the exact label followed by a colon (e.g., "${e[0]?.title}:") and then provide a valid ${je(e[0]?.type)} value. Keep the output concise and avoid unrelated text.`),Ne=e=>new W(`Expected (Required) field not found: '${e.title}'. Begin a new section with "${e.title}:" and then provide a valid ${je(e.type)} value directly after.`),Pe=e=>new W(`Required field is missing: '${e.title}'. After the "${e.title}:" label, provide a non-empty ${je(e.type)}. Do not use null, undefined, or leave it blank.`),Fe=(e,t)=>new W(`Invalid JSON: ${t} in field '${e.title}'. Return only valid JSON. Prefer a fenced code block containing a single JSON object or array with no trailing text.`),Ie=(e,t)=>new W(`Invalid Array: ${t} for '${e.title}'. Provide a JSON array of ${je(e.type)} items (e.g., [ ... ]). Markdown lists are also accepted if each item is on its own line starting with a hyphen.`),Le=(e,t,n)=>new W(`Field '${e.title}' has an invalid value '${t}': ${n}. Provide a ${je(e.type)}. Ensure formatting exactly matches the expected type.`),Re=(e,t,n)=>new W(`Invalid date for '${e.title}': ${n}. Use the exact format YYYY-MM-DD (e.g., 2024-05-09). You provided: ${t}.`),ze=(e,t,n)=>new W(`Invalid date/time for '${e.title}': ${n}. Prefer ISO 8601 with an explicit timezone, e.g. 2024-05-09T14:30:00Z or 2024-05-09T14:30:00-07:00. Legacy values like "2024-05-09 14:30 America/New_York" are also accepted. You provided: ${t}.`),Be=(e,t,n)=>new W(`Invalid date range for '${e.title}': ${n}. Prefer JSON like {"start":"2024-05-09","end":"2024-05-12"} or an interval like 2024-05-09/2024-05-12. You provided: ${t}.`),Ve=(e,t,n)=>new W(`Invalid date/time range for '${e.title}': ${n}. Prefer JSON like {"start":"2024-05-09T14:30:00Z","end":"2024-05-09T15:30:00Z"} or an ISO interval like 2024-05-09T14:30:00Z/2024-05-09T15:30:00Z. You provided: ${t}.`),He=(e,t,n)=>new W(`Invalid URL for '${e.title}': ${n}. Use a valid URL format (e.g., https://example.com). You provided: ${t}.`),Ue=(e,t,n,r)=>{let i=`Field '${e.title}' failed validation: `;return n===`minLength`?i+=`String must be at least ${r} characters long. You provided: "${t}" (${t.length} characters).`:n===`maxLength`?i+=`String must be at most ${r} characters long. You provided: "${t}" (${t.length} characters).`:n===`pattern`?i+=`String must match pattern /${r}/. You provided: "${t}".`:n===`format`&&(i+=`String must be a ${r}. You provided: "${t}".`),new W(i)},We=(e,t,n,r)=>{let i=`Field '${e.title}' failed validation: `;return n===`minimum`?i+=`Number must be at least ${r}. You provided: ${t}.`:n===`maximum`&&(i+=`Number must be at most ${r}. You provided: ${t}.`),new W(i)},Ge=({error:e,errCount:t,debug:n,logger:r,metricsInstruments:i,signatureName:a,span:o,customLabels:s})=>{let c=e.getFixingInstructions();if(n&&r){let n=c?.map(e=>e.title).join(`, `)??``;S(e,t,n,r)}return i&&Se(i,`validation`,a,s),o&&o.addEvent(`validation.error`,{message:e.toString(),fixing_instructions:c?.map(e=>e.title).join(`, `)??``}),c},Ke=({error:e,errCount:t,debug:n,logger:r,metricsInstruments:i,signatureName:a,span:o,customLabels:s})=>{n&&r&&C(e,t,r),i&&Ce(i,a,s),o&&o.addEvent(`refusal.error`,{message:e.toString()})};var qe=class extends Error{fieldPath;provenance;constructor(e,t){super(`Decision provider ${t.provider} refused question "${e}"`),this.fieldPath=e,this.provenance=t,this.name=`AxDecisionRefusalError`}};function Je(e){let t=e.name??e.type;if(e.evidence!==void 0){if(![`boolean`,`class`,`score`].includes(t??``))throw Error(`Evidence requires a boolean, class or score field`);if(Object.keys(e.evidence).some(e=>e!==`threshold`&&e!==`onRefusal`))throw Error(`Unknown evidence option`);let n=e.evidence.threshold;if(n!==void 0&&(t!==`boolean`||typeof n!=`number`||!Number.isFinite(n)||n<0||n>1))throw Error(`threshold requires a boolean field and a finite value in [0, 1]`);if(e.evidence.onRefusal!==void 0&&![`throw`,`return`].includes(e.evidence.onRefusal))throw Error(`onRefusal must be throw or return`)}if(t===`score`&&(!e.options||e.options.length<2||e.options.length>10||e.options.some(e=>typeof e!=`string`||!e.trim())||new Set(e.options).size!==e.options.length))throw Error(`Score requires 2–10 distinct, nonempty ordered rubric labels`)}function Ye(e){return e.type?.evidence!==void 0||e.type?.name===`score`}function Xe(e){return e.some(e=>Ye(e)||e.type?.fields&&Xe(Qe(e.type.fields)))}function Ze(e){let t=e.filter(Ye).map(e=>[e.name,{type:e.type.name,options:e.type.options,evidence:e.type.evidence,isArray:e.type.isArray,isOptional:e.isOptional}]);return t.length?Object.fromEntries(t):void 0}function Qe(e){return Object.entries(e).map(([e,t])=>({name:e,description:t.description,isOptional:t.isOptional,type:{...t,name:t.type,options:t.options?[...t.options]:void 0}}))}function $e(e,t){if(!e||typeof e!=`object`||Array.isArray(e))throw new W(`Invalid decision evidence for ${t}: expected an object`);return e}function et(e,t){if(typeof e!=`number`||!Number.isFinite(e)||e<0||e>1)throw new W(`Invalid probability for ${t}`);return e}function tt(e,t,n){let r=$e(e,n);if(Object.keys(r).length!==t.length||t.some(e=>!Object.hasOwn(r,e)))throw new W(`Decision distribution for ${n} must cover exactly its declared options`);let i=Object.fromEntries(t.map(e=>[e,et(r[e],`${n}.${e}`)])),a=Object.values(i).reduce((e,t)=>e+t,0);if(Math.abs(a-1)>.01+2**-52*t.length)throw new W(`Decision probabilities for ${n} must sum to one`);return i}function nt(e,t,n,r=``){for(let i of e){let e=i.type,a=t[i.name];if(!e||a===void 0||a===null&&i.isOptional)continue;let o=(t,r)=>{if(!Ye(i))return e.fields&&t&&typeof t==`object`&&!Array.isArray(t)&&nt(Qe(e.fields),t,n,r),t;let a=$e(t,r),o=n.native?.[r],s=a.status===`refused`?[`status`]:[e.name===`boolean`?`probability`:`probabilities`,...e.evidence?.onRefusal===`return`?[`status`]:[]];if(Object.keys(a).some(e=>!s.includes(e))||n.provenance.source!==`native`&&e.evidence?.onRefusal===`return`&&a.status!==`answered`&&a.status!==`refused`)throw new W(`Invalid decision evidence shape for ${r}`);if(n.provenance.source===`native`&&!o)throw new W(`Missing native decision for ${r}`);if(n.provenance.source===`native`?o?.refused===!0:a.status===`refused`){if(e.evidence?.onRefusal!==`return`)throw new qe(r,n.provenance);return{status:`refused`,provenance:n.provenance}}let c;if(e.name===`boolean`){let t=et(a.probability,r),i=e.evidence?.threshold??.5;c={value:t>=i,probability:t,threshold:i,provenance:n.provenance}}else{let t=e.name===`score`?e.options.map((e,t)=>String(t)):e.options,i=tt(e.name===`score`&&Array.isArray(a.probabilities)?Object.fromEntries(a.probabilities.map((e,t)=>[String(t),e])):a.probabilities,t,r),s;if(n.provenance.source===`native`&&o?.value!==void 0)s=o.value;else if(e.name===`score`){let e=Object.values(i).reduce((e,t)=>e+t,0);s=t.reduce((e,t,n)=>e+n*i[t],0)/e}else s=t.reduce((e,t)=>i[t]>i[e]?t:e,t[0]);if(e.name===`score`){if(typeof s!=`number`||!Number.isFinite(s)||s<0||s>e.options.length-1)throw new W(`Invalid score for ${r}`);if(!e.evidence)return s;c={value:s,levels:[...e.options],probabilities:t.map(e=>i[e]),provenance:n.provenance}}else{if(typeof s!=`string`||!t.includes(s))throw new W(`Invalid class choice for ${r}`);c={value:s,probabilities:i,provenance:n.provenance}}n.provenance.source===`native`&&o?.confidence!==void 0&&(c.confidence=et(o.confidence,r))}return e.evidence?.onRefusal===`return`?{status:`answered`,...c}:c},s=r?`${r}.${i.name}`:i.name;if(e.isArray&&!Array.isArray(a))throw new W(`Expected decision array for ${s}`);t[i.name]=e.isArray?a.map((e,t)=>o(e,`${s}[${t}]`)):o(a,s)}}function rt(e){let t={type:`number`,minimum:0,maximum:1},n=e.name===`boolean`?{probability:t}:{probabilities:e.name===`score`?{type:`array`,items:t,minItems:e.options.length,maxItems:e.options.length}:{type:`object`,properties:Object.fromEntries(e.options.map(e=>[e,t])),required:[...e.options],additionalProperties:!1}},r={type:`object`,properties:n,required:Object.keys(n),additionalProperties:!1};return e.evidence?.onRefusal===`return`?{anyOf:[{...r,properties:{status:{type:`string`,enum:[`answered`]},...n},required:[`status`,...r.required]},{type:`object`,properties:{status:{type:`string`,enum:[`refused`]}},required:[`status`],additionalProperties:!1}]}:r}function it(e,t){let n={...t};for(let t of e){let e=t.type;if(!e||!(t.name in n))continue;let r=n=>{if(!n||typeof n!=`object`||Array.isArray(n))return n;if(!Ye(t))return e.fields?it(Qe(e.fields),n):n;let r=n;if(r.status===`refused`)return{status:`refused`};let i=e.name===`boolean`?`probability`:`probabilities`;return{[i]:r[i],...e.evidence?.onRefusal===`return`?{status:`answered`}:{}}},i=n[t.name];n[t.name]=e.isArray&&Array.isArray(i)?i.map(r):r(i)}return n}function at(e){let t=e.filter(e=>!e.isInternal&&e.type?.valueDescriptions&&Object.keys(e.type.valueDescriptions).length>0).map(e=>[e.name,{description:e.description,valueDescriptions:{...e.type.valueDescriptions}}]);return t.length?Object.fromEntries(t):void 0}function ot(e,t,n,r=e){if(t===void 0)return;if(!t||typeof t!=`object`||Array.isArray(t)||e!==`boolean`&&e!==`class`)throw Error(`Field "${r}": value descriptions require a boolean or class field`);let i=e===`boolean`?[`true`,`false`]:n??[];for(let[e,n]of Object.entries(t)){if(!i.includes(e))throw Error(`Field "${r}": unknown described value "${e}"`);if(typeof n!=`string`||!n.trim())throw Error(`Field "${r}": description for "${e}" must be a nonempty string`)}}function st(e){return(e.name===`boolean`?[`true`,`false`]:e.options??[]).flatMap(t=>e.valueDescriptions&&Object.hasOwn(e.valueDescriptions,t)?[[t,e.valueDescriptions[t]]]:[])}function ct(e){let t=e.type?st(e.type):[];return t.length?[e.description,...t.map(([e,t])=>`${e}: ${t}`)].filter(e=>e!==void 0&&e!==``).join(`
2
2
  `):e.description}function lt(e,t=``){return Object.entries(e??{}).flatMap(([e,n])=>{let r=t?`${t}.${e}`:e;return[...st({...n,name:n.type}).map(([e,t])=>`${r} = ${e}: ${t}`),...lt(n.fields,r)]})}function ut(e,t){if(!t)return e;let n=[];if(t.format===`email`&&n.push(`Must be a valid email address format`),(t.format===`uri`||t.format===`url`||t.name===`url`)&&n.push(`Must be a valid URL format`),(t.name===`string`||t.name===`code`||t.name===`url`||t.name===`date`||t.name===`dateRange`||t.name===`datetime`||t.name===`datetimeRange`)&&(t.minLength!==void 0&&t.maxLength!==void 0?n.push(`Minimum length: ${t.minLength} characters, maximum length: ${t.maxLength} characters`):t.minLength===void 0?t.maxLength!==void 0&&n.push(`Maximum length: ${t.maxLength} characters`):n.push(`Minimum length: ${t.minLength} characters`)),t.name===`number`&&(t.minimum!==void 0&&t.maximum!==void 0?n.push(`Minimum value: ${t.minimum}, maximum value: ${t.maximum}`):t.minimum===void 0?t.maximum!==void 0&&n.push(`Maximum value: ${t.maximum}`):n.push(`Minimum value: ${t.minimum}`)),t.pattern!==void 0){if(!t.patternDescription)throw Error(`Field with pattern '${t.pattern}' must include a patternDescription to explain the pattern to the LLM`);n.push(t.patternDescription)}if(t.name===`date`&&n.push(`Format: YYYY-MM-DD`),t.name===`dateRange`&&n.push(`Format: JSON object with start and end dates, or YYYY-MM-DD/YYYY-MM-DD`),t.name===`datetime`&&n.push(`Format: ISO 8601 date-time`),t.name===`datetimeRange`&&n.push(`Format: JSON object with start and end ISO 8601 date-times, or ISO interval start/end`),n.length===0)return e;let r=n.join(`. `);return!e||e.trim().length===0?r:`${e.trim().endsWith(`.`)?e.trim():`${e.trim()}.`} ${r}`}function dt(e){let t=`Return this field as a JSON-encoded string that can be parsed with JSON.parse.`;return!e||e.trim().length===0?t:`${e.trim().endsWith(`.`)?e.trim():`${e.trim()}.`} ${t}`}function ft(e){let t=`Return plain text to synthesize as speech; do not return audio bytes or JSON audio objects.`;return!e||e.trim().length===0?t:`${e.trim().endsWith(`.`)?e.trim():`${e.trim()}.`} ${t}`}function pt(e,t){return t?.flexibleJsonFieldsAsString===!0&&(e?.name===`json`||e?.name===`object`&&!e.fields)}function mt(e,t){return t?.strictStructuredOutputs===!0||!e.isOptional}function ht(e){e.type!==void 0&&(Array.isArray(e.type)?e.type.includes(`null`)||(e.type=[...e.type,`null`]):e.type=[e.type,`null`],Array.isArray(e.enum)&&!e.enum.includes(null)&&(e.enum=[...e.enum,null]))}function gt(e,t=`Schema`,n){if(`name`in e&&`type`in e)return _t(e,!1,n);let r={},i=[];for(let t of e){if(t.isInternal)continue;let e=_t(t,!1,n);r[t.name]=e,mt(t,n)&&i.push(t.name)}return{type:`object`,title:t,properties:r,required:i,additionalProperties:!1}}function _t(e,t=!1,n){let r=e.type;if(r&&Ye(e)){let t=rt(r);if(n?.decisionMode===`result`){if(!r.evidence)t={type:`number`,minimum:0,maximum:r.options.length-1};else{let e={type:`object`,properties:{source:{type:`string`,enum:[`native`,`elicited`]},provider:{type:`string`},model:{type:`string`}},required:[`source`,`provider`],additionalProperties:!1},n={value:r.name===`boolean`?{type:`boolean`}:r.name===`class`?{type:`string`,enum:r.options}:{type:`number`,minimum:0,maximum:r.options.length-1},provenance:e};r.name===`boolean`?(n.probability={type:`number`,minimum:0,maximum:1},n.threshold={type:`number`,minimum:0,maximum:1}):r.name===`score`?(n.levels={type:`array`,items:{type:`string`}},n.probabilities={type:`array`,items:{type:`number`,minimum:0,maximum:1}}):n.probabilities={type:`object`,properties:Object.fromEntries(r.options.map(e=>[e,{type:`number`,minimum:0,maximum:1}])),required:r.options,additionalProperties:!1},t={type:`object`,properties:n,required:Object.keys(n),additionalProperties:!1},r.name!==`boolean`&&(t.properties.confidence={type:`number`,minimum:0,maximum:1}),r.evidence.onRefusal===`return`&&(t={anyOf:[{...t,properties:{...n,status:{type:`string`,enum:[`answered`]}},required:[...t.required,`status`]},{type:`object`,properties:{status:{type:`string`,enum:[`refused`]},provenance:e},required:[`status`,`provenance`],additionalProperties:!1}]})}}let i=r.name===`boolean`?`Return the probability of true.`:r.name===`score`?`Return probabilities in the declared rubric order, from lowest to highest: ${r.options.map((e,t)=>`${t}: ${e}`).join(`; `)}.`:`Return a probability for every declared class.`;return t.description=[ct(e),n?.decisionMode===`result`?``:i].filter(Boolean).join(` `),r.isArray&&(t={type:`array`,items:t}),e.isOptional&&n?.strictStructuredOutputs&&(t={anyOf:[t,{type:`null`}]}),t}let i=ut(ct(e),r);if(t&&r?.name&&(r.name===`image`||r.name===`audio`||r.name===`file`))throw Error(`Media type '${r.name}' is not allowed in nested object fields. Media types (image, audio, file) can only be used as top-level fields. Field: ${e.name}`);let a={};if(i&&(a.description=i),r?.isArray){if(a.type=`array`,r.fields){a.items={type:`object`,properties:{},required:[],additionalProperties:!1},r.description&&(a.items.description=r.description);for(let[e,t]of Object.entries(r.fields)){let r={name:e,description:t.description,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0,fields:t.fields,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,valueDescriptions:t.valueDescriptions,evidence:t.evidence,format:t.format},isOptional:t.isOptional,isInternal:t.isInternal};a.items.properties[e]=_t(r,!0,n),mt(t,n)&&a.items.required.push(e)}}else if(r.name===`class`&&r.options)a.items={type:`string`,enum:r.options,...r.valueDescriptions?{description:i}:{}};else{let t=ut(ct({...e,description:r.description||e.description}),r);a.items={type:pt(r,n)?`string`:vt(r.name)},pt(r,n)?a.items.description=dt(t):t&&(a.items.description=t),r.name===`string`||r.name===`code`||r.name===`url`||r.name===`date`||r.name===`dateRange`||r.name===`datetime`||r.name===`datetimeRange`?(r.minLength!==void 0&&(a.items.minLength=r.minLength),r.maxLength!==void 0&&(a.items.maxLength=r.maxLength),r.pattern!==void 0&&(a.items.pattern=r.pattern),r.format!==void 0&&(a.items.format=r.format)):r.name===`number`&&(r.minimum!==void 0&&(a.items.minimum=r.minimum),r.maximum!==void 0&&(a.items.maximum=r.maximum))}}else if(r?.name===`object`&&r.fields){a.type=`object`,a.properties={},a.required=[],a.additionalProperties=!1;for(let[e,t]of Object.entries(r.fields)){let r={name:e,description:t.description,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0,fields:t.fields,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,valueDescriptions:t.valueDescriptions,evidence:t.evidence,format:t.format},isOptional:t.isOptional,isInternal:t.isInternal};a.properties[e]=_t(r,!0,n),mt(t,n)&&a.required.push(e)}}else r?.name===`class`&&r.options?(a.type=`string`,a.enum=r.options):(a.type=pt(r,n)?`string`:vt(r?.name??`string`),pt(r,n)&&(a.description=dt(a.description)),r?.name===`audio`&&(a.description=ft(a.description)),r?.name===`string`||r?.name===`code`||r?.name===`url`||r?.name===`date`||r?.name===`dateRange`||r?.name===`datetime`||r?.name===`datetimeRange`?(r.minLength!==void 0&&(a.minLength=r.minLength),r.maxLength!==void 0&&(a.maxLength=r.maxLength),r.pattern!==void 0&&(a.pattern=r.pattern),r.format!==void 0&&(a.format=r.format),r.name===`url`&&!r.format&&(a.format=`uri`),r.name===`date`&&!r.format&&(a.format=`date`),r.name===`datetime`&&!r.format&&(a.format=`date-time`)):r?.name===`number`&&(r.minimum!==void 0&&(a.minimum=r.minimum),r.maximum!==void 0&&(a.maximum=r.maximum)));return e.isOptional&&n?.strictStructuredOutputs===!0&&ht(a),a}function vt(e){switch(e){case`string`:case`code`:case`url`:case`date`:case`datetime`:case`dateRange`:case`datetimeRange`:case`image`:case`audio`:case`file`:return`string`;case`number`:return`number`;case`boolean`:return`boolean`;case`json`:case`object`:return[`object`,`array`,`string`,`number`,`boolean`,`null`];default:return`string`}}function yt(e){if(!e||typeof e!=`object`)throw Error(`Schema must be an object`);if(e.type===`array`){if(!e.items)throw Error(`Array schema is missing an "items" definition (required by JSON Schema and all LLM providers for function tools)`);yt(e.items)}else if(e.type===`object`&&e.properties)for(let t of Object.values(e.properties))yt(t)}var G=class extends Error{position;context;suggestion;constructor(e,t,n,r){super(e),this.position=t,this.context=n,this.suggestion=r,this.name=`SignatureValidationError`}},bt=class{input;position;currentFieldName=null;currentSection=`description`;constructor(e){if(this.input=e.trim(),this.position=0,!this.input)throw new G(`Empty signature provided`,0,``,`A signature must contain at least input and output fields separated by "->". Example: "userQuery:string -> aiResponse:string"`)}parse(){try{this.skipWhitespace();let e=this.parseParsedString();this.skipWhitespace(),this.currentSection=`inputs`;let t=this.parseFieldList(()=>this.parseInputField(),`input`);if(this.skipWhitespace(),this.position>=this.input.length)throw new G(`Incomplete signature: Missing output section`,this.position,this.getErrorContext(),`Add "->" followed by output fields. Example: "-> responseText:string"`);if(this.expectArrow(),this.skipWhitespace(),this.position>=this.input.length)throw new G(`Incomplete signature: No output fields specified after "->"`,this.position,this.getErrorContext(),`Add at least one output field. Example: "-> responseText:string"`);this.currentSection=`outputs`;let n=this.parseFieldList(()=>this.parseOutputField(),`output`);if(this.skipWhitespace(),this.position<this.input.length)throw new G(`Unexpected content after signature: "${this.input.slice(this.position)}"`,this.position,this.getErrorContext(),`Remove any extra content after the output fields`);return this.validateParsedSignature({desc:e?.trim(),inputs:t,outputs:n}),{desc:e?.trim(),inputs:t,outputs:n}}catch(e){throw e instanceof G?e:new G(e instanceof Error?e.message:`Unknown error`,this.position,this.getErrorContext())}}validateParsedSignature(e){let t=/* @__PURE__ */ new Set;for(let n of e.inputs){if(t.has(n.name))throw new G(`Duplicate input field name: "${n.name}"`,0,``,`Each field name must be unique within the signature`);t.add(n.name)}let n=/* @__PURE__ */ new Set;for(let t of e.outputs){if(n.has(t.name))throw new G(`Duplicate output field name: "${t.name}"`,0,``,`Each field name must be unique within the signature`);n.add(t.name)}for(let n of e.outputs)if(t.has(n.name))throw new G(`Field name "${n.name}" appears in both inputs and outputs`,0,``,`Use different names for input and output fields to avoid confusion`);if(e.inputs.length===0)throw new G(`Signature must have at least one input field`,0,``,`Add an input field before "->". Example: "userInput:string -> ..."`);if(e.outputs.length===0)throw new G(`Signature must have at least one output field`,0,``,`Add an output field after "->". Example: "... -> responseText:string"`)}getErrorContext(){let e=Math.max(0,this.position-25),t=Math.min(this.input.length,this.position+25),n=this.input.slice(e,this.position),r=this.input.slice(this.position,t),i=`${` `.repeat(n.length)}^`;return[`Position ${this.position} in signature:`,`"${n}${r}"`,` ${i}`].join(`
3
3
  `)}parseFieldList(e,t){let n=[];if(this.skipWhitespace(),this.position>=this.input.length)throw new G(`Empty ${t} section: Expected at least one field`,this.position,this.getErrorContext(),`Add a ${t} field. Example: ${t===`input`?`userInput:string`:`responseText:string`}`);try{n.push(e())}catch(e){throw e instanceof G?e:new G(`Invalid first ${t} field: ${e instanceof Error?e.message:`Unknown error`}`,this.position,this.getErrorContext())}for(this.skipWhitespace();this.position<this.input.length&&!(this.input[this.position]===`-`&&this.position+1<this.input.length&&this.input[this.position+1]===`>`)&&this.match(`,`);){if(this.skipWhitespace(),this.position>=this.input.length)throw new G(`Unexpected end of input after comma in ${t} section`,this.position,this.getErrorContext(),`Add another ${t} field after the comma`);try{n.push(e())}catch(e){throw e instanceof G?e:new G(`Invalid ${t} field after comma: ${e instanceof Error?e.message:`Unknown error`}`,this.position,this.getErrorContext())}this.skipWhitespace()}return n}parseInputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,`input`);let t;for(;;){if(this.match(`?`)){t=!0;continue}if(this.match(`!`))throw new G(`Input field "${e}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),`Internal markers (!) are only allowed on output fields`);break}let n,r;if(this.skipWhitespace(),this.match(`:`)){if(this.skipWhitespace(),/^class\b/.test(this.input.slice(this.position)))throw new G(`Input field "${e}" cannot use the "class" type`,this.position,this.getErrorContext(),`Class types are only allowed on output fields. Use "string" type for input classifications`);try{let t=this.parseNonClassType(`input`,e);n=t.type,r=t.isCached}catch(t){throw t instanceof G?t:new G(`Input field "${e}": ${t instanceof Error?t.message:`Unknown error`}`,this.position,this.getErrorContext())}}return this.skipWhitespace(),{name:e,desc:this.parseParsedString()?.trim()??(n?.name===`code`?n.language:void 0),type:n,isOptional:t,...r?{isCached:!0}:{}}}parseOutputField(){this.skipWhitespace();let e=this.parseParsedIdentifier();this.currentFieldName=e,this.validateFieldName(e,`output`);let t=!1,n=!1;for(;;){if(this.match(`?`)){t=!0;continue}if(this.match(`!`)){n=!0;continue}break}let r;if(this.skipWhitespace(),this.match(`:`)){if(this.skipWhitespace(),this.match(`class`)||this.match(`score`)){let t=this.input.slice(this.position-5,this.position);this.rejectClassModifierBag(e);let n=this.match(`[]`);this.rejectClassModifierBag(e),this.skipWhitespace();let i=this.parseParsedString();if(!i)throw new G(`Output field "${e}": Missing class options after "class" type`,this.position,this.getErrorContext(),`Add class names in quotes. Example: class "positive, negative, neutral"`);let a=i.split(/[,|]/).map(e=>e.trim()).filter(e=>t===`score`||e.length>0);if(a.length===0)throw new G(`Output field "${e}": Empty class list provided`,this.position,this.getErrorContext(),`Provide at least one class option. Example: "positive, negative"`);let o=this.parseClassValueDescriptions(a,e);this.match(`[]`)&&(n=!0),Je({type:t,options:a,evidence:o?.evidence}),r={name:t,isArray:n,options:a,...o??{}}}else try{r=this.parseNonClassType(`output`,e).type;let t=r.name,n=r.isArray;if(t===`image`&&n)throw new G(`Output field "${e}": Arrays of images are not supported`,this.position,this.getErrorContext(),`Use a single image type instead: "image"`);if(t===`audio`&&n)throw new G(`Output field "${e}": Arrays of audio are not supported`,this.position,this.getErrorContext(),`Use a single audio type instead: "audio"`);if(t===`image`)throw new G(`Output field "${e}": Image type is not supported in output fields`,this.position,this.getErrorContext(),`Image types can only be used in input fields`)}catch(t){throw t instanceof G?t:new G(`Output field "${e}": ${t instanceof Error?t.message:`Unknown error`}`,this.position,this.getErrorContext())}}return this.skipWhitespace(),{name:e,desc:this.parseParsedString()?.trim()??(r?.name===`code`?r.language:void 0),type:r,isOptional:t,isInternal:n}}validateFieldName(e,t){if(H.signatureStrict&&[`text`,`object`,`image`,`string`,`number`,`boolean`,`json`,`array`,`daterange`,`datetimerange`,`datetime`,`date`,`time`,`type`,`class`,`input`,`output`,`data`,`value`,`result`,`response`,`request`,`item`,`element`].includes(e.toLowerCase())){let n=t===`input`?[`userInput`,`questionText`,`documentContent`,`messageText`]:[`responseText`,`analysisResult`,`categoryType`,`summaryText`];throw new G(`Field name "${e}" is too generic`,this.position,this.getErrorContext(),`Use a more descriptive name. Examples: ${n.join(`, `)}`)}if(!/^[a-z][a-zA-Z0-9]*$/.test(e)&&!/^[a-z]+(_[a-z0-9]+)*$/.test(e))throw new G(`Invalid field name "${e}"`,this.position,this.getErrorContext(),`Field names must be in camelCase (e.g., "userInput") or snake_case (e.g., "user_input")`);if(e.length<2)throw new G(`Field name "${e}" is too short`,this.position,this.getErrorContext(),`Field names must be at least 2 characters long`);if(e.length>50)throw new G(`Field name "${e}" is too long (${e.length} characters)`,this.position,this.getErrorContext(),`Field names should be 50 characters or less`)}parseTypeNotClass(){let e=[`string`,`number`,`score`,`class`,`boolean`,`json`,`image`,`audio`,`file`,`url`,`datetimeRange`,`dateRange`,`datetime`,`date`,`code`,`object`],t=/^[a-zA-Z][a-zA-Z0-9]*/.exec(this.input.slice(this.position))?.[0];if(t&&e.includes(t))return this.position+=t.length,t;let n=t??(this.input.slice(this.position).match(/^\w+/)?.[0]||``),r=this.suggestType(n);throw new G(`${`Invalid type "${n||`empty`}"`}${r?`. Did you mean "${r}"?`:``}`,this.position,this.getErrorContext(),`Expected one of: ${e.join(`, `)}`)}suggestType(e){return{str:`string`,text:`string`,int:`number`,integer:`number`,float:`number`,double:`number`,bool:`boolean`,object:`json`,dict:`json`,daterange:`dateRange`,range:`datetimeRange`,datetimerange:`datetimeRange`,timestamp:`datetime`,time:`datetime`,img:`image`,picture:`image`,sound:`audio`,voice:`audio`,classification:`class`,category:`class`}[e.toLowerCase()]||null}rejectClassModifierBag(e){if(this.input[this.position]===`(`)throw new G(`Field "${e}": constraints are not supported on class fields`,this.position,this.getErrorContext(),`Class options use a quoted string. Example: class "positive, negative"`)}parseNonClassType(e,t){let n=this.parseTypeNotClass();if(n===`score`||n===`class`){let e=this.match(`[]`);this.skipWhitespace();let r=this.parseParsedString();if(!r)throw Error(`${n} requires quoted labels`);let i=r.split(/[,|]/).map(e=>e.trim()),a=this.parseClassValueDescriptions(i,t)??{};return Je({type:n,options:i,evidence:a.evidence}),{type:{name:n,isArray:this.match(`[]`)||e,options:i,...a}}}if(n===`object`){let e=this.position;if(this.skipWhitespace(),this.match(`{`)){let e=this.parseObjectFields(t);return{type:{name:`object`,isArray:this.match(`[]`),fields:e}}}this.position=e}let r={},i,a;if(this.input[this.position]===`(`){let o=this.parseModifierBag(n,e,t);r=o.constraints,i=o.isCached,a=o.itemDescription}let o=this.match(`[]`);if(a!==void 0&&!o)throw new G(`Field "${t}": the "item" modifier requires an array type`,this.position,this.getErrorContext(),`Add "[]" after the modifier list. Example: tags:string(item "a short tag")[]`);return{type:{name:n,isArray:o,...r,...a===void 0?{}:{description:a}},...i?{isCached:!0}:{}}}parseModifierBag(e,t,n){this.position++;let r={},i,a,o=/* @__PURE__ */ new Set,s=()=>{let n=[];return e===`string`&&n.push(`min <n>`,`max <n>`,`format <email|uri|date|date-time>`,`pattern "<regex>"`),e===`number`&&n.push(`min <n>`,`max <n>`),e===`boolean`&&n.push(`true "<description>"`,`false "<description>"`),e===`code`&&n.push(`<language>`),t!==`nested`&&n.push(`item "<description>"`),t===`input`&&n.push(`cache`),n.length>0?n.join(`, `):`no modifiers apply to this type here`},c=(e,t)=>{throw new G(e,this.position,this.getErrorContext(),t)},l=e=>{o.has(e)&&c(`Field "${n}": duplicate "${e}" modifier`,`Each modifier may appear at most once per field`),o.add(e)};for(this.skipWhitespace(),this.match(`)`)&&c(`Field "${n}": empty modifier list "()"`,`Remove the parentheses or add a modifier. Allowed here: ${s()}`);;){this.skipWhitespace();let o=/^[a-zA-Z][a-zA-Z0-9+#.-]*/.exec(this.input.slice(this.position))?.[0];if(!o){c(`Field "${n}": expected a modifier name inside "(...)"`,`Allowed here: ${s()}`);break}switch(this.position+=o.length,o){case`evidence`:l(o),[`boolean`,`score`,`class`].includes(e)||c(`Evidence requires boolean, class or score`),r.evidence={...r.evidence};break;case`threshold`:{l(o),e!==`boolean`&&c(`threshold requires boolean evidence`),this.skipWhitespace();let t=/^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)/.exec(this.input.slice(this.position))?.[0];t||c(`threshold requires a number in [0, 1]`),this.position+=t.length,r.evidence={...r.evidence,threshold:Number(t)};break}case`refusal`:{l(o),this.skipWhitespace();let e=/^(return|throw)\b/.exec(this.input.slice(this.position))?.[0];e||c(`refusal requires return or throw`),this.position+=e.length,r.evidence={...r.evidence,onRefusal:e};break}case`true`:case`false`:{l(o),e!==`boolean`&&c(`Field "${n}": "${o}" value descriptions require a boolean field`),this.skipWhitespace();let t=this.parseParsedString();(t===void 0||!t.trim())&&c(`Field "${n}": "${o}" requires a nonempty quoted description`),r.valueDescriptions={...r.valueDescriptions,[o]:t};break}case`min`:case`max`:{l(o),e!==`string`&&e!==`number`&&c(`Field "${n}": "${o}" is not supported for type "${e}"`,`"${o}" applies to string (length) and number (value) fields only`),this.skipWhitespace();let t=/^-?\d+(\.\d+)?/.exec(this.input.slice(this.position))?.[0];if(!t){c(`Field "${n}": "${o}" requires a numeric value`,`Example: ${o} ${o===`min`?`0`:`100`}`);break}this.position+=t.length;let i=Number(t);e===`string`?o===`min`?r.minLength=i:r.maxLength=i:o===`min`?r.minimum=i:r.maximum=i;break}case`format`:{l(`format`),e!==`string`&&c(`Field "${n}": "format" is not supported for type "${e}"`,`"format" applies to string fields only`),this.skipWhitespace();let t=[`email`,`uri`,`date-time`,`date`],i=/^[a-z-]+/.exec(this.input.slice(this.position))?.[0];if(!i||!t.includes(i)){c(`Field "${n}": unknown format "${i??``}"`,`Expected one of: ${t.join(`, `)}`);break}this.position+=i.length,r.format=i;break}case`pattern`:{l(`pattern`),e!==`string`&&c(`Field "${n}": "pattern" is not supported for type "${e}"`,`"pattern" applies to string fields only`),this.skipWhitespace();let t=this.parseParsedString();if(t===void 0){c(`Field "${n}": "pattern" requires a quoted regular expression`,`Example: pattern "^[A-Z]{3}-\\\\d+$" "three capitals, a dash, digits" (backslashes are escaped inside quotes)`);break}r.pattern=t,this.skipWhitespace();let i=this.parseParsedString();i!==void 0&&(r.patternDescription=i);break}case`cache`:l(`cache`),t!==`input`&&c(`Field "${n}": "cache" is only supported on top-level input fields`,t===`nested`?`Move the cache modifier to the enclosing top-level input field`:`Remove "cache" from this output field`),i=!0;break;case`item`:{l(`item`),t===`nested`&&c(`Field "${n}": "item" is not supported inside object fields`,`Use a field description instead`),this.skipWhitespace();let e=this.parseParsedString();if(e===void 0){c(`Field "${n}": "item" requires a quoted description`,`Example: tags:string(item "a short tag")[]`);break}a=e;break}default:e===`code`?(l(`language`),r.language=o):c(`Field "${n}": unknown modifier "${o}" for type "${e}"`,`Allowed here: ${s()}`)}if(this.skipWhitespace(),this.match(`,`)){this.skipWhitespace(),this.input[this.position]===`)`&&c(`Field "${n}": trailing comma in modifier list`,`Remove the comma before ")"`);continue}if(this.match(`)`))break;c(`Field "${n}": expected "," or ")" in modifier list`,`Separate modifiers with commas and close the list with ")"`)}return r.evidence&&!o.has(`evidence`)&&c(`threshold/refusal requires evidence`),Je({type:e,evidence:r.evidence}),{constraints:r,isCached:i,itemDescription:a}}parseClassValueDescriptions(e,t){if(this.skipWhitespace(),!this.match(`(`))return;let n={},r,i=/* @__PURE__ */ new Set,a=e=>{throw new G(`Field "${t}": ${e}`,this.position,this.getErrorContext())};for(this.skipWhitespace(),this.input[this.position]===`)`&&a(`empty value description list`);;){this.skipWhitespace();let e=this.input[this.position]===`"`,t=this.parseParsedString();if(t===void 0&&(t=/^[A-Za-z_][A-Za-z0-9_.-]*/.exec(this.input.slice(this.position))?.[0],t===void 0&&a(`expected a class label`),this.position+=t.length),this.skipWhitespace(),!e&&(t===`evidence`||t===`refusal`)){if(i.has(t)&&a(`duplicate ${t} modifier`),i.add(t),t===`evidence`)r={...r};else{let e=/^(return|throw)\b/.exec(this.input.slice(this.position))?.[0];e||a(`refusal requires return or throw`),this.position+=e.length,r={...r,onRefusal:e}}}else{Object.hasOwn(n,t)&&a(`duplicate description for "${t}"`),this.skipWhitespace();let e=this.parseParsedString();(e===void 0||!e.trim())&&a(`"${t}" requires a nonempty quoted description`),n={...n,[t]:e}}if(this.skipWhitespace(),this.match(`)`))break;this.match(`,`)||a(`expected "," or ")" in value descriptions`),this.skipWhitespace(),this.input[this.position]===`)`&&a(`trailing comma in value descriptions`)}r&&!i.has(`evidence`)&&a(`refusal requires the evidence modifier`);try{ot(`class`,n,e,t)}catch(e){a(e instanceof Error?e.message:String(e))}return{...Object.keys(n).length?{valueDescriptions:n}:{},...r?{evidence:r}:{}}}parseObjectFields(e){let t={};if(this.skipWhitespace(),this.match(`}`))throw new G(`Field "${e}": object type requires at least one field`,this.position-1,this.getErrorContext(),`Add fields inside the braces. Example: object{ name:string, age:number }`);for(;;){if(this.position>=this.input.length)throw new G(`Field "${e}": unbalanced "{" in object type`,this.position,this.getErrorContext(),`Close the object field list with "}"`);let[n,r]=this.parseNestedField(e);if(Object.hasOwn(t,n))throw new G(`Field "${e}": duplicate object field name "${n}"`,this.position,this.getErrorContext(),`Each field name must be unique within an object`);if(t[n]=r,this.skipWhitespace(),this.match(`,`)){if(this.skipWhitespace(),this.input[this.position]===`}`)throw new G(`Field "${e}": trailing comma in object type`,this.position,this.getErrorContext(),`Remove the comma before "}"`);continue}if(this.match(`}`))break;throw new G(`Field "${e}": ${this.position>=this.input.length?`unbalanced "{" in object type`:`expected "," or "}" in object type`}`,this.position,this.getErrorContext(),`Separate object fields with commas and close the list with "}"`)}return t}parseNestedField(e){this.skipWhitespace();let t=this.parseParsedIdentifier(),n=`${e}.${t}`,r=!1;for(;;){if(this.match(`?`)){r=!0;continue}if(this.match(`!`))throw new G(`Object field "${n}" cannot use the internal marker "!"`,this.position-1,this.getErrorContext(),`Internal markers are only allowed on top-level output fields`);break}let i;if(this.skipWhitespace(),this.match(`:`)){if(this.skipWhitespace(),/^(class|score)\b/.test(this.input.slice(this.position))){let e=/^(class|score)/.exec(this.input.slice(this.position))[0];this.match(e),this.rejectClassModifierBag(n);let t=this.match(`[]`);this.rejectClassModifierBag(n),this.skipWhitespace();let a=this.parseParsedString();if(!a)throw new G(`Object field "${n}": Missing class options after "class" type`,this.position,this.getErrorContext(),`Add class names in quotes. Example: class "high, medium, low"`);let o=a.split(/[,|]/).map(e=>e.trim()).filter(t=>e===`score`||t.length>0);if(o.length===0)throw new G(`Object field "${n}": Empty class list provided`,this.position,this.getErrorContext(),`Provide at least one class option. Example: "high, medium"`);let s=this.parseClassValueDescriptions(o,n);this.match(`[]`)&&(t=!0),Je({type:e,options:o,evidence:s?.evidence}),i={type:e,isArray:t,options:o,...s??{},isOptional:r,isInternal:!1}}else{let e=this.parseTypeNotClass();if(e===`image`||e===`audio`||e===`file`)throw new G(`Object field "${n}": ${e} type is not allowed in nested object fields`,this.position,this.getErrorContext(),`Media types (image, audio, file) can only be used as top-level input fields`);if(e===`object`){let e=this.position;if(this.skipWhitespace(),this.match(`{`)){let e=this.parseObjectFields(n);i={type:`object`,isArray:this.match(`[]`),fields:e,isOptional:r,isInternal:!1}}else this.position=e}if(!i){let t={};this.input[this.position]===`(`&&(t=this.parseModifierBag(e,`nested`,n).constraints),i={type:e,isArray:this.match(`[]`),...t,isOptional:r,isInternal:!1}}}}else i={type:`string`,isArray:!1,isOptional:r,isInternal:!1};this.skipWhitespace();let a=this.parseParsedString()?.trim()??(i.type===`code`?i.language:void 0);return a!==void 0&&(i.description=a),[t,i]}parseParsedIdentifier(){this.skipWhitespace();let e=/^[a-zA-Z_][a-zA-Z_0-9]*/.exec(this.input.slice(this.position));if(e)return this.position+=e[0].length,e[0];let t=/^\S+/.exec(this.input.slice(this.position)),n=t?t[0]:``;throw n===``?new G(`Expected field name but found end of input`,this.position,this.getErrorContext(),`Add a field name. Field names must start with a letter or underscore`):/^\d/.test(n)?new G(`Invalid field name "${n}" - cannot start with a number`,this.position,this.getErrorContext(),`Field names must start with a letter or underscore. Example: "userInput" or "_internal"`):new G(`Invalid field name "${n}"`,this.position,this.getErrorContext(),`Field names must start with a letter or underscore and contain only letters, numbers, or underscores`)}parseParsedString(){for(let e of[`'`,`"`])if(this.match(e)){let t=``,n=!1,r=this.position-1;for(;this.position<this.input.length;){let r=this.input[this.position];if(this.position++,n)t+=r,n=!1;else if(r===`\\`)n=!0;else if(r===e)return t;else t+=r}let i=this.input.slice(r,Math.min(this.position,r+20));throw new G(`Unterminated string starting at position ${r}`,r,this.getErrorContext(),`Add closing ${e} to complete the string: ${i}${e}`)}}skipWhitespace(){let e=/^[\s\t\r\n]+/.exec(this.input.slice(this.position));e&&(this.position+=e[0].length)}match(e){let t;if(typeof e==`string`){if(this.input.startsWith(e,this.position))return this.position+=e.length,!0}else if(t=e.exec(this.input.slice(this.position)),t)return this.position+=t[0].length,!0;return!1}expectArrow(){if(!this.match(`->`)){let e=this.input.slice(this.position,this.position+10),t=e.includes(`>`)?`Use "->" (dash followed by greater-than)`:e.includes(`-`)?`Add ">" after the dash`:`Add "->" to separate input and output fields`;throw new G(`Expected "->" but found "${e}..."`,this.position,this.getErrorContext(),t)}}};function xt(e){return new bt(e).parse()}function St(e){return typeof e==`object`&&!!e&&`~standard`in e&&typeof e[`~standard`]==`object`}function Ct(e){return St(e)&&e[`~standard`].vendor!==`ax`}function wt(e){let t=e;for(;t;){let e=Tt(t),n=e?.typeName??e?.type;if(n===`ZodOptional`||n===`ZodNullable`||n===`ZodDefault`||n===`optional`||n===`nullable`||n==="default"){let n=e?.innerType??e?.schema;if(!n)return t;t=n;continue}return t}return t}function Tt(e){return e._def??e._zod?.def}function Et(e){let t=Tt(e),n=t?.typeName??t?.type;if(n===`ZodOptional`||n===`ZodDefault`||n===`optional`||n==="default")return!0;let r=e.isOptional;if(typeof r==`function`)try{return r.call(e)}catch{}return!1}function Dt(e){let t=Tt(e);return e.description??t?.description}function Ot(e){let t=wt(e),n=Tt(t),r=n?.typeName??n?.type,i=Dt(e)??Dt(t),a=Et(e),o=(e,t={})=>({type:e,isArray:!1,description:i,isOptional:a,...t});switch(r){case`ZodString`:case`string`:{let e=n?.checks??[],t={};for(let n of e)(n.kind===`min`||n.kind===`min_length`)&&(t.minLength=n.value??n.minimum),(n.kind===`max`||n.kind===`max_length`)&&(t.maxLength=n.value??n.maximum),n.kind===`email`&&(t.format=`email`),(n.kind===`url`||n.kind===`uri`)&&(t.format=`uri`),n.kind===`regex`&&(t.pattern=n.regex?.source??String(n.regex),t.patternDescription=i??`match the regex pattern`);return o(`string`,t)}case`ZodNumber`:case`number`:{let e=n?.checks??[],t={};for(let n of e)(n.kind===`min`||n.kind===`greater_than`)&&(t.minimum=n.value??n.minimum),(n.kind===`max`||n.kind===`less_than`)&&(t.maximum=n.value??n.maximum);return o(`number`,t)}case`ZodBoolean`:case`boolean`:return o(`boolean`);case`ZodDate`:case`date`:return o(`datetime`);case`ZodEnum`:case`ZodNativeEnum`:case`enum`:return o(`class`,{options:Array.isArray(n?.values)?n.values:Object.values(n?.values??{})});case`ZodLiteral`:case`literal`:{let e=n?.value??n?.values?.[0];return o(`class`,{options:e===void 0?[]:[String(e)]})}case`ZodArray`:case`array`:{let e=n?.type??n?.element,t=e?Ot(e):o(`string`);return{...t,isArray:!0,description:i??t.description,isOptional:a}}case`ZodObject`:case`object`:{let e=typeof n?.shape==`function`?n.shape():n?.shape??{},t={};for(let[n,r]of Object.entries(e))t[n]=Ot(r);return o(`object`,{fields:t})}case`ZodRecord`:case`record`:case`ZodAny`:case`any`:case`ZodUnknown`:case`unknown`:return o(`json`);default:return o(`json`)}}function kt(e){if(e[`~standard`]?.vendor!==`zod`)return!1;let t=Tt(e),n=t?.typeName??t?.type;return n===`ZodObject`||n===`object`}function At(e,t=`Schema`){let n=e[`~standard`]?.vendor;if(n===`zod`)return gt(jt(e),t);throw n===`ax`?new W(`Use toJsonSchema(fields) directly for native ax fields — standardSchemaToJsonSchema expects an object schema from an external validator.`):new W(`Unsupported Standard Schema vendor: '${n??`unknown`}'. ax currently accepts zod schemas and its native f.* fields. For other validators, define fields with f.*() or request vendor support.`)}function jt(e,t){let n=e[`~standard`]?.vendor;if(n!==`zod`)throw new W(`Unsupported Standard Schema vendor: '${n??`unknown`}'. ax currently accepts zod schemas here. For other validators, define fields with f.*() or request vendor support.`);let r=Tt(wt(e)),i=r?.typeName??r?.type;if(i!==`ZodObject`&&i!==`object`)throw new W(`Expected a top-level object schema (e.g. z.object({...})); received a ${i??`non-object`} schema. Wrap fields in z.object({...}) or use the per-field form: .input('name', zSchema).`);let a=typeof r?.shape==`function`?r.shape():r?.shape??{},o=t?.fields??{},s=[];for(let[e,t]of Object.entries(a)){let n=Ot(t),r=o[e]??{};s.push(Nt(e,n,r,t))}return s}function Mt(e,t,n){let r=t[`~standard`]?.vendor;if(r!==`zod`)throw new W(`Unsupported Standard Schema vendor: '${r??`unknown`}'. ax currently accepts zod schemas here. For other validators, use f.*() field types.`);return Nt(e,Ot(t),n??{},t)}function Nt(e,t,n,r){return{name:e,description:t.description,type:{name:t.type,isArray:t.isArray,options:t.options?[...t.options]:void 0,fields:t.fields,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,format:t.format},isOptional:t.isOptional||void 0,isInternal:n.internal||void 0,isCached:n.cache||void 0,schema:r}}function Pt(e,t,n){let r=e[`~standard`].validate(n);if(r instanceof Promise)throw new W(`Async Standard Schema validators are not supported for field '${t}'. Use a synchronous validator (e.g., avoid z.refine with async predicates).`);if(r.issues&&r.issues.length>0)throw new W(`Field '${t}' failed validation: ${r.issues.map(e=>{let t=e.path?.map(e=>typeof e==`object`&&e&&`key`in e?String(e.key):String(e)).join(`.`)??``;return t?`${t}: ${e.message}`:e.message}).join(`; `)}`);return r.value}var Ft=class{ANSI_WHITE_BRIGHT=`\x1B[97m`;ANSI_GREEN_BRIGHT=`\x1B[92m`;ANSI_BLUE_BRIGHT=`\x1B[94m`;ANSI_RED_BRIGHT=`\x1B[91m`;ANSI_YELLOW_BRIGHT=`\x1B[93m`;ANSI_YELLOW=`\x1B[93m`;ANSI_RED=`\x1B[91m`;ANSI_RESET=`\x1B[0m`;ANSI_ORANGE=`\x1B[38;5;208m`;ANSI_WHITE=`\x1B[37m`;ANSI_CYAN_BRIGHT=`\x1B[96m`;ANSI_MAGENTA_BRIGHT=`\x1B[95m`;ANSI_GRAY=`\x1B[90m`;ANSI_GREEN=`\x1B[32m`;ANSI_CYAN=`\x1B[36m`;ANSI_MAGENTA=`\x1B[35m`;ANSI_BLUE=`\x1B[34m`;ANSI_YELLOW_DIM=`\x1B[33m`;colorize(e,t){return`${t}${e}${this.ANSI_RESET}`}whiteBright(e){return this.colorize(e,this.ANSI_WHITE_BRIGHT)}greenBright(e){return this.colorize(e,this.ANSI_GREEN_BRIGHT)}blueBright(e){return this.colorize(e,this.ANSI_BLUE_BRIGHT)}redBright(e){return this.colorize(e,this.ANSI_RED_BRIGHT)}white(e){return this.colorize(e,this.ANSI_WHITE)}yellow(e){return this.colorize(e,this.ANSI_YELLOW)}yellowBright(e){return this.colorize(e,this.ANSI_YELLOW_BRIGHT)}red(e){return this.colorize(e,this.ANSI_RED)}orange(e){return this.colorize(e,this.ANSI_ORANGE)}cyanBright(e){return this.colorize(e,this.ANSI_CYAN_BRIGHT)}magentaBright(e){return this.colorize(e,this.ANSI_MAGENTA_BRIGHT)}gray(e){return this.colorize(e,this.ANSI_GRAY)}green(e){return this.colorize(e,this.ANSI_GREEN)}cyan(e){return this.colorize(e,this.ANSI_CYAN)}magenta(e){return this.colorize(e,this.ANSI_MAGENTA)}blue(e){return this.colorize(e,this.ANSI_BLUE)}yellowDim(e){return this.colorize(e,this.ANSI_YELLOW_DIM)}};new Ft;const It=(e,t)=>{let n=e.type??{name:`string`,isArray:!1},r=(t,r)=>{if(Ye(e))return typeof r==`object`&&r?!Array.isArray(r):t===`boolean`?typeof r==`boolean`:t===`class`?typeof r==`string`&&(n.options?.includes(r)??!1):typeof r==`number`&&Number.isFinite(r);switch(t){case`class`:return typeof r==`string`;case`code`:return typeof r==`string`;case`string`:return typeof r==`string`;case`number`:return typeof r==`number`;case`boolean`:return typeof r==`boolean`;case`date`:return r instanceof Date||typeof r==`string`;case`datetime`:return r instanceof Date||typeof r==`string`;case`dateRange`:case`datetimeRange`:return typeof r==`string`||typeof r==`object`&&!!r&&`start`in r&&`end`in r;case`json`:return typeof r==`object`||typeof r==`string`;case`object`:return typeof r==`object`;default:return!1}},i=e=>!(!e||typeof e!=`object`||!(`mimeType`in e)||!(`data`in e));if(e.type?.name===`image`){let n;if(Array.isArray(t)){for(let e of t)if(!i(e)){n=`object ({ mimeType: string; data: string })`;break}}else i(t)||(n=`object ({ mimeType: string; data: string })`);if(n)throw Error(`Validation failed: Expected '${e.name}' to be type '${n}' instead got '${t}'`);return}let a=e=>typeof e==`string`||!(!e||typeof e!=`object`||!(`data`in e)&&!(`id`in e));if(e.type?.name===`audio`){let n;if(Array.isArray(t)){for(let e of t)if(!a(e)){n=`string or object ({ data: string; format?: string })`;break}}else a(t)||(n=`string or object ({ data: string; format?: string })`);if(n)throw Error(`Validation failed: Expected '${e.name}' to be type '${n}' instead got '${t}'`);return}let o=e=>{if(!e||typeof e!=`object`||!(`mimeType`in e))return!1;let t=`data`in e,n=`fileUri`in e;return!(!t&&!n||t&&n)};if(e.type?.name===`file`){let n;if(Array.isArray(t)){for(let e of t)if(!o(e)){n=`object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })`;break}}else o(t)||(n=`object ({ mimeType: string; data: string } | { mimeType: string; fileUri: string })`);if(n)throw Error(`Validation failed: Expected '${e.name}' to be type '${n}' instead got '${t}'`);return}let s=e=>typeof e==`string`||!(!e||typeof e!=`object`||!(`url`in e));if(e.type?.name===`url`){let n;if(Array.isArray(t)){for(let e of t)if(!s(e)){n=`string or object ({ url: string; title?: string; description?: string })`;break}}else s(t)||(n=`string or object ({ url: string; title?: string; description?: string })`);if(n)throw Error(`Validation failed: Expected '${e.name}' to be type '${n}' instead got '${t}'`);return}let c=!0;if(n.isArray){if(!Array.isArray(t))c=!1;else for(let e of t)if(!r(n.name,e)){c=!1;break}}else c=r(n.name,t);if(!c){let r=Array.isArray(t)?`array`:typeof t;throw Error(`Validation failed: Expected '${e.name}' to be a ${e.type?.isArray?`an array of `:``}${n.name} instead got '${r}' (${JSON.stringify(t)})`)}};function Lt(e){let t={},n=[`promptTokens`,`completionTokens`,`totalTokens`,`thoughtsTokens`,`reasoningTokens`,`cacheCreationTokens`,`cacheReadTokens`];for(let r of e){let e=`${r.ai}:${r.model}`;if(!t[e]){t[e]={...r,...r.tokens?{tokens:{...r.tokens}}:{}};continue}let i=t[e];if(i){let e=i.tokens??{promptTokens:0,completionTokens:0,totalTokens:0};for(let t of n){let n=r?.tokens?.[t];(n!==void 0||e[t]!==void 0)&&(e[t]=(e[t]??0)+(n??0))}!e.serviceTier&&r?.tokens?.serviceTier&&(e.serviceTier=r.tokens.serviceTier),i.tokens=e;let t=i.citations??[],a=r.citations??[];if(a.length){let e=new Set(t.map(e=>e.url));for(let n of a)n?.url&&!e.has(n.url)&&(t.push(n),e.add(n.url));i.citations=t}}}return Object.values(t)}const Rt=e=>{if(!e.trim())return[];let t=/* @__PURE__ */ new Set([`-`,`*`,`+`]),n=/^\d+[\s]*[.)\]]\s*/,r=e.split(`
4
- `),i=[];for(let e of r){let r=e.trim();if(r){if(r[0]&&t.has(r[0]))i.push(r.slice(1).trim());else if(n.test(r))i.push(r.replace(n,``).trim());else if(i.length!==0)throw Error(`Could not parse markdown list: mixed content detected`)}}if(i.length===0)throw Error(`Could not parse markdown list: no valid list items found`);return i};function zt(e,t){let{index:n,delta:r,version:i}=t,a=e.find(e=>e.index===n)?.delta;if(!a)return e.push({index:n,delta:r,version:i}),e;for(let e of Object.keys(r)){let t=a[e],n=r[e];a[e]=t===void 0&&Array.isArray(n)?[...n]:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:(t===void 0||typeof t==`string`)&&typeof n==`string`?`${t??``}${n}`:n}let o=e.find(e=>e.index===n);return o&&(o.version=i),e}const Bt=new class{cache=/* @__PURE__ */ new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(e,t)}}(500);function Vt(e,t,n=0,r=Bt){if(/^```[a-zA-Z]*\s*$/.test(e))return-4;if(/^[\s`]*$/.test(e))return-3;let i=e.indexOf(t,n);if(i!==-1)return i;let a=r.get(t)??Array.from({length:t.length},(e,n)=>t.slice(0,n+1));r.get(t)||r.set(t,a);let o=-1;for(let t=a.length-1;t>=0;t--){let n=a[t];if(e.endsWith(n)){o=t;break}}return o>=0?-2:-1}var Ht=class{inputFields=[];outputFields=[];desc;input(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`input() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.inputFields.push(e);return this}if(Ct(t))return this.inputFields.push(Mt(e,t,n)),this;let r=qt(e,t);return n===!0?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`output() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.outputFields.push(e);return this}if(Ct(t))return this.outputFields.push(Mt(e,t,n)),this;let r=qt(e,t);return n===!0?this.outputFields.unshift(r):this.outputFields.push(r),this}addInputFields(e){for(let t of e)this.inputFields.push(t);return this}addOutputFields(e){for(let t of e)this.outputFields.push(t);return this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=J.from(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Ut=class e{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;evidence;valueDescriptions;patternDescription;format;language;itemDescription;constructor(e){this.type=e.type,this.evidence=e.evidence,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.valueDescriptions=e.valueDescriptions?{...e.valueDescriptions}:void 0,this.format=e.format,this.language=e.language}describeValues(t){return ot(this.type,t,this.options),new e({...this,valueDescriptions:t})}withEvidence(t){Je({type:this.type,options:this.options,evidence:t??{}});let n=this;return new e({...n,evidence:t??{}})}optional(){return new e({...this,isOptional:!0})}array(t){return new e({...this,isArray:!0,description:t||this.description,itemDescription:t?this.description:void 0})}internal(){return new e({...this,isInternal:!0})}cache(){return new e({...this,isCached:!0})}min(t){return this.type===`string`?new e({...this,minLength:t}):this.type===`number`?new e({...this,minimum:t}):this}max(t){return this.type===`string`?new e({...this,maxLength:t}):this.type===`number`?new e({...this,maximum:t}):this}email(){return this.type===`string`?new e({...this,format:`email`}):this}url(){return this.type===`string`?new e({...this,format:`uri`}):this}regex(t,n){return this.type===`string`?new e({...this,pattern:t,patternDescription:n}):this}date(){return this.type===`string`?new e({...this,format:`date`}):this}datetime(){return this.type===`string`?new e({...this,format:`date-time`}):this}get"~standard"(){return{version:1,vendor:`ax`,validate:e=>{try{let t={name:`value`,type:{name:this.type,isArray:this.isArray||void 0,options:this.options?[...this.options]:void 0,minLength:this.minLength,maxLength:this.maxLength,minimum:this.minimum,maximum:this.maximum,pattern:this.pattern,patternDescription:this.patternDescription,format:this.format},isOptional:this.isOptional||void 0};return e==null&&this.isOptional||It(t,e),{value:e}}catch(e){return{issues:[{message:e instanceof Error?e.message:String(e)}]}}}}}};const Wt=e=>{let t=e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z])([A-Z][a-z])/g,`$1 $2`).replace(/([^0-9])([0-9])/g,`$1 $2`).replace(/\s+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)},K=Object.assign(()=>new Ht,{string:e=>new Ut({type:`string`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),score:(e,t)=>(Je({type:`score`,options:e}),new Ut({type:`score`,isArray:!1,options:e,description:t,isOptional:!1,isInternal:!1,isCached:!1})),number:e=>new Ut({type:`number`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),boolean:e=>new Ut({type:`boolean`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),json:e=>new Ut({type:`json`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),datetime:e=>new Ut({type:`datetime`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),datetimeRange:e=>new Ut({type:`datetimeRange`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),date:e=>new Ut({type:`date`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),dateRange:e=>new Ut({type:`dateRange`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),class:(e,t)=>new Ut({type:`class`,isArray:!1,options:e,description:t,isOptional:!1,isInternal:!1,isCached:!1}),image:e=>new Ut({type:`image`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),audio:e=>new Ut({type:`audio`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),file:e=>new Ut({type:`file`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),url:e=>new Ut({type:`url`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),email:e=>new Ut({type:`string`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1,format:`email`}),code:(e,t)=>new Ut({type:`code`,isArray:!1,description:t||e,language:e,isOptional:!1,isInternal:!1,isCached:!1}),object:(e,t)=>new Ut({type:`object`,isArray:!1,fields:e,description:t,isOptional:!1,isInternal:!1,isCached:!1})});function Gt(e){return{type:e.type,isArray:e.isArray,options:e.options,description:e.description,isOptional:e.isOptional,isInternal:e.isInternal,minLength:e.minLength,maxLength:e.maxLength,minimum:e.minimum,maximum:e.maximum,pattern:e.pattern,patternDescription:e.patternDescription,valueDescriptions:e.valueDescriptions,evidence:e.evidence,format:e.format,language:e.language,fields:e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,Gt(t)])):void 0}}function Kt(e){return{type:{name:e.type,isArray:e.isArray,options:e.options?[...e.options]:void 0,fields:e.fields,minLength:e.minLength,maxLength:e.maxLength,minimum:e.minimum,maximum:e.maximum,pattern:e.pattern,patternDescription:e.patternDescription,valueDescriptions:e.valueDescriptions,evidence:e.evidence,format:e.format,language:e.language},description:e.description,isOptional:e.isOptional,isInternal:e.isInternal}}function qt(e,t){return{name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,valueDescriptions:t.valueDescriptions,evidence:t.evidence,format:t.format,language:t.language,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([e,t])=>[e,Gt(t)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||void 0}}function Jt(e){return e.length===0?{type:`object`,properties:{}}:gt(e,`Schema`)}function Yt(e){return gt([qt(`__value`,e)],`Schema`).properties?.__value??{type:`json`}}var Xt=class{name;desc;ns;argFields=[];returnFields=[];returnFieldType;returnMode;returnJsonSchema;fnHandler;fnExamples=[];executionMode=`blocking`;execution(e){return this.executionMode=e,this}constructor(e){this.name=e}description(e){return this.desc=e,this}namespace(e){return this.ns=e,this}arg(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`arg() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.argFields.push(e);return this}if(Ct(t))return this.argFields.push(Mt(e,t,n)),this;let r=t;return this.argFields.push(qt(e,r)),this}returns(e,t){if(Ct(e)){if(this.returnMode)throw Error(`Cannot use fn().returns(zodSchema) after fn().returns/returnsField(...); choose exactly one return schema style`);if(kt(e)){let n=jt(e,t);this.returnMode=`fields`;for(let e of n)this.returnFields.push(e)}else this.returnMode=`single`,this.returnJsonSchema=At(e);return this}if(this.returnMode===`fields`)throw Error(`Cannot use fn().returns(...) after fn().returnsField(...); choose exactly one return schema style`);return this.returnMode=`single`,this.returnFieldType=e,this}returnsField(e,t,n){if(this.returnMode===`single`)throw Error(`Cannot use fn().returnsField(...) after fn().returns(...); choose exactly one return schema style`);if(this.returnMode=`fields`,Ct(t))return this.returnFields.push(Mt(e,t,n)),this;let r=t;return this.returnFields.push(qt(e,r)),this}example(e){return this.fnExamples.push(e),this}examples(e){return this.fnExamples.push(...e),this}handler(e){return this.fnHandler=e,this}build(){let e=this.name.trim(),t=this.desc?.trim(),n=this.ns?.trim();if(!e)throw Error(`fn() requires a non-empty function name`);if(!t)throw Error(`Function "${e}" must define a non-empty description`);if(!this.fnHandler)throw Error(`Function "${e}" must define a handler`);if(this.fnExamples.some(e=>!e.code.trim()))throw Error(`Function "${e}" examples must define non-empty code`);return{name:e,description:t,...n?{namespace:n}:{},execution:this.executionMode,parameters:Jt(this.argFields),...this.returnMode===`single`&&this.returnJsonSchema?{returns:this.returnJsonSchema}:this.returnMode===`single`&&this.returnFieldType?{returns:Yt(this.returnFieldType)}:this.returnMode===`fields`?{returns:Jt(this.returnFields)}:{},...this.fnExamples.length>0?{examples:this.fnExamples.map(e=>({...e}))}:{},func:this.fnHandler}}};const Zt=e=>new Xt(e);var q=class extends Error{fieldName;suggestion;constructor(e,t,n){super(e),this.fieldName=t,this.suggestion=n,this.name=`AxSignatureValidationError`}},J=class e{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(t){if(!t){this.inputFields=[],this.outputFields=[],this.sigHash=``,this.sigString=``;return}if(typeof t==`string`){let e;try{e=xt(t)}catch(e){if(e instanceof Error){let t=`suggestion`in e&&typeof e.suggestion==`string`?e.suggestion:`Please check the signature format. Example: "userInput:string -> responseText:string"`;throw new q(`Invalid Signature: ${e.message}`,void 0,t)}throw new q(`Invalid Signature: ${t}`,void 0,`Please check the signature format. Example: "userInput:string -> responseText:string"`)}this.description=e.desc,this.inputFields=e.inputs.map(e=>this.parseParsedField(e)),this.outputFields=e.outputs.map(e=>this.parseParsedField(e)),[this.sigHash,this.sigString]=this.updateHash()}else if(t instanceof e)this.description=t.getDescription(),this.inputFields=t.getInputFields().map(e=>this.parseField(e)),this.outputFields=t.getOutputFields().map(e=>this.parseField(e)),this.sigHash=t.hash(),this.sigString=t.toString(),t.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=t._forceComplexFields,this._hasComplexFields=t._hasComplexFields;else if(typeof t==`object`&&t){if(!(`inputs`in t)||!(`outputs`in t))throw new q(`Invalid signature object: missing inputs or outputs`,void 0,`Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }`);if(!Array.isArray(t.inputs)||!Array.isArray(t.outputs))throw new q(`Invalid signature object: inputs and outputs must be arrays`,void 0,`Both "inputs" and "outputs" must be arrays of AxField objects`);try{this.description=t.description,this.inputFields=t.inputs.map(e=>this.parseField(e)),this.outputFields=t.outputs.map(e=>this.parseField(e)),[this.sigHash,this.sigString]=this.updateHash()}catch(e){throw e instanceof q?e:new q(`Failed to create signature from object: ${e instanceof Error?e.message:`Unknown error`}`,void 0,`Check that all fields in inputs and outputs arrays are valid AxField objects`)}}else throw new q(`Invalid signature argument type`,void 0,`Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays`)}static create(t){return e.from(t)}static from(t){return new e(t)}static empty(){return new e}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new q(`Field name is required`,e.name,`Every field must have a descriptive name. Example: "userInput", "responseText"`);let t=this.toTitle(e.name);return{name:e.name,title:t,description:`desc`in e?e.desc:void 0,type:e.type??{name:`string`,isArray:!1},...`isInternal`in e?{isInternal:e.isInternal}:{},...`isOptional`in e?{isOptional:e.isOptional}:{},...`isCached`in e&&e.isCached?{isCached:!0}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new q(`Field type name is required`,e.name,`Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, dateRange, datetime, datetimeRange, class, code`);return{...e,title:t}};setDescription=e=>{if(typeof e!=`string`)throw new q(`Description must be a string`,void 0,`Provide a string description for the signature`);this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);on(t,`input`);for(let e of this.inputFields)if(e.name===t.name)throw new q(`Duplicate input field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);for(let e of this.outputFields)if(e.name===t.name)throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:`Unknown error`}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);on(t,`output`);for(let e of this.outputFields)if(e.name===t.name)throw new q(`Duplicate output field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);for(let e of this.inputFields)if(e.name===t.name)throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:`Unknown error`}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new q(`Input fields must be an array`,void 0,`Provide an array of field objects`);try{let t=e.map(e=>{let t=this.parseField(e);return on(t,`input`),t});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(e){throw e instanceof q?e:new q(`Failed to set input fields: ${e instanceof Error?e.message:`Unknown error`}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new q(`Output fields must be an array`,void 0,`Provide an array of field objects`);try{let t=e.map(e=>{let t=this.parseField(e);return on(t,`output`),t});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(e){throw e instanceof q?e:new q(`Failed to set output fields: ${e instanceof Error?e.message:`Unknown error`}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(t,n)=>{let r=e.from(this);return r.addInputField({name:t,...Kt(n)}),r};prependInputField=(t,n)=>{let r=e.from(this),i={name:t,...Kt(n)},a=r.parseField(i);on(a,`input`);for(let e of r.inputFields)if(e.name===a.name)throw new q(`Duplicate input field name: "${a.name}"`,a.name,`Each field name must be unique within the signature`);for(let e of r.outputFields)if(e.name===a.name)throw new q(`Field name "${a.name}" appears in both inputs and outputs`,a.name,`Use different names for input and output fields to avoid confusion`);return r.inputFields.unshift(a),r.invalidateValidationCache(),r.updateHashLight(),r};appendOutputField=(t,n)=>{let r=e.from(this);return r.addOutputField({name:t,...Kt(n)}),r};prependOutputField=(t,n)=>{let r=e.from(this),i={name:t,...Kt(n)},a=r.parseField(i);on(a,`output`);for(let e of r.outputFields)if(e.name===a.name)throw new q(`Duplicate output field name: "${a.name}"`,a.name,`Each field name must be unique within the signature`);for(let e of r.inputFields)if(e.name===a.name)throw new q(`Field name "${a.name}" appears in both inputs and outputs`,a.name,`Use different names for input and output fields to avoid confusion`);return r.outputFields.unshift(a),r.invalidateValidationCache(),r.updateHashLight(),r};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>Wt(e);updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{on(e,`input`)}),this.getOutputFields().forEach(e=>{on(e,`output`)}),this.sigHash=m(`sha256`).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest(`hex`),this.sigString=rn(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`Signature validation failed: ${e instanceof Error?e.message:`Unknown error`}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{on(e,`input`)}),this.getOutputFields().forEach(e=>{on(e,`output`)}),this.validateSignatureConsistency(),this.sigHash=m(`sha256`).update(this.description??``).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest(`hex`),this.sigString=rn(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`Signature validation failed: ${e instanceof Error?e.message:`Unknown error`}`)}};validateSignatureConsistency(){let e=/* @__PURE__ */ new Set;for(let t of this.inputFields){if(e.has(t.name))throw new q(`Duplicate input field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);e.add(t.name)}let t=/* @__PURE__ */ new Set;for(let e of this.outputFields){if(t.has(e.name))throw new q(`Duplicate output field name: "${e.name}"`,e.name,`Each field name must be unique within the signature`);t.add(e.name)}for(let t of this.outputFields)if(e.has(t.name))throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);if(this.inputFields.length===0)throw new q(`Signature must have at least one input field`,void 0,`Add an input field. Example: "userInput:string -> ..."`);if(this.outputFields.length===0)throw new q(`Signature must have at least one output field`,void 0,`Add an output field. Example: "... -> responseText:string"`)}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>(this._hasComplexFields===void 0&&(this._hasComplexFields=this.computeHasComplexFields()),this._hasComplexFields);computeHasComplexFields=()=>Xe(this.outputFields)||this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name===`object`||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>gt([...this.inputFields,...this.outputFields],this.description??`Schema`,{decisionMode:`result`});toInputJSONSchema=()=>gt(this.inputFields,this.description??`Schema`,{decisionMode:`result`})};function Qt(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function $t(e,t){let n=st(e).map(([t,n])=>`${e.name===`boolean`?t:`"${Qt(t)}"`} "${Qt(n)}"`);e.evidence&&(n.push(`evidence`),e.evidence.threshold!==void 0&&n.push(`threshold ${e.evidence.threshold}`),e.evidence.onRefusal!==void 0&&n.push(`refusal ${e.evidence.onRefusal}`));let r=e.minLength??e.minimum,i=e.maxLength??e.maximum;if(r!==void 0&&n.push(`min ${r}`),i!==void 0&&n.push(`max ${i}`),e.format!==void 0&&n.push(`format ${e.format}`),e.pattern!==void 0){let t=`pattern "${Qt(e.pattern)}"`;n.push(e.patternDescription===void 0?t:`${t} "${Qt(e.patternDescription)}"`)}return e.name!==`class`&&e.isArray&&e.description&&n.push(`item "${Qt(e.description)}"`),e.name===`code`&&e.language&&n.push(e.language),t&&n.push(`cache`),n.length>0?`(${n.join(`, `)})`:``}function en(e){if(e.type===`class`||e.type===`score`){let t=e.type;return e.isArray&&(t+=`[]`),t+=` "${Qt((e.options??[]).join(` | `))}"`,t+=$t({...e,name:e.type},void 0),t}if(e.type===`object`&&e.fields){let t=`object${tn(e.fields)}`;return e.isArray&&(t+=`[]`),t}let t=e.type;return t+=$t({name:e.type,...e},void 0),e.isArray&&(t+=`[]`),t}function tn(e){return`{ ${Object.entries(e).map(([e,t])=>{let n=e;return t.isOptional&&(n+=`?`),n+=`:${en(t)}`,t.description&&(t.type!==`code`||t.description!==t.language)&&(n+=` "${Qt(t.description)}"`),n}).join(`, `)} }`}function nn(e){let t=e.name;return e.isOptional&&(t+=`?`),e.isInternal&&(t+=`!`),e.type?e.type.name===`object`&&e.type.fields?(t+=`:object${tn(e.type.fields)}`,e.type.isArray&&(t+=`[]`)):(t+=`:${e.type.name}`,e.type.name!==`class`&&e.type.name!==`score`&&(t+=$t(e.type,e.isCached)),e.type.isArray&&(t+=`[]`),(e.type.name===`class`||e.type.name===`score`)&&e.type.options&&(t+=` "${Qt(e.type.options.join(` | `))}"`,t+=$t(e.type,void 0))):e.isCached&&(t+=`:string(cache)`),e.description&&(e.type?.name!==`code`||e.description!==e.type.language)&&(t+=` "${Qt(e.description)}"`),t}function rn(e,t,n){return`${e?`"${e}" `:``}${t.map(nn).join(`, `)} -> ${n.map(nn).join(`, `)}`}function an(e){return/^[a-z][a-zA-Z0-9]*$/.test(e)||/^[a-z]+(_[a-z0-9]+)*$/.test(e)}function on(e,t){if(!e.name||e.name.length===0)throw new q(`Field name cannot be blank`,e.name,`Every field must have a descriptive name`);if(!an(e.name))throw new q(`Invalid field name '${e.name}' - must be camelCase or snake_case`,e.name,`Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")`);if(H.signatureStrict&&[`text`,`object`,`image`,`string`,`number`,`boolean`,`json`,`array`,`daterange`,`datetimerange`,`datetime`,`date`,`time`,`type`,`class`,`input`,`output`,`data`,`value`,`result`,`response`,`request`,`item`,`element`].includes(e.name.toLowerCase())){let n=t===`input`?[`userInput`,`questionText`,`documentContent`,`messageText`,`queryString`]:[`responseText`,`analysisResult`,`categoryType`,`summaryText`,`outputData`];throw new q(`Field name '${e.name}' is too generic`,e.name,`Use a more descriptive name. Examples for ${t} fields: ${n.join(`, `)}`)}if(e.name.length<2)throw new q(`Field name '${e.name}' is too short`,e.name,`Field names must be at least 2 characters long`);if(e.name.length>50)throw new q(`Field name '${e.name}' is too long (${e.name.length} characters)`,e.name,`Field names should be 50 characters or less`);e.type&&sn(e,t)}function sn(e,t){if(!e.type)return;let{type:n}=e;if(Je(n),ot(n.name,n.valueDescriptions,n.options,e.name),(n.name===`image`||n.name===`file`)&&t===`output`)throw new q(`${n.name} type is not supported in output fields`,e.name,`${n.name} types can only be used in input fields`);if(n.name===`audio`&&t===`output`&&n.isArray)throw new q(`audio array type is not supported in output fields`,e.name,`Use a single audio output field instead`);if(n.name===`class`){if(t===`input`&&!n.evidence)throw new q(`Class type is not supported in input fields`,e.name,`Class types are only allowed on output fields. Use "string" type for input classifications`);if(!n.options||n.options.length===0)throw new q(`Class type requires options`,e.name,`Provide class options. Example: class "positive, negative, neutral"`);for(let t of n.options){if(!t||t.trim().length===0)throw new q(`Empty class option found`,e.name,`All class options must be non-empty strings`);let n=t.trim();if(n.includes(`,`)||n.includes(`|`))throw new q(`Invalid class option "${n}"`,e.name,`Class options cannot contain commas (,) or pipes (|) as they are used to separate options`)}if(new Set(n.options.map(e=>e.trim().toLowerCase())).size!==n.options.length)throw new q(`Duplicate class options found`,e.name,`Each class option must be unique (case-insensitive)`)}if(n.name===`code`&&n.isArray)throw new q(`Arrays of code are not commonly supported`,e.name,`Consider using a single code field or an array of strings instead`);if(e.isInternal&&t===`input`)throw new q(`Internal marker (!) is not allowed on input fields`,e.name,`Internal markers are only allowed on output fields`);n.name===`object`&&n.fields&&cn(n.fields,e.name,t)}function cn(e,t,n,r=1){for(let[i,a]of Object.entries(e)){let e=`${t}.${i}`;if(ot(a.type,a.valueDescriptions,a.options,e),a.type===`image`||a.type===`audio`||a.type===`file`)throw new q(`${a.type} type is not allowed in nested object fields`,e,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${r}.`);a.type===`object`&&a.fields&&cn(a.fields,e,n,r+1),a.isArray&&a.fields&&cn(a.fields,`${e}[]`,n,r+1)}}const ln={"dsp/dspy.md":`<identity>
4
+ `),i=[];for(let e of r){let r=e.trim();if(r){if(r[0]&&t.has(r[0]))i.push(r.slice(1).trim());else if(n.test(r))i.push(r.replace(n,``).trim());else if(i.length!==0)throw Error(`Could not parse markdown list: mixed content detected`)}}if(i.length===0)throw Error(`Could not parse markdown list: no valid list items found`);return i};function zt(e,t){let{index:n,delta:r,version:i}=t,a=e.find(e=>e.index===n)?.delta;if(!a)return e.push({index:n,delta:r,version:i}),e;for(let e of Object.keys(r)){let t=a[e],n=r[e];a[e]=t===void 0&&Array.isArray(n)?[...n]:Array.isArray(t)&&Array.isArray(n)?[...t,...n]:(t===void 0||typeof t==`string`)&&typeof n==`string`?`${t??``}${n}`:n}let o=e.find(e=>e.index===n);return o&&(o.version=i),e}const Bt=new class{cache=/* @__PURE__ */ new Map;maxSize;constructor(e){this.maxSize=e}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t)),t}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(e,t)}}(500);function Vt(e,t,n=0,r=Bt){if(/^```[a-zA-Z]*\s*$/.test(e))return-4;if(/^[\s`]*$/.test(e))return-3;let i=e.indexOf(t,n);if(i!==-1)return i;let a=r.get(t)??Array.from({length:t.length},(e,n)=>t.slice(0,n+1));r.get(t)||r.set(t,a);let o=-1;for(let t=a.length-1;t>=0;t--){let n=a[t];if(e.endsWith(n)){o=t;break}}return o>=0?-2:-1}var Ht=class{inputFields=[];outputFields=[];desc;input(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`input() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.inputFields.push(e);return this}if(Ct(t))return this.inputFields.push(Mt(e,t,n)),this;let r=qt(e,t);return n===!0?this.inputFields.unshift(r):this.inputFields.push(r),this}output(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`output() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.outputFields.push(e);return this}if(Ct(t))return this.outputFields.push(Mt(e,t,n)),this;let r=qt(e,t);return n===!0?this.outputFields.unshift(r):this.outputFields.push(r),this}addInputFields(e){for(let t of e)this.inputFields.push(t);return this}addOutputFields(e){for(let t of e)this.outputFields.push(t);return this}description(e){return this.desc=e,this}useStructured(){return this._useStructuredOutputs=!0,this}build(){let e={description:this.desc,inputs:this.inputFields,outputs:this.outputFields},t=J.from(e);return this._useStructuredOutputs&&(t._forceComplexFields=!0,t._hasComplexFields=void 0),t}},Ut=class e{type;isArray;options;description;isOptional;isInternal;isCached;fields;minLength;maxLength;minimum;maximum;pattern;evidence;valueDescriptions;patternDescription;format;language;itemDescription;constructor(e){this.type=e.type,this.evidence=e.evidence,this.isArray=e.isArray,this.options=e.options,this.description=e.description,this.itemDescription=e.itemDescription,this.isOptional=e.isOptional,this.isInternal=e.isInternal,this.isCached=e.isCached,this.fields=e.fields,this.minLength=e.minLength,this.maxLength=e.maxLength,this.minimum=e.minimum,this.maximum=e.maximum,this.pattern=e.pattern,this.patternDescription=e.patternDescription,this.valueDescriptions=e.valueDescriptions?{...e.valueDescriptions}:void 0,this.format=e.format,this.language=e.language}describeValues(t){return ot(this.type,t,this.options),new e({...this,valueDescriptions:t})}withEvidence(t){Je({type:this.type,options:this.options,evidence:t??{}});let n=this;return new e({...n,evidence:t??{}})}optional(){return new e({...this,isOptional:!0})}array(t){return new e({...this,isArray:!0,description:t||this.description,itemDescription:t?this.description:void 0})}internal(){return new e({...this,isInternal:!0})}cache(){return new e({...this,isCached:!0})}min(t){return this.type===`string`?new e({...this,minLength:t}):this.type===`number`?new e({...this,minimum:t}):this}max(t){return this.type===`string`?new e({...this,maxLength:t}):this.type===`number`?new e({...this,maximum:t}):this}email(){return this.type===`string`?new e({...this,format:`email`}):this}url(){return this.type===`string`?new e({...this,format:`uri`}):this}regex(t,n){return this.type===`string`?new e({...this,pattern:t,patternDescription:n}):this}date(){return this.type===`string`?new e({...this,format:`date`}):this}datetime(){return this.type===`string`?new e({...this,format:`date-time`}):this}get"~standard"(){return{version:1,vendor:`ax`,validate:e=>{try{let t={name:`value`,type:{name:this.type,isArray:this.isArray||void 0,options:this.options?[...this.options]:void 0,minLength:this.minLength,maxLength:this.maxLength,minimum:this.minimum,maximum:this.maximum,pattern:this.pattern,patternDescription:this.patternDescription,format:this.format},isOptional:this.isOptional||void 0};return e==null&&this.isOptional||It(t,e),{value:e}}catch(e){return{issues:[{message:e instanceof Error?e.message:String(e)}]}}}}}};const Wt=e=>{let t=e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/([A-Z])([A-Z][a-z])/g,`$1 $2`).replace(/([^0-9])([0-9])/g,`$1 $2`).replace(/\s+/g,` `).trim();return t.charAt(0).toUpperCase()+t.slice(1)},K=Object.assign(()=>new Ht,{string:e=>new Ut({type:`string`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),score:(e,t)=>(Je({type:`score`,options:e}),new Ut({type:`score`,isArray:!1,options:e,description:t,isOptional:!1,isInternal:!1,isCached:!1})),number:e=>new Ut({type:`number`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),boolean:e=>new Ut({type:`boolean`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),json:e=>new Ut({type:`json`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),datetime:e=>new Ut({type:`datetime`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),datetimeRange:e=>new Ut({type:`datetimeRange`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),date:e=>new Ut({type:`date`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),dateRange:e=>new Ut({type:`dateRange`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),class:(e,t)=>new Ut({type:`class`,isArray:!1,options:e,description:t,isOptional:!1,isInternal:!1,isCached:!1}),image:e=>new Ut({type:`image`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),audio:e=>new Ut({type:`audio`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),file:e=>new Ut({type:`file`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),url:e=>new Ut({type:`url`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1}),email:e=>new Ut({type:`string`,isArray:!1,description:e,isOptional:!1,isInternal:!1,isCached:!1,format:`email`}),code:(e,t)=>new Ut({type:`code`,isArray:!1,description:t||e,language:e,isOptional:!1,isInternal:!1,isCached:!1}),object:(e,t)=>new Ut({type:`object`,isArray:!1,fields:e,description:t,isOptional:!1,isInternal:!1,isCached:!1})});function Gt(e){return{type:e.type,isArray:e.isArray,options:e.options,description:e.description,isOptional:e.isOptional,isInternal:e.isInternal,minLength:e.minLength,maxLength:e.maxLength,minimum:e.minimum,maximum:e.maximum,pattern:e.pattern,patternDescription:e.patternDescription,valueDescriptions:e.valueDescriptions,evidence:e.evidence,format:e.format,language:e.language,fields:e.fields?Object.fromEntries(Object.entries(e.fields).map(([e,t])=>[e,Gt(t)])):void 0}}function Kt(e){return{type:{name:e.type,isArray:e.isArray,options:e.options?[...e.options]:void 0,fields:e.fields,minLength:e.minLength,maxLength:e.maxLength,minimum:e.minimum,maximum:e.maximum,pattern:e.pattern,patternDescription:e.patternDescription,valueDescriptions:e.valueDescriptions,evidence:e.evidence,format:e.format,language:e.language},description:e.description,isOptional:e.isOptional,isInternal:e.isInternal}}function qt(e,t){return{name:e,type:{name:t.type,isArray:t.isArray||void 0,options:t.options?[...t.options]:void 0,minLength:t.minLength,maxLength:t.maxLength,minimum:t.minimum,maximum:t.maximum,pattern:t.pattern,patternDescription:t.patternDescription,valueDescriptions:t.valueDescriptions,evidence:t.evidence,format:t.format,language:t.language,description:t.itemDescription,fields:t.fields?Object.fromEntries(Object.entries(t.fields).map(([e,t])=>[e,Gt(t)])):void 0},description:t.description,isOptional:t.isOptional||void 0,isInternal:t.isInternal||void 0,isCached:t.isCached||void 0}}function Jt(e){return e.length===0?{type:`object`,properties:{}}:gt(e,`Schema`)}function Yt(e){return gt([qt(`__value`,e)],`Schema`).properties?.__value??{type:`json`}}var Xt=class{name;desc;ns;argFields=[];returnFields=[];returnFieldType;returnMode;returnJsonSchema;fnHandler;fnExamples=[];executionMode=`blocking`;execution(e){return this.executionMode=e,this}constructor(e){this.name=e}description(e){return this.desc=e,this}namespace(e){return this.ns=e,this}arg(e,t,n){if(typeof e!=`string`){if(!Ct(e))throw Error(`arg() expects a field name + fluent field, or an external Standard Schema object (zod/valibot/arktype).`);let n=jt(e,t);for(let e of n)this.argFields.push(e);return this}if(Ct(t))return this.argFields.push(Mt(e,t,n)),this;let r=t;return this.argFields.push(qt(e,r)),this}returns(e,t){if(Ct(e)){if(this.returnMode)throw Error(`Cannot use fn().returns(zodSchema) after fn().returns/returnsField(...); choose exactly one return schema style`);if(kt(e)){let n=jt(e,t);this.returnMode=`fields`;for(let e of n)this.returnFields.push(e)}else this.returnMode=`single`,this.returnJsonSchema=At(e);return this}if(this.returnMode===`fields`)throw Error(`Cannot use fn().returns(...) after fn().returnsField(...); choose exactly one return schema style`);return this.returnMode=`single`,this.returnFieldType=e,this}returnsField(e,t,n){if(this.returnMode===`single`)throw Error(`Cannot use fn().returnsField(...) after fn().returns(...); choose exactly one return schema style`);if(this.returnMode=`fields`,Ct(t))return this.returnFields.push(Mt(e,t,n)),this;let r=t;return this.returnFields.push(qt(e,r)),this}example(e){return this.fnExamples.push(e),this}examples(e){return this.fnExamples.push(...e),this}handler(e){return this.fnHandler=e,this}build(){let e=this.name.trim(),t=this.desc?.trim(),n=this.ns?.trim();if(!e)throw Error(`fn() requires a non-empty function name`);if(!t)throw Error(`Function "${e}" must define a non-empty description`);if(!this.fnHandler)throw Error(`Function "${e}" must define a handler`);if(this.fnExamples.some(e=>!e.code.trim()))throw Error(`Function "${e}" examples must define non-empty code`);return{name:e,description:t,...n?{namespace:n}:{},execution:this.executionMode,parameters:Jt(this.argFields),...this.returnMode===`single`&&this.returnJsonSchema?{returns:this.returnJsonSchema}:this.returnMode===`single`&&this.returnFieldType?{returns:Yt(this.returnFieldType)}:this.returnMode===`fields`?{returns:Jt(this.returnFields)}:{},...this.fnExamples.length>0?{examples:this.fnExamples.map(e=>({...e}))}:{},func:this.fnHandler}}};const Zt=e=>new Xt(e);var q=class extends Error{fieldName;suggestion;constructor(e,t,n){super(e),this.fieldName=t,this.suggestion=n,this.name=`AxSignatureValidationError`}},J=class e{description;inputFields;outputFields;sigHash;sigString;validatedAtHash;constructor(t){if(!t){this.inputFields=[],this.outputFields=[],this.sigHash=``,this.sigString=``;return}if(typeof t==`string`){let e;try{e=xt(t)}catch(e){if(e instanceof Error){let t=`suggestion`in e&&typeof e.suggestion==`string`?e.suggestion:`Please check the signature format. Example: "userInput:string -> responseText:string"`;throw new q(`Invalid Signature: ${e.message}`,void 0,t)}throw new q(`Invalid Signature: ${t}`,void 0,`Please check the signature format. Example: "userInput:string -> responseText:string"`)}this.description=e.desc,this.inputFields=e.inputs.map(e=>this.parseParsedField(e)),this.outputFields=e.outputs.map(e=>this.parseParsedField(e)),[this.sigHash,this.sigString]=this.updateHash()}else if(t instanceof e)this.description=t.getDescription(),this.inputFields=t.getInputFields().map(e=>this.parseField(e)),this.outputFields=t.getOutputFields().map(e=>this.parseField(e)),this.sigHash=t.hash(),this.sigString=t.toString(),t.validatedAtHash===this.sigHash&&(this.validatedAtHash=this.sigHash),this._forceComplexFields=t._forceComplexFields,this._hasComplexFields=t._hasComplexFields;else if(typeof t==`object`&&t){if(!(`inputs`in t)||!(`outputs`in t))throw new q(`Invalid signature object: missing inputs or outputs`,void 0,`Signature object must have "inputs" and "outputs" arrays. Example: { inputs: [...], outputs: [...] }`);if(!Array.isArray(t.inputs)||!Array.isArray(t.outputs))throw new q(`Invalid signature object: inputs and outputs must be arrays`,void 0,`Both "inputs" and "outputs" must be arrays of AxField objects`);try{this.description=t.description,this.inputFields=t.inputs.map(e=>this.parseField(e)),this.outputFields=t.outputs.map(e=>this.parseField(e)),[this.sigHash,this.sigString]=this.updateHash()}catch(e){throw e instanceof q?e:new q(`Failed to create signature from object: ${e instanceof Error?e.message:`Unknown error`}`,void 0,`Check that all fields in inputs and outputs arrays are valid AxField objects`)}}else throw new q(`Invalid signature argument type`,void 0,`Signature must be a string, another AxSignature instance, or an object with inputs and outputs arrays`)}static create(t){return e.from(t)}static from(t){return new e(t)}static empty(){return new e}parseParsedField=e=>{if(!e.name||e.name.length===0)throw new q(`Field name is required`,e.name,`Every field must have a descriptive name. Example: "userInput", "responseText"`);let t=this.toTitle(e.name);return{name:e.name,title:t,description:`desc`in e?e.desc:void 0,type:e.type??{name:`string`,isArray:!1},...`isInternal`in e?{isInternal:e.isInternal}:{},...`isOptional`in e?{isOptional:e.isOptional}:{},...`isCached`in e&&e.isCached?{isCached:!0}:{}}};parseField=e=>{let t=!e.title||e.title.length===0?this.toTitle(e.name):e.title;if(e.type&&(!e.type.name||e.type.name.length===0))throw new q(`Field type name is required`,e.name,`Specify a valid type. Available types: string, number, boolean, json, image, audio, file, url, date, dateRange, datetime, datetimeRange, class, code`);return{...e,title:t}};setDescription=e=>{if(typeof e!=`string`)throw new q(`Description must be a string`,void 0,`Provide a string description for the signature`);this.description=e,this.invalidateValidationCache(),this.updateHashLight()};addInputField=e=>{try{let t=this.parseField(e);on(t,`input`);for(let e of this.inputFields)if(e.name===t.name)throw new q(`Duplicate input field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);for(let e of this.outputFields)if(e.name===t.name)throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);this.inputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`Failed to add input field "${e.name}": ${t instanceof Error?t.message:`Unknown error`}`,e.name)}};addOutputField=e=>{try{let t=this.parseField(e);on(t,`output`);for(let e of this.outputFields)if(e.name===t.name)throw new q(`Duplicate output field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);for(let e of this.inputFields)if(e.name===t.name)throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);this.outputFields.push(t),this.invalidateValidationCache(),this.updateHashLight()}catch(t){throw t instanceof q?t:new q(`Failed to add output field "${e.name}": ${t instanceof Error?t.message:`Unknown error`}`,e.name)}};setInputFields=e=>{if(!Array.isArray(e))throw new q(`Input fields must be an array`,void 0,`Provide an array of field objects`);try{let t=e.map(e=>{let t=this.parseField(e);return on(t,`input`),t});this.inputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(e){throw e instanceof q?e:new q(`Failed to set input fields: ${e instanceof Error?e.message:`Unknown error`}`)}};setOutputFields=e=>{if(!Array.isArray(e))throw new q(`Output fields must be an array`,void 0,`Provide an array of field objects`);try{let t=e.map(e=>{let t=this.parseField(e);return on(t,`output`),t});this.outputFields=t,this.invalidateValidationCache(),this.updateHashLight()}catch(e){throw e instanceof q?e:new q(`Failed to set output fields: ${e instanceof Error?e.message:`Unknown error`}`)}};getInputFields=()=>this.inputFields;getOutputFields=()=>this.outputFields;getDescription=()=>this.description;appendInputField=(t,n)=>{let r=e.from(this);return r.addInputField({name:t,...Kt(n)}),r};prependInputField=(t,n)=>{let r=e.from(this),i={name:t,...Kt(n)},a=r.parseField(i);on(a,`input`);for(let e of r.inputFields)if(e.name===a.name)throw new q(`Duplicate input field name: "${a.name}"`,a.name,`Each field name must be unique within the signature`);for(let e of r.outputFields)if(e.name===a.name)throw new q(`Field name "${a.name}" appears in both inputs and outputs`,a.name,`Use different names for input and output fields to avoid confusion`);return r.inputFields.unshift(a),r.invalidateValidationCache(),r.updateHashLight(),r};appendOutputField=(t,n)=>{let r=e.from(this);return r.addOutputField({name:t,...Kt(n)}),r};prependOutputField=(t,n)=>{let r=e.from(this),i={name:t,...Kt(n)},a=r.parseField(i);on(a,`output`);for(let e of r.outputFields)if(e.name===a.name)throw new q(`Duplicate output field name: "${a.name}"`,a.name,`Each field name must be unique within the signature`);for(let e of r.inputFields)if(e.name===a.name)throw new q(`Field name "${a.name}" appears in both inputs and outputs`,a.name,`Use different names for input and output fields to avoid confusion`);return r.outputFields.unshift(a),r.invalidateValidationCache(),r.updateHashLight(),r};invalidateValidationCache=()=>{this.validatedAtHash=void 0,this._hasComplexFields=void 0};toTitle=e=>Wt(e);updateHashLight=()=>{try{return this.getInputFields().forEach(e=>{on(e,`input`)}),this.getOutputFields().forEach(e=>{on(e,`output`)}),this.sigHash=m(`sha256`).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest(`hex`),this.sigString=rn(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`Signature validation failed: ${e instanceof Error?e.message:`Unknown error`}`)}};updateHash=()=>{try{return this.getInputFields().forEach(e=>{on(e,`input`)}),this.getOutputFields().forEach(e=>{on(e,`output`)}),this.validateSignatureConsistency(),this.sigHash=m(`sha256`).update(this.description??``).update(JSON.stringify(this.inputFields)).update(JSON.stringify(this.outputFields)).digest(`hex`),this.sigString=rn(this.description,this.inputFields,this.outputFields),this._hasComplexFields=this.computeHasComplexFields(),[this.sigHash,this.sigString]}catch(e){throw e instanceof q?e:new q(`Signature validation failed: ${e instanceof Error?e.message:`Unknown error`}`)}};validateSignatureConsistency(){let e=/* @__PURE__ */ new Set;for(let t of this.inputFields){if(e.has(t.name))throw new q(`Duplicate input field name: "${t.name}"`,t.name,`Each field name must be unique within the signature`);e.add(t.name)}let t=/* @__PURE__ */ new Set;for(let e of this.outputFields){if(t.has(e.name))throw new q(`Duplicate output field name: "${e.name}"`,e.name,`Each field name must be unique within the signature`);t.add(e.name)}for(let t of this.outputFields)if(e.has(t.name))throw new q(`Field name "${t.name}" appears in both inputs and outputs`,t.name,`Use different names for input and output fields to avoid confusion`);if(this.inputFields.length===0)throw new q(`Signature must have at least one input field`,void 0,`Add an input field. Example: "userInput:string -> ..."`);if(this.outputFields.length===0)throw new q(`Signature must have at least one output field`,void 0,`Add an output field. Example: "... -> responseText:string"`)}_forceComplexFields=!1;_hasComplexFields;hasComplexFields=()=>(this._hasComplexFields===void 0&&(this._hasComplexFields=this.computeHasComplexFields()),this._hasComplexFields);computeHasComplexFields=()=>Xe(this.outputFields)||this._forceComplexFields?!0:this.outputFields.some(e=>e.type?.name===`object`||e.type?.isArray&&e.type.fields!==void 0);validate=()=>{if(this.validatedAtHash===this.sigHash)return!0;try{return this.updateHash(),this.validatedAtHash=this.sigHash,!0}catch(e){throw this.validatedAtHash=void 0,e}};hash=()=>this.sigHash;toString=()=>this.sigString;toJSON=()=>({id:this.hash(),description:this.description,inputFields:this.inputFields,outputFields:this.outputFields});toJSONSchema=()=>gt([...this.inputFields,...this.outputFields],this.description??`Schema`,{decisionMode:`result`});toInputJSONSchema=()=>gt(this.inputFields,this.description??`Schema`,{decisionMode:`result`})};function Qt(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function $t(e,t){let n=st(e).map(([t,n])=>`${e.name===`boolean`?t:`"${Qt(t)}"`} "${Qt(n)}"`);e.evidence&&(n.push(`evidence`),e.evidence.threshold!==void 0&&n.push(`threshold ${e.evidence.threshold}`),e.evidence.onRefusal!==void 0&&n.push(`refusal ${e.evidence.onRefusal}`));let r=e.minLength??e.minimum,i=e.maxLength??e.maximum;if(r!==void 0&&n.push(`min ${r}`),i!==void 0&&n.push(`max ${i}`),e.format!==void 0&&n.push(`format ${e.format}`),e.pattern!==void 0){let t=`pattern "${Qt(e.pattern)}"`;n.push(e.patternDescription===void 0?t:`${t} "${Qt(e.patternDescription)}"`)}return e.name!==`class`&&e.isArray&&e.description&&n.push(`item "${Qt(e.description)}"`),e.name===`code`&&e.language&&n.push(e.language),t&&n.push(`cache`),n.length>0?`(${n.join(`, `)})`:``}function en(e){if(e.type===`class`||e.type===`score`){let t=e.type;return e.isArray&&(t+=`[]`),t+=` "${Qt((e.options??[]).join(` | `))}"`,t+=$t({...e,name:e.type},void 0),t}if(e.type===`object`&&e.fields){let t=`object${tn(e.fields)}`;return e.isArray&&(t+=`[]`),t}let t=e.type;return t+=$t({name:e.type,...e},void 0),e.isArray&&(t+=`[]`),t}function tn(e){return`{ ${Object.entries(e).map(([e,t])=>{let n=e;return t.isOptional&&(n+=`?`),n+=`:${en(t)}`,t.description&&(t.type!==`code`||t.description!==t.language)&&(n+=` "${Qt(t.description)}"`),n}).join(`, `)} }`}function nn(e){let t=e.name;return e.isOptional&&(t+=`?`),e.isInternal&&(t+=`!`),e.type?e.type.name===`object`&&e.type.fields?(t+=`:object${tn(e.type.fields)}`,e.type.isArray&&(t+=`[]`)):(t+=`:${e.type.name}`,e.type.name!==`class`&&e.type.name!==`score`&&(t+=$t(e.type,e.isCached)),e.type.isArray&&(t+=`[]`),(e.type.name===`class`||e.type.name===`score`)&&e.type.options&&(t+=` "${Qt(e.type.options.join(` | `))}"`,t+=$t(e.type,void 0))):e.isCached&&(t+=`:string(cache)`),e.description&&(e.type?.name!==`code`||e.description!==e.type.language)&&(t+=` "${Qt(e.description)}"`),t}function rn(e,t,n){return`${e?`"${Qt(e)}" `:``}${t.map(nn).join(`, `)} -> ${n.map(nn).join(`, `)}`}function an(e){return/^[a-z][a-zA-Z0-9]*$/.test(e)||/^[a-z]+(_[a-z0-9]+)*$/.test(e)}function on(e,t){if(!e.name||e.name.length===0)throw new q(`Field name cannot be blank`,e.name,`Every field must have a descriptive name`);if(!an(e.name))throw new q(`Invalid field name '${e.name}' - must be camelCase or snake_case`,e.name,`Use camelCase (e.g., "userInput") or snake_case (e.g., "user_input")`);if(H.signatureStrict&&[`text`,`object`,`image`,`string`,`number`,`boolean`,`json`,`array`,`daterange`,`datetimerange`,`datetime`,`date`,`time`,`type`,`class`,`input`,`output`,`data`,`value`,`result`,`response`,`request`,`item`,`element`].includes(e.name.toLowerCase())){let n=t===`input`?[`userInput`,`questionText`,`documentContent`,`messageText`,`queryString`]:[`responseText`,`analysisResult`,`categoryType`,`summaryText`,`outputData`];throw new q(`Field name '${e.name}' is too generic`,e.name,`Use a more descriptive name. Examples for ${t} fields: ${n.join(`, `)}`)}if(e.name.length<2)throw new q(`Field name '${e.name}' is too short`,e.name,`Field names must be at least 2 characters long`);if(e.name.length>50)throw new q(`Field name '${e.name}' is too long (${e.name.length} characters)`,e.name,`Field names should be 50 characters or less`);e.type&&sn(e,t)}function sn(e,t){if(!e.type)return;let{type:n}=e;if(Je(n),ot(n.name,n.valueDescriptions,n.options,e.name),(n.name===`image`||n.name===`file`)&&t===`output`)throw new q(`${n.name} type is not supported in output fields`,e.name,`${n.name} types can only be used in input fields`);if(n.name===`audio`&&t===`output`&&n.isArray)throw new q(`audio array type is not supported in output fields`,e.name,`Use a single audio output field instead`);if(n.name===`class`){if(t===`input`&&!n.evidence)throw new q(`Class type is not supported in input fields`,e.name,`Class types are only allowed on output fields. Use "string" type for input classifications`);if(!n.options||n.options.length===0)throw new q(`Class type requires options`,e.name,`Provide class options. Example: class "positive, negative, neutral"`);for(let t of n.options){if(!t||t.trim().length===0)throw new q(`Empty class option found`,e.name,`All class options must be non-empty strings`);let n=t.trim();if(n.includes(`,`)||n.includes(`|`))throw new q(`Invalid class option "${n}"`,e.name,`Class options cannot contain commas (,) or pipes (|) as they are used to separate options`)}if(new Set(n.options.map(e=>e.trim().toLowerCase())).size!==n.options.length)throw new q(`Duplicate class options found`,e.name,`Each class option must be unique (case-insensitive)`)}if(n.name===`code`&&n.isArray)throw new q(`Arrays of code are not commonly supported`,e.name,`Consider using a single code field or an array of strings instead`);if(e.isInternal&&t===`input`)throw new q(`Internal marker (!) is not allowed on input fields`,e.name,`Internal markers are only allowed on output fields`);n.name===`object`&&n.fields&&cn(n.fields,e.name,t)}function cn(e,t,n,r=1){for(let[i,a]of Object.entries(e)){let e=`${t}.${i}`;if(ot(a.type,a.valueDescriptions,a.options,e),a.type===`image`||a.type===`audio`||a.type===`file`)throw new q(`${a.type} type is not allowed in nested object fields`,e,`Media types (image, audio, file) can only be used as top-level input fields, not within objects. Found at depth ${r}.`);a.type===`object`&&a.fields&&cn(a.fields,e,n,r+1),a.isArray&&a.fields&&cn(a.fields,`${e}[]`,n,r+1)}}const ln={"dsp/dspy.md":`<identity>
5
5
  {{ identityText }}
6
6
  </identity>{{ if hasFunctions }}
7
7
 
@@ -633,9 +633,9 @@ Rules:
633
633
  - If expectedOutput is present and completionType is final, compare the final output against it.
634
634
  - If expectedActions is present, confirm that the functionCalls align with them.
635
635
  - If forbiddenActions is present, strongly penalize any matching function calls.
636
- - If recursiveTrace or recursiveStats are present, use them to judge decomposition quality, unnecessary fan-out, missed direct-answer opportunities, and cost efficiency.`,n=e?.trim();return n?`${t}\n\nAdditional Evaluation Guidance:\n${n}`:t}function Df(e){let{criteria:t,description:n,randomizeOrder:r,...i}=e;return{...i,maxSteps:1}}function Of(e){let t=e.toLowerCase();return t===`excellent`?1:t===`good`?.8:t===`acceptable`?.5:t===`poor`?.2:t===`unacceptable`?0:.5}function kf(e,t){return t.qualifiedName===e||t.name===e||t.qualifiedName.endsWith(`.${e}`)}function Af(e,t,n){let r=Math.max(0,Math.min(1,e)),i=t.expectedActions??[];if(i.length>0){let e=i.filter(e=>n.functionCalls.some(t=>kf(e,t))).length;r*=.5+.5*(e/i.length)}return(t.forbiddenActions??[]).some(e=>n.functionCalls.some(t=>kf(e,t)))&&(r*=.2),Math.max(0,Math.min(1,r))}function jf(e,t){let n=new Set(e.map(e=>e.id));if(t===`actor`){let e=[...n].filter(e=>e.endsWith(`.actor`));if(e.length===0)throw Error(`AxAgent.optimize(): no actor target is available`);return e.sort()}if(t===`responder`){let e=[...n].filter(e=>e.endsWith(`.responder`)).find(e=>e.startsWith(`task.`));if(e)return[e];if(n.has(`root.responder`))return[`root.responder`];let t=[...n].filter(e=>e.endsWith(`.responder`));if(t.length===0)throw Error(`AxAgent.optimize(): no responder target is available`);return[t.sort()[0]]}if(t===`all`){let e=[...n].filter(e=>(e.startsWith(`ctx.`)||e.startsWith(`task.`))&&(e.endsWith(`.actor`)||e.endsWith(`.responder`)));return(e.length>0?e:[...n]).sort()}let r=[...t];for(let e of r)if(!n.has(e))throw Error(`AxAgent.optimize(): unknown target program ID "${e}"`);return r}function Mf(e){return`[POLICY] ${e} must contain at most one fenced code block. No code from the previous turn was executed.`}function Nf(e){return`Your previous ${e} value contained multiple fenced code blocks, so none of them were executed. On this turn, put every executable statement in one ${e} value with at most one fence.`}function Pf(e,t){let n=e[e.length-1]?.messages;if(n)for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.role!==`assistant`)continue;let i=r.content.replace(/<think>[\s\S]*?<\/think>/g,``).replace(/[^\n]*<\/think>/g,``).trim(),a=`${t}:`,o=i.indexOf(a);return o>=0?i.slice(o+a.length).trim():i}}function Ff(e){let t=!1,n=0;for(let r of e.split(/\r?\n/)){let e=r.match(/```([A-Za-z0-9_-]+)?[ \t]*$/);if(!e)continue;let i=e[1]!==void 0;if(t&&!i){t=!1;continue}if(n++,n>1)return!0;t=!0}return!1}async function If(e,t,n,r,i,a){let{s:o,ai:s,rlm:c,runtimeContext:l,inputState:u,completionState:d,guidanceState:f,actionLogEntries:p,actorMergedOptions:m,summaryForwardOptions:h,functionCallRecords:g,explicitActorDebugHideSystemPrompt:_,contextStage:v,contextThreshold:y,mutableState:b,helpers:x}=e,{refreshActorInstruction:S,buildActorPromptValues:C,measureActorPromptChars:w,renderActionLogParts:T,renderActionLogPartsWithReplayMode:E,resetActorModelErrorState:D,noteActorTurnErrorState:O,syncDiscoveredActorModelNamespaces:k,refreshCheckpointSummary:A}=x,j=S();await i(),u.recomputeTurnInputs(!0);for(let e of u.drainAutoPromotionEvents())await Ic(o.onContextEvent,{kind:`field_auto_promoted`,stage:v,turn:t+1,...e});await A(p.length)&&D();let M=T(),N=M.summary||void 0,P=M.history||`(no actions yet)`,F=zd(f.entries),I=await w(P,F,b.runtimeStateSummary,N),L=I.systemPromptCharacters+I.exampleChatContextCharacters,R=_c(l.effectiveContextConfig.targetPromptChars,L),ee=!!b.checkpointState,te=Pc({mutablePromptChars:I.mutableChatContextCharacters,effectiveBudgetChars:R,checkpointActive:ee}),z=l.effectiveContextConfig.contextHygiene?.pressureMode,ne=l.effectiveContextConfig.contextHygiene?.defaultMode??`none`;if(te!==`ok`&&z&&z!==ne){let e=b.checkpointState,t=E(l.effectiveContextConfig.actionReplay,e?.summary,e?.turns,z),n=t.history||`(no actions yet)`,r=t.summary||void 0,i=await w(n,F,b.runtimeStateSummary,r);i.mutableChatContextCharacters<I.mutableChatContextCharacters&&(M=t,P=n,N=r,I=i,L=I.systemPromptCharacters+I.exampleChatContextCharacters,R=_c(l.effectiveContextConfig.targetPromptChars,L),te=Pc({mutablePromptChars:I.mutableChatContextCharacters,effectiveBudgetChars:R,checkpointActive:ee}))}let re=l.effectiveContextConfig.preset===`full`?void 0:Fc(te);for(let e of M.compactions)await Ic(o.onContextEvent,{kind:`action_compacted`,stage:v,turn:e.turn,mode:e.mode,reason:e.reason,originalChars:e.originalChars,renderedChars:e.renderedChars});await Ic(o.onContextEvent,{kind:`budget_check`,stage:v,turn:t+1,pressure:te,mutablePromptChars:I.mutableChatContextCharacters,fixedPromptChars:L,effectiveBudgetChars:R,targetPromptChars:l.effectiveContextConfig.targetPromptChars,checkpointActive:ee,actionLogEntryCount:p.length,guidanceLogEntryCount:f.entries.length}),y&&I.mutableChatContextCharacters>_c(y,L)&&(P+=`
636
+ - If recursiveTrace or recursiveStats are present, use them to judge decomposition quality, unnecessary fan-out, missed direct-answer opportunities, and cost efficiency.`,n=e?.trim();return n?`${t}\n\nAdditional Evaluation Guidance:\n${n}`:t}function Df(e){let{criteria:t,description:n,randomizeOrder:r,...i}=e;return{...i,maxSteps:1}}function Of(e){let t=e.toLowerCase();return t===`excellent`?1:t===`good`?.8:t===`acceptable`?.5:t===`poor`?.2:t===`unacceptable`?0:.5}function kf(e,t){return t.qualifiedName===e||t.name===e||t.qualifiedName.endsWith(`.${e}`)}function Af(e,t,n){let r=Math.max(0,Math.min(1,e)),i=t.expectedActions??[];if(i.length>0){let e=i.filter(e=>n.functionCalls.some(t=>kf(e,t))).length;r*=.5+.5*(e/i.length)}return(t.forbiddenActions??[]).some(e=>n.functionCalls.some(t=>kf(e,t)))&&(r*=.2),Math.max(0,Math.min(1,r))}function jf(e,t){let n=new Set(e.map(e=>e.id));if(t===`actor`){let e=[...n].filter(e=>e.endsWith(`.actor`));if(e.length===0)throw Error(`AxAgent.optimize(): no actor target is available`);return e.sort()}if(t===`responder`){let e=[...n].filter(e=>e.endsWith(`.responder`)).find(e=>e.startsWith(`task.`));if(e)return[e];if(n.has(`root.responder`))return[`root.responder`];let t=[...n].filter(e=>e.endsWith(`.responder`));if(t.length===0)throw Error(`AxAgent.optimize(): no responder target is available`);return[t.sort()[0]]}if(t===`all`){let e=[...n].filter(e=>(e.startsWith(`ctx.`)||e.startsWith(`task.`))&&(e.endsWith(`.actor`)||e.endsWith(`.responder`)));return(e.length>0?e:[...n]).sort()}let r=[...t];for(let e of r)if(!n.has(e))throw Error(`AxAgent.optimize(): unknown target program ID "${e}"`);return r}function Mf(e){return`[POLICY] ${e} must contain at most one fenced code block. No code from the previous turn was executed.`}function Nf(e){return`Your previous ${e} value contained multiple fenced code blocks, so none of them were executed. On this turn, put every executable statement in one ${e} value with at most one fence.`}function Pf(e,t,n){let r=e[e.length-1]?.messages;if(r)for(let e=r.length-1;e>=0;e--){let i=r[e];if(i?.role!==`assistant`)continue;let a=i.content.replace(/<think>[\s\S]*?<\/think>/g,``).replace(/[^\n]*<\/think>/g,``).trim();try{let e=JSON.parse(a);if(e&&typeof e==`object`&&!Array.isArray(e)){let n=e[t];if(typeof n==`string`)return n}}catch{}let o=`${n}:`,s=a.indexOf(o);return s>=0?a.slice(s+o.length).trim():a}}function Ff(e){let t=!1,n=0;for(let r of e.split(/\r?\n/)){let e=r.match(/```([A-Za-z0-9_-]+)?[ \t]*$/);if(!e)continue;let i=e[1]!==void 0;if(t&&!i){t=!1;continue}if(n++,n>1)return!0;t=!0}return!1}async function If(e,t,n,r,i,a){let{s:o,ai:s,rlm:c,runtimeContext:l,inputState:u,completionState:d,guidanceState:f,actionLogEntries:p,actorMergedOptions:m,summaryForwardOptions:h,functionCallRecords:g,explicitActorDebugHideSystemPrompt:_,contextStage:v,contextThreshold:y,mutableState:b,helpers:x}=e,{refreshActorInstruction:S,buildActorPromptValues:C,measureActorPromptChars:w,renderActionLogParts:T,renderActionLogPartsWithReplayMode:E,resetActorModelErrorState:D,noteActorTurnErrorState:O,syncDiscoveredActorModelNamespaces:k,refreshCheckpointSummary:A}=x,j=S();await i(),u.recomputeTurnInputs(!0);for(let e of u.drainAutoPromotionEvents())await Ic(o.onContextEvent,{kind:`field_auto_promoted`,stage:v,turn:t+1,...e});await A(p.length)&&D();let M=T(),N=M.summary||void 0,P=M.history||`(no actions yet)`,F=zd(f.entries),I=await w(P,F,b.runtimeStateSummary,N),L=I.systemPromptCharacters+I.exampleChatContextCharacters,R=_c(l.effectiveContextConfig.targetPromptChars,L),ee=!!b.checkpointState,te=Pc({mutablePromptChars:I.mutableChatContextCharacters,effectiveBudgetChars:R,checkpointActive:ee}),z=l.effectiveContextConfig.contextHygiene?.pressureMode,ne=l.effectiveContextConfig.contextHygiene?.defaultMode??`none`;if(te!==`ok`&&z&&z!==ne){let e=b.checkpointState,t=E(l.effectiveContextConfig.actionReplay,e?.summary,e?.turns,z),n=t.history||`(no actions yet)`,r=t.summary||void 0,i=await w(n,F,b.runtimeStateSummary,r);i.mutableChatContextCharacters<I.mutableChatContextCharacters&&(M=t,P=n,N=r,I=i,L=I.systemPromptCharacters+I.exampleChatContextCharacters,R=_c(l.effectiveContextConfig.targetPromptChars,L),te=Pc({mutablePromptChars:I.mutableChatContextCharacters,effectiveBudgetChars:R,checkpointActive:ee}))}let re=l.effectiveContextConfig.preset===`full`?void 0:Fc(te);for(let e of M.compactions)await Ic(o.onContextEvent,{kind:`action_compacted`,stage:v,turn:e.turn,mode:e.mode,reason:e.reason,originalChars:e.originalChars,renderedChars:e.renderedChars});await Ic(o.onContextEvent,{kind:`budget_check`,stage:v,turn:t+1,pressure:te,mutablePromptChars:I.mutableChatContextCharacters,fixedPromptChars:L,effectiveBudgetChars:R,targetPromptChars:l.effectiveContextConfig.targetPromptChars,checkpointActive:ee,actionLogEntryCount:p.length,guidanceLogEntryCount:f.entries.length}),y&&I.mutableChatContextCharacters>_c(y,L)&&(P+=`
637
637
 
638
- [HINT: Actor prompt is large. Call \`const state = await inspectRuntime()\` for a compact snapshot of current variables instead of re-reading old outputs.]`);let ie=m;if(o.executorModelPolicy){k();let e=Mc(o.executorModelPolicy,Ec(b.actorModelState),Dc(b.actorModelState));ie=e===void 0?m:{...m,model:e}}let B=_??(t>0&&j===b.lastDebugLoggedActorInstruction);ie={...ie,debugHideSystemPrompt:B,functions:l.getNativeFunctions?.(ie)};let ae=o.actorProgram.getUsage()?.length??0,V=c.actorTurnCallback,oe=await o.actorProgram.forward(s,C(P,F,b.runtimeStateSummary,N,re),ie);B||(b.lastDebugLoggedActorInstruction=j);let se=V?o.actorProgram.getUsage()?.slice(ae):void 0,ce=ie.model===void 0?void 0:String(ie.model),le=o.actorProgram.getChatLog(),H=V?Rd(le):void 0;t===0&&(b.restoreNotice=void 0);let ue=o.runtimeCodeFieldName??`javascriptCode`,de=o.runtimeCodeFieldTitle??`Javascript Code`,U=oe[ue],fe=U?.trim(),pe=Pf(le,de)?.trim()??fe,me=typeof pe==`string`&&Ff(pe);if(me)U=pe;else{if(!U||!fe)return{shouldBreak:!0,shouldContinue:!1};U=Tf(fe)}oe[ue]=U,d.payload=void 0;let he=g?.length??0;if(me||o.enforceIncrementalConsoleTurns){let e=me?{violation:Mf(de)}:Zu(U);if(e?.autoSplitDiscoveryCode&&await l.executeActorCode(e.autoSplitDiscoveryCode),e?.violation){let t=e.violation,n=p.length+1;return Ld(f.entries,{turn:n,guidance:me?Nf(de):`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.`,triggeredBy:`runtime policy`}),p.push({turn:n,code:U,output:[...l.consumeNativeToolActivity?.()??[],t].join(`
638
+ [HINT: Actor prompt is large. Call \`const state = await inspectRuntime()\` for a compact snapshot of current variables instead of re-reading old outputs.]`);let ie=m;if(o.executorModelPolicy){k();let e=Mc(o.executorModelPolicy,Ec(b.actorModelState),Dc(b.actorModelState));ie=e===void 0?m:{...m,model:e}}let B=_??(t>0&&j===b.lastDebugLoggedActorInstruction);ie={...ie,debugHideSystemPrompt:B,functions:l.getNativeFunctions?.(ie)};let ae=o.actorProgram.getUsage()?.length??0,V=c.actorTurnCallback,oe=await o.actorProgram.forward(s,C(P,F,b.runtimeStateSummary,N,re),ie);B||(b.lastDebugLoggedActorInstruction=j);let se=V?o.actorProgram.getUsage()?.slice(ae):void 0,ce=ie.model===void 0?void 0:String(ie.model),le=o.actorProgram.getChatLog(),H=V?Rd(le):void 0;t===0&&(b.restoreNotice=void 0);let ue=o.runtimeCodeFieldName??`javascriptCode`,de=o.runtimeCodeFieldTitle??`Javascript Code`,U=oe[ue],fe=U?.trim(),pe=Pf(le,ue,de)?.trim()??fe,me=typeof pe==`string`&&Ff(pe);if(me)U=pe;else{if(!U||!fe)return{shouldBreak:!0,shouldContinue:!1};U=Tf(fe)}oe[ue]=U,d.payload=void 0;let he=g?.length??0;if(me||o.enforceIncrementalConsoleTurns){let e=me?{violation:Mf(de)}:Zu(U);if(e?.autoSplitDiscoveryCode&&await l.executeActorCode(e.autoSplitDiscoveryCode),e?.violation){let t=e.violation,n=p.length+1;return Ld(f.entries,{turn:n,guidance:me?Nf(de):`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.`,triggeredBy:`runtime policy`}),p.push({turn:n,code:U,output:[...l.consumeNativeToolActivity?.()??[],t].join(`
639
639
  `),tags:[`error`],...(()=>{let e=g?.slice(he)??[];return e.length>0?{_functionCalls:e}:{}})()}),V&&await V({stage:v,turn:n,actionLogEntryCount:p.length,guidanceLogEntryCount:f.entries.length,executorResult:oe,code:U,result:void 0,output:t,isError:!0,thought:typeof oe.thought==`string`?oe.thought:void 0,usage:se,model:ce,chatLogMessages:H}),await Hl(p,p.length-1,l.effectiveContextConfig,s,h,{stage:v,onContextEvent:o.onContextEvent}),O(!0),await A(n)&&D(),{shouldBreak:!1,shouldContinue:!0}}}o.inputUpdateCallback&&await l.syncRuntimeInputsToSession();let ge,_e,ve,ye;try{let e=await l.executeActorCode(U);ge=e.result,_e=e.output,ve=e.isError,ye=e.isCodeError===!0}catch(e){if(e instanceof Pi||e instanceof X||o.shouldBubbleUserError(e)){let t=e instanceof Error?e:Error(String(e));V&&await V({stage:v,turn:p.length+1,actionLogEntryCount:p.length,guidanceLogEntryCount:f.entries.length,executorResult:oe,code:U,result:void 0,output:Su(t,l.effectiveContextConfig.maxRuntimeChars),isError:e instanceof X||o.shouldBubbleUserError(e),thought:typeof oe.thought==`string`?oe.thought:void 0,usage:se,model:ce,chatLogMessages:H})}throw e}let be=d.payload,xe=be?.type===`guide_agent`?be:void 0;if(xe){let e=p.length+1;Ld(f.entries,{turn:e,guidance:xe.guidance,...xe.triggeredBy?{triggeredBy:xe.triggeredBy}:{}}),ge=void 0,_e=Bd(xe),ve=!1,ye=!1}let Se=ve&&!ye,Ce=l.consumeDiscoveryTurnArtifacts();Se||(_e=Fd(_e,Ce.texts),_e=Id(_e,Ce.summary)),_e=[...l.consumeNativeToolActivity?.()??[],_e].join(`
640
640
  `);let we=p.length+1,Te=xe?Vd(xe):U;return p.push({turn:we,code:Te,output:_e,tags:ve?[`error`]:[],...(()=>{let e=g?.slice(he)??[];return e.length>0?{_functionCalls:e}:{}})()}),V&&await V({stage:v,turn:we,actionLogEntryCount:p.length,guidanceLogEntryCount:f.entries.length,executorResult:oe,code:U,result:ge,output:_e,isError:ve,thought:typeof oe.thought==`string`?oe.thought:void 0,usage:se,model:ce,chatLogMessages:H}),await Hl(p,p.length-1,l.effectiveContextConfig,s,h,{stage:v,onContextEvent:o.onContextEvent}),Se||(b.runtimeStateSummary=await l.captureRuntimeStateSummary()),O(ve),await A(we)&&D(),d.payload&&`guidance`in d.payload?(d.payload=void 0,{shouldBreak:!1,shouldContinue:!0}):d.payload?{shouldBreak:!0,shouldContinue:!1}:{shouldBreak:!1,shouldContinue:!1}}const Lf=`failures_to_avoid`;function Rf(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t-1)}…`:n}function zf(e){let t=e.split(`
641
641
  `).map(e=>e.trim()).filter(Boolean);return t.find(e=>/\b\w+Error:/.test(e)&&!e.startsWith(`[`))??t.find(e=>!e.startsWith(`[`)&&!e.startsWith(`...`))??Hc(e)}function Bf(e){let t=e.map(e=>({turn:e.turn,code:e.code,output:e.output,tags:[...e.tags],...e.producedVars?{producedVars:[...e.producedVars]}:{},...e.stepKind?{stepKind:e.stepKind}:{}}));for(let e=0;e+1<t.length;e++){let n=t[e],r=t[e+1];n&&r&&xl(n,r)}return new Set(t.filter(e=>e.tags.includes(`dead-end`)).map(e=>e.turn))}function Vf(e,t){let n=`${t.kind}${t.signature}`,r=e.get(n);if(r){r.occurrences+=1;return}e.set(n,{...t,occurrences:1})}function Hf(e,t){try{return Uf(e,t)}catch{return}}function Uf(e,t){if(e.length===0)return;let n=Bf(e),r=/* @__PURE__ */ new Map;if(e.forEach((t,i)=>{if(t.tags.includes(`error`)){let a=Hc(t.output),o=Rf(zf(t.output),200),s=t.code?Rf(t.code,240):void 0,c=e.slice(i+1),l=c.find(e=>!e.tags.includes(`error`)),u=c.some(e=>e.tags.includes(`error`)&&Hc(e.output)===a);if(l&&!u){let e=l.summary??Rf(l.code,120);Vf(r,{kind:`resolved_error`,turn:t.turn,signature:a,detail:e?`${o} — resolved by: ${e}`:o,resolvedByTurn:l.turn,...s?{code:s}:{}})}else n.has(t.turn)?Vf(r,{kind:`dead_end`,turn:t.turn,signature:a,detail:o,...s?{code:s}:{}}):Vf(r,{kind:`error_turn`,turn:t.turn,signature:a,detail:o,...s?{code:s}:{}})}for(let e of t._functionCalls??[]){if(!e.error)continue;let n=Rf(e.error,120);Vf(r,{kind:`tool_error`,turn:t.turn,signature:`${e.qualifiedName}: ${n.slice(0,60)}`,detail:`${e.qualifiedName} failed: ${n}`,...e.arguments===void 0?{}:{code:Rf(Wf(e.arguments),240)}})}}),r.size!==0)return{stage:t,signals:[...r.values()]}}function Wf(e){try{return JSON.stringify(e)??String(e)}catch{return String(e)}}function Gf(e){let t=/* @__PURE__ */ new Map;for(let n of e)for(let e of n?.signals??[]){let n=`${e.kind}${e.signature}`,r=t.get(n);r?r.occurrences+=e.occurrences:t.set(n,{...e})}return[...t.values()]}function Kf(e,t){let n=e.slice(0,12),r=n.map(e=>{let t=e.occurrences>1?` (x${e.occurrences})`:``,n=e.resolvedByTurn===void 0?``:` [resolved in turn ${e.resolvedByTurn}]`,r=e.code?`\n failing code: ${e.code}`:``;return`- (${e.kind}${t}) [${e.signature}] ${e.detail}${n}${r}`}),i=e.length>n.length?`\n(${e.length-n.length} more signals omitted)`:``;return`The agent run for task "${Rf(t,300)}" produced these failure signals: