@fungi.computer/grove 0.1.0 → 0.2.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.
Files changed (71) hide show
  1. package/README.md +18 -9
  2. package/dist/assets/Effect-BY0T-p9d.js +76 -0
  3. package/dist/assets/abort-signals-joV34wzR.js +1 -0
  4. package/dist/assets/anthropic-messages-BPUe3sjP.js +19 -0
  5. package/dist/assets/azure-openai-responses-qVCjcy57.js +1 -0
  6. package/dist/assets/{base-face-BaB6vmvy.js → base-face-Dc6wvM5e.js} +1 -1
  7. package/dist/assets/burger-CJ8nsj7v.js +1 -0
  8. package/dist/assets/cat-DCYVOD6V.js +1 -0
  9. package/dist/assets/classifier-shared-DtTbFkSF.js +1 -0
  10. package/dist/assets/cloudflare-workers-ai-system-one-C4GWBDtR.js +1 -0
  11. package/dist/assets/compat-Dluy1HPa.js +2 -0
  12. package/dist/assets/{diagnostics-CmW2yJSB.js → diagnostics-CxvqSC4Q.js} +1 -1
  13. package/dist/assets/{document-D5hwZS3o.js → document-DjWTbvB5.js} +1 -1
  14. package/dist/assets/error-BTdmRKoB.js +1 -0
  15. package/dist/assets/extension-hook-Ce1QNicQ.js +721 -0
  16. package/dist/assets/extensions-D55BOb_a.js +1 -0
  17. package/dist/assets/{google-generative-ai-DP-8xZvz.js → google-generative-ai-D4EEWKtU.js} +1 -1
  18. package/dist/assets/{google-shared-Cs5udoZV.js → google-shared-CvUYw8Za.js} +3 -3
  19. package/dist/assets/{google-vertex-BJiAIGUd.js → google-vertex-MtdrRNuD.js} +1 -1
  20. package/dist/assets/index--Y1OC0IE.js +171 -0
  21. package/dist/assets/index-BmdZJzrt.css +1 -0
  22. package/dist/assets/{json-parse-nqKewMRF.js → json-parse-M7s0500m.js} +2 -2
  23. package/dist/assets/mistral-conversations-CI9T5Sz9.js +4 -0
  24. package/dist/assets/models-BM_0GHMS.js +1 -0
  25. package/dist/assets/mushroom-CstiBfYI.js +1 -0
  26. package/dist/assets/{node.browser-hsQQ6fyG.js → node.browser-DL9pz-ZD.js} +1 -1
  27. package/dist/assets/node.browser-HQ5SKBOf.js +1 -0
  28. package/dist/assets/openai-codex-responses-C1JF2nxc.js +9 -0
  29. package/dist/assets/openai-completions-DJRWblh-.js +5 -0
  30. package/dist/assets/openai-decisions-CRn788gD.js +2 -0
  31. package/dist/assets/openai-responses-DT9fG-Eg.js +1 -0
  32. package/dist/assets/openai-responses-shared-BDR0j8d9.js +10 -0
  33. package/dist/assets/{openrouter-images-DwousKhc.js → openrouter-images-BqwSYNGm.js} +1 -1
  34. package/dist/assets/parakeet-conversation-DFuwoFfN.js +4 -0
  35. package/dist/assets/{pi-messages-CfXPQ4jp.js → pi-messages-0BariYjJ.js} +1 -1
  36. package/dist/assets/preload-helper-DY31Aviq.js +8 -0
  37. package/dist/assets/{provider-retry-CSlu6hjs.js → provider-retry-RVfYd5Vz.js} +1 -1
  38. package/dist/assets/renderer-l9sYXW5N.js +1 -0
  39. package/dist/assets/runtime-core-BHRx5Fxu.js +2 -0
  40. package/dist/assets/system-one-shared-DywxmMny.js +1 -0
  41. package/dist/assets/transform-messages-ByuM-ZZe.js +1 -0
  42. package/dist/assets/typesafe-system-one-D7tQu98S.js +1 -0
  43. package/dist/index.html +7 -7
  44. package/package.json +38 -18
  45. package/dist/assets/Effect-CxgtVs4O.js +0 -76
  46. package/dist/assets/anthropic-messages-DVt3Yh9K.js +0 -41
  47. package/dist/assets/azure-openai-responses-QZaJy-8U.js +0 -1
  48. package/dist/assets/burger-CoqBXzRV.js +0 -1
  49. package/dist/assets/cat-2dRm7fBw.js +0 -1
  50. package/dist/assets/cloudflare-workers-ai-system-one-Bq-3_D9p.js +0 -1
  51. package/dist/assets/compat-fz0ZcRJH.js +0 -2
  52. package/dist/assets/error-CJ3RHG07.js +0 -1
  53. package/dist/assets/extension-hook-0UB2lkEs.js +0 -560
  54. package/dist/assets/extensions-CAsZR9ky.js +0 -1
  55. package/dist/assets/index-Bw6tV9qS.css +0 -1
  56. package/dist/assets/index-DRDNbHYF.js +0 -171
  57. package/dist/assets/mistral-conversations-mRYg3mWw.js +0 -4
  58. package/dist/assets/models-CcNnosqL.js +0 -1
  59. package/dist/assets/mushroom-B9t9hgQE.js +0 -1
  60. package/dist/assets/node.browser-DFtqp6Hr.js +0 -1
  61. package/dist/assets/openai-codex-responses-CA-ivUEd.js +0 -9
  62. package/dist/assets/openai-completions-BxBCgHHI.js +0 -5
  63. package/dist/assets/openai-responses-cvwOEFWg.js +0 -1
  64. package/dist/assets/openai-responses-shared-DzD8B6NI.js +0 -10
  65. package/dist/assets/parakeet-conversation-w0nznEs9.js +0 -3
  66. package/dist/assets/preload-helper-mbhLTglw.js +0 -8
  67. package/dist/assets/renderer-s3PB0XrL.js +0 -1
  68. package/dist/assets/runtime-core-GKyHklNK.js +0 -2
  69. package/dist/assets/system-one-shared-CGF8IYMZ.js +0 -1
  70. package/dist/assets/transform-messages-CrQEqmfx.js +0 -1
  71. package/dist/assets/typesafe-system-one-CWcJw-Ys.js +0 -1
@@ -1,4 +0,0 @@
1
- import{_ as e,f as t,o as n,v as r}from"./preload-helper-mbhLTglw.js";import{a as i}from"./diagnostics-CmW2yJSB.js";import{n as a,t as o}from"./models-CcNnosqL.js";import{t as s}from"./headers-FK4rgixo.js";import{n as c}from"./json-parse-nqKewMRF.js";import{f as l,p as u,r as d,t as f,u as p}from"./transform-messages-CrQEqmfx.js";import{t as m}from"./sanitize-unicode-DmIE6hZJ.js";import{t as h}from"./hash-yQufAZII.js";var g=9,_=4e3,v=(e,n,r)=>{let a=new i,o=t(n,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let t=b(e);try{let n=r?.apiKey;if(!n)throw Error(`No API key for provider: ${e.provider}`);let i=x(),s=f(o.messages,e,e=>i(e)),c=B(e,o,s,r),l=await r?.onPayload?.(c,e);l!==void 0&&(c=l);let u=await E(e,c,n,r);if(a.push({type:`start`,partial:t}),await U(e,t,a,u,r?.onProviderStreamEvent),r?.signal?.aborted)throw Error(`Request was aborted`);if(t.stopReason===`pending`)throw Error(`Mistral stream ended without a finish reason`);if(t.stopReason===`aborted`||t.stopReason===`error`)throw Error(t.errorMessage||`An unknown error occurred`);a.push({type:`done`,reason:t.stopReason,message:t}),a.end()}catch(e){for(let e of t.content)delete e.partialArgs;t.stopReason=r?.signal?.aborted?`aborted`:`error`,t.errorMessage=C(e),a.push({type:`error`,reason:t.stopReason,error:t}),a.end()}})(),a},y=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let i={...d(e,t,n,r),toolChoice:n?.toolChoice},o=n?.reasoning?a(e,n.reasoning):void 0,s=o===`off`?void 0:o,c=e.reasoning?e.thinkingLevelMap:void 0,l=c?s?c[s]??`high`:c.off??void 0:void 0;return v(e,t,{...i,promptMode:e.reasoning&&!c&&s?`reasoning`:void 0,reasoningEffort:l})};function b(e){return{role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()}}function x(){let e=new Map,t=new Map;return n=>{let r=e.get(n);if(r)return r;let i=0;for(;;){let r=S(n,i),a=t.get(r);if(!a||a===n)return e.set(n,r),t.set(r,n),r;i++}}}function S(e,t){let n=e.replace(/[^a-zA-Z0-9]/g,``);if(t===0&&n.length===g)return n;let r=n||e,i=t===0?r:`${r}:${t}`;return h(i).replace(/[^a-zA-Z0-9]/g,``).slice(0,g)}function C(e){if(e instanceof Error){let t=e,n=typeof t.statusCode==`number`?t.statusCode:void 0,r=typeof t.body==`string`?t.body.trim():void 0;return n!==void 0&&r?`Mistral API error (${n}): ${w(r,_)}`:n===void 0?e.message:`Mistral API error (${n}): ${e.message}`}return T(e)}function w(e,t){return e.length<=t?e:`${e.slice(0,t)}... [truncated ${e.length-t} chars]`}function T(e){try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}async function E(e,t,n,r){let i=new URL(e.baseUrl);i.pathname=`${i.pathname.replace(/\/+$/u,``)}/`;let a=new URL(`v1/chat/completions`,i),o=O(e,n,r),c=AbortSignal.timeout(r?.timeoutMs??6e4),l=r?.signal?AbortSignal.any([r.signal,c]):c,u=await(r?.fetch??globalThis.fetch)(a,{method:`POST`,headers:o,body:JSON.stringify(j(t)),signal:l});if(await r?.onResponse?.({status:u.status,headers:s(u.headers)},e),!u.ok){let e=await u.text();throw new D(u.status,e,u.statusText)}if(!u.body)throw Error(`Mistral response has no body`);return L(u.body,l)}var D=class extends Error{statusCode;body;constructor(e,t,n){super(n||`Request failed with status ${e}`),this.name=`MistralHttpError`,this.statusCode=e,this.body=t}};function O(e,t,n){let r=new Headers({"User-Agent":u(),accept:`text/event-stream`,authorization:`Bearer ${t}`,"content-type":`application/json`});k(r,e.headers),k(r,n?.headers);let i=A(e.headers,`x-affinity`)||A(n?.headers,`x-affinity`);return V(n)&&!i&&r.set(`x-affinity`,n.sessionId),r}function k(e,t){if(t)for(let[n,r]of Object.entries(t))r===null?e.delete(n):e.set(n,r)}function A(e,t){return!!e&&Object.keys(e).some(e=>e.toLowerCase()===t)}function j(e){let t={...e};for(let[e,n]of[[`topP`,`top_p`],[`maxTokens`,`max_tokens`],[`randomSeed`,`random_seed`],[`responseFormat`,`response_format`],[`toolChoice`,`tool_choice`],[`presencePenalty`,`presence_penalty`],[`frequencyPenalty`,`frequency_penalty`],[`parallelToolCalls`,`parallel_tool_calls`],[`reasoningEffort`,`reasoning_effort`],[`promptMode`,`prompt_mode`],[`promptCacheKey`,`prompt_cache_key`],[`safePrompt`,`safe_prompt`]])P(t,e,n);t.messages=e.messages.map(e=>M(e));let n=t.response_format;if(F(n)){let e={...n};P(e,`jsonSchema`,`json_schema`);let r=e.json_schema;if(F(r)){let t={...r};P(t,`schemaDefinition`,`schema`),e.json_schema=t}t.response_format=e}return t}function M(e){let t={...e};return P(t,`toolCalls`,`tool_calls`),P(t,`toolCallId`,`tool_call_id`),Array.isArray(e.content)&&(t.content=e.content.map(e=>N(e))),t}function N(e){let t={...e};for(let[e,n]of[[`imageUrl`,`image_url`],[`documentUrl`,`document_url`],[`documentName`,`document_name`],[`fileId`,`file_id`],[`referenceIds`,`reference_ids`],[`inputAudio`,`input_audio`]])P(t,e,n);return t}function P(e,t,n){t in e&&(e[n]=e[t],delete e[t])}function F(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var I=Symbol(`mistral-stream-done`);async function*L(e,t){let n=e.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t.addEventListener(`abort`,a,{once:!0});try{for(;;){if(t.aborted)throw t.reason;let{done:e,value:a}=await n.read();if(t.aborted)throw t.reason;i+=e?r.decode():r.decode(a,{stream:!0});let o=R(i);for(;o;){let e=z(i.slice(0,o.index));if(i=i.slice(o.index+o.length),e===I)return;e&&(yield e),o=R(i)}if(e)break}if(i.trim()){let e=z(i);e!==I&&e&&(yield e)}}finally{t.removeEventListener(`abort`,a);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}function R(e){let t=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(e);return t?.index===void 0?void 0:{index:t.index,length:t[0].length}}function z(e){let t=e.split(/\r\n|\r|\n/u).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
2
- `).trim();if(!t)return;if(t===`[DONE]`)return I;let n=JSON.parse(t);if(!F(n)||!Array.isArray(n.choices))throw Error(`Invalid Mistral streaming event`);return{data:n}}function B(e,t,r,i){let a={model:e.id,stream:!0,messages:K(r,e.input.includes(`image`))},o=n(t.messages);return o.length>0&&(a.tools=W(o)),i?.temperature!==void 0&&(a.temperature=i.temperature),i?.maxTokens!==void 0&&(a.maxTokens=i.maxTokens),i?.toolChoice&&(a.toolChoice=J(i.toolChoice)),i?.promptMode&&(a.promptMode=i.promptMode),i?.reasoningEffort&&(a.reasoningEffort=i.reasoningEffort),V(i)&&(a.promptCacheKey=i.sessionId),a}function V(e){return e?.cacheRetention!==`none`&&!!e?.sessionId}function H(e,t){let n=e,r=n.promptTokensDetails?.cachedTokens??n.prompt_tokens_details?.cached_tokens??n.promptTokenDetails?.cachedTokens??n.prompt_token_details?.cached_tokens??n.numCachedTokens??n.num_cached_tokens??0;return Math.min(t,Math.max(0,typeof r==`number`&&Number.isFinite(r)?r:0))}async function U(e,t,n,r,i){let a=null,s=t.content,l=()=>s.length-1,u=new Map,d=e=>{if(e){if(e.type===`text`){n.push({type:`text_end`,contentIndex:l(),content:e.text,partial:t});return}e.type===`thinking`&&n.push({type:`thinking_end`,contentIndex:l(),content:e.thinking,partial:t})}};for await(let s of r){let r=s.data;if(await i?.(r,e),t.responseId||=r.id,r.usage){let n=r.usage.prompt_tokens||0,i=H(r.usage,n);t.usage.input=Math.max(0,n-i),t.usage.output=r.usage.completion_tokens||0,t.usage.cacheRead=i,t.usage.cacheWrite=0,t.usage.totalTokens=r.usage.total_tokens||t.usage.input+t.usage.output+t.usage.cacheRead+t.usage.cacheWrite,o(e,t.usage)}let f=r.choices[0];if(!f)continue;if(f.finish_reason){t.rawStopReason=f.finish_reason;let e=Y(f.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage)}let p=f.delta;if(p.content!==null&&p.content!==void 0){let e=typeof p.content==`string`?[p.content]:p.content;for(let r of e){if(typeof r==`string`){let e=m(r);if(!e)continue;(!a||a.type!==`text`)&&(d(a),a={type:`text`,text:``},t.content.push(a),n.push({type:`text_start`,contentIndex:l(),partial:t})),a.text+=e,n.push({type:`text_delta`,contentIndex:l(),delta:e,partial:t});continue}if(r.type===`thinking`){let e=(r.thinking??[]).map(e=>e.text??``).filter(e=>e.length>0).join(``),i=m(e);if(!i)continue;(!a||a.type!==`thinking`)&&(d(a),a={type:`thinking`,thinking:``},t.content.push(a),n.push({type:`thinking_start`,contentIndex:l(),partial:t})),a.thinking+=i,n.push({type:`thinking_delta`,contentIndex:l(),delta:i,partial:t});continue}if(r.type===`text`){let e=m(r.text??``);if(!e)continue;(!a||a.type!==`text`)&&(d(a),a={type:`text`,text:``},t.content.push(a),n.push({type:`text_start`,contentIndex:l(),partial:t})),a.text+=e,n.push({type:`text_delta`,contentIndex:l(),delta:e,partial:t})}}}let h=p.tool_calls||[];for(let e of h){a&&=(d(a),null);let r=e.id&&e.id!==`null`?e.id:S(`toolcall:${e.index??0}`,0),i=e.index??r,o=u.get(i),s;if(o!==void 0){let e=t.content[o];e?.type===`toolCall`&&(s=e)}s||(s={type:`toolCall`,id:r,name:e.function.name,arguments:{},partialArgs:``},t.content.push(s),u.set(i,t.content.length-1),n.push({type:`toolcall_start`,contentIndex:t.content.length-1,partial:t}));let l=typeof e.function.arguments==`string`?e.function.arguments:JSON.stringify(e.function.arguments||{});s.partialArgs=(s.partialArgs||``)+l,s.arguments=c(s.partialArgs),n.push({type:`toolcall_delta`,contentIndex:u.get(i),delta:l,partial:t})}}d(a);for(let e of u.values()){let r=t.content[e];if(r.type!==`toolCall`)continue;let i=r;i.arguments=c(i.partialArgs),delete i.partialArgs,n.push({type:`toolcall_end`,contentIndex:e,toolCall:i,partial:t})}}function W(e){return e.map(e=>{let t=l(e,!0);return{type:`function`,function:{name:e.name,description:e.description,parameters:G(p(e,t)),strict:t??!1}}})}function G(e){if(Array.isArray(e))return e.map(e=>G(e));if(e&&typeof e==`object`){let t={};for(let[n,r]of Object.entries(e))t[n]=G(r);return t}return e}function K(t,n){let i=[];for(let[a,o]of t.entries()){if(o.role===`system`){let t=a===0?e(o):r(o);t.length>0&&i.push({role:`system`,content:m(t)});continue}if(o.role===`user`){if(typeof o.content==`string`){i.push({role:`user`,content:m(o.content)});continue}let e=o.content.some(e=>e.type===`image`),t=o.content.filter(e=>e.type===`text`||n).map(e=>e.type===`text`?{type:`text`,text:m(e.text)}:{type:`image_url`,imageUrl:`data:${e.mimeType};base64,${e.data}`});if(t.length>0){i.push({role:`user`,content:t});continue}e&&!n&&i.push({role:`user`,content:`(image omitted: model does not support images)`});continue}if(o.role===`assistant`){let e=[],t=[];for(let n of o.content){if(n.type===`text`){n.text.trim().length>0&&e.push({type:`text`,text:m(n.text)});continue}if(n.type===`thinking`){n.thinking.trim().length>0&&e.push({type:`thinking`,thinking:[{type:`text`,text:m(n.thinking)}]});continue}t.push({id:n.id,type:`function`,function:{name:n.name,arguments:JSON.stringify(n.arguments||{})},index:0})}let n={role:`assistant`,prefix:!1};e.length>0&&(n.content=e),t.length>0&&(n.toolCalls=t),(e.length>0||t.length>0)&&i.push(n);continue}let t=[],s=q(o.content.filter(e=>e.type===`text`).map(e=>e.type===`text`?m(e.text):``).join(`
3
- `),o.content.some(e=>e.type===`image`),n,o.isError);t.push({type:`text`,text:s});for(let e of o.content)n&&e.type===`image`&&t.push({type:`image_url`,imageUrl:`data:${e.mimeType};base64,${e.data}`});i.push({role:`tool`,toolCallId:o.toolCallId,name:o.toolName,content:t})}return i}function q(e,t,n,r){let i=e.trim(),a=r?`[tool error] `:``;return i.length>0?`${a}${i}${t&&!n?`
4
- [tool image omitted: model does not support images]`:``}`:t?n?r?`[tool error] (see attached image)`:`(see attached image)`:r?`[tool error] (image omitted: model does not support images)`:`(image omitted: model does not support images)`:r?`[tool error] (no tool output)`:`(no tool output)`}function J(e){if(e)return e===`auto`||e===`none`||e===`any`||e===`required`?e:{type:`function`,function:{name:e.function.name}}}function Y(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:return{stopReason:`stop`};case`length`:case`model_length`:return{stopReason:`length`};case`tool_calls`:return{stopReason:`toolUse`};case`error`:return{stopReason:`error`,errorMessage:`Provider stopped with: error`};default:return{stopReason:`error`,errorMessage:`Provider stopped with: ${e}`}}}export{v as stream,y as streamSimple};
@@ -1 +0,0 @@
1
- import{d as e,t}from"./preload-helper-mbhLTglw.js";import{a as n,i as r}from"./diagnostics-CmW2yJSB.js";function i(e,t){return{role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function a(e){return typeof e.result==`function`}async function o(e,t){for await(let n of t)e.push(n);e.end(a(t)?await t.result():void 0)}function s(e,t){let r=new n;return t().then(e=>o(r,e)).catch(t=>{let n=i(e,t);r.push({type:`error`,reason:`error`,error:n}),r.end(n)}),r}function c(e,t){let n={stream:(t,n,r)=>s(t,async()=>(await e()).stream(t,n,r)),streamSimple:(t,n,r)=>s(t,async()=>(await e()).streamSimple(t,n,r))};return t?.fetchDeferred&&(n.fetchDeferred=(t,n,r)=>s(t,async()=>{let i=await e();if(!i.fetchDeferred)throw Error(`API does not support deferred responses`);return i.fetchDeferred(t,n,r)})),t?.cancelDeferred&&(n.cancelDeferred=async(t,n,r)=>{let i=await e();if(!i.cancelDeferred)throw Error(`API cannot cancel deferred responses`);await i.cancelDeferred(t,n,r)}),n}var l=function(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e},u=e=>t(()=>import(l(e)),[]);function d(){return globalThis.process?.env}function f(){return{async env(e){let t=d()?.[e];return typeof t==`string`&&t.trim().length>0?t:void 0},async fileExists(e){try{let t=await u(`node:fs/promises`),n=e;return n.startsWith(`~`)&&(n=(await u(`node:os`)).homedir()+n.slice(1)),await t.access(n),!0}catch{return!1}}}}function p(e){if(e.reason!==void 0)return e.reason;let t=Error(`The operation was aborted`);return t.name=`AbortError`,t}function m(e){return e??new AbortController().signal}function h(e,t){return t.aborted?(e.catch(()=>{}),Promise.reject(p(t))):new Promise((n,r)=>{let i=!1,a=()=>t.removeEventListener(`abort`,o),o=()=>{i||(i=!0,a(),r(p(t)))};t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{i||(i=!0,a(),n(e))},e=>{i||(i=!0,a(),r(e))}),t.aborted&&o()})}var g=class{credentials=new Map;chains=new Map;enqueue(e,t,n){let r=m(n?.signal),i=this.chains.get(e)??Promise.resolve(),a=(async()=>(await i.catch(()=>{}),r.throwIfAborted(),t()))(),o=a.catch(()=>{});return this.chains.set(e,o),o.then(()=>{this.chains.get(e)===o&&this.chains.delete(e)}),h(a,r)}async read(e,t){return t?.signal?.throwIfAborted(),this.credentials.get(e)}async list(e){return e?.signal?.throwIfAborted(),[...this.credentials].map(([e,t])=>({providerId:e,type:t.type}))}modify(e,t,n){return this.enqueue(e,async()=>{let r=this.credentials.get(e),i=await t(r);return n?.signal?.throwIfAborted(),i!==void 0&&this.credentials.set(e,i),i??r},n)}delete(e,t){return this.enqueue(e,async()=>{this.credentials.delete(e)},t)}},_=class extends Error{code;constructor(e,t,n){super(v(t,n?.cause),n),this.name=`ModelsError`,this.code=e}};function v(e,t){if(t==null)return e;let n=r(t).trim();return!n||e.includes(n)?e:`${e}: ${n}`}function y(e,t,n,r){let i=m(r?.signal);return h(b(e,t,n,r,i),i)}async function b(e,t,n,r,i){i.throwIfAborted();let a=r?.env?x(n,r.env):n;if(r?.apiKey!==void 0&&e.auth.apiKey)return T(a,e.auth.apiKey,e.id,{type:`api_key`,key:r.apiKey,env:r.env},i);let o=await E(t,e.id,i);if(o){if(o.type===`oauth`&&e.auth.oauth)return w(t,e.id,e.auth.oauth,o,i,r?.minOAuthValidityMs);if(o.type===`api_key`&&e.auth.apiKey){let t=r?.env?{...o,env:{...o.env,...r.env}}:o;return T(a,e.auth.apiKey,e.id,t,i)}return}return e.auth.apiKey?T(a,e.auth.apiKey,e.id,void 0,i):void 0}function x(e,t){return{env:async n=>t[n]||await e.env(n),fileExists:t=>e.fileExists(t)}}var S=3e5,C=15e3;async function w(e,t,n,r,i,a){let o=Math.max(S,a??0),s=e=>Date.now()+o>=e.expires,c=r;if(s(c)){let r;try{r=await e.modify(t,async e=>{if(e?.type===`oauth`&&s(e))try{let t=AbortSignal.any([i,AbortSignal.timeout(C)]);return await n.refresh(e,t)}catch(e){throw new _(`oauth`,`OAuth refresh failed for ${t}`,{cause:e})}},{signal:i})}catch(e){throw e instanceof _?e:new _(`auth`,`Credential store modify failed for ${t}`,{cause:e})}if(r?.type!==`oauth`)return;if(c=r,a!==void 0&&s(c))throw new _(`oauth`,`OAuth refresh returned a token that expires too soon for ${t}`)}try{return{auth:await n.toAuth(c),source:`OAuth`}}catch(e){throw new _(`oauth`,`OAuth auth derivation failed for ${t}`,{cause:e})}}async function T(e,t,n,r,i){try{return await t.resolve({ctx:e,credential:r,signal:i})}catch(e){throw new _(`auth`,`API key auth failed for provider ${n}`,{cause:e})}}async function E(e,t,n){try{return await e.read(t,{signal:n})}catch(e){throw new _(`auth`,`Credential store read failed for ${t}`,{cause:e})}}var D=class{entries=new Map;async read(e,t){t?.signal?.throwIfAborted();let n=this.entries.get(e);return n?structuredClone(n):void 0}async write(e,t,n){n?.signal?.throwIfAborted(),this.entries.set(e,structuredClone(t))}async delete(e,t){t?.signal?.throwIfAborted(),this.entries.delete(e)}};function O(e){return e.type??`chat`}function k(e,t){return O(e)===t}function A(e){if(!k(e,`chat`))throw new _(`provider`,`Model ${e.provider}/${e.id} is not a chat model`)}function j(e){if(!k(e,`image`))throw new _(`provider`,`Model ${e.provider}/${e.id} is not an image model`)}function M(e){if(!k(e,`classifier`))throw new _(`provider`,`Model ${e.provider}/${e.id} is not a classifier model`)}function N(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,output:[],stopReason:n?`aborted`:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}function P(e,t,n=!1){return{api:e.api,provider:e.provider,model:e.id,answers:{},stopReason:n?`aborted`:`error`,errorMessage:t instanceof Error?t.message:String(t),timestamp:Date.now()}}var F={chat:!0,image:!0,classifier:!0};function I(e){return Object.hasOwn(F,O(e))}function L(e){return{...e,models:e.models.filter(I)}}function R(e,t){if(!e&&!t)return;let n={...e};for(let[e,r]of Object.entries(t??{})){let t=e.toLowerCase();for(let e of Object.keys(n))e.toLowerCase()===t&&delete n[e];n[e]=r}return n}var z=class{providers=new Map;credentials;modelsStore;authContext;refreshGenerations=new Map;refreshControllers=new Map;publicationChains=new Map;constructor(e){this.credentials=e?.credentials??new g,this.modelsStore=e?.modelsStore??new D,this.authContext=e?.authContext??f()}setProvider(e){this.supersedeProviderRefresh(e.id),this.providers.set(e.id,e)}deleteProvider(e){this.supersedeProviderRefresh(e),this.providers.delete(e)}clearProviders(){for(let e of new Set([...this.providers.keys(),...this.refreshControllers.keys()]))this.supersedeProviderRefresh(e);this.providers.clear()}getProviders(){return Array.from(this.providers.values())}getProvider(e){return this.providers.get(e)}getModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getModels()}catch{return[]}}let t=[];for(let e of this.providers.values())try{t.push(...e.getModels())}catch{}return t}getAllModels(e){if(e!==void 0){let t=this.providers.get(e);if(!t)return[];try{return t.getAllModels?.()??t.getModels()}catch{return[]}}let t=[];for(let e of this.providers.values())try{t.push(...e.getAllModels?.()??e.getModels())}catch{}return t}getModelsOfType(e,t){return this.getAllModels(t).filter(t=>k(t,e))}getModel(e,t){return this.getModels(e).find(e=>e.id===t)}getModelOfType(e,t,n){return this.getModelsOfType(e,t).find(e=>e.id===n)}supersedeProviderRefresh(e){let t=(this.refreshGenerations.get(e)??0)+1;this.refreshGenerations.set(e,t);let n=this.refreshControllers.get(e);return n&&(this.refreshControllers.delete(e),n.abort()),t}beginProviderRefresh(e){let t=this.supersedeProviderRefresh(e),n=new AbortController;return this.refreshControllers.set(e,n),{generation:t,controller:n}}publishProviderModels(e,t,n,r){let i=this.publicationChains.get(e)??Promise.resolve(),a=(async()=>(await i.catch(()=>{}),n.aborted||this.refreshGenerations.get(e)!==t||(r.persist===null?await this.modelsStore.delete(e,{signal:n}):r.persist!==void 0&&await this.modelsStore.write(e,structuredClone(r.persist),{signal:n}),n.aborted||this.refreshGenerations.get(e)!==t)?!1:(r.update?.(),!0)))(),o=a.catch(()=>{});return this.publicationChains.set(e,o),o.then(()=>{this.publicationChains.get(e)===o&&this.publicationChains.delete(e)}),h(a,n)}async runProviderRefreshPhase(e,t,n,r,i,a){let o=await this.modelsStore.read(e.id,{signal:a});await e.refreshModels({credential:t,stored:o?L(structuredClone(o)):void 0,publish:t=>this.publishProviderModels(e.id,i,a,t),allowNetwork:n,force:n?r:void 0,signal:a})}async refresh(e={}){let t=e.allowNetwork??!0,n=m(e.signal),r=new Map;if(n.aborted)return{aborted:!0,errors:r};let i=e.providers?new Set(e.providers):void 0,a=Array.from(this.providers.values()).filter(e=>e.refreshModels!==void 0&&(!i||i.has(e.id))),o=Promise.all(a.map(async i=>{let{generation:a,controller:o}=this.beginProviderRefresh(i.id),s=AbortSignal.any([n,o.signal]),c=(async()=>{let n,r;try{n=await this.readCredential(i.id,s)}catch(e){r=e}if(await this.runProviderRefreshPhase(i,n,!1,void 0,a,s),r!==void 0)throw r;if(!t||s.aborted)return;let o=await this.resolveRefreshCredential(i,n,s);o&&await this.runProviderRefreshPhase(i,o,!0,e.force,a,s)})();try{await h(c,s)}catch(e){s.aborted||r.set(i.id,e instanceof Error?e:new _(`model_source`,`Model refresh failed for ${i.id}`,{cause:e}))}finally{this.refreshControllers.get(i.id)===o&&this.refreshControllers.delete(i.id)}}));try{await h(o,n)}catch(e){if(!n.aborted)throw e}return{aborted:n.aborted,errors:new Map(r)}}async resolveRefreshCredential(e,t,n){if(t?.type===`oauth`){let r=e.auth.oauth;if(!r)return;if(Date.now()<t.expires)return t;if(n.aborted)return;let i=await this.credentials.modify(e.id,async e=>{if(!(e?.type!==`oauth`||Date.now()<e.expires))return r.refresh(e,n)},{signal:n});return i?.type===`oauth`?i:void 0}let r=e.auth.apiKey;if(!r)return;let i=t?.type===`api_key`?t:void 0,a=await r.resolve({ctx:this.authContext,credential:i,signal:n});if(a)return{type:`api_key`,key:a.auth.apiKey,env:a.env}}async readCredential(e,t){try{return await this.credentials.read(e,{signal:t})}catch(t){throw new _(`auth`,`Credential store read failed for ${e}`,{cause:t})}}async checkProviderAuth(e,t,n){if(t?.type===`oauth`)return e.auth.oauth?{source:`OAuth`,type:`oauth`}:void 0;let r=e.auth.apiKey;if(!r)return;if(r.check)try{return await r.check({ctx:this.authContext,credential:t?.type===`api_key`?t:void 0,signal:n})}catch(t){throw new _(`auth`,`API key auth check failed for provider ${e.id}`,{cause:t})}let i=await y(e,this.credentials,this.authContext,{signal:n});return i?{source:i.source,type:`api_key`}:void 0}checkAuth(e,t){let n=m(t?.signal);return h((async()=>{n.throwIfAborted();let t=this.providers.get(e);if(t)return this.checkProviderAuth(t,await this.readCredential(e,n),n)})(),n)}async getAuthenticatedProviders(e,t){t.throwIfAborted();let n=e?[this.providers.get(e)].filter(e=>e!==void 0):this.getProviders();return(await Promise.all(n.map(async e=>{let n=await this.readCredential(e.id,t);return{provider:e,credential:n,auth:await this.checkProviderAuth(e,n,t)}}))).filter(e=>e.auth!==void 0)}getAvailable(e,t){let n=m(t?.signal);return h((async()=>(await this.getAuthenticatedProviders(e,n)).flatMap(({provider:e,credential:t})=>{let n=e.getModels();return e.filterModels?.(n,t)??n}))(),n)}async getAvailableOfType(e,t,n){return(await this.getAllAvailable(t,n)).filter(t=>k(t,e))}getAllAvailable(e,t){let n=m(t?.signal);return h((async()=>(await this.getAuthenticatedProviders(e,n)).flatMap(({provider:e,credential:t})=>{let n=e.getAllModels?.()??e.getModels();if(e.filterAllModels)return e.filterAllModels(n,t);if(!e.filterModels)return n;let r=new Set(e.filterModels(e.getModels(),t).map(e=>e.id));return n.filter(e=>!k(e,`chat`)||r.has(e.id))}))(),n)}async getAuth(e,t){let n=m(t?.signal),r=typeof e==`string`?e:e.provider,i=this.providers.get(r);if(!i)return;let a=await y(i,this.credentials,this.authContext,{...t,signal:n});return!a||typeof e==`string`||!e.headers?a:{...a,auth:{...a.auth,headers:R(a.auth.headers,e.headers)}}}async login(e,t,n,r){let i=m(n.signal);i.throwIfAborted();let a=this.providers.get(e);if(!a)throw new _(`provider`,`Unknown provider: ${e}`);let o=t===`oauth`?a.auth.oauth:a.auth.apiKey;if(!o?.login)throw new _(`auth`,`${a.name} does not support ${t} login`);let s=await h(o.login({...n,signal:i},r),i),c=!1,l,u=new Promise(e=>{l=e}),d=this.credentials.modify(e,async()=>(c=!0,l?.(),s),{signal:i});d.catch(()=>{});try{await new Promise((e,t)=>{let n=()=>{c||t(i.reason)};i.addEventListener(`abort`,n,{once:!0}),Promise.race([u,d]).then(()=>{i.removeEventListener(`abort`,n),e()},e=>{i.removeEventListener(`abort`,n),t(e)}),i.aborted&&n()}),await d}catch(t){throw i.throwIfAborted(),new _(`auth`,`Credential store modify failed for ${e}`,{cause:t})}return s}async logout(e,t){let n=m(t?.signal);n.throwIfAborted();try{await this.credentials.delete(e,{signal:n})}catch(t){throw n.throwIfAborted(),new _(`auth`,`Credential store delete failed for ${e}`,{cause:t})}}requireProvider(e){let t=this.providers.get(e.provider);if(!t)throw new _(`provider`,`Unknown provider: ${e.provider}`);return t}requireChatProvider(e){return A(e),this.requireProvider(e)}async applyAuth(e,t){this.requireProvider(e);let n=await this.getAuth(e,{apiKey:t?.apiKey,env:t?.env,signal:t?.signal});if(!n)throw new _(`auth`,`Provider is not configured: ${e.provider}`);let r=n.auth,i=t?.apiKey??r.apiKey,a=R(r.headers,t?.headers);t?.transformHeaders&&(a=await t.transformHeaders(a??{}));let o=n.env||t?.env?{...n.env??{},...t?.env??{}}:void 0,s=r.baseUrl?{...e,baseUrl:r.baseUrl}:e,{transformHeaders:c,...l}=t??{};return{requestModel:s,requestOptions:{...l,apiKey:i,headers:a,env:o}}}stream(t,n,r){let i=e(n);return s(t,async()=>{let e=this.requireChatProvider(t),{requestModel:n,requestOptions:a}=await this.applyAuth(t,r);return e.stream(n,i,a)})}async complete(e,t,n){return this.stream(e,t,n).result()}streamSimple(t,n,r){let i=e(n);return s(t,async()=>{let e=this.requireChatProvider(t),{requestModel:n,requestOptions:a}=await this.applyAuth(t,r);return e.streamSimple(n,i,a)})}async completeSimple(e,t,n){return this.streamSimple(e,t,n).result()}streamDeferred(e,t,n){return s(e,async()=>{let r=this.requireChatProvider(e);if(!r.fetchDeferred)throw new _(`provider`,`Provider ${e.provider} does not support deferred responses`);let{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return r.fetchDeferred(i,t,a)})}async fetchDeferred(e,t,n){return this.streamDeferred(e,t,n).result()}async cancelDeferred(e,t,n){let r=this.requireChatProvider(e);if(!r.cancelDeferred)throw new _(`provider`,`Provider ${e.provider} does not support deferred responses`);let{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);await r.cancelDeferred(i,t,a)}async generateImages(e,t,n){try{j(e);let r=this.requireProvider(e);if(!r.generateImages)throw new _(`provider`,`Provider ${e.provider} does not support image generation`);let{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return await r.generateImages(i,t,a)}catch(t){return N(e,t,n?.signal?.aborted)}}async classify(e,t,n){try{M(e);let r=this.requireProvider(e);if(!r.classify)throw new _(`provider`,`Provider ${e.provider} does not support classification`);let{requestModel:i,requestOptions:a}=await this.applyAuth(e,n);return await r.classify(i,t,a)}catch(t){return P(e,t,n?.signal?.aborted)}}};function B(e){return new z(e)}function V(e){let t=e.api&&typeof e.api.stream==`function`?e.api:void 0,n=t||!e.api?void 0:e.api,r=e.images,i=e.classifiers,a=t?[t]:Object.values(n??{}).filter(e=>e!==void 0),o=Object.values(r??{}).filter(e=>e!==void 0),c=Object.values(i??{}).filter(e=>e!==void 0);if(a.length===0&&o.length===0&&c.length===0)throw Error(`Provider ${e.id}: at least one of "api", "images", or "classifiers" is required.`);let l=e.models,u=[],d=e.fetchModels,f=()=>{let e=[...l];for(let t of u){let n=e.findIndex(e=>O(e)===O(t)&&e.id===t.id);n>=0?e[n]=t:e.push(t)}return e},p=e=>t??n?.[e.api],m=(t,n)=>{let r=p(t);return r?n(r):s(t,async()=>{throw new _(`stream`,`Provider ${e.id} has no API implementation for "${t.api}"`)})},h={id:e.id,name:e.name??e.id,baseUrl:e.baseUrl,headers:e.headers,auth:e.auth,getModels:()=>f().filter(e=>k(e,`chat`)),getAllModels:f,refreshModels:d?async t=>{if(t.stored){let n=t.stored.models.filter(t=>t.provider===e.id).map(e=>e);if(!await t.publish({update:()=>{u=n}}))return}if(!t.allowNetwork||t.signal.aborted)return;let n=await d(t);if(t.signal.aborted)return;let r=n.filter(I);await t.publish({persist:{models:r,checkedAt:Date.now()},update:()=>{u=r}})}:void 0,filterModels:e.filterModels,filterAllModels:e.filterAllModels,stream:(e,t,n)=>m(e,r=>r.stream(e,t,n)),streamSimple:(e,t,n)=>m(e,r=>r.streamSimple(e,t,n))};return a.some(e=>e.fetchDeferred!==void 0)&&(h.fetchDeferred=(t,n,r)=>s(t,async()=>{let i=p(t);if(!i?.fetchDeferred)throw new _(`provider`,`Provider ${e.id} does not support deferred responses for "${t.api}"`);return i.fetchDeferred(t,n,r)})),a.some(e=>e.cancelDeferred!==void 0)&&(h.cancelDeferred=async(t,n,r)=>{let i=p(t);if(!i?.cancelDeferred)throw new _(`provider`,`Provider ${e.id} cannot cancel deferred responses for "${t.api}"`);await i.cancelDeferred(t,n,r)}),r&&o.length>0&&(h.generateImages=async(t,n,i)=>{let a=r[t.api];return a?a.generateImages(t,n,i):N(t,new _(`provider`,`Provider ${e.id} has no image generation implementation for "${t.api}"`))}),i&&c.length>0&&(h.classify=async(t,n,r)=>{let a=i[t.api];return a?a.classify(t,n,r):P(t,new _(`provider`,`Provider ${e.id} has no classifier implementation for "${t.api}"`))}),h}function H(e,t){let n=t.input+t.cacheRead+t.cacheWrite,r=e.cost,i=-1;for(let t of e.cost.tiers??[])n>t.inputTokensAbove&&t.inputTokensAbove>i&&(r=t,i=t.inputTokensAbove);let a=t.cacheWrite1h??0,o=t.cacheWrite-a;return t.cost.input=r.input/1e6*t.input,t.cost.output=r.output/1e6*t.output,t.cost.cacheRead=r.cacheRead/1e6*t.cacheRead,t.cost.cacheWrite=(r.cacheWrite*o+r.input*2*a)/1e6,t.cost.total=t.cost.input+t.cost.output+t.cost.cacheRead+t.cost.cacheWrite,t.cost}var U=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`];function W(e){return e.reasoning?U.filter(t=>{let n=e.thinkingLevelMap?.[t];return n===null?!1:t===`xhigh`||t===`max`?n!==void 0:!0}):[`off`]}function G(e,t){let n=W(e);if(n.includes(t))return t;let r=U.indexOf(t);if(r===-1)return n[0]??`off`;for(let e=r;e<U.length;e++){let t=U[e];if(n.includes(t))return t}for(let e=r-1;e>=0;e--){let t=U[e];if(n.includes(t))return t}return n[0]??`off`}export{W as a,D as c,f as d,c as f,V as i,_ as l,G as n,O as o,s as p,B as r,k as s,H as t,g as u};
@@ -1 +0,0 @@
1
- import{a as e}from"./document-D5hwZS3o.js";import{t}from"./renderer-s3PB0XrL.js";var n={version:1,name:`mushroom`,renderer:`zdog`,controls:{body:{type:`color`,label:`body`,default:`#fff7e4`},cap:{type:`color`,label:`cap`,default:`#f98284`},capSpot:{type:`color`,label:`capSpot`,default:`#ffe6c6`},eye:{type:`color`,label:`eye`,default:`#28282e`},mouth:{type:`color`,label:`mouth`,default:`#28282e`},blush:{type:`color`,label:`blush`,default:`#feaae4`},dead:{type:`color`,label:`dead`,default:`#6c5671`},deadTongue:{type:`color`,label:`deadTongue`,default:`#d9c8bf`},tongue:{type:`color`,label:`tongue`,default:`#f98284`},sweat:{type:`color`,label:`sweat`,default:`#accce4`},white:{type:`color`,label:`white`,default:`#ffffff`}},data:JSON.parse(`{"root":"node-0","nodes":[{"id":"node-0","kind":"group","options":{"name":"root"}},{"id":"node-1","parent":"node-0","kind":"group","options":{"name":"body","updateSort":true}},{"id":"node-2","parent":"node-1","kind":"hemisphere","options":{"name":"body.hemisphere","translate":{"y":2},"rotate":{"x":4.71238898038469},"color":"\\u0000sprite-color:body","stroke":false,"backface":"\\u0000sprite-color:cap","diameter":32}},{"id":"node-3","parent":"node-1","kind":"hemisphere","options":{"name":"cap.hemisphere","translate":{"y":2},"rotate":{"x":1.5707963267948966},"color":"\\u0000sprite-color:cap","stroke":false,"backface":"\\u0000sprite-color:capSpot","diameter":42}},{"id":"node-4","parent":"node-3","kind":"shape","options":{"name":"cap.spot.front","translate":{"x":-8,"y":8,"z":12},"color":"\\u0000sprite-color:capSpot","stroke":12,"path":[{"x":0,"y":0}]}},{"id":"node-5","parent":"node-3","kind":"shape","options":{"name":"cap.spot.top","translate":{"x":8,"y":-4,"z":13},"color":"\\u0000sprite-color:capSpot","stroke":18,"path":[{"x":0,"y":0}]}},{"id":"node-6","parent":"node-1","kind":"group","options":{"name":"face","translate":{"y":7,"z":8}}},{"id":"node-7","parent":"node-6","kind":"group","options":{"name":"eyes"}},{"id":"node-8","parent":"node-7","kind":"group","options":{"name":"eyes.normal"}},{"id":"node-9","parent":"node-8","kind":"group","options":{"translate":{"x":-6,"y":-2}}},{"id":"node-10","parent":"node-9","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-11","parent":"node-9","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-12","parent":"node-8","kind":"group","options":{"translate":{"x":6,"y":-2}}},{"id":"node-13","parent":"node-12","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-14","parent":"node-12","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-15","parent":"node-7","kind":"group","options":{"name":"eyes.sad"}},{"id":"node-16","parent":"node-15","kind":"group","options":{"translate":{"x":-6,"y":-1},"rotate":{"z":0.2}}},{"id":"node-17","parent":"node-16","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":4}},{"id":"node-18","parent":"node-16","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-19","parent":"node-15","kind":"group","options":{"translate":{"x":6,"y":-1},"rotate":{"z":-0.2}}},{"id":"node-20","parent":"node-19","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":4}},{"id":"node-21","parent":"node-19","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-22","parent":"node-7","kind":"group","options":{"name":"eyes.surprised"}},{"id":"node-23","parent":"node-22","kind":"group","options":{"translate":{"x":-6,"y":-2}}},{"id":"node-24","parent":"node-23","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":4,"height":5}},{"id":"node-25","parent":"node-23","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-26","parent":"node-22","kind":"group","options":{"translate":{"x":6,"y":-2}}},{"id":"node-27","parent":"node-26","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":4,"height":5}},{"id":"node-28","parent":"node-26","kind":"ellipse","options":{"translate":{"y":-1,"z":1},"color":"\\u0000sprite-color:white","stroke":0.5,"fill":true,"width":1.5,"height":2}},{"id":"node-29","parent":"node-7","kind":"group","options":{"name":"eyes.happy"}},{"id":"node-30","parent":"node-29","kind":"shape","options":{"translate":{"x":-6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":-1,"y":-1.5},{"x":1,"y":-1.5},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-31","parent":"node-29","kind":"shape","options":{"translate":{"x":6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":-1,"y":-1.5},{"x":1,"y":-1.5},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-32","parent":"node-7","kind":"group","options":{"name":"eyes.angry"}},{"id":"node-33","parent":"node-32","kind":"group","options":{"translate":{"x":-6,"y":-1},"rotate":{"z":-0.3}}},{"id":"node-34","parent":"node-33","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":4}},{"id":"node-35","parent":"node-33","kind":"shape","options":{"translate":{"y":-1},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-3,"y":-3},{"x":3,"y":-2}]}},{"id":"node-36","parent":"node-32","kind":"group","options":{"translate":{"x":6,"y":-1},"rotate":{"z":0.3}}},{"id":"node-37","parent":"node-36","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":4}},{"id":"node-38","parent":"node-36","kind":"shape","options":{"translate":{"y":-1},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-3,"y":-3},{"x":3,"y":-2}]}},{"id":"node-39","parent":"node-7","kind":"group","options":{"name":"eyes.dead"}},{"id":"node-40","parent":"node-39","kind":"group","options":{"translate":{"x":-6,"y":-2}}},{"id":"node-41","parent":"node-40","kind":"shape","options":{"color":"\\u0000sprite-color:dead","stroke":1.5,"path":[{"x":-2,"y":-3},{"x":2,"y":3}]}},{"id":"node-42","parent":"node-40","kind":"shape","options":{"color":"\\u0000sprite-color:dead","stroke":1.5,"path":[{"x":2,"y":-3},{"x":-2,"y":3}]}},{"id":"node-43","parent":"node-39","kind":"group","options":{"translate":{"x":6,"y":-2}}},{"id":"node-44","parent":"node-43","kind":"shape","options":{"color":"\\u0000sprite-color:dead","stroke":1.5,"path":[{"x":-2,"y":-3},{"x":2,"y":3}]}},{"id":"node-45","parent":"node-43","kind":"shape","options":{"color":"\\u0000sprite-color:dead","stroke":1.5,"path":[{"x":2,"y":-3},{"x":-2,"y":3}]}},{"id":"node-46","parent":"node-7","kind":"group","options":{"name":"eyes.confused"}},{"id":"node-47","parent":"node-46","kind":"group","options":{"translate":{"x":-6,"y":-2}}},{"id":"node-48","parent":"node-47","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-49","parent":"node-47","kind":"shape","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-3,"y":-4},{"x":3,"y":-2}]}},{"id":"node-50","parent":"node-46","kind":"group","options":{"translate":{"x":6,"y":-2}}},{"id":"node-51","parent":"node-50","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-52","parent":"node-7","kind":"group","options":{"name":"eyes.sleepy"}},{"id":"node-53","parent":"node-52","kind":"shape","options":{"translate":{"x":-6,"y":-1},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":1},{"bezier":[{"x":-1,"y":0},{"x":1,"y":0},{"x":2.5,"y":1}]}],"closed":false}},{"id":"node-54","parent":"node-52","kind":"shape","options":{"translate":{"x":6,"y":-1},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":1},{"bezier":[{"x":-1,"y":0},{"x":1,"y":0},{"x":2.5,"y":1}]}],"closed":false}},{"id":"node-55","parent":"node-7","kind":"group","options":{"name":"eyes.nervous"}},{"id":"node-56","parent":"node-55","kind":"group","options":{"translate":{"x":-6,"y":-2}}},{"id":"node-57","parent":"node-56","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-58","parent":"node-55","kind":"group","options":{"translate":{"x":6,"y":-2}}},{"id":"node-59","parent":"node-58","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-60","parent":"node-55","kind":"group","options":{"translate":{"x":10,"y":4}}},{"id":"node-61","parent":"node-60","kind":"shape","options":{"color":"\\u0000sprite-color:sweat","stroke":2,"path":[{"x":0,"y":-4}]}},{"id":"node-62","parent":"node-60","kind":"ellipse","options":{"translate":{"y":2},"color":"\\u0000sprite-color:sweat","stroke":0,"fill":true,"width":3,"height":4}},{"id":"node-63","parent":"node-7","kind":"group","options":{"name":"eyes.shy"}},{"id":"node-64","parent":"node-63","kind":"ellipse","options":{"translate":{"x":-6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":2.5,"height":2}},{"id":"node-65","parent":"node-63","kind":"ellipse","options":{"translate":{"x":6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":2.5,"height":2}},{"id":"node-66","parent":"node-7","kind":"group","options":{"name":"eyes.cute"}},{"id":"node-67","parent":"node-66","kind":"group","options":{"translate":{"x":-6,"y":-1}}},{"id":"node-68","parent":"node-67","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":5,"height":6}},{"id":"node-69","parent":"node-67","kind":"ellipse","options":{"translate":{"y":-1.5,"z":1},"color":"\\u0000sprite-color:white","stroke":0,"fill":true,"width":2.5,"height":3}},{"id":"node-70","parent":"node-67","kind":"ellipse","options":{"translate":{"x":-1.5,"y":1.5,"z":1},"color":"\\u0000sprite-color:white","stroke":0,"fill":true,"width":1,"height":1}},{"id":"node-71","parent":"node-66","kind":"group","options":{"translate":{"x":6,"y":-1}}},{"id":"node-72","parent":"node-71","kind":"ellipse","options":{"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":5,"height":6}},{"id":"node-73","parent":"node-71","kind":"ellipse","options":{"translate":{"y":-1.5,"z":1},"color":"\\u0000sprite-color:white","stroke":0,"fill":true,"width":2.5,"height":3}},{"id":"node-74","parent":"node-71","kind":"ellipse","options":{"translate":{"x":-1.5,"y":1.5,"z":1},"color":"\\u0000sprite-color:white","stroke":0,"fill":true,"width":1,"height":1}},{"id":"node-75","parent":"node-7","kind":"group","options":{"name":"eyes.wink"}},{"id":"node-76","parent":"node-75","kind":"group","options":{"name":"eyes.wink.left"}},{"id":"node-77","parent":"node-76","kind":"shape","options":{"translate":{"x":-6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":-1,"y":-1.5},{"x":1,"y":-1.5},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-78","parent":"node-76","kind":"ellipse","options":{"translate":{"x":6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-79","parent":"node-75","kind":"group","options":{"name":"eyes.wink.right"}},{"id":"node-80","parent":"node-79","kind":"shape","options":{"translate":{"x":6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":-1,"y":-1.5},{"x":1,"y":-1.5},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-81","parent":"node-79","kind":"ellipse","options":{"translate":{"x":-6,"y":-2},"color":"\\u0000sprite-color:eye","stroke":1.5,"fill":true,"width":3,"height":5}},{"id":"node-82","parent":"node-6","kind":"group","options":{"name":"mouth"}},{"id":"node-83","parent":"node-82","kind":"shape","options":{"name":"mouth.normal","translate":{"y":2},"color":"\\u0000sprite-color:mouth","stroke":1.5,"path":[{"x":-2.5,"y":0},{"x":2.5,"y":0}],"closed":false}},{"id":"node-84","parent":"node-82","kind":"shape","options":{"name":"mouth.happy","translate":{"y":2},"color":"\\u0000sprite-color:mouth","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":0,"y":4},{"x":2.5,"y":2},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-85","parent":"node-82","kind":"shape","options":{"name":"mouth.sad","translate":{"y":2},"color":"\\u0000sprite-color:mouth","stroke":1.5,"path":[{"x":-2.5,"y":2},{"bezier":[{"x":0,"y":0},{"x":2.5,"y":2},{"x":2.5,"y":2}]}],"closed":false}},{"id":"node-86","parent":"node-82","kind":"shape","options":{"name":"mouth.small","translate":{"y":2},"color":"\\u0000sprite-color:mouth","stroke":1,"path":[{"x":-1.5,"y":0},{"x":1.5,"y":0}],"closed":false}},{"id":"node-87","parent":"node-82","kind":"shape","options":{"name":"mouth.worried","translate":{"y":2},"color":"\\u0000sprite-color:mouth","stroke":1,"path":[{"x":-2,"y":1},{"bezier":[{"x":-0.5,"y":0.5},{"x":0.5,"y":0.5},{"x":2,"y":1}]}],"closed":false}},{"id":"node-88","parent":"node-82","kind":"ellipse","options":{"name":"mouth.pout","translate":{"y":3},"color":"\\u0000sprite-color:mouth","stroke":1.5,"fill":true,"width":2,"height":2.5}},{"id":"node-89","parent":"node-82","kind":"ellipse","options":{"name":"mouth.surprised","translate":{"y":3},"color":"\\u0000sprite-color:mouth","stroke":1.5,"fill":true,"width":3,"height":4}},{"id":"node-90","parent":"node-82","kind":"group","options":{"name":"mouth.dead","translate":{"y":5}}},{"id":"node-91","parent":"node-90","kind":"ellipse","options":{"color":"\\u0000sprite-color:dead","stroke":1.5,"fill":true,"width":3,"height":2}},{"id":"node-92","parent":"node-90","kind":"ellipse","options":{"translate":{"y":0.5},"color":"\\u0000sprite-color:deadTongue","stroke":0,"fill":true,"width":1.5,"height":1}},{"id":"node-93","parent":"node-82","kind":"group","options":{"name":"mouth.open","translate":{"y":2}}},{"id":"node-94","parent":"node-93","kind":"ellipse","options":{"color":"\\u0000sprite-color:mouth","stroke":1.5,"fill":true,"width":6,"height":4}},{"id":"node-95","parent":"node-93","kind":"ellipse","options":{"name":"mouth.tongue","translate":{"y":1},"color":"\\u0000sprite-color:tongue","stroke":0,"fill":true,"width":3,"height":1.5}},{"id":"node-96","parent":"node-6","kind":"group","options":{"name":"blush.off"}},{"id":"node-97","parent":"node-6","kind":"group","options":{"name":"blush.medium"}},{"id":"node-98","parent":"node-97","kind":"ellipse","options":{"translate":{"x":-10,"y":4},"color":"\\u0000sprite-color:blush","stroke":1,"fill":true,"width":5,"height":2.5}},{"id":"node-99","parent":"node-97","kind":"ellipse","options":{"translate":{"x":10,"y":4},"color":"\\u0000sprite-color:blush","stroke":1,"fill":true,"width":5,"height":2.5}}],"palette":{"body":"#fff7e4","cap":"#f98284","capSpot":"#ffe6c6","eye":"#28282e","mouth":"#28282e","blush":"#feaae4","dead":"#6c5671","deadTongue":"#d9c8bf","tongue":"#f98284","sweat":"#accce4","white":"#ffffff"},"variants":{"eyes":{"normal":"node-8","happy":"node-29","sad":"node-15","angry":"node-32","surprised":"node-22","dead":"node-39","confused":"node-46","sleepy":"node-52","nervous":"node-55","shy":"node-63","wink":"node-76","cute":"node-66","wink.left":"node-76","wink.right":"node-79"},"mouth":{"normal":"node-83","happy":"node-84","sad":"node-85","angry":"node-85","surprised":"node-89","dead":"node-90","small":"node-86","worried":"node-87","pout":"node-88","open":"node-93"},"blush":{"off":"node-96","small":"node-97","medium":"node-97","big":"node-97"}},"expressions":{"angry":{"variants":{"eyes":"angry","mouth":"angry","blush":"off"},"motion":{"target":"root","translate":{"x":1,"y":0},"durationMs":150,"repeat":"none"}},"confused":{"variants":{"eyes":"confused","mouth":"normal","blush":"off"},"motion":{"target":"root","translate":{"x":0,"y":0.5},"durationMs":150,"repeat":"none"}},"cute":{"variants":{"eyes":"cute","mouth":"happy","blush":"big"},"motion":{"target":"root","translate":{"x":0,"y":-2.5},"durationMs":150,"repeat":"none"}},"dead":{"variants":{"eyes":"dead","mouth":"dead","blush":"off"}},"happy":{"variants":{"eyes":"happy","mouth":"happy","blush":"medium"},"motion":{"target":"root","translate":{"x":0,"y":-2},"durationMs":150,"repeat":"none"}},"nervous":{"variants":{"eyes":"nervous","mouth":"worried","blush":"off"},"motion":{"target":"root","translate":{"x":-0.5,"y":-1},"durationMs":150,"repeat":"none"}},"normal":{"variants":{"eyes":"normal","mouth":"normal","blush":"off"},"motion":{"target":"root","translate":{"x":0,"y":1},"durationMs":150,"repeat":"none"}},"pleading":{"variants":{"eyes":"cute","mouth":"pout","blush":"medium"},"motion":{"target":"root","translate":{"x":0,"y":-1},"durationMs":150,"repeat":"none"}},"sad":{"variants":{"eyes":"sad","mouth":"sad","blush":"off"},"motion":{"target":"root","translate":{"x":0,"y":2},"durationMs":150,"repeat":"none"}},"shy":{"variants":{"eyes":"shy","mouth":"small","blush":"small"},"motion":{"target":"root","translate":{"x":0,"y":1.5},"durationMs":150,"repeat":"none"}},"sleepy":{"variants":{"eyes":"sleepy","mouth":"small","blush":"off"},"motion":{"target":"root","translate":{"x":0,"y":2},"durationMs":150,"repeat":"none"}},"surprised":{"variants":{"eyes":"surprised","mouth":"surprised","blush":"off"},"motion":{"target":"root","translate":{"x":0,"y":-3},"durationMs":150,"repeat":"none"}},"wink":{"variants":{"mouth":"happy","blush":"small"},"variantChoices":{"eyes":["wink.left","wink.right"]},"motion":{"target":"root","translate":{"x":0,"y":-1.5},"durationMs":150,"repeat":"none"}}},"activities":{"idle":{"motion":{"target":"root","translate":{"y":0.5},"durationMs":2000,"repeat":"yoyo"},"mouseInfluence":1},"listening":{"motion":{"target":"root","rotate":{"x":-0.2},"durationMs":300,"repeat":"yoyo"},"mouseInfluence":0.3},"processing":{"mouseInfluence":0.2},"speaking":{"motion":{"target":"root","translate":{"y":0.5},"durationMs":1500,"repeat":"yoyo"},"mouseInfluence":0,"mouthCycle":[{"durationMs":100,"mouth":"open"},{"durationMs":150,"mouth":"base"},{"durationMs":100,"mouth":"open"},{"durationMs":200,"mouth":"base"}]},"thinking":{"motion":{"target":"root","rotate":{"z":0.1},"durationMs":800,"repeat":"yoyo"},"mouseInfluence":0},"error":{"motion":{"target":"root","rotate":{"x":0.9},"durationMs":600,"repeat":"none"},"mouseInfluence":0.1,"geometry":{"eyes":"dead","mouth":"dead"}}},"defaultPresentation":{"activity":"idle","expression":"sleepy"}}`)},r={document:e.parse(n),render:t};export{r as default};
@@ -1 +0,0 @@
1
- import{a as e}from"./error-CJ3RHG07.js";function t(t){return new Proxy({},{get(n,r){if(typeof r!=`symbol`)throw new e(`\`${t}.${r}\` is not available in this environment; it needs a Node.js-compatible runtime`)}})}t(`child_process`),t(`crypto`);var n=t(`fs`);t(`os`);var r=t(`path`);t(`stream`),t(`util`);export{n as fs,r as path};
@@ -1,9 +0,0 @@
1
- import{_ as e,c as t,d as n,f as r,p as i,s as a}from"./preload-helper-mbhLTglw.js";import{t as o}from"./provider-env-CcCbsTJq.js";import{a as s,i as c,n as l,t as u}from"./diagnostics-CmW2yJSB.js";import{n as d}from"./models-CcNnosqL.js";import{t as f}from"./headers-FK4rgixo.js";import{c as p,p as m,r as h}from"./transform-messages-CrQEqmfx.js";import{n as g,t as _}from"./error-body-pkrba6pf.js";import{t as v}from"./openai-prompt-cache-DXo9f3w5.js";import{n as y,r as b,t as x}from"./openai-responses-shared-DzD8B6NI.js";import{n as S}from"./runtime-core-GKyHklNK.js";var C=new Set;function w(e){return C.add(e),()=>{C.delete(e)}}function ee(e){let t=e.filter(e=>e!==void 0);if(t.length===0)return{cleanup:()=>{}};if(t.length===1)return{signal:t[0],cleanup:()=>{}};let n=new AbortController,r=[],i=e=>{n.signal.aborted||n.abort(e.reason)};for(let e of t){if(e.aborted){i(e);break}let t=()=>i(e);e.addEventListener(`abort`,t,{once:!0}),r.push({signal:e,listener:t})}return{signal:n.signal,cleanup:()=>{for(let{signal:e,listener:t}of r)e.removeEventListener(`abort`,t)}}}var T={ftp:21,gopher:70,http:80,https:443,ws:80,wss:443};function E(e,t){let n=e.toLowerCase(),r=e.toUpperCase();return t?.[n]||t?.[r]||o(n)||o(r)||``}function D(e){if(e instanceof URL)return e;try{return new URL(e)}catch{return}}function O(e){return e.startsWith(`[`)&&e.endsWith(`]`)?e.slice(1,-1):e}function k(e){let t=e.trim().toLowerCase();if(!t)return;if(t.startsWith(`[`)){let e=t.indexOf(`]`);if(e!==-1){let n=t.slice(1,e),r=t.slice(e+1);if(r.startsWith(`:`)){let e=Number.parseInt(r.slice(1),10);return{host:n,port:Number.isNaN(e)?0:e}}return{host:n,port:0}}}if(t.includes(`:`)&&t.split(`:`).length>2)return{host:t,port:0};let n=t.lastIndexOf(`:`);if(n!==-1&&n===t.indexOf(`:`)){let e=t.slice(0,n),r=Number.parseInt(t.slice(n+1),10);if(!Number.isNaN(r))return{host:e,port:r}}return{host:t,port:0}}function A(e,t,n){let r=E(`no_proxy`,n).toLowerCase();if(!r)return!0;if(r===`*`)return!1;let i=O(e.toLowerCase());return r.split(/[,\s]/).every(e=>{let n=k(e);if(!n||n.port&&n.port!==t)return!0;let r=O(n.host);return r.startsWith(`*.`)?r=r.slice(2):(r.startsWith(`.`)||r.startsWith(`*`))&&(r=r.slice(1)),!r||!(i===r||i.endsWith(`.${r}`))})}function j(e,t){let n=D(e);if(!n?.protocol||!n.host)return``;let r=n.protocol.split(`:`,1)[0];if(!A(O(n.hostname||n.host.replace(/:\d*$/,``)),Number.parseInt(n.port,10)||T[r]||0,t))return``;let i=E(`${r}_proxy`,t)||E(`all_proxy`,t);return i&&!i.includes(`://`)&&(i=`${r}://${i}`),i}var M=`Unsupported proxy protocol. SOCKS and PAC proxy URLs are not supported; use an HTTP or HTTPS proxy URL.`;function te(e,t){let n=j(e,t);if(!n)return;let r;try{r=new URL(n)}catch(e){throw Error(`Invalid proxy URL ${JSON.stringify(n)}: ${e instanceof Error?e.message:String(e)}`)}if(r.protocol!==`http:`&&r.protocol!==`https:`)throw Error(`${M} Got ${r.protocol}`);return r}var ne=`https://chatgpt.com/backend-api`,re=`https://api.openai.com/auth`,ie=0,N=1e3,ae=6e4,oe=15e3,se=3,P=new Set([`openai`,`openai-codex`,`opencode`]),ce=1009,le=`websocket_connection_limit_reached`,ue=`previous_response_not_found`,de=new Set([`completed`,`incomplete`,`failed`,`cancelled`,`queued`,`in_progress`]);function fe(e){if(e.stopReason===`pending`)throw Error(`Codex stream ended without a stop reason`);if(e.stopReason===`error`||e.stopReason===`aborted`)throw Error(e.errorMessage||`An unknown error occurred`)}function pe(e){return/GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(e)}function me(e,t){return e===429&&pe(t)?!1:e===429||e===500||e===502||e===503||e===504||/rate.?limit|overloaded|service.?unavailable|upstream.?connect|connection.?refused/i.test(t)}function he(e){let t=e.get(`retry-after-ms`);if(t!==null){let e=Number(t);if(Number.isFinite(e))return Math.max(0,e)}let n=e.get(`retry-after`);if(!n)return;let r=Number(n);if(Number.isFinite(r))return Math.max(0,r*1e3);let i=Date.parse(n);if(!Number.isNaN(i))return Math.max(0,i-Date.now())}var ge=class extends Error{};function _e(e,t){let n=t?.maxRetryDelayMs??ae;if(n>0&&e>n)throw new ge(`Server requested ${Math.ceil(e/1e3)}s retry delay (max: ${Math.ceil(n/1e3)}s)`);return e}function ve(e,t){return new Promise((n,r)=>{if(t?.aborted){r(Error(`Request was aborted`));return}let i=setTimeout(n,e);t?.addEventListener(`abort`,()=>{clearTimeout(i),r(Error(`Request was aborted`))})})}function F(e){if(e!==void 0){if(!Number.isFinite(e)||e<0)throw Error(`Invalid timeoutMs: ${String(e)}`);return Math.floor(e)}}function ye(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:zlib`)??null}function be(e){let t=ye();if(!t||typeof t.zstdCompressSync!=`function`)return null;try{let n=t.zstdCompressSync(e,{params:{[t.constants.ZSTD_c_compressionLevel]:se}});return new Uint8Array(n.buffer,n.byteOffset,n.byteLength)}catch{return null}}var I=(e,t,n)=>{let i=new s,o=r(t,e.compat?.supportsMidConvoSystemMessages);return(async()=>{let t={role:`assistant`,content:[],api:`openai-codex-responses`,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let s=rt(r),c=p(a(o.messages),e.compat?.supportsOpenAIGrammarTools??!1),d=n?.cacheRetention===`none`?void 0:n?.sessionId,m=v(d),h=Se(e,o,n,m,c),g=await n?.onPayload?.(h,e);g!==void 0&&(h=g);let _=m||S(),y=at(e.headers,n?.headers,s,r,m),b=ot(e.headers,n?.headers,s,r,_),x=JSON.stringify(h),C=F(n?.timeoutMs),w=F(n?.websocketConnectTimeoutMs),T=n?.transport||`auto`,E=!1,D=T!==`sse`&&Y(d);if(D&&Le(d),T!==`sse`&&!D){let r=!1,a=!1,o=!1;for(;;){r=!1;try{if(await tt(we(e.baseUrl),h,b,t,i,e,()=>{r=!0,E||(E=!0,i.push({type:`start`,partial:t}))},C,w,d,s,c,n),n?.signal?.aborted)throw Error(`Request was aborted`);fe(t),i.push({type:`done`,reason:t.stopReason,message:t}),i.end();return}catch(e){let i=n?.signal?.aborted,s=!r&&De(e),c=Oe(e);if(!i&&c&&!o){o=!0;continue}if(!i&&s&&!a){a=!0;continue}if(i||Ee(e)&&!s||(u(t,l(`provider_transport_failure`,e,{configuredTransport:T,...r?{}:{fallbackTransport:`sse`},eventsEmitted:r,phase:r?`after_message_stream_start`:`before_message_stream_start`,requestBytes:new TextEncoder().encode(x).byteLength})),Re(d,e),r))throw e;Le(d);break}}}let O=be(x);O&&y.set(`content-encoding`,`zstd`);let k=O??x,A,j,M=n?.maxRetries??ie;for(let t=0;t<=M;t++){if(n?.signal?.aborted)throw Error(`Request was aborted`);try{let r=C!==void 0&&C>0?AbortSignal.timeout(C):void 0,i=ee([n?.signal,r]);try{A=await(n?.fetch??globalThis.fetch)(z(e.baseUrl),{method:`POST`,headers:y,body:k,signal:i.signal})}catch(e){throw r?.aborted&&!n?.signal?.aborted?Error(`Codex SSE response headers timed out after ${C}ms`):e}finally{i.cleanup()}if(await n?.onResponse?.({status:A.status,headers:f(A.headers)},e),A.ok)break;let a=await A.text();if(t<M&&me(A.status,a)){let e=he(A.headers);await ve(e===void 0?N*2**t:_e(e,n),n?.signal);continue}let o=await nt(new Response(a,{status:A.status,statusText:A.statusText}));throw Error(o.friendlyMessage||o.message)}catch(e){if(e instanceof Error&&(e.name===`AbortError`||e.message===`Request was aborted`))throw Error(`Request was aborted`);if(j=e instanceof Error?e:Error(String(e)),t<M&&!(j instanceof ge)&&!j.message.includes(`usage limit`)){await ve(N*2**t,n?.signal);continue}throw j}}if(!A?.ok)throw j??Error(`Failed after retries`);if(!A.body)throw Error(`No response body`);if(E||(E=!0,i.push({type:`start`,partial:t})),await Te(A,t,i,e,c,n),n?.signal?.aborted)throw Error(`Request was aborted`);fe(t),i.push({type:`done`,reason:t.stopReason,message:t}),i.end()}catch(e){for(let e of t.content)delete e.partialJson,delete e.customInput;t.stopReason=n?.signal?.aborted?`aborted`:`error`,t.errorMessage=_(g(e)),i.push({type:`error`,reason:t.stopReason,error:t}),i.end()}})(),i},xe=(e,t,n)=>{let r=n?.apiKey;if(!r)throw Error(`No API key for provider: ${e.provider}`);let i={...h(e,t,n,r),toolChoice:n?.toolChoice},a=n?.reasoning?d(e,n.reasoning):void 0,o=a===`off`?void 0:a;return I(e,t,{...i,reasoningEffort:o})};function Se(n,r,o,s,c=p(a(r.messages),n.compat?.supportsOpenAIGrammarTools??!1)){let l=n.compat?.supportsStrictMode??!0,u=n.compat?.supportsOpenAIGrammarTools??!1,d=n.compat?.supportsAdditionalTools??!1,f=n.compat?.supportsToolSearch??!1,m=i(r.messages,d||f),h=x(n,r,P,{includeSystemPrompt:!1,grammarToolInputProperties:c,supportsMidConvoSystemMessages:n.compat?.supportsMidConvoSystemMessages??!1,supportsAdditionalTools:d,supportsToolSearch:f,toolOptions:{strict:null,supportsStrictMode:l,supportsOpenAIGrammarTools:u}}),g=t(r.messages),_=g?e(g):``,v={model:n.id,store:!1,stream:!0,instructions:_||`You are a helpful assistant.`,input:h,text:{verbosity:o?.textVerbosity||`low`},include:[`reasoning.encrypted_content`],prompt_cache_key:s,tool_choice:o?.toolChoice??`auto`,parallel_tool_calls:!0};if(o?.temperature!==void 0&&(v.temperature=o.temperature),o?.serviceTier!==void 0&&(v.service_tier=o.serviceTier),m.requestTools.length>0&&(v.tools=y(m.requestTools,{strict:null,supportsStrictMode:l,supportsOpenAIGrammarTools:u})),o?.reasoningEffort!==void 0){let e=o.reasoningEffort===`none`?n.thinkingLevelMap?.off===void 0?`none`:n.thinkingLevelMap.off:n.thinkingLevelMap?.[o.reasoningEffort]??o.reasoningEffort;e!==null&&(v.reasoning={effort:e,summary:o.reasoningSummary??`auto`})}else n.reasoning&&n.thinkingLevelMap?.off!==null&&(v.reasoning={effort:n.thinkingLevelMap?.off??`none`});return v}function Ce(e,t){switch(t){case`flex`:return .5;case`priority`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function L(e,t,n){let r=Ce(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}function R(e,t){return e==="default"&&(t===`flex`||t===`priority`)?t:e??t}function z(e){let t=(e&&e.trim().length>0?e:ne).replace(/\/+$/,``);return t.endsWith(`/codex/responses`)?t:t.endsWith(`/codex`)?`${t}/responses`:`${t}/codex/responses`}function we(e){let t=new URL(z(e));return t.protocol===`https:`&&(t.protocol=`wss:`),t.protocol===`http:`&&(t.protocol=`ws:`),t.toString()}async function Te(e,t,n,r,i,a){await b(U(je(e,a?.signal),t,r,a?.onProviderStreamEvent),t,n,r,{serviceTier:a?.serviceTier,grammarToolInputProperties:i,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,r)})}var B=class extends Error{code;payload;constructor(e,t){super(e),this.name=`CodexApiError`,this.code=t?.code,this.payload=t?.payload,this.cause=t?.cause}},V=class extends Error{payload;constructor(e,t){super(e),this.name=`CodexProtocolError`,this.payload=t?.payload,this.cause=t?.cause}},H=class extends Error{constructor(e){super(c(e)),this.name=`ProviderStreamEventCallbackError`,this.cause=e}};function Ee(e){return e instanceof B||e instanceof V||e instanceof H}function De(e){return e instanceof B&&e.code===le}function Oe(e){return e instanceof B&&e.code===ue}function ke(e){let t=e.error&&typeof e.error==`object`?e.error:void 0;return{code:typeof e.code==`string`?e.code:typeof t?.code==`string`?t.code:void 0,message:typeof e.message==`string`?e.message:typeof t?.message==`string`?t.message:void 0}}async function*U(e,t,n,r){for await(let i of e){try{await r?.(i,n)}catch(e){throw new H(e)}let e=typeof i.type==`string`?i.type:void 0;if(e){if(e===`error`){let{code:e,message:t}=ke(i);throw new B(`Codex error: ${t||e||JSON.stringify(i)}`,{code:e,payload:i})}if(e===`response.failed`){let e=i.response,t=e?.error?.code,n=e?.error?.message;throw new B(n||`Codex response failed`,{code:t,payload:i})}if(e===`response.done`||e===`response.completed`||e===`response.incomplete`){let e=i.response;typeof e?.end_turn==`boolean`&&(t.endTurn=e.end_turn);let n=e&&{...e,status:Ae(e.status)};yield{...i,type:`response.completed`,response:n};return}yield i}}}function Ae(e){if(typeof e==`string`)return de.has(e)?e:void 0}async function*je(e,t){if(!e.body)return;let n=e.body.getReader(),r=new TextDecoder,i=``,a=()=>{n.cancel().catch(()=>{})};t?.addEventListener(`abort`,a,{once:!0});try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);let{done:e,value:a}=await n.read();if(t?.aborted)throw Error(`Request was aborted`);i+=e?r.decode():r.decode(a,{stream:!0}),e&&i.trim()&&(i+=`
2
-
3
- `);let o=i.indexOf(`
4
-
5
- `);for(;o!==-1;){let e=i.slice(0,o);i=i.slice(o+2);let t=e.split(`
6
- `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());if(t.length>0){let e=t.join(`
7
- `).trim();if(e&&e!==`[DONE]`)try{yield JSON.parse(e)}catch(t){throw new V(`Invalid Codex SSE JSON: ${c(t)}`,{cause:t,payload:e})}}o=i.indexOf(`
8
-
9
- `)}if(e)break}}finally{t?.removeEventListener(`abort`,a);try{await n.cancel()}catch{}try{n.releaseLock()}catch{}}}var Me=`responses_websockets=2026-02-06`,Ne=3e5,Pe=33e5,W=new Map,G=new Map,K=new Set;function q(e){let t=G.get(e);return t||(t={requests:0,connectionsCreated:0,connectionsReused:0,cachedContextRequests:0,storeTrueRequests:0,fullContextRequests:0,deltaRequests:0,lastInputItems:0,websocketFailures:0,sseFallbacks:0},G.set(e,t)),t}function Fe(e){let t=G.get(e);return t?{...t}:void 0}function Ie(e){if(e){G.delete(e),K.delete(e);return}G.clear(),K.clear()}function J(e){let t=e=>{e.idleTimer&&clearTimeout(e.idleTimer),Q(e.socket,1e3,`debug_close`)};if(e){for(let n of W.get(e)?.values()??[])t(n);W.delete(e);return}for(let e of W.values())for(let n of e.values())t(n);W.clear()}w(J);function Y(e){return e?K.has(e):!1}function Le(e){if(!e)return;let t=q(e);t.sseFallbacks++,t.websocketFallbackActive=Y(e)}function Re(e,t){if(!e)return;K.add(e);let n=q(e);n.websocketFailures++,n.lastWebSocketError=c(t),n.websocketFallbackActive=!0}var X=null;async function ze(e){if(!e&&X)return X;if(typeof process<`u`&&process.versions?.bun){let t=class extends WebSocket{constructor(t,n){let r={};r=Array.isArray(n)||typeof n==`string`?{protocols:n}:{...n};let i=te(t.toString().replace(/^wss:/,`https:`).replace(/^ws:/,`http:`),e);super(t,{...r,...i?{proxy:i.toString()}:{}})}};return e||(X=t),t}let t=globalThis.WebSocket;return typeof t==`function`?t:null}var Be=class extends Error{code;reason;wasClean;constructor(e,t){super(e),this.name=`WebSocketCloseError`,this.code=t?.code,this.reason=t?.reason,this.wasClean=t?.wasClean}};function Ve(e){let t=e.readyState;return typeof t==`number`?t:void 0}function Z(e){let t=Ve(e);return t===void 0||t===1}function He(e){return Date.now()-e.createdAt>=Pe}function Q(e,t=1e3,n=`done`){try{e.close(t,n)}catch{}}function Ue(e,t,n){n.idleTimer&&clearTimeout(n.idleTimer),n.idleTimer=setTimeout(()=>{if(n.busy)return;Q(n.socket,1e3,`idle_timeout`);let r=W.get(e);r?.get(t)===n&&r.delete(t),r?.size===0&&W.delete(e)},Ne)}async function $(e,t,n,r=oe,i){let a=await ze(i);if(!a)throw Error(`WebSocket transport is not available in this runtime`);let o=f(t);return delete o[`OpenAI-Beta`],new Promise((t,i)=>{let s=!1,c,l;try{l=new a(e,{headers:o})}catch(e){i(e instanceof Error?e:Error(String(e)));return}let u=()=>{c&&=(clearTimeout(c),void 0),l.removeEventListener(`open`,f),l.removeEventListener(`error`,p),l.removeEventListener(`close`,m),n?.removeEventListener(`abort`,h)},d=(e,t)=>{s||(s=!0,u(),t&&Q(l,1e3,t),i(e))},f=()=>{s||(s=!0,u(),t(l))},p=e=>{d(Ge(e))},m=e=>{d(Ke(e))},h=()=>{d(Error(`Request was aborted`),`aborted`)};l.addEventListener(`open`,f),l.addEventListener(`error`,p),l.addEventListener(`close`,m),n?.addEventListener(`abort`,h),r>0&&(c=setTimeout(()=>{d(Error(`WebSocket connect timeout after ${r}ms`),`connect_timeout`)},r)),n?.aborted&&h()})}async function We(e,t,n,r,i,a,o){if(!n){let n=await $(e,t,i,a,o);return{socket:n,reused:!1,release:()=>Q(n)}}let s=W.get(n),c=s?.get(r);if(c){if(c.idleTimer&&=(clearTimeout(c.idleTimer),void 0),!c.busy&&He(c))Q(c.socket,1e3,`connection_age_limit`),s?.delete(r),s?.size===0&&W.delete(n);else if(!c.busy&&Z(c.socket))return c.busy=!0,{socket:c.socket,entry:c,reused:!0,release:({keep:e}={})=>{if(!e||!Z(c.socket)){Q(c.socket);let e=W.get(n);e?.get(r)===c&&e.delete(r),e?.size===0&&W.delete(n);return}c.busy=!1,Ue(n,r,c)}};if(c.busy){let n=await $(e,t,i,a,o);return{socket:n,reused:!1,release:()=>{Q(n)}}}Z(c.socket)||(Q(c.socket),s?.delete(r),s?.size===0&&W.delete(n))}let l=await $(e,t,i,a,o),u={socket:l,busy:!0,createdAt:Date.now()};return s=W.get(n),s||(s=new Map,W.set(n,s)),s.set(r,u),{socket:l,entry:u,reused:!1,release:({keep:e}={})=>{if(!e||!Z(u.socket)){Q(u.socket),u.idleTimer&&clearTimeout(u.idleTimer);let e=W.get(n);e?.get(r)===u&&e.delete(r),e?.size===0&&W.delete(n);return}u.busy=!1,Ue(n,r,u)}}}function Ge(e){if(e&&typeof e==`object`){let t=`message`in e?e.message:void 0;if(typeof t==`string`&&t.length>0)return Error(t);let n=`error`in e?e.error:void 0;if(n instanceof Error&&n.message.length>0)return n;if(n&&typeof n==`object`&&`message`in n){let e=n.message;if(typeof e==`string`&&e.length>0)return Error(e)}}return Error(`WebSocket error`)}function Ke(e){if(e&&typeof e==`object`){let t=`code`in e?e.code:void 0,n=`reason`in e?e.reason:void 0,r=`wasClean`in e?e.wasClean:void 0,i=typeof t==`number`?` ${t}`:``,a=typeof n==`string`&&n.length>0?` ${n}`:``;return!a&&t===ce&&(a=` message too big`),new Be(`WebSocket closed${i}${a}`.trim(),{code:typeof t==`number`?t:void 0,reason:typeof n==`string`&&n.length>0?n:void 0,wasClean:typeof r==`boolean`?r:void 0})}return Error(`WebSocket closed`)}async function qe(e){if(typeof e==`string`)return e;if(e instanceof ArrayBuffer)return new TextDecoder().decode(new Uint8Array(e));if(ArrayBuffer.isView(e)){let t=e;return new TextDecoder().decode(new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}if(e&&typeof e==`object`&&`arrayBuffer`in e){let t=await e.arrayBuffer();return new TextDecoder().decode(new Uint8Array(t))}return null}async function*Je(e,t,n){let r=[],i=null,a=!1,o=null,s=!1,l=()=>{if(!i)return;let e=i;i=null,e()},u=e=>{(async()=>{let t=null;try{if(!e||typeof e!=`object`||!(`data`in e)||(t=await qe(e.data),!t))return;let n=JSON.parse(t),i=typeof n.type==`string`?n.type:``;(i===`response.completed`||i===`response.done`||i===`response.incomplete`)&&(s=!0,a=!0),r.push(n),l()}catch(e){o=new V(`Invalid Codex WebSocket JSON: ${c(e)}`,{cause:e,payload:t}),a=!0,l()}})()},d=e=>{o=Ge(e),a=!0,l()},f=e=>{if(s){a=!0,l();return}o||=Ke(e),a=!0,l()},p=()=>{o=Error(`Request was aborted`),a=!0,l()};e.addEventListener(`message`,u),e.addEventListener(`error`,d),e.addEventListener(`close`,f),t?.addEventListener(`abort`,p);try{for(;;){if(t?.aborted)throw Error(`Request was aborted`);if(r.length>0){yield r.shift();continue}if(a)break;let s;await new Promise((t,r)=>{i=t,n!==void 0&&n>0&&(s=setTimeout(()=>{let t=Error(`WebSocket idle timeout after ${n}ms`);o=t,a=!0,i=null,Q(e,1e3,`idle_timeout`),r(t)},n))}).finally(()=>{s&&clearTimeout(s)})}if(o)throw o;if(!s)throw Error(`WebSocket stream closed before response.completed`)}finally{e.removeEventListener(`message`,u),e.removeEventListener(`error`,d),e.removeEventListener(`close`,f),t?.removeEventListener(`abort`,p)}}function Ye(e){let{input:t,previous_response_id:n,...r}=e;return r}function Xe(e,t){return JSON.stringify(e??[])===JSON.stringify(t??[])}function Ze(e,t){return JSON.stringify(Ye(e))===JSON.stringify(Ye(t))}function Qe(e,t){if(!Ze(e,t.lastRequestBody))return;let n=e.input??[],r=[...t.lastRequestBody.input??[],...t.lastResponseItems];if(!(n.length<r.length)&&Xe(n.slice(0,r.length),r))return n.slice(r.length)}function $e(e,t){let n=e.continuation;if(!n)return t;let r=Qe(t,n);return!r||!n.lastResponseId?(e.continuation=void 0,t):{...t,previous_response_id:n.lastResponseId,input:r}}async function*et(e,t){let n=!1;for await(let r of e)n||(n=!0,t()),yield r}async function tt(e,t,r,i,a,o,s,c,l,u,d,f,p){let{socket:m,entry:h,reused:g,release:_}=await We(e,r,u,d,p?.signal,l,p?.env),v=!0,y=p?.transport===`websocket-cached`||p?.transport===`auto`,S=t,C=y&&h?$e(h,S):S,w=u?q(u):void 0;w&&(w.requests++,g?w.connectionsReused++:w.connectionsCreated++,y&&w.cachedContextRequests++,C.store===!0&&w.storeTrueRequests++,w.lastInputItems=C.input?.length??0,C.previous_response_id?(w.deltaRequests++,w.lastDeltaInputItems=C.input?.length??0,w.lastPreviousResponseId=C.previous_response_id):(w.fullContextRequests++,w.lastDeltaInputItems=void 0,w.lastPreviousResponseId=void 0));try{if(m.send(JSON.stringify({type:`response.create`,...C})),await b(et(U(Je(m,p?.signal,c),i,o,p?.onProviderStreamEvent),s),i,a,o,{serviceTier:p?.serviceTier,grammarToolInputProperties:f,resolveServiceTier:R,applyServiceTierPricing:(e,t)=>L(e,t,o)}),p?.signal?.aborted)v=!1;else if(y&&h&&i.responseId){let e=x(o,n({messages:[i]}),P,{includeSystemPrompt:!1,grammarToolInputProperties:f}).filter(e=>e.type!==`function_call_output`&&e.type!==`custom_tool_call_output`);h.continuation={lastRequestBody:S,lastResponseId:i.responseId,lastResponseItems:e}}}catch(e){throw h&&(h.continuation=void 0),v=!1,e}finally{_({keep:v})}}async function nt(e){let t=await e.text(),n=t||e.statusText||`Request failed`,r;try{let i=JSON.parse(t)?.error;if(i){let t=i.code||i.type||``;if(/usage_limit_reached|usage_not_included|rate_limit_exceeded/i.test(t)||e.status===429){let e=i.plan_type?` (${i.plan_type.toLowerCase()} plan)`:``,t=i.resets_at?Math.max(0,Math.round((i.resets_at*1e3-Date.now())/6e4)):void 0;r=`You have hit your ChatGPT usage limit${e}.${t===void 0?``:` Try again in ~${t} min.`}`.trim()}n=i.message||r||n}}catch{}return{message:n,friendlyMessage:r}}function rt(e){try{let t=e.split(`.`);if(t.length!==3)throw Error(`Invalid token`);let n=JSON.parse(atob(t[1]))?.[re]?.chatgpt_account_id;if(!n)throw Error(`No account ID in token`);return n}catch{throw Error(`Failed to extract accountId from token`)}}function it(e,t,n,r){let i=new Headers(e);for(let[e,n]of Object.entries(t||{}))n===null?i.delete(e):i.set(e,n);return i.set(`Authorization`,`Bearer ${r}`),i.set(`chatgpt-account-id`,n),i.set(`originator`,`pi`),i.set(`User-Agent`,m()),i}function at(e,t,n,r,i){let a=it(e,t,n,r);return a.set(`OpenAI-Beta`,`responses=experimental`),a.set(`accept`,`text/event-stream`),a.set(`content-type`,`application/json`),i&&(a.set(`session-id`,i),a.set(`x-client-request-id`,i)),a}function ot(e,t,n,r,i){let a=it(e,t,n,r);return a.delete(`accept`),a.delete(`content-type`),a.delete(`OpenAI-Beta`),a.delete(`openai-beta`),a.set(`OpenAI-Beta`,Me),a.set(`x-client-request-id`,i),a.set(`session-id`,i),a}export{J as closeOpenAICodexWebSocketSessions,Fe as getOpenAICodexWebSocketDebugStats,Ie as resetOpenAICodexWebSocketDebugStats,I as stream,xe as streamSimple,w as t};
@@ -1,5 +0,0 @@
1
- import{_ as e,f as t,p as n,s as r,v as i}from"./preload-helper-mbhLTglw.js";import{t as a}from"./provider-env-CcCbsTJq.js";import{a as o}from"./diagnostics-CmW2yJSB.js";import{n as s,t as c}from"./models-CcNnosqL.js";import{t as l}from"./headers-FK4rgixo.js";import{n as u}from"./json-parse-nqKewMRF.js";import{a as d,c as f,d as p,f as m,l as h,o as g,p as _,r as v,s as y,t as b,u as x}from"./transform-messages-CrQEqmfx.js";import{t as S}from"./provider-retry-CSlu6hjs.js";import{t as C}from"./sanitize-unicode-DmIE6hZJ.js";import{n as w,t as T}from"./github-copilot-headers-DRgtIyTm.js";import{n as E}from"./openai-Cpe0uoXQ.js";import{n as D,t as O}from"./error-body-pkrba6pf.js";import{t as k}from"./openai-prompt-cache-DXo9f3w5.js";import{t as A}from"./hash-yQufAZII.js";function j(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function M(e,t,n){if(t)return t;if(j(n,`authorization`)||j(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function N(e){for(let t of e)if(t.role===`toolResult`||t.role===`assistant`&&t.content.some(e=>e.type===`toolCall`))return!0;return!1}function P(e){return e.type===`text`}function F(e){return e.type===`thinking`}function I(e){return e.type===`toolCall`}function L(e){return e.type===`image`}function ee(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function R(e){return(e.id===void 0||e.id===null||typeof e.id==`string`)&&(e.format===void 0||typeof e.format==`string`)&&(e.index===void 0||typeof e.index==`number`)}function z(e){if(!ee(e)||!R(e))return!1;switch(e.type){case`reasoning.summary`:return typeof e.summary==`string`;case`reasoning.encrypted`:return typeof e.data==`string`;case`reasoning.text`:return typeof e.text==`string`&&(e.signature===void 0||e.signature===null||typeof e.signature==`string`);default:return!1}}function te(e){if(e)try{let t=JSON.parse(e);return Array.isArray(t)&&t.length>0&&t.every(z)?t:void 0}catch{return}}function ne(e){if(e)try{let t=JSON.parse(e);return z(t)&&t.type===`reasoning.encrypted`&&typeof t.id==`string`&&t.id.length>0&&t.data.length>0?t:void 0}catch{return}}function B(e,t){e.id??=t.id,e.format||=t.format,e.index??=t.index}function re(e,t){let n=e[e.length-1];if(t.type===`reasoning.text`&&n?.type===`reasoning.text`){n.text+=t.text,n.signature||=t.signature,B(n,t);return}if(t.type===`reasoning.summary`&&n?.type===`reasoning.summary`){n.summary+=t.summary,B(n,t);return}e.push({...t})}var ie=[`reasoning`,`reasoning_content`,`reasoning_text`];function ae(e){return ie.includes(e)}function V(e,t){return e||(a(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}var H=(e,n,i)=>{let a=new o,s=t(n,$(e).supportsMidConvoSystemMessages);return(async()=>{let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()},n,o=e=>{n!==void 0&&(e.thinkingSignature=JSON.stringify(n))};try{let c=M(e.provider,i?.apiKey,i?.headers),d=$(e),p=f(r(s.messages),d.supportsOpenAIGrammarTools),m=V(i?.cacheRetention,i?.env),h=m===`none`?void 0:i?.sessionId,g=W(e,s,c,i?.headers,i?.fetch,h,d),_=G(e,s,i,d,m,p),v=await i?.onPayload?.(_,e);v!==void 0&&(_=v);let b={...i?.signal?{signal:i.signal}:{},...i?.timeoutMs===void 0?{}:{timeout:i.timeoutMs},maxRetries:0},{data:x,response:C}=await S(()=>g.chat.completions.create(_,b).withResponse(),{maxRetries:i?.maxRetries,maxRetryDelayMs:i?.maxRetryDelayMs,signal:i?.signal});await i?.onResponse?.({status:C.status,headers:l(C.headers)},e),a.push({type:`start`,partial:t});let w=null,T=null,E=!1,D=new Map,O=new Map,k=t.content,A=e=>k.indexOf(e),j=e=>{let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``},N=(e,t,n)=>{let r=e.customInput;if(!r)return;let i=y(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i},P=e=>{let n=A(e);if(n!==-1){if(e.type===`text`)a.push({type:`text_end`,contentIndex:n,content:e.text,partial:t});else if(e.type===`thinking`)o(e),a.push({type:`thinking_end`,contentIndex:n,content:e.thinking,partial:t});else if(e.type===`toolCall`){if(e.customInput){let r=N(e,j(e),!0);r!==void 0&&a.push({type:`toolcall_delta`,contentIndex:n,delta:r,partial:t})}else e.arguments=u(e.partialArgs);delete e.partialArgs,delete e.customInput,delete e.streamIndex,a.push({type:`toolcall_end`,contentIndex:n,toolCall:e,partial:t})}}},F=()=>(w||(w={type:`text`,text:``},k.push(w),a.push({type:`text_start`,contentIndex:A(w),partial:t})),w),I=e=>(T||(T={type:`thinking`,thinking:``,thinkingSignature:e},k.push(T),a.push({type:`thinking_start`,contentIndex:A(T),partial:t})),T),L=e=>{let n=typeof e.index==`number`?e.index:void 0,r=e.function?.name??e.custom?.name??``,i=n===void 0?void 0:D.get(n);if(!i&&e.id&&(i=O.get(e.id)),!i){let o=e.custom&&!e.function?p.get(r)??`input`:void 0,s=o!==void 0;i={type:`toolCall`,id:e.id||``,name:r,arguments:s?{[o]:``}:{},partialArgs:s?void 0:``,customInput:s?{property:o,jsonBuffer:{input:``,started:!1,closed:!1}}:void 0,streamIndex:n},n!==void 0&&D.set(n,i),e.id&&O.set(e.id,i),k.push(i),a.push({type:`toolcall_start`,contentIndex:A(i),partial:t})}if(n!==void 0&&i.streamIndex===void 0&&(i.streamIndex=n,D.set(n,i)),e.id&&O.set(e.id,i),!i.name&&r&&(i.name=r),e.custom&&!e.function&&!i.customInput){let e=p.get(i.name)??`input`;i.arguments={[e]:``},i.customInput={property:e,jsonBuffer:{input:``,started:!1,closed:!1}},delete i.partialArgs}return i};for await(let r of x){if(await i?.onProviderStreamEvent?.(r,e),!r||typeof r!=`object`)continue;t.responseId||=r.id,typeof r.model==`string`&&r.model.length>0&&r.model!==e.id&&(t.responseModel||=r.model),r.usage&&(t.usage=Q(r.usage,e));let o=Array.isArray(r.choices)?r.choices[0]:void 0;if(o){if(!r.usage&&o.usage&&(t.usage=Q(o.usage,e)),o.finish_reason){t.rawStopReason=o.finish_reason;let e=me(o.finish_reason);t.stopReason=e.stopReason,e.errorMessage&&(t.errorMessage=e.errorMessage),E=!0}if(o.delta){if(o.delta.content!==null&&o.delta.content!==void 0&&o.delta.content.length>0){let e=F();e.text+=o.delta.content,a.push({type:`text_delta`,contentIndex:A(e),delta:o.delta.content,partial:t})}let r=[`reasoning_content`,`reasoning`,`reasoning_text`],i=o.delta,s=null;for(let e of r){let t=i[e];if(typeof t==`string`&&t.length>0){s=e;break}}if(s){let n=i[s];if(typeof n==`string`&&n.length>0){let r=I(e.provider===`opencode-go`&&s===`reasoning`?`reasoning_content`:s);r.thinking+=n,a.push({type:`thinking_delta`,contentIndex:A(r),delta:n,partial:t})}}if(o?.delta?.tool_calls)for(let e of o.delta.tool_calls){let n=L(e);!n.id&&e.id&&(n.id=e.id,O.set(e.id,n));let r=e.function?.name??e.custom?.name;!n.name&&r&&(n.name=r);let i=``;e.function?.arguments?(i=e.function.arguments,n.partialArgs=(n.partialArgs??``)+e.function.arguments,n.arguments=u(n.partialArgs)):e.custom?.input&&(i=N(n,j(n)+e.custom.input,!1)??``),a.push({type:`toolcall_delta`,contentIndex:A(n),delta:i,partial:t})}let c=o.delta.reasoning_details;if(Array.isArray(c))for(let e of c)z(e)&&(I(``),n??=[],re(n,e))}}}for(let e of k)P(e);if(i?.signal?.aborted||t.stopReason===`aborted`)throw Error(`Request was aborted`);if(!E&&!d.supportsFinishReason&&(t.stopReason=t.content.some(e=>e.type===`toolCall`)?`toolUse`:`stop`),t.stopReason===`error`)throw Error(t.errorMessage||`Provider returned an error stop reason`);if(d.supportsFinishReason&&!E||t.stopReason===`pending`)throw Error(`Stream ended without finish_reason`);a.push({type:`done`,reason:t.stopReason,message:t}),a.end()}catch(e){for(let e of t.content)e.type===`thinking`&&o(e),delete e.index,delete e.partialArgs,delete e.customInput,delete e.streamIndex;t.stopReason=i?.signal?.aborted?`aborted`:`error`,t.errorMessage=O(D(e));let n=e?.error?.metadata?.raw;n&&!t.errorMessage.includes(String(n))&&(t.errorMessage+=`\n${n}`),a.push({type:`error`,reason:t.stopReason,error:t}),a.end()}})(),a},U=(e,t,n)=>{M(e.provider,n?.apiKey,n?.headers);let r={...v(e,t,n,n?.apiKey),toolChoice:n?.toolChoice},i=n?.reasoning?s(e,n.reasoning):void 0,a=i===`off`?void 0:i;return H(e,t,{...r,reasoningEffort:a,thinkingBudgets:n?.thinkingBudgets})};function W(e,t,n,r,i,a,o=$(e)){let s={"User-Agent":_(),...e.headers};if(e.provider===`github-copilot`){let e=w(t.messages),n=T({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&o.sendSessionAffinityHeaders&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a,s[`x-session-affinity`]=a)),r&&Object.assign(s,r),new E({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function G(e,t,i,a=$(e),o=V(i?.cacheRetention,i?.env),s=f(r(t.messages),a.supportsOpenAIGrammarTools)){let c=n(t.messages,a.supportsMidConvoSystemMessages===!0&&a.supportsMidConvoToolAdditions===!0),l=X(e,t,a,{grammarToolInputProperties:s}),u=se(a,o),d={model:e.id,messages:l,stream:!0,prompt_cache_key:e.baseUrl.includes(`api.openai.com`)&&o!==`none`||o===`long`&&a.supportsLongCacheRetention?k(i?.sessionId):void 0,prompt_cache_retention:o===`long`&&a.supportsLongCacheRetention?`24h`:void 0};a.supportsUsageInStreaming!==!1&&(d.stream_options={include_usage:!0}),a.supportsStore&&(d.store=!1),i?.maxTokens&&(a.maxTokensField===`max_tokens`?d.max_tokens=i.maxTokens:d.max_completion_tokens=i.maxTokens),i?.temperature!==void 0&&(d.temperature=i.temperature),c.requestTools.length>0?(d.tools=Z(c.requestTools,a),a.zaiToolStream&&(d.tool_stream=!0)):N(t.messages)&&(d.tools=[]),u&&ce(l,d.tools,u),i?.toolChoice&&(d.tool_choice=i.toolChoice),a.vllmPriority!==void 0&&(d.priority=a.vllmPriority);let p=K(a),m=q(e,i,d);if(a.thinkingFormat===`zai`&&e.reasoning){let t=d;if(t.thinking=i?.reasoningEffort?{type:`enabled`,clear_thinking:!1}:{type:`disabled`},i?.reasoningEffort&&a.supportsReasoningEffort){let n=e.thinkingLevelMap?.[i.reasoningEffort],r=n===void 0?i.reasoningEffort:n;typeof r==`string`&&(t.reasoning_effort=r)}}else if(a.thinkingFormat===`qwen`&&e.reasoning){if(d.enable_thinking=!!i?.reasoningEffort,i?.reasoningEffort&&a.supportsReasoningEffort){let t=e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort;typeof t==`string`&&(d.reasoning_effort=t)}}else if(a.thinkingFormat===`qwen-chat-template`&&e.reasoning)d.chat_template_kwargs={enable_thinking:!!i?.reasoningEffort,preserve_thinking:!0};else if(a.thinkingFormat===`chat-template`&&e.reasoning){let t=J(e,i,a.chatTemplateKwargs,m);t&&(d.chat_template_kwargs=t)}else if(a.thinkingFormat===`baseten`&&e.reasoning){let t=d,n=J(e,i,a.chatTemplateArgs,m);if(n&&(t.chat_template_args=n),a.supportsReasoningEffort){let n=i?.reasoningEffort,r=n?e.thinkingLevelMap?.[n]:e.thinkingLevelMap?.off,a=r===void 0?n:r;typeof a==`string`&&(t.reasoning_effort=a)}}else if(a.thinkingFormat===`deepseek`&&e.reasoning)i?.reasoningEffort?d.thinking={type:`enabled`}:e.thinkingLevelMap?.off!==null&&(d.thinking={type:`disabled`}),i?.reasoningEffort&&a.supportsReasoningEffort&&(d.reasoning_effort=e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort);else if(a.thinkingFormat===`openrouter`&&e.reasoning){let t=d;i?.reasoningEffort?t.reasoning={effort:e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort}:e.thinkingLevelMap?.off!==null&&(t.reasoning={effort:e.thinkingLevelMap?.off??`none`})}else if(a.thinkingFormat===`ant-ling`&&e.reasoning&&i?.reasoningEffort){let t=e.thinkingLevelMap?.[i.reasoningEffort];typeof t==`string`&&(d.reasoning={effort:t})}else if(a.thinkingFormat===`together`&&e.reasoning){let t=d;t.reasoning={enabled:!!i?.reasoningEffort},i?.reasoningEffort&&a.supportsReasoningEffort&&(t.reasoning_effort=e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort)}else if(a.thinkingFormat===`string-thinking`&&e.reasoning){let t=d;i?.reasoningEffort?t.thinking=e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort:e.thinkingLevelMap?.off!==null&&(t.thinking=e.thinkingLevelMap?.off??`none`)}else if(i?.reasoningEffort&&e.reasoning&&a.supportsReasoningEffort)d.reasoning_effort=e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort;else if(!i?.reasoningEffort&&e.reasoning&&a.supportsReasoningEffort){let t=e.thinkingLevelMap?.off;typeof t==`string`&&(d.reasoning_effort=t)}if(p&&m!==void 0&&Object.assign(d,{[p]:m}),e.compat?.openRouterRouting&&(d.provider=e.compat.openRouterRouting),e.compat?.vercelGatewayRouting){let t=e.compat.vercelGatewayRouting;if(t.only||t.order){let e={};t.only&&(e.only=t.only),t.order&&(e.order=t.order),d.providerOptions={gateway:e}}}return Object.assign(d,e.samplingParams,i?.samplingParams),d}function K(e){if(e.thinkingTokenBudgetField)return e.thinkingTokenBudgetField;if(e.supportsThinkingTokenBudget)return`thinking_token_budget`}function q(e,t,n){if(!t?.reasoningEffort||!e.reasoning)return;let r=n.max_tokens??n.max_completion_tokens??e.maxTokens,i=d(g(t.reasoningEffort,t.thinkingBudgets),r);return i>0?i:void 0}function J(e,t,n,r){let i={};for(let[a,o]of Object.entries(n)){let n=oe(e,t,o,r);n!==void 0&&(i[a]=n)}return Object.keys(i).length>0?i:void 0}function oe(e,t,n,r){if(typeof n!=`object`||!n)return n;let i=t?.reasoningEffort;if(!i&&n.omitWhenOff)return;if(n.$var===`thinking.enabled`)return!!i;if(n.$var===`thinking.budget`)return r;let a=i?e.thinkingLevelMap?.[i]:e.thinkingLevelMap?.off;return a===void 0?i:typeof a==`string`?a:void 0}function se(e,t){if(e.cacheControlFormat!==`anthropic`||t===`none`)return;let n=t===`long`&&e.supportsLongCacheRetention?`1h`:void 0;return{type:`ephemeral`,...n?{ttl:n}:{}}}function ce(e,t,n){le(e,n),de(t,n),ue(e,n)}function le(e,t){for(let n of e)if(n.role===`system`||n.role===`developer`){fe(n,t);return}}function ue(e,t){for(let n=e.length-1;n>=0;n--){let r=e[n];if((r.role===`user`||r.role===`assistant`||r.role===`tool`)&&pe(r,t))return}}function de(e,t){if(!e||e.length===0)return;let n=e[e.length-1];n.cache_control=t}function fe(e,t){return Y(e,t)}function pe(e,t){return e.role===`user`||e.role===`assistant`||e.role===`tool`?Y(e,t):!1}function Y(e,t){let n=e.content;if(typeof n==`string`)return n.length!==0&&(e.content=[{type:`text`,text:n,cache_control:t}],!0);if(!Array.isArray(n))return!1;for(let e=n.length-1;e>=0;e--){let r=n[e];if(r?.type===`text`){let e=r;return e.cache_control=t,!0}}return!1}function X(r,a,o,s){let c=t(a,o.supportsMidConvoSystemMessages),l=[],u=e=>{if(e.includes(`|`)){let t=e.indexOf(`|`),n=e.slice(0,t).replace(/[^a-zA-Z0-9_-]/g,`_`),r=e.slice(t+1).replace(/[^a-zA-Z0-9_-]/g,`_`),i=r.length>0?`${n}_${r}`:n;if(i.length<=40)return i;let a=A(e).slice(0,8);return`${n.slice(0,Math.max(1,40-a.length-1))}_${a}`}return r.provider===`openai`&&e.length>40?e.slice(0,40):e},d=b(c.messages,r,e=>u(e)),f=n(c.messages,o.supportsMidConvoSystemMessages===!0&&o.supportsMidConvoToolAdditions===!0),p=r.reasoning&&o.supportsDeveloperRole?`developer`:`system`,m=null;for(let t=0;t<d.length;t++){let n=d[t];if(o.requiresAssistantAfterToolResult&&m===`toolResult`&&n.role===`user`&&l.push({role:`assistant`,content:`I have processed the tool results.`}),n.role===`system`){let r=t>0&&f.anchorsAdditions?n.toolsAdded??[]:[];if(r.length>0){let e={role:`system`,tools:Z(r,o)};l.push(e)}let a=t===0?e(n):i(n);a.length>0&&l.push({role:p,content:C(a)})}else if(n.role===`user`){if(typeof n.content==`string`)l.push({role:`user`,content:C(n.content)});else{let e=n.content.filter(e=>e.type!==`text`||e.text.length>0).map(e=>e.type===`text`?{type:`text`,text:C(e.text)}:{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}});if(e.length===0)continue;l.push({role:`user`,content:e})}}else if(n.role===`assistant`){let e={role:`assistant`,content:o.requiresAssistantAfterToolResult?``:null},t=n.content.filter(P).filter(e=>e.text.trim().length>0).map(e=>({type:`text`,text:C(e.text)})),i=t.map(e=>e.text).join(``),a=n.content.filter(F),c=n.content.filter(I),u=a.map(e=>te(e.thinkingSignature)).find(e=>e!==void 0),d=c.map(e=>ne(e.thoughtSignature)).filter(e=>e!==void 0),f=u??(d.length>0?d:void 0),p=a.filter(e=>e.thinking.trim().length>0);if(p.length>0){if(o.requiresThinkingAsText)e.content=[{type:`text`,text:p.map(e=>C(e.thinking)).join(`
2
-
3
- `)},...t];else if(i.length>0&&(e.content=i),!f){let t=p[0].thinkingSignature;r.provider===`opencode-go`&&t===`reasoning`&&(t=`reasoning_content`),t&&ae(t)&&(e[t]=p.map(e=>e.thinking).join(`
4
- `))}}else i.length>0&&(e.content=i);c.length>0&&(e.tool_calls=c.map(e=>{let t=s?.grammarToolInputProperties?.get(e.name);return t===void 0?{id:e.id,type:`function`,function:{name:e.name,arguments:JSON.stringify(e.arguments)}}:{id:e.id,type:`custom`,custom:{name:e.name,input:C(h(e.name,e.arguments,t))}}})),f&&(e.reasoning_details=f),o.requiresReasoningContentOnAssistantMessages&&r.reasoning&&e.reasoning_content===void 0&&(e.reasoning_content=``);let m=e.content;if(!(m!=null&&m.length>0)&&!e.tool_calls)continue;l.push(e)}else if(n.role===`toolResult`){let e=[],n=t;for(;n<d.length&&d[n].role===`toolResult`;n++){let t=d[n],i=t.content.filter(P).map(e=>e.text).join(`
5
- `),a=t.content.some(e=>e.type===`image`),s=i.length>0?i:a?`(see attached image)`:`(no tool output)`,c={role:`tool`,content:C(s),tool_call_id:t.toolCallId};if(o.requiresToolResultName&&t.toolName&&(c.name=t.toolName),l.push(c),a&&r.input.includes(`image`))for(let n of t.content)L(n)&&e.push({type:`image_url`,image_url:{url:`data:${n.mimeType};base64,${n.data}`}})}t=n-1,e.length>0?(o.requiresAssistantAfterToolResult&&l.push({role:`assistant`,content:`I have processed the tool results.`}),l.push({role:`user`,content:[{type:`text`,text:`Attached image(s) from tool result:`},...e]}),m=`user`):m=`toolResult`;continue}m=n.role}return l}function Z(e,t){return e.map(e=>{let n=p(e,t.supportsOpenAIGrammarTools);if(n)return{type:`custom`,custom:{name:e.name,description:e.description,format:{type:`grammar`,grammar:{syntax:n.format,definition:n.definition}}}};let r=m(e,t.supportsStrictMode!==!1);return{type:`function`,function:{name:e.name,description:e.description,parameters:x(e,r),...t.supportsStrictMode!==!1&&{strict:r??!1}}}})}function Q(e,t){let n=e.prompt_tokens||0,r=e.prompt_tokens_details?.cached_tokens??e.prompt_cache_hit_tokens??e.cached_tokens??0,i=e.prompt_tokens_details?.cache_write_tokens||0,a=Math.max(0,n-r-i),o=e.completion_tokens||0,s={input:a,output:o,cacheRead:r,cacheWrite:i,reasoning:e.completion_tokens_details?.reasoning_tokens||0,totalTokens:a+o+r+i,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};return c(t,s),s}function me(e){if(e===null)return{stopReason:`stop`};switch(e){case`stop`:case`end`:return{stopReason:`stop`};case`length`:return{stopReason:`length`};case`function_call`:case`tool_calls`:return{stopReason:`toolUse`};case`content_filter`:return{stopReason:`error`,errorMessage:`Provider finish_reason: content_filter`};case`network_error`:return{stopReason:`error`,errorMessage:`Provider finish_reason: network_error`};default:return{stopReason:`error`,errorMessage:`Provider finish_reason: ${e}`}}}function he(e){let t=e.provider,n=e.baseUrl,r=t===`zai`||t===`zai-coding-cn`||n.includes(`api.z.ai`)||n.includes(`open.bigmodel.cn`),i=t===`together`||n.includes(`api.together.ai`)||n.includes(`api.together.xyz`),a=t===`moonshotai`||t===`moonshotai-cn`||n.includes(`api.moonshot.`),o=t===`openrouter`||n.includes(`openrouter.ai`),s=t===`cloudflare-workers-ai`||n.includes(`api.cloudflare.com`),c=t===`cloudflare-ai-gateway`||n.includes(`gateway.ai.cloudflare.com`),l=t===`nvidia`||n.includes(`integrate.api.nvidia.com`),u=t===`ant-ling`||n.includes(`api.ant-ling.com`),d=t===`cerebras`||n.includes(`cerebras.ai`),f=t===`deepseek`||n.toLowerCase().includes(`deepseek.com`),p=l||d||t===`xai`||n.includes(`api.x.ai`)||i||n.includes(`chutes.ai`)||f||r||a||t===`opencode`||n.includes(`opencode.ai`)||s||c||u,m=n.includes(`chutes.ai`)||f||a||c||i||l||u||r,h=t===`xai`||n.includes(`api.x.ai`),g=o&&(e.id.startsWith(`anthropic/`)||e.id.startsWith(`openai/`)),_=t===`openrouter`&&e.id.startsWith(`anthropic/`)?`anthropic`:void 0;return{supportsStore:!p,supportsDeveloperRole:g||!p&&!o,supportsReasoningEffort:!h&&!r&&!a&&!i&&!c&&!l&&!u,supportsUsageInStreaming:!0,supportsFinishReason:!0,maxTokensField:m?`max_tokens`:`max_completion_tokens`,requiresToolResultName:!1,requiresAssistantAfterToolResult:!1,requiresThinkingAsText:!1,requiresReasoningContentOnAssistantMessages:f,thinkingFormat:f?`deepseek`:r?`zai`:i?`together`:u?`ant-ling`:o?`openrouter`:`openai`,openRouterRouting:{},vercelGatewayRouting:{},chatTemplateKwargs:{},chatTemplateArgs:{},zaiToolStream:!1,supportsThinkingTokenBudget:!1,thinkingTokenBudgetField:void 0,supportsStrictMode:!1,supportsOpenAIGrammarTools:!1,supportsMidConvoSystemMessages:!1,supportsMidConvoToolAdditions:!1,cacheControlFormat:_,sendSessionAffinityHeaders:o,sessionAffinityFormat:o?`openrouter`:`openai`,supportsLongCacheRetention:!(i||s||c||l||u)}}function $(e){let t=he(e);return e.compat?{supportsStore:e.compat.supportsStore??t.supportsStore,supportsDeveloperRole:e.compat.supportsDeveloperRole??t.supportsDeveloperRole,supportsReasoningEffort:e.compat.supportsReasoningEffort??t.supportsReasoningEffort,supportsUsageInStreaming:e.compat.supportsUsageInStreaming??t.supportsUsageInStreaming,supportsFinishReason:e.compat.supportsFinishReason??t.supportsFinishReason,maxTokensField:e.compat.maxTokensField??t.maxTokensField,requiresToolResultName:e.compat.requiresToolResultName??t.requiresToolResultName,requiresAssistantAfterToolResult:e.compat.requiresAssistantAfterToolResult??t.requiresAssistantAfterToolResult,requiresThinkingAsText:e.compat.requiresThinkingAsText??t.requiresThinkingAsText,requiresReasoningContentOnAssistantMessages:e.compat.requiresReasoningContentOnAssistantMessages??t.requiresReasoningContentOnAssistantMessages,thinkingFormat:e.compat.thinkingFormat??t.thinkingFormat,openRouterRouting:e.compat.openRouterRouting??{},vercelGatewayRouting:e.compat.vercelGatewayRouting??t.vercelGatewayRouting,chatTemplateKwargs:e.compat.chatTemplateKwargs??t.chatTemplateKwargs,chatTemplateArgs:e.compat.chatTemplateArgs??t.chatTemplateArgs,zaiToolStream:e.compat.zaiToolStream??t.zaiToolStream,supportsThinkingTokenBudget:e.compat.supportsThinkingTokenBudget??t.supportsThinkingTokenBudget,thinkingTokenBudgetField:e.compat.thinkingTokenBudgetField??t.thinkingTokenBudgetField,supportsStrictMode:e.compat.supportsStrictMode??t.supportsStrictMode,supportsOpenAIGrammarTools:e.compat.supportsOpenAIGrammarTools??t.supportsOpenAIGrammarTools,supportsMidConvoSystemMessages:e.compat.supportsMidConvoSystemMessages??t.supportsMidConvoSystemMessages,supportsMidConvoToolAdditions:e.compat.supportsMidConvoToolAdditions??t.supportsMidConvoToolAdditions,cacheControlFormat:e.compat.cacheControlFormat??t.cacheControlFormat,sendSessionAffinityHeaders:e.compat.sendSessionAffinityHeaders??t.sendSessionAffinityHeaders,sessionAffinityFormat:e.compat.sessionAffinityFormat??t.sessionAffinityFormat,supportsLongCacheRetention:e.compat.supportsLongCacheRetention??t.supportsLongCacheRetention,vllmPriority:e.compat.vllmPriority}:t}export{X as convertMessages,H as stream,U as streamSimple};
@@ -1 +0,0 @@
1
- import{f as e,p as t,s as n}from"./preload-helper-mbhLTglw.js";import{t as r}from"./provider-env-CcCbsTJq.js";import{a as i}from"./diagnostics-CmW2yJSB.js";import{n as a}from"./models-CcNnosqL.js";import{t as o}from"./headers-FK4rgixo.js";import{c as s,p as c,r as l}from"./transform-messages-CrQEqmfx.js";import{t as u}from"./provider-retry-CSlu6hjs.js";import{n as d,t as f}from"./github-copilot-headers-DRgtIyTm.js";import{n as p}from"./openai-Cpe0uoXQ.js";import{n as m,t as h}from"./error-body-pkrba6pf.js";import{t as g}from"./openai-prompt-cache-DXo9f3w5.js";import{n as _,r as v,t as y}from"./openai-responses-shared-DzD8B6NI.js";var b=new Set([`openai`,`openai-codex`,`opencode`]),x=16,S=`https://chatgpt.com/settings/usage`;function C(e,t){return e.provider===`openai`&&e.baseUrl===`https://api.openai.com/v1`&&t!==void 0&&!t.startsWith(`sk-`)}function w(e,t){if(!e)return!1;let n=t.toLowerCase();for(let[t,r]of Object.entries(e))if(t.toLowerCase()===n&&r!==null&&r.trim().length>0)return!0;return!1}function T(e,t,n){if(t)return t;if(w(n,`authorization`)||w(n,`cf-aig-authorization`))return`unused`;throw Error(`No API key for provider: ${e}`)}function E(e){return e.provider===`openrouter`||e.baseUrl.includes(`openrouter.ai`)?`openrouter`:`openai`}function D(e,t){return e||(r(`PI_CACHE_RETENTION`,t)===`long`?`long`:`short`)}function O(e){return{supportsDeveloperRole:e.compat?.supportsDeveloperRole??!0,supportsMidConvoSystemMessages:e.compat?.supportsMidConvoSystemMessages??!1,sessionAffinityFormat:e.compat?.sessionAffinityFormat??E(e),supportsLongCacheRetention:e.compat?.supportsLongCacheRetention??!0,supportsStrictMode:e.compat?.supportsStrictMode??!1,supportsOpenAIGrammarTools:e.compat?.supportsOpenAIGrammarTools??!1,supportsAdditionalTools:e.compat?.supportsAdditionalTools??!1,supportsToolSearch:e.compat?.supportsToolSearch??!1,supportsExplicitPromptCacheMode:e.compat?.supportsExplicitPromptCacheMode??!1,supportsMaxOutputTokens:e.compat?.supportsMaxOutputTokens??!0}}function k(e,t){return t===`long`&&e.supportsLongCacheRetention&&!e.supportsExplicitPromptCacheMode?`24h`:void 0}function A(e,t){if(e.supportsExplicitPromptCacheMode){if(t===`none`)return{mode:`explicit`};if(t===`long`&&e.supportsLongCacheRetention)return{ttl:`30m`}}}var j=(t,r,a)=>{let c=new i,l=e(r,O(t).supportsMidConvoSystemMessages);return(async()=>{let e={role:`assistant`,content:[],api:t.api,provider:t.provider,model:t.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:`pending`,timestamp:Date.now()};try{let r=T(t.provider,a?.apiKey,a?.headers),i=D(a?.cacheRetention,a?.env)===`none`?void 0:a?.sessionId,d=O(t),f=s(n(l.messages),d.supportsOpenAIGrammarTools),p=N(t,l,r,a?.headers,a?.fetch,i),m=P(t,l,a,d,f),h=await a?.onPayload?.(m,t);h!==void 0&&(m=h);let g={...a?.signal?{signal:a.signal}:{},...a?.timeoutMs===void 0?{}:{timeout:a.timeoutMs},maxRetries:0},{data:_,response:y}=await u(()=>p.responses.create(m,g).withResponse(),{maxRetries:a?.maxRetries,maxRetryDelayMs:a?.maxRetryDelayMs,signal:a?.signal});if(await a?.onResponse?.({status:y.status,headers:o(y.headers)},t),c.push({type:`start`,partial:e}),await v(_,e,c,t,{onProviderStreamEvent:a?.onProviderStreamEvent,serviceTier:a?.serviceTier,grammarToolInputProperties:f,applyServiceTierPricing:(e,n)=>I(e,n,t)}),a?.signal?.aborted)throw Error(`Request was aborted`);if(e.stopReason===`pending`)throw Error(`OpenAI Responses stream ended without a stop reason`);if(e.stopReason===`aborted`||e.stopReason===`error`)throw Error(e.errorMessage||`An unknown error occurred`);c.push({type:`done`,reason:e.stopReason,message:e}),c.end()}catch(n){for(let t of e.content)delete t.index,delete t.partialJson,delete t.customInput;e.stopReason=a?.signal?.aborted?`aborted`:`error`;let r=h(m(n),`${t.provider===`openai`?`OpenAI`:t.provider} API error`);e.errorMessage=r.includes(`subscription_sharing_usage_limit_exceeded`)?`${r}\nCheck your ChatGPT usage: ${S}`:r,c.push({type:`error`,reason:e.stopReason,error:e}),c.end()}})(),c},M=(e,t,n)=>{T(e.provider,n?.apiKey,n?.headers);let r={...l(e,t,n,n?.apiKey),toolChoice:n?.toolChoice},i=n?.reasoning?a(e,n.reasoning):void 0,o=i===`off`?void 0:i;return j(e,t,{...r,reasoningEffort:o})};function N(e,t,n,r,i,a){let o=O(e),s={"User-Agent":c(),...e.headers};if(e.provider===`github-copilot`){let e=d(t.messages),n=f({messages:t.messages,hasImages:e});Object.assign(s,n)}return a&&(o.sessionAffinityFormat===`openrouter`?s[`x-session-id`]=a:(o.sessionAffinityFormat===`openai`&&(s.session_id=a),s[`x-client-request-id`]=a)),r&&Object.assign(s,r),new p({apiKey:n,baseURL:e.baseUrl,dangerouslyAllowBrowser:!0,fetch:i,defaultHeaders:s})}function P(e,r,i,a=O(e),o=s(n(r.messages),a.supportsOpenAIGrammarTools)){let c=t(r.messages,a.supportsAdditionalTools||a.supportsToolSearch),l=y(e,r,b,{grammarToolInputProperties:o,supportsMidConvoSystemMessages:a.supportsMidConvoSystemMessages,supportsAdditionalTools:a.supportsAdditionalTools,supportsToolSearch:a.supportsToolSearch,toolOptions:{supportsStrictMode:a.supportsStrictMode,supportsOpenAIGrammarTools:a.supportsOpenAIGrammarTools}}),u=D(i?.cacheRetention,i?.env),d=C(e,i?.apiKey),f={model:e.id,input:l,stream:!0,prompt_cache_key:u===`none`?void 0:g(i?.sessionId),prompt_cache_retention:d?void 0:k(a,u),prompt_cache_options:d?void 0:A(a,u),store:!1};return i?.maxTokens&&a.supportsMaxOutputTokens&&!d&&(f.max_output_tokens=Math.max(i.maxTokens,x)),i?.temperature!==void 0&&!d&&(f.temperature=i?.temperature),i?.serviceTier!==void 0&&(f.service_tier=i.serviceTier),c.requestTools.length>0&&(f.tools=_(c.requestTools,{supportsStrictMode:a.supportsStrictMode,supportsOpenAIGrammarTools:a.supportsOpenAIGrammarTools})),i?.toolChoice!==void 0&&(f.tool_choice=i.toolChoice),e.reasoning&&(i?.reasoningEffort||i?.reasoningSummary?(f.reasoning={effort:i?.reasoningEffort?e.thinkingLevelMap?.[i.reasoningEffort]??i.reasoningEffort:`medium`,summary:i?.reasoningSummary||`auto`},f.include=[`reasoning.encrypted_content`]):e.provider!==`github-copilot`&&e.thinkingLevelMap?.off!==null&&(f.reasoning={effort:e.thinkingLevelMap?.off??`none`}),e.provider===`xai`&&(f.include=[`reasoning.encrypted_content`])),Object.assign(f,e.samplingParams,i?.samplingParams),f}function F(e,t){switch(t){case`flex`:return .5;case`priority`:case`fast`:return e.id===`gpt-5.5`?2.5:2;default:return 1}}function I(e,t,n){let r=F(n,t);r!==1&&(e.cost.input*=r,e.cost.output*=r,e.cost.cacheRead*=r,e.cost.cacheWrite*=r,e.cost.total=e.cost.input+e.cost.output+e.cost.cacheRead+e.cost.cacheWrite)}export{j as stream,M as streamSimple};
@@ -1,10 +0,0 @@
1
- import{_ as e,f as t,p as n,v as r}from"./preload-helper-mbhLTglw.js";import{t as i}from"./models-CcNnosqL.js";import{n as a}from"./json-parse-nqKewMRF.js";import{d as o,f as s,l as c,s as l,t as u,u as d}from"./transform-messages-CrQEqmfx.js";import{t as f}from"./sanitize-unicode-DmIE6hZJ.js";import{t as p}from"./hash-yQufAZII.js";function m(e,t){let n={v:1,id:e};return t&&(n.phase=t),JSON.stringify(n)}function h(e){if(e){if(e.startsWith(`{`))try{let t=JSON.parse(e);if(t.v===1&&typeof t.id==`string`)return t.phase===`commentary`||t.phase===`final_answer`?{id:t.id,phase:t.phase}:{id:t.id}}catch{}return{id:e}}}function g(e,t){let n=t.filter(e=>e.type===`text`).map(e=>e.text).join(`
2
- `),r=t.filter(e=>e.type===`image`),i=n.length>0;if(r.length===0||!e.input.includes(`image`))return f(i?n:r.length>0?`(see attached image)`:`(no tool output)`);let a=[];i&&a.push({type:`input_text`,text:f(n)});for(let e of r)a.push({type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});return a}function _(i,a,o,s){let l=t(a,s?.supportsMidConvoSystemMessages),d=[],m=e=>{let t=e.replace(/[^a-zA-Z0-9_-]/g,`_`);return(t.length>64?t.slice(0,64):t).replace(/_+$/,``)},_=e=>{let t=`fc_${p(e)}`;return t.length>64?t.slice(0,64):t},y=u(l.messages,i,(e,t,n)=>{if(!o.has(i.provider)||!e.includes(`|`))return m(e);let[r,a]=e.split(`|`),s=m(r),c=n.provider!==i.provider||n.api!==i.api?_(a):m(a);return c.startsWith(`fc_`)||(c=m(`fc_${c}`)),`${s}|${c}`}),b=n(l.messages,(s?.supportsAdditionalTools??!1)||(s?.supportsToolSearch??!1)),x=(e,t)=>{let n=b.anchorsAdditions?e.toolsAdded??[]:[];if(n.length===0)return;if(s?.supportsAdditionalTools){d.push({type:`additional_tools`,role:`developer`,tools:v(n,s.toolOptions)});return}if(!s?.supportsToolSearch)return;let r=n.map(e=>e.name),i=`pi_tool_load_${p(`${t}:${r.join(`,`)}`)}`;d.push({type:`tool_search_call`,call_id:i,execution:`client`,status:`completed`,arguments:{query:r.join(` `),limit:r.length}}),d.push({type:`tool_search_output`,call_id:i,execution:`client`,status:`completed`,tools:v(n,{...s.toolOptions,toolSearchResult:!0})})},S=s?.includeSystemPrompt??!0,C=i.compat,w=i.reasoning&&C?.supportsDeveloperRole!==!1?`developer`:`system`,T=0,E=0;for(let t of y){let n=E++===0&&t.role===`system`;if(t.role===`system`){if(n||x(t,`system:${T}`),!n||S){let i=n?e(t):r(t);i.length>0&&d.push({role:w,content:f(i)})}}else if(t.role===`user`){if(typeof t.content==`string`)d.push({role:`user`,content:[{type:`input_text`,text:f(t.content)}]});else{let e=t.content.map(e=>e.type===`text`?{type:`input_text`,text:f(e.text)}:{type:`input_image`,detail:`auto`,image_url:`data:${e.mimeType};base64,${e.data}`});if(e.length===0)continue;d.push({role:`user`,content:e})}}else if(t.role===`assistant`){let e=[],n=t,r=n.provider===i.provider&&n.api===i.api,a=r&&n.model===i.id,o=r&&n.model!==i.id,l=0;for(let n of t.content)if(n.type===`thinking`){if(n.thinkingSignature){let t=JSON.parse(n.thinkingSignature);e.push(t)}}else if(n.type===`text`){let t=n,r=h(t.textSignature),i=l===0?`msg_pi_${T}`:`msg_pi_${T}_${l}`;l++;let a=r?.id;a?a.length>64&&(a=`msg_${p(a)}`):a=i,e.push({type:`message`,role:`assistant`,content:[{type:`output_text`,text:f(t.text),annotations:[]}],status:`completed`,id:a,phase:r?.phase})}else if(n.type===`toolCall`){let t=n,[r,i]=t.id.split(`|`),l=s?.grammarToolInputProperties?.get(t.name),u=i;(o&&u?.startsWith(`fc_`)||l===void 0&&!u?.startsWith(`fc_`))&&(u=void 0),l===void 0?e.push({type:`function_call`,id:u,call_id:r,name:t.name,arguments:JSON.stringify(t.arguments),...a&&t.namespace!==void 0?{namespace:t.namespace}:{}}):e.push({type:`custom_tool_call`,id:u,call_id:r,name:t.name,input:f(c(t.name,t.arguments,l)),...a&&t.namespace!==void 0?{namespace:t.namespace}:{}})}if(e.length===0)continue;d.push(...e)}else if(t.role===`toolResult`){let[e]=t.toolCallId.split(`|`),n=g(i,t.content);s?.grammarToolInputProperties?.has(t.toolName)?d.push({type:`custom_tool_call_output`,call_id:e,output:n}):d.push({type:`function_call_output`,call_id:e,output:n})}n||T++}return d}function v(e,t){let n=t?.strict!==void 0&&t.strict,r=t?.supportsStrictMode??!0,i=t?.supportsOpenAIGrammarTools??!1;return e.map(e=>{let a=o(e,i);if(a)return{type:`custom`,name:e.name,description:e.description,format:{type:`grammar`,syntax:a.format,definition:a.definition},...t?.toolSearchResult?{defer_loading:!0}:{}};let c=s(e,r)??n,l={type:`function`,name:e.name,description:e.description,parameters:d(e,c===!0),...t?.toolSearchResult?{defer_loading:!0}:{}};return r&&(l.strict=c),l})}function y(e){let t=e.customInput?.property;if(t===void 0)return``;let n=e.arguments[t];return typeof n==`string`?n:``}function b(e,t,n){let r=e.customInput;if(!r)return;let i=l(r.jsonBuffer,r.property,t,n);return e.arguments={[r.property]:t},i}async function x(e,t,n,r,o){let s=!1,c=new Map,l=new Map,u=e=>{e.type===`message`&&e.phase===`final_answer`&&(t.stopReason=`stop`)},d=(e,t)=>{let n=c.get(e);return n?.type===t?n:void 0},f=(e,r)=>{r!==void 0&&n.push({type:`toolcall_delta`,contentIndex:e.contentIndex,delta:r,partial:t})},p=(e,r)=>{if(r.type===`reasoning`){let r={type:`thinking`,thinking:``};t.content.push(r);let i={type:`thinking`,block:r,contentIndex:t.content.length-1};return c.set(e,i),n.push({type:`thinking_start`,contentIndex:i.contentIndex,partial:t}),i}if(r.type===`message`){u(r);let i={type:`text`,text:``};t.content.push(i);let a={type:`text`,block:i,contentIndex:t.content.length-1};return c.set(e,a),n.push({type:`text_start`,contentIndex:a.contentIndex,partial:t}),a}if(r.type===`function_call`){let i={type:`toolCall`,id:`${r.call_id}|${r.id}`,name:r.name,arguments:{},...r.namespace===void 0?{}:{namespace:r.namespace},partialJson:r.arguments||``};t.content.push(i);let a={type:`toolCall`,block:i,contentIndex:t.content.length-1};return c.set(e,a),n.push({type:`toolcall_start`,contentIndex:a.contentIndex,partial:t}),a}if(r.type===`custom_tool_call`){let i=o?.grammarToolInputProperties?.get(r.name)??`input`,a=r.input||``,s={type:`toolCall`,id:`${r.call_id}|${r.id}`,name:r.name,arguments:{[i]:a},...r.namespace===void 0?{}:{namespace:r.namespace},customInput:{property:i,jsonBuffer:{input:``,started:!1,closed:!1}}};t.content.push(s);let l={type:`toolCall`,block:s,contentIndex:t.content.length-1};return c.set(e,l),n.push({type:`toolcall_start`,contentIndex:l.contentIndex,partial:t}),l}},h=(e,t)=>c.get(e)??p(e,t),g=e=>{for(let t of e){if(t.type!==`reasoning`||!t.encrypted_content)continue;let e=l.get(t.id);if(!e?.thinkingSignature)continue;let n=JSON.parse(e.thinkingSignature);n.encrypted_content||(e.thinkingSignature=JSON.stringify({...n,encrypted_content:t.encrypted_content}))}},_=e=>{if(s=!0,g(e.output??[]),e?.id&&(t.responseId=e.id),e?.usage){let n=e.usage.input_tokens_details,r=n?.cached_tokens||0,i=n?.cache_write_tokens||0;t.usage={input:Math.max(0,(e.usage.input_tokens||0)-r-i),output:e.usage.output_tokens||0,cacheRead:r,cacheWrite:i,reasoning:e.usage.output_tokens_details?.reasoning_tokens||0,totalTokens:e.usage.total_tokens||0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}if(i(r,t.usage),o?.applyServiceTierPricing){let n=o.resolveServiceTier?o.resolveServiceTier(e?.service_tier,o.serviceTier):e?.service_tier??o.serviceTier;o.applyServiceTierPricing(t.usage,n)}let n=e?.status,a=e?.incomplete_details,c=typeof a?.reason==`string`?a.reason:void 0;t.rawStopReason=c?`${n}.${c}`:n;let l=S(n,c);t.stopReason=l.stopReason,l.errorMessage===void 0?delete t.errorMessage:t.errorMessage=l.errorMessage,t.content.some(e=>e.type===`toolCall`)&&t.stopReason===`stop`&&(t.stopReason=`toolUse`)};for await(let i of e)if(await o?.onProviderStreamEvent?.(i,r),i.type===`response.created`)t.responseId=i.response.id;else if(i.type===`response.output_item.added`)p(i.output_index,i.item);else if(i.type===`response.reasoning_summary_text.delta`){let e=d(i.output_index,`thinking`);if(!e)continue;e.block.thinking+=i.delta,n.push({type:`thinking_delta`,contentIndex:e.contentIndex,delta:i.delta,partial:t})}else if(i.type===`response.reasoning_summary_part.done`){let e=d(i.output_index,`thinking`);if(!e)continue;e.block.thinking+=`
3
-
4
- `,n.push({type:`thinking_delta`,contentIndex:e.contentIndex,delta:`
5
-
6
- `,partial:t})}else if(i.type===`response.reasoning_text.delta`){let e=d(i.output_index,`thinking`);if(!e)continue;e.block.thinking+=i.delta,n.push({type:`thinking_delta`,contentIndex:e.contentIndex,delta:i.delta,partial:t})}else if(i.type===`response.output_text.delta`){let e=d(i.output_index,`text`);if(!e)continue;e.block.text+=i.delta,n.push({type:`text_delta`,contentIndex:e.contentIndex,delta:i.delta,partial:t})}else if(i.type===`response.refusal.delta`){let e=d(i.output_index,`text`);if(!e)continue;e.block.text+=i.delta,n.push({type:`text_delta`,contentIndex:e.contentIndex,delta:i.delta,partial:t})}else if(i.type===`response.function_call_arguments.delta`){let e=d(i.output_index,`toolCall`);if(!e||e.block.partialJson===void 0)continue;e.block.partialJson+=i.delta,e.block.arguments=a(e.block.partialJson),f(e,i.delta)}else if(i.type===`response.function_call_arguments.done`){let e=d(i.output_index,`toolCall`);if(!e||e.block.partialJson===void 0)continue;let t=e.block.partialJson;if(e.block.partialJson=i.arguments,e.block.arguments=a(e.block.partialJson),i.arguments.startsWith(t)){let n=i.arguments.slice(t.length);n.length>0&&f(e,n)}}else if(i.type===`response.custom_tool_call_input.delta`){let e=d(i.output_index,`toolCall`);if(!e||!e.block.customInput)continue;f(e,b(e.block,y(e.block)+i.delta,!1))}else if(i.type===`response.custom_tool_call_input.done`){let e=d(i.output_index,`toolCall`);if(!e||!e.block.customInput)continue;f(e,b(e.block,i.input,!0))}else if(i.type===`response.output_item.done`){let e=i.item;u(e);let r=h(i.output_index,e);if(e.type===`reasoning`&&r?.type===`thinking`){let a=e.summary?.map(e=>e.text).join(`
7
-
8
- `)||``,o=e.content?.map(e=>e.text).join(`
9
-
10
- `)||``;r.block.thinking=a||o||r.block.thinking,r.block.thinkingSignature=JSON.stringify(e),l.set(e.id,r.block),n.push({type:`thinking_end`,contentIndex:r.contentIndex,content:r.block.thinking,partial:t}),c.delete(i.output_index)}else e.type===`message`&&r?.type===`text`?(r.block.text=e.content?.map(e=>e.type===`output_text`?e.text:e.refusal).join(``)||``,r.block.textSignature=m(e.id,e.phase??void 0),n.push({type:`text_end`,contentIndex:r.contentIndex,content:r.block.text,partial:t}),c.delete(i.output_index)):e.type===`function_call`&&r?.type===`toolCall`&&r.block.partialJson!==void 0?(r.block.arguments=a(e.arguments||r.block.partialJson||`{}`),e.namespace!==void 0&&(r.block.namespace=e.namespace),delete r.block.partialJson,n.push({type:`toolcall_end`,contentIndex:r.contentIndex,toolCall:r.block,partial:t}),c.delete(i.output_index)):e.type===`custom_tool_call`&&r?.type===`toolCall`&&r.block.customInput&&(f(r,b(r.block,e.input??y(r.block),!0)),e.namespace!==void 0&&(r.block.namespace=e.namespace),delete r.block.customInput,n.push({type:`toolcall_end`,contentIndex:r.contentIndex,toolCall:r.block,partial:t}),c.delete(i.output_index))}else if(i.type===`response.completed`||i.type===`response.incomplete`)_(i.response);else if(i.type===`error`)throw Error(`Error Code ${i.code}: ${i.message}`||`Unknown error`);else if(i.type===`response.failed`){s=!0,t.rawStopReason=i.response?.status;let e=i.response?.error,n=i.response?.incomplete_details,r=e?`${e.code||`unknown`}: ${e.message||`no message`}`:n?.reason?`incomplete: ${n.reason}`:`Unknown error (no error details in response)`;throw Error(r)}if(!s)throw Error(`OpenAI Responses stream ended before a terminal response event`);if(t.stopReason===`toolUse`)for(let e of t.content){if(e.type!==`toolCall`)continue;let t=e;if(t.partialJson!==void 0||t.customInput!==void 0)throw Error(`OpenAI Responses stream completed with an unfinished tool call: ${t.name} (${t.id})`)}}function S(e,t){if(!e)return{stopReason:`stop`};switch(e){case`completed`:return{stopReason:`stop`};case`incomplete`:return t===`max_output_tokens`?{stopReason:`length`}:{stopReason:`error`,errorMessage:t?`Response incomplete: ${t}`:`Response incomplete without a provider reason`};case`failed`:case`cancelled`:return{stopReason:`error`};case`in_progress`:case`queued`:return{stopReason:`stop`};default:throw Error(`Unhandled stop reason: ${e}`)}}export{v as n,x as r,_ as t};
@@ -1,3 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$i as t,Bi as n,Jn as r,fa as i,na as a,oa as o,ra as s,sa as c,ut as l}from"./Effect-CxgtVs4O.js";import{$r as u,Ci as d,Cr as f,Di as p,Fi as m,Fr as h,Hr as ee,Ii as g,Ir as te,Mr as _,Nr as ne,Pi as v,Sr as y,Tr as b,Xr as re,ar as ie,ci as ae,cr as x,di as oe,dr as S,hi as se,hr as C,i as w,ji as T,mr as E,or as D,wr as O,xr as k}from"./extension-hook-0UB2lkEs.js";import{$ as ce,J as le,K as ue,Q as de,X as fe,Y as pe,Z as A,_ as j,a as me,c as M,et as he,g as ge,h as _e,i as ve,l as N,m as ye,nt as be,o as xe,p as Se,q as Ce,r as we,s as Te,tt as Ee,v as P}from"./index-DRDNbHYF.js";import"./extensions-CAsZR9ky.js";function F(e){return b({nextSequence:S.check(ae(0)),omitted:S.check(oe(0)),events:D(b({id:O,sequence:S,at:S,commandId:k(O),event:e}))})}new TextEncoder;var I=te(e=>ge.safeParse(e).success,{representation:{id:`@fungi.computer/whistle/catalog-step/v1`,payload:null}});l(()=>ie());var L=O.pipe(h(p(1)),h(d(4e3)),h(T(/\S/u,{message:`Goal objective is blank`})));O.pipe(h(p(1)),h(d(1e3)),h(T(/\S/u)));var De=O.pipe(h(p(1)),h(d(256))),R=b({revision:O,objective:L,state:C([`active`,`paused`,`complete`,`blocked`]),stopReason:k(O)}),Oe=_([b({action:E(`set`),objective:L,requestId:De,expectedRevision:m(k(O)),confirmed:m(x)}),b({action:C([`pause`,`resume`,`replace`,`clear`])}),b({})]),ke=b({goal:k(R),history:F(R)}),Ae={id:w.make(`botanical-session-goal`),commands:{goal:{scope:`session`,input:Oe,output:I},pause:{scope:`session`,input:b({}),output:R},resume:{scope:`session`,input:b({}),output:R},clear:{scope:`session`,input:b({}),output:b({})},set:{scope:`session`,input:b({objective:L,expectedRevision:k(O),requestId:De}),output:b({goal:R,accepted:b({status:E(`accepted`),commandId:O})})}},projection:{schema:ke}},z=e=>e.state===`blocked`?`error`:e.state===`complete`?`settled`:e.state===`paused`?`muted`:`running`,je=j(Ae,{correlatedPrompts:`note`,contribute:e=>{if(e.status!==`running`||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{goal:t,history:n}=e.value,r=[];if(t!==null){let e={id:`goal`,title:t.objective,detail:`Goal · ${t.state}`,tone:z(t)};r.push(t.state===`active`||t.state===`paused`?{...e,actions:[{id:`goal`,label:t.state===`active`?`Pause goal`:`Resume goal`,input:{action:t.state===`active`?`pause`:`resume`}}]}:e),t.stopReason!==null&&r.push({id:`reason`,title:t.stopReason.slice(0,4096),tone:`attention`})}return{chips:t===null?[]:[{id:`goal`,order:1,row:{id:`goal`,title:`Goal ${t.state}${t.stopReason?.startsWith(`Stalled:`)?`: stalled`:``}`,tone:z(t)}}],panel:r,timeline:{omitted:n.omitted,cells:n.events.map(({event:e,...t})=>({...t,rows:[{id:`state`,title:`Goal ${e.state}`,tone:z(e)},{id:`objective`,title:e.objective},...e.stopReason===null?[]:[{id:`reason`,title:e.stopReason.slice(0,4096),tone:z(e)}]]}))},waiting:null}}}),B=O.pipe(h(p(1)),h(d(262144))),V=O.pipe(h(p(1)),h(d(200))),Me=b({expression:O.pipe(h(p(1)),h(d(256))),timeZone:O.pipe(h(p(1)),h(d(128)))}),H=b({loopId:O,origin:C([`human`,`model`]),expiresAt:k(S),prompt:B,mode:C([`self_paced`,`fixed_interval`]),cron:k(Me),state:C([`active`,`paused`,`finished`,`failed`,`cancelled`]),commandId:O,reason:k(O),nextDueAt:k(S),lastError:k(O)}),Ne=b({loop:H,accepted:b({status:E(`accepted`),commandId:O})}),Pe=_([b({action:E(`start`),text:B,requestId:V}),b({action:C([`status`,`pause`,`resume`,`stop`,`new`])}),b({})]),Fe=b({loop:k(H),history:F(H)}),Ie={id:w.make(`botanical-session-loop`),commands:{loop:{scope:`session`,input:Pe,output:I},startSelfPaced:{scope:`session`,input:b({prompt:B,requestId:V}),output:Ne},startFixedInterval:{scope:`session`,input:b({prompt:B,requestId:V,...Me.fields}),output:Ne},pause:{scope:`session`,input:b({}),output:H},resume:{scope:`session`,input:b({}),output:H},stop:{scope:`session`,input:b({}),output:H}},projection:{schema:Fe}},U=e=>e.state===`failed`?`error`:e.state===`active`?`running`:e.state===`paused`?`muted`:`settled`,Le=e=>new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,timeZoneName:`short`}).format(e),Re=j(Ie,{contribute:e=>{if(e.status!==`running`||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{loop:t,history:n}=e.value,r=t!==null&&t.state===`active`&&t.nextDueAt!==null;return{chips:t===null||t.state!==`active`&&t.state!==`paused`?[]:[{id:`loop`,order:2,row:{id:`loop`,title:`Loop ${t.mode===`self_paced`?`self-paced`:`fixed`}${r?` (waiting)`:``}`,tone:U(t)}}],panel:t===null?[]:[{id:`loop`,title:`Loop · ${t.state} · ${t.mode===`self_paced`?`self-paced`:`${t.cron?.expression??`fixed`} ${t.cron?.timeZone??``}`}${t.nextDueAt===null?``:` · Next ${Le(t.nextDueAt)}`}`,detail:t.prompt.slice(0,1024),tone:U(t)},...t.lastError===null?[]:[{id:`error`,title:t.lastError.slice(0,4096),tone:`error`}]],timeline:{omitted:n.omitted,cells:n.events.map(({event:e,...t})=>({...t,rows:[{id:`loop`,title:`Loop ${e.state}`,detail:(e.lastError??e.reason??e.prompt).slice(0,1024),tone:U(e)}]}))},waiting:r?{summary:`Waiting until ${Le(t.nextDueAt)}`,cancel:{id:`loop`,label:`stop loop`,input:{action:`stop`}}}:null}}}),W=b({explanation:g(O.pipe(h(d(2e3)))),steps:D(b({step:O.pipe(h(p(1)),h(d(500))),status:C([`pending`,`in_progress`,`completed`])})).pipe(h(d(50)))});W.pipe(h(v(e=>e.steps.filter(e=>e.status===`in_progress`).length<=1||`At most one plan step may be in progress`)));function ze(e){return e.steps.some(e=>e.status!==`completed`)}var Be=b({plan:W,history:F(W)}),Ve=_([b({action:E(`clear`)}),b({})]),He={id:w.make(`botanical-session-plan`),commands:{plan:{scope:`session`,input:Ve,output:I}},projection:{schema:Be}},Ue=e=>{let t=e.steps.findIndex(e=>e.status===`in_progress`),n=e.steps.filter(e=>e.status===`completed`).length;return{title:(t<0?e.steps.find(e=>e.status===`pending`):e.steps[t])?.step??`Plan complete`,detail:`${String(t<0?n:t+1)}/${String(e.steps.length)}`}},We=e=>e.steps.map((e,t)=>({id:String(t),title:e.step,tone:e.status===`completed`?`settled`:e.status===`in_progress`?`running`:`muted`})),Ge=j(He,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null||!ze(e.value.plan)?[]:[{id:`plan`,...Ue(e.value.plan),actions:[{id:`plan`,label:`Clear plan`,input:{action:`clear`}}],inspection:{commandId:`plan`,title:`Plan`,rows:We(e.value.plan)}}],timeline:{cells:[],omitted:0},waiting:null})}),G=e=>O.check(p(1),d(e),T(/\S/u)),Ke=b({id:G(32).check(T(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u)),header:G(12),question:G(1e3),options:D(b({label:G(60),description:G(300)})).check(p(2),d(4),v(e=>new Set(e.map(e=>e.label)).size===e.length||`Option labels must be unique`,{representation:{id:`botanical/ask/unique-option-labels`,payload:null}})),multiple:g(x)}),qe=D(Ke).check(p(1),d(4),v(e=>new Set(e.map(e=>e.id)).size===e.length||`Question ids must be unique`,{representation:{id:`botanical/ask/unique-question-ids`,payload:null}})),Je=b({askId:O,questions:qe,status:C([`live`,`parked`]),createdAt:y,expiresAt:k(y)}),Ye=b({asks:D(Je).check(d(4))}),K=G(256),q=f(Ke.fields.id,b({selected:D(G(60)).check(d(4)),text:g(O.check(d(4e3)))})),J=b({askId:G(256),requestId:K,answers:q}),Xe=b({askId:G(256),requestId:K,note:g(O.check(d(4e3)))}),Ze=C([`answered`,`declined`,`withdrawn`,`expired`,`cancelled`,`undeliverable`]),Qe=_([b({result:E(`accepted`),via:C([`in_turn`,`follow_up`])}),b({result:E(`closed`),status:Ze}),b({result:E(`not_found`)})]),Y={askId:J.fields.askId,requestId:K,index:y.check(se(),u({minimum:0,maximum:3})),answers:q},$e=_([b({stage:E(`multiple`),...Y,selection:O.check(d(1e3))}),b({stage:E(`selection`),...Y,selection:O.check(d(1e3))}),b({stage:E(`text`),...Y,selected:q.value.fields.selected,text:O.check(d(4e3))}),b({askId:J.fields.askId}),b({})]),et={id:w.make(`botanical-session-question`),commands:{answerFlow:{scope:`session`,input:$e,output:I},answer:{scope:`session`,input:J,output:Qe},decline:{scope:`session`,input:Xe,output:Qe},list:{scope:`session`,input:b({}),output:Ye}},projection:{schema:Ye}},tt=j(et,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:e.value.asks.map(e=>{let t=e.questions[0];return{id:e.askId,title:`${t?.question??`Question`}${e.questions.length>1?` (+${String(e.questions.length-1)} more)`:``}`,detail:t?.options.map(e=>e.label).join(` · `)??``,tone:`attention`,actions:[{id:`answerFlow`,label:`Answer`,input:{askId:e.askId}}]}}),timeline:{cells:[],omitted:0},waiting:null})}),X=O.check(p(1),d(256)),nt=C([`working`,`waiting`,`idle`,`failed`,`unavailable`]),rt=b({agentId:X,name:X,sessionId:k(X),state:nt,attention:g(O.check(d(200)))}),it=b({agents:D(rt).check(d(16)),more:S.check(oe(0))}),at={id:w.make(`botanical-session-subagents`),commands:{},projection:{schema:it}},ot={working:{label:`working`,tone:`running`,status:`info`},waiting:{label:`waiting on you`,tone:`attention`,status:`warning`},idle:{label:`idle`,tone:`settled`,status:`success`},failed:{label:`failed`,tone:`error`,status:`error`},unavailable:{label:`unavailable`,tone:`muted`,status:`neutral`}};function st(e){let t=ot[e.state],n={id:e.agentId,title:`${e.name} · ${t.label}`,tone:t.tone,status:{label:t.label,tone:t.status}},r=e.attention===void 0?n:{...n,detail:e.attention};return e.sessionId===null?{...r,detail:e.attention??`not messaged yet`}:{...r,open:{params:[{key:`agent`,value:e.agentId},{key:`session`,value:e.sessionId}]}}}var ct=j(at,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:[...e.value.agents.map(st),...e.value.more===0?[]:[{id:`more`,title:`${String(e.value.more)} more sub-agent${e.value.more===1?``:`s`}`,tone:`muted`}]],timeline:{cells:[],omitted:0},waiting:null})});function lt(e,t){if(e===null||!URL.canParse(t))return!1;let n=new URL(t);return n.protocol!==`https:`||n.hash!==`#team-billing`?!1:(e.openTeamBilling().catch(t=>(console.error(`Chat Billing navigation failed`,t),e.showToast({message:`Billing could not be opened. Please try again.`,tone:`error`}))),!0)}var Z=e(be(),1),Q=Ee();function ut(e){if(e.name!==`execute`||e.status!==`completed`)return;let t=e.result?.content;if(t?.length!==1||t[0]?.type!==`text`)return;let n=ee(re(ne))(t[0].text);if(r(n))return;let i=_e.safeParse(n.value);return i.success?i.data.file:void 0}function dt({item:e,ui:t}){let n=ut(e),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1);if(!n)return null;let s=async()=>{i(!0),o(!1);try{await t.openNavigation(n)}catch(e){console.error(`Chat file navigation failed`,e),o(!0)}finally{i(!1)}};return(0,Q.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,Q.jsx)(P,{variant:`ghost`,size:`sm`,disabled:r,onClick:()=>void s(),type:`button`,children:r?`Opening file…`:`Open ${n.path} in Inkcap`}),a?(0,Q.jsx)(`p`,{role:`alert`,children:`The file could not be opened. Try again.`}):null]})}var ft=o({kind:t(`generated`),file:o({computerId:c().min(1),path:c().min(1)}),format:n([`png`,`jpeg`,`gif`,`webp`,`mp4`]),width:a(),height:a(),bytes:a(),costMilliunits:a(),receipt:c()});function pt(e){if(e.name!==`execute`||e.status!==`completed`)return;let t=e.result?.content??[],n=t.at(0);if(n?.type!==`text`||t.slice(1).some(e=>e.type!==`image`))return;let i=ee(re(ne))(n.text);if(r(i))return;let a=ft.safeParse(i.value);return a.success?a.data:void 0}function mt({item:e,ui:t}){let n=pt(e),[r,i]=(0,Z.useState)(!1),[a,o]=(0,Z.useState)(!1);if(!n)return null;let s=async()=>{i(!0),o(!1);try{await t.openNavigation(n.file)}catch(e){console.error(`Chat image navigation failed`,e),o(!0)}finally{i(!1)}};return(0,Q.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,Q.jsx)(P,{variant:`ghost`,size:`sm`,disabled:r,onClick:()=>void s(),type:`button`,children:r?`Opening file…`:`Open ${n.file.path} in Inkcap`}),a?(0,Q.jsx)(`p`,{role:`alert`,children:`The file could not be opened. Try again.`}):null]})}var ht=(0,Z.forwardRef)(function({heading:e,eyebrow:t,cover:n,action:r,children:i,className:a,...o},s){return(0,Q.jsxs)(Ce,{...o,className:A(`caps-game-share`,a),ref:s,children:[n?(0,Q.jsx)(`div`,{className:`caps-game-share-cover`,children:n}):null,(0,Q.jsxs)(fe,{children:[t,(0,Q.jsx)(`h3`,{className:`caps-game-share-heading`,children:e})]}),(0,Q.jsx)(le,{className:`gap-sm`,children:i}),(0,Q.jsx)(pe,{children:(0,Q.jsx)(P,{asChild:!0,variant:`primary`,className:`caps-game-share-action`,children:r})})]})});function gt(e){let t=0;return e.map(e=>{let n={...e,offset:t};return t+=e.text.length,n})}function _t({value:e,label:t,fieldLabel:n,displayValue:r,layout:i,title:a,tokens:o,className:s,...c}){let l=(0,Z.useId)(),[u,d]=(0,Z.useState)({kind:`ready`}),f=o?o.map(e=>e.text).join(``):e,p=async()=>{d(await navigator.clipboard.writeText(f).then(()=>({kind:`copied`}),e=>({kind:`failed`,cause:e})))};if(n!==void 0)return(0,Q.jsxs)(`div`,{...c,className:A(`caps-copy-field-input`,s),children:[(0,Q.jsx)(Te,{htmlFor:l,children:n}),(0,Q.jsxs)(xe,{children:[(0,Q.jsx)(me,{className:`caps-copy-field-control`,"aria-label":n,id:l,onFocus:e=>{e.currentTarget.select()},readOnly:!0,value:r??f}),(0,Q.jsx)(P,{onClick:()=>void p(),size:`sm`,variant:`outline`,children:u.kind===`copied`?`Copied`:t??`Copy`})]}),u.kind===`failed`?(0,Q.jsx)(`span`,{role:`status`,children:`Could not copy. Select the text to copy it.`}):null]});let m=u.kind===`copied`?`Copied`:u.kind===`failed`?`Copy failed`:t??`Copy`;return i===`block`?(0,Q.jsxs)(`figure`,{...c,className:A(`caps-copy-field-block`,s),"data-state":u.kind,children:[(0,Q.jsxs)(`figcaption`,{className:`caps-copy-field-header`,children:[(0,Q.jsx)(`span`,{className:`caps-copy-field-title`,children:a}),(0,Q.jsxs)(P,{onClick:()=>void p(),size:`sm`,variant:u.kind===`copied`?`ghost`:`outline`,children:[u.kind===`copied`?(0,Q.jsx)(N,{"aria-hidden":`true`,size:15}):(0,Q.jsx)(M,{"aria-hidden":`true`,size:15}),m]}),(0,Q.jsx)(ue,{role:`status`,children:u.kind===`copied`?`Copied to the clipboard`:u.kind===`failed`?`Could not copy. Select the code to copy it.`:``})]}),(0,Q.jsx)(`pre`,{className:`caps-copy-field-code`,tabIndex:0,children:(0,Q.jsx)(`code`,{children:o?gt(o).map(e=>(0,Q.jsx)(`span`,{className:`caps-copy-field-token`,"data-kind":e.kind,children:e.text},e.offset)):f})})]}):(0,Q.jsxs)(`div`,{...c,className:A(`caps-copy-field`,s),children:[(0,Q.jsx)(`code`,{className:`caps-copy-field-value`,children:f}),(0,Q.jsxs)(P,{"aria-label":`${m}: ${f}`,onClick:()=>void p(),size:`sm`,variant:`outline`,children:[u.kind===`copied`?(0,Q.jsx)(N,{size:15}):(0,Q.jsx)(M,{size:15}),m]})]})}var vt=s({game:s({title:c().min(1),summary:c(),coverUrl:i().nullable(),shareUrl:i()})});function $(e){let t=/(?:^|\n)\s*Share:\s*(https?:\/\/[^\s<>]+)/iu.exec(e);if(!t?.[1])return null;let n=t[1].replace(/[.,;!?]+$/u,``);if(!URL.canParse(n))return null;let r=new URL(n);return r.username||r.password||r.hash||r.protocol===`http:`&&![`localhost`,`127.0.0.1`].includes(r.hostname)?null:r.href}function yt(e){return $(e)?e.split(`
2
- `).filter(e=>!/^\s*Share:\s*/iu.test(e)).join(`
3
- `).trim():e}function bt(e){let t=new URL(e),n=/^\/([a-z0-9]+(?:-[a-z0-9]+)*)\/?$/u.exec(t.pathname)?.[1];return!n||t.search?null:new URL(`/api/games/${n}`,t.origin)}function xt({reply:e,previewGame:t}){let n=$(e),r=n?bt(n):null,{data:i}=he({queryKey:de.of(null,`game-share`,n),enabled:r!==null&&t===void 0,queryFn:async({signal:e})=>{if(!r)return null;let t=await fetch(r,{signal:e});if(!t.ok)return null;let i=vt.safeParse(await t.json());return i.success&&i.data.game.shareUrl===n?i.data.game:null}}),a=t??i;if(!n)return null;let o=new URL(n),s=`${o.host}${o.pathname.replace(/\/$/u,``)}`,c=a?.coverUrl&&r?t?a.coverUrl:new URL(`${r.pathname}/cover`,r.origin).href:null;return(0,Q.jsxs)(ht,{"data-game-share-card":`true`,"data-theme":`vishnu`,heading:a?.title??`Your game is ready`,eyebrow:(0,Q.jsx)(ve,{tone:`secondary`,variant:`quiet`,children:`Made with your Agent`}),cover:c?(0,Q.jsx)(`img`,{alt:`A scene from ${a?.title??`your game`}`,src:c}):null,action:(0,Q.jsx)(`a`,{href:n,rel:`noopener noreferrer`,target:`_blank`,children:`Play ↗`}),children:[a?.summary?(0,Q.jsx)(`p`,{className:`text-sm`,children:a.summary}):null,(0,Q.jsx)(_t,{displayValue:s,fieldLabel:`Share link`,label:`Copy link`,value:n})]})}var St=[je,Re,Ge,tt,ct],Ct=e=>(0,Q.jsx)(xt,{reply:e});function wt({prefill:e,onPrefilled:t}){let n=ye(),r=(0,Z.useRef)(null);return(0,Z.useEffect)(()=>{!e||r.current===e.requestId||(r.current=e.requestId,n.setDraft(e.text),t())},[n.setDraft,t,e]),null}function Tt({session:e,connection:t,commands:n,prefill:r=null,onPrefilled:i=()=>void 0,onOpen:a}){let o=t?.ui??null,s=(0,Z.useCallback)(e=>lt(o,e),[o]),c=(0,Z.useCallback)(e=>o?(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(dt,{item:e,ui:o}),(0,Q.jsx)(mt,{item:e,ui:o})]}):null,[o]);return(0,Q.jsxs)(Se,{session:e,clients:St,authorOf:ce,children:[(0,Q.jsx)(wt,{prefill:r,onPrefilled:i}),(0,Q.jsx)(we,{onLink:s,onOpen:a,composerActionVariant:`outline`,commands:n,renderAssistantAttachment:Ct,formatAssistantText:yt,renderToolActions:c})]})}export{Tt as ParakeetConversation};
@@ -1,8 +0,0 @@
1
- function e(e,t=`
2
- `){return typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(t)}function t(t){let n=[e(t.content)];for(let e of Object.values(t.sections??{}))e!==null&&n.push(e);return n.filter(e=>e.length>0).join(`
3
-
4
- `)}function n(t){let n=[],r=e(t.content);r.length>0&&n.push(r);for(let[e,r]of Object.entries(t.sections??{}))n.push(r===null?`Removed system prompt section "${e}".`:`Updated system prompt section "${e}":\n\n${r}`);return n.join(`
5
-
6
- `)}function r(e,t){let n=e!==void 0&&e.length>0,r=t!==void 0&&t.length>0;if(!(!n&&!r))return{role:`system`,content:e??``,...r?{toolsAdded:t}:{},timestamp:0}}function i(e){let t=r(e.systemPrompt,e.tools);return{messages:t?[t,...e.messages]:e.messages}}function a(e){return e.role===`system`}function o(e){let t=e[0];return t&&a(t)?t:void 0}function s(e){return o(e)?e.slice(1):e}function c(e){let t=new Map;for(let n of e)if(a(n)){for(let e of n.toolsRemoved??[])t.delete(e.name);for(let e of n.toolsAdded??[])t.set(e.name,e)}return[...t.values()]}function l(t){let n=[],r=new Map,i;for(let o of t){if(!a(o))continue;i??=o.timestamp;let t=e(o.content);t.length>0&&n.push(t);for(let[e,t]of Object.entries(o.sections??{}))t===null?r.delete(e):r.set(e,t)}let o=c(t);if(i!==void 0||o.length!==0)return{role:`system`,content:n.join(`
7
-
8
- `),...r.size>0?{sections:Object.fromEntries(r)}:{},...o.length>0?{toolsAdded:o}:{},timestamp:i??0}}function u(e){let t=l(e.messages),n=e.messages.filter(e=>e.role!==`system`);return{messages:t?[t,...n]:n}}function d(e,t){return t?e:u(e)}function f(e){return{name:e.name,description:e.description,parameters:JSON.parse(JSON.stringify(e.parameters)),...e.constrainedSampling===void 0?{}:{constrainedSampling:e.constrainedSampling}}}function p(e,t){return JSON.stringify(f(e))===JSON.stringify(f(t))}function m(e){let t=new Map;for(let n of e)if(a(n))for(let e of n.toolsAdded??[])t.set(e.name,e);return[...t.values()]}function h(e){let t=new Map;for(let n of e)if(a(n))for(let e of n.toolsAdded??[]){let n=t.get(e.name);if(n!==void 0&&!p(n,e))return!0;t.set(e.name,e)}return!1}function g(e){let t=new Set;for(let n of e)if(a(n)){if((n.toolsRemoved?.length??0)>0)return!0;for(let e of n.toolsAdded??[]){if(t.has(e.name))return!0;t.add(e.name)}}return!1}function _(e,t){let n=t&&!g(e);return{requestTools:n?o(e)?.toolsAdded??[]:c(e),anchorsAdditions:n}}var v=function(e){return`/`+e},y={},b=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=v(t,n),t=s(t),t in y)return;y[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:`modulepreload`,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};export{t as _,l as a,o as c,i as d,d as f,e as g,s as h,p as i,g as l,f as m,u as n,c as o,_ as p,r,m as s,b as t,h as u,n as v};
@@ -1 +0,0 @@
1
- import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{A as n,r,sa as i,t as a,ut as o}from"./Effect-CxgtVs4O.js";import{i as s,t as c}from"./document-D5hwZS3o.js";import{A as l,B as u,C as d,D as f,E as p,F as m,G as h,H as g,I as _,L as v,M as y,N as ee,O as b,P as x,R as S,S as C,T as te,U as w,V as T,W as ne,b as re,j as E,k as ie,w as ae,x as D,y as oe,z as O}from"./index-DRDNbHYF.js";var se=(e,t)=>{if(u(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},k=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),v(t))return n;if(x(+t))return+t;let r=t,i=e?e.labels:null,a=!ee(i),o=se(e,r),s=!v(o),c=ne.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return f(u,d,e[0])}return s?o:a?v(i[r])?n:i[r]:n};function ce(e){return l((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function A(e,t,n,r,i,a){let o=x(e.duration)&&e.duration<=1e-11?n-w:n;t.composition&&p(t,o,1,1,h.AUTO);let s=r?new oe(r,e,t,o,!1,i,a):new C(e,t,o);return t.composition&&s.init(!0),ie(t,s),E(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=ce(t),t}var j=0,M=class extends C{constructor(e={}){super(e,null,0),++j,this.id=v(e.id)?j:e.id,this.duration=0,this.labels={};let t=e.defaults,n=T.defaults;this.defaults=t?S(t,n):n,this.composition=b(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=b(e.playbackEase,n.playbackEase);this._ease=r?re(r):null,this.iterationDuration=0}add(e,t,n){let r=m(t),i=m(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=T.editor&&T.editor.addTimelineChild,a=n&&n.type===`Stagger`&&T.editor,o=y(n)?n:null;if(o||a){let t=D(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||T.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,v(c)||(n.id=c+`-`+l);let i=k(this,f(e,l,t,null,this));A(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;A(t,this,k(this,a),e)}}else A(e,this,k(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(v(e)||e&&v(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!v(e)&&!v(e.persist)&&(e.persist=!0);let r=T.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return v(t)?this:(t.duration=w,t.composition=g.replace,this.add(e,t,n))}call(e,t){return v(e)||e&&!y(e)?this:(T.editor&&T.editor.addTimelineCall&&(t=T.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return v(e)||e&&!_(e)?this:(T.editor&&T.editor.addTimelineLabel&&(t=T.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=k(this,t),this)}remove(e,t){return ae(D(e),this,t),this}stretch(e){let t=this.duration;if(t===O(e))return this;let n=e/t,r=this.labels;E(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return E(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),E(this,e=>e.revert,!0),te(this)}then(e){return super.then(e)}},N=e=>T.editor?T.editor.addTimeline(e):new M(e).init(),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),I=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),R=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),F(),I());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),z=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),le=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),z());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(R());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),R(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(P(),F(),I(),L(),R(),z(),le(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=s(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=s(n.color);r&&(n.color=this.palette[r]);let i=s(n.backface);i&&(n.backface=this.palette[i]);let a=s(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=N({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=d({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>n(function*(){let t=c.parse(e.document.data),n=yield*a(o(()=>e.target.ownerDocument.createElement(`canvas`)),e=>o(()=>{e.remove()}));n.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(n);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let l,u=!0,d=!1,f=()=>{u||d||l!==void 0||(l=s.requestAnimationFrame(e=>{l=void 0,m.tick(e)&&f()}))},p=()=>{d||(u?m.renderStill():f())},m=yield*a(o(()=>ye({target:n,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>o(()=>{e.destroy()}));yield*r(()=>o(()=>{d=!0,l!==void 0&&s.cancelAnimationFrame(l)})),m.pause(!0);let h,g;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,r]of Object.entries(e.appearance)){let e=i().safeParse(r);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let r=JSON.stringify(n);r!==g&&(m.setPalette(n),g=r);let a=e.expression??t.defaultPresentation.expression;if(!a)throw Error(`Zdog avatar needs an expression`);let o=JSON.stringify([e.activity,a]);o!==h&&(m.present({activity:e.activity,expression:a}),h=o),p()},pause(e){u=e,m.pause(e),u&&l!==void 0&&(s.cancelAnimationFrame(l),l=void 0),p()}}});export{be as t};