@genesislcap/foundation-rapid-cdn 15.107.0 → 15.108.0

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.
@@ -250,7 +250,7 @@ function ty(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r
250
250
  `;case`t`:return` `;case`r`:return`\r`;case`b`:return`\b`;case`f`:return`\f`;case`\\`:return`\\`;case`"`:return`"`;case`'`:return`'`;case`/`:return`/`;case`u`:return this.readHexCodepoint(4);case`x`:return this.readHexCodepoint(2);default:return this.bail()}}readHexCodepoint(e){let t=this.src.slice(this.pos,this.pos+e);return(t.length!==e||!/^[0-9a-fA-F]+$/.test(t))&&this.bail(),this.pos+=e,String.fromCharCode(parseInt(t,16))}readNumber(){let e=this.pos;for((this.peek()===`-`||this.peek()===`+`)&&(this.pos+=1);this.pos<this.src.length&&/[0-9.eE+-]/.test(this.src[this.pos]);)this.pos+=1;let t=Number(this.src.slice(e,this.pos));return Number.isFinite(t)||this.bail(),t}readBareword(){switch(this.readIdentifier()){case`true`:case`True`:return!0;case`false`:case`False`:return!1;case`null`:case`None`:return null;default:return this.bail()}}readIdentifier(){let e=this.pos;for(/[A-Za-z_]/.test(this.peek())||this.bail();this.pos<this.src.length&&/[A-Za-z0-9_]/.test(this.src[this.pos]);)this.pos+=1;return this.src.slice(e,this.pos)}isDigit(e){return e>=`0`&&e<=`9`}peek(){return this.pos<this.src.length?this.src[this.pos]:``}skipWhitespace(){for(;this.pos<this.src.length&&/\s/.test(this.src[this.pos]);)this.pos+=1}expect(e){this.src[this.pos]!==e&&this.bail(),this.pos+=1}expectLiteral(e){this.src.slice(this.pos,this.pos+e.length)!==e&&this.bail(),this.pos+=e.length}bail(){throw Error(`MalformedFunctionCallParser: unexpected token`)}};function Noe(e,t){if(!e)return null;let n;try{n=new Moe(e).parse()}catch{return null}return t.has(n.name)?n:null}let Poe=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Foe={"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,"gemini-2.5-flash-lite":1048576,"gemini-4-argon":1048576,"gemini-3.8-flash":1048576,"gemini-3.5-flash":1048576,"gemini-3.1-flash-lite":1048576,"gemini-3.1-pro-preview":1048576};function Ioe(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Loe(e){if(!nx.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${nx.join(`, `)}.`)}let Roe={"gemini-2.5-flash":`GeminiTransport: using gemini-2.5-flash — higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-2.5-pro":`GeminiTransport: using gemini-2.5-pro — significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`,"gemini-3.5-flash":`GeminiTransport: using gemini-3.5-flash — frontier model, materially higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-3.8-flash":`GeminiTransport: using gemini-3.8-flash — frontier model, materially higher cost than flash-lite. Billed at an introductory $0.75/$3.75 per MTok through 2026-12-31 and $1.50/$7.50 from 2027-01-01; weigh a tier choice against the later rate.`,"gemini-4-argon":`GeminiTransport: using gemini-4-argon — premium reasoning model, materially higher cost than the flash tiers. Billed at $2/$10 per MTok through 2026-11-30 and $4/$20 from 2026-12-01; weigh a tier choice against the later rate.`,"gemini-3.1-pro-preview":`GeminiTransport: using gemini-3.1-pro-preview — PREVIEW model (no stability guarantee, may be withdrawn) with significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`},RS=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],zoe=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Boe=[`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],zS=[`minimal`,`low`,`medium`,`high`],BS={"gemini-4-argon":[`low`,`medium`,`high`],"gemini-3.8-flash":[`low`,`medium`,`high`],"gemini-3.5-flash":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-flash-lite":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-pro-preview":[`low`,`medium`,`high`]};function VS(e,t){if(!e?.length||e.includes(t))return t;let n=zS.indexOf(t),r=e=>Math.abs(zS.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let HS={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},US=e=>e!==void 0&&e!==`auto`&&e!==`off`;function Voe(e,t){if(US(t)){let n=BS[e];if(n)return{includeThoughts:!0,thinkingLevel:VS(n,HS[t])}}return t===`off`&&RS.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&RS.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let WS=`gemini`;function GS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:ax(r.mimeType),data:ox(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var Hoe=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},KS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!RS.includes(this.model)){this.warnedThinkingClamped=!0,Qb.warn(`GeminiTransport: thinkingPolicy 'off' ignored — ${this.model} runs its default thinking posture and takes no budget we can safely set. Reasoning tokens are still billed at the candidate rate; use a flash tier if you need them gone.`);return}if(US(e)){let t=BS[this.model];if(!t){this.warnedThinkingClamped=!0,Qb.warn(`GeminiTransport: thinkingPolicy '${e}' ignored — ${this.model} takes a numeric thinking budget, not the graded 'thinkingLevel' the Gemini 3 tiers use, so this turn runs at its default reasoning posture. Use a Gemini 3 tier to set reasoning depth.`);return}let n=HS[e],r=VS(t,n);r!==n&&(this.warnedThinkingClamped=!0,Qb.warn(`GeminiTransport: thinkingPolicy '${e}' sent as thinkingLevel '${r}' — ${this.model} does not accept '${n}' (it takes ${t.join(`/`)}). Reasoning bills at the candidate rate, so an upward clamp costs more than you asked for.`))}}}constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=!1;let t=e.model??`gemini-2.5-flash-lite`;Loe(t),this.model=t;let n=Roe[t];n&&Qb.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint}getConfig(){return{provider:`gemini`,model:this.model,contextLimit:Foe[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e,i=[];return t&&(i.push({role:`user`,parts:[{text:t}]}),i.push({role:`model`,parts:[{text:`Understood.`}]})),i.push({role:`user`,parts:[{text:n}]}),(yield this.post({model:this.model,contents:i,responseSchema:r}))?.content??``})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.toGeminiContents(e,t,n?.attachments);n?.tailContext&&r.push({role:`user`,parts:[{text:n.tailContext}]});let i=n?.tools?.length?[{functionDeclarations:n.tools.map(e=>({name:e.name,description:e.description,parameters:Px(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Ioe(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:Voe(this.model,n?.thinkingPolicy)};n?.maxTokens!=null&&(s.maxOutputTokens=n.maxTokens);let c=[...n?.attachments??[],...e.flatMap(e=>e.attachments??[]),...e.flatMap(e=>e.toolResult?.attachments??[])].find(e=>e.kind===`image`&&e.detail);c?.kind===`image`&&c.detail&&zoe.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=cx(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=Boe.includes(this.model),d=n?.responseSchema!=null&&(!i||u),f=yield this.post(Object.assign({model:this.model,contents:r,tools:i,systemInstruction:a,toolConfig:o,generationConfig:s},d?{responseSchema:Px(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=gx(this.model,{promptTokens:t,candidateTokens:n,thoughtTokens:r,cachedTokens:i});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let c=e.COST_DECIMAL_PLACES;return console.log(`--- Gemini Token Usage (${this.model}) ---`),console.log(`Prompt Tokens: ${t} (${i} cached) ($${s.promptUsd.toFixed(c)} + $${s.cacheReadUsd.toFixed(c)})`),console.log(`Candidate Tokens: ${n} (+${r} thinking) ($${s.candidateUsd.toFixed(c)})`),console.log(`Total Cost: $${a.toFixed(c)}`),console.log(`Cache Saved: $${o.toFixed(c)} (lifetime $${this.lifetimeSavingsUsd.toFixed(c)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(c)}`),console.log(`--------------------------`),a}toGeminiContents(e,t,n){let r=[],i=/* @__PURE__ */ new Map;for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;let e=t.role===`user`?`user`:`model`;if(t.toolResult){let e=i.get(t.toolResult.toolCallId)??t.toolResult.toolCallId;r.push({role:`user`,parts:[{functionResponse:{name:e,response:{content:t.toolResult.content}}}]});let n=t.toolResult.attachments??[];n.length&&r.push({role:`user`,parts:n.map(e=>({inlineData:{mimeType:ax(e.mimeType),data:e.data}}))})}else if(t.toolCalls?.length){for(let e of t.toolCalls)i.set(e.id,e.name);r.push({role:`model`,parts:t.toolCalls.map((e,t)=>{let n={functionCall:{name:e.name,args:e.args}},r=e.providerMetadata?.[WS],i=r?.model===this.model?r.thoughtSignature:void 0;return i?n.thoughtSignature=i:t===0&&(n.thoughtSignature=`skip_thought_signature_validator`),n})})}else if(e===`user`&&t.attachments?.length){let{imageParts:e,textParts:n}=GS(t.attachments);r.push({role:`user`,parts:[...e,...t.content?[{text:t.content}]:[],...n]})}else r.push({role:e,parts:[{text:t.content}]})}let{imageParts:a,textParts:o}=GS(n??[]);return(t||a.length||o.length)&&r.push({role:`user`,parts:[...a,...t?[{text:t}]:[],...o]}),r}usageFromGemini(e){if(!e)return{};let t=e,n=this.logTokenUsage(t.promptTokenCount??0,t.candidatesTokenCount??0,t.thoughtsTokenCount??0,t.cachedContentTokenCount??0);return{inputTokens:t.promptTokenCount,outputTokens:t.candidatesTokenCount!=null||t.thoughtsTokenCount!=null?(t.candidatesTokenCount??0)+(t.thoughtsTokenCount??0):void 0,thoughtsTokens:t.thoughtsTokenCount,cacheReadTokens:t.cachedContentTokenCount,cost:n}}fromGeminiResponse(e,t=/* @__PURE__ */ new Set,n){let{inputTokens:r,outputTokens:i,thoughtsTokens:a,cacheReadTokens:o,cost:s}=this.usageFromGemini(e.usageMetadata),c=e?.candidates?.[0],l=c?.content?.parts??[],u=[],d=[],f=[];for(let e of l)if(e.functionCall){let t={model:this.model};e.thoughtSignature&&(t.thoughtSignature=e.thoughtSignature),u.push({id:crypto.randomUUID(),name:e.functionCall.name,args:e.functionCall.args??{},providerMetadata:{[WS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=Noe(c.finishMessage,t);if(!e)throw new Hoe(c.finishMessage);u.push({id:crypto.randomUUID(),name:e.name,args:e.args})}let p=d.join(``),m=f.join(``),h=u.length>0?{role:`assistant`,content:m,reasoning:p||void 0,toolCalls:u}:{role:`assistant`,content:m,reasoning:p||void 0},g=c?.finishReason;(u.length===0&&!p&&!m||g&&g!==`STOP`&&g!==`MALFORMED_FUNCTION_CALL`)&&this.logAbnormalResponse(e,{finishReason:g,functionCallParts:u.length,thoughtParts:d.length,textParts:f.length}),this.guardMaxTokensTruncation(g,u,m,i,n),r!=null&&(h.inputTokens=r),i!=null&&(h.outputTokens=i),o!=null&&(h.cacheReadTokens=o),s!=null&&(h.cost=s);let _=e.promptFeedback?.blockReason;return(g!=null||a!=null||_!=null)&&(h.responseMeta={finishReason:g,thoughtsTokens:a,parts:{functionCall:u.length,thought:d.length,text:f.length},blockReason:_}),h}guardMaxTokensTruncation(e,t,n,r,i){if(e===`MAX_TOKENS`&&(t.length!==0||n.trim()===``))throw new FS(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};Qb.warn(`GeminiTransport: blank/non-STOP response`,{model:this.model,finishReason:t.finishReason,finishMessage:r.finishMessage,parts:{total:t.functionCallParts+t.thoughtParts+t.textParts,functionCall:t.functionCallParts,thought:t.thoughtParts,text:t.textParts},usage:{promptTokenCount:n.promptTokenCount,candidatesTokenCount:n.candidatesTokenCount,thoughtsTokenCount:n.thoughtsTokenCount,totalTokenCount:n.totalTokenCount},promptFeedback:e.promptFeedback,safetyRatings:r.safetyRatings,citationMetadata:r.citationMetadata})}buildEndpoint(e){if(this.apiKey)return{url:`${Poe(this.model)}?key=${this.apiKey}`,payload:this.toDirectPayload(e),headers:{"Content-Type":`application/json`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`GeminiTransport: no API key or server endpoint configured. Set GEMINI_API_KEY in your .env or pass apiKey/serverEndpoint in GeminiAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield bS({url:r,headers:a,body:i,credentials:o,vendorLabel:zx.gemini,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}toDirectPayload(e){let t=Object.assign({},e);return delete t.model,t.responseSchema&&(t.generationConfig=Object.assign(Object.assign({},t.generationConfig),{responseMimeType:`application/json`,responseSchema:t.responseSchema}),delete t.responseSchema),t}};KS.TOKENS_PER_MILLION=1e6,KS.COST_DECIMAL_PLACES=6,KS.RATE_LIMIT_STATUS=429,KS.SERVICE_UNAVAILABLE_STATUS=503,KS.BAD_GATEWAY_STATUS=502,KS.RETRYABLE_STATUSES=[KS.RATE_LIMIT_STATUS,KS.SERVICE_UNAVAILABLE_STATUS,KS.BAD_GATEWAY_STATUS],KS.BACKOFF_BASE_MS=1e3;let Uoe={"gpt-6-astra":922e3,"gpt-6.1-sol":105e4,"gpt-6.1-terra":105e4,"gpt-6-sol":105e4,"gpt-6-luna":105e4},qS=[`gpt-6.1-terra`,`gpt-6-luna`],Woe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Goe(e,t){if(t!==void 0&&t!==`auto`)return t===`off`?qS.includes(e)?`none`:`low`:Woe[t]}function Koe(e){if(e&&e!==`auto`)return e===`required`||e===`none`?e:{type:`function`,name:e.tool}}function qoe(e){let t=e.enforceSchema?Rx(e.parameters,e.name):e.parameters;return{type:`function`,name:e.name,description:e.description,parameters:t,strict:!!e.enforceSchema}}function Joe(e){if(!ix.includes(e))throw Error(`OpenAITransport: unsupported model "${e}". Use one of: ${ix.join(`, `)}.`)}let Yoe={"gpt-6-astra":`OpenAITransport: using gpt-6-astra — flagship model at $10/$50 per MTok; reserve for tasks where the cheaper tiers are insufficient.`,"gpt-6.1-sol":`OpenAITransport: using gpt-6.1-sol — materially higher cost than terra/luna, and it cannot turn reasoning off (thinkingPolicy "off" runs at effort "low").`,"gpt-6-sol":`OpenAITransport: using gpt-6-sol — superseded by gpt-6.1-sol at the same price, and it cannot turn reasoning off.`},JS=`openai`,YS=Object.freeze({mode:`explicit`});function Xoe(e){let t=[],n=[],r=[],i=[],a=[],o;for(let s of e)if(s.type===`reasoning`){t.push(s);for(let e of s.summary??[])e.text&&n.push(e.text)}else if(s.type===`message`){typeof s.phase==`string`&&o!==`final_answer`&&(o=s.phase);for(let e of s.content??[])e.type===`output_text`&&typeof e.text==`string`&&r.push(e.text),e.type===`refusal`&&typeof e.refusal==`string`&&i.push(e.refusal)}else s.type===`function_call`&&a.push({id:String(s.call_id??s.id??crypto.randomUUID()),name:String(s.name),args:tse(s.arguments)});return{reasoning:t,summaryParts:n,textParts:r,refusals:i,toolCalls:a,phase:o}}function XS(e){let t={type:`input_image`,image_url:`data:${ax(e.mimeType)};base64,${ox(e.data)}`};return e.detail&&(t.detail=e.detail===`medium`?`auto`:e.detail),t}function ZS(e,t){let n=[];for(let e of t)e.kind===`image`&&n.push(XS(e));e&&n.push({type:`input_text`,text:e});for(let e of t)e.kind!==`image`&&n.push({type:`input_text`,text:`[File: ${e.name}]\n${e.content}`});return n}function Zoe(e){return e.providerMetadata?.[JS]??e.toolCalls?.[0]?.providerMetadata?.[JS]}function Qoe(e){let{status:t}=e;return rd(e,[`status`])}var QS=class e{constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=/* @__PURE__ */ new Set;let t=e.model??`gpt-6-luna`;Joe(t),this.model=t;let n=Yoe[t];n&&Qb.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint,this.maxTokens=e.maxTokens,this.reasoningSummary=e.reasoningSummary??`none`}getConfig(){return{provider:`openai`,model:this.model,contextLimit:Uoe[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e;return(yield this.sendChatMessage([],n,{systemPrompt:t,responseSchema:r})).content})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.buildRequestBody(e,t,n),i=yield this.post(r,n?.signal),a=this.fromResponse(i,r.max_output_tokens);return this.restoreOptionalFields(a,n),a})}restoreOptionalFields(e,t){let n=ese(t?.tools);for(let t of e.toolCalls??[]){let e=n.get(t.name);e&&$S(t.args,e)}if(!t?.responseSchema||!e.content)return;let{madeNullable:r}=Lx(t.responseSchema);if(r.length)try{let t=JSON.parse(e.content);$S(t,r),e.content=JSON.stringify(t)}catch{}}buildRequestBody(e,t,n){let r=n?.cachePolicy&&n.cachePolicy.scope!=="default"?n.cachePolicy.scope:void 0,i=[];if(n?.systemPrompt){let e={type:`input_text`,text:n.systemPrompt};r&&(e.prompt_cache_breakpoint=YS),i.push({type:`message`,role:`developer`,content:[e]})}i.push(...this.toInputItems(e,t,n?.attachments)),r===`history`&&this.markHistoryBreakpoints(i),n?.tailContext&&i.push({type:`message`,role:`user`,content:[{type:`input_text`,text:n.tailContext}]});let a={model:this.model,input:i,store:!1,include:[`reasoning.encrypted_content`]};if(r&&(a.prompt_cache_options={mode:`explicit`,ttl:`30m`}),n?.tools?.length){a.tools=n.tools.map(qoe);let e=Koe(n.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingClamped(n?.thinkingPolicy);let o=Goe(this.model,n?.thinkingPolicy);o?a.reasoning=o===`none`||this.reasoningSummary===`none`?{effort:o}:{effort:o,summary:this.reasoningSummary}:this.reasoningSummary!==`none`&&(a.reasoning={summary:this.reasoningSummary}),n?.temperature!=null&&o===`none`&&(a.temperature=cx(n.temperature,{defaultTemp:1,maxTemp:2}));let s=n?.maxTokens??this.maxTokens;return s!=null&&(a.max_output_tokens=s),n?.responseSchema&&(a.text={format:{type:`json_schema`,name:`response`,schema:Lx(n.responseSchema).schema,strict:!0}}),a}warnIfThinkingClamped(e){e&&!this.warnedThinkingClamped.has(e)&&(e===`off`&&!qS.includes(this.model)?(this.warnedThinkingClamped.add(e),Qb.warn(`OpenAITransport: thinkingPolicy 'off' sent as effort 'low' — ${this.model} does not accept effort 'none'. Reasoning tokens are billed as output; use gpt-6.1-terra or gpt-6-luna if you need them gone.`)):e===`minimal`&&(this.warnedThinkingClamped.add(e),Qb.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' — OpenAI has no 'minimal' effort.`)))}toInputItems(e,t,n){let r=[],i=/* @__PURE__ */ new Set;for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;if(t.toolResult){r.push(this.toFunctionCallOutput(t));continue}if(t.role===`user`){let e=ZS(t.content,t.attachments??[]);e.length&&r.push({type:`message`,role:`user`,content:e});continue}let e=Zoe(t);if(e?.model===this.model)for(let t of e.reasoning??[]){let e=t.id??t.encrypted_content;i.has(e)||(i.add(e),r.push(Qoe(t)))}if(t.content){let n={type:`message`,role:`assistant`,content:[{type:`output_text`,text:t.content}]};e?.phase&&(n.phase=e.phase),r.push(n)}for(let e of t.toolCalls??[])r.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.args??{})})}let a=ZS(t,n??[]);return a.length&&r.push({type:`message`,role:`user`,content:a}),r}toFunctionCallOutput(e){let t=e.toolResult,n=t.attachments??[];return{type:`function_call_output`,call_id:t.toolCallId,output:[{type:`input_text`,text:t.content},...n.map(XS)]}}markHistoryBreakpoints(e){let t=0;for(let n=e.length-1;n>=0&&t<49;--n){let r=e[n];if(r.role===`developer`)continue;let i=r.type===`function_call_output`?`output`:r.type===`message`&&r.role!==`assistant`?`content`:void 0;if(!i)continue;let a=[...r[i]],o=-1;for(let e=a.length-1;e>=0;--e)if(a[e].type===`input_text`){o=e;break}o<0||(a[o]=Object.assign(Object.assign({},a[o]),{prompt_cache_breakpoint:YS}),e[n]=Object.assign(Object.assign({},r),{[i]:a}),t+=1)}}usageFromResponse(t){if(!t)return{};let n=t,r=n.input_tokens_details?.cached_tokens??0,i=n.input_tokens_details?.cache_write_tokens??0,{costUsd:a,savedUsd:o}=yx(this.model,{inputTokens:n.input_tokens??0,outputTokens:n.output_tokens??0,cacheReadTokens:r,cacheWriteTokens:i,cacheWrite12hTokens:n.input_tokens_details?.cache_write_tokens_details?.ttl_12h_tokens??0});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let s=e.COST_DECIMAL_PLACES;return console.log(`--- OpenAI Token Usage (${this.model}) ---`),console.log(`Input Tokens: ${n.input_tokens??0} (${r} cached, ${i} written)`),console.log(`Output Tokens: ${n.output_tokens??0} (incl. ${n.output_tokens_details?.reasoning_tokens??0} reasoning)`),console.log(`Total Cost: $${a.toFixed(s)}`),console.log(`Cache Saved: $${o.toFixed(s)} (lifetime $${this.lifetimeSavingsUsd.toFixed(s)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(s)}`),console.log(`--------------------------`),{inputTokens:n.input_tokens,outputTokens:n.output_tokens,thoughtsTokens:n.output_tokens_details?.reasoning_tokens,cacheReadTokens:n.input_tokens_details?.cached_tokens,cacheWriteTokens:n.input_tokens_details?.cache_write_tokens,cost:a}}fromResponse(e,t){let n=this.usageFromResponse(e.usage),r=e.output??[],{reasoning:i,summaryParts:a,textParts:o,refusals:s,toolCalls:c,phase:l}=Xoe(r),u={model:this.model};i.length&&(u.reasoning=i),l&&(u.phase=l);let d={[JS]:u};c.length&&(c[0].providerMetadata=d);let f=o.join(``),p=a.join(`
251
251
 
252
252
  `),m=Object.assign({role:`assistant`,content:f,reasoning:p||void 0},c.length?{toolCalls:c}:{providerMetadata:d}),h=e.status;if(h===`failed`)throw $oe(this.model,e.error);let g=e.incomplete_details?.reason,_=s.length&&!f&&!c.length?`refusal`:h===`incomplete`?g??`incomplete`:h;if(_===`refusal`&&Qb.warn(`OpenAITransport: the model refused`,{model:this.model,refusal:s.join(`
253
- `)}),h===`incomplete`&&g===`content_filter`&&(m.content=``,delete m.toolCalls,Qb.warn(`OpenAITransport: response stopped by the content filter; partial output dropped`,{model:this.model,outputTypes:r.map(e=>e.type)})),h===`incomplete`&&g===`max_output_tokens`&&(c.length||!f.trim()))throw new FS(this.model,t,n.outputTokens,c.map(e=>e.name));return!c.length&&!f&&!p&&_!==`refusal`&&_!==`content_filter`&&Qb.warn(`OpenAITransport: blank response`,{model:this.model,status:h,incompleteReason:g,outputTypes:r.map(e=>e.type),usage:e.usage}),n.inputTokens!=null&&(m.inputTokens=n.inputTokens),n.outputTokens!=null&&(m.outputTokens=n.outputTokens),n.cacheReadTokens!=null&&(m.cacheReadTokens=n.cacheReadTokens),n.cacheWriteTokens!=null&&(m.cacheWriteTokens=n.cacheWriteTokens),n.cost!=null&&(m.cost=n.cost),m.model=this.model,(_!=null||n.thoughtsTokens!=null)&&(m.responseMeta={finishReason:_,thoughtsTokens:n.thoughtsTokens,parts:{functionCall:c.length,thought:a.length,text:o.length}}),m}buildEndpoint(e){if(this.apiKey)return{url:`https://api.openai.com/v1/responses`,payload:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiKey}`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield bS({url:r,headers:a,body:i,credentials:o,vendorLabel:zx.openai,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};QS.COST_DECIMAL_PLACES=6,QS.RATE_LIMIT_STATUS=429,QS.SERVER_ERROR_STATUS=500,QS.BAD_GATEWAY_STATUS=502,QS.SERVICE_UNAVAILABLE_STATUS=503,QS.RETRYABLE_STATUSES=[QS.RATE_LIMIT_STATUS,QS.SERVER_ERROR_STATUS,QS.BAD_GATEWAY_STATUS,QS.SERVICE_UNAVAILABLE_STATUS],QS.BACKOFF_BASE_MS=1e3;function $oe(e,t){let{code:n,message:r}=t??{};return/* @__PURE__ */ Error(`OpenAITransport: ${e} response failed${n?` (${n})`:``}: ${r??`no error detail`}`)}function $S(e,t){for(let n of t)eC(e,n.split(`/`).slice(1))}function eC(e,t){if(!e||typeof e!=`object`)return;let[n,...r]=t;if(n===`items`&&Array.isArray(e)){for(let t of e)eC(t,r);return}if(n!==`properties`||!r.length||Array.isArray(e))return;let[i,...a]=r,o=e;if(!a.length){o[i]===null&&delete o[i];return}eC(o[i],a)}function ese(e){let t=/* @__PURE__ */ new Map;for(let n of e??[]){if(!n.enforceSchema)continue;let{madeNullable:e}=Lx(n.parameters);e.length&&t.set(n.name,e)}return t}function tse(e){if(e&&typeof e==`object`)return e;if(typeof e!=`string`||!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return Qb.warn(`OpenAITransport: function_call arguments are not valid JSON`,{raw:e}),{}}}var tC=class e{constructor(){this.noopProvider=new tx}get(t){return t===e.DEFAULT_NAME?this.noopProvider:void 0}default(){return this.noopProvider}defaultName(){return e.DEFAULT_NAME}names(){return[e.DEFAULT_NAME]}getStatus(t){return J(this,void 0,void 0,function*(){var n;return t!==void 0&&t!==e.DEFAULT_NAME?null:(yield(n=this.noopProvider).getStatus?.call(n))??null})}listStatuses(){return J(this,void 0,void 0,function*(){var t;let n=(yield(t=this.noopProvider).getStatus?.call(t))??null;return[{name:e.DEFAULT_NAME,isDefault:!0,status:n}]})}};tC.DEFAULT_NAME=`default`;let nC=N.createInterface(e=>e.singleton(tC)),rC=6e4,iC=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:rC,timeoutMs:iC}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:rC,timeoutMs:iC}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:rC,timeoutMs:iC})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:rC,timeoutMs:iC}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:rC,timeoutMs:iC}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:rC,timeoutMs:iC})})});let aC=O` :host{display: block;width: 800px}.ai-criteria-search{display: flex;flex-direction: column;gap: calc(${B} * 2px)}.ai-criteria-search-row{display: flex;flex-direction: row;gap: calc(${B} * 2px);align-items: center}.criteria-input{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0}.criteria-chips-inline{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0;display: flex;align-items: center;gap: calc(${B} * 1px);overflow-x: auto;padding: 0 calc(${B} * 2px);background: var(--neutral-fill-input-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(var(--control-corner-radius) * 1px);scrollbar-width: none}.criteria-chips-inline::-webkit-scrollbar{display: none}.mic-icon{color: var(--neutral-foreground-rest);fill: currentColor}.criteria-toggle-button, .criteria-clear-button{flex-shrink: 0}.criteria-chip{display: inline-flex;align-items: center;flex-shrink: 0;gap: calc(${B} * 1px);padding: calc(${B} * 0.5px) calc(${B} * 2px);background: var(--neutral-fill-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(${B} * 4px);font-size: var(--type-ramp-minus-1-font-size);color: var(--neutral-foreground-rest);white-space: nowrap}.criteria-chip-field{font-weight: 600}.criteria-chip-operator{color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-style: italic}.criteria-chip-remove{display: inline-flex;align-items: center;justify-content: center;width: 14px;height: 14px;padding: 0;margin-left: calc(${B} * 0.5px);background: none;border: none;cursor: pointer;color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-size: 10px;border-radius: 50%;line-height: 1}.criteria-chip-remove:hover{background: var(--neutral-fill-hover);color: var(--neutral-foreground-rest)}`,nse=e=>T` ${A(()=>Zb(),T`<div class="ai-criteria-search"><div class="ai-criteria-search-row">${A(e=>!e.showingChips,T`<${e}-text-area ${k(`textAreaRef`)}class="criteria-input" placeholder="${e=>e.placeholder}" ?disabled=${e=>e.disabled||e.isInterpreting}:value=${lf(e=>e.inputValue,`string`,`input`)}@blur=${e=>e.handleBlur()}rows="1"></${e}-text-area>`)} ${A(e=>e.showingChips,T`<div class="criteria-chips-inline">${j(e=>e.criteriaChips,T`<span class="criteria-chip"><span class="criteria-chip-field">${e=>e.fieldLabel}</span><span class="criteria-chip-operator">${e=>e.operatorLabel}</span>${A(e=>!!e.valueLabel,T`<span class="criteria-chip-value">${e=>e.valueLabel}</span>`)}<button class="criteria-chip-remove" aria-label="Remove filter" @click=${(e,t)=>t.parent.removeChip(e.groupIndex,e.clauseIndex)}>
253
+ `)}),h===`incomplete`&&g===`content_filter`&&(m.content=``,delete m.toolCalls,Qb.warn(`OpenAITransport: response stopped by the content filter; partial output dropped`,{model:this.model,outputTypes:r.map(e=>e.type)})),h===`incomplete`&&g===`max_output_tokens`&&(c.length||!f.trim()))throw new FS(this.model,t,n.outputTokens,c.map(e=>e.name));return!c.length&&!f&&!p&&_!==`refusal`&&_!==`content_filter`&&Qb.warn(`OpenAITransport: blank response`,{model:this.model,status:h,incompleteReason:g,outputTypes:r.map(e=>e.type),usage:e.usage}),n.inputTokens!=null&&(m.inputTokens=n.inputTokens),n.outputTokens!=null&&(m.outputTokens=n.outputTokens),n.cacheReadTokens!=null&&(m.cacheReadTokens=n.cacheReadTokens),n.cacheWriteTokens!=null&&(m.cacheWriteTokens=n.cacheWriteTokens),n.cost!=null&&(m.cost=n.cost),m.model=this.model,(_!=null||n.thoughtsTokens!=null)&&(m.responseMeta={finishReason:_,thoughtsTokens:n.thoughtsTokens,parts:{functionCall:c.length,thought:a.length,text:o.length}}),m}buildEndpoint(e){if(this.apiKey)return{url:`https://api.openai.com/v1/responses`,payload:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiKey}`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield bS({url:r,headers:a,body:i,credentials:o,vendorLabel:zx.openai,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};QS.COST_DECIMAL_PLACES=6,QS.RATE_LIMIT_STATUS=429,QS.SERVER_ERROR_STATUS=500,QS.BAD_GATEWAY_STATUS=502,QS.SERVICE_UNAVAILABLE_STATUS=503,QS.RETRYABLE_STATUSES=[QS.RATE_LIMIT_STATUS,QS.SERVER_ERROR_STATUS,QS.BAD_GATEWAY_STATUS,QS.SERVICE_UNAVAILABLE_STATUS],QS.BACKOFF_BASE_MS=1e3;function $oe(e,t){let{code:n,message:r}=t??{};return/* @__PURE__ */ Error(`OpenAITransport: ${e} response failed${n?` (${n})`:``}: ${r??`no error detail`}`)}function $S(e,t){for(let n of t)eC(e,n.split(`/`).slice(1))}function eC(e,t){if(!e||typeof e!=`object`)return;let[n,...r]=t;if(n===`items`&&Array.isArray(e)){for(let t of e)eC(t,r);return}if(n!==`properties`||!r.length||Array.isArray(e))return;let[i,...a]=r,o=e;if(!a.length){o[i]===null&&delete o[i];return}eC(o[i],a)}function ese(e){let t=/* @__PURE__ */ new Map;for(let n of e??[]){if(!n.enforceSchema)continue;let{madeNullable:e}=Lx(n.parameters);e.length&&t.set(n.name,e)}return t}function tse(e){if(e&&typeof e==`object`)return e;if(typeof e!=`string`||!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return Qb.warn(`OpenAITransport: function_call arguments are not valid JSON`,{raw:e}),{}}}var tC=class e{constructor(){this.noopProvider=new tx}get(t){return t===e.DEFAULT_NAME?this.noopProvider:void 0}default(){return this.noopProvider}defaultName(){return e.DEFAULT_NAME}names(){return[e.DEFAULT_NAME]}getStatus(t){return J(this,void 0,void 0,function*(){var n;return t!==void 0&&t!==e.DEFAULT_NAME?null:(yield(n=this.noopProvider).getStatus?.call(n))??null})}listStatuses(){return J(this,void 0,void 0,function*(){var t;let n=(yield(t=this.noopProvider).getStatus?.call(t))??null;return[{name:e.DEFAULT_NAME,isDefault:!0,status:n}]})}};tC.DEFAULT_NAME=`default`;let nC=N.createInterface(e=>e.singleton(tC)),rC=6e4,iC=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:rC,timeoutMs:iC}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:rC,timeoutMs:iC}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:rC,timeoutMs:iC})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:rC,timeoutMs:iC}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:rC,timeoutMs:iC}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:rC,timeoutMs:iC})}),openai:Object.freeze({low:Object.freeze({model:`gpt-6-luna`,stallTimeoutMs:rC,timeoutMs:iC}),high:Object.freeze({model:`gpt-6.1-terra`,stallTimeoutMs:rC,timeoutMs:iC}),reasoning:Object.freeze({model:`gpt-6.1-sol`,stallTimeoutMs:rC,timeoutMs:iC})})});let aC=O` :host{display: block;width: 800px}.ai-criteria-search{display: flex;flex-direction: column;gap: calc(${B} * 2px)}.ai-criteria-search-row{display: flex;flex-direction: row;gap: calc(${B} * 2px);align-items: center}.criteria-input{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0}.criteria-chips-inline{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0;display: flex;align-items: center;gap: calc(${B} * 1px);overflow-x: auto;padding: 0 calc(${B} * 2px);background: var(--neutral-fill-input-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(var(--control-corner-radius) * 1px);scrollbar-width: none}.criteria-chips-inline::-webkit-scrollbar{display: none}.mic-icon{color: var(--neutral-foreground-rest);fill: currentColor}.criteria-toggle-button, .criteria-clear-button{flex-shrink: 0}.criteria-chip{display: inline-flex;align-items: center;flex-shrink: 0;gap: calc(${B} * 1px);padding: calc(${B} * 0.5px) calc(${B} * 2px);background: var(--neutral-fill-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(${B} * 4px);font-size: var(--type-ramp-minus-1-font-size);color: var(--neutral-foreground-rest);white-space: nowrap}.criteria-chip-field{font-weight: 600}.criteria-chip-operator{color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-style: italic}.criteria-chip-remove{display: inline-flex;align-items: center;justify-content: center;width: 14px;height: 14px;padding: 0;margin-left: calc(${B} * 0.5px);background: none;border: none;cursor: pointer;color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-size: 10px;border-radius: 50%;line-height: 1}.criteria-chip-remove:hover{background: var(--neutral-fill-hover);color: var(--neutral-foreground-rest)}`,nse=e=>T` ${A(()=>Zb(),T`<div class="ai-criteria-search"><div class="ai-criteria-search-row">${A(e=>!e.showingChips,T`<${e}-text-area ${k(`textAreaRef`)}class="criteria-input" placeholder="${e=>e.placeholder}" ?disabled=${e=>e.disabled||e.isInterpreting}:value=${lf(e=>e.inputValue,`string`,`input`)}@blur=${e=>e.handleBlur()}rows="1"></${e}-text-area>`)} ${A(e=>e.showingChips,T`<div class="criteria-chips-inline">${j(e=>e.criteriaChips,T`<span class="criteria-chip"><span class="criteria-chip-field">${e=>e.fieldLabel}</span><span class="criteria-chip-operator">${e=>e.operatorLabel}</span>${A(e=>!!e.valueLabel,T`<span class="criteria-chip-value">${e=>e.valueLabel}</span>`)}<button class="criteria-chip-remove" aria-label="Remove filter" @click=${(e,t)=>t.parent.removeChip(e.groupIndex,e.clauseIndex)}>
254
254
  &#x2715;
255
255
  </button></span>`)}</div>`)}<${e}-button class="criteria-toggle-button" appearance="outline" title=${e=>e.showingChips?`Add more criteria`:`View active filters`}?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.toggleCriteriaView()}><${e}-icon name="pen" size="sm"></${e}-icon></${e}-button><${e}-button class="criteria-clear-button" appearance="outline" title="Clear all filters" ?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.clearChips()}><${e}-icon name="trash-alt" size="sm"></${e}-icon></${e}-button>${A(e=>e.speechAvailable,T`<${e}-button class="mic-button" appearance="${e=>e.isRecording?`accent`:`outline`}" ?disabled=${e=>e.disabled||e.isInterpreting}@click=${e=>e.toggleSpeechInput()}title=${e=>e.isRecording?`Stop recording`:`Start voice input`}><${e}-icon class="mic-icon" name="microphone" size="lg" variant="solid"></${e}-icon></${e}-button>`)}</div></div>`)} `,oC=T` ${e=>nse(vb(e))} `,rse={contains:kb.containsIgnoreCase,equals:kb.EQ,startsWith:kb.startsWith,endsWith:kb.endsWith,greaterThan:kb.GT,lessThan:kb.LT,greaterThanOrEqual:kb.GE,lessThanOrEqual:kb.LE,notEqual:kb.NE,dateIsToday:kb.dateIsToday,dateIsAfter:kb.dateIsGreaterEqual,dateIsGreaterEqual:kb.dateIsGreaterEqual,dateIsBefore:kb.dateIsLessEqual,dateIsLessEqual:kb.dateIsLessEqual,dateIsEqual:kb.dateIsEqual,dateTimeIsAfter:kb.dateTimeIsGreaterEqual,dateTimeIsGreaterEqual:kb.dateTimeIsGreaterEqual,dateTimeIsBefore:kb.dateTimeIsLessEqual,dateTimeIsLessEqual:kb.dateTimeIsLessEqual};function ise(e){let t=rse[e.operator];if(!t)throw Error(`Unknown criteria operator '${e.operator}'`);return new Pb().withField(e.field).withValue(e.value??null).withSerialiser(t).withGroup(`default`).build()}function ase(e,t){return e.length===1?e[0]:e.reduce((e,n,r)=>r===0?[n]:[...e,t,n],[])}function sC(e){let t=new Nb,n=!1;for(let r of e){if(!r.clauses?.length)continue;let e=r.clauses.map(ise),i=r.logic===`or`?Sb.Or():Sb.And(),a=ase(e,i),o=e.length>1?{join:i}:{};r.negated?t.And([Sb.Not(),a]):t.And(e.length===1?e[0]:e,o),n=!0}return n?t.build():``}let ose=[`contains`,`equals`,`startsWith`,`notEqual`],cC=[`equals`,`greaterThan`,`lessThan`,`greaterThanOrEqual`,`lessThanOrEqual`,`notEqual`],lC=[`dateIsToday`,`dateIsAfter`,`dateIsBefore`,`dateIsEqual`,`dateIsGreaterEqual`,`dateIsLessEqual`],uC=[`dateTimeIsAfter`,`dateTimeIsBefore`,`dateTimeIsGreaterEqual`,`dateTimeIsLessEqual`],sse={contains:`contains`,equals:`=`,startsWith:`starts with`,endsWith:`ends with`,notEqual:`≠`,greaterThan:`>`,lessThan:`<`,greaterThanOrEqual:`≥`,lessThanOrEqual:`≤`,dateIsToday:`is today`,dateIsAfter:`after`,dateIsBefore:`before`,dateIsEqual:`=`,dateIsGreaterEqual:`≥`,dateIsLessEqual:`≤`,dateTimeIsAfter:`after`,dateTimeIsBefore:`before`,dateTimeIsGreaterEqual:`≥`,dateTimeIsLessEqual:`≤`},cse=/* @__PURE__ */ new Set([`DATE`,`LOCALDATE`]),lse=/* @__PURE__ */ new Set([`DATETIME`,`NANO_TIMESTAMP`,`LOCALDATETIME`,`TIMESTAMP`]),dC=/* @__PURE__ */ new Set([`INT`,`INTEGER`,`LONG`,`SHORT`,`DOUBLE`,`BIGDECIMAL`,`DECIMAL`]);function fC(e){return(e||``).toUpperCase().trim().split(`(`)[0].trim()}function use(e){let t=fC(e);return cse.has(t)?lC:lse.has(t)?uC:dC.has(t)?cC:ose}function dse(e){return dC.has(fC(e))}function fse(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e)&&e>0:typeof e==`string`?/^\d{8}$/.test(e)||/^\d{4}-\d{2}-\d{2}$/.test(e)||/^\d{8}-\d{2}:\d{2}(:\d{2})?$/.test(e):!1}function pse(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e):typeof e==`string`&&!Number.isNaN(Number(e))}function mse(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map;Array.isArray(t)&&t.length>0&&(typeof t[0]==`string`?t.forEach(e=>i.set(e,void 0)):t.forEach(e=>i.set(e.NAME,e)));for(let t of e){let{field:e,operator:a,value:o}=t;if(!e||typeof e!=`string`){r.push({field:String(e),message:`Field name is required`});continue}let s=i.get(e),c=s&&`TYPE`in s?s.TYPE:`STRING`;if(!use(c).includes(a)){r.push({field:e,operator:a,value:o,message:`Operator '${a}' is not allowed for field type ${c}`});continue}if((lC.includes(a)||uC.includes(a))&&a!==`dateIsToday`&&!fse(o)){r.push({field:e,operator:a,value:o,message:`Invalid date/datetime value; use yyyyMMdd, yyyy-MM-dd, or epoch`});continue}if(dse(c)&&cC.includes(a)&&!pse(o)){r.push({field:e,operator:a,value:o,message:`Invalid numeric value`});continue}if(i.size>0&&!i.has(e)){r.push({field:e,operator:a,value:o,message:`Unknown field '${e}'`});continue}n.push(t)}return{valid:n,invalid:r}}function hse(e,t){let n=[],r=[];for(let i of e){if(!i?.clauses||!Array.isArray(i.clauses)){r.push({field:``,message:`Group must have a clauses array`});continue}let{valid:e,invalid:a}=mse(i.clauses,t);r.push(...a),e.length>0&&n.push({logic:i.logic??`and`,negated:i.negated,clauses:e})}return{valid:n,invalid:r}}let pC=Ad(`foundation-notifications`),mC=null,hC=/* @__PURE__ */ new Map,gC=e=>`${e?.title??`Error`}: ${e?.body??`Something went wrong`}`,gse=e=>e?.logLevel||e?.config?.logLevel||vd.debug,_C=e=>{pC.log({message:gC(e),level:gse(e)})},vC=(e,t)=>{let n=document.querySelector(`#${e}`);if(!n){if(hC.has(e))n=hC.get(e);else{let t=Ld(document).find(t=>t.id===e);t&&(n=t,hC.set(e,t))}}if(!n){n=document.createElement(`div`),n.setAttribute(`id`,e),n.style.zIndex=`9999`;let{element:t,prefix:r}=Bd(document.body,`rapid`);if(t)t.appendChild(n),mC=t;else if(mC)mC.appendChild(n);else{let e=document.createElement(`${r}-design-system-provider`);e.appendChild(n),document.body.appendChild(e),mC=e}}return n},_se=e=>{for(;e&&!(e instanceof ShadowRoot);){let t=(e?.getRootNode())?.getElementById(`banner-anchor`);if(t)return t.style.position=`relative`,t;e=e?.getRootNode()?.host}return vse()},vse=()=>{let e=document.createElement(`div`);return e.setAttribute(`id`,`banner-anchor`),e.style.position=`relative`,document.body.insertBefore(e,document.body.firstChild),e},yse=e=>{_C(e),alert(gC(e))},bse=(e,t,n)=>{_C(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-banner`),a=_se(n);a?.children?.length>0&&(i.style.position=`absolute`,i.style.top=`0`,i.style.left=`0`,i.style.width=`100%`),a.appendChild(i),i.notification=e},xse=e=>{let t=e.querySelector(`#dialog-container`);return t||(t=document.createElement(`div`),t.setAttribute(`id`,`dialog-container`),t.style.position=`relative`,e.appendChild(t)),t},Sse=(e,t,n)=>{_C(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-dialog`);(n?xse(n):vC(`dialog-container`,t)).appendChild(i),i.notification=e,i.show()};var yC;(function(e){e.NOTIFICATION_EVENT=`notification-event`})(yC||(yC={}));var bC;(function(e){e.Top=`top`,e.Bottom=`bottom`})(bC||(bC={}));var xC;(function(e){e.Left=`left`,e.Right=`right`})(xC||(xC={}));let SC=`12px`,Cse=(e,t,n)=>{e.style.position=`fixed`,e.style.top=t===bC.Top?SC:``,e.style.bottom=t===bC.Bottom?SC:``,e.style.left=n===xC.Left?SC:``,e.style.right=n===xC.Right?SC:``},wse=(e,t)=>{_C(e);let n=t.split(`-`)[0],r=document.createElement(`${n}-snackbar`),i=e.config?.snackbar?.verticalEdge??bC.Bottom,a=e.config?.snackbar?.horizontalEdge??xC.Left,o=vC(`snack-container-${i}-${a}`,t);o&&Cse(o,i,a),o.appendChild(r),r.notification=e},Tse=e=>Ld(document.body).find(t=>t.tagName.toLowerCase()===`notify-container`&&t.position===e);function Ese(e,t){switch(t.style.position=`fixed`,e?.config?.toast?.position){case`top-left`:t.style.top=`var(--nav-height, 0)`,t.style.left=`0`;break;case`bottom-left`:t.style.bottom=`0`,t.style.left=`0`;break;case`bottom-right`:t.style.bottom=`0`,t.style.right=`0`;break;default:t.style.top=`var(--nav-height, 0)`,t.style.right=`0`}}let CC=(e,t,n)=>{var r,i;_C(e);let a=t.split(`-`)[0],o=e?.config?.toast?.position||`top-right`,s=n??Tse(o)??vC(`notify-container`,t);s&&s.tagName.toLowerCase()!==`notify-container`&&Ese(e,s);let c=document.createElement(`${a}-toast`),l=document.createElement(`div`);l.setAttribute(`slot`,`top`),l.textContent=e.title;let u=document.createElement(`div`);u.setAttribute(`slot`,`content`),u.textContent=e?.body||``;let d=document.createElement(`div`);d.setAttribute(`slot`,`date`),d.textContent=(e?.createdAt)?.toLocaleTimeString()||``;let f;e?.config?.toast?.buttons&&e?.config?.toast?.buttons?.length&&(f=document.createElement(`div`),f.setAttribute(`slot`,`bottom`),e.config.toast.buttons.forEach(t=>{let n=document.createElement(`${a}-button`);n.textContent=t.placeholder||`example placeholder`,n.addEventListener(`click`,()=>{let{details:r}=e.config.toast;if(t.action)return t.action({details:r,buttonElement:n,toastElement:c})}),t.appearance&&n.setAttribute(`appearance`,t.appearance),f.appendChild(n)})),c.setAttribute(`notify`,e?.config?.toast?.type||``),e.iconName&&c.setAttribute(`notification-icon`,e.iconName),(r=e?.config?.toast)!=null&&r.autoClose&&c.setAttribute(`auto-close`,`${e?.config?.toast?.autoClose}`),(i=e?.config?.toast)!=null&&i.closeTimeout&&c.setAttribute(`close-timeout`,`${e?.config?.toast?.closeTimeout}`),c.appendChild(l),c.appendChild(u),c.appendChild(d),f&&c.appendChild(f),s.prepend(c)},wC=(e,t,n)=>{if(!e.title)throw Error(`Title is required`);if(!e.body)throw Error(`Missing required param 'body'`);let r={title:e.title,body:e.body,iconName:e.iconName},i={};e.createdAt&&(r=Object.assign({createdAt:e.createdAt},r)),e.logLevel!=null&&(r=Object.assign({logLevel:e.logLevel},r)),e.toast&&(i=Object.assign({toast:e.toast},i),r=Object.assign({config:i},r)),CC(r,t,n)},Dse=O` :host{position: fixed;z-index: 9999;display: flex;flex-direction: column;gap: 4px;box-sizing: border-box;pointer-events: none;/* Allow clicks to pass through empty space */ width: 415px}.toast-container{padding: 0 8px 12px 12px;position: relative}/* Expanded / List State: Allow scrolling if too many items */ :host(:not([stack-collapsed])){max-height: calc(100% - var(--nav-height));overflow: hidden;pointer-events: auto;/* Enable pointer events for scrolling */ slot{display: block;height: calc(100vh - var(--nav-height) - 54px);position: relative}.toast-container{flex: 1;height: 100%;overflow: hidden auto;scrollbar-color: var(--neutral-layer-3) transparent;&:hover{scrollbar-color: var(--neutral-layer-4) transparent}}}.header{display: flex;gap: 12px;pointer-events: none;margin: 5px 24px;justify-content: space-between;visibility: hidden;align-items: center;box-sizing: border-box;.header-title{text-shadow: 0 0 10px #000}.notification-header-buttons{display: flex;gap: 4px;rapid-icon{color: var(--neutral-foreground-hint);margin-left: 4px;display: inline-flex;font-size: 14px;&.chevron-up.collapse{transform: rotate(180deg);transition: transform 0.3s ease}}}--base-height-multiplier: 8;*[appearance='neutral']{font-size: 11px;cursor: pointer;background: var(--neutral-fill-rest)}}.header.visible{visibility: visible;pointer-events: auto;/* Enable clicks on header buttons */}:host([position$='left']) .header{justify-content: space-between}:host([position^='bottom']) .header{margin-bottom: 0;margin-top: 4px}/* Ensure children (toasts) are clickable */ ::slotted(*){pointer-events: auto}:host([position='top-right']){top: var(--nav-height, 0);right: 0}:host([position='top-left']){top: var(--nav-height, 0);left: 0}:host([position='bottom-right']){bottom: 0;right: 0;flex-direction: column-reverse}:host([position='bottom-left']){bottom: 0;left: 0;flex-direction: column-reverse}/* Stacked / Collapsed State */ :host([stack-collapsed]){height: min-content;/* Host allows pointer events so they can reach the slot */ pointer-events: auto;cursor: pointer}/* Apply the grid layout to the slot itself so it acts as the container and click target */ :host([stack-collapsed]) slot{display: grid;grid-template-columns: auto;grid-template-rows: auto;place-items: end center;/* Default to bottom-up stacking */ /* The slot catches the click */ pointer-events: auto}/* Rotate when the collapse class is present */ :host([stack-collapsed][position^='top']) slot{align-items: start}:host([stack-collapsed][position$='right']) slot{justify-items: end}:host([stack-collapsed][position$='left']) slot{justify-items: start}:host([stack-collapsed]) ::slotted(*){grid-area: 1 / 1;transition: transform 0.3s ease, top 0.3s ease, opacity 0.3s ease;opacity: 0%;pointer-events: none !important;/* Disable interaction with toasts in collapsed state */ transform: scale(0.9);top: 0 !important}/* Show and offset the top 3 items in the stack */ :host([stack-collapsed]) ::slotted([data-stack-index='0']){opacity: 100%;pointer-events: auto;transform: translateY(0) scale(1);z-index: 3;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='1']){opacity: 100%;transform: translateY(var(--stack-offset-y, 8px)) scale(0.95);z-index: 2;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='2']){opacity: 100%;transform: translateY(var(--stack-offset-y-2, 16px)) scale(0.9);z-index: 1;position: relative !important}/* Adjust offset direction based on position */ :host([stack-collapsed][position^='top']){--stack-offset-y: 8px;--stack-offset-y-2: 16px}:host([stack-collapsed][position^='bottom']){--stack-offset-y: -8px;--stack-offset-y-2: -16px}`,Ose=e=>T`<div class="header ${e=>pn([`visible`,e.slottedNodes.length>1])}">${A(e=>e.showCount,T`<span class="header-title">${e=>e.slottedNodes.length}Notifications</span>`)}<div class="notification-header-buttons">${A(e=>e.allowManualCollapse,T`<${e}-button @click=${e=>e.handleToggleCollapse()}>${e=>e.stackCollapsed?`Expand`:`Collapse`}<${e}-icon class="chevron-up ${e=>pn([`collapse`,e.stackCollapsed])}" name="chevron-up"></${e}-icon></${e}-button>`)} ${A(e=>e.allowCloseAll,T`<${e}-button @click=${e=>e.handleCloseAll()}>
256
256
  Close All <${e}-icon name="xmark"></${e}-icon></${e}-button>`)}</div></div>`,kse=T` ${A(e=>e.allowCloseAll||e.allowManualCollapse,T` ${e=>Ose(e.designSystemPrefix)} `)}<div class="toast-container"><slot ${xt(`slottedNodes`)}@click="${e=>e.handleContainerClick()}"></slot></div>`,TC=class extends Qe{constructor(){super(...arguments),this.position=`top-right`,this.stackThreshold=5,this.allowManualCollapse=!0,this.allowCloseAll=!0,this.designSystemPrefix=`rapid`,this.showCount=!0,this.stackCollapsed=!1,this.notificationInterval=0,this.manuallyExpanded=!1,this.pendingQueue=[],this.queueTimer=null,this.queuedNodes=/* @__PURE__ */ new Set,this.mutationObserver=null,this.knownNodes=/* @__PURE__ */ new Set,this.peekingNode=null,this.peekTimer=null,this.routeSubscriber={handleChange:()=>this.checkRoute(Vf.shared.pathName)},this.slottedNodes=[]}connectedCallback(){super.connectedCallback(),(this.position===`bottom-left`||this.position===`bottom-right`)&&pC.error(`NotifyContainer doesn't currently support bottom corner placements`),S.getNotifier(Vf.shared).subscribe(this.routeSubscriber,`pathName`),this.checkRoute(Vf.shared.pathName),this.mutationObserver=new MutationObserver(e=>this.handleMutation(e)),this.mutationObserver.observe(this,{childList:!0})}disconnectedCallback(){var e;super.disconnectedCallback(),S.getNotifier(Vf.shared).unsubscribe(this.routeSubscriber,`pathName`),(e=this.mutationObserver)==null||e.disconnect(),this.mutationObserver=null}checkRoute(e){(e.includes(`/login`)||e.includes(`/logout`))&&(this.pendingQueue=[],this.queuedNodes.clear(),clearTimeout(this.queueTimer),this.queueTimer=null,this.handleCloseAll())}slottedNodesChanged(){if(!this.manuallyExpanded&&!this.stackCollapsed&&this.slottedNodes.length>this.stackThreshold&&(this.stackCollapsed=!0),this.stackCollapsed&&this.slottedNodes.length<=1&&(this.stackCollapsed=!1,this.manuallyExpanded=!1,this.cancelPeek()),this.stackCollapsed){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement&&!this.knownNodes.has(e)).shift();e&&this.maybePeek(e)}this.knownNodes=new Set(this.slottedNodes),this.applySort()}handleContainerClick(){this.stackCollapsed&&(this.stackCollapsed=!1,this.manuallyExpanded=!0,this.cancelPeek())}handleToggleCollapse(){this.stackCollapsed=!this.stackCollapsed,this.manuallyExpanded=!this.stackCollapsed,this.stackCollapsed||this.cancelPeek()}handleCloseAll(){for(this.cancelPeek();this.firstChild;)this.removeChild(this.firstChild);this.stackCollapsed=!1,this.manuallyExpanded=!1}notificationIntervalChanged(e,t){!t&&this.pendingQueue&&this.flushQueue()}handleMutation(e){this.notificationInterval&&(e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&(this.queuedNodes.has(e)?this.queuedNodes.delete(e):(this.removeChild(e),this.pendingQueue.push(e)))})}),this.queueTimer||this.processQueue())}processQueue(){if(!this.pendingQueue.length){this.queueTimer=null;return}let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e),this.queueTimer=setTimeout(()=>{this.queueTimer=null,this.processQueue()},this.notificationInterval)}flushQueue(){for(clearTimeout(this.queueTimer),this.queueTimer=null;this.pendingQueue.length;){let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e)}}sortFnChanged(){this.applySort()}applySort(){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement);if(!e.length)return;let t=this.sortFn&&e.length>1?[...e].sort(this.sortFn):e;this.peekingNode&&t.includes(this.peekingNode)?this.handlePosition([this.peekingNode,...t.filter(e=>e!==this.peekingNode)]):this.handlePosition(t)}maybePeek(e){let t=this.slottedNodes.filter(e=>e instanceof HTMLElement);if((this.sortFn&&t.length>1?[...t].sort(this.sortFn):t).indexOf(e)===0)return;this.cancelPeek(),this.peekingNode=e;let n=this.notificationInterval?this.notificationInterval/2:1500;this.peekTimer=setTimeout(()=>{this.peekingNode=null,this.peekTimer=null,this.applySort()},n)}cancelPeek(){clearTimeout(this.peekTimer),this.peekTimer=null,this.peekingNode=null}handlePosition(e){if(!e.length)return;e.forEach((t,n)=>{t.style.position=`absolute`,t.style.transition=`all 0.3s ease-in`,t.style.right=`0px`,t.style.zIndex=(e.length-n).toString(),t.dataset.stackIndex=n.toString()});let t=e.map(e=>e.offsetHeight);e.reduce((e,n,r)=>(n.style.top=`${e}px`,e+t[r]),0)}};q([D],TC.prototype,`position`,void 0),q([D({attribute:`stack-threshold`})],TC.prototype,`stackThreshold`,void 0),q([D({attribute:`allow-manual-collapse`,mode:`boolean`})],TC.prototype,`allowManualCollapse`,void 0),q([D({attribute:`allow-close-all`,mode:`boolean`})],TC.prototype,`allowCloseAll`,void 0),q([D({attribute:`design-system-prefix`})],TC.prototype,`designSystemPrefix`,void 0),q([D({attribute:`show-count`,mode:`boolean`})],TC.prototype,`showCount`,void 0),q([D({attribute:`stack-collapsed`,mode:`boolean`})],TC.prototype,`stackCollapsed`,void 0),q([D({attribute:`notification-interval`})],TC.prototype,`notificationInterval`,void 0),q([C],TC.prototype,`sortFn`,void 0),q([C],TC.prototype,`slottedNodes`,void 0),TC=q([$e({name:`notify-container`,template:kse,styles:Dse})],TC);let EC={alert:yse,toast:CC,dialog:Sse,snackbar:wse,banner:bse},DC=(e,t,n)=>{Object.keys(e?.config||{}).forEach(r=>{EC[r]&&EC[r](e,t,n)})};function Ase(e){return e.length===0?``:e.length===1?e[0].message:e.map(e=>e.message).join(`; `)}function OC(e,t,n){t?.trim()&&DC({title:e,body:t,config:{toast:{autoClose:!0,closeTimeout:4e3,type:`error`}}},n)}var kC=class extends P{constructor(){super(...arguments),this.placeholder=`Describe your search criteria in natural language...`,this.inputValue=``,this.isInterpreting=!1,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.fieldMetadata=[],this.isRecording=!1,this.stopRecording=null,this.speechApplyDebounceTimer=null}get speechAvailable(){return $b()}get criteriaChips(){return this.activeGroups.flatMap((e,t)=>e.clauses.map((e,n)=>({groupIndex:t,clauseIndex:n,fieldLabel:this.getFieldLabel(e.field),operatorLabel:sse[e.operator]??e.operator,valueLabel:e.operator===`dateIsToday`?``:String(e.value??``)})))}getFieldLabel(e){if(!Array.isArray(this.fieldMetadata)||this.fieldMetadata.length===0||typeof this.fieldMetadata[0]==`string`)return e;let t=this.fieldMetadata.find(t=>t.NAME===e);return t?.UI_LABEL??t?.NAME??e}toggleCriteriaView(){this.showingChips?(this.inputValue=``,this.showingChips=!1):this.showingChips=!0}removeChip(e,t){var n;let r=this.activeGroups.map(e=>Object.assign(Object.assign({},e),{clauses:[...e.clauses]}));(n=r[e])==null||n.clauses.splice(t,1);let i=r.filter(e=>e.clauses.length>0);if(this.activeGroups=i,i.length===0)this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null);else{let e=sC(i);this.lastValidCriteria=e,this.$emit(`criteria-changed`,e)}}clearChips(){this.activeGroups=[],this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null)}handleSubmit(){return J(this,void 0,void 0,function*(){let e=this.inputValue?.trim();if(!e||this.isInterpreting)return;let t=this.providerRegistry?.default();if(!t?.interpretCriteria){OC(`AI criteria search`,`AI provider not configured`,vb(this));return}this.isInterpreting=!0;try{let n=Array.isArray(this.fieldMetadata)?this.fieldMetadata:[],r=yield t.interpretCriteria(e,{fields:n});if(!(r?.groups)?.some(e=>e.clauses?.length)){OC(`AI criteria search`,`AI could not interpret the criteria`,vb(this)),this.isInterpreting=!1;return}let{valid:i,invalid:a}=hse(r.groups,this.fieldMetadata);if(a.length>0&&(OC(`Criteria validation error`,Ase(a),vb(this)),this.$emit(`validation-errors`,a)),i.length>0){let e=[...this.activeGroups,...i],t=sC(e);this.lastValidCriteria=t,this.activeGroups=e,this.inputValue=``,this.showingChips=!0,this.$emit(`criteria-changed`,t)}}catch(e){OC(`AI criteria search`,e instanceof Error?e.message:`Interpretation failed`,vb(this))}finally{this.isInterpreting=!1}})}handleBlur(){this.isRecording||(this.inputValue?.trim()?this.handleSubmit():this.activeGroups.length>0&&(this.showingChips=!0))}clear(){this.inputValue=``,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.$emit(`criteria-changed`,null)}toggleSpeechInput(){if(this.isRecording&&this.stopRecording){this.clearSpeechApplyDebounce(),this.stopRecording(),this.stopRecording=null,this.isRecording=!1;return}this.inputValue=``,this.showingChips=!1,this.stopRecording=ex((e,t)=>{this.inputValue=e,t&&e?.trim()&&(this.clearSpeechApplyDebounce(),this.stopRecording&&(this.stopRecording(),this.stopRecording=null,this.isRecording=!1),this.speechApplyDebounceTimer=setTimeout(()=>{this.speechApplyDebounceTimer=null,this.handleSubmit()},700))},()=>{this.clearSpeechApplyDebounce(),this.isRecording=!1,this.stopRecording=null}),this.stopRecording&&(this.isRecording=!0)}clearSpeechApplyDebounce(){this.speechApplyDebounceTimer&&(clearTimeout(this.speechApplyDebounceTimer),this.speechApplyDebounceTimer=null)}};q([nC],kC.prototype,`providerRegistry`,void 0),q([D],kC.prototype,`placeholder`,void 0),q([D({mode:`boolean`})],kC.prototype,`disabled`,void 0),q([C],kC.prototype,`inputValue`,void 0),q([C],kC.prototype,`isInterpreting`,void 0),q([C],kC.prototype,`lastValidCriteria`,void 0),q([C],kC.prototype,`activeGroups`,void 0),q([C],kC.prototype,`showingChips`,void 0),q([C],kC.prototype,`fieldMetadata`,void 0),q([C],kC.prototype,`isRecording`,void 0),q([w],kC.prototype,`speechAvailable`,null),q([w],kC.prototype,`criteriaChips`,null);let AC={};kC.compose(Object.assign({baseName:`ai-criteria-search`,template:oC,styles:aC,shadowOptions:void 0},AC));let jC=(e,t)=>O` :host{display: flex;justify-content: center;align-items: center;width: 100%;margin: calc(var(--design-unit) * 2px) 0;position: relative;/* Same as connection indicator */ --green: 50 164 49;--trafic-light-green: rgb(var(--green));--red: 187 30 16;--trafic-light-red: rgb(var(--red));--amber: 230 160 20;--trafic-light-amber: rgb(var(--amber))}.ai-indicator-container{display: flex;flex-direction: column;align-items: center;position: relative}.ai-indicator-badge{display: inline-flex;align-items: center;gap: calc(var(--design-unit) * 1.4px);font-size: 12px;line-height: 1;font-weight: 600;text-transform: uppercase;height: calc(var(--design-unit) * 6px);padding: calc(var(--design-unit) * 0.5px) calc(var(--design-unit) * 2px);border-radius: calc(var(--design-unit) * 1px);cursor: pointer;color: #fff}.ai-indicator-badge:hover{opacity: 90%}.ai-indicator-badge.green{background: var(--trafic-light-green)}.ai-indicator-badge.amber{background: var(--trafic-light-amber)}.ai-indicator-badge.red{background: var(--trafic-light-red)}.ai-indicator-badge .ai-indicator-icon{flex-shrink: 0;color: inherit}.ai-indicator-badge.pulsing{animation: ai-indicator-pulse 1.5s ease-in-out infinite}@keyframes ai-indicator-pulse{0%, 100%{opacity: 100%}50%{opacity: 50%}}.ai-indicator-dropdown{position: absolute;top: 100%;right: 0;margin-top: calc(var(--design-unit) * 2px);min-width: 200px;padding: calc(var(--design-unit) * 4px);background: var(--neutral-layer-floating, #fff);border: 1px solid var(--neutral-stroke-rest, #e0e0e0);border-radius: calc(var(--design-unit) * 2px);box-shadow: 0 calc(var(--design-unit) * 1px) calc(var(--design-unit) * 4px) rgb(0 0 0 / 12%);z-index: 1000}.ai-indicator-info{display: flex;flex-direction: column;gap: 0;margin: 0;padding: 0}.ai-indicator-info .info-row{display: grid;grid-template-columns: 72px 1fr;gap: calc(var(--design-unit) * 4px);align-items: baseline;padding: calc(var(--design-unit) * 1.5px) 0;border-bottom: 1px solid var(--neutral-stroke-subtle, #eee)}.ai-indicator-info .info-row:last-child{border-bottom: none}.ai-indicator-info .info-label{margin: 0;font-size: var(--type-ramp-base-font-size);font-weight: 500;color: var(--neutral-foreground-hint, #666)}.ai-indicator-info .info-value{margin: 0;font-size: var(--type-ramp-base-font-size);color: var(--neutral-foreground-rest, #333);text-transform: capitalize;word-break: break-word}.install-button{margin-top: calc(var(--design-unit) * 3px);width: 100%}`,jse=e=>T` ${A(()=>Zb(),T`<div class="ai-indicator-container" part="ai-indicator-container"><div class=${e=>pn(`ai-indicator-badge`,[`green`,e.state===`available`||e.state===`server`],[`amber`,e.state===`downloading`||e.state===`downloadable`],[`red`,e.state===`unavailable`||e.state===`none`],[`pulsing`,e.state===`downloading`||e.isInstalling])}data-test-id="ai-indicator-badge" part="ai-indicator-badge" role="button" tabindex="0" aria-label="AI status" aria-haspopup="true" aria-expanded="${e=>e.open}" @click=${e=>e.toggleDropdown()}@keydown=${(e,t)=>{let n=t.event;(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),e.toggleDropdown())}}><${e}-icon class="ai-indicator-icon" name="wand-magic-sparkles" size="xs" variant="solid" part="ai-indicator-icon"></${e}-icon><span class="ai-indicator-text" data-test-id="ai-indicator-text" part="ai-indicator-text">AI</span></div>${A(e=>e.open,T`<div class="ai-indicator-dropdown" part="ai-indicator-dropdown"><dl class="ai-indicator-info"><div class="info-row"><dt class="info-label">Provider</dt><dd class="info-value">${e=>e.status?.provider??`none`}</dd></div><div class="info-row"><dt class="info-label">Model</dt><dd class="info-value">${e=>e.status?.model||`—`}</dd></div>${A(e=>e.chromeStatusLabel,T`<div class="info-row"><dt class="info-label">Status</dt><dd class="info-value">${e=>e.chromeStatusLabel}</dd></div>`)}</dl>${A(e=>e.canInstall,T`<${e}-button class="install-button" appearance="accent" @click=${(e,t)=>{t.event.preventDefault(),e.onInstall()}}>
@@ -250,7 +250,7 @@ function ay(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r
250
250
  `;case`t`:return` `;case`r`:return`\r`;case`b`:return`\b`;case`f`:return`\f`;case`\\`:return`\\`;case`"`:return`"`;case`'`:return`'`;case`/`:return`/`;case`u`:return this.readHexCodepoint(4);case`x`:return this.readHexCodepoint(2);default:return this.bail()}}readHexCodepoint(e){let t=this.src.slice(this.pos,this.pos+e);return(t.length!==e||!/^[0-9a-fA-F]+$/.test(t))&&this.bail(),this.pos+=e,String.fromCharCode(parseInt(t,16))}readNumber(){let e=this.pos;for((this.peek()===`-`||this.peek()===`+`)&&(this.pos+=1);this.pos<this.src.length&&/[0-9.eE+-]/.test(this.src[this.pos]);)this.pos+=1;let t=Number(this.src.slice(e,this.pos));return Number.isFinite(t)||this.bail(),t}readBareword(){switch(this.readIdentifier()){case`true`:case`True`:return!0;case`false`:case`False`:return!1;case`null`:case`None`:return null;default:return this.bail()}}readIdentifier(){let e=this.pos;for(/[A-Za-z_]/.test(this.peek())||this.bail();this.pos<this.src.length&&/[A-Za-z0-9_]/.test(this.src[this.pos]);)this.pos+=1;return this.src.slice(e,this.pos)}isDigit(e){return e>=`0`&&e<=`9`}peek(){return this.pos<this.src.length?this.src[this.pos]:``}skipWhitespace(){for(;this.pos<this.src.length&&/\s/.test(this.src[this.pos]);)this.pos+=1}expect(e){this.src[this.pos]!==e&&this.bail(),this.pos+=1}expectLiteral(e){this.src.slice(this.pos,this.pos+e.length)!==e&&this.bail(),this.pos+=e.length}bail(){throw Error(`MalformedFunctionCallParser: unexpected token`)}};function joe(e,t){if(!e)return null;let n;try{n=new Aoe(e).parse()}catch{return null}return t.has(n.name)?n:null}let Moe=e=>`https://generativelanguage.googleapis.com/v1beta/models/${e}:generateContent`,Noe={"gemini-2.5-pro":1048576,"gemini-2.5-flash":1048576,"gemini-2.5-flash-lite":1048576,"gemini-4-argon":1048576,"gemini-3.8-flash":1048576,"gemini-3.5-flash":1048576,"gemini-3.1-flash-lite":1048576,"gemini-3.1-pro-preview":1048576};function Poe(e){if(e&&e!==`auto`)return e===`required`?{functionCallingConfig:{mode:`ANY`}}:e===`none`?{functionCallingConfig:{mode:`NONE`}}:{functionCallingConfig:{mode:`ANY`,allowedFunctionNames:[e.tool]}}}function Foe(e){if(!ox.includes(e))throw Error(`GeminiTransport: unsupported model "${e}". Use one of: ${ox.join(`, `)}.`)}let Ioe={"gemini-2.5-flash":`GeminiTransport: using gemini-2.5-flash — higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-2.5-pro":`GeminiTransport: using gemini-2.5-pro — significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`,"gemini-3.5-flash":`GeminiTransport: using gemini-3.5-flash — frontier model, materially higher cost than flash-lite; use for harder reasoning or agent tasks.`,"gemini-3.8-flash":`GeminiTransport: using gemini-3.8-flash — frontier model, materially higher cost than flash-lite. Billed at an introductory $0.75/$3.75 per MTok through 2026-12-31 and $1.50/$7.50 from 2027-01-01; weigh a tier choice against the later rate.`,"gemini-4-argon":`GeminiTransport: using gemini-4-argon — premium reasoning model, materially higher cost than the flash tiers. Billed at $2/$10 per MTok through 2026-11-30 and $4/$20 from 2026-12-01; weigh a tier choice against the later rate.`,"gemini-3.1-pro-preview":`GeminiTransport: using gemini-3.1-pro-preview — PREVIEW model (no stability guarantee, may be withdrawn) with significantly higher, prompt-size-tiered cost; reserve for tasks where flash reliability is insufficient.`},BS=[`gemini-2.5-flash`,`gemini-2.5-flash-lite`],Loe=[`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],Roe=[`gemini-4-argon`,`gemini-3.8-flash`,`gemini-3.5-flash`,`gemini-3.1-flash-lite`,`gemini-3.1-pro-preview`],VS=[`minimal`,`low`,`medium`,`high`],HS={"gemini-4-argon":[`low`,`medium`,`high`],"gemini-3.8-flash":[`low`,`medium`,`high`],"gemini-3.5-flash":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-flash-lite":[`minimal`,`low`,`medium`,`high`],"gemini-3.1-pro-preview":[`low`,`medium`,`high`]};function US(e,t){if(!e?.length||e.includes(t))return t;let n=VS.indexOf(t),r=e=>Math.abs(VS.indexOf(e)-n),i=e[0];for(let t of e)r(t)<=r(i)&&(i=t);return i}let WS={minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,max:`high`},GS=e=>e!==void 0&&e!==`auto`&&e!==`off`;function zoe(e,t){if(GS(t)){let n=HS[e];if(n)return{includeThoughts:!0,thinkingLevel:US(n,WS[t])}}return t===`off`&&BS.includes(e)?{includeThoughts:!1,thinkingBudget:0}:t===`auto`&&BS.includes(e)?{includeThoughts:!0,thinkingBudget:-1}:{includeThoughts:!0}}let KS=`gemini`;function qS(e){let t=[],n=[];for(let r of e)r.kind===`image`?t.push({inlineData:{mimeType:lx(r.mimeType),data:ux(r.data)}}):n.push({text:`[File: ${r.name}]\n${r.content}`});return{imageParts:t,textParts:n}}var Boe=class extends Error{constructor(e){super(`Gemini returned MALFORMED_FUNCTION_CALL`),this.finishMessage=e,this.name=`MalformedFunctionCallError`}},JS=class e{warnIfThinkingUnclampable(e){if(!this.warnedThinkingClamped){if(e===`off`&&!BS.includes(this.model)){this.warnedThinkingClamped=!0,nx.warn(`GeminiTransport: thinkingPolicy 'off' ignored — ${this.model} runs its default thinking posture and takes no budget we can safely set. Reasoning tokens are still billed at the candidate rate; use a flash tier if you need them gone.`);return}if(GS(e)){let t=HS[this.model];if(!t){this.warnedThinkingClamped=!0,nx.warn(`GeminiTransport: thinkingPolicy '${e}' ignored — ${this.model} takes a numeric thinking budget, not the graded 'thinkingLevel' the Gemini 3 tiers use, so this turn runs at its default reasoning posture. Use a Gemini 3 tier to set reasoning depth.`);return}let n=WS[e],r=US(t,n);r!==n&&(this.warnedThinkingClamped=!0,nx.warn(`GeminiTransport: thinkingPolicy '${e}' sent as thinkingLevel '${r}' — ${this.model} does not accept '${n}' (it takes ${t.join(`/`)}). Reasoning bills at the candidate rate, so an upward clamp costs more than you asked for.`))}}}constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=!1;let t=e.model??`gemini-2.5-flash-lite`;Foe(t),this.model=t;let n=Ioe[t];n&&nx.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint}getConfig(){return{provider:`gemini`,model:this.model,contextLimit:Noe[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e,i=[];return t&&(i.push({role:`user`,parts:[{text:t}]}),i.push({role:`model`,parts:[{text:`Understood.`}]})),i.push({role:`user`,parts:[{text:n}]}),(yield this.post({model:this.model,contents:i,responseSchema:r}))?.content??``})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.toGeminiContents(e,t,n?.attachments);n?.tailContext&&r.push({role:`user`,parts:[{text:n.tailContext}]});let i=n?.tools?.length?[{functionDeclarations:n.tools.map(e=>({name:e.name,description:e.description,parameters:Rx(e.parameters)}))}]:void 0,a=n?.systemPrompt?{role:`system`,parts:[{text:n.systemPrompt}]}:void 0,o=i?Poe(n?.toolChoice):void 0;this.warnIfThinkingUnclampable(n?.thinkingPolicy);let s={thinkingConfig:zoe(this.model,n?.thinkingPolicy)};n?.maxTokens!=null&&(s.maxOutputTokens=n.maxTokens);let c=[...n?.attachments??[],...e.flatMap(e=>e.attachments??[]),...e.flatMap(e=>e.toolResult?.attachments??[])].find(e=>e.kind===`image`&&e.detail);c?.kind===`image`&&c.detail&&Loe.includes(this.model)&&(s.mediaResolution=`MEDIA_RESOLUTION_${c.detail.toUpperCase()}`),n?.temperature!=null&&(s.temperature=fx(n.temperature,{defaultTemp:1,maxTemp:2}));let l=new Set((n?.tools??[]).map(e=>e.name)),u=Roe.includes(this.model),d=n?.responseSchema!=null&&(!i||u),f=yield this.post(Object.assign({model:this.model,contents:r,tools:i,systemInstruction:a,toolConfig:o,generationConfig:s},d?{responseSchema:Rx(n.responseSchema)}:{}),n?.signal);return this.fromGeminiResponse(f,l,s.maxOutputTokens)})}logTokenUsage(t,n,r,i){let{costUsd:a,savedUsd:o,breakdown:s}=bx(this.model,{promptTokens:t,candidateTokens:n,thoughtTokens:r,cachedTokens:i});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let c=e.COST_DECIMAL_PLACES;return console.log(`--- Gemini Token Usage (${this.model}) ---`),console.log(`Prompt Tokens: ${t} (${i} cached) ($${s.promptUsd.toFixed(c)} + $${s.cacheReadUsd.toFixed(c)})`),console.log(`Candidate Tokens: ${n} (+${r} thinking) ($${s.candidateUsd.toFixed(c)})`),console.log(`Total Cost: $${a.toFixed(c)}`),console.log(`Cache Saved: $${o.toFixed(c)} (lifetime $${this.lifetimeSavingsUsd.toFixed(c)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(c)}`),console.log(`--------------------------`),a}toGeminiContents(e,t,n){let r=[],i=/* @__PURE__ */ new Map;for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;let e=t.role===`user`?`user`:`model`;if(t.toolResult){let e=i.get(t.toolResult.toolCallId)??t.toolResult.toolCallId;r.push({role:`user`,parts:[{functionResponse:{name:e,response:{content:t.toolResult.content}}}]});let n=t.toolResult.attachments??[];n.length&&r.push({role:`user`,parts:n.map(e=>({inlineData:{mimeType:lx(e.mimeType),data:e.data}}))})}else if(t.toolCalls?.length){for(let e of t.toolCalls)i.set(e.id,e.name);r.push({role:`model`,parts:t.toolCalls.map((e,t)=>{let n={functionCall:{name:e.name,args:e.args}},r=e.providerMetadata?.[KS],i=r?.model===this.model?r.thoughtSignature:void 0;return i?n.thoughtSignature=i:t===0&&(n.thoughtSignature=`skip_thought_signature_validator`),n})})}else if(e===`user`&&t.attachments?.length){let{imageParts:e,textParts:n}=qS(t.attachments);r.push({role:`user`,parts:[...e,...t.content?[{text:t.content}]:[],...n]})}else r.push({role:e,parts:[{text:t.content}]})}let{imageParts:a,textParts:o}=qS(n??[]);return(t||a.length||o.length)&&r.push({role:`user`,parts:[...a,...t?[{text:t}]:[],...o]}),r}usageFromGemini(e){if(!e)return{};let t=e,n=this.logTokenUsage(t.promptTokenCount??0,t.candidatesTokenCount??0,t.thoughtsTokenCount??0,t.cachedContentTokenCount??0);return{inputTokens:t.promptTokenCount,outputTokens:t.candidatesTokenCount!=null||t.thoughtsTokenCount!=null?(t.candidatesTokenCount??0)+(t.thoughtsTokenCount??0):void 0,thoughtsTokens:t.thoughtsTokenCount,cacheReadTokens:t.cachedContentTokenCount,cost:n}}fromGeminiResponse(e,t=/* @__PURE__ */ new Set,n){let{inputTokens:r,outputTokens:i,thoughtsTokens:a,cacheReadTokens:o,cost:s}=this.usageFromGemini(e.usageMetadata),c=e?.candidates?.[0],l=c?.content?.parts??[],u=[],d=[],f=[];for(let e of l)if(e.functionCall){let t={model:this.model};e.thoughtSignature&&(t.thoughtSignature=e.thoughtSignature),u.push({id:crypto.randomUUID(),name:e.functionCall.name,args:e.functionCall.args??{},providerMetadata:{[KS]:t}})}else e.thought&&e.text?d.push(e.text):e.text&&f.push(e.text);if(c?.finishReason===`MALFORMED_FUNCTION_CALL`){let e=joe(c.finishMessage,t);if(!e)throw new Boe(c.finishMessage);u.push({id:crypto.randomUUID(),name:e.name,args:e.args})}let p=d.join(``),m=f.join(``),h=u.length>0?{role:`assistant`,content:m,reasoning:p||void 0,toolCalls:u}:{role:`assistant`,content:m,reasoning:p||void 0},g=c?.finishReason;(u.length===0&&!p&&!m||g&&g!==`STOP`&&g!==`MALFORMED_FUNCTION_CALL`)&&this.logAbnormalResponse(e,{finishReason:g,functionCallParts:u.length,thoughtParts:d.length,textParts:f.length}),this.guardMaxTokensTruncation(g,u,m,i,n),r!=null&&(h.inputTokens=r),i!=null&&(h.outputTokens=i),o!=null&&(h.cacheReadTokens=o),s!=null&&(h.cost=s);let _=e.promptFeedback?.blockReason;return(g!=null||a!=null||_!=null)&&(h.responseMeta={finishReason:g,thoughtsTokens:a,parts:{functionCall:u.length,thought:d.length,text:f.length},blockReason:_}),h}guardMaxTokensTruncation(e,t,n,r,i){if(e===`MAX_TOKENS`&&(t.length!==0||n.trim()===``))throw new LS(this.model,i,r,t.map(e=>e.name))}logAbnormalResponse(e,t){let n=e.usageMetadata??{},r=e.candidates?.[0]??{};nx.warn(`GeminiTransport: blank/non-STOP response`,{model:this.model,finishReason:t.finishReason,finishMessage:r.finishMessage,parts:{total:t.functionCallParts+t.thoughtParts+t.textParts,functionCall:t.functionCallParts,thought:t.thoughtParts,text:t.textParts},usage:{promptTokenCount:n.promptTokenCount,candidatesTokenCount:n.candidatesTokenCount,thoughtsTokenCount:n.thoughtsTokenCount,totalTokenCount:n.totalTokenCount},promptFeedback:e.promptFeedback,safetyRatings:r.safetyRatings,citationMetadata:r.citationMetadata})}buildEndpoint(e){if(this.apiKey)return{url:`${Moe(this.model)}?key=${this.apiKey}`,payload:this.toDirectPayload(e),headers:{"Content-Type":`application/json`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`GeminiTransport: no API key or server endpoint configured. Set GEMINI_API_KEY in your .env or pass apiKey/serverEndpoint in GeminiAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield SS({url:r,headers:a,body:i,credentials:o,vendorLabel:Ux.gemini,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}toDirectPayload(e){let t=Object.assign({},e);return delete t.model,t.responseSchema&&(t.generationConfig=Object.assign(Object.assign({},t.generationConfig),{responseMimeType:`application/json`,responseSchema:t.responseSchema}),delete t.responseSchema),t}};JS.TOKENS_PER_MILLION=1e6,JS.COST_DECIMAL_PLACES=6,JS.RATE_LIMIT_STATUS=429,JS.SERVICE_UNAVAILABLE_STATUS=503,JS.BAD_GATEWAY_STATUS=502,JS.RETRYABLE_STATUSES=[JS.RATE_LIMIT_STATUS,JS.SERVICE_UNAVAILABLE_STATUS,JS.BAD_GATEWAY_STATUS],JS.BACKOFF_BASE_MS=1e3;let Voe={"gpt-6-astra":922e3,"gpt-6.1-sol":105e4,"gpt-6.1-terra":105e4,"gpt-6-sol":105e4,"gpt-6-luna":105e4},YS=[`gpt-6.1-terra`,`gpt-6-luna`],Hoe={minimal:`low`,low:`low`,medium:`medium`,high:`high`,max:`max`};function Uoe(e,t){if(t!==void 0&&t!==`auto`)return t===`off`?YS.includes(e)?`none`:`low`:Hoe[t]}function Woe(e){if(e&&e!==`auto`)return e===`required`||e===`none`?e:{type:`function`,name:e.tool}}function Goe(e){let t=e.enforceSchema?Hx(e.parameters,e.name):e.parameters;return{type:`function`,name:e.name,description:e.description,parameters:t,strict:!!e.enforceSchema}}function Koe(e){if(!cx.includes(e))throw Error(`OpenAITransport: unsupported model "${e}". Use one of: ${cx.join(`, `)}.`)}let qoe={"gpt-6-astra":`OpenAITransport: using gpt-6-astra — flagship model at $10/$50 per MTok; reserve for tasks where the cheaper tiers are insufficient.`,"gpt-6.1-sol":`OpenAITransport: using gpt-6.1-sol — materially higher cost than terra/luna, and it cannot turn reasoning off (thinkingPolicy "off" runs at effort "low").`,"gpt-6-sol":`OpenAITransport: using gpt-6-sol — superseded by gpt-6.1-sol at the same price, and it cannot turn reasoning off.`},XS=`openai`,ZS=Object.freeze({mode:`explicit`});function Joe(e){let t=[],n=[],r=[],i=[],a=[],o;for(let s of e)if(s.type===`reasoning`){t.push(s);for(let e of s.summary??[])e.text&&n.push(e.text)}else if(s.type===`message`){typeof s.phase==`string`&&o!==`final_answer`&&(o=s.phase);for(let e of s.content??[])e.type===`output_text`&&typeof e.text==`string`&&r.push(e.text),e.type===`refusal`&&typeof e.refusal==`string`&&i.push(e.refusal)}else s.type===`function_call`&&a.push({id:String(s.call_id??s.id??crypto.randomUUID()),name:String(s.name),args:$oe(s.arguments)});return{reasoning:t,summaryParts:n,textParts:r,refusals:i,toolCalls:a,phase:o}}function QS(e){let t={type:`input_image`,image_url:`data:${lx(e.mimeType)};base64,${ux(e.data)}`};return e.detail&&(t.detail=e.detail===`medium`?`auto`:e.detail),t}function $S(e,t){let n=[];for(let e of t)e.kind===`image`&&n.push(QS(e));e&&n.push({type:`input_text`,text:e});for(let e of t)e.kind!==`image`&&n.push({type:`input_text`,text:`[File: ${e.name}]\n${e.content}`});return n}function Yoe(e){return e.providerMetadata?.[XS]??e.toolCalls?.[0]?.providerMetadata?.[XS]}function Xoe(e){let{status:t}=e;return rd(e,[`status`])}var eC=class e{constructor(e={}){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0,this.warnedThinkingClamped=/* @__PURE__ */ new Set;let t=e.model??`gpt-6-luna`;Koe(t),this.model=t;let n=qoe[t];n&&nx.warn(n),this.timeout=e.timeout??3e5,this.stallTimeout=e.stallTimeout??3e4,this.apiKey=e.apiKey,this.serverEndpoint=e.serverEndpoint,this.maxTokens=e.maxTokens,this.reasoningSummary=e.reasoningSummary??`none`}getConfig(){return{provider:`openai`,model:this.model,contextLimit:Voe[this.model]}}getLifetimeCost(){return this.lifetimeCostUsd}getLifetimeSavings(){return this.lifetimeSavingsUsd}resetLifetimeCost(){this.lifetimeCostUsd=0,this.lifetimeSavingsUsd=0}sendStructuredPrompt(e){return J(this,void 0,void 0,function*(){let{systemPrompt:t,userPrompt:n,responseSchema:r}=e;return(yield this.sendChatMessage([],n,{systemPrompt:t,responseSchema:r})).content})}sendChatMessage(e,t,n){return J(this,void 0,void 0,function*(){let r=this.buildRequestBody(e,t,n),i=yield this.post(r,n?.signal),a=this.fromResponse(i,r.max_output_tokens);return this.restoreOptionalFields(a,n),a})}restoreOptionalFields(e,t){let n=Qoe(t?.tools);for(let t of e.toolCalls??[]){let e=n.get(t.name);e&&tC(t.args,e)}if(!t?.responseSchema||!e.content)return;let{madeNullable:r}=Vx(t.responseSchema);if(r.length)try{let t=JSON.parse(e.content);tC(t,r),e.content=JSON.stringify(t)}catch{}}buildRequestBody(e,t,n){let r=n?.cachePolicy&&n.cachePolicy.scope!=="default"?n.cachePolicy.scope:void 0,i=[];if(n?.systemPrompt){let e={type:`input_text`,text:n.systemPrompt};r&&(e.prompt_cache_breakpoint=ZS),i.push({type:`message`,role:`developer`,content:[e]})}i.push(...this.toInputItems(e,t,n?.attachments)),r===`history`&&this.markHistoryBreakpoints(i),n?.tailContext&&i.push({type:`message`,role:`user`,content:[{type:`input_text`,text:n.tailContext}]});let a={model:this.model,input:i,store:!1,include:[`reasoning.encrypted_content`]};if(r&&(a.prompt_cache_options={mode:`explicit`,ttl:`30m`}),n?.tools?.length){a.tools=n.tools.map(Goe);let e=Woe(n.toolChoice);e&&(a.tool_choice=e)}this.warnIfThinkingClamped(n?.thinkingPolicy);let o=Uoe(this.model,n?.thinkingPolicy);o?a.reasoning=o===`none`||this.reasoningSummary===`none`?{effort:o}:{effort:o,summary:this.reasoningSummary}:this.reasoningSummary!==`none`&&(a.reasoning={summary:this.reasoningSummary}),n?.temperature!=null&&o===`none`&&(a.temperature=fx(n.temperature,{defaultTemp:1,maxTemp:2}));let s=n?.maxTokens??this.maxTokens;return s!=null&&(a.max_output_tokens=s),n?.responseSchema&&(a.text={format:{type:`json_schema`,name:`response`,schema:Vx(n.responseSchema).schema,strict:!0}}),a}warnIfThinkingClamped(e){e&&!this.warnedThinkingClamped.has(e)&&(e===`off`&&!YS.includes(this.model)?(this.warnedThinkingClamped.add(e),nx.warn(`OpenAITransport: thinkingPolicy 'off' sent as effort 'low' — ${this.model} does not accept effort 'none'. Reasoning tokens are billed as output; use gpt-6.1-terra or gpt-6-luna if you need them gone.`)):e===`minimal`&&(this.warnedThinkingClamped.add(e),nx.warn(`OpenAITransport: thinkingPolicy 'minimal' sent as effort 'low' — OpenAI has no 'minimal' effort.`)))}toInputItems(e,t,n){let r=[],i=/* @__PURE__ */ new Set;for(let t of e){if(t.role===`system`||t.role===`system-event`||t.role===`synthetic-user`||t.role===`compacted-summary`||t.category===`reasoning`||t.category===`narration`||t.excludeFromProvider||t.thinking)continue;if(t.toolResult){r.push(this.toFunctionCallOutput(t));continue}if(t.role===`user`){let e=$S(t.content,t.attachments??[]);e.length&&r.push({type:`message`,role:`user`,content:e});continue}let e=Yoe(t);if(e?.model===this.model)for(let t of e.reasoning??[]){let e=t.id??t.encrypted_content;i.has(e)||(i.add(e),r.push(Xoe(t)))}if(t.content){let n={type:`message`,role:`assistant`,content:[{type:`output_text`,text:t.content}]};e?.phase&&(n.phase=e.phase),r.push(n)}for(let e of t.toolCalls??[])r.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.args??{})})}let a=$S(t,n??[]);return a.length&&r.push({type:`message`,role:`user`,content:a}),r}toFunctionCallOutput(e){let t=e.toolResult,n=t.attachments??[];return{type:`function_call_output`,call_id:t.toolCallId,output:[{type:`input_text`,text:t.content},...n.map(QS)]}}markHistoryBreakpoints(e){let t=0;for(let n=e.length-1;n>=0&&t<49;--n){let r=e[n];if(r.role===`developer`)continue;let i=r.type===`function_call_output`?`output`:r.type===`message`&&r.role!==`assistant`?`content`:void 0;if(!i)continue;let a=[...r[i]],o=-1;for(let e=a.length-1;e>=0;--e)if(a[e].type===`input_text`){o=e;break}o<0||(a[o]=Object.assign(Object.assign({},a[o]),{prompt_cache_breakpoint:ZS}),e[n]=Object.assign(Object.assign({},r),{[i]:a}),t+=1)}}usageFromResponse(t){if(!t)return{};let n=t,r=n.input_tokens_details?.cached_tokens??0,i=n.input_tokens_details?.cache_write_tokens??0,{costUsd:a,savedUsd:o}=Cx(this.model,{inputTokens:n.input_tokens??0,outputTokens:n.output_tokens??0,cacheReadTokens:r,cacheWriteTokens:i,cacheWrite12hTokens:n.input_tokens_details?.cache_write_tokens_details?.ttl_12h_tokens??0});this.lifetimeCostUsd+=a,this.lifetimeSavingsUsd+=o;let s=e.COST_DECIMAL_PLACES;return console.log(`--- OpenAI Token Usage (${this.model}) ---`),console.log(`Input Tokens: ${n.input_tokens??0} (${r} cached, ${i} written)`),console.log(`Output Tokens: ${n.output_tokens??0} (incl. ${n.output_tokens_details?.reasoning_tokens??0} reasoning)`),console.log(`Total Cost: $${a.toFixed(s)}`),console.log(`Cache Saved: $${o.toFixed(s)} (lifetime $${this.lifetimeSavingsUsd.toFixed(s)})`),console.log(`Lifetime Cost: $${this.lifetimeCostUsd.toFixed(s)}`),console.log(`--------------------------`),{inputTokens:n.input_tokens,outputTokens:n.output_tokens,thoughtsTokens:n.output_tokens_details?.reasoning_tokens,cacheReadTokens:n.input_tokens_details?.cached_tokens,cacheWriteTokens:n.input_tokens_details?.cache_write_tokens,cost:a}}fromResponse(e,t){let n=this.usageFromResponse(e.usage),r=e.output??[],{reasoning:i,summaryParts:a,textParts:o,refusals:s,toolCalls:c,phase:l}=Joe(r),u={model:this.model};i.length&&(u.reasoning=i),l&&(u.phase=l);let d={[XS]:u};c.length&&(c[0].providerMetadata=d);let f=o.join(``),p=a.join(`
251
251
 
252
252
  `),m=Object.assign({role:`assistant`,content:f,reasoning:p||void 0},c.length?{toolCalls:c}:{providerMetadata:d}),h=e.status;if(h===`failed`)throw Zoe(this.model,e.error);let g=e.incomplete_details?.reason,_=s.length&&!f&&!c.length?`refusal`:h===`incomplete`?g??`incomplete`:h;if(_===`refusal`&&nx.warn(`OpenAITransport: the model refused`,{model:this.model,refusal:s.join(`
253
- `)}),h===`incomplete`&&g===`content_filter`&&(m.content=``,delete m.toolCalls,nx.warn(`OpenAITransport: response stopped by the content filter; partial output dropped`,{model:this.model,outputTypes:r.map(e=>e.type)})),h===`incomplete`&&g===`max_output_tokens`&&(c.length||!f.trim()))throw new LS(this.model,t,n.outputTokens,c.map(e=>e.name));return!c.length&&!f&&!p&&_!==`refusal`&&_!==`content_filter`&&nx.warn(`OpenAITransport: blank response`,{model:this.model,status:h,incompleteReason:g,outputTypes:r.map(e=>e.type),usage:e.usage}),n.inputTokens!=null&&(m.inputTokens=n.inputTokens),n.outputTokens!=null&&(m.outputTokens=n.outputTokens),n.cacheReadTokens!=null&&(m.cacheReadTokens=n.cacheReadTokens),n.cacheWriteTokens!=null&&(m.cacheWriteTokens=n.cacheWriteTokens),n.cost!=null&&(m.cost=n.cost),m.model=this.model,(_!=null||n.thoughtsTokens!=null)&&(m.responseMeta={finishReason:_,thoughtsTokens:n.thoughtsTokens,parts:{functionCall:c.length,thought:a.length,text:o.length}}),m}buildEndpoint(e){if(this.apiKey)return{url:`https://api.openai.com/v1/responses`,payload:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiKey}`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield SS({url:r,headers:a,body:i,credentials:o,vendorLabel:Ux.openai,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};eC.COST_DECIMAL_PLACES=6,eC.RATE_LIMIT_STATUS=429,eC.SERVER_ERROR_STATUS=500,eC.BAD_GATEWAY_STATUS=502,eC.SERVICE_UNAVAILABLE_STATUS=503,eC.RETRYABLE_STATUSES=[eC.RATE_LIMIT_STATUS,eC.SERVER_ERROR_STATUS,eC.BAD_GATEWAY_STATUS,eC.SERVICE_UNAVAILABLE_STATUS],eC.BACKOFF_BASE_MS=1e3;function Zoe(e,t){let{code:n,message:r}=t??{};return/* @__PURE__ */ Error(`OpenAITransport: ${e} response failed${n?` (${n})`:``}: ${r??`no error detail`}`)}function tC(e,t){for(let n of t)nC(e,n.split(`/`).slice(1))}function nC(e,t){if(!e||typeof e!=`object`)return;let[n,...r]=t;if(n===`items`&&Array.isArray(e)){for(let t of e)nC(t,r);return}if(n!==`properties`||!r.length||Array.isArray(e))return;let[i,...a]=r,o=e;if(!a.length){o[i]===null&&delete o[i];return}nC(o[i],a)}function Qoe(e){let t=/* @__PURE__ */ new Map;for(let n of e??[]){if(!n.enforceSchema)continue;let{madeNullable:e}=Vx(n.parameters);e.length&&t.set(n.name,e)}return t}function $oe(e){if(e&&typeof e==`object`)return e;if(typeof e!=`string`||!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return nx.warn(`OpenAITransport: function_call arguments are not valid JSON`,{raw:e}),{}}}var rC=class e{constructor(){this.noopProvider=new ax}get(t){return t===e.DEFAULT_NAME?this.noopProvider:void 0}default(){return this.noopProvider}defaultName(){return e.DEFAULT_NAME}names(){return[e.DEFAULT_NAME]}getStatus(t){return J(this,void 0,void 0,function*(){var n;return t!==void 0&&t!==e.DEFAULT_NAME?null:(yield(n=this.noopProvider).getStatus?.call(n))??null})}listStatuses(){return J(this,void 0,void 0,function*(){var t;let n=(yield(t=this.noopProvider).getStatus?.call(t))??null;return[{name:e.DEFAULT_NAME,isDefault:!0,status:n}]})}};rC.DEFAULT_NAME=`default`;let iC=N.createInterface(e=>e.singleton(rC)),aC=6e4,oC=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:aC,timeoutMs:oC}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:aC,timeoutMs:oC}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:aC,timeoutMs:oC})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:aC,timeoutMs:oC}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:aC,timeoutMs:oC}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:aC,timeoutMs:oC})})});let sC=O` :host{display: block;width: 800px}.ai-criteria-search{display: flex;flex-direction: column;gap: calc(${B} * 2px)}.ai-criteria-search-row{display: flex;flex-direction: row;gap: calc(${B} * 2px);align-items: center}.criteria-input{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0}.criteria-chips-inline{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0;display: flex;align-items: center;gap: calc(${B} * 1px);overflow-x: auto;padding: 0 calc(${B} * 2px);background: var(--neutral-fill-input-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(var(--control-corner-radius) * 1px);scrollbar-width: none}.criteria-chips-inline::-webkit-scrollbar{display: none}.mic-icon{color: var(--neutral-foreground-rest);fill: currentColor}.criteria-toggle-button, .criteria-clear-button{flex-shrink: 0}.criteria-chip{display: inline-flex;align-items: center;flex-shrink: 0;gap: calc(${B} * 1px);padding: calc(${B} * 0.5px) calc(${B} * 2px);background: var(--neutral-fill-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(${B} * 4px);font-size: var(--type-ramp-minus-1-font-size);color: var(--neutral-foreground-rest);white-space: nowrap}.criteria-chip-field{font-weight: 600}.criteria-chip-operator{color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-style: italic}.criteria-chip-remove{display: inline-flex;align-items: center;justify-content: center;width: 14px;height: 14px;padding: 0;margin-left: calc(${B} * 0.5px);background: none;border: none;cursor: pointer;color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-size: 10px;border-radius: 50%;line-height: 1}.criteria-chip-remove:hover{background: var(--neutral-fill-hover);color: var(--neutral-foreground-rest)}`,ese=e=>T` ${A(()=>tx(),T`<div class="ai-criteria-search"><div class="ai-criteria-search-row">${A(e=>!e.showingChips,T`<${e}-text-area ${k(`textAreaRef`)}class="criteria-input" placeholder="${e=>e.placeholder}" ?disabled=${e=>e.disabled||e.isInterpreting}:value=${uf(e=>e.inputValue,`string`,`input`)}@blur=${e=>e.handleBlur()}rows="1"></${e}-text-area>`)} ${A(e=>e.showingChips,T`<div class="criteria-chips-inline">${j(e=>e.criteriaChips,T`<span class="criteria-chip"><span class="criteria-chip-field">${e=>e.fieldLabel}</span><span class="criteria-chip-operator">${e=>e.operatorLabel}</span>${A(e=>!!e.valueLabel,T`<span class="criteria-chip-value">${e=>e.valueLabel}</span>`)}<button class="criteria-chip-remove" aria-label="Remove filter" @click=${(e,t)=>t.parent.removeChip(e.groupIndex,e.clauseIndex)}>
253
+ `)}),h===`incomplete`&&g===`content_filter`&&(m.content=``,delete m.toolCalls,nx.warn(`OpenAITransport: response stopped by the content filter; partial output dropped`,{model:this.model,outputTypes:r.map(e=>e.type)})),h===`incomplete`&&g===`max_output_tokens`&&(c.length||!f.trim()))throw new LS(this.model,t,n.outputTokens,c.map(e=>e.name));return!c.length&&!f&&!p&&_!==`refusal`&&_!==`content_filter`&&nx.warn(`OpenAITransport: blank response`,{model:this.model,status:h,incompleteReason:g,outputTypes:r.map(e=>e.type),usage:e.usage}),n.inputTokens!=null&&(m.inputTokens=n.inputTokens),n.outputTokens!=null&&(m.outputTokens=n.outputTokens),n.cacheReadTokens!=null&&(m.cacheReadTokens=n.cacheReadTokens),n.cacheWriteTokens!=null&&(m.cacheWriteTokens=n.cacheWriteTokens),n.cost!=null&&(m.cost=n.cost),m.model=this.model,(_!=null||n.thoughtsTokens!=null)&&(m.responseMeta={finishReason:_,thoughtsTokens:n.thoughtsTokens,parts:{functionCall:c.length,thought:a.length,text:o.length}}),m}buildEndpoint(e){if(this.apiKey)return{url:`https://api.openai.com/v1/responses`,payload:e,headers:{"Content-Type":`application/json`,Authorization:`Bearer ${this.apiKey}`},credentials:`omit`};if(this.serverEndpoint)return{url:this.serverEndpoint,payload:e,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},credentials:`include`};throw Error(`OpenAITransport: no API key or server endpoint configured. Pass apiKey or serverEndpoint in OpenAIAIConfig.`)}post(t,n){return J(this,void 0,void 0,function*(){let{url:r,payload:i,headers:a,credentials:o}=this.buildEndpoint(t);return yield SS({url:r,headers:a,body:i,credentials:o,vendorLabel:Ux.openai,retryableStatuses:e.RETRYABLE_STATUSES,timeout:this.timeout,stallTimeout:this.stallTimeout,backoffBaseMs:e.BACKOFF_BASE_MS,signal:n})})}};eC.COST_DECIMAL_PLACES=6,eC.RATE_LIMIT_STATUS=429,eC.SERVER_ERROR_STATUS=500,eC.BAD_GATEWAY_STATUS=502,eC.SERVICE_UNAVAILABLE_STATUS=503,eC.RETRYABLE_STATUSES=[eC.RATE_LIMIT_STATUS,eC.SERVER_ERROR_STATUS,eC.BAD_GATEWAY_STATUS,eC.SERVICE_UNAVAILABLE_STATUS],eC.BACKOFF_BASE_MS=1e3;function Zoe(e,t){let{code:n,message:r}=t??{};return/* @__PURE__ */ Error(`OpenAITransport: ${e} response failed${n?` (${n})`:``}: ${r??`no error detail`}`)}function tC(e,t){for(let n of t)nC(e,n.split(`/`).slice(1))}function nC(e,t){if(!e||typeof e!=`object`)return;let[n,...r]=t;if(n===`items`&&Array.isArray(e)){for(let t of e)nC(t,r);return}if(n!==`properties`||!r.length||Array.isArray(e))return;let[i,...a]=r,o=e;if(!a.length){o[i]===null&&delete o[i];return}nC(o[i],a)}function Qoe(e){let t=/* @__PURE__ */ new Map;for(let n of e??[]){if(!n.enforceSchema)continue;let{madeNullable:e}=Vx(n.parameters);e.length&&t.set(n.name,e)}return t}function $oe(e){if(e&&typeof e==`object`)return e;if(typeof e!=`string`||!e.trim())return{};try{let t=JSON.parse(e);return t&&typeof t==`object`?t:{}}catch{return nx.warn(`OpenAITransport: function_call arguments are not valid JSON`,{raw:e}),{}}}var rC=class e{constructor(){this.noopProvider=new ax}get(t){return t===e.DEFAULT_NAME?this.noopProvider:void 0}default(){return this.noopProvider}defaultName(){return e.DEFAULT_NAME}names(){return[e.DEFAULT_NAME]}getStatus(t){return J(this,void 0,void 0,function*(){var n;return t!==void 0&&t!==e.DEFAULT_NAME?null:(yield(n=this.noopProvider).getStatus?.call(n))??null})}listStatuses(){return J(this,void 0,void 0,function*(){var t;let n=(yield(t=this.noopProvider).getStatus?.call(t))??null;return[{name:e.DEFAULT_NAME,isDefault:!0,status:n}]})}};rC.DEFAULT_NAME=`default`;let iC=N.createInterface(e=>e.singleton(rC)),aC=6e4,oC=3e5;Object.freeze({anthropic:Object.freeze({low:Object.freeze({model:`claude-haiku-4-5-20251001`,maxTokens:16e3,stallTimeoutMs:aC,timeoutMs:oC}),high:Object.freeze({model:`claude-sonnet-5`,maxTokens:128e3,stallTimeoutMs:aC,timeoutMs:oC}),reasoning:Object.freeze({model:`claude-opus-4-8`,maxTokens:32e3,stallTimeoutMs:aC,timeoutMs:oC})}),gemini:Object.freeze({low:Object.freeze({model:`gemini-3.1-flash-lite`,stallTimeoutMs:aC,timeoutMs:oC}),high:Object.freeze({model:`gemini-3.8-flash`,stallTimeoutMs:aC,timeoutMs:oC}),reasoning:Object.freeze({model:`gemini-3.1-pro-preview`,stallTimeoutMs:aC,timeoutMs:oC})}),openai:Object.freeze({low:Object.freeze({model:`gpt-6-luna`,stallTimeoutMs:aC,timeoutMs:oC}),high:Object.freeze({model:`gpt-6.1-terra`,stallTimeoutMs:aC,timeoutMs:oC}),reasoning:Object.freeze({model:`gpt-6.1-sol`,stallTimeoutMs:aC,timeoutMs:oC})})});let sC=O` :host{display: block;width: 800px}.ai-criteria-search{display: flex;flex-direction: column;gap: calc(${B} * 2px)}.ai-criteria-search-row{display: flex;flex-direction: row;gap: calc(${B} * 2px);align-items: center}.criteria-input{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0}.criteria-chips-inline{height: calc(((var(--base-height-multiplier) + var(--density)) * var(--design-unit) - 4) * 1px);flex: 1;min-width: 0;display: flex;align-items: center;gap: calc(${B} * 1px);overflow-x: auto;padding: 0 calc(${B} * 2px);background: var(--neutral-fill-input-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(var(--control-corner-radius) * 1px);scrollbar-width: none}.criteria-chips-inline::-webkit-scrollbar{display: none}.mic-icon{color: var(--neutral-foreground-rest);fill: currentColor}.criteria-toggle-button, .criteria-clear-button{flex-shrink: 0}.criteria-chip{display: inline-flex;align-items: center;flex-shrink: 0;gap: calc(${B} * 1px);padding: calc(${B} * 0.5px) calc(${B} * 2px);background: var(--neutral-fill-rest);border: calc(var(--stroke-width) * 1px) solid var(--neutral-stroke-rest);border-radius: calc(${B} * 4px);font-size: var(--type-ramp-minus-1-font-size);color: var(--neutral-foreground-rest);white-space: nowrap}.criteria-chip-field{font-weight: 600}.criteria-chip-operator{color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-style: italic}.criteria-chip-remove{display: inline-flex;align-items: center;justify-content: center;width: 14px;height: 14px;padding: 0;margin-left: calc(${B} * 0.5px);background: none;border: none;cursor: pointer;color: var(--neutral-foreground-hint, var(--neutral-foreground-rest));font-size: 10px;border-radius: 50%;line-height: 1}.criteria-chip-remove:hover{background: var(--neutral-fill-hover);color: var(--neutral-foreground-rest)}`,ese=e=>T` ${A(()=>tx(),T`<div class="ai-criteria-search"><div class="ai-criteria-search-row">${A(e=>!e.showingChips,T`<${e}-text-area ${k(`textAreaRef`)}class="criteria-input" placeholder="${e=>e.placeholder}" ?disabled=${e=>e.disabled||e.isInterpreting}:value=${uf(e=>e.inputValue,`string`,`input`)}@blur=${e=>e.handleBlur()}rows="1"></${e}-text-area>`)} ${A(e=>e.showingChips,T`<div class="criteria-chips-inline">${j(e=>e.criteriaChips,T`<span class="criteria-chip"><span class="criteria-chip-field">${e=>e.fieldLabel}</span><span class="criteria-chip-operator">${e=>e.operatorLabel}</span>${A(e=>!!e.valueLabel,T`<span class="criteria-chip-value">${e=>e.valueLabel}</span>`)}<button class="criteria-chip-remove" aria-label="Remove filter" @click=${(e,t)=>t.parent.removeChip(e.groupIndex,e.clauseIndex)}>
254
254
  &#x2715;
255
255
  </button></span>`)}</div>`)}<${e}-button class="criteria-toggle-button" appearance="outline" title=${e=>e.showingChips?`Add more criteria`:`View active filters`}?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.toggleCriteriaView()}><${e}-icon name="pen" size="sm"></${e}-icon></${e}-button><${e}-button class="criteria-clear-button" appearance="outline" title="Clear all filters" ?disabled=${e=>e.activeGroups.length===0||e.isInterpreting}@click=${e=>e.clearChips()}><${e}-icon name="trash-alt" size="sm"></${e}-icon></${e}-button>${A(e=>e.speechAvailable,T`<${e}-button class="mic-button" appearance="${e=>e.isRecording?`accent`:`outline`}" ?disabled=${e=>e.disabled||e.isInterpreting}@click=${e=>e.toggleSpeechInput()}title=${e=>e.isRecording?`Stop recording`:`Start voice input`}><${e}-icon class="mic-icon" name="microphone" size="lg" variant="solid"></${e}-icon></${e}-button>`)}</div></div>`)} `,cC=T` ${e=>ese(Sb(e))} `,tse={contains:Nb.containsIgnoreCase,equals:Nb.EQ,startsWith:Nb.startsWith,endsWith:Nb.endsWith,greaterThan:Nb.GT,lessThan:Nb.LT,greaterThanOrEqual:Nb.GE,lessThanOrEqual:Nb.LE,notEqual:Nb.NE,dateIsToday:Nb.dateIsToday,dateIsAfter:Nb.dateIsGreaterEqual,dateIsGreaterEqual:Nb.dateIsGreaterEqual,dateIsBefore:Nb.dateIsLessEqual,dateIsLessEqual:Nb.dateIsLessEqual,dateIsEqual:Nb.dateIsEqual,dateTimeIsAfter:Nb.dateTimeIsGreaterEqual,dateTimeIsGreaterEqual:Nb.dateTimeIsGreaterEqual,dateTimeIsBefore:Nb.dateTimeIsLessEqual,dateTimeIsLessEqual:Nb.dateTimeIsLessEqual};function nse(e){let t=tse[e.operator];if(!t)throw Error(`Unknown criteria operator '${e.operator}'`);return new Rb().withField(e.field).withValue(e.value??null).withSerialiser(t).withGroup(`default`).build()}function rse(e,t){return e.length===1?e[0]:e.reduce((e,n,r)=>r===0?[n]:[...e,t,n],[])}function lC(e){let t=new Lb,n=!1;for(let r of e){if(!r.clauses?.length)continue;let e=r.clauses.map(nse),i=r.logic===`or`?Eb.Or():Eb.And(),a=rse(e,i),o=e.length>1?{join:i}:{};r.negated?t.And([Eb.Not(),a]):t.And(e.length===1?e[0]:e,o),n=!0}return n?t.build():``}let ise=[`contains`,`equals`,`startsWith`,`notEqual`],uC=[`equals`,`greaterThan`,`lessThan`,`greaterThanOrEqual`,`lessThanOrEqual`,`notEqual`],dC=[`dateIsToday`,`dateIsAfter`,`dateIsBefore`,`dateIsEqual`,`dateIsGreaterEqual`,`dateIsLessEqual`],fC=[`dateTimeIsAfter`,`dateTimeIsBefore`,`dateTimeIsGreaterEqual`,`dateTimeIsLessEqual`],ase={contains:`contains`,equals:`=`,startsWith:`starts with`,endsWith:`ends with`,notEqual:`≠`,greaterThan:`>`,lessThan:`<`,greaterThanOrEqual:`≥`,lessThanOrEqual:`≤`,dateIsToday:`is today`,dateIsAfter:`after`,dateIsBefore:`before`,dateIsEqual:`=`,dateIsGreaterEqual:`≥`,dateIsLessEqual:`≤`,dateTimeIsAfter:`after`,dateTimeIsBefore:`before`,dateTimeIsGreaterEqual:`≥`,dateTimeIsLessEqual:`≤`},ose=/* @__PURE__ */ new Set([`DATE`,`LOCALDATE`]),sse=/* @__PURE__ */ new Set([`DATETIME`,`NANO_TIMESTAMP`,`LOCALDATETIME`,`TIMESTAMP`]),pC=/* @__PURE__ */ new Set([`INT`,`INTEGER`,`LONG`,`SHORT`,`DOUBLE`,`BIGDECIMAL`,`DECIMAL`]);function mC(e){return(e||``).toUpperCase().trim().split(`(`)[0].trim()}function cse(e){let t=mC(e);return ose.has(t)?dC:sse.has(t)?fC:pC.has(t)?uC:ise}function lse(e){return pC.has(mC(e))}function use(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e)&&e>0:typeof e==`string`?/^\d{8}$/.test(e)||/^\d{4}-\d{2}-\d{2}$/.test(e)||/^\d{8}-\d{2}:\d{2}(:\d{2})?$/.test(e):!1}function dse(e){return e==null?!1:typeof e==`number`?!Number.isNaN(e):typeof e==`string`&&!Number.isNaN(Number(e))}function fse(e,t){let n=[],r=[],i=/* @__PURE__ */ new Map;Array.isArray(t)&&t.length>0&&(typeof t[0]==`string`?t.forEach(e=>i.set(e,void 0)):t.forEach(e=>i.set(e.NAME,e)));for(let t of e){let{field:e,operator:a,value:o}=t;if(!e||typeof e!=`string`){r.push({field:String(e),message:`Field name is required`});continue}let s=i.get(e),c=s&&`TYPE`in s?s.TYPE:`STRING`;if(!cse(c).includes(a)){r.push({field:e,operator:a,value:o,message:`Operator '${a}' is not allowed for field type ${c}`});continue}if((dC.includes(a)||fC.includes(a))&&a!==`dateIsToday`&&!use(o)){r.push({field:e,operator:a,value:o,message:`Invalid date/datetime value; use yyyyMMdd, yyyy-MM-dd, or epoch`});continue}if(lse(c)&&uC.includes(a)&&!dse(o)){r.push({field:e,operator:a,value:o,message:`Invalid numeric value`});continue}if(i.size>0&&!i.has(e)){r.push({field:e,operator:a,value:o,message:`Unknown field '${e}'`});continue}n.push(t)}return{valid:n,invalid:r}}function pse(e,t){let n=[],r=[];for(let i of e){if(!i?.clauses||!Array.isArray(i.clauses)){r.push({field:``,message:`Group must have a clauses array`});continue}let{valid:e,invalid:a}=fse(i.clauses,t);r.push(...a),e.length>0&&n.push({logic:i.logic??`and`,negated:i.negated,clauses:e})}return{valid:n,invalid:r}}let hC=Ad(`foundation-notifications`),gC=null,_C=/* @__PURE__ */ new Map,vC=e=>`${e?.title??`Error`}: ${e?.body??`Something went wrong`}`,mse=e=>e?.logLevel||e?.config?.logLevel||vd.debug,yC=e=>{hC.log({message:vC(e),level:mse(e)})},bC=(e,t)=>{let n=document.querySelector(`#${e}`);if(!n){if(_C.has(e))n=_C.get(e);else{let t=Rd(document).find(t=>t.id===e);t&&(n=t,_C.set(e,t))}}if(!n){n=document.createElement(`div`),n.setAttribute(`id`,e),n.style.zIndex=`9999`;let{element:t,prefix:r}=Vd(document.body,`rapid`);if(t)t.appendChild(n),gC=t;else if(gC)gC.appendChild(n);else{let e=document.createElement(`${r}-design-system-provider`);e.appendChild(n),document.body.appendChild(e),gC=e}}return n},hse=e=>{for(;e&&!(e instanceof ShadowRoot);){let t=(e?.getRootNode())?.getElementById(`banner-anchor`);if(t)return t.style.position=`relative`,t;e=e?.getRootNode()?.host}return gse()},gse=()=>{let e=document.createElement(`div`);return e.setAttribute(`id`,`banner-anchor`),e.style.position=`relative`,document.body.insertBefore(e,document.body.firstChild),e},_se=e=>{yC(e),alert(vC(e))},vse=(e,t,n)=>{yC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-banner`),a=hse(n);a?.children?.length>0&&(i.style.position=`absolute`,i.style.top=`0`,i.style.left=`0`,i.style.width=`100%`),a.appendChild(i),i.notification=e},yse=e=>{let t=e.querySelector(`#dialog-container`);return t||(t=document.createElement(`div`),t.setAttribute(`id`,`dialog-container`),t.style.position=`relative`,e.appendChild(t)),t},bse=(e,t,n)=>{yC(e);let r=t.split(`-`)[0],i=document.createElement(`${r}-dialog`);(n?yse(n):bC(`dialog-container`,t)).appendChild(i),i.notification=e,i.show()};var xC;(function(e){e.NOTIFICATION_EVENT=`notification-event`})(xC||(xC={}));var SC;(function(e){e.Top=`top`,e.Bottom=`bottom`})(SC||(SC={}));var CC;(function(e){e.Left=`left`,e.Right=`right`})(CC||(CC={}));let wC=`12px`,xse=(e,t,n)=>{e.style.position=`fixed`,e.style.top=t===SC.Top?wC:``,e.style.bottom=t===SC.Bottom?wC:``,e.style.left=n===CC.Left?wC:``,e.style.right=n===CC.Right?wC:``},Sse=(e,t)=>{yC(e);let n=t.split(`-`)[0],r=document.createElement(`${n}-snackbar`),i=e.config?.snackbar?.verticalEdge??SC.Bottom,a=e.config?.snackbar?.horizontalEdge??CC.Left,o=bC(`snack-container-${i}-${a}`,t);o&&xse(o,i,a),o.appendChild(r),r.notification=e},Cse=e=>Rd(document.body).find(t=>t.tagName.toLowerCase()===`notify-container`&&t.position===e);function wse(e,t){switch(t.style.position=`fixed`,e?.config?.toast?.position){case`top-left`:t.style.top=`var(--nav-height, 0)`,t.style.left=`0`;break;case`bottom-left`:t.style.bottom=`0`,t.style.left=`0`;break;case`bottom-right`:t.style.bottom=`0`,t.style.right=`0`;break;default:t.style.top=`var(--nav-height, 0)`,t.style.right=`0`}}let TC=(e,t,n)=>{var r,i;yC(e);let a=t.split(`-`)[0],o=e?.config?.toast?.position||`top-right`,s=n??Cse(o)??bC(`notify-container`,t);s&&s.tagName.toLowerCase()!==`notify-container`&&wse(e,s);let c=document.createElement(`${a}-toast`),l=document.createElement(`div`);l.setAttribute(`slot`,`top`),l.textContent=e.title;let u=document.createElement(`div`);u.setAttribute(`slot`,`content`),u.textContent=e?.body||``;let d=document.createElement(`div`);d.setAttribute(`slot`,`date`),d.textContent=(e?.createdAt)?.toLocaleTimeString()||``;let f;e?.config?.toast?.buttons&&e?.config?.toast?.buttons?.length&&(f=document.createElement(`div`),f.setAttribute(`slot`,`bottom`),e.config.toast.buttons.forEach(t=>{let n=document.createElement(`${a}-button`);n.textContent=t.placeholder||`example placeholder`,n.addEventListener(`click`,()=>{let{details:r}=e.config.toast;if(t.action)return t.action({details:r,buttonElement:n,toastElement:c})}),t.appearance&&n.setAttribute(`appearance`,t.appearance),f.appendChild(n)})),c.setAttribute(`notify`,e?.config?.toast?.type||``),e.iconName&&c.setAttribute(`notification-icon`,e.iconName),(r=e?.config?.toast)!=null&&r.autoClose&&c.setAttribute(`auto-close`,`${e?.config?.toast?.autoClose}`),(i=e?.config?.toast)!=null&&i.closeTimeout&&c.setAttribute(`close-timeout`,`${e?.config?.toast?.closeTimeout}`),c.appendChild(l),c.appendChild(u),c.appendChild(d),f&&c.appendChild(f),s.prepend(c)},EC=(e,t,n)=>{if(!e.title)throw Error(`Title is required`);if(!e.body)throw Error(`Missing required param 'body'`);let r={title:e.title,body:e.body,iconName:e.iconName},i={};e.createdAt&&(r=Object.assign({createdAt:e.createdAt},r)),e.logLevel!=null&&(r=Object.assign({logLevel:e.logLevel},r)),e.toast&&(i=Object.assign({toast:e.toast},i),r=Object.assign({config:i},r)),TC(r,t,n)},Tse=O` :host{position: fixed;z-index: 9999;display: flex;flex-direction: column;gap: 4px;box-sizing: border-box;pointer-events: none;/* Allow clicks to pass through empty space */ width: 415px}.toast-container{padding: 0 8px 12px 12px;position: relative}/* Expanded / List State: Allow scrolling if too many items */ :host(:not([stack-collapsed])){max-height: calc(100% - var(--nav-height));overflow: hidden;pointer-events: auto;/* Enable pointer events for scrolling */ slot{display: block;height: calc(100vh - var(--nav-height) - 54px);position: relative}.toast-container{flex: 1;height: 100%;overflow: hidden auto;scrollbar-color: var(--neutral-layer-3) transparent;&:hover{scrollbar-color: var(--neutral-layer-4) transparent}}}.header{display: flex;gap: 12px;pointer-events: none;margin: 5px 24px;justify-content: space-between;visibility: hidden;align-items: center;box-sizing: border-box;.header-title{text-shadow: 0 0 10px #000}.notification-header-buttons{display: flex;gap: 4px;rapid-icon{color: var(--neutral-foreground-hint);margin-left: 4px;display: inline-flex;font-size: 14px;&.chevron-up.collapse{transform: rotate(180deg);transition: transform 0.3s ease}}}--base-height-multiplier: 8;*[appearance='neutral']{font-size: 11px;cursor: pointer;background: var(--neutral-fill-rest)}}.header.visible{visibility: visible;pointer-events: auto;/* Enable clicks on header buttons */}:host([position$='left']) .header{justify-content: space-between}:host([position^='bottom']) .header{margin-bottom: 0;margin-top: 4px}/* Ensure children (toasts) are clickable */ ::slotted(*){pointer-events: auto}:host([position='top-right']){top: var(--nav-height, 0);right: 0}:host([position='top-left']){top: var(--nav-height, 0);left: 0}:host([position='bottom-right']){bottom: 0;right: 0;flex-direction: column-reverse}:host([position='bottom-left']){bottom: 0;left: 0;flex-direction: column-reverse}/* Stacked / Collapsed State */ :host([stack-collapsed]){height: min-content;/* Host allows pointer events so they can reach the slot */ pointer-events: auto;cursor: pointer}/* Apply the grid layout to the slot itself so it acts as the container and click target */ :host([stack-collapsed]) slot{display: grid;grid-template-columns: auto;grid-template-rows: auto;place-items: end center;/* Default to bottom-up stacking */ /* The slot catches the click */ pointer-events: auto}/* Rotate when the collapse class is present */ :host([stack-collapsed][position^='top']) slot{align-items: start}:host([stack-collapsed][position$='right']) slot{justify-items: end}:host([stack-collapsed][position$='left']) slot{justify-items: start}:host([stack-collapsed]) ::slotted(*){grid-area: 1 / 1;transition: transform 0.3s ease, top 0.3s ease, opacity 0.3s ease;opacity: 0%;pointer-events: none !important;/* Disable interaction with toasts in collapsed state */ transform: scale(0.9);top: 0 !important}/* Show and offset the top 3 items in the stack */ :host([stack-collapsed]) ::slotted([data-stack-index='0']){opacity: 100%;pointer-events: auto;transform: translateY(0) scale(1);z-index: 3;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='1']){opacity: 100%;transform: translateY(var(--stack-offset-y, 8px)) scale(0.95);z-index: 2;position: relative !important}:host([stack-collapsed]) ::slotted([data-stack-index='2']){opacity: 100%;transform: translateY(var(--stack-offset-y-2, 16px)) scale(0.9);z-index: 1;position: relative !important}/* Adjust offset direction based on position */ :host([stack-collapsed][position^='top']){--stack-offset-y: 8px;--stack-offset-y-2: 16px}:host([stack-collapsed][position^='bottom']){--stack-offset-y: -8px;--stack-offset-y-2: -16px}`,Ese=e=>T`<div class="header ${e=>pn([`visible`,e.slottedNodes.length>1])}">${A(e=>e.showCount,T`<span class="header-title">${e=>e.slottedNodes.length}Notifications</span>`)}<div class="notification-header-buttons">${A(e=>e.allowManualCollapse,T`<${e}-button @click=${e=>e.handleToggleCollapse()}>${e=>e.stackCollapsed?`Expand`:`Collapse`}<${e}-icon class="chevron-up ${e=>pn([`collapse`,e.stackCollapsed])}" name="chevron-up"></${e}-icon></${e}-button>`)} ${A(e=>e.allowCloseAll,T`<${e}-button @click=${e=>e.handleCloseAll()}>
256
256
  Close All <${e}-icon name="xmark"></${e}-icon></${e}-button>`)}</div></div>`,Dse=T` ${A(e=>e.allowCloseAll||e.allowManualCollapse,T` ${e=>Ese(e.designSystemPrefix)} `)}<div class="toast-container"><slot ${xt(`slottedNodes`)}@click="${e=>e.handleContainerClick()}"></slot></div>`,DC=class extends Qe{constructor(){super(...arguments),this.position=`top-right`,this.stackThreshold=5,this.allowManualCollapse=!0,this.allowCloseAll=!0,this.designSystemPrefix=`rapid`,this.showCount=!0,this.stackCollapsed=!1,this.notificationInterval=0,this.manuallyExpanded=!1,this.pendingQueue=[],this.queueTimer=null,this.queuedNodes=/* @__PURE__ */ new Set,this.mutationObserver=null,this.knownNodes=/* @__PURE__ */ new Set,this.peekingNode=null,this.peekTimer=null,this.routeSubscriber={handleChange:()=>this.checkRoute(Hf.shared.pathName)},this.slottedNodes=[]}connectedCallback(){super.connectedCallback(),(this.position===`bottom-left`||this.position===`bottom-right`)&&hC.error(`NotifyContainer doesn't currently support bottom corner placements`),S.getNotifier(Hf.shared).subscribe(this.routeSubscriber,`pathName`),this.checkRoute(Hf.shared.pathName),this.mutationObserver=new MutationObserver(e=>this.handleMutation(e)),this.mutationObserver.observe(this,{childList:!0})}disconnectedCallback(){var e;super.disconnectedCallback(),S.getNotifier(Hf.shared).unsubscribe(this.routeSubscriber,`pathName`),(e=this.mutationObserver)==null||e.disconnect(),this.mutationObserver=null}checkRoute(e){(e.includes(`/login`)||e.includes(`/logout`))&&(this.pendingQueue=[],this.queuedNodes.clear(),clearTimeout(this.queueTimer),this.queueTimer=null,this.handleCloseAll())}slottedNodesChanged(){if(!this.manuallyExpanded&&!this.stackCollapsed&&this.slottedNodes.length>this.stackThreshold&&(this.stackCollapsed=!0),this.stackCollapsed&&this.slottedNodes.length<=1&&(this.stackCollapsed=!1,this.manuallyExpanded=!1,this.cancelPeek()),this.stackCollapsed){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement&&!this.knownNodes.has(e)).shift();e&&this.maybePeek(e)}this.knownNodes=new Set(this.slottedNodes),this.applySort()}handleContainerClick(){this.stackCollapsed&&(this.stackCollapsed=!1,this.manuallyExpanded=!0,this.cancelPeek())}handleToggleCollapse(){this.stackCollapsed=!this.stackCollapsed,this.manuallyExpanded=!this.stackCollapsed,this.stackCollapsed||this.cancelPeek()}handleCloseAll(){for(this.cancelPeek();this.firstChild;)this.removeChild(this.firstChild);this.stackCollapsed=!1,this.manuallyExpanded=!1}notificationIntervalChanged(e,t){!t&&this.pendingQueue&&this.flushQueue()}handleMutation(e){this.notificationInterval&&(e.forEach(e=>{e.addedNodes.forEach(e=>{e instanceof HTMLElement&&(this.queuedNodes.has(e)?this.queuedNodes.delete(e):(this.removeChild(e),this.pendingQueue.push(e)))})}),this.queueTimer||this.processQueue())}processQueue(){if(!this.pendingQueue.length){this.queueTimer=null;return}let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e),this.queueTimer=setTimeout(()=>{this.queueTimer=null,this.processQueue()},this.notificationInterval)}flushQueue(){for(clearTimeout(this.queueTimer),this.queueTimer=null;this.pendingQueue.length;){let e=this.pendingQueue.shift();this.queuedNodes.add(e),this.prepend(e)}}sortFnChanged(){this.applySort()}applySort(){let e=this.slottedNodes.filter(e=>e instanceof HTMLElement);if(!e.length)return;let t=this.sortFn&&e.length>1?[...e].sort(this.sortFn):e;this.peekingNode&&t.includes(this.peekingNode)?this.handlePosition([this.peekingNode,...t.filter(e=>e!==this.peekingNode)]):this.handlePosition(t)}maybePeek(e){let t=this.slottedNodes.filter(e=>e instanceof HTMLElement);if((this.sortFn&&t.length>1?[...t].sort(this.sortFn):t).indexOf(e)===0)return;this.cancelPeek(),this.peekingNode=e;let n=this.notificationInterval?this.notificationInterval/2:1500;this.peekTimer=setTimeout(()=>{this.peekingNode=null,this.peekTimer=null,this.applySort()},n)}cancelPeek(){clearTimeout(this.peekTimer),this.peekTimer=null,this.peekingNode=null}handlePosition(e){if(!e.length)return;e.forEach((t,n)=>{t.style.position=`absolute`,t.style.transition=`all 0.3s ease-in`,t.style.right=`0px`,t.style.zIndex=(e.length-n).toString(),t.dataset.stackIndex=n.toString()});let t=e.map(e=>e.offsetHeight);e.reduce((e,n,r)=>(n.style.top=`${e}px`,e+t[r]),0)}};q([D],DC.prototype,`position`,void 0),q([D({attribute:`stack-threshold`})],DC.prototype,`stackThreshold`,void 0),q([D({attribute:`allow-manual-collapse`,mode:`boolean`})],DC.prototype,`allowManualCollapse`,void 0),q([D({attribute:`allow-close-all`,mode:`boolean`})],DC.prototype,`allowCloseAll`,void 0),q([D({attribute:`design-system-prefix`})],DC.prototype,`designSystemPrefix`,void 0),q([D({attribute:`show-count`,mode:`boolean`})],DC.prototype,`showCount`,void 0),q([D({attribute:`stack-collapsed`,mode:`boolean`})],DC.prototype,`stackCollapsed`,void 0),q([D({attribute:`notification-interval`})],DC.prototype,`notificationInterval`,void 0),q([C],DC.prototype,`sortFn`,void 0),q([C],DC.prototype,`slottedNodes`,void 0),DC=q([$e({name:`notify-container`,template:Dse,styles:Tse})],DC);let OC={alert:_se,toast:TC,dialog:bse,snackbar:Sse,banner:vse},kC=(e,t,n)=>{Object.keys(e?.config||{}).forEach(r=>{OC[r]&&OC[r](e,t,n)})};function Ose(e){return e.length===0?``:e.length===1?e[0].message:e.map(e=>e.message).join(`; `)}function AC(e,t,n){t?.trim()&&kC({title:e,body:t,config:{toast:{autoClose:!0,closeTimeout:4e3,type:`error`}}},n)}var jC=class extends P{constructor(){super(...arguments),this.placeholder=`Describe your search criteria in natural language...`,this.inputValue=``,this.isInterpreting=!1,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.fieldMetadata=[],this.isRecording=!1,this.stopRecording=null,this.speechApplyDebounceTimer=null}get speechAvailable(){return rx()}get criteriaChips(){return this.activeGroups.flatMap((e,t)=>e.clauses.map((e,n)=>({groupIndex:t,clauseIndex:n,fieldLabel:this.getFieldLabel(e.field),operatorLabel:ase[e.operator]??e.operator,valueLabel:e.operator===`dateIsToday`?``:String(e.value??``)})))}getFieldLabel(e){if(!Array.isArray(this.fieldMetadata)||this.fieldMetadata.length===0||typeof this.fieldMetadata[0]==`string`)return e;let t=this.fieldMetadata.find(t=>t.NAME===e);return t?.UI_LABEL??t?.NAME??e}toggleCriteriaView(){this.showingChips?(this.inputValue=``,this.showingChips=!1):this.showingChips=!0}removeChip(e,t){var n;let r=this.activeGroups.map(e=>Object.assign(Object.assign({},e),{clauses:[...e.clauses]}));(n=r[e])==null||n.clauses.splice(t,1);let i=r.filter(e=>e.clauses.length>0);if(this.activeGroups=i,i.length===0)this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null);else{let e=lC(i);this.lastValidCriteria=e,this.$emit(`criteria-changed`,e)}}clearChips(){this.activeGroups=[],this.showingChips=!1,this.lastValidCriteria=null,this.$emit(`criteria-changed`,null)}handleSubmit(){return J(this,void 0,void 0,function*(){let e=this.inputValue?.trim();if(!e||this.isInterpreting)return;let t=this.providerRegistry?.default();if(!t?.interpretCriteria){AC(`AI criteria search`,`AI provider not configured`,Sb(this));return}this.isInterpreting=!0;try{let n=Array.isArray(this.fieldMetadata)?this.fieldMetadata:[],r=yield t.interpretCriteria(e,{fields:n});if(!(r?.groups)?.some(e=>e.clauses?.length)){AC(`AI criteria search`,`AI could not interpret the criteria`,Sb(this)),this.isInterpreting=!1;return}let{valid:i,invalid:a}=pse(r.groups,this.fieldMetadata);if(a.length>0&&(AC(`Criteria validation error`,Ose(a),Sb(this)),this.$emit(`validation-errors`,a)),i.length>0){let e=[...this.activeGroups,...i],t=lC(e);this.lastValidCriteria=t,this.activeGroups=e,this.inputValue=``,this.showingChips=!0,this.$emit(`criteria-changed`,t)}}catch(e){AC(`AI criteria search`,e instanceof Error?e.message:`Interpretation failed`,Sb(this))}finally{this.isInterpreting=!1}})}handleBlur(){this.isRecording||(this.inputValue?.trim()?this.handleSubmit():this.activeGroups.length>0&&(this.showingChips=!0))}clear(){this.inputValue=``,this.lastValidCriteria=null,this.activeGroups=[],this.showingChips=!1,this.$emit(`criteria-changed`,null)}toggleSpeechInput(){if(this.isRecording&&this.stopRecording){this.clearSpeechApplyDebounce(),this.stopRecording(),this.stopRecording=null,this.isRecording=!1;return}this.inputValue=``,this.showingChips=!1,this.stopRecording=ix((e,t)=>{this.inputValue=e,t&&e?.trim()&&(this.clearSpeechApplyDebounce(),this.stopRecording&&(this.stopRecording(),this.stopRecording=null,this.isRecording=!1),this.speechApplyDebounceTimer=setTimeout(()=>{this.speechApplyDebounceTimer=null,this.handleSubmit()},700))},()=>{this.clearSpeechApplyDebounce(),this.isRecording=!1,this.stopRecording=null}),this.stopRecording&&(this.isRecording=!0)}clearSpeechApplyDebounce(){this.speechApplyDebounceTimer&&(clearTimeout(this.speechApplyDebounceTimer),this.speechApplyDebounceTimer=null)}};q([iC],jC.prototype,`providerRegistry`,void 0),q([D],jC.prototype,`placeholder`,void 0),q([D({mode:`boolean`})],jC.prototype,`disabled`,void 0),q([C],jC.prototype,`inputValue`,void 0),q([C],jC.prototype,`isInterpreting`,void 0),q([C],jC.prototype,`lastValidCriteria`,void 0),q([C],jC.prototype,`activeGroups`,void 0),q([C],jC.prototype,`showingChips`,void 0),q([C],jC.prototype,`fieldMetadata`,void 0),q([C],jC.prototype,`isRecording`,void 0),q([w],jC.prototype,`speechAvailable`,null),q([w],jC.prototype,`criteriaChips`,null);let MC={};jC.compose(Object.assign({baseName:`ai-criteria-search`,template:cC,styles:sC,shadowOptions:void 0},MC));let NC=(e,t)=>O` :host{display: flex;justify-content: center;align-items: center;width: 100%;margin: calc(var(--design-unit) * 2px) 0;position: relative;/* Same as connection indicator */ --green: 50 164 49;--trafic-light-green: rgb(var(--green));--red: 187 30 16;--trafic-light-red: rgb(var(--red));--amber: 230 160 20;--trafic-light-amber: rgb(var(--amber))}.ai-indicator-container{display: flex;flex-direction: column;align-items: center;position: relative}.ai-indicator-badge{display: inline-flex;align-items: center;gap: calc(var(--design-unit) * 1.4px);font-size: 12px;line-height: 1;font-weight: 600;text-transform: uppercase;height: calc(var(--design-unit) * 6px);padding: calc(var(--design-unit) * 0.5px) calc(var(--design-unit) * 2px);border-radius: calc(var(--design-unit) * 1px);cursor: pointer;color: #fff}.ai-indicator-badge:hover{opacity: 90%}.ai-indicator-badge.green{background: var(--trafic-light-green)}.ai-indicator-badge.amber{background: var(--trafic-light-amber)}.ai-indicator-badge.red{background: var(--trafic-light-red)}.ai-indicator-badge .ai-indicator-icon{flex-shrink: 0;color: inherit}.ai-indicator-badge.pulsing{animation: ai-indicator-pulse 1.5s ease-in-out infinite}@keyframes ai-indicator-pulse{0%, 100%{opacity: 100%}50%{opacity: 50%}}.ai-indicator-dropdown{position: absolute;top: 100%;right: 0;margin-top: calc(var(--design-unit) * 2px);min-width: 200px;padding: calc(var(--design-unit) * 4px);background: var(--neutral-layer-floating, #fff);border: 1px solid var(--neutral-stroke-rest, #e0e0e0);border-radius: calc(var(--design-unit) * 2px);box-shadow: 0 calc(var(--design-unit) * 1px) calc(var(--design-unit) * 4px) rgb(0 0 0 / 12%);z-index: 1000}.ai-indicator-info{display: flex;flex-direction: column;gap: 0;margin: 0;padding: 0}.ai-indicator-info .info-row{display: grid;grid-template-columns: 72px 1fr;gap: calc(var(--design-unit) * 4px);align-items: baseline;padding: calc(var(--design-unit) * 1.5px) 0;border-bottom: 1px solid var(--neutral-stroke-subtle, #eee)}.ai-indicator-info .info-row:last-child{border-bottom: none}.ai-indicator-info .info-label{margin: 0;font-size: var(--type-ramp-base-font-size);font-weight: 500;color: var(--neutral-foreground-hint, #666)}.ai-indicator-info .info-value{margin: 0;font-size: var(--type-ramp-base-font-size);color: var(--neutral-foreground-rest, #333);text-transform: capitalize;word-break: break-word}.install-button{margin-top: calc(var(--design-unit) * 3px);width: 100%}`,kse=e=>T` ${A(()=>tx(),T`<div class="ai-indicator-container" part="ai-indicator-container"><div class=${e=>pn(`ai-indicator-badge`,[`green`,e.state===`available`||e.state===`server`],[`amber`,e.state===`downloading`||e.state===`downloadable`],[`red`,e.state===`unavailable`||e.state===`none`],[`pulsing`,e.state===`downloading`||e.isInstalling])}data-test-id="ai-indicator-badge" part="ai-indicator-badge" role="button" tabindex="0" aria-label="AI status" aria-haspopup="true" aria-expanded="${e=>e.open}" @click=${e=>e.toggleDropdown()}@keydown=${(e,t)=>{let n=t.event;(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),e.toggleDropdown())}}><${e}-icon class="ai-indicator-icon" name="wand-magic-sparkles" size="xs" variant="solid" part="ai-indicator-icon"></${e}-icon><span class="ai-indicator-text" data-test-id="ai-indicator-text" part="ai-indicator-text">AI</span></div>${A(e=>e.open,T`<div class="ai-indicator-dropdown" part="ai-indicator-dropdown"><dl class="ai-indicator-info"><div class="info-row"><dt class="info-label">Provider</dt><dd class="info-value">${e=>e.status?.provider??`none`}</dd></div><div class="info-row"><dt class="info-label">Model</dt><dd class="info-value">${e=>e.status?.model||`—`}</dd></div>${A(e=>e.chromeStatusLabel,T`<div class="info-row"><dt class="info-label">Status</dt><dd class="info-value">${e=>e.chromeStatusLabel}</dd></div>`)}</dl>${A(e=>e.canInstall,T`<${e}-button class="install-button" appearance="accent" @click=${(e,t)=>{t.event.preventDefault(),e.onInstall()}}>
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@genesislcap/foundation-rapid-cdn",
3
3
  "description": "Side-effecting CDN bundle that auto-registers the Rapid Design System. Intended for AI/prototyping tools (e.g. Claude Artifacts), not for production apps.",
4
- "version": "15.107.0",
4
+ "version": "15.108.0",
5
5
  "sideEffects": true,
6
6
  "license": "SEE LICENSE IN license.txt",
7
7
  "unpkg": "dist/foundation-rapid-cdn.iife.min.js",
@@ -24,11 +24,11 @@
24
24
  "@babel/generator": "^7.29.0",
25
25
  "@babel/parser": "^7.29.0",
26
26
  "@babel/traverse": "^7.29.0",
27
- "@genesislcap/genx": "15.107.0",
27
+ "@genesislcap/genx": "15.108.0",
28
28
  "rolldown": "~1.2.9"
29
29
  },
30
30
  "dependencies": {
31
- "@genesislcap/rapid-design-system": "15.107.0"
31
+ "@genesislcap/rapid-design-system": "15.108.0"
32
32
  },
33
33
  "repository": {
34
34
  "type": "git",