castle-web-cli 0.4.190 → 0.4.191

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.
@@ -446,4 +446,4 @@ Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error
446
446
 
447
447
  `),chips:n}}function TY(e,t){let n=[],r=e.map((r,i)=>{if(r.kind!==`md`)return r;let a=wY(r.text,t&&i===e.length-1);for(let e of a.chips)n.includes(e)||n.push(e);return{kind:`md`,text:a.prose}});return n.length>0&&r.push({kind:`chips`,chips:n}),r}function EY(e){let t;try{t=JSON.parse(e)}catch{return null}if(!t||!Array.isArray(t.questions))return null;let n=[];return t.questions.forEach((e,t)=>{let r=e;if(!r||typeof r.q!=`string`||!Array.isArray(r.options))return;let i=r.options.filter(e=>typeof e==`string`&&e.trim()!==``).filter(e=>!_Y(e)),a=typeof r.id==`string`&&r.id.trim()?r.id.trim():`q${t}`;n.push({id:a,q:r.q,options:i,multi:r.multi===!0})}),n.length===0?null:{questions:n}}function DY(e,t=!1){let n=!1;if((e.split("```").length-1)%2==1){let t=e.lastIndexOf("```"),r=e.slice(t+3),i=r.indexOf(`
448
448
  `),a=(i===-1?r:r.slice(0,i)).trim();i===-1?a===``?e=e.slice(0,t):`ask`.startsWith(a)&&(e=e.slice(0,t),n=!0):a===`ask`&&(e=e.slice(0,t),n=!0)}let r=[],i=0,a;for(SY.lastIndex=0;(a=SY.exec(e))!==null;){let t=EY(a[1]);t&&(a.index>i&&r.push({kind:`md`,text:e.slice(i,a.index)}),r.push({kind:`ask`,spec:t}),i=a.index+a[0].length)}return i<e.length&&r.push({kind:`md`,text:e.slice(i)}),r.length===0&&!n&&r.push({kind:`md`,text:e}),n&&r.push({kind:`ask-pending`}),TY(r,t)}function OY(e){return e.some(e=>e.kind===`ask`||e.kind===`ask-pending`||e.kind===`chips`||e.kind===`md`&&e.text.trim()!==``)}function kY(e,t){let n=[];for(let r of e.questions){let e=t[r.id]??[];if(vY(e)){n.push(`- ${r.q} \u2192 skipped`);continue}let i=yY(r,e),a=bY(r,e).trim(),o=[...i,...a?[a]:[]];o.length!==0&&n.push(`- ${r.q} \u2192 ${o.join(`, `)}`)}return n.length?`Here's what I picked:\n${n.join(`
449
- `)}`:``}var AY={thinking:(0,U.jsx)(W,{name:`lightbulb`}),reading:(0,U.jsx)(W,{name:`book`}),building:(0,U.jsx)(W,{name:`hammer`}),painting:(0,U.jsx)(W,{name:`pencil`}),playing:(0,U.jsx)(W,{name:`gamepad`})},jY={thinking:`Thinking`,reading:`Reading files`,building:`Editing logic`,painting:`Editing art`,playing:`Playtesting`},MY={thinking:`#FFC826`,reading:`#FFC826`,building:`#FFEB57`,painting:`#FFEB57`,playing:`#D3FC7E`};function NY(e){if(e.status===`done`)return{icon:(0,U.jsx)(W,{name:`check`}),color:`#5AC54F`};if(e.status===`failed`)return{icon:(0,U.jsx)(W,{name:`times`}),color:`#F5545D`};if(e.status===`interrupted`)return{icon:(0,U.jsx)(W,{name:`stop`}),color:`#B4B4B4`};if(e.status===`blocked`)return{icon:(0,U.jsx)(W,{name:`stop`}),color:`#F5A623`};let t=e.avatar&&AY[e.avatar]?e.avatar:`thinking`;return{icon:AY[t],color:MY[t]}}function PY(e){let t=Math.max(1,Math.round((e??0)/1e3));if(t<60)return`Thought for ${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`Thought for ${n}m`:`Thought for ${n}m ${r}s`}var FY=`plan.md`;function IY(){let e=xS();return(0,U.jsxs)(`div`,{className:`operator-line msg-plan`,children:[(0,U.jsx)(W,{name:`file-md`,className:`icon-inline`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`button`,{type:`button`,className:`operator-line-link`,title:`Open ${FY}`,onClick:()=>e.openFile(FY),children:FY}),` `,`updated`]})]})}function LY(e){let t=xS();return(0,U.jsx)(`button`,{type:`button`,className:`msg-file`,title:`Open ${gF(e.loc)}`,onClick:()=>kF(t,e.loc),children:e.token})}function RY(e){let{text:t}=e,n=GC(),r=g.useMemo(()=>OF(t,HC),[t,n]),i=[],a=0;for(let e of r)e.start>a&&i.push(t.slice(a,e.start)),i.push((0,U.jsx)(LY,{loc:e.loc,token:t.slice(e.start,e.end)},e.start)),a=e.end;return a<t.length&&i.push(t.slice(a)),(0,U.jsx)(`span`,{children:i})}var zY=(0,U.jsx)(W,{name:`send`}),BY=(0,U.jsx)(W,{name:`stop`}),VY=(0,U.jsx)(W,{name:`chevron-down`}),HY=`openai/gpt-5.6-terra`,UY=[{value:`sonnet`,label:`Sonnet`},{value:`opus`,label:`Opus`},{value:`fable`,label:`Fable`}],WY={sonnet:`Sonnet`,opus:`Opus`,fable:`Fable`};function GY(e){return e===`router`?{claude:`routerClaudeModel`,slug:`routerOpenrouterModel`}:{claude:`tasksClaudeModel`,slug:`tasksOpenrouterModel`}}function KY(e){let t=e?.freeModel;return t&&t.trim()?t:null}function qY(e,t,n){let{claude:r,slug:i}=GY(e);if(t[r]!==`openrouter`)return`claude`;let a=KY(n);return a&&(n?.freeRoles?.[e]||t[i]?.trim()===a)?`muse`:`openrouter`}function JY(e){if(!e||!e.trim())return null;let t=e.trim(),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function YY(e,t,n){let{claude:r,slug:i}=GY(e),a=t[r];return qY(e,t,n)===`muse`?`Muse`:a===`openrouter`?JY(t[i])??`OpenRouter`:WY[a]??a??`?`}function XY(e,t){return`${YY(`router`,e,t)} → ${YY(`tasks`,e,t)}`}function ZY(e){let{label:t,placeholder:n,value:r,warning:i,discardOnUnmount:a,onCommit:o}=e,[s,c]=g.useState(r);g.useEffect(()=>c(r),[r]);let l=g.useRef(s),u=g.useRef(r),d=g.useRef(o);l.current=s,u.current=r,d.current=o;let f=()=>{let e=l.current.trim();return e&&e!==u.current?(d.current(e),!0):!1},p=()=>{f()||c(u.current)};g.useEffect(()=>{a&&(a.current=!1)},[a]),g.useEffect(()=>()=>{a?.current||f()},[a]);let m=e=>{c(e),o(e)};return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`div`,{className:`settings-row-main settings-model-detail`,children:[(0,U.jsx)(`span`,{className:`settings-label`,children:t}),(0,U.jsx)(`input`,{type:`text`,size:1,className:`text-field${i?` settings-text-warn`:``}`,value:s,placeholder:n,onChange:e=>c(e.target.value),onBlur:p,onKeyDown:e=>{e.key===`Enter`&&(p(),e.target.blur())}})]}),i?(0,U.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,i.message,i.suggestion?(0,U.jsxs)(U.Fragment,{children:[` `,`Did you mean`,` `,(0,U.jsx)(`button`,{type:`button`,className:`settings-warning-suggest`,onMouseDown:e=>{e.preventDefault(),m(i.suggestion)},children:i.suggestion}),`?`]}):null]}):null]})}function QY(e,t,n){let r=e?.[t];if(!(!r||!n||r.model!==n))return{message:r.message,suggestion:r.suggestion}}function $Y(e){let{claude:t,slug:n}=GY(e.role),r=e.role===`router`?`Operator model`:`Task model`,i=KY(e.usage),a=qY(e.role,e.settings,e.usage),o=g.useRef(!1),s=UY.filter(t=>!e.blockedClaudeModels.includes(t.value)),c=e.role===`router`?`opus`:`sonnet`,l=s.some(e=>e.value===c)?c:s[0]?.value,u=r=>{if(r===a)return;if(r===`muse`){if(!i)return;o.current=!0,e.onSetSettings({[t]:`openrouter`,[n]:i});return}if(r===`claude`){if(!l)return;o.current=!0,e.onSetSetting(t,l);return}let s=e.settings[n]?.trim()??``;if(!s||s===i){e.onSetSettings({[t]:`openrouter`,[n]:HY});return}e.settings[t]!==`openrouter`&&e.onSetSetting(t,`openrouter`)},d=e=>e.preventDefault();return(0,U.jsxs)(`div`,{className:`settings-row settings-row-stack settings-model-picker`,children:[(0,U.jsxs)(`div`,{className:`settings-row-main`,children:[(0,U.jsx)(`span`,{className:`settings-label`,children:r}),(0,U.jsxs)(`div`,{className:`segmented settings-model-family`,role:`group`,"aria-label":r,children:[i?(0,U.jsxs)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":a===`muse`,onMouseDown:d,onClick:()=>u(`muse`),children:[(0,U.jsx)(`span`,{children:`Muse`}),(0,U.jsx)(`span`,{className:`settings-free-chip`,children:`FREE`})]}):null,[`claude`,`openrouter`].map(e=>(0,U.jsx)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":a===e,onMouseDown:d,onClick:()=>u(e),children:(0,U.jsx)(`span`,{children:e===`claude`?`Claude`:`OpenRouter`})},e))]})]}),e.hasAnthropicAccount&&e.settings[t]===`openrouter`?(0,U.jsx)(`div`,{className:`settings-warning`,children:`⚠ Pick Claude to use your Anthropic credentials`}):null,a===`claude`?(0,U.jsx)(`div`,{className:`settings-row-main settings-model-detail`,children:(0,U.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":`${e.role===`router`?`Operator`:`Task`} Claude model`,children:s.map(n=>(0,U.jsx)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":e.settings[t]===n.value,onClick:()=>{e.settings[t]!==n.value&&e.onSetSetting(t,n.value)},children:(0,U.jsx)(`span`,{children:n.label})},n.value))})}):null,a===`openrouter`?(0,U.jsx)(ZY,{label:`OpenRouter slug`,placeholder:HY,value:e.settings[n]??``,discardOnUnmount:o,warning:QY(e.warnings,n,e.settings[n]),onCommit:t=>e.onSetSetting(n,t)}):null]})}function eX(e){if(!e||e.limitMicros===null||e.limitMicros<=0)return null;if(e.blocked)return 1;if(e.credits?.plan===`daily`&&e.credits.dailyFreeRemainingCredits!==null){let t=e.credits.dailyFreeRemainingCredits*1e4;return t<=0?1:Math.min(1,Math.max(0,e.usedMicros/(e.usedMicros+t)))}return Math.min(1,e.usedMicros/e.limitMicros)}function tX(e){let t=e?.autoReload;return!t?.enabled||t.disabledReason||t.thresholdCredits===null||t.amountCredits===null?null:{thresholdCredits:t.thresholdCredits,amountCredits:t.amountCredits}}function nX(e){if(e?.blocked)return`operator-usage-blocked`;if(e?.credits?.plan===`credits`)return e.credits.lowBalance&&!tX(e.credits)?`operator-usage-warn`:``;let t=eX(e);return t===null?``:t>=.8?`operator-usage-warn`:``}var rX=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`});function iX(e){return rX.format(e/100)}function aX(e){return iX(e/1e4)}function oX(e,t){if(!t||t.displayUnit===`usd`||t.usdPerCredit<=0)return aX(e);let n=Math.round(e/1e6/t.usdPerCredit);return`${n.toLocaleString()} ${n===1?`credit`:`credits`}`}function sX(e){return e.resetAtMs?new Date(e.resetAtMs).toLocaleTimeString([],{hour:`numeric`,minute:`2-digit`}):``}function cX(e){let{usage:t}=e,n=eX(t);if(n===null)return null;let r=sX(t),i=t.credits?.plan===`daily`?t.credits.purchasedCredits+t.credits.grantedCredits:0,a=i>0?` + ${iX(i)} credits`:``,o=(t.blocked?`Limit reached`:`${Math.round(n*100)}%${r?` \u00b7 resets ${r}`:``}`)+a;return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`settings-row`,children:(0,U.jsx)(`span`,{className:`settings-label`,children:`Daily Operator usage`})}),(0,U.jsx)(`div`,{className:`settings-usage-bar`,children:(0,U.jsx)(`div`,{className:`settings-usage-fill`+(t.blocked?` blocked`:``),style:{width:`${n*100}%`}})}),(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:o})]})}function lX(e){let t=e.credits,n=t?.autoReload,r=tX(t),i=t?.rates,a=`${oX(e.creditsExhausted?0:e.spendableMicros??0,i)} left`,o=t?.nextGrantAt?`Refreshes ${new Date(t.nextGrantAt).toLocaleDateString()}`:null,s=r?`Auto-reload will add ${oX(r.amountCredits*1e4,i)} when you drop below ${oX(r.thresholdCredits*1e4,i)}`:null,c=sX(e),l=e.blocked?`Daily limit reached${c?` · Resets at ${c}`:``}`:null,u=!!n?.disabledReason,d=null;return e.creditsExhausted?d=u?{severity:`danger`,text:`Auto-reload was unsuccessful`,action:`Update your card`}:{severity:`danger`,text:`Out of credits`,action:`Set up auto-reload`}:t?.lowBalance&&!r&&(d=u?{severity:`danger`,text:`Auto-reload was unsuccessful`,action:`Update your card`}:{severity:`warn`,text:`Running low on credits`,action:`Set up auto-reload`}),{amount:a,caption:s,grant:o,dailyBlocked:l,banner:d}}function uX(e){let{usage:t,onRefreshUsage:n}=e;if(t.spendableMicros===null||t.freeTier&&t.creditsExhausted)return null;let r=lX(t);return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`settings-row`,children:(0,U.jsx)(`span`,{className:`settings-label`,children:`Operator credits`})}),(0,U.jsxs)(`div`,{className:`settings-split`,children:[(0,U.jsx)(`div`,{className:`settings-credits`,children:r.amount}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:()=>fX(n),children:(0,U.jsx)(`span`,{children:`Get credits`})})]}),r.caption?(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:r.caption}):null,r.grant?(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:r.grant}):null,r.dailyBlocked?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger settings-usage-subtext`,children:r.dailyBlocked}):null,r.banner?(0,U.jsxs)(`div`,{className:`feedback-banner feedback-${r.banner.severity} is-inset`,role:`status`,children:[(0,U.jsx)(`span`,{children:r.banner.text}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:()=>fX(n),children:(0,U.jsx)(`span`,{children:r.banner.action})})]}):null]})}function dX(e){return e.usage.credits?.plan===`credits`?(0,U.jsx)(uX,{usage:e.usage,onRefreshUsage:e.onRefreshUsage}):(0,U.jsx)(cX,{usage:e.usage})}function fX(e){if(window.ReactNativeWebView){window.ReactNativeWebView.postMessage(JSON.stringify({type:`castle-open-credits`}));return}if(!window.open(`https://castle.xyz/credits`,`_blank`))return;pX?.();let t=()=>{document.visibilityState===`visible`&&(pX?.(),e())};pX=()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t),pX=null},document.addEventListener(`visibilitychange`,t),window.addEventListener(`focus`,t)}var pX=null;function mX(e){let t=e.providers.filter(e=>e.key?.present||e.login?.loggedIn).map(e=>e.label);return(0,U.jsxs)(`div`,{className:`settings-split`,children:[t.length>0?(0,U.jsxs)(`div`,{className:`settings-split-copy`,children:[(0,U.jsx)(`div`,{className:`settings-credits`,children:`Use your own agent provider`}),(0,U.jsxs)(`div`,{className:`settings-usage-subtext`,children:[`Connected: `,t.join(`, `)]})]}):(0,U.jsx)(`div`,{className:`settings-credits`,children:`Use your own agent provider`}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:e.onOpen,children:(0,U.jsx)(`span`,{children:t.length>0?`Manage providers`:`Add provider`})})]})}function hX(e){let{login:t}=e,[n,r]=g.useState(``),i=()=>{n.trim()&&e.onSubmitCode(n.trim())};return(0,U.jsxs)(U.Fragment,{children:[t.url?(0,U.jsxs)(`div`,{className:`castle-key-login`,children:[(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Open this link to sign in, then come back here.`}),(0,U.jsx)(`a`,{className:`castle-key-url`,href:t.url,target:`_blank`,rel:`noreferrer noopener`,children:t.url})]}):(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Starting sign-in…`}),t.phase===`awaiting-code`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Paste the code the browser shows you:`}),(0,U.jsx)(`input`,{className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,value:n,placeholder:`code`,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i()}}),t.message?(0,U.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null]}):null,t.phase===`verifying`?(0,U.jsx)(`div`,{className:`castle-key-stored`,children:`Finishing sign-in…`}):null,t.phase===`error`?(0,U.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null,(0,U.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:e.onCancel,children:t.phase===`error`?`Close`:`Cancel`}),t.phase===`awaiting-code`?(0,U.jsx)(`button`,{type:`button`,onClick:i,disabled:!n.trim(),children:`Submit`}):null]})]})}function gX(e){let t=e.accounts.providers,n=e.accounts.login,[r,i]=g.useState(()=>(t.find(e=>e.key?.present||e.login?.loggedIn)??t[0])?.id??``),[a,o]=g.useState(``),[s,c]=g.useState(null),l=(n?t.find(e=>e.login?.provider===n.provider):null)??t.find(e=>e.id===r)??t[0]??null,u=g.useRef(e.onClose);u.current=e.onClose;let d=n!==null;g.useEffect(()=>{let e=e=>{e.key===`Escape`&&!d&&u.current()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[d]);let f=g.useRef(null);if(g.useEffect(()=>{if(n){f.current=n.provider;return}let e=f.current;e!==null&&(f.current=null,t.find(t=>t.login?.provider===e)?.login?.loggedIn&&u.current())}),!l)return null;let p=!!l.login?.loggedIn,m=!!l.key?.present,h=p||m,_=()=>{let t=a.trim();if(t){if(t.length>500){c(`That key is too long.`);return}if([...t].some(e=>{let t=e.codePointAt(0)??0;return t<32||t===127})){c(`That key contains invalid characters.`);return}e.onSave(l.id,t),e.onClose()}};return(0,tb.createPortal)((0,U.jsx)(`div`,{className:`castle-modal-scrim`,onMouseDown:n?void 0:e.onClose,children:(0,U.jsxs)(`div`,{className:`castle-modal`,onMouseDown:e=>e.stopPropagation(),children:[(0,U.jsx)(`div`,{className:`castle-key-heading`,children:n?`Sign in to ${l.label}`:`Your account`}),n?null:(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Run the operator on your own account and bypass Castle's daily limit.`}),t.length>1&&!n?(0,U.jsx)(`div`,{className:`castle-key-tabs`,children:t.map(e=>(0,U.jsx)(`button`,{type:`button`,className:`castle-key-tab`+(e.id===l.id?` active`:``),onClick:()=>{i(e.id),o(``),c(null)},children:e.label},e.id))}):null,n?(0,U.jsx)(hX,{login:n,onSubmitCode:e.onSubmitCode,onCancel:e.onCancelLogin}):(0,U.jsxs)(U.Fragment,{children:[h?(0,U.jsxs)(U.Fragment,{children:[p?(0,U.jsxs)(`div`,{className:`castle-key-row`,children:[(0,U.jsxs)(`span`,{children:[`Signed in with your `,l.label,` account.`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>{e.onLogout(l.id),e.onClose()},children:`Sign out`})]}):null,m?(0,U.jsxs)(`div`,{className:`castle-key-row`,children:[(0,U.jsxs)(`span`,{children:[`API key saved (`,l.key?.hint,`).`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemove(l.id),e.onClose()},children:`Remove`})]}):null]}):(0,U.jsxs)(U.Fragment,{children:[l.login?(0,U.jsxs)(`button`,{type:`button`,className:`castle-key-signin`,onClick:()=>e.onStartLogin(l.id),children:[`Sign in with your `,l.label,` account`]}):null,l.login&&l.key?(0,U.jsx)(`div`,{className:`castle-key-or`,children:`or`}):null,l.key?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`castle-key-field-label`,children:`Add API key`}),(0,U.jsx)(`input`,{type:`password`,className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,"data-1p-ignore":!0,"data-lpignore":`true`,value:a,placeholder:l.key.placeholder,onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&_()}}),s?(0,U.jsx)(`div`,{className:`castle-key-error`,children:s}):null]}):null]}),(0,U.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:e.onClose,children:`Cancel`}),!h&&l.key?(0,U.jsx)(`button`,{type:`button`,onClick:_,disabled:!a.trim(),children:`Save`}):null]})]})]})}),document.body)}function _X(e){let{settings:t,onSetSetting:n,onClose:r}=e,i=e.usage?.credits?.plan===`credits`?e.usage.spendableMicros!==null:eX(e.usage)!==null,a=e.accounts.providers.some(e=>e.key?.present||e.login?.loggedIn),o=e.accounts.providers.some(e=>e.id===`anthropic`&&(e.key?.present||e.login?.loggedIn)),s=e.accounts.providers.length>0&&(i||a),c=g.useRef(null),l=e.usage?.blockedClaudeModels??[];return Sw(c,r,e.triggerRef),(0,tb.createPortal)((0,U.jsxs)(`div`,{className:`popover settings-popover`,ref:c,style:Ew(c,e.triggerRef,[t,i,s,e.usage,o]),onMouseDown:e=>e.stopPropagation(),children:[i&&e.usage?(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)(dX,{usage:e.usage,onRefreshUsage:e.onRefreshUsage})}):null,s?(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)(mX,{providers:e.accounts.providers,onOpen:e.onOpenKeys})}):null,(0,U.jsx)(`div`,{className:`settings-model-pickers`,children:[`router`,`tasks`].map(r=>(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)($Y,{role:r,settings:t,warnings:e.warnings,usage:e.usage,blockedClaudeModels:l,hasAnthropicAccount:o,onSetSetting:n,onSetSettings:e.onSetSettings})},r))})]}),document.body)}function vX(e){let{spec:t,interactive:n,answers:r,onSubmit:i}=e,[a,o]=g.useState({}),s=n?a:r??{},c=(e,t)=>{n&&o(n=>{let r=(n[e.id]??[]).filter(e=>e!==gY),i=r.filter(t=>!e.options.includes(t)),a=yY(e,r);if(e.multi){let r=a.includes(t)?a.filter(e=>e!==t):[...a,t];return{...n,[e.id]:[...r,...i]}}return{...n,[e.id]:a[0]===t&&i.length===0?[]:[t]}})},l=e=>{n&&o(t=>({...t,[e.id]:vY(t[e.id])?[]:[gY]}))},u=g.useRef({}),d=e=>{if(!n)return;let t=!xY(e,s[e.id]);(0,tb.flushSync)(()=>{o(t=>{let n=t[e.id]??[];if(xY(e,n))return{...t,[e.id]:yY(e,n)};let r=yY(e,n),i=bY(e,n);return{...t,[e.id]:e.multi?[...r,i]:[i]}})}),t&&u.current[e.id]?.focus()},f=(e,t)=>{n&&o(n=>{let r=yY(e,n[e.id]);return{...n,[e.id]:e.multi?[...r,t]:[t]}})};return(0,U.jsxs)(`div`,{className:`picker${n?``:` picker-locked`}`,children:[t.questions.map(e=>{let t=s[e.id],r=vY(t),i=!r&&xY(e,t),a=r?``:bY(e,t),o=!n||r;return(0,U.jsxs)(`fieldset`,{className:`picker-q${r?` is-skipped`:``}`,disabled:!n,children:[(0,U.jsxs)(`legend`,{className:`picker-q-head`,children:[(0,U.jsx)(`span`,{className:`picker-q-label`,children:e.q}),(0,U.jsx)(`button`,{type:`button`,className:`picker-skip text-style-smallcaps${r?` is-on`:``}`,"aria-pressed":r,disabled:!n,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(e)},children:`Skip`})]}),(0,U.jsxs)(`div`,{className:`picker-options`,children:[e.options.map(n=>{let i=!r&&(t??[]).includes(n);return(0,U.jsxs)(`label`,{className:`picker-option${i?` is-checked`:``}`,children:[(0,U.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:i,disabled:o,onChange:()=>c(e,n)}),(0,U.jsx)(`span`,{children:n})]},n)}),(0,U.jsxs)(`div`,{className:`picker-option picker-option-other${i?` is-checked`:``}`,children:[(0,U.jsxs)(`label`,{className:`picker-other-toggle`,children:[(0,U.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:i,disabled:o,"aria-label":`Other`,onChange:()=>d(e)}),i?null:(0,U.jsx)(`span`,{className:`picker-other-label`,children:`Other`})]}),i?(0,U.jsx)(`input`,{ref:t=>{u.current[e.id]=t},type:`text`,className:`picker-other-input`,value:a,disabled:o,"aria-label":`Other`,onChange:t=>f(e,t.target.value)}):null]})]})]},e.id)}),n?(0,U.jsx)(`div`,{className:`picker-actions`,children:(0,U.jsx)(`button`,{className:`button`,type:`button`,onClick:()=>{let e=kY(t,a);e&&i(a,e)},children:(0,U.jsx)(`span`,{children:`Submit`})})}):r?(0,U.jsx)(`div`,{className:`picker-actions`,children:(0,U.jsx)(`button`,{className:`button`,type:`button`,disabled:!0,children:(0,U.jsx)(`span`,{children:`Submitted`})})}):null]})}function yX(e){let{chips:t,interactive:n,onPick:r}=e,[i,a]=g.useState(null),o=n&&i===null;return(0,U.jsx)(`div`,{className:`chips`+(o?``:` chips-inert`),children:t.map(e=>(0,U.jsx)(`button`,{type:`button`,className:`chip`+(i===e?` is-picked`:``),disabled:!o,onClick:()=>{a(e),r(e)},children:e},e))})}function bX(){return(0,U.jsxs)(`div`,{className:`picker picker-skeleton`,"aria-hidden":`true`,children:[(0,U.jsx)(`span`,{className:`picker-skeleton-hint`,children:`preparing options…`}),(0,U.jsxs)(`div`,{className:`picker-q`,children:[(0,U.jsxs)(`div`,{className:`picker-q-head`,children:[(0,U.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-label`}),(0,U.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-skip`})]}),(0,U.jsxs)(`div`,{className:`picker-options`,children:[(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:84}}),(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:116}}),(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:72}})]})]})]})}function xX(e){let t=/^\[Editing (.+)\]$/,n=/^\[Reading (.+)\]$/,r=new Set;for(let n of e){let e=t.exec(n.trim());if(e)for(let t of e[1].split(`, `))r.add(t)}let i=[];for(let t of e){let e=n.exec(t.trim());if(e){let t=e[1].split(`, `).filter(e=>!r.has(e));if(t.length===0)continue;i.push(`[Reading ${t.join(`, `)}]`);continue}i.push(t)}return i}function SX(e){let t=/^\[([A-Za-z]+)\s+(.+)\]$/,n=[];for(let r of e){let e=t.exec(r.trim());if(e){let r=n.length?t.exec(n[n.length-1].trim()):null;if(r&&r[1]===e[1]){r[2].split(`, `).includes(e[2])||(n[n.length-1]=`[${e[1]} ${r[2]}, ${e[2]}]`);continue}}n.push(r)}return n}function CX(e){return e.detail?(0,U.jsxs)(`details`,{className:`msg-error-detail`,children:[(0,U.jsxs)(`summary`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`warning`,className:`icon-inline`}),(0,U.jsx)(`span`,{children:`Details`}),(0,U.jsx)(W,{name:`chevron-right`,className:`icon-inline thinking-caret`})]}),(0,U.jsxs)(`div`,{className:`msg-error-detail-body`,children:[(0,U.jsx)(`p`,{className:`msg-error-detail-hint`,children:`View the full text in the browser console`}),(0,U.jsx)(`pre`,{children:e.detail})]})]}):null}function wX(e){let t=ZJ(),n=g.useRef(null),r=g.useRef(!0);return g.useLayoutEffect(()=>{let e=n.current;e&&r.current&&(e.scrollTop=e.scrollHeight)},[e.lines]),(0,U.jsx)(`div`,{className:`task-feed`,ref:n,onScroll:()=>{let e=n.current;e&&(r.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},onClick:e=>e.stopPropagation(),children:SX(xX(e.lines)).map((e,n)=>{let r=/^\[(.+)\]$/.exec(e.trim());return r?(0,U.jsx)(`div`,{className:`task-feed-tool`,children:r[1]},n):(0,U.jsx)(`div`,{className:`task-feed-msg`,onClick:t,dangerouslySetInnerHTML:YJ(e)},n)})})}function TX(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function EX(e,t,n){return t?`${e} · ${t}`:n?`${e} · Worked for ${n}`:e}function DX(e){let[t,n]=g.useState(()=>Date.now());g.useEffect(()=>{if(e.status!==`running`)return;let t=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(t)},[e.status]);let r=e.startedAt?Date.parse(e.startedAt):null,i=e.finishedAt?Date.parse(e.finishedAt):null,a=C.includes(e.status),o=e.status===`done`?100:a?e.progress:Math.min(e.progress,95),s=e.status===`running`?e.phase?.trim()||jY[e.avatar??``]||`Working`:e.status===`waiting`?`Queued`:e.status===`blocked`?`Blocked`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`interrupted`?`Interrupted`:e.status,c=e.status===`running`&&r!==null?TX(t-r):null,l=a&&r!==null&&i!==null?TX(i-r):null;return{pct:o,avatar:NY(e),stage:s,elapsed:c,workedFor:l,finished:a,display:oY(e)}}function OX(e){let{task:t,onAck:n}=e,r=e.variant===`archive`,i=ZJ(),[a,o]=g.useState(t.status===`failed`);g.useEffect(()=>{t.status===`failed`&&o(!0)},[t.status]);let s=()=>{o(e=>!e)},{pct:c,avatar:l,stage:u,elapsed:d,workedFor:f,finished:p,display:m}=DX(t);return(0,U.jsxs)(`div`,{className:`task${a?` open`:``}`,onClick:s,children:[(0,U.jsxs)(`div`,{className:`task-row`,children:[(0,U.jsx)(`div`,{className:`pie`,style:{"--pct":c},children:(0,U.jsx)(`div`,{className:`avatar`,style:{background:l.color},children:(0,U.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:l.icon})})}),(0,U.jsxs)(`div`,{className:`task-meta`,children:[(0,U.jsx)(`div`,{className:`task-name`,children:(0,U.jsx)(`span`,{className:`tn`,children:t.title})}),(0,U.jsx)(`div`,{className:`task-sub`,children:EX(u,d,f)})]}),(0,U.jsxs)(`div`,{className:`task-actions`,children:[p&&!r?(0,U.jsx)(`button`,{className:`button button-icon task-action`,type:`button`,title:`Clear`,"aria-label":`Clear ${t.title}`,onClick:e=>{e.stopPropagation(),n(t.id,!1)},children:(0,U.jsx)(W,{name:`archive`})}):null,e.onOpen?(0,U.jsx)(`button`,{className:`button button-icon task-action`,type:`button`,title:`Open`,"aria-label":`Open ${t.title}`,onClick:n=>{n.stopPropagation(),e.onOpen?.(t)},children:(0,U.jsx)(W,{name:`chevron-right`})}):null]})]}),(0,U.jsxs)(`div`,{className:`task-body`,children:[a&&t.status===`running`&&e.feed&&e.feed.length>0?(0,U.jsx)(wX,{lines:e.feed}):null,a&&t.status!==`running`&&m.error?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger`,children:m.error}):null,a&&t.status!==`running`&&m.notes?(0,U.jsx)(`div`,{className:`task-notes`,onClick:i,dangerouslySetInnerHTML:YJ(m.notes)}):null,a&&t.status===`failed`?(0,U.jsx)(CX,{detail:t.errorDetail}):null,a?(0,U.jsx)(kX,{frames:t.playtestFrames}):null]})]})}function kX(e){let t=e.frames??[];return t.length===0?null:(0,U.jsxs)(`div`,{className:`task-playtest-frames`,children:[(0,U.jsxs)(`div`,{className:`task-playtest-frames-label`,children:[`Playtest frames (`,t.length,`)`]}),(0,U.jsx)(`div`,{className:`task-playtest-frames-row`,children:t.map(e=>(0,U.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:(0,U.jsx)(`img`,{className:`task-playtest-frame`,src:e,alt:`playtest frame`})},e))})]})}function AX(e){return e.filter(e=>!(e.acknowledged&&C.includes(e.status)))}function jX(e){let t=g.useRef(null),n=g.useRef(!0),r=g.useRef(0),[i,a]=g.useState(!1),o=AX(e.tasks);g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.tasks]),g.useEffect(()=>()=>window.clearTimeout(r.current),[]);let s=()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24,a(!0),window.clearTimeout(r.current),r.current=window.setTimeout(()=>a(!1),900))};if(o.length===0)return null;let c=o.filter(e=>C.includes(e.status));return(0,U.jsxs)(`div`,{id:`task-board`,className:`task-stack${i?` scrolling`:``}`,ref:t,onScroll:s,children:[(0,U.jsxs)(`div`,{className:`task-board-header`,children:[(0,U.jsxs)(`button`,{type:`button`,className:`button`,onClick:e.onOpenTasks,children:[(0,U.jsx)(`span`,{children:`Tasks`}),(0,U.jsx)(W,{name:`chevron-right`})]}),c.length>0?(0,U.jsxs)(`button`,{type:`button`,className:`button`,onClick:()=>{for(let t of c)e.onAck(t.id,!1)},children:[(0,U.jsx)(W,{name:`archive`}),(0,U.jsx)(`span`,{children:`Clear completed`}),(0,U.jsx)(`span`,{className:`button-badge`,children:c.length})]}):null]}),o.map(t=>(0,U.jsx)(OX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask},t.id))]})}function MX(e){let{task:t}=e,{pct:n,avatar:r,stage:i,elapsed:a,workedFor:o}=DX(t);return(0,U.jsx)(`header`,{className:`task-page-header`,children:(0,U.jsxs)(`div`,{className:`task-row`,children:[(0,U.jsx)(`div`,{className:`pie`,style:{"--pct":n},children:(0,U.jsx)(`div`,{className:`avatar`,style:{background:r.color},children:(0,U.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:r.icon})})}),(0,U.jsxs)(`div`,{className:`task-meta`,children:[(0,U.jsx)(`div`,{className:`task-name`,children:(0,U.jsx)(`span`,{className:`tn`,children:t.title})}),(0,U.jsx)(`div`,{className:`task-sub`,children:EX(i,a,o)})]})]})})}function NX(e){let{task:t}=e,n=ZJ(),r=g.useRef(null),i=g.useRef(!0),a=e.feed??[],o=oY(t),s=t.status===`running`,c=a.length>0,l=!s&&(!!o.error||!!o.notes);return g.useLayoutEffect(()=>{i.current=!0},[t.id]),g.useLayoutEffect(()=>{let e=r.current;e&&i.current&&(e.scrollTop=e.scrollHeight)},[t.id,e.feed,o.notes,o.error,t.status,t.playtestFrames]),(0,U.jsxs)(`div`,{className:`task-page`,children:[(0,U.jsx)(MX,{task:t}),(0,U.jsxs)(`div`,{className:`task-page-body`,ref:r,onScroll:()=>{let e=r.current;e&&(i.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},children:[c?(0,U.jsx)(wX,{lines:a}):null,l&&o.error?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger`,children:o.error}):null,l&&o.notes?(0,U.jsxs)(`div`,{className:`task-notes`,onClick:n,children:[(0,U.jsx)(`p`,{className:`task-report-label`,children:`Report`}),(0,U.jsx)(`div`,{dangerouslySetInnerHTML:YJ(o.notes)})]}):null,t.status===`failed`?(0,U.jsx)(CX,{detail:t.errorDetail}):null,(0,U.jsx)(kX,{frames:t.playtestFrames}),!c&&!l&&!(t.playtestFrames&&t.playtestFrames.length>0)?(0,U.jsx)(`p`,{className:`task-page-empty`,children:`No activity yet.`}):null]})]})}function PX(e){let t=AX(e.tasks),n=fY(e.tasks);return(0,U.jsxs)(`div`,{className:`task-page-body task-board-page`,children:[t.length>0?(0,U.jsx)(`div`,{className:`task-stack`,children:t.map(t=>(0,U.jsx)(OX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask},t.id))}):null,n.length>0?(0,U.jsxs)(`div`,{className:`task-archive task-stack`,children:[(0,U.jsx)(`div`,{className:`task-archive-heading text-style-smallcaps`,children:`Cleared`}),n.map(t=>(0,U.jsx)(OX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask,variant:`archive`},t.id))]}):null,t.length===0&&n.length===0?(0,U.jsx)(`p`,{className:`task-page-empty`,children:`No tasks yet.`}):null]})}function FX(e){let{msg:t,onPickerSubmit:n,onChip:r,chipsLive:i=!1,interactive:a=!1}=e,o=ZJ();if(t.role===`log`)return(0,U.jsx)(`div`,{className:`msg toolline`,children:t.text});if(t.role===`user`)return(0,U.jsxs)(`div`,{className:`msg user`,children:[(t.attachments??[]).map(e=>(0,U.jsx)(`img`,{className:`msg-image`,src:e,alt:``},e)),t.text?(0,U.jsx)(RY,{text:t.text}):null]});let s=t.status===`streaming`,c=DY(t.text,s),l=OY(c)||t.planUpdated===!0;if(!s&&!l)return null;let u=!s&&!t.pickerAnswers&&a,d=-1;c.forEach((e,t)=>{e.kind===`md`&&e.text.trim()!==``&&(d=t)});let f=c.some(e=>e.kind===`ask`||e.kind===`ask-pending`),p=s&&d===-1&&!f||!!(s&&t.activity),m=t.activity??`Thinking`;return(0,U.jsxs)(`div`,{className:`assistant-turn`,onClick:o,children:[t.thinking&&t.thinking.trim()?(0,U.jsxs)(`details`,{className:`msg-thinking`+(p?` is-active`:``),children:[(0,U.jsxs)(`summary`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`lightbulb`,className:`icon-inline`}),(0,U.jsx)(`span`,{className:`thinking-label`,children:p?m:PY(t.thinkingMs)}),(0,U.jsx)(W,{name:`chevron-right`,className:`icon-inline thinking-caret`})]}),(0,U.jsx)(`div`,{className:`msg-thinking-body`,dangerouslySetInnerHTML:YJ(t.thinking??``)})]}):p?(0,U.jsxs)(`div`,{className:`operator-line msg-thinking is-active`,children:[(0,U.jsx)(W,{name:`lightbulb`,className:`icon-inline`}),(0,U.jsx)(`span`,{className:`thinking-label`,children:m})]}):null,c.map((e,a)=>{if(e.kind===`ask-pending`)return(0,U.jsx)(bX,{},a);if(e.kind===`chips`)return(0,U.jsx)(yX,{chips:e.chips,interactive:!s&&i,onPick:r},a);if(e.kind===`ask`)return(0,U.jsx)(vX,{spec:e.spec,interactive:u,answers:t.pickerAnswers,onSubmit:(e,r)=>n(t,e,r)},a);if(!e.text.trim())return null;let o=[`msg`,`assistant`,`md`];return s&&a===d&&o.push(`streaming`),t.status===`error`&&o.push(`errbubble`),(0,U.jsx)(`div`,{className:o.join(` `),dangerouslySetInnerHTML:YJ(e.text)},a)}),s?null:(0,U.jsx)(CX,{detail:t.errorDetail}),t.planUpdated?(0,U.jsx)(IY,{}):null,t.interrupted?(0,U.jsxs)(`div`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`square`,className:`icon-inline`}),(0,U.jsx)(`span`,{children:`Interrupted by your next message`})]}):null]})}function IX(e){let t=g.useRef(null),n=g.useRef(null),r=g.useRef(0),i=g.useRef(!0),a=g.useRef(0),o=g.useRef(0),[s,c]=g.useState(!1),l=g.useRef(!1),u=g.useCallback(()=>{l.current=!0,c(!0)},[]),d=g.useCallback(()=>{let e=t.current;if(!e)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.abs(e.scrollTop-n)>1;e.scrollTop=n,r&&(a.current=typeof performance<`u`?performance.now():Date.now())},[]);e.pinThreadRef.current=()=>{i.current&&d()};let f=g.useCallback(()=>{d();let e=t.current;e&&e.clientHeight>0&&u()},[d,u]);g.useLayoutEffect(()=>{if(!i.current)return;f();let e=requestAnimationFrame(f),t=window.setTimeout(f,250),n=window.setTimeout(u,500);return()=>{cancelAnimationFrame(e),clearTimeout(t),clearTimeout(n)}},[e.messages,f,u]),g.useEffect(()=>{let e=t.current;if(!e)return;o.current=e.clientHeight;let a=new ResizeObserver(()=>{o.current=e.clientHeight,i.current?f():e.scrollTop=e.scrollHeight-e.clientHeight-r.current});return a.observe(e),n.current&&a.observe(n.current),()=>a.disconnect()},[f]);let p=()=>{let e=t.current;if(!e||!l.current||(typeof performance<`u`?performance.now():Date.now())-a.current<200)return;let n=e.clientHeight,s=n!==o.current;o.current=n,!s&&(r.current=e.scrollHeight-e.scrollTop-e.clientHeight,i.current=r.current<48)},m=RX(e.messages),h=zX(e.messages);return(0,U.jsx)(`div`,{id:`chat-messages`,className:`chat-scroll`,"data-castle-allow-select":``,ref:t,onScroll:p,children:(0,U.jsxs)(`div`,{className:`chat-thread`+(s?` ready`:``),ref:n,children:[e.messages.length===0?(0,U.jsx)(`div`,{id:`chat-empty`,children:`Tell the agent what you want to make.`}):null,e.messages.map(t=>(0,U.jsx)(FX,{msg:t,interactive:t.id===m,chipsLive:t.id===h,onPickerSubmit:e.onPickerSubmit,onChip:e.onChip},t.id))]})})}function LX(e){return e.role!==`assistant`||e.pickerAnswers?!1:DY(e.text).some(e=>e.kind===`ask`)}function RX(e){for(let t=e.length-1;t>=0;t--)if(LX(e[t]))return e[t].id;return null}function zX(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(n.role===`assistant`){if(n.status===`streaming`)return null;if(DY(n.text).some(e=>e.kind===`chips`))return n.id}}return null}function BX(e,t){for(let n of Array.from(e)){if(!n.type.startsWith(`image/`))continue;let e=new FileReader;e.onload=()=>{typeof e.result==`string`&&t({name:n.name,dataUrl:e.result})},e.readAsDataURL(n)}}function VX(e){return e.pending.length===0?null:(0,U.jsx)(`div`,{id:`chat-pending`,children:e.pending.map((t,n)=>(0,U.jsx)(`img`,{className:`operator-thumb`,src:t.dataUrl,alt:t.name,title:`remove`,onClick:()=>e.onRemove(n)},`${t.name}-${n}`))})}function HX(e){return e.queued.length===0?null:(0,U.jsx)(`div`,{className:`chat-queue`,onMouseDown:e=>e.preventDefault(),children:e.queued.map((t,n)=>(0,U.jsxs)(`div`,{className:`queue-row`,children:[(0,U.jsx)(`span`,{className:`queue-snippet`,children:t.length>60?`${t.slice(0,60)}\u2026`:t}),(0,U.jsx)(`button`,{className:`button`,type:`button`,tabIndex:-1,title:`Send now — interrupts the turn`,onClick:e.onInterrupt,children:(0,U.jsx)(`span`,{children:`Send now`})}),(0,U.jsx)(`button`,{className:`button button-icon button-quiet`,type:`button`,tabIndex:-1,title:`Remove from queue`,"aria-label":`Remove`,onClick:()=>e.onCancelQueued(n),children:(0,U.jsx)(W,{name:`times`})})]},n))})}function UX(e,t){if(!e)return;e.style.height=`auto`;let n=Number.parseFloat(window.getComputedStyle(e).lineHeight),r=Number.isFinite(n)?Math.ceil(n):21,i=t.length===0?r:Math.min(e.scrollHeight,120);e.style.height=i>0?`${i}px`:``}function WX(e){let{running:t,queued:n}=e,[r,i]=g.useState(``),[a,o]=g.useState(!1),[s,c]=g.useState(!1),l=g.useRef(null),[u,d]=g.useState([]),[f,p]=g.useState(!1);g.useEffect(()=>{t||p(!1)},[t]);let m=g.useRef(null),h=g.useRef(null),_=iY({inputRef:m,anchorRef:h,setValue:i});g.useLayoutEffect(()=>{UX(m.current,r),e.pinThreadRef.current()},[r,u.length,n.length,e.pinThreadRef]);let v=e=>{d(t=>t.length>=6?t:[...t,e])},y=()=>{let t=r.trim();!t&&u.length===0||(e.onSend(t,u,_.attachedIn(t)),i(``),d([]),_.clear())},b=r.trim().length>0||u.length>0,x=e=>{let t=e.target;h.current?.contains(t)&&(t instanceof Element&&t.closest(`.composer-settings .button, #chat-send`)||m.current?.focus())},S=t&&!b;return(0,U.jsxs)(`div`,{className:`operator-composer`,children:[(0,U.jsx)(VX,{pending:u,onRemove:e=>d(t=>t.filter((t,n)=>n!==e))}),_.overlay,(0,U.jsxs)(`div`,{className:`chat-input`,ref:h,children:[(0,U.jsx)(HX,{queued:n,onInterrupt:e.onInterrupt,onCancelQueued:e.onCancelQueued}),(0,U.jsxs)(`div`,{className:`ta`,onClick:x,children:[(0,U.jsx)(`textarea`,{id:`chat-input`,className:`ta-text`,ref:m,rows:1,placeholder:t?`Queue a message…`:`Message the operator`,value:r,onChange:e=>{i(e.target.value),_.sync()},onSelect:_.sync,onPaste:e=>{let t=e.clipboardData?.files;t&&t.length>0&&(e.preventDefault(),BX(t,v))},onKeyDown:e=>{_.handleKeyDown(e)||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),y())}}),(0,U.jsxs)(`div`,{className:`ta-bottom`,onMouseDown:e=>e.preventDefault(),children:[(0,U.jsxs)(`div`,{className:`composer-settings`,children:[(0,U.jsxs)(`button`,{ref:l,className:[`button`,`button-quiet`,nX(e.usage)].filter(Boolean).join(` `),type:`button`,tabIndex:-1,title:`Agent & model settings`,"aria-label":`Agent & model settings`,"aria-pressed":a,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:()=>{a||e.onRefreshUsage(),o(e=>!e)},children:[(0,U.jsx)(`span`,{children:XY(e.settings,e.usage)}),VY]}),a?(0,U.jsx)(_X,{settings:e.settings,warnings:e.settingsWarnings,usage:e.usage,accounts:e.accounts,triggerRef:l,onSetSetting:e.onSetSetting,onSetSettings:e.onSetSettings,onOpenKeys:()=>c(!0),onRefreshUsage:e.onRefreshUsage,onClose:()=>o(!1)}):null,s?(0,U.jsx)(gX,{accounts:e.accounts,onSave:e.onSetCredential,onRemove:e.onClearCredential,onStartLogin:e.onStartLogin,onSubmitCode:e.onSubmitLoginCode,onCancelLogin:e.onCancelLogin,onLogout:e.onLogout,onClose:()=>c(!1)}):null]}),(0,U.jsx)(`button`,{id:`chat-send`,className:`button button-icon composer-action`,type:`button`,tabIndex:-1,title:S?f?`Stopping…`:`Stop`:`Send`,"aria-label":S?f?`Stopping`:`Stop`:`Send`,disabled:!S&&!b||S&&f,onClick:()=>{S?(p(!0),e.onInterrupt()):y()},children:S?BY:zY})]})]})]})]})}function GX(e){let{agent:t,mobile:n,active:r}=e,{messages:i,tasks:a,feeds:o,settings:s,running:c,queued:l}=t,u=uY(n),[d,f]=g.useState(null),p=g.useRef(()=>{}),m=dY(d),h=e=>{u.openView(e.id)};Tb(()=>!r||u.view===`chat`||u.view===`tasks`&&!n?!1:(u.goChat(),!0));let _=(e,n,r)=>{t.submitPicker(e.id,n,r)},v=e=>{t.sendUserMessage(e,[],[])},y=u.view!==`chat`&&u.view!==`tasks`?a.find(e=>e.id===u.view):void 0;return(0,U.jsxs)(`div`,{id:`chat-host`,ref:f,children:[m?(0,U.jsx)(pY,{view:u.view,openIds:u.openIds,tasks:a,mobile:n,onChat:u.goChat,onSelect:u.openView,onClose:u.closeView,onReorder:u.reorderOpenIds,slot:m}):null,(0,U.jsx)(`div`,{className:`operator-inset`,children:u.view===`chat`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(jX,{tasks:a,feeds:o,onAck:t.ackTask,onOpenTask:h,onOpenTasks:()=>u.openView(cY)}),AX(a).length>0?(0,U.jsx)(`div`,{className:`chat-divider`,"aria-hidden":`true`}):null,(0,U.jsx)(IX,{messages:i,onPickerSubmit:_,onChip:v,pinThreadRef:p})]}):u.view===`tasks`?(0,U.jsx)(PX,{tasks:a,feeds:o,onAck:t.ackTask,onOpenTask:h}):y?(0,U.jsx)(NX,{task:y,feed:o[y.id]}):(0,U.jsx)(`p`,{className:`task-page-empty`,children:`This task is gone.`})}),(0,U.jsx)(WX,{pinThreadRef:p,running:c,queued:l,onSend:t.sendUserMessage,onInterrupt:t.interrupt,onCancelQueued:t.cancelQueued,settings:s,settingsWarnings:t.settingsWarnings,usage:t.usage,accounts:t.accounts,onSetSetting:t.setSetting,onSetSettings:t.setSettings,onRefreshUsage:t.refreshUsage,onSetCredential:t.setCredential,onClearCredential:t.clearCredential,onStartLogin:t.startLogin,onSubmitLoginCode:t.submitLoginCode,onCancelLogin:t.cancelLogin,onLogout:t.logout})]})}function KX(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function qX(e,t){return e.messageId===t.messageId&&KX(e.taskIds,t.taskIds)}function JX(e,t,n,r,i){if(!t)return i;let a=n[n.length-1]??``;return e||i.messageId===void 0?{messageId:a,taskIds:r}:i.messageId!==``&&n.length>0&&!n.includes(i.messageId)?{messageId:a,taskIds:i.taskIds}:i.taskIds===void 0?{messageId:i.messageId,taskIds:r}:i}function YX(e,t){if(t===void 0)return 0;if(t===``)return e.length;let n=e.indexOf(t);return n<0?0:e.length-n-1}function XX(e,t){if(t===void 0)return 0;let n=new Set(t),r=0;for(let t of e)n.has(t)||(r+=1);return r}function ZX(e,t,n){return YX(e,n.messageId)+XX(t,n.taskIds)}var QX=`castle-operator-seen-v1`,$X=`castle-operator-seen-v2`;function eZ(){try{let e=localStorage.getItem($X);if(e!==null){let t=JSON.parse(e);if(t&&typeof t==`object`){let e=t,n=e.taskIds;return{messageId:typeof e.messageId==`string`?e.messageId:void 0,taskIds:Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:void 0}}}let t=localStorage.getItem(QX);if(t!==null)return{messageId:t,taskIds:void 0}}catch{}return{messageId:void 0,taskIds:void 0}}function tZ(e,t){try{localStorage.setItem($X,JSON.stringify({messageId:e,taskIds:t}))}catch{}}function nZ(e){let t=[];for(let n of e)n.role===`assistant`&&n.status!==`streaming`&&t.push(n.id);return t}function rZ(e){let t=[];for(let n of e)C.includes(n.status)&&!n.acknowledged&&t.push(n.id);return t}function iZ(){let[e,t]=g.useState(()=>document.visibilityState===`visible`);return g.useEffect(()=>{let e=()=>t(document.visibilityState===`visible`);return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),e}function aZ(e){let t=e.boundingClientRect;if(t.width<=0||t.height<=0)return!1;let n=e.intersectionRect;return n.width>=t.width-1&&n.height>=t.height-1}var oZ=Array.from({length:21},(e,t)=>t/20);function sZ(e){let[t,n]=g.useState(!1);return g.useEffect(()=>{if(!e){n(!1);return}let t=new IntersectionObserver(([e])=>n(e?aZ(e):!1),{threshold:oZ});return t.observe(e),()=>t.disconnect()},[e]),t}function cZ(e,t,n){let r=iZ(),i=sZ(n),a=r&&(t||i),[o,s]=g.useState(eZ),c=nZ(e.messages),l=rZ(e.tasks),u=JX(a,e.messages.length>0,c,l,o);return g.useEffect(()=>{qX(u,o)||(u.messageId!==void 0&&u.taskIds!==void 0&&tZ(u.messageId,u.taskIds),s(u))},[a,e.messages,e.tasks,o]),ZX(c,l,u)}var lZ=`castle-flow-layout:`,uZ=1;function dZ(e,t){if(e)try{let n={version:uZ,state:t};localStorage.setItem(lZ+e,JSON.stringify(n))}catch{}}function fZ(e,t,n){if(!e)return null;try{let r=localStorage.getItem(lZ+e);if(!r)return null;let i=JSON.parse(r);if(i.version!==uZ||!i.state||!Array.isArray(i.state.groups))return null;let a=an(yZ(bZ(i.state,t)),n);return a.groups.length===0?null:pt(a)}catch{return null}}var pZ=new Set([`operator`,`files`,`params`]);function mZ(e){let t=e.codeView;if(t===void 0)return e;let n={...e};return delete n.codeView,t&&(n.view=fe),n}function hZ(e,t){let n=t.some(t=>t.id===e.activeTabId)?e.activeTabId:t[0].id;return{...e,tabs:t,activeTabId:n}}var gZ=`params`;function _Z(e){return e.kind===`editor`&&e.view===gZ}function vZ(e,t){if(e.kind!==`params`||e.path===void 0||t.has(e.path))return e;let n={...e};return delete n.path,n}function yZ(e){if(!e.groups.some(e=>e.tabs.some(_Z)))return e;let t,n=!1,r=0,i=[];for(let a of e.groups){let e=[];for(let o of a.tabs){if(!_Z(o)){e.push(o);continue}let a={...o};if(delete a.view,n){e.push(a);continue}n=!0,t=o.path,r=i.length+1}if(e.length===0){r=Math.min(r,i.length);continue}i.push(hZ(a,e))}let a=ut(`params`,t);return i.splice(Math.min(r,i.length),0,ft([a],it(a))),{...e,groups:i}}function bZ(e,t){let n=new Set,r=[];for(let i of e.groups){let e=i.tabs.filter(e=>!(e.kind===`editor`&&e.path!==void 0&&!t.has(e.path))).map(mZ).map(e=>vZ(e,t));if(e.length===0)continue;let a=e.find(e=>e.kind!==`editor`);if(a&&pZ.has(a.kind)){if(n.has(a.kind))continue;n.add(a.kind)}r.push(hZ(i,e))}return{groups:r,activeGroupId:r.some(t=>t.id===e.activeGroupId)?e.activeGroupId:r[0]?.id??null,pinnedGroupId:r.some(t=>t.id===e.pinnedGroupId)?e.pinnedGroupId:null,maximizedGroupId:null}}var xZ=g.createContext(null),SZ={groups:[],activeGroupId:null,pinnedGroupId:null,maximizedGroupId:null};function CZ(e,t){let n=[];if(e.forEach((e,r)=>{let i=t.get(r);if(!i)return;let a=i.getBoundingClientRect(),o=e.left-a.left,s=e.top-a.top;Math.abs(o)<1&&Math.abs(s)<1||(i.style.transition=`none`,i.style.transform=`translate(${o}px, ${s}px)`,n.push(i))}),n.length!==0){n[0].getBoundingClientRect();for(let e of n){e.style.transition=`transform 180ms ease`,e.style.transform=`translate(0px, 0px)`;let t=()=>{e.style.transition=``,e.style.transform=``,e.removeEventListener(`transitionend`,t)};e.addEventListener(`transitionend`,t)}}}function wZ(e){return Array.isArray(e.column)}function TZ(e){return Array.isArray(e.tabs)}function EZ(e){let t=[],n=e=>{TZ(e)?t.push(...e.tabs??[]):t.push(e)};for(let t of e)wZ(t)?(t.column??[]).forEach(n):n(t);return t}function DZ(e){return e===`files`?`files`:e===`playtest`?`play`:e===`terminal`?`terminal`:e===`editor`?`editor`:e===`params`?`params`:null}var OZ=[{type:`files`},{type:`playtest`},{type:`editor`,file:`scenes/main.scene`}];function kZ(e,t){let n=e&&e.length>0?EZ(e):OZ,r=v?null:ut(`operator`),i=r?[ft([r],it(r))]:[],a=new Map,o=null;for(let e of n){let n=DZ(e.type);if(!n||n===`editor`&&!e.file)continue;if(n===`editor`&&e.file){let n=t(e.file),r=a.get(n);if(r){r.tabs.push(ut(`editor`,e.file));continue}let s=ut(`editor`,e.file),c=ft([s],it(s));a.set(n,c),i.push(c),o||=c.id;continue}let r=ut(n,e.file);i.push(ft([r],it(r)))}return{groups:i,activeGroupId:o??i[0]?.id??null,pinnedGroupId:null,maximizedGroupId:null}}function AZ(){let e=OT(),[t,n]=g.useState(()=>jT());return g.useEffect(()=>{if(e)return;let t=window.matchMedia(`(max-width: 768px)`),r=()=>n(t.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}function jZ(e){let t=e.target;if(!(t instanceof HTMLIFrameElement)||!t.classList.contains(`deck-frame`))return t;try{let n=t.contentDocument;if(!n)return t;let r=t.getBoundingClientRect();return n.elementFromPoint(e.clientX-r.left,e.clientY-r.top)??t}catch{return t}}function MZ(e,t){let n=e,r=!!(n?.ownerDocument&&n.ownerDocument!==t.ownerDocument),i=r?null:t.parentElement;for(;n&&n!==i;){if(n.nodeType===1){let e=getComputedStyle(n).overflowY;if((e===`auto`||e===`scroll`)&&n.scrollHeight>n.clientHeight+1)return!0}if(!r&&n===t)break;n=n.parentElement}return!1}function NZ(e,t,n){let r=e,i=t.parentElement;for(;r&&r!==i;){if(r.nodeType===1){let e=getComputedStyle(r),t=e.touchAction;if(t.includes(`pan-y`)&&!t.includes(`pan-x`))return!0;let i=e.overflowX;if(i===`auto`||i===`scroll`){let e=r.scrollWidth-r.clientWidth;if(e>1&&(n>0?r.scrollLeft>1:r.scrollLeft<e-1))return!0}}if(r===t)break;r=r.parentElement}return!1}function PZ(e,t){g.useEffect(()=>{if(!t)return;let n=e.current;if(!n)return;let r=e=>{e.deltaY!==0&&(n.scrollWidth<=n.clientWidth||!e.shiftKey&&MZ(jZ(e),n)||(n.scrollLeft+=e.deltaX-e.deltaY,e.preventDefault()))};return n.addEventListener(`wheel`,r,{passive:!1}),()=>n.removeEventListener(`wheel`,r)},[e,t])}function FZ(e,t,n,r){g.useLayoutEffect(()=>{let n=e.current,r=n?.querySelector(`.flow-row`);if(!n||!r)return;let i=()=>{let e=[...r.children].reverse().find(e=>e instanceof HTMLElement&&!e.classList.contains(`is-docked`)),i=e?.querySelector(`:scope .flow-card`),a=e?.classList.contains(`flow-card-slot`)&&i instanceof HTMLElement?i:e,o=a?a.offsetLeft+a.offsetWidth:0,s=t&&o>n.clientWidth?n.clientWidth/2:0;r.style.setProperty(`--flow-overscroll`,`${Math.round(s)}px`)};i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e,t,n,r])}function IZ(e,t,n){let r=e.getBoundingClientRect(),i=t.getBoundingClientRect();if(i.left>=r.left-1&&i.right<=r.right+1)return;let a=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;e.scrollTo({left:e.scrollLeft+(i.left+i.width/2-(r.left+r.width/2)),behavior:n??(a?`auto`:`smooth`)})}function LZ(e,t,n,r){return t||n||r||!e.pinnedGroupId?null:_t(e,e.pinnedGroupId)}function RZ(e,t){let n=e.get(t);return n||(n=document.createElement(`div`),n.className=`flow-card-host`,e.set(t,n)),n}function zZ(e,t,n,r,i,a){g.useLayoutEffect(()=>{if(e){for(let e of a.current.values())e.remove();return}let o=gt(t),s=new Set(o.map(e=>e.id));for(let e of o){let t=a.current.get(e.id);if(!t)continue;let o=e.id===n?r.current:i.current.get(e.id);o&&t.parentNode!==o&&o.appendChild(t)}for(let[e,t]of[...a.current])s.has(e)||(t.remove(),a.current.delete(e))}),g.useEffect(()=>()=>{for(let e of a.current.values())e.remove();a.current.clear()},[a])}function BZ(e,t){let n=g.useRef(new Map),r=g.useCallback(e=>{let t=n.current.get(e);if(t)return t.obj;let r={visible:!1,active:!1,activeCbs:new Set,visibleCbs:new Set,obj:{id:e,isVisible:()=>r.visible,isActive:()=>r.active,onDidActiveChange:e=>(r.activeCbs.add(e),()=>r.activeCbs.delete(e)),onDidVisibilityChange:e=>(r.visibleCbs.add(e),()=>r.visibleCbs.delete(e))}};return n.current.set(e,r),r.obj},[]);return g.useEffect(()=>{let r=new Set;for(let i of e.groups){let a=t?i.id===e.activeGroupId:!0;for(let t of i.tabs){r.add(t.id);let o=n.current.get(t.id);if(!o)continue;let s=i.activeTabId===t.id,c=a&&s,l=i.id===e.activeGroupId&&s;c!==o.visible&&(o.visible=c,o.visibleCbs.forEach(e=>e(c))),l!==o.active&&(o.active=l,o.activeCbs.forEach(e=>e(l)))}}for(let e of n.current.keys())r.has(e)||n.current.delete(e)}),r}function VZ(e,t,n,r){let i=gt(t.groups).length-gt(e.groups).length,a=t;if(i>0&&!r){let t=a.activeGroupId,n=e.activeGroupId;t&&n&&t!==n&&(a=un(a,t,n))}return gn(a,n)}function HZ({agent:e}){let[t,n]=g.useState(SZ),[r,i]=g.useState(eT),[a,o]=g.useState(null),[s,c]=g.useState(null),[l,u]=g.useState(!1),d=g.useRef(null),f=g.useRef(!1),p=AZ(),m=!p&&r===`fit`,h=g.useRef(m);h.current=m;let _=t.groups.some(e=>e.id===t.activeGroupId)?t.activeGroupId:t.groups[0]?.id??null,y=p?null:t.maximizedGroupId,b=LZ(t,p,m,y),x=b?(b.groups.find(e=>e.id===_)??b.groups[0]).w+12:0,S=g.useRef(p);S.current=p;let C=g.useRef(SZ),w=g.useRef(null),[T,ee]=g.useState(null);C.current=t;let E=g.useRef(new Map),D=g.useRef(new Map),O=g.useRef(new Map),te=g.useRef(new Map),ne=g.useRef(null),k=t.groups.find(e=>e.tabs.some(e=>e.kind===`operator`))?.id??null,A=g.useRef(k);A.current=k;let[re,ie]=g.useState(null),ae=g.useRef(null),oe=g.useRef(null),se=g.useRef(null),j=g.useRef({page:0,count:0,ids:[]});PZ(oe,!m),zZ(p,t.groups,b?.id??null,ne,O,te),FZ(oe,!p&&!t.maximizedGroupId&&!m,t.groups,x);let ce=BZ(t,p);g.useEffect(()=>{let e=!0;Promise.all([be(),ke().catch(()=>[])]).then(([t,r])=>{e&&(d.current=t.deckId,le(t),o(t.kitEditorExtensions),c(r),n(fZ(t.deckId,new Set(r),me)??kZ(t.initialPanels,me)),f.current=!0,u(!0))},()=>{e&&(o([]),c([]),n(kZ(null,me)),f.current=!0,u(!0))});let t=Px(t=>{t.changes.some(e=>e.event!==`change`)&&ke().then(t=>{e&&c(t)}).catch(()=>{}),t.changes.some(e=>e.path===`castle.json`||e.path.startsWith(`imports/`))&&be().then(t=>{e&&(le(t),o(t.kitEditorExtensions))},()=>{})});return()=>{e=!1,t()}},[]),g.useEffect(()=>{if(!f.current)return;let e=window.setTimeout(()=>dZ(d.current,t),400);return()=>window.clearTimeout(e)},[t]);let ue=g.useMemo(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId),n=e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0];return n&&n.kind===`editor`?n.path??null:null},[t.groups,t.activeGroupId]),de=g.useRef(null),fe=g.useCallback(e=>{if(S.current||C.current.maximizedGroupId||h.current)return;let t=C.current;if(LZ(t,S.current,h.current,t.maximizedGroupId)?.groups.some(t=>t.id===e))return;let n=oe.current,r=_t(t,e),i=(r?D.current.get(r.id):null)??E.current.get(e);n&&i&&IZ(n,i)},[]),pe=g.useCallback((e,t)=>{e&&(de.current=e,t||requestAnimationFrame(()=>{de.current===e&&(de.current=null,fe(e))}))},[fe]);g.useLayoutEffect(()=>{let e=de.current;e&&(de.current=null,fe(e))},[t.groups,t.activeGroupId,t.maximizedGroupId,fe]);let he=g.useCallback(()=>oe.current?.clientWidth||window.innerWidth,[]),ge=g.useCallback(e=>!Tt(e,he()-200-12),[he]),_e=g.useCallback(e=>h.current?gn(e,he()):e,[he]),ve=g.useCallback(()=>{let e=r===`fit`?`scroll`:`fit`;tT(e),i(e),e===`scroll`&&n(e=>hn(e))},[r]);g.useLayoutEffect(()=>{!l||!m||n(e=>gn(e,he()))},[l,m,he]),g.useEffect(()=>{if(!m)return;let e=0,t=()=>{window.clearTimeout(e),e=window.setTimeout(()=>{n(e=>gn(e,he()))},120)};return window.addEventListener(`resize`,t),()=>{window.clearTimeout(e),window.removeEventListener(`resize`,t)}},[m,he]);let ye=g.useCallback(e=>{let t=C.current,r=e(t);h.current&&(r=VZ(t,r,he(),ge(t))),r!==t&&n(()=>r),pe(r.activeGroupId,r!==t)},[pe,he,ge]),xe=g.useCallback((e,t,r,i)=>{let a=C.current,o=i?.line===void 0&&i?.field===void 0;i&&!(o&&Et(a,e))&&DS(e,i);let s=S.current?1:1/0,c=t?Yt(a,t,e,me,s,r):Jt(a,e,me,s,r);if(c===a)return;h.current&&(c=VZ(a,c,he(),ge(a)));let l=nt(c);for(let e of nt(a))l.has(e)||ky(e);Fb(d.current,e),n(()=>c),pe(c.activeGroupId,!0)},[pe,he,ge]),Se=g.useMemo(()=>({openFile:(e,t,n)=>xe(e,void 0,t,n),openPlaytest:()=>ye(e=>Qt(e,`play`)),openParams:(e,t)=>{e&&t?.field&&DS(e,{field:t.field}),ye(t=>nn(t,e))},setParamsScope:e=>n(t=>tn(t,e)),mentionInChat:e=>{v||(cq(e),ye(e=>Qt(e,`operator`)))},closeEditor:e=>n(t=>{let n=Et(t,e);return n?_e(Ut(t,n.group.id,n.tab.id)):t}),activeEditorPath:ue,kitEditorExts:a,terminalTheme:`dark`}),[a,ue,xe,ye,_e]);SS(Se);let Ce=g.useCallback((e,t)=>{let r=C.current,i=r.maximizedGroupId?bn({...r,maximizedGroupId:null},e):zt(r,e);i!==r&&n(()=>i),t?.reveal&&pe(e,i!==r)},[pe]),we=g.useCallback(e=>{let t=ht(C.current,e);if(t)for(let e of t.tabs)e.kind===`editor`&&e.path&&ky(e.path);n(t=>_e(rn(t,e)))},[_e]),Te=g.useCallback((e,t)=>{let r=ht(C.current,e)?.tabs.find(e=>e.id===t);r?.kind===`editor`&&r.path&&ky(r.path),n(n=>_e(Ut(n,e,t)))},[_e]),Ee=g.useCallback((e,t)=>n(n=>Bt(n,e,t)),[]),De=g.useCallback((e,t,r)=>{n(n=>_n(n,e,t,r))},[]),[Oe,Ae]=g.useState(null),je=g.useCallback(e=>Ae(e),[]),Me=g.useCallback(()=>Ae(null),[]),Ne=g.useCallback((e,t)=>xe(t,e),[xe]),Pe=g.useCallback((e,t,r)=>{n(n=>Kt(n,e,t,r))},[]),Fe=g.useCallback(e=>{let t=C.current,r=!!_t(t,e)?.groups.some(e=>e.id===t.maximizedGroupId);n(t=>bn(t,e)),r&&pe(e,!0)},[pe]),Ie=g.useCallback((e,t,r)=>{n(n=>Cn(Sn(n,e,t),e,r))},[]);g.useEffect(()=>{if(!p)return;let e=oe.current,t=se.current;if(!e||!t)return;let r=0,i=0,a=0,o=1,s=!1,c=!1,l=null,u=e=>t.style.setProperty(`--flow-drag`,`${e}px`),d=t=>{t.touches.length===1&&(r=t.touches[0].clientX,i=t.touches[0].clientY,a=t.timeStamp,l=t.target,o=e.clientWidth||1,s=!1,c=!1)},f=n=>{if(n.touches.length!==1)return;let a=n.touches[0].clientX-r,o=n.touches[0].clientY-i;if(!s){if(Math.abs(a)<8&&Math.abs(o)<8)return;s=!0,c=Math.abs(a)>Math.abs(o)&&!NZ(l,e,a),c&&t.classList.add(`flow-dragging`)}if(!c)return;n.preventDefault();let{page:d,count:f}=j.current;u(d===0&&a>0||d===f-1&&a<0?a*.3:a)},m=e=>{if(!c){t.classList.remove(`flow-dragging`);return}c=!1,t.classList.remove(`flow-dragging`);let i=e.changedTouches[0],s=i?i.clientX-r:0,l=e.timeStamp-a,{page:d,count:f,ids:p}=j.current,m=Math.abs(s)>50&&l<250,h=Math.abs(s)>o*.25,g=d;s<0&&(m||h)?g=Math.min(f-1,d+1):s>0&&(m||h)&&(g=Math.max(0,d-1));let _=p[g];g!==d&&_?n(e=>zt(e,_)):u(0)};return e.addEventListener(`touchstart`,d,{passive:!0}),e.addEventListener(`touchmove`,f,{passive:!1}),e.addEventListener(`touchend`,m,{passive:!0}),e.addEventListener(`touchcancel`,m,{passive:!0}),()=>{e.removeEventListener(`touchstart`,d),e.removeEventListener(`touchmove`,f),e.removeEventListener(`touchend`,m),e.removeEventListener(`touchcancel`,m)}},[p]);let Le=g.useCallback((e,t)=>{t?E.current.set(e,t):E.current.delete(e),e===A.current&&ie(t)},[]),Re=g.useCallback((e,t)=>{t?D.current.set(e,t):D.current.delete(e)},[]),ze=g.useCallback((e,t)=>{t?O.current.set(e,t):O.current.delete(e)},[]);g.useLayoutEffect(()=>{ie(k?E.current.get(k)??null:null)},[k]);let Be=cZ(e,(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId);return(e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0])?.kind===`operator`})(),re),[Ve,He]=g.useState(null),Ue=g.useRef(null),We=g.useRef(null),Ge=g.useRef(!1),Ke=g.useCallback(()=>{let e=new Map;return D.current.forEach((t,n)=>e.set(n,t.getBoundingClientRect())),e},[]);g.useLayoutEffect(()=>{let e=Ue.current;if(!e)return;Ue.current=null;let t=We.current;if(We.current=null,t){let e=oe.current,n=D.current.get(t);e&&n&&IZ(e,n,`auto`)}CZ(e,D.current)});let qe=g.useCallback(e=>{let t=C.current,r=_t(t,e),i=!!LZ(t,S.current,h.current,t.maximizedGroupId)?.groups.some(t=>t.id===e);Ue.current=Ke(),i&&r&&(We.current=r.id),n(t=>yn(t,e))},[Ke]),Je=g.useCallback((e,t)=>{let r=C.current;if(S.current){let n=on(r,e,t),i=r.groups.findIndex(e=>e.id===r.activeGroupId);n.groups.findIndex(e=>e.id===n.activeGroupId)!==i&&(Ge.current=!0)}else Ue.current=Ke();n(n=>on(n,e,t))},[Ke]);g.useEffect(()=>()=>{ae.current?.()},[]);let Ye=g.useCallback((e,r)=>{if(p||e.button!==0||!Mw(e.target))return;let i=jw(e.target),a=i?.closest(`.panel-type-toggle`),o=e.currentTarget instanceof HTMLElement?e.currentTarget:i?.closest(`.flow-tabstrip`),s=a instanceof HTMLElement?a:o instanceof HTMLElement?o:null;if(!s)return;i?.closest(`button`)||e.preventDefault(),ae.current?.();let c=e.pointerId,l=e.pointerType===`mouse`,u=e=>{e.preventDefault(),e.stopPropagation(),s.removeEventListener(`click`,u,!0)},d=e.clientX,f=gt(t.groups),m=f.findIndex(e=>e.groups.some(e=>e.id===r)),g=LZ(t,p,h.current,t.maximizedGroupId)?.id??null,_=!!g&&f[m]?.id===g,v=(e,n)=>{let i=f.filter(e=>!e.groups.some(e=>e.id===r));for(let t of i){let r=D.current.get(t.id)?.getBoundingClientRect();if(r&&e>=r.left&&e<=r.right&&n>=r.top&&n<=r.bottom){let n=(e-r.left)/Math.max(1,r.width);if(n>.25&&n<.75)return{kind:`merge`,targetId:t.groups[0].id}}}let a=(_?i:i.filter(e=>e.id!==g)).map(e=>{let t=D.current.get(e.id)?.getBoundingClientRect();return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),o=0;for(;o<a.length&&a[o].center<e;)o+=1;let s=cn(t,r,o,g);if(s.groups.length===t.groups.length&&s.groups.every((e,n)=>e.id===t.groups[n].id))return{kind:`reorder`,target:o,x:null};let c=o<a.length?a[o].left-6:a.length?a[a.length-1].right+6:e;return{kind:`reorder`,target:o,x:c}},y=!1,b=null,x=e.clientX,S=e.clientY,C=0,w=()=>{let e=oe.current;if(!h.current&&e&&e.scrollWidth>e.clientWidth+1){let t=e.getBoundingClientRect(),n=0;if(x<t.left+64?n=-(1-Math.max(0,x-t.left)/64):x>t.right-64&&(n=1-Math.max(0,t.right-x)/64),n!==0){e.scrollLeft+=n*24;let t=v(x,S);He({id:r,x:t.kind===`reorder`?t.x:null,mergeId:t.kind===`merge`?t.targetId:null})}}C=requestAnimationFrame(w)},T=e=>{if(e.pointerId!==c||!y&&Math.abs(e.clientX-d)<5)return;if(!y){if(y=!0,l)try{s.setPointerCapture(c)}catch{}s.blur(),document.body.classList.add(`flow-reordering`),s.addEventListener(`click`,u,!0);let t=f[m],n=t?.groups.find(e=>e.id===r)??t?.groups[0];n&&(b=rT(n,{stackCount:t.groups.length,iconRoot:E.current.get(n.id)??s}),document.body.appendChild(b),px(b,e.clientX,e.clientY)),C=requestAnimationFrame(w)}x=e.clientX,S=e.clientY,b&&px(b,e.clientX,e.clientY);let t=v(e.clientX,e.clientY);He({id:r,x:t.kind===`reorder`?t.x:null,mergeId:t.kind===`merge`?t.targetId:null})},ee=!1,O=()=>{if(!ee){ee=!0,window.removeEventListener(`pointermove`,T),window.removeEventListener(`pointerup`,te),window.removeEventListener(`pointercancel`,ne),l&&s.removeEventListener(`lostpointercapture`,ne);try{s.hasPointerCapture(c)&&s.releasePointerCapture(c)}catch{}C&&cancelAnimationFrame(C),document.body.classList.remove(`flow-reordering`),b?.remove(),b=null,ae.current=null,window.setTimeout(()=>s.removeEventListener(`click`,u,!0),0)}},te=e=>{if(e.pointerId!==c)return;let t=y;if(O(),t){let t=v(e.clientX,e.clientY);t.kind===`merge`?(Ue.current=Ke(),n(e=>_e(un(e,r,t.targetId)))):t.x!==null&&(Ue.current=Ke(),n(e=>cn(e,r,t.target,g)))}He(null)},ne=e=>{e&&e.pointerId!==c||(O(),He(null))};ae.current=()=>ne(),window.addEventListener(`pointermove`,T),window.addEventListener(`pointerup`,te),window.addEventListener(`pointercancel`,ne),l&&s.addEventListener(`lostpointercapture`,ne)},[p,t,Ke,_e]),Xe=g.useCallback((e,r)=>{if(p||e.button!==0)return;let i=_t(t,r);if(!i||i.groups.length<2)return;ae.current?.();let a=e.currentTarget,o=a.closest(`.flow-rail`),s=o instanceof HTMLElement?o:null,c=e.pointerId,l=e.pointerType===`mouse`,u=e.clientX,d=e.clientY,f=i.groups.findIndex(e=>e.id===r),m=e=>{e.preventDefault(),e.stopPropagation(),a.removeEventListener(`click`,m,!0)},g=!1,_=null,v=t.groups.filter(e=>e.id!==r),y=gt(v),b=gt(t.groups),x=LZ(t,p,h.current,t.maximizedGroupId)?.id??null,S=x&&i.id!==x?y.filter(e=>e.id!==x):y,C=e=>{let t=D.current.get(e.id);if(t)return t.getBoundingClientRect();let n=b.find(t=>t.groups.some(t=>t.id===e.groups[0].id));return n?D.current.get(n.id)?.getBoundingClientRect():void 0},w=e=>{let t=[...D.current.get(i.id)?.querySelectorAll(`[data-rail-gid]`)??[]].filter(e=>e.dataset.railGid!==r),n=0;for(;n<t.length;){let r=t[n].getBoundingClientRect();if(e<r.top+r.height/2)break;n+=1}return n},T=e=>{let t=S.map(e=>{let t=C(e);return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),n=0;for(;n<t.length&&t[n].center<e;)n+=1;let r=n<t.length?t[n].left-6:t.length?t[t.length-1].right+6:e,i=n>=S.length?v.length:v.findIndex(e=>e.id===S[n].groups[0].id);return{toIndex:i<0?v.length:i,x:r}},ee=e=>{if(e.pointerId!==c)return;if(!g){if(Math.hypot(e.clientX-u,e.clientY-d)<5)return;if(g=!0,l&&s)try{s.setPointerCapture(c)}catch{}document.body.classList.add(`flow-reordering`),a.addEventListener(`click`,m,!0);let t=i.groups.find(e=>e.id===r);t&&(_=rT(t,{iconRoot:a}),document.body.appendChild(_),px(_,e.clientX,e.clientY))}e.cancelable&&e.preventDefault(),_&&px(_,e.clientX,e.clientY);let t=D.current.get(i.id)?.getBoundingClientRect(),n=t&&e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom;He({id:r,x:n?null:T(e.clientX).x,mergeId:null,railInsertAt:n?w(e.clientY):null})},E=!1,O=()=>{if(!E){E=!0,window.removeEventListener(`pointermove`,ee),window.removeEventListener(`pointerup`,te),window.removeEventListener(`pointercancel`,ne),l&&s&&s.removeEventListener(`lostpointercapture`,ne);try{s?.hasPointerCapture(c)&&s.releasePointerCapture(c)}catch{}document.body.classList.remove(`flow-reordering`),_?.remove(),_=null,ae.current=null,window.setTimeout(()=>a.removeEventListener(`click`,m,!0),0)}},te=e=>{if(e.pointerId!==c)return;let t=g;if(O(),t){let t=D.current.get(i.id)?.getBoundingClientRect();if(t&&e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom){let t=w(e.clientY);t!==f&&n(e=>fn(e,r,t))}else Ue.current=Ke(),n(t=>_e(dn(t,r,T(e.clientX).toIndex)))}He(null)},ne=e=>{e&&e.pointerId!==c||(O(),He(null))};ae.current=()=>ne(),window.addEventListener(`pointermove`,ee,{passive:!1}),window.addEventListener(`pointerup`,te),window.addEventListener(`pointercancel`,ne),l&&s&&s.addEventListener(`lostpointercapture`,ne)},[p,t,Ke,_e]),[Ze,Qe]=g.useState(null),$e=g.useCallback(e=>Qe(t=>t?null:{anchor:e}),[]),et=g.useCallback(()=>{let e=se.current?.querySelector(`.flow-tabs-add`);Qe({anchor:e?.getBoundingClientRect()??new DOMRect(window.innerWidth/2,48)})},[]);g.useEffect(()=>{let e=(e,t)=>(t&&t!==window?[...document.querySelectorAll(`iframe.deck-frame`)].find(e=>e.contentWindow===t):e)?.closest?.(`.flow-group`)?.getAttribute(`data-group-id`)??null;return Xy(`pointermove`,t=>{let n=e(t.target,t.view);w.current=n,!S.current&&ee(e=>e===n?e:n)},{passive:!0})},[]);let rt=g.useMemo(()=>Ry({getState:()=>C.current,setState:n,spawn:ye,focusGroup:e=>Ce(e,{reveal:!0}),closeGroup:we,closeTab:Te,openPath:e=>xe(e),openNewGroupPicker:et,getHoveredGroupId:()=>w.current,toggleMaximize:Fe,togglePin:qe}),[ye,Ce,we,Te,xe,et,Fe,qe]),it=$y(rt),at=Math.max(0,t.groups.findIndex(e=>e.id===_));j.current={page:at,count:t.groups.length,ids:t.groups.map(e=>e.id)},g.useLayoutEffect(()=>{let e=se.current;if(!e)return;let t=Ge.current;t&&e.classList.add(`flow-dragging`),e.style.setProperty(`--flow-page`,String(at)),e.style.setProperty(`--flow-drag`,`0px`),t&&(Ge.current=!1,e.offsetHeight,requestAnimationFrame(()=>e.classList.remove(`flow-dragging`)))},[at,p]),xb(se),Tb(()=>Oe?(Ae(null),!0):Ze?(Qe(null),!0):!1,1);let ot=Oe?ht(t,Oe):null,st=ot?.tabs.find(e=>e.id===ot.activeTabId)??ot?.tabs[0],ct=st&&st.kind===`editor`?st.path??``:``;return(0,U.jsx)(bS,{value:Se,children:(0,U.jsx)(xZ.Provider,{value:e,children:(0,U.jsxs)(`div`,{ref:se,className:`flow-root${p?` is-mobile`:``}${y?` is-maximized`:``}${m?` is-fit`:``}`,children:[(0,U.jsx)(UZ,{state:t,activeId:_,operatorBadge:Be,layoutMode:r,showLayoutToggle:!p,onToggleLayoutMode:ve,onFocusGroup:Ce,onReorderGroup:Je,onNewGroup:$e}),(0,U.jsxs)(`div`,{className:`flow-workbench`,children:[(0,U.jsx)(`div`,{className:`flow-pin-dock`,ref:ne}),(0,U.jsx)(`div`,{className:`flow-scroller`,ref:oe,children:(0,U.jsx)(`div`,{className:`flow-field`,children:(0,U.jsx)(`div`,{className:`flow-row`,style:x?{"--flow-pin-inset":`${x}px`}:void 0,children:p?t.groups.map(e=>(0,U.jsx)(qZ,{group:e,active:e.id===_,mobile:p,pinned:!1,maximized:!1,hidden:!1,dragging:!1,hovered:e.id===T,fill:!1,showResize:!1,showPin:!1,getLifecycle:ce,registerEl:Le,onFocusGroup:Ce,onClose:we,onActivateTab:Ee,onCloseTab:Te,onReorderTab:De,onOpenMobileSwitch:je,onOpenInGroup:Ne,onSetTabView:Pe,onTogglePin:qe,onToggleMaximize:Fe,onStartDrag:Ye,onResize:Ie},e.id)):gt(t.groups).map(e=>(0,U.jsx)(`div`,{className:`flow-card-slot${b&&e.id===b.id?` is-docked`:``}`,ref:t=>ze(e.id,t)},e.id))})})}),!p&&gt(t.groups).map((e,r,i)=>{let a=e.groups.length>1,o=e.groups.find(e=>e.id===_)??e.groups[0],s=e.groups.some(e=>e.id===t.pinnedGroupId)&&!y,c=!!b&&e.id===b.id,l=e.groups.some(e=>e.id===y),u=y!==null&&!l,d=!!Ve?.id&&Ve.railInsertAt===void 0&&e.groups.some(e=>e.id===Ve.id),f=!!Ve?.mergeId&&e.groups.some(e=>e.id===Ve.mergeId),p=i[r+1],h=l?{flex:`1 1 auto`}:m?{flexGrow:o.w,"--flow-card-min":`${Ct(e)}px`}:{width:o.w,height:o.h},v=(0,U.jsxs)(U.Fragment,{children:[a?(0,U.jsx)(Xw,{groups:e.groups,activeGroupId:o.id,operatorBadge:Be,onActivate:e=>Ce(e),onUnstack:e=>n(t=>_e(dn(t,e,t.groups.length))),onPointerDown:Xe,reorder:Ve&&Ve.railInsertAt!==void 0&&e.groups.some(e=>e.id===Ve.id)?{dragId:Ve.id,insertAt:Ve.railInsertAt}:void 0}):null,e.groups.map(e=>(0,U.jsx)(qZ,{group:e,active:e.id===_,mobile:!1,pinned:s,maximized:l,hidden:u||e.id!==o.id,dragging:!1,hovered:e.id===T,fill:!0,showResize:!m&&!l&&e.id===o.id,showPin:!m,getLifecycle:ce,registerEl:Le,onFocusGroup:Ce,onClose:we,onActivateTab:Ee,onCloseTab:Te,onReorderTab:De,onOpenMobileSwitch:je,onOpenInGroup:Ne,onSetTabView:Pe,onTogglePin:qe,onToggleMaximize:Fe,onStartDrag:Ye,onResize:Ie},e.id))]});return(0,U.jsx)(g.Fragment,{children:(0,tb.createPortal)((0,U.jsxs)(`div`,{ref:t=>Re(e.id,t),"data-card-id":e.id,className:`flow-card${a?` is-stacked panel`:``}${o.id===_&&!y?` is-active`:``}${c?` pinned`:``}${l?` maximized`:``}${u?` hidden`:``}${d?` is-dragging`:``}${f?` is-drop-target`:``}`,style:h,children:[a?(0,U.jsx)(`div`,{className:`flow-card-stack`,children:v}):v,m&&!y&&p?(0,U.jsx)(sQ,{leftW:o.w,rightW:p.groups[0].w,leftMin:Ct(e),rightMin:Ct(p),onSplit:(e,t)=>n(n=>wn(n,o.id,p.groups[0].id,e,t))}):null]}),RZ(te.current,e.id))},e.id)})]}),Ve&&Ve.x!==null&&(()=>{let e=oe.current?.getBoundingClientRect(),n=_t(t,Ve.id),r=(n&&D.current.get(n.id)||E.current.get(Ve.id))?.getBoundingClientRect();if(!e||!r)return null;let i=Math.max(r.top,e.top+12+36),a=Math.min(r.bottom,e.bottom)-i;return a<=0?null:(0,U.jsx)(`div`,{className:`flow-drop-indicator`,style:{left:Ve.x,top:i,height:a}})})(),Ze&&(0,U.jsx)(oQ,{anchor:Ze.anchor,files:s??[],onOpenFile:e=>xe(e),onSpawnPanel:e=>ye(t=>Qt(t,e)),onSpawnClass:e=>ye(t=>Xt(t,e,me)),onClose:()=>Qe(null)}),Oe&&(0,U.jsx)(wT,{groupId:Oe,groupClass:tt(ot,me),currentFile:ct,files:s,recent:Lb(d.current),view:st?.view,onSetView:e=>{Oe&&st&&Pe(Oe,st.id,e)},onOpen:(e,t)=>xe(e,t),onClose:Me}),(0,U.jsx)(Ab,{openFile:e=>xe(e),openPanel:e=>ye(t=>Qt(t,e===`playtest`?`play`:e)),panels:eQ,getCommands:rt}),it?(0,U.jsxs)(`div`,{className:`chord-hint`,role:`status`,children:[(0,U.jsx)(`kbd`,{children:it}),(0,U.jsx)(`span`,{children:`waiting for the next key…`})]}):null]})})})}function UZ(e){let{state:t,activeId:n,operatorBadge:r,layoutMode:i,showLayoutToggle:a,onToggleLayoutMode:o,onFocusGroup:s,onReorderGroup:c,onNewGroup:l}=e,u=Db(),[d,f]=g.useState(!1),p=u?.title?.trim()||`Untitled deck`;vb(p,r),yb(r);let m=u?.visibility===`public`?Qb:u?.visibility===`unlisted`?Xb:Zb,h=u?.saving??`idle`,_=u?.saveError??null,v=u?.draftAutosaveState??null,y=v===`starting`||v===`saving`?`Saving draft…`:v===`dirty`?`Unsaved changes`:v===`error`?`Draft save failed`:v===`saved`?`Draft saved`:null,[b,x]=g.useState(null),S=g.useRef(!1);g.useEffect(()=>{b!==null&&(h===`working`&&(S.current=!0),h===`done`&&S.current&&x(`done`),_&&S.current&&x(`failed`))},[h,_,b]);let C=g.useCallback(()=>{S.current=!1,x(`pushing`),gb(`push`)},[]);return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`div`,{className:`flow-topbar`,children:[(0,U.jsxs)(`div`,{className:`flow-topbar-leading`,children:[OT()?null:(0,U.jsxs)(`div`,{className:`flow-castle-wrap`,children:[(0,U.jsx)(`button`,{type:`button`,className:`dock-control dock-control-icon dock-control-mark`,title:`Menu`,"aria-haspopup":`menu`,"aria-expanded":d,onClick:()=>f(e=>!e),children:ox}),d&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-menu-backdrop`,onClick:()=>f(!1)}),(0,U.jsxs)(`div`,{className:`menu flow-castle-menu`,role:`menu`,children:[(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{f(!1),gb(`back-to-decks`)},children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:ex}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:`Back to decks`})]}),(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{f(!1),gb(`new-deck`)},children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:Kb}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:`New deck`})]}),(0,U.jsx)(`div`,{className:`menu-separator flow-menu-narrow`}),(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,onClick:()=>{f(!1),gb(`open-settings`)},children:(0,U.jsx)(`span`,{className:`menu-item-label`,children:`Deck settings`})}),(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,disabled:h===`working`,onClick:()=>{f(!1),C()},children:(0,U.jsx)(`span`,{className:`menu-item-label`,children:h===`working`?`Pushing…`:_?`Push failed — retry`:h===`done`?`Pushed ✓`:`Push to Castle`})})]})]})]}),(0,U.jsxs)(`button`,{type:`button`,className:`dock-control dock-control-quiet flow-deck-identity`,title:`Deck settings`,onClick:()=>gb(`open-settings`),children:[(0,U.jsx)(`span`,{className:`flow-deck-vis`,children:m}),(0,U.jsx)(`span`,{className:`flow-deck-name`,children:p}),(0,U.jsx)(`span`,{className:`flow-deck-caret`,children:tx})]}),y?(0,U.jsx)(`span`,{className:`flow-draft-status${v===`error`?` is-error`:``}`,role:`status`,children:y}):null]}),(0,U.jsxs)(`div`,{className:`flow-tabs-wrap`,children:[a?(0,U.jsx)(Gw,{layoutMode:i,onToggleLayoutMode:o,activeTabId:t.groups.find(e=>e.id===n)?.activeTabId??null}):null,(0,U.jsx)(Vw,{groups:t.groups,activeId:n,operatorBadge:r,onFocusGroup:s,onReorderGroup:c}),(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet flow-tabs-add flow-picker-trigger`,title:`New group`,"aria-label":`New group`,onClick:e=>l(e.currentTarget.getBoundingClientRect()),children:Kb})]}),(0,U.jsx)(`div`,{className:`flow-topbar-trailing`,children:(0,U.jsxs)(`button`,{type:`button`,className:`dock-control flow-preview-btn${_?` flow-preview-btn-failed`:``}`,title:_??`Publish this deck to your Castle account (sandbox edits stay local until pushed)`,disabled:h===`working`,onClick:()=>gb(`push`),children:[$b,(0,U.jsxs)(`span`,{className:`flow-preview-label`,children:[(0,U.jsx)(`span`,{className:`flow-preview-label-sizer`,"aria-hidden":`true`,children:`Push to Castle`}),(0,U.jsx)(`span`,{children:h===`working`?`Pushing…`:_?`Push failed`:h===`done`?`Pushed ✓`:`Push to Castle`})]})]})})]}),b!==null&&(0,U.jsx)(`div`,{className:`flow-push-modal-backdrop`,children:(0,U.jsx)(`div`,{className:`flow-push-modal`,role:`dialog`,"aria-modal":`true`,children:b===`failed`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-check flow-push-check-failed`,children:`!`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Push failed`}),(0,U.jsx)(`div`,{className:`flow-push-sub`,children:_}),(0,U.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>x(null),children:`Dismiss`})]}):b===`done`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-check`,children:`✓`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Pushed to Castle`}),u?.shareUrl?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Your deck is live at`}),(0,U.jsx)(`a`,{className:`flow-push-url`,href:u.shareUrl,target:`_blank`,rel:`noreferrer`,children:u.shareUrl.replace(/^https?:\/\//,``)})]}):(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Saved to your Castle account.`}),(0,U.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>x(null),children:`Done`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-spinner`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Pushing to Castle…`}),(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Publishing your latest changes.`})]})})})]})}function WZ(e,t){e.currentTarget.blur(),t()}function GZ(e,t,n){let r=g.useRef(null);return g.useEffect(()=>{let t=r.current;if(!t)return;let i=t=>{t.button===0&&n(e)};return t.addEventListener(`pointerdown`,i),()=>t.removeEventListener(`pointerdown`,i)},[e,n]),g.useCallback(n=>{r.current=n,t(e,n)},[e,t])}function KZ(e,t,n){let r=g.useRef(null);return g.useEffect(()=>{let i=r.current;if(!i)return;let a=r=>{Mw(r.target)&&(e||n(r,t))},o=e=>e.preventDefault();return i.addEventListener(`pointerdown`,a),i.addEventListener(`dragstart`,o),()=>{i.removeEventListener(`pointerdown`,a),i.removeEventListener(`dragstart`,o)}},[e,t,n]),r}var qZ=g.memo(function(e){let{group:t,active:n,mobile:r,pinned:i,maximized:a,hidden:o,dragging:s,hovered:c,fill:l,showResize:u,showPin:d,getLifecycle:f,registerEl:p}=e,{onFocusGroup:m,onClose:h}=e,_=et(t),v=cQ(t,e.onResize),[y,b]=g.useState(()=>_&&t.tabs.every($e)),x=g.useCallback(()=>b(e=>!e),[]),S=KZ(a,t.id,e.onStartDrag),C=GZ(t.id,p,m),w=r?void 0:l?{flex:`1 1 auto`,minWidth:0,height:`100%`}:a?{flex:`1 1 auto`}:{flex:`0 0 auto`,width:t.w,height:t.h},T=_?null:t.tabs[0],ee=(0,U.jsx)(`button`,{type:`button`,className:r?`button button-icon button-icon-large button-quiet`:`button button-icon button-quiet`,title:`Close`,"aria-label":`Close`,onClick:e=>WZ(e,()=>h(t.id)),children:qb}),E=n&&!r&&!a,D=T?.kind===`operator`;return(0,U.jsxs)(`div`,{ref:C,"data-group-id":t.id,className:`panel flow-group${E?` is-active`:``}${i&&!l?` pinned`:``}${a?` maximized`:``}${o?` hidden`:``}${s?` is-dragging`:``}${c?` is-hover`:``}${_?` is-editor`:``}`,style:w,children:[_?(0,U.jsx)(Iw,{group:t,mobile:r,pinned:i,maximized:a,onStartDrag:e.onStartDrag,onActivateTab:e.onActivateTab,onCloseTab:e.onCloseTab,onCloseGroup:h,onReorderTab:e.onReorderTab,onTogglePin:e.onTogglePin,onToggleMaximize:e.onToggleMaximize,onOpenMobileSwitch:e.onOpenMobileSwitch,onSetTabView:e.onSetTabView,drawerOpen:y,onToggleDrawer:x,showPin:d}):(0,U.jsxs)(`div`,{ref:S,className:`${D?`panel-tabs-header`:`panel-header`} flow-tabstrip${r?` flow-tabstrip-mobile`:``}`,children:[D?(0,U.jsx)(`div`,{className:`operator-chrome`,"data-operator-chrome":!0}):r?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`panel-header-actions flow-mobile-strip-left`,children:(0,U.jsx)(BS,{tabId:T?.id})}),(0,U.jsxs)(`div`,{className:`panel-mobile-current`,children:[(0,U.jsx)(`span`,{className:`flow-tab-icon`,children:T&&Gb(T.kind,T.path)}),(0,U.jsx)(`span`,{className:`panel-mobile-current-label`,children:T?.label})]})]}):(0,U.jsxs)(`div`,{className:`panel-title`,children:[(0,U.jsx)(`span`,{className:`flow-tab-icon`,children:T&&Gb(T.kind,T.path)}),(0,U.jsx)(`span`,{children:T?.label})]}),(0,U.jsxs)(`div`,{className:`panel-header-actions${r?` flow-mobile-strip-right`:``}`,children:[d&&(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:i?`Unpin`:`Pin to left`,"aria-label":i?`Unpin`:`Pin to left`,"aria-pressed":i,onClick:n=>WZ(n,()=>e.onTogglePin(t.id)),children:Yb}),!r&&(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:a?`Restore`:`Maximize`,"aria-label":a?`Restore`:`Maximize`,"aria-pressed":a,onClick:n=>WZ(n,()=>e.onToggleMaximize(t.id)),children:a?rx:nx}),ee]})]}),(0,U.jsx)(`div`,{className:`flow-panel-body`,children:t.tabs.map(i=>(0,U.jsx)(`div`,{className:`flow-tab-body${i.id===t.activeTabId?``:` inactive`}`,children:(0,U.jsx)(JZ,{tab:i,groupId:t.id,lifecycle:f(i.id),onOpenInGroup:e.onOpenInGroup,onSetTabView:e.onSetTabView,drawerOpen:y&&!r,mobile:r,active:n})},i.id))}),!r&&u&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-resize-e`,onPointerDown:v(`x`),title:`Drag to resize width`}),(0,U.jsx)(`div`,{className:`flow-resize-s`,onPointerDown:v(`y`),title:`Drag to resize height`}),(0,U.jsx)(`div`,{className:`flow-resize-se`,onPointerDown:v(`xy`),title:`Drag to resize`})]})]})}),JZ=g.memo(function(e){let{tab:t,groupId:n,lifecycle:r,onOpenInGroup:i,onSetTabView:a,drawerOpen:o,mobile:s,active:c}=e;if(t.kind===`editor`&&$e(t))return(0,U.jsxs)(`div`,{className:`flow-empty-editor`,children:[o?(0,U.jsx)(ZG,{currentFile:``,filterClass:t.classHint,onOpen:e=>i(n,e)}):null,(0,U.jsx)(`div`,{className:`flow-empty-editor-msg`,children:`Open a file`})]});switch(t.kind){case`editor`:return(0,U.jsx)(VG,{file:t.path,editorClass:t.view,lifecycle:r,hideContextBar:!0,drawerOpen:o,drawer:(0,U.jsx)(ZG,{currentFile:t.path??``,filterClass:t.path?me(t.path):void 0,onOpen:e=>i(n,e),view:t.view,onSetView:e=>a(n,t.id,e)})});case`play`:return(0,U.jsx)(YG,{lifecycle:r});case`terminal`:return(0,U.jsx)(XG,{lifecycle:r});case`files`:return(0,U.jsx)($K,{lifecycle:r});case`params`:return(0,U.jsx)(xw,{scope:t.path,lifecycle:r});case`operator`:return(0,U.jsx)(YZ,{mobile:s,active:c});default:return(0,U.jsx)(XZ,{tab:t})}});function YZ(e){let t=g.useContext(xZ);return t?(0,U.jsx)(`div`,{className:`shell-root docked flow-operator-host`,style:{"--operator-col":`100%`},children:(0,U.jsx)(GX,{agent:t,mobile:e.mobile,active:e.active})}):(0,U.jsx)(`div`,{className:`flow-placeholder`,children:`operator unavailable`})}function XZ(e){let{tab:t}=e;return(0,U.jsxs)(`div`,{className:`flow-placeholder kind-${t.kind}`,children:[(0,U.jsx)(`div`,{className:`flow-placeholder-icon`,children:Gb(t.kind,t.path)}),(0,U.jsx)(`div`,{className:`flow-placeholder-label`,children:t.label}),(0,U.jsx)(`div`,{className:`flow-placeholder-kind`,children:t.path??t.kind})]})}function ZZ(e,t){g.useEffect(()=>{let n=n=>{n.target.closest(e)||t()},r=window.setTimeout(()=>document.addEventListener(`mousedown`,n),0);return()=>{window.clearTimeout(r),document.removeEventListener(`mousedown`,n)}},[e,t])}function QZ(e,t){return Math.max(8,Math.min(e,window.innerWidth-t-8))}var $Z=300,eQ=[...v?[]:[{kind:`operator`,label:`Operator`}],{kind:`play`,label:`Play`},...v?[]:[{kind:`terminal`,label:`Terminal`}],{kind:`files`,label:`Files`},{kind:`params`,label:`Parameters`}].map(({kind:e,label:t})=>({kind:e===`play`?`playtest`:e,label:t}));function tQ(e,t){return!t||e.toLowerCase().includes(t)}function nQ(e){let t=he(fe);return[{kind:`panel`,panel:`play`,label:`Play`},...v?[]:[{kind:`panel`,panel:`operator`,label:`Operator`}],{kind:`panel`,panel:`files`,label:`Files`},{kind:`class`,classId:fe,label:t.label,icon:t.icon},{kind:`panel`,panel:`params`,label:`Parameters`},...v?[]:[{kind:`panel`,panel:`terminal`,label:`Terminal`}]].filter(t=>tQ(t.label,e))}function rQ(e,t){let n=new Set;for(let t of e){let e=me(t);e!==`code`&&n.add(e)}return[...n].map(e=>{let t=he(e);return{kind:`class`,classId:e,label:t.label,icon:t.icon}}).filter(e=>tQ(e.label,t)).sort((e,t)=>e.label.localeCompare(t.label))}function iQ(e,t){let n=t.trim().toLowerCase(),r=[rQ(e,n),nQ(n),e.filter(e=>e.toLowerCase().includes(n)).slice(0,40).map(e=>({kind:`file`,path:e}))].filter(e=>e.length>0),i=[];for(let e=0;e<r.length;e++)e>0&&i.push({kind:`divider`}),i.push(...r[e]);return i}function aQ(e){return e.kind!==`divider`}function oQ(e){let{anchor:t,files:n,onOpenFile:r,onSpawnPanel:i,onSpawnClass:a,onClose:o}=e,[s,c]=g.useState(``),[l,u]=g.useState(0);ZZ(`.flow-picker, .flow-picker-trigger`,o);let d=iQ(n,s),f=d.filter(aQ),p=Math.min(l,Math.max(0,f.length-1)),m=e=>{e.kind===`panel`?i(e.panel):e.kind===`class`?a(e.classId):r(e.path),o()},h=e=>{e.key===`Escape`?o():e.key===`ArrowDown`?(e.preventDefault(),u(e=>Math.min(e+1,f.length-1))):e.key===`ArrowUp`?(e.preventDefault(),u(e=>Math.max(e-1,0))):e.key===`Enter`&&f[p]&&m(f[p])},_=0;return(0,tb.createPortal)((0,U.jsxs)(`div`,{className:`menu flow-picker`,style:{top:t.bottom+4,left:QZ(t.left,$Z),width:$Z},onMouseDown:e=>e.stopPropagation(),children:[(0,U.jsx)(`input`,{className:`flow-picker-input`,autoFocus:!0,placeholder:`Open a file or panel…`,value:s,onChange:e=>{c(e.target.value),u(0)},onKeyDown:h}),(0,U.jsxs)(`div`,{className:`flow-picker-list`,children:[(0,U.jsx)(`div`,{className:`menu-separator`}),f.length===0&&(0,U.jsx)(`div`,{className:`flow-picker-empty`,children:`No matches`}),d.map((e,t)=>{if(e.kind===`divider`)return(0,U.jsx)(`div`,{className:`menu-separator`},`d:${t}`);let n=_++;return(0,U.jsxs)(`button`,{type:`button`,className:`menu-item${n===p?` is-hover`:``}`,onMouseEnter:()=>u(n),onClick:()=>m(e),children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:e.kind===`panel`?Gb(e.panel):e.kind===`class`?Hb(e.icon):Gb(`editor`,e.path)}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:e.kind===`panel`||e.kind===`class`?e.label:e.path})]},e.kind===`panel`?`p:${e.panel}`:e.kind===`class`?`c:${e.classId}`:`f:${e.path}`)})]})]}),document.body)}function sQ(e){let{leftW:t,rightW:n,leftMin:r,rightMin:i,onSplit:a}=e;return(0,U.jsx)(`div`,{className:`flow-splitter`,onPointerDown:e=>{e.preventDefault(),e.stopPropagation();let o=e.clientX,s=e.currentTarget,c=s.parentElement,l=c?.nextElementSibling,u=c?.getBoundingClientRect().width??t,d=l?.getBoundingClientRect().width??n;s.setPointerCapture(e.pointerId);let f=!1,p=e=>{let t=e.clientX-o;if(!f&&Math.abs(t)<5)return;f=!0;let n=u+t,s=d-t;n<r&&(s-=r-n,n=r),s<i&&(n-=i-s,s=i),!(n<r||s<i)&&a(n,s)},m=()=>{s.removeEventListener(`pointermove`,p),s.removeEventListener(`pointerup`,m)};s.addEventListener(`pointermove`,p),s.addEventListener(`pointerup`,m)},title:`Drag to resize`})}function cQ(e,t){return g.useCallback(n=>r=>{r.preventDefault(),r.stopPropagation();let i=r.clientX,a=r.clientY,o=e.w,s=e.h,c=r.currentTarget;c.setPointerCapture(r.pointerId);let l=!1,u=r=>{let c=r.clientX-i,u=r.clientY-a;if(!l&&Math.abs(c)<5&&Math.abs(u)<5)return;l=!0;let d=n===`y`?o:Math.max(200,o+c),f=n===`x`?s:Math.max(160,s+u);t(e.id,d,f)},d=()=>{c.removeEventListener(`pointermove`,u),c.removeEventListener(`pointerup`,d)};c.addEventListener(`pointermove`,u),c.addEventListener(`pointerup`,d)},[e.id,e.w,e.h,t])}function lQ(){let e=oe(),t=g.useRef(0);return Eb(()=>{let n=Date.now();n-t.current<1e3||(t.current=n,e.refreshUsage())}),(0,U.jsx)(HZ,{agent:e})}var uQ=document.getElementById(`root`);if(!uQ)throw Error(`Missing #root`);cK(),JF(),fS(),(0,_.createRoot)(uQ).render((0,U.jsx)(lQ,{}));
449
+ `)}`:``}var AY={thinking:(0,U.jsx)(W,{name:`lightbulb`}),reading:(0,U.jsx)(W,{name:`book`}),building:(0,U.jsx)(W,{name:`hammer`}),painting:(0,U.jsx)(W,{name:`pencil`}),playing:(0,U.jsx)(W,{name:`gamepad`})},jY={thinking:`Thinking`,reading:`Reading files`,building:`Editing logic`,painting:`Editing art`,playing:`Playtesting`},MY={thinking:`#FFC826`,reading:`#FFC826`,building:`#FFEB57`,painting:`#FFEB57`,playing:`#D3FC7E`};function NY(e){if(e.status===`done`)return{icon:(0,U.jsx)(W,{name:`check`}),color:`#5AC54F`};if(e.status===`failed`)return{icon:(0,U.jsx)(W,{name:`times`}),color:`#F5545D`};if(e.status===`interrupted`)return{icon:(0,U.jsx)(W,{name:`stop`}),color:`#B4B4B4`};if(e.status===`blocked`)return{icon:(0,U.jsx)(W,{name:`stop`}),color:`#F5A623`};let t=e.avatar&&AY[e.avatar]?e.avatar:`thinking`;return{icon:AY[t],color:MY[t]}}function PY(e){let t=Math.max(1,Math.round((e??0)/1e3));if(t<60)return`Thought for ${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`Thought for ${n}m`:`Thought for ${n}m ${r}s`}var FY=`plan.md`;function IY(){let e=xS();return(0,U.jsxs)(`div`,{className:`operator-line msg-plan`,children:[(0,U.jsx)(W,{name:`file-md`,className:`icon-inline`}),(0,U.jsxs)(`span`,{children:[(0,U.jsx)(`button`,{type:`button`,className:`operator-line-link`,title:`Open ${FY}`,onClick:()=>e.openFile(FY),children:FY}),` `,`updated`]})]})}function LY(e){let t=xS();return(0,U.jsx)(`button`,{type:`button`,className:`msg-file`,title:`Open ${gF(e.loc)}`,onClick:()=>kF(t,e.loc),children:e.token})}function RY(e){let{text:t}=e,n=GC(),r=g.useMemo(()=>OF(t,HC),[t,n]),i=[],a=0;for(let e of r)e.start>a&&i.push(t.slice(a,e.start)),i.push((0,U.jsx)(LY,{loc:e.loc,token:t.slice(e.start,e.end)},e.start)),a=e.end;return a<t.length&&i.push(t.slice(a)),(0,U.jsx)(`span`,{children:i})}var zY=(0,U.jsx)(W,{name:`send`}),BY=(0,U.jsx)(W,{name:`stop`}),VY=(0,U.jsx)(W,{name:`chevron-down`}),HY=`openai/gpt-5.6-terra`,UY=[{value:`sonnet`,label:`Sonnet`},{value:`opus`,label:`Opus`},{value:`fable`,label:`Fable`}],WY=[{value:`low`,label:`Low`},{value:`medium`,label:`Med`},{value:`high`,label:`High`},{value:`xhigh`,label:`Extra`},{value:`max`,label:`Max`}],GY={sonnet:`Sonnet`,opus:`Opus`,fable:`Fable`};function KY(e){return e===`router`?{claude:`routerClaudeModel`,slug:`routerOpenrouterModel`,effort:`routerEffort`}:{claude:`tasksClaudeModel`,slug:`tasksOpenrouterModel`,effort:`tasksEffort`}}function qY(e){let t=e?.freeModel;return t&&t.trim()?t:null}function JY(e,t,n){let{claude:r,slug:i}=KY(e);if(t[r]!==`openrouter`)return`claude`;let a=qY(n);return a&&(n?.freeRoles?.[e]||t[i]?.trim()===a)?`muse`:`openrouter`}function YY(e){if(!e||!e.trim())return null;let t=e.trim(),n=t.lastIndexOf(`/`);return n>=0?t.slice(n+1):t}function XY(e,t,n){let{claude:r,slug:i}=KY(e),a=t[r];return JY(e,t,n)===`muse`?`Muse`:a===`openrouter`?YY(t[i])??`OpenRouter`:GY[a]??a??`?`}function ZY(e,t){return`${XY(`router`,e,t)} → ${XY(`tasks`,e,t)}`}function QY(e){let{label:t,placeholder:n,value:r,warning:i,discardOnUnmount:a,onCommit:o}=e,[s,c]=g.useState(r);g.useEffect(()=>c(r),[r]);let l=g.useRef(s),u=g.useRef(r),d=g.useRef(o);l.current=s,u.current=r,d.current=o;let f=()=>{let e=l.current.trim();return e&&e!==u.current?(d.current(e),!0):!1},p=()=>{f()||c(u.current)};g.useEffect(()=>{a&&(a.current=!1)},[a]),g.useEffect(()=>()=>{a?.current||f()},[a]);let m=e=>{c(e),o(e)};return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`div`,{className:`settings-row-main settings-model-detail`,children:[(0,U.jsx)(`span`,{className:`settings-label`,children:t}),(0,U.jsx)(`input`,{type:`text`,size:1,className:`text-field${i?` settings-text-warn`:``}`,value:s,placeholder:n,onChange:e=>c(e.target.value),onBlur:p,onKeyDown:e=>{e.key===`Enter`&&(p(),e.target.blur())}})]}),i?(0,U.jsxs)(`div`,{className:`settings-warning`,children:[`⚠ `,i.message,i.suggestion?(0,U.jsxs)(U.Fragment,{children:[` `,`Did you mean`,` `,(0,U.jsx)(`button`,{type:`button`,className:`settings-warning-suggest`,onMouseDown:e=>{e.preventDefault(),m(i.suggestion)},children:i.suggestion}),`?`]}):null]}):null]})}function $Y(e,t,n){let r=e?.[t];if(!(!r||!n||r.model!==n))return{message:r.message,suggestion:r.suggestion}}function eX(e){let{claude:t,slug:n,effort:r}=KY(e.role),i=e.role===`router`?`Operator model`:`Task model`,a=e.role===`router`?`Operator effort`:`Task effort`,o=qY(e.usage),s=JY(e.role,e.settings,e.usage),c=g.useRef(!1),l=UY.filter(t=>!e.blockedClaudeModels.includes(t.value)),u=e.role===`router`?`opus`:`sonnet`,d=l.some(e=>e.value===u)?u:l[0]?.value,f=r=>{if(r===s)return;if(r===`muse`){if(!o)return;c.current=!0,e.onSetSettings({[t]:`openrouter`,[n]:o});return}if(r===`claude`){if(!d)return;c.current=!0,e.onSetSetting(t,d);return}let i=e.settings[n]?.trim()??``;if(!i||i===o){e.onSetSettings({[t]:`openrouter`,[n]:HY});return}e.settings[t]!==`openrouter`&&e.onSetSetting(t,`openrouter`)},p=e=>e.preventDefault();return(0,U.jsxs)(`div`,{className:`settings-row settings-row-stack settings-model-picker`,children:[(0,U.jsxs)(`div`,{className:`settings-row-main`,children:[(0,U.jsx)(`span`,{className:`settings-label`,children:i}),(0,U.jsxs)(`div`,{className:`segmented settings-model-family`,role:`group`,"aria-label":i,children:[o?(0,U.jsxs)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":s===`muse`,onMouseDown:p,onClick:()=>f(`muse`),children:[(0,U.jsx)(`span`,{children:`Muse`}),(0,U.jsx)(`span`,{className:`settings-free-chip`,children:`FREE`})]}):null,[`claude`,`openrouter`].map(e=>(0,U.jsx)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":s===e,onMouseDown:p,onClick:()=>f(e),children:(0,U.jsx)(`span`,{children:e===`claude`?`Claude`:`OpenRouter`})},e))]})]}),e.hasAnthropicAccount&&e.settings[t]===`openrouter`?(0,U.jsx)(`div`,{className:`settings-warning`,children:`⚠ Pick Claude to use your Anthropic credentials`}):null,s===`claude`?(0,U.jsx)(`div`,{className:`settings-row-main settings-model-detail`,children:(0,U.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":`${e.role===`router`?`Operator`:`Task`} Claude model`,children:l.map(n=>(0,U.jsx)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":e.settings[t]===n.value,onClick:()=>{e.settings[t]!==n.value&&e.onSetSetting(t,n.value)},children:(0,U.jsx)(`span`,{children:n.label})},n.value))})}):null,s===`openrouter`?(0,U.jsx)(QY,{label:`OpenRouter slug`,placeholder:HY,value:e.settings[n]??``,discardOnUnmount:c,warning:$Y(e.warnings,n,e.settings[n]),onCommit:t=>e.onSetSetting(n,t)}):null,(0,U.jsxs)(`div`,{className:`settings-row-main settings-model-detail`,children:[(0,U.jsx)(`span`,{className:`settings-label`,children:a}),(0,U.jsx)(`div`,{className:`segmented`,role:`group`,"aria-label":a,children:WY.map(t=>(0,U.jsx)(`button`,{type:`button`,tabIndex:-1,className:`button`,"aria-pressed":(e.settings[r]??`medium`)===t.value,onClick:()=>{(e.settings[r]??`medium`)!==t.value&&e.onSetSetting(r,t.value)},children:(0,U.jsx)(`span`,{children:t.label})},t.value))})]})]})}function tX(e){if(!e||e.limitMicros===null||e.limitMicros<=0)return null;if(e.blocked)return 1;if(e.credits?.plan===`daily`&&e.credits.dailyFreeRemainingCredits!==null){let t=e.credits.dailyFreeRemainingCredits*1e4;return t<=0?1:Math.min(1,Math.max(0,e.usedMicros/(e.usedMicros+t)))}return Math.min(1,e.usedMicros/e.limitMicros)}function nX(e){let t=e?.autoReload;return!t?.enabled||t.disabledReason||t.thresholdCredits===null||t.amountCredits===null?null:{thresholdCredits:t.thresholdCredits,amountCredits:t.amountCredits}}function rX(e){if(e?.blocked)return`operator-usage-blocked`;if(e?.credits?.plan===`credits`)return e.credits.lowBalance&&!nX(e.credits)?`operator-usage-warn`:``;let t=tX(e);return t===null?``:t>=.8?`operator-usage-warn`:``}var iX=new Intl.NumberFormat(void 0,{style:`currency`,currency:`USD`});function aX(e){return iX.format(e/100)}function oX(e){return aX(e/1e4)}function sX(e,t){if(!t||t.displayUnit===`usd`||t.usdPerCredit<=0)return oX(e);let n=Math.round(e/1e6/t.usdPerCredit);return`${n.toLocaleString()} ${n===1?`credit`:`credits`}`}function cX(e){return e.resetAtMs?new Date(e.resetAtMs).toLocaleTimeString([],{hour:`numeric`,minute:`2-digit`}):``}function lX(e){let{usage:t}=e,n=tX(t);if(n===null)return null;let r=cX(t),i=t.credits?.plan===`daily`?t.credits.purchasedCredits+t.credits.grantedCredits:0,a=i>0?` + ${aX(i)} credits`:``,o=(t.blocked?`Limit reached`:`${Math.round(n*100)}%${r?` \u00b7 resets ${r}`:``}`)+a;return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`settings-row`,children:(0,U.jsx)(`span`,{className:`settings-label`,children:`Daily Operator usage`})}),(0,U.jsx)(`div`,{className:`settings-usage-bar`,children:(0,U.jsx)(`div`,{className:`settings-usage-fill`+(t.blocked?` blocked`:``),style:{width:`${n*100}%`}})}),(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:o})]})}function uX(e){let t=e.credits,n=t?.autoReload,r=nX(t),i=t?.rates,a=`${sX(e.creditsExhausted?0:e.spendableMicros??0,i)} left`,o=t?.nextGrantAt?`Refreshes ${new Date(t.nextGrantAt).toLocaleDateString()}`:null,s=r?`Auto-reload will add ${sX(r.amountCredits*1e4,i)} when you drop below ${sX(r.thresholdCredits*1e4,i)}`:null,c=cX(e),l=e.blocked?`Daily limit reached${c?` · Resets at ${c}`:``}`:null,u=!!n?.disabledReason,d=null;return e.creditsExhausted?d=u?{severity:`danger`,text:`Auto-reload was unsuccessful`,action:`Update your card`}:{severity:`danger`,text:`Out of credits`,action:`Set up auto-reload`}:t?.lowBalance&&!r&&(d=u?{severity:`danger`,text:`Auto-reload was unsuccessful`,action:`Update your card`}:{severity:`warn`,text:`Running low on credits`,action:`Set up auto-reload`}),{amount:a,caption:s,grant:o,dailyBlocked:l,banner:d}}function dX(e){let{usage:t,onRefreshUsage:n}=e;if(t.spendableMicros===null||t.freeTier&&t.creditsExhausted)return null;let r=uX(t);return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`settings-row`,children:(0,U.jsx)(`span`,{className:`settings-label`,children:`Operator credits`})}),(0,U.jsxs)(`div`,{className:`settings-split`,children:[(0,U.jsx)(`div`,{className:`settings-credits`,children:r.amount}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:()=>pX(n),children:(0,U.jsx)(`span`,{children:`Get credits`})})]}),r.caption?(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:r.caption}):null,r.grant?(0,U.jsx)(`div`,{className:`settings-usage-subtext`,children:r.grant}):null,r.dailyBlocked?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger settings-usage-subtext`,children:r.dailyBlocked}):null,r.banner?(0,U.jsxs)(`div`,{className:`feedback-banner feedback-${r.banner.severity} is-inset`,role:`status`,children:[(0,U.jsx)(`span`,{children:r.banner.text}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:()=>pX(n),children:(0,U.jsx)(`span`,{children:r.banner.action})})]}):null]})}function fX(e){return e.usage.credits?.plan===`credits`?(0,U.jsx)(dX,{usage:e.usage,onRefreshUsage:e.onRefreshUsage}):(0,U.jsx)(lX,{usage:e.usage})}function pX(e){if(window.ReactNativeWebView){window.ReactNativeWebView.postMessage(JSON.stringify({type:`castle-open-credits`}));return}if(!window.open(`https://castle.xyz/credits`,`_blank`))return;mX?.();let t=()=>{document.visibilityState===`visible`&&(mX?.(),e())};mX=()=>{document.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t),mX=null},document.addEventListener(`visibilitychange`,t),window.addEventListener(`focus`,t)}var mX=null;function hX(e){let t=e.providers.filter(e=>e.key?.present||e.login?.loggedIn).map(e=>e.label);return(0,U.jsxs)(`div`,{className:`settings-split`,children:[t.length>0?(0,U.jsxs)(`div`,{className:`settings-split-copy`,children:[(0,U.jsx)(`div`,{className:`settings-credits`,children:`Use your own agent provider`}),(0,U.jsxs)(`div`,{className:`settings-usage-subtext`,children:[`Connected: `,t.join(`, `)]})]}):(0,U.jsx)(`div`,{className:`settings-credits`,children:`Use your own agent provider`}),(0,U.jsx)(`button`,{type:`button`,className:`button`,onClick:e.onOpen,children:(0,U.jsx)(`span`,{children:t.length>0?`Manage providers`:`Add provider`})})]})}function gX(e){let{login:t}=e,[n,r]=g.useState(``),i=()=>{n.trim()&&e.onSubmitCode(n.trim())};return(0,U.jsxs)(U.Fragment,{children:[t.url?(0,U.jsxs)(`div`,{className:`castle-key-login`,children:[(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Open this link to sign in, then come back here.`}),(0,U.jsx)(`a`,{className:`castle-key-url`,href:t.url,target:`_blank`,rel:`noreferrer noopener`,children:t.url})]}):(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Starting sign-in…`}),t.phase===`awaiting-code`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Paste the code the browser shows you:`}),(0,U.jsx)(`input`,{className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,value:n,placeholder:`code`,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&i()}}),t.message?(0,U.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null]}):null,t.phase===`verifying`?(0,U.jsx)(`div`,{className:`castle-key-stored`,children:`Finishing sign-in…`}):null,t.phase===`error`?(0,U.jsx)(`div`,{className:`castle-key-error`,children:t.message}):null,(0,U.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:e.onCancel,children:t.phase===`error`?`Close`:`Cancel`}),t.phase===`awaiting-code`?(0,U.jsx)(`button`,{type:`button`,onClick:i,disabled:!n.trim(),children:`Submit`}):null]})]})}function _X(e){let t=e.accounts.providers,n=e.accounts.login,[r,i]=g.useState(()=>(t.find(e=>e.key?.present||e.login?.loggedIn)??t[0])?.id??``),[a,o]=g.useState(``),[s,c]=g.useState(null),l=(n?t.find(e=>e.login?.provider===n.provider):null)??t.find(e=>e.id===r)??t[0]??null,u=g.useRef(e.onClose);u.current=e.onClose;let d=n!==null;g.useEffect(()=>{let e=e=>{e.key===`Escape`&&!d&&u.current()};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[d]);let f=g.useRef(null);if(g.useEffect(()=>{if(n){f.current=n.provider;return}let e=f.current;e!==null&&(f.current=null,t.find(t=>t.login?.provider===e)?.login?.loggedIn&&u.current())}),!l)return null;let p=!!l.login?.loggedIn,m=!!l.key?.present,h=p||m,_=()=>{let t=a.trim();if(t){if(t.length>500){c(`That key is too long.`);return}if([...t].some(e=>{let t=e.codePointAt(0)??0;return t<32||t===127})){c(`That key contains invalid characters.`);return}e.onSave(l.id,t),e.onClose()}};return(0,tb.createPortal)((0,U.jsx)(`div`,{className:`castle-modal-scrim`,onMouseDown:n?void 0:e.onClose,children:(0,U.jsxs)(`div`,{className:`castle-modal`,onMouseDown:e=>e.stopPropagation(),children:[(0,U.jsx)(`div`,{className:`castle-key-heading`,children:n?`Sign in to ${l.label}`:`Your account`}),n?null:(0,U.jsx)(`div`,{className:`castle-key-subtitle`,children:`Run the operator on your own account and bypass Castle's daily limit.`}),t.length>1&&!n?(0,U.jsx)(`div`,{className:`castle-key-tabs`,children:t.map(e=>(0,U.jsx)(`button`,{type:`button`,className:`castle-key-tab`+(e.id===l.id?` active`:``),onClick:()=>{i(e.id),o(``),c(null)},children:e.label},e.id))}):null,n?(0,U.jsx)(gX,{login:n,onSubmitCode:e.onSubmitCode,onCancel:e.onCancelLogin}):(0,U.jsxs)(U.Fragment,{children:[h?(0,U.jsxs)(U.Fragment,{children:[p?(0,U.jsxs)(`div`,{className:`castle-key-row`,children:[(0,U.jsxs)(`span`,{children:[`Signed in with your `,l.label,` account.`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>{e.onLogout(l.id),e.onClose()},children:`Sign out`})]}):null,m?(0,U.jsxs)(`div`,{className:`castle-key-row`,children:[(0,U.jsxs)(`span`,{children:[`API key saved (`,l.key?.hint,`).`]}),(0,U.jsx)(`button`,{type:`button`,onClick:()=>{e.onRemove(l.id),e.onClose()},children:`Remove`})]}):null]}):(0,U.jsxs)(U.Fragment,{children:[l.login?(0,U.jsxs)(`button`,{type:`button`,className:`castle-key-signin`,onClick:()=>e.onStartLogin(l.id),children:[`Sign in with your `,l.label,` account`]}):null,l.login&&l.key?(0,U.jsx)(`div`,{className:`castle-key-or`,children:`or`}):null,l.key?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`castle-key-field-label`,children:`Add API key`}),(0,U.jsx)(`input`,{type:`password`,className:`castle-key-input`,autoFocus:!0,spellCheck:!1,autoComplete:`off`,"data-1p-ignore":!0,"data-lpignore":`true`,value:a,placeholder:l.key.placeholder,onChange:e=>{o(e.target.value),c(null)},onKeyDown:e=>{e.key===`Enter`&&_()}}),s?(0,U.jsx)(`div`,{className:`castle-key-error`,children:s}):null]}):null]}),(0,U.jsxs)(`div`,{className:`castle-modal-actions`,children:[(0,U.jsx)(`button`,{type:`button`,onClick:e.onClose,children:`Cancel`}),!h&&l.key?(0,U.jsx)(`button`,{type:`button`,onClick:_,disabled:!a.trim(),children:`Save`}):null]})]})]})}),document.body)}function vX(e){let{settings:t,onSetSetting:n,onClose:r}=e,i=e.usage?.credits?.plan===`credits`?e.usage.spendableMicros!==null:tX(e.usage)!==null,a=e.accounts.providers.some(e=>e.key?.present||e.login?.loggedIn),o=e.accounts.providers.some(e=>e.id===`anthropic`&&(e.key?.present||e.login?.loggedIn)),s=e.accounts.providers.length>0&&(i||a),c=g.useRef(null),l=e.usage?.blockedClaudeModels??[];return Sw(c,r,e.triggerRef),(0,tb.createPortal)((0,U.jsxs)(`div`,{className:`popover settings-popover`,ref:c,style:Ew(c,e.triggerRef,[t,i,s,e.usage,o]),onMouseDown:e=>e.stopPropagation(),children:[i&&e.usage?(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)(fX,{usage:e.usage,onRefreshUsage:e.onRefreshUsage})}):null,s?(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)(hX,{providers:e.accounts.providers,onOpen:e.onOpenKeys})}):null,(0,U.jsx)(`div`,{className:`settings-model-pickers`,children:[`router`,`tasks`].map(r=>(0,U.jsx)(`div`,{className:`settings-group`,children:(0,U.jsx)(eX,{role:r,settings:t,warnings:e.warnings,usage:e.usage,blockedClaudeModels:l,hasAnthropicAccount:o,onSetSetting:n,onSetSettings:e.onSetSettings})},r))})]}),document.body)}function yX(e){let{spec:t,interactive:n,answers:r,onSubmit:i}=e,[a,o]=g.useState({}),s=n?a:r??{},c=(e,t)=>{n&&o(n=>{let r=(n[e.id]??[]).filter(e=>e!==gY),i=r.filter(t=>!e.options.includes(t)),a=yY(e,r);if(e.multi){let r=a.includes(t)?a.filter(e=>e!==t):[...a,t];return{...n,[e.id]:[...r,...i]}}return{...n,[e.id]:a[0]===t&&i.length===0?[]:[t]}})},l=e=>{n&&o(t=>({...t,[e.id]:vY(t[e.id])?[]:[gY]}))},u=g.useRef({}),d=e=>{if(!n)return;let t=!xY(e,s[e.id]);(0,tb.flushSync)(()=>{o(t=>{let n=t[e.id]??[];if(xY(e,n))return{...t,[e.id]:yY(e,n)};let r=yY(e,n),i=bY(e,n);return{...t,[e.id]:e.multi?[...r,i]:[i]}})}),t&&u.current[e.id]?.focus()},f=(e,t)=>{n&&o(n=>{let r=yY(e,n[e.id]);return{...n,[e.id]:e.multi?[...r,t]:[t]}})};return(0,U.jsxs)(`div`,{className:`picker${n?``:` picker-locked`}`,children:[t.questions.map(e=>{let t=s[e.id],r=vY(t),i=!r&&xY(e,t),a=r?``:bY(e,t),o=!n||r;return(0,U.jsxs)(`fieldset`,{className:`picker-q${r?` is-skipped`:``}`,disabled:!n,children:[(0,U.jsxs)(`legend`,{className:`picker-q-head`,children:[(0,U.jsx)(`span`,{className:`picker-q-label`,children:e.q}),(0,U.jsx)(`button`,{type:`button`,className:`picker-skip text-style-smallcaps${r?` is-on`:``}`,"aria-pressed":r,disabled:!n,onClick:t=>{t.preventDefault(),t.stopPropagation(),l(e)},children:`Skip`})]}),(0,U.jsxs)(`div`,{className:`picker-options`,children:[e.options.map(n=>{let i=!r&&(t??[]).includes(n);return(0,U.jsxs)(`label`,{className:`picker-option${i?` is-checked`:``}`,children:[(0,U.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:i,disabled:o,onChange:()=>c(e,n)}),(0,U.jsx)(`span`,{children:n})]},n)}),(0,U.jsxs)(`div`,{className:`picker-option picker-option-other${i?` is-checked`:``}`,children:[(0,U.jsxs)(`label`,{className:`picker-other-toggle`,children:[(0,U.jsx)(`input`,{type:e.multi?`checkbox`:`radio`,name:e.id,checked:i,disabled:o,"aria-label":`Other`,onChange:()=>d(e)}),i?null:(0,U.jsx)(`span`,{className:`picker-other-label`,children:`Other`})]}),i?(0,U.jsx)(`input`,{ref:t=>{u.current[e.id]=t},type:`text`,className:`picker-other-input`,value:a,disabled:o,"aria-label":`Other`,onChange:t=>f(e,t.target.value)}):null]})]})]},e.id)}),n?(0,U.jsx)(`div`,{className:`picker-actions`,children:(0,U.jsx)(`button`,{className:`button`,type:`button`,onClick:()=>{let e=kY(t,a);e&&i(a,e)},children:(0,U.jsx)(`span`,{children:`Submit`})})}):r?(0,U.jsx)(`div`,{className:`picker-actions`,children:(0,U.jsx)(`button`,{className:`button`,type:`button`,disabled:!0,children:(0,U.jsx)(`span`,{children:`Submitted`})})}):null]})}function bX(e){let{chips:t,interactive:n,onPick:r}=e,[i,a]=g.useState(null),o=n&&i===null;return(0,U.jsx)(`div`,{className:`chips`+(o?``:` chips-inert`),children:t.map(e=>(0,U.jsx)(`button`,{type:`button`,className:`chip`+(i===e?` is-picked`:``),disabled:!o,onClick:()=>{a(e),r(e)},children:e},e))})}function xX(){return(0,U.jsxs)(`div`,{className:`picker picker-skeleton`,"aria-hidden":`true`,children:[(0,U.jsx)(`span`,{className:`picker-skeleton-hint`,children:`preparing options…`}),(0,U.jsxs)(`div`,{className:`picker-q`,children:[(0,U.jsxs)(`div`,{className:`picker-q-head`,children:[(0,U.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-label`}),(0,U.jsx)(`div`,{className:`picker-skeleton-line picker-skeleton-skip`})]}),(0,U.jsxs)(`div`,{className:`picker-options`,children:[(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:84}}),(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:116}}),(0,U.jsx)(`span`,{className:`picker-skeleton-chip`,style:{width:72}})]})]})]})}function SX(e){let t=/^\[Editing (.+)\]$/,n=/^\[Reading (.+)\]$/,r=new Set;for(let n of e){let e=t.exec(n.trim());if(e)for(let t of e[1].split(`, `))r.add(t)}let i=[];for(let t of e){let e=n.exec(t.trim());if(e){let t=e[1].split(`, `).filter(e=>!r.has(e));if(t.length===0)continue;i.push(`[Reading ${t.join(`, `)}]`);continue}i.push(t)}return i}function CX(e){let t=/^\[([A-Za-z]+)\s+(.+)\]$/,n=[];for(let r of e){let e=t.exec(r.trim());if(e){let r=n.length?t.exec(n[n.length-1].trim()):null;if(r&&r[1]===e[1]){r[2].split(`, `).includes(e[2])||(n[n.length-1]=`[${e[1]} ${r[2]}, ${e[2]}]`);continue}}n.push(r)}return n}function wX(e){return e.detail?(0,U.jsxs)(`details`,{className:`msg-error-detail`,children:[(0,U.jsxs)(`summary`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`warning`,className:`icon-inline`}),(0,U.jsx)(`span`,{children:`Details`}),(0,U.jsx)(W,{name:`chevron-right`,className:`icon-inline thinking-caret`})]}),(0,U.jsxs)(`div`,{className:`msg-error-detail-body`,children:[(0,U.jsx)(`p`,{className:`msg-error-detail-hint`,children:`View the full text in the browser console`}),(0,U.jsx)(`pre`,{children:e.detail})]})]}):null}function TX(e){let t=ZJ(),n=g.useRef(null),r=g.useRef(!0);return g.useLayoutEffect(()=>{let e=n.current;e&&r.current&&(e.scrollTop=e.scrollHeight)},[e.lines]),(0,U.jsx)(`div`,{className:`task-feed`,ref:n,onScroll:()=>{let e=n.current;e&&(r.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},onClick:e=>e.stopPropagation(),children:CX(SX(e.lines)).map((e,n)=>{let r=/^\[(.+)\]$/.exec(e.trim());return r?(0,U.jsx)(`div`,{className:`task-feed-tool`,children:r[1]},n):(0,U.jsx)(`div`,{className:`task-feed-msg`,onClick:t,dangerouslySetInnerHTML:YJ(e)},n)})})}function EX(e){let t=Math.max(0,Math.round(e/1e3)),n=Math.floor(t/60),r=t%60;return n>0?`${n}m ${r}s`:`${r}s`}function DX(e,t,n){return t?`${e} · ${t}`:n?`${e} · Worked for ${n}`:e}function OX(e){let[t,n]=g.useState(()=>Date.now());g.useEffect(()=>{if(e.status!==`running`)return;let t=setInterval(()=>n(Date.now()),1e3);return()=>clearInterval(t)},[e.status]);let r=e.startedAt?Date.parse(e.startedAt):null,i=e.finishedAt?Date.parse(e.finishedAt):null,a=C.includes(e.status),o=e.status===`done`?100:a?e.progress:Math.min(e.progress,95),s=e.status===`running`?e.phase?.trim()||jY[e.avatar??``]||`Working`:e.status===`waiting`?`Queued`:e.status===`blocked`?`Blocked`:e.status===`done`?`Done`:e.status===`failed`?`Failed`:e.status===`interrupted`?`Interrupted`:e.status,c=e.status===`running`&&r!==null?EX(t-r):null,l=a&&r!==null&&i!==null?EX(i-r):null;return{pct:o,avatar:NY(e),stage:s,elapsed:c,workedFor:l,finished:a,display:oY(e)}}function kX(e){let{task:t,onAck:n}=e,r=e.variant===`archive`,i=ZJ(),[a,o]=g.useState(t.status===`failed`);g.useEffect(()=>{t.status===`failed`&&o(!0)},[t.status]);let s=()=>{o(e=>!e)},{pct:c,avatar:l,stage:u,elapsed:d,workedFor:f,finished:p,display:m}=OX(t);return(0,U.jsxs)(`div`,{className:`task${a?` open`:``}`,onClick:s,children:[(0,U.jsxs)(`div`,{className:`task-row`,children:[(0,U.jsx)(`div`,{className:`pie`,style:{"--pct":c},children:(0,U.jsx)(`div`,{className:`avatar`,style:{background:l.color},children:(0,U.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:l.icon})})}),(0,U.jsxs)(`div`,{className:`task-meta`,children:[(0,U.jsx)(`div`,{className:`task-name`,children:(0,U.jsx)(`span`,{className:`tn`,children:t.title})}),(0,U.jsx)(`div`,{className:`task-sub`,children:DX(u,d,f)})]}),(0,U.jsxs)(`div`,{className:`task-actions`,children:[p&&!r?(0,U.jsx)(`button`,{className:`button button-icon task-action`,type:`button`,title:`Clear`,"aria-label":`Clear ${t.title}`,onClick:e=>{e.stopPropagation(),n(t.id,!1)},children:(0,U.jsx)(W,{name:`archive`})}):null,e.onOpen?(0,U.jsx)(`button`,{className:`button button-icon task-action`,type:`button`,title:`Open`,"aria-label":`Open ${t.title}`,onClick:n=>{n.stopPropagation(),e.onOpen?.(t)},children:(0,U.jsx)(W,{name:`chevron-right`})}):null]})]}),(0,U.jsxs)(`div`,{className:`task-body`,children:[a&&t.status===`running`&&e.feed&&e.feed.length>0?(0,U.jsx)(TX,{lines:e.feed}):null,a&&t.status!==`running`&&m.error?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger`,children:m.error}):null,a&&t.status!==`running`&&m.notes?(0,U.jsx)(`div`,{className:`task-notes`,onClick:i,dangerouslySetInnerHTML:YJ(m.notes)}):null,a&&t.status===`failed`?(0,U.jsx)(wX,{detail:t.errorDetail}):null,a?(0,U.jsx)(AX,{frames:t.playtestFrames}):null]})]})}function AX(e){let t=e.frames??[];return t.length===0?null:(0,U.jsxs)(`div`,{className:`task-playtest-frames`,children:[(0,U.jsxs)(`div`,{className:`task-playtest-frames-label`,children:[`Playtest frames (`,t.length,`)`]}),(0,U.jsx)(`div`,{className:`task-playtest-frames-row`,children:t.map(e=>(0,U.jsx)(`a`,{href:e,target:`_blank`,rel:`noreferrer`,onClick:e=>e.stopPropagation(),children:(0,U.jsx)(`img`,{className:`task-playtest-frame`,src:e,alt:`playtest frame`})},e))})]})}function jX(e){return e.filter(e=>!(e.acknowledged&&C.includes(e.status)))}function MX(e){let t=g.useRef(null),n=g.useRef(!0),r=g.useRef(0),[i,a]=g.useState(!1),o=jX(e.tasks);g.useLayoutEffect(()=>{let e=t.current;e&&n.current&&(e.scrollTop=e.scrollHeight)},[e.tasks]),g.useEffect(()=>()=>window.clearTimeout(r.current),[]);let s=()=>{let e=t.current;e&&(n.current=e.scrollHeight-e.scrollTop-e.clientHeight<24,a(!0),window.clearTimeout(r.current),r.current=window.setTimeout(()=>a(!1),900))};if(o.length===0)return null;let c=o.filter(e=>C.includes(e.status));return(0,U.jsxs)(`div`,{id:`task-board`,className:`task-stack${i?` scrolling`:``}`,ref:t,onScroll:s,children:[(0,U.jsxs)(`div`,{className:`task-board-header`,children:[(0,U.jsxs)(`button`,{type:`button`,className:`button`,onClick:e.onOpenTasks,children:[(0,U.jsx)(`span`,{children:`Tasks`}),(0,U.jsx)(W,{name:`chevron-right`})]}),c.length>0?(0,U.jsxs)(`button`,{type:`button`,className:`button`,onClick:()=>{for(let t of c)e.onAck(t.id,!1)},children:[(0,U.jsx)(W,{name:`archive`}),(0,U.jsx)(`span`,{children:`Clear completed`}),(0,U.jsx)(`span`,{className:`button-badge`,children:c.length})]}):null]}),o.map(t=>(0,U.jsx)(kX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask},t.id))]})}function NX(e){let{task:t}=e,{pct:n,avatar:r,stage:i,elapsed:a,workedFor:o}=OX(t);return(0,U.jsx)(`header`,{className:`task-page-header`,children:(0,U.jsxs)(`div`,{className:`task-row`,children:[(0,U.jsx)(`div`,{className:`pie`,style:{"--pct":n},children:(0,U.jsx)(`div`,{className:`avatar`,style:{background:r.color},children:(0,U.jsx)(`span`,{className:`avatar-icon-wrap`,"aria-hidden":`true`,children:r.icon})})}),(0,U.jsxs)(`div`,{className:`task-meta`,children:[(0,U.jsx)(`div`,{className:`task-name`,children:(0,U.jsx)(`span`,{className:`tn`,children:t.title})}),(0,U.jsx)(`div`,{className:`task-sub`,children:DX(i,a,o)})]})]})})}function PX(e){let{task:t}=e,n=ZJ(),r=g.useRef(null),i=g.useRef(!0),a=e.feed??[],o=oY(t),s=t.status===`running`,c=a.length>0,l=!s&&(!!o.error||!!o.notes);return g.useLayoutEffect(()=>{i.current=!0},[t.id]),g.useLayoutEffect(()=>{let e=r.current;e&&i.current&&(e.scrollTop=e.scrollHeight)},[t.id,e.feed,o.notes,o.error,t.status,t.playtestFrames]),(0,U.jsxs)(`div`,{className:`task-page`,children:[(0,U.jsx)(NX,{task:t}),(0,U.jsxs)(`div`,{className:`task-page-body`,ref:r,onScroll:()=>{let e=r.current;e&&(i.current=e.scrollHeight-e.scrollTop-e.clientHeight<24)},children:[c?(0,U.jsx)(TX,{lines:a}):null,l&&o.error?(0,U.jsx)(`p`,{className:`feedback-note feedback-danger`,children:o.error}):null,l&&o.notes?(0,U.jsxs)(`div`,{className:`task-notes`,onClick:n,children:[(0,U.jsx)(`p`,{className:`task-report-label`,children:`Report`}),(0,U.jsx)(`div`,{dangerouslySetInnerHTML:YJ(o.notes)})]}):null,t.status===`failed`?(0,U.jsx)(wX,{detail:t.errorDetail}):null,(0,U.jsx)(AX,{frames:t.playtestFrames}),!c&&!l&&!(t.playtestFrames&&t.playtestFrames.length>0)?(0,U.jsx)(`p`,{className:`task-page-empty`,children:`No activity yet.`}):null]})]})}function FX(e){let t=jX(e.tasks),n=fY(e.tasks);return(0,U.jsxs)(`div`,{className:`task-page-body task-board-page`,children:[t.length>0?(0,U.jsx)(`div`,{className:`task-stack`,children:t.map(t=>(0,U.jsx)(kX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask},t.id))}):null,n.length>0?(0,U.jsxs)(`div`,{className:`task-archive task-stack`,children:[(0,U.jsx)(`div`,{className:`task-archive-heading text-style-smallcaps`,children:`Cleared`}),n.map(t=>(0,U.jsx)(kX,{task:t,feed:e.feeds[t.id],onAck:e.onAck,onOpen:e.onOpenTask,variant:`archive`},t.id))]}):null,t.length===0&&n.length===0?(0,U.jsx)(`p`,{className:`task-page-empty`,children:`No tasks yet.`}):null]})}function IX(e){let{msg:t,onPickerSubmit:n,onChip:r,chipsLive:i=!1,interactive:a=!1}=e,o=ZJ();if(t.role===`log`)return(0,U.jsx)(`div`,{className:`msg toolline`,children:t.text});if(t.role===`user`)return(0,U.jsxs)(`div`,{className:`msg user`,children:[(t.attachments??[]).map(e=>(0,U.jsx)(`img`,{className:`msg-image`,src:e,alt:``},e)),t.text?(0,U.jsx)(RY,{text:t.text}):null]});let s=t.status===`streaming`,c=DY(t.text,s),l=OY(c)||t.planUpdated===!0;if(!s&&!l)return null;let u=!s&&!t.pickerAnswers&&a,d=-1;c.forEach((e,t)=>{e.kind===`md`&&e.text.trim()!==``&&(d=t)});let f=c.some(e=>e.kind===`ask`||e.kind===`ask-pending`),p=s&&d===-1&&!f||!!(s&&t.activity),m=t.activity??`Thinking`;return(0,U.jsxs)(`div`,{className:`assistant-turn`,onClick:o,children:[t.thinking&&t.thinking.trim()?(0,U.jsxs)(`details`,{className:`msg-thinking`+(p?` is-active`:``),children:[(0,U.jsxs)(`summary`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`lightbulb`,className:`icon-inline`}),(0,U.jsx)(`span`,{className:`thinking-label`,children:p?m:PY(t.thinkingMs)}),(0,U.jsx)(W,{name:`chevron-right`,className:`icon-inline thinking-caret`})]}),(0,U.jsx)(`div`,{className:`msg-thinking-body`,dangerouslySetInnerHTML:YJ(t.thinking??``)})]}):p?(0,U.jsxs)(`div`,{className:`operator-line msg-thinking is-active`,children:[(0,U.jsx)(W,{name:`lightbulb`,className:`icon-inline`}),(0,U.jsx)(`span`,{className:`thinking-label`,children:m})]}):null,c.map((e,a)=>{if(e.kind===`ask-pending`)return(0,U.jsx)(xX,{},a);if(e.kind===`chips`)return(0,U.jsx)(bX,{chips:e.chips,interactive:!s&&i,onPick:r},a);if(e.kind===`ask`)return(0,U.jsx)(yX,{spec:e.spec,interactive:u,answers:t.pickerAnswers,onSubmit:(e,r)=>n(t,e,r)},a);if(!e.text.trim())return null;let o=[`msg`,`assistant`,`md`];return s&&a===d&&o.push(`streaming`),t.status===`error`&&o.push(`errbubble`),(0,U.jsx)(`div`,{className:o.join(` `),dangerouslySetInnerHTML:YJ(e.text)},a)}),s?null:(0,U.jsx)(wX,{detail:t.errorDetail}),t.planUpdated?(0,U.jsx)(IY,{}):null,t.interrupted?(0,U.jsxs)(`div`,{className:`operator-line`,children:[(0,U.jsx)(W,{name:`square`,className:`icon-inline`}),(0,U.jsx)(`span`,{children:`Interrupted by your next message`})]}):null]})}function LX(e){let t=g.useRef(null),n=g.useRef(null),r=g.useRef(0),i=g.useRef(!0),a=g.useRef(0),o=g.useRef(0),[s,c]=g.useState(!1),l=g.useRef(!1),u=g.useCallback(()=>{l.current=!0,c(!0)},[]),d=g.useCallback(()=>{let e=t.current;if(!e)return;let n=Math.max(0,e.scrollHeight-e.clientHeight),r=Math.abs(e.scrollTop-n)>1;e.scrollTop=n,r&&(a.current=typeof performance<`u`?performance.now():Date.now())},[]);e.pinThreadRef.current=()=>{i.current&&d()};let f=g.useCallback(()=>{d();let e=t.current;e&&e.clientHeight>0&&u()},[d,u]);g.useLayoutEffect(()=>{if(!i.current)return;f();let e=requestAnimationFrame(f),t=window.setTimeout(f,250),n=window.setTimeout(u,500);return()=>{cancelAnimationFrame(e),clearTimeout(t),clearTimeout(n)}},[e.messages,f,u]),g.useEffect(()=>{let e=t.current;if(!e)return;o.current=e.clientHeight;let a=new ResizeObserver(()=>{o.current=e.clientHeight,i.current?f():e.scrollTop=e.scrollHeight-e.clientHeight-r.current});return a.observe(e),n.current&&a.observe(n.current),()=>a.disconnect()},[f]);let p=()=>{let e=t.current;if(!e||!l.current||(typeof performance<`u`?performance.now():Date.now())-a.current<200)return;let n=e.clientHeight,s=n!==o.current;o.current=n,!s&&(r.current=e.scrollHeight-e.scrollTop-e.clientHeight,i.current=r.current<48)},m=zX(e.messages),h=BX(e.messages);return(0,U.jsx)(`div`,{id:`chat-messages`,className:`chat-scroll`,"data-castle-allow-select":``,ref:t,onScroll:p,children:(0,U.jsxs)(`div`,{className:`chat-thread`+(s?` ready`:``),ref:n,children:[e.messages.length===0?(0,U.jsx)(`div`,{id:`chat-empty`,children:`Tell the agent what you want to make.`}):null,e.messages.map(t=>(0,U.jsx)(IX,{msg:t,interactive:t.id===m,chipsLive:t.id===h,onPickerSubmit:e.onPickerSubmit,onChip:e.onChip},t.id))]})})}function RX(e){return e.role!==`assistant`||e.pickerAnswers?!1:DY(e.text).some(e=>e.kind===`ask`)}function zX(e){for(let t=e.length-1;t>=0;t--)if(RX(e[t]))return e[t].id;return null}function BX(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if(n.role===`user`)return null;if(n.role===`assistant`){if(n.status===`streaming`)return null;if(DY(n.text).some(e=>e.kind===`chips`))return n.id}}return null}function VX(e,t){for(let n of Array.from(e)){if(!n.type.startsWith(`image/`))continue;let e=new FileReader;e.onload=()=>{typeof e.result==`string`&&t({name:n.name,dataUrl:e.result})},e.readAsDataURL(n)}}function HX(e){return e.pending.length===0?null:(0,U.jsx)(`div`,{id:`chat-pending`,children:e.pending.map((t,n)=>(0,U.jsx)(`img`,{className:`operator-thumb`,src:t.dataUrl,alt:t.name,title:`remove`,onClick:()=>e.onRemove(n)},`${t.name}-${n}`))})}function UX(e){return e.queued.length===0?null:(0,U.jsx)(`div`,{className:`chat-queue`,onMouseDown:e=>e.preventDefault(),children:e.queued.map((t,n)=>(0,U.jsxs)(`div`,{className:`queue-row`,children:[(0,U.jsx)(`span`,{className:`queue-snippet`,children:t.length>60?`${t.slice(0,60)}\u2026`:t}),(0,U.jsx)(`button`,{className:`button`,type:`button`,tabIndex:-1,title:`Send now — interrupts the turn`,onClick:e.onInterrupt,children:(0,U.jsx)(`span`,{children:`Send now`})}),(0,U.jsx)(`button`,{className:`button button-icon button-quiet`,type:`button`,tabIndex:-1,title:`Remove from queue`,"aria-label":`Remove`,onClick:()=>e.onCancelQueued(n),children:(0,U.jsx)(W,{name:`times`})})]},n))})}function WX(e,t){if(!e)return;e.style.height=`auto`;let n=Number.parseFloat(window.getComputedStyle(e).lineHeight),r=Number.isFinite(n)?Math.ceil(n):21,i=t.length===0?r:Math.min(e.scrollHeight,120);e.style.height=i>0?`${i}px`:``}function GX(e){let{running:t,queued:n}=e,[r,i]=g.useState(``),[a,o]=g.useState(!1),[s,c]=g.useState(!1),l=g.useRef(null),[u,d]=g.useState([]),[f,p]=g.useState(!1);g.useEffect(()=>{t||p(!1)},[t]);let m=g.useRef(null),h=g.useRef(null),_=iY({inputRef:m,anchorRef:h,setValue:i});g.useLayoutEffect(()=>{WX(m.current,r),e.pinThreadRef.current()},[r,u.length,n.length,e.pinThreadRef]);let v=e=>{d(t=>t.length>=6?t:[...t,e])},y=()=>{let t=r.trim();!t&&u.length===0||(e.onSend(t,u,_.attachedIn(t)),i(``),d([]),_.clear())},b=r.trim().length>0||u.length>0,x=e=>{let t=e.target;h.current?.contains(t)&&(t instanceof Element&&t.closest(`.composer-settings .button, #chat-send`)||m.current?.focus())},S=t&&!b;return(0,U.jsxs)(`div`,{className:`operator-composer`,children:[(0,U.jsx)(HX,{pending:u,onRemove:e=>d(t=>t.filter((t,n)=>n!==e))}),_.overlay,(0,U.jsxs)(`div`,{className:`chat-input`,ref:h,children:[(0,U.jsx)(UX,{queued:n,onInterrupt:e.onInterrupt,onCancelQueued:e.onCancelQueued}),(0,U.jsxs)(`div`,{className:`ta`,onClick:x,children:[(0,U.jsx)(`textarea`,{id:`chat-input`,className:`ta-text`,ref:m,rows:1,placeholder:t?`Queue a message…`:`Message the operator`,value:r,onChange:e=>{i(e.target.value),_.sync()},onSelect:_.sync,onPaste:e=>{let t=e.clipboardData?.files;t&&t.length>0&&(e.preventDefault(),VX(t,v))},onKeyDown:e=>{_.handleKeyDown(e)||e.key===`Enter`&&!e.shiftKey&&!e.metaKey&&!e.altKey&&(e.preventDefault(),y())}}),(0,U.jsxs)(`div`,{className:`ta-bottom`,onMouseDown:e=>e.preventDefault(),children:[(0,U.jsxs)(`div`,{className:`composer-settings`,children:[(0,U.jsxs)(`button`,{ref:l,className:[`button`,`button-quiet`,rX(e.usage)].filter(Boolean).join(` `),type:`button`,tabIndex:-1,title:`Agent & model settings`,"aria-label":`Agent & model settings`,"aria-pressed":a,onMouseDown:e=>{e.preventDefault(),e.stopPropagation()},onClick:()=>{a||e.onRefreshUsage(),o(e=>!e)},children:[(0,U.jsx)(`span`,{children:ZY(e.settings,e.usage)}),VY]}),a?(0,U.jsx)(vX,{settings:e.settings,warnings:e.settingsWarnings,usage:e.usage,accounts:e.accounts,triggerRef:l,onSetSetting:e.onSetSetting,onSetSettings:e.onSetSettings,onOpenKeys:()=>c(!0),onRefreshUsage:e.onRefreshUsage,onClose:()=>o(!1)}):null,s?(0,U.jsx)(_X,{accounts:e.accounts,onSave:e.onSetCredential,onRemove:e.onClearCredential,onStartLogin:e.onStartLogin,onSubmitCode:e.onSubmitLoginCode,onCancelLogin:e.onCancelLogin,onLogout:e.onLogout,onClose:()=>c(!1)}):null]}),(0,U.jsx)(`button`,{id:`chat-send`,className:`button button-icon composer-action`,type:`button`,tabIndex:-1,title:S?f?`Stopping…`:`Stop`:`Send`,"aria-label":S?f?`Stopping`:`Stop`:`Send`,disabled:!S&&!b||S&&f,onClick:()=>{S?(p(!0),e.onInterrupt()):y()},children:S?BY:zY})]})]})]})]})}function KX(e){let{agent:t,mobile:n,active:r}=e,{messages:i,tasks:a,feeds:o,settings:s,running:c,queued:l}=t,u=uY(n),[d,f]=g.useState(null),p=g.useRef(()=>{}),m=dY(d),h=e=>{u.openView(e.id)};Tb(()=>!r||u.view===`chat`||u.view===`tasks`&&!n?!1:(u.goChat(),!0));let _=(e,n,r)=>{t.submitPicker(e.id,n,r)},v=e=>{t.sendUserMessage(e,[],[])},y=u.view!==`chat`&&u.view!==`tasks`?a.find(e=>e.id===u.view):void 0;return(0,U.jsxs)(`div`,{id:`chat-host`,ref:f,children:[m?(0,U.jsx)(pY,{view:u.view,openIds:u.openIds,tasks:a,mobile:n,onChat:u.goChat,onSelect:u.openView,onClose:u.closeView,onReorder:u.reorderOpenIds,slot:m}):null,(0,U.jsx)(`div`,{className:`operator-inset`,children:u.view===`chat`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(MX,{tasks:a,feeds:o,onAck:t.ackTask,onOpenTask:h,onOpenTasks:()=>u.openView(cY)}),jX(a).length>0?(0,U.jsx)(`div`,{className:`chat-divider`,"aria-hidden":`true`}):null,(0,U.jsx)(LX,{messages:i,onPickerSubmit:_,onChip:v,pinThreadRef:p})]}):u.view===`tasks`?(0,U.jsx)(FX,{tasks:a,feeds:o,onAck:t.ackTask,onOpenTask:h}):y?(0,U.jsx)(PX,{task:y,feed:o[y.id]}):(0,U.jsx)(`p`,{className:`task-page-empty`,children:`This task is gone.`})}),(0,U.jsx)(GX,{pinThreadRef:p,running:c,queued:l,onSend:t.sendUserMessage,onInterrupt:t.interrupt,onCancelQueued:t.cancelQueued,settings:s,settingsWarnings:t.settingsWarnings,usage:t.usage,accounts:t.accounts,onSetSetting:t.setSetting,onSetSettings:t.setSettings,onRefreshUsage:t.refreshUsage,onSetCredential:t.setCredential,onClearCredential:t.clearCredential,onStartLogin:t.startLogin,onSubmitLoginCode:t.submitLoginCode,onCancelLogin:t.cancelLogin,onLogout:t.logout})]})}function qX(e,t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function JX(e,t){return e.messageId===t.messageId&&qX(e.taskIds,t.taskIds)}function YX(e,t,n,r,i){if(!t)return i;let a=n[n.length-1]??``;return e||i.messageId===void 0?{messageId:a,taskIds:r}:i.messageId!==``&&n.length>0&&!n.includes(i.messageId)?{messageId:a,taskIds:i.taskIds}:i.taskIds===void 0?{messageId:i.messageId,taskIds:r}:i}function XX(e,t){if(t===void 0)return 0;if(t===``)return e.length;let n=e.indexOf(t);return n<0?0:e.length-n-1}function ZX(e,t){if(t===void 0)return 0;let n=new Set(t),r=0;for(let t of e)n.has(t)||(r+=1);return r}function QX(e,t,n){return XX(e,n.messageId)+ZX(t,n.taskIds)}var $X=`castle-operator-seen-v1`,eZ=`castle-operator-seen-v2`;function tZ(){try{let e=localStorage.getItem(eZ);if(e!==null){let t=JSON.parse(e);if(t&&typeof t==`object`){let e=t,n=e.taskIds;return{messageId:typeof e.messageId==`string`?e.messageId:void 0,taskIds:Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:void 0}}}let t=localStorage.getItem($X);if(t!==null)return{messageId:t,taskIds:void 0}}catch{}return{messageId:void 0,taskIds:void 0}}function nZ(e,t){try{localStorage.setItem(eZ,JSON.stringify({messageId:e,taskIds:t}))}catch{}}function rZ(e){let t=[];for(let n of e)n.role===`assistant`&&n.status!==`streaming`&&t.push(n.id);return t}function iZ(e){let t=[];for(let n of e)C.includes(n.status)&&!n.acknowledged&&t.push(n.id);return t}function aZ(){let[e,t]=g.useState(()=>document.visibilityState===`visible`);return g.useEffect(()=>{let e=()=>t(document.visibilityState===`visible`);return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),e}function oZ(e){let t=e.boundingClientRect;if(t.width<=0||t.height<=0)return!1;let n=e.intersectionRect;return n.width>=t.width-1&&n.height>=t.height-1}var sZ=Array.from({length:21},(e,t)=>t/20);function cZ(e){let[t,n]=g.useState(!1);return g.useEffect(()=>{if(!e){n(!1);return}let t=new IntersectionObserver(([e])=>n(e?oZ(e):!1),{threshold:sZ});return t.observe(e),()=>t.disconnect()},[e]),t}function lZ(e,t,n){let r=aZ(),i=cZ(n),a=r&&(t||i),[o,s]=g.useState(tZ),c=rZ(e.messages),l=iZ(e.tasks),u=YX(a,e.messages.length>0,c,l,o);return g.useEffect(()=>{JX(u,o)||(u.messageId!==void 0&&u.taskIds!==void 0&&nZ(u.messageId,u.taskIds),s(u))},[a,e.messages,e.tasks,o]),QX(c,l,u)}var uZ=`castle-flow-layout:`,dZ=1;function fZ(e,t){if(e)try{let n={version:dZ,state:t};localStorage.setItem(uZ+e,JSON.stringify(n))}catch{}}function pZ(e,t,n){if(!e)return null;try{let r=localStorage.getItem(uZ+e);if(!r)return null;let i=JSON.parse(r);if(i.version!==dZ||!i.state||!Array.isArray(i.state.groups))return null;let a=an(bZ(xZ(i.state,t)),n);return a.groups.length===0?null:pt(a)}catch{return null}}var mZ=new Set([`operator`,`files`,`params`]);function hZ(e){let t=e.codeView;if(t===void 0)return e;let n={...e};return delete n.codeView,t&&(n.view=fe),n}function gZ(e,t){let n=t.some(t=>t.id===e.activeTabId)?e.activeTabId:t[0].id;return{...e,tabs:t,activeTabId:n}}var _Z=`params`;function vZ(e){return e.kind===`editor`&&e.view===_Z}function yZ(e,t){if(e.kind!==`params`||e.path===void 0||t.has(e.path))return e;let n={...e};return delete n.path,n}function bZ(e){if(!e.groups.some(e=>e.tabs.some(vZ)))return e;let t,n=!1,r=0,i=[];for(let a of e.groups){let e=[];for(let o of a.tabs){if(!vZ(o)){e.push(o);continue}let a={...o};if(delete a.view,n){e.push(a);continue}n=!0,t=o.path,r=i.length+1}if(e.length===0){r=Math.min(r,i.length);continue}i.push(gZ(a,e))}let a=ut(`params`,t);return i.splice(Math.min(r,i.length),0,ft([a],it(a))),{...e,groups:i}}function xZ(e,t){let n=new Set,r=[];for(let i of e.groups){let e=i.tabs.filter(e=>!(e.kind===`editor`&&e.path!==void 0&&!t.has(e.path))).map(hZ).map(e=>yZ(e,t));if(e.length===0)continue;let a=e.find(e=>e.kind!==`editor`);if(a&&mZ.has(a.kind)){if(n.has(a.kind))continue;n.add(a.kind)}r.push(gZ(i,e))}return{groups:r,activeGroupId:r.some(t=>t.id===e.activeGroupId)?e.activeGroupId:r[0]?.id??null,pinnedGroupId:r.some(t=>t.id===e.pinnedGroupId)?e.pinnedGroupId:null,maximizedGroupId:null}}var SZ=g.createContext(null),CZ={groups:[],activeGroupId:null,pinnedGroupId:null,maximizedGroupId:null};function wZ(e,t){let n=[];if(e.forEach((e,r)=>{let i=t.get(r);if(!i)return;let a=i.getBoundingClientRect(),o=e.left-a.left,s=e.top-a.top;Math.abs(o)<1&&Math.abs(s)<1||(i.style.transition=`none`,i.style.transform=`translate(${o}px, ${s}px)`,n.push(i))}),n.length!==0){n[0].getBoundingClientRect();for(let e of n){e.style.transition=`transform 180ms ease`,e.style.transform=`translate(0px, 0px)`;let t=()=>{e.style.transition=``,e.style.transform=``,e.removeEventListener(`transitionend`,t)};e.addEventListener(`transitionend`,t)}}}function TZ(e){return Array.isArray(e.column)}function EZ(e){return Array.isArray(e.tabs)}function DZ(e){let t=[],n=e=>{EZ(e)?t.push(...e.tabs??[]):t.push(e)};for(let t of e)TZ(t)?(t.column??[]).forEach(n):n(t);return t}function OZ(e){return e===`files`?`files`:e===`playtest`?`play`:e===`terminal`?`terminal`:e===`editor`?`editor`:e===`params`?`params`:null}var kZ=[{type:`files`},{type:`playtest`},{type:`editor`,file:`scenes/main.scene`}];function AZ(e,t){let n=e&&e.length>0?DZ(e):kZ,r=v?null:ut(`operator`),i=r?[ft([r],it(r))]:[],a=new Map,o=null;for(let e of n){let n=OZ(e.type);if(!n||n===`editor`&&!e.file)continue;if(n===`editor`&&e.file){let n=t(e.file),r=a.get(n);if(r){r.tabs.push(ut(`editor`,e.file));continue}let s=ut(`editor`,e.file),c=ft([s],it(s));a.set(n,c),i.push(c),o||=c.id;continue}let r=ut(n,e.file);i.push(ft([r],it(r)))}return{groups:i,activeGroupId:o??i[0]?.id??null,pinnedGroupId:null,maximizedGroupId:null}}function jZ(){let e=OT(),[t,n]=g.useState(()=>jT());return g.useEffect(()=>{if(e)return;let t=window.matchMedia(`(max-width: 768px)`),r=()=>n(t.matches);return t.addEventListener(`change`,r),()=>t.removeEventListener(`change`,r)},[e]),t}function MZ(e){let t=e.target;if(!(t instanceof HTMLIFrameElement)||!t.classList.contains(`deck-frame`))return t;try{let n=t.contentDocument;if(!n)return t;let r=t.getBoundingClientRect();return n.elementFromPoint(e.clientX-r.left,e.clientY-r.top)??t}catch{return t}}function NZ(e,t){let n=e,r=!!(n?.ownerDocument&&n.ownerDocument!==t.ownerDocument),i=r?null:t.parentElement;for(;n&&n!==i;){if(n.nodeType===1){let e=getComputedStyle(n).overflowY;if((e===`auto`||e===`scroll`)&&n.scrollHeight>n.clientHeight+1)return!0}if(!r&&n===t)break;n=n.parentElement}return!1}function PZ(e,t,n){let r=e,i=t.parentElement;for(;r&&r!==i;){if(r.nodeType===1){let e=getComputedStyle(r),t=e.touchAction;if(t.includes(`pan-y`)&&!t.includes(`pan-x`))return!0;let i=e.overflowX;if(i===`auto`||i===`scroll`){let e=r.scrollWidth-r.clientWidth;if(e>1&&(n>0?r.scrollLeft>1:r.scrollLeft<e-1))return!0}}if(r===t)break;r=r.parentElement}return!1}function FZ(e,t){g.useEffect(()=>{if(!t)return;let n=e.current;if(!n)return;let r=e=>{e.deltaY!==0&&(n.scrollWidth<=n.clientWidth||!e.shiftKey&&NZ(MZ(e),n)||(n.scrollLeft+=e.deltaX-e.deltaY,e.preventDefault()))};return n.addEventListener(`wheel`,r,{passive:!1}),()=>n.removeEventListener(`wheel`,r)},[e,t])}function IZ(e,t,n,r){g.useLayoutEffect(()=>{let n=e.current,r=n?.querySelector(`.flow-row`);if(!n||!r)return;let i=()=>{let e=[...r.children].reverse().find(e=>e instanceof HTMLElement&&!e.classList.contains(`is-docked`)),i=e?.querySelector(`:scope .flow-card`),a=e?.classList.contains(`flow-card-slot`)&&i instanceof HTMLElement?i:e,o=a?a.offsetLeft+a.offsetWidth:0,s=t&&o>n.clientWidth?n.clientWidth/2:0;r.style.setProperty(`--flow-overscroll`,`${Math.round(s)}px`)};i();let a=new ResizeObserver(i);return a.observe(n),()=>a.disconnect()},[e,t,n,r])}function LZ(e,t,n){let r=e.getBoundingClientRect(),i=t.getBoundingClientRect();if(i.left>=r.left-1&&i.right<=r.right+1)return;let a=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches;e.scrollTo({left:e.scrollLeft+(i.left+i.width/2-(r.left+r.width/2)),behavior:n??(a?`auto`:`smooth`)})}function RZ(e,t,n,r){return t||n||r||!e.pinnedGroupId?null:_t(e,e.pinnedGroupId)}function zZ(e,t){let n=e.get(t);return n||(n=document.createElement(`div`),n.className=`flow-card-host`,e.set(t,n)),n}function BZ(e,t,n,r,i,a){g.useLayoutEffect(()=>{if(e){for(let e of a.current.values())e.remove();return}let o=gt(t),s=new Set(o.map(e=>e.id));for(let e of o){let t=a.current.get(e.id);if(!t)continue;let o=e.id===n?r.current:i.current.get(e.id);o&&t.parentNode!==o&&o.appendChild(t)}for(let[e,t]of[...a.current])s.has(e)||(t.remove(),a.current.delete(e))}),g.useEffect(()=>()=>{for(let e of a.current.values())e.remove();a.current.clear()},[a])}function VZ(e,t){let n=g.useRef(new Map),r=g.useCallback(e=>{let t=n.current.get(e);if(t)return t.obj;let r={visible:!1,active:!1,activeCbs:new Set,visibleCbs:new Set,obj:{id:e,isVisible:()=>r.visible,isActive:()=>r.active,onDidActiveChange:e=>(r.activeCbs.add(e),()=>r.activeCbs.delete(e)),onDidVisibilityChange:e=>(r.visibleCbs.add(e),()=>r.visibleCbs.delete(e))}};return n.current.set(e,r),r.obj},[]);return g.useEffect(()=>{let r=new Set;for(let i of e.groups){let a=t?i.id===e.activeGroupId:!0;for(let t of i.tabs){r.add(t.id);let o=n.current.get(t.id);if(!o)continue;let s=i.activeTabId===t.id,c=a&&s,l=i.id===e.activeGroupId&&s;c!==o.visible&&(o.visible=c,o.visibleCbs.forEach(e=>e(c))),l!==o.active&&(o.active=l,o.activeCbs.forEach(e=>e(l)))}}for(let e of n.current.keys())r.has(e)||n.current.delete(e)}),r}function HZ(e,t,n,r){let i=gt(t.groups).length-gt(e.groups).length,a=t;if(i>0&&!r){let t=a.activeGroupId,n=e.activeGroupId;t&&n&&t!==n&&(a=un(a,t,n))}return gn(a,n)}function UZ({agent:e}){let[t,n]=g.useState(CZ),[r,i]=g.useState(eT),[a,o]=g.useState(null),[s,c]=g.useState(null),[l,u]=g.useState(!1),d=g.useRef(null),f=g.useRef(!1),p=jZ(),m=!p&&r===`fit`,h=g.useRef(m);h.current=m;let _=t.groups.some(e=>e.id===t.activeGroupId)?t.activeGroupId:t.groups[0]?.id??null,y=p?null:t.maximizedGroupId,b=RZ(t,p,m,y),x=b?(b.groups.find(e=>e.id===_)??b.groups[0]).w+12:0,S=g.useRef(p);S.current=p;let C=g.useRef(CZ),w=g.useRef(null),[T,ee]=g.useState(null);C.current=t;let E=g.useRef(new Map),D=g.useRef(new Map),O=g.useRef(new Map),te=g.useRef(new Map),ne=g.useRef(null),k=t.groups.find(e=>e.tabs.some(e=>e.kind===`operator`))?.id??null,A=g.useRef(k);A.current=k;let[re,ie]=g.useState(null),ae=g.useRef(null),oe=g.useRef(null),se=g.useRef(null),j=g.useRef({page:0,count:0,ids:[]});FZ(oe,!m),BZ(p,t.groups,b?.id??null,ne,O,te),IZ(oe,!p&&!t.maximizedGroupId&&!m,t.groups,x);let ce=VZ(t,p);g.useEffect(()=>{let e=!0;Promise.all([be(),ke().catch(()=>[])]).then(([t,r])=>{e&&(d.current=t.deckId,le(t),o(t.kitEditorExtensions),c(r),n(pZ(t.deckId,new Set(r),me)??AZ(t.initialPanels,me)),f.current=!0,u(!0))},()=>{e&&(o([]),c([]),n(AZ(null,me)),f.current=!0,u(!0))});let t=Px(t=>{t.changes.some(e=>e.event!==`change`)&&ke().then(t=>{e&&c(t)}).catch(()=>{}),t.changes.some(e=>e.path===`castle.json`||e.path.startsWith(`imports/`))&&be().then(t=>{e&&(le(t),o(t.kitEditorExtensions))},()=>{})});return()=>{e=!1,t()}},[]),g.useEffect(()=>{if(!f.current)return;let e=window.setTimeout(()=>fZ(d.current,t),400);return()=>window.clearTimeout(e)},[t]);let ue=g.useMemo(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId),n=e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0];return n&&n.kind===`editor`?n.path??null:null},[t.groups,t.activeGroupId]),de=g.useRef(null),fe=g.useCallback(e=>{if(S.current||C.current.maximizedGroupId||h.current)return;let t=C.current;if(RZ(t,S.current,h.current,t.maximizedGroupId)?.groups.some(t=>t.id===e))return;let n=oe.current,r=_t(t,e),i=(r?D.current.get(r.id):null)??E.current.get(e);n&&i&&LZ(n,i)},[]),pe=g.useCallback((e,t)=>{e&&(de.current=e,t||requestAnimationFrame(()=>{de.current===e&&(de.current=null,fe(e))}))},[fe]);g.useLayoutEffect(()=>{let e=de.current;e&&(de.current=null,fe(e))},[t.groups,t.activeGroupId,t.maximizedGroupId,fe]);let he=g.useCallback(()=>oe.current?.clientWidth||window.innerWidth,[]),ge=g.useCallback(e=>!Tt(e,he()-200-12),[he]),_e=g.useCallback(e=>h.current?gn(e,he()):e,[he]),ve=g.useCallback(()=>{let e=r===`fit`?`scroll`:`fit`;tT(e),i(e),e===`scroll`&&n(e=>hn(e))},[r]);g.useLayoutEffect(()=>{!l||!m||n(e=>gn(e,he()))},[l,m,he]),g.useEffect(()=>{if(!m)return;let e=0,t=()=>{window.clearTimeout(e),e=window.setTimeout(()=>{n(e=>gn(e,he()))},120)};return window.addEventListener(`resize`,t),()=>{window.clearTimeout(e),window.removeEventListener(`resize`,t)}},[m,he]);let ye=g.useCallback(e=>{let t=C.current,r=e(t);h.current&&(r=HZ(t,r,he(),ge(t))),r!==t&&n(()=>r),pe(r.activeGroupId,r!==t)},[pe,he,ge]),xe=g.useCallback((e,t,r,i)=>{let a=C.current,o=i?.line===void 0&&i?.field===void 0;i&&!(o&&Et(a,e))&&DS(e,i);let s=S.current?1:1/0,c=t?Yt(a,t,e,me,s,r):Jt(a,e,me,s,r);if(c===a)return;h.current&&(c=HZ(a,c,he(),ge(a)));let l=nt(c);for(let e of nt(a))l.has(e)||ky(e);Fb(d.current,e),n(()=>c),pe(c.activeGroupId,!0)},[pe,he,ge]),Se=g.useMemo(()=>({openFile:(e,t,n)=>xe(e,void 0,t,n),openPlaytest:()=>ye(e=>Qt(e,`play`)),openParams:(e,t)=>{e&&t?.field&&DS(e,{field:t.field}),ye(t=>nn(t,e))},setParamsScope:e=>n(t=>tn(t,e)),mentionInChat:e=>{v||(cq(e),ye(e=>Qt(e,`operator`)))},closeEditor:e=>n(t=>{let n=Et(t,e);return n?_e(Ut(t,n.group.id,n.tab.id)):t}),activeEditorPath:ue,kitEditorExts:a,terminalTheme:`dark`}),[a,ue,xe,ye,_e]);SS(Se);let Ce=g.useCallback((e,t)=>{let r=C.current,i=r.maximizedGroupId?bn({...r,maximizedGroupId:null},e):zt(r,e);i!==r&&n(()=>i),t?.reveal&&pe(e,i!==r)},[pe]),we=g.useCallback(e=>{let t=ht(C.current,e);if(t)for(let e of t.tabs)e.kind===`editor`&&e.path&&ky(e.path);n(t=>_e(rn(t,e)))},[_e]),Te=g.useCallback((e,t)=>{let r=ht(C.current,e)?.tabs.find(e=>e.id===t);r?.kind===`editor`&&r.path&&ky(r.path),n(n=>_e(Ut(n,e,t)))},[_e]),Ee=g.useCallback((e,t)=>n(n=>Bt(n,e,t)),[]),De=g.useCallback((e,t,r)=>{n(n=>_n(n,e,t,r))},[]),[Oe,Ae]=g.useState(null),je=g.useCallback(e=>Ae(e),[]),Me=g.useCallback(()=>Ae(null),[]),Ne=g.useCallback((e,t)=>xe(t,e),[xe]),Pe=g.useCallback((e,t,r)=>{n(n=>Kt(n,e,t,r))},[]),Fe=g.useCallback(e=>{let t=C.current,r=!!_t(t,e)?.groups.some(e=>e.id===t.maximizedGroupId);n(t=>bn(t,e)),r&&pe(e,!0)},[pe]),Ie=g.useCallback((e,t,r)=>{n(n=>Cn(Sn(n,e,t),e,r))},[]);g.useEffect(()=>{if(!p)return;let e=oe.current,t=se.current;if(!e||!t)return;let r=0,i=0,a=0,o=1,s=!1,c=!1,l=null,u=e=>t.style.setProperty(`--flow-drag`,`${e}px`),d=t=>{t.touches.length===1&&(r=t.touches[0].clientX,i=t.touches[0].clientY,a=t.timeStamp,l=t.target,o=e.clientWidth||1,s=!1,c=!1)},f=n=>{if(n.touches.length!==1)return;let a=n.touches[0].clientX-r,o=n.touches[0].clientY-i;if(!s){if(Math.abs(a)<8&&Math.abs(o)<8)return;s=!0,c=Math.abs(a)>Math.abs(o)&&!PZ(l,e,a),c&&t.classList.add(`flow-dragging`)}if(!c)return;n.preventDefault();let{page:d,count:f}=j.current;u(d===0&&a>0||d===f-1&&a<0?a*.3:a)},m=e=>{if(!c){t.classList.remove(`flow-dragging`);return}c=!1,t.classList.remove(`flow-dragging`);let i=e.changedTouches[0],s=i?i.clientX-r:0,l=e.timeStamp-a,{page:d,count:f,ids:p}=j.current,m=Math.abs(s)>50&&l<250,h=Math.abs(s)>o*.25,g=d;s<0&&(m||h)?g=Math.min(f-1,d+1):s>0&&(m||h)&&(g=Math.max(0,d-1));let _=p[g];g!==d&&_?n(e=>zt(e,_)):u(0)};return e.addEventListener(`touchstart`,d,{passive:!0}),e.addEventListener(`touchmove`,f,{passive:!1}),e.addEventListener(`touchend`,m,{passive:!0}),e.addEventListener(`touchcancel`,m,{passive:!0}),()=>{e.removeEventListener(`touchstart`,d),e.removeEventListener(`touchmove`,f),e.removeEventListener(`touchend`,m),e.removeEventListener(`touchcancel`,m)}},[p]);let Le=g.useCallback((e,t)=>{t?E.current.set(e,t):E.current.delete(e),e===A.current&&ie(t)},[]),Re=g.useCallback((e,t)=>{t?D.current.set(e,t):D.current.delete(e)},[]),ze=g.useCallback((e,t)=>{t?O.current.set(e,t):O.current.delete(e)},[]);g.useLayoutEffect(()=>{ie(k?E.current.get(k)??null:null)},[k]);let Be=lZ(e,(()=>{let e=t.groups.find(e=>e.id===t.activeGroupId);return(e?.tabs.find(t=>t.id===e.activeTabId)??e?.tabs[0])?.kind===`operator`})(),re),[Ve,He]=g.useState(null),Ue=g.useRef(null),We=g.useRef(null),Ge=g.useRef(!1),Ke=g.useCallback(()=>{let e=new Map;return D.current.forEach((t,n)=>e.set(n,t.getBoundingClientRect())),e},[]);g.useLayoutEffect(()=>{let e=Ue.current;if(!e)return;Ue.current=null;let t=We.current;if(We.current=null,t){let e=oe.current,n=D.current.get(t);e&&n&&LZ(e,n,`auto`)}wZ(e,D.current)});let qe=g.useCallback(e=>{let t=C.current,r=_t(t,e),i=!!RZ(t,S.current,h.current,t.maximizedGroupId)?.groups.some(t=>t.id===e);Ue.current=Ke(),i&&r&&(We.current=r.id),n(t=>yn(t,e))},[Ke]),Je=g.useCallback((e,t)=>{let r=C.current;if(S.current){let n=on(r,e,t),i=r.groups.findIndex(e=>e.id===r.activeGroupId);n.groups.findIndex(e=>e.id===n.activeGroupId)!==i&&(Ge.current=!0)}else Ue.current=Ke();n(n=>on(n,e,t))},[Ke]);g.useEffect(()=>()=>{ae.current?.()},[]);let Ye=g.useCallback((e,r)=>{if(p||e.button!==0||!Mw(e.target))return;let i=jw(e.target),a=i?.closest(`.panel-type-toggle`),o=e.currentTarget instanceof HTMLElement?e.currentTarget:i?.closest(`.flow-tabstrip`),s=a instanceof HTMLElement?a:o instanceof HTMLElement?o:null;if(!s)return;i?.closest(`button`)||e.preventDefault(),ae.current?.();let c=e.pointerId,l=e.pointerType===`mouse`,u=e=>{e.preventDefault(),e.stopPropagation(),s.removeEventListener(`click`,u,!0)},d=e.clientX,f=gt(t.groups),m=f.findIndex(e=>e.groups.some(e=>e.id===r)),g=RZ(t,p,h.current,t.maximizedGroupId)?.id??null,_=!!g&&f[m]?.id===g,v=(e,n)=>{let i=f.filter(e=>!e.groups.some(e=>e.id===r));for(let t of i){let r=D.current.get(t.id)?.getBoundingClientRect();if(r&&e>=r.left&&e<=r.right&&n>=r.top&&n<=r.bottom){let n=(e-r.left)/Math.max(1,r.width);if(n>.25&&n<.75)return{kind:`merge`,targetId:t.groups[0].id}}}let a=(_?i:i.filter(e=>e.id!==g)).map(e=>{let t=D.current.get(e.id)?.getBoundingClientRect();return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),o=0;for(;o<a.length&&a[o].center<e;)o+=1;let s=cn(t,r,o,g);if(s.groups.length===t.groups.length&&s.groups.every((e,n)=>e.id===t.groups[n].id))return{kind:`reorder`,target:o,x:null};let c=o<a.length?a[o].left-6:a.length?a[a.length-1].right+6:e;return{kind:`reorder`,target:o,x:c}},y=!1,b=null,x=e.clientX,S=e.clientY,C=0,w=()=>{let e=oe.current;if(!h.current&&e&&e.scrollWidth>e.clientWidth+1){let t=e.getBoundingClientRect(),n=0;if(x<t.left+64?n=-(1-Math.max(0,x-t.left)/64):x>t.right-64&&(n=1-Math.max(0,t.right-x)/64),n!==0){e.scrollLeft+=n*24;let t=v(x,S);He({id:r,x:t.kind===`reorder`?t.x:null,mergeId:t.kind===`merge`?t.targetId:null})}}C=requestAnimationFrame(w)},T=e=>{if(e.pointerId!==c||!y&&Math.abs(e.clientX-d)<5)return;if(!y){if(y=!0,l)try{s.setPointerCapture(c)}catch{}s.blur(),document.body.classList.add(`flow-reordering`),s.addEventListener(`click`,u,!0);let t=f[m],n=t?.groups.find(e=>e.id===r)??t?.groups[0];n&&(b=rT(n,{stackCount:t.groups.length,iconRoot:E.current.get(n.id)??s}),document.body.appendChild(b),px(b,e.clientX,e.clientY)),C=requestAnimationFrame(w)}x=e.clientX,S=e.clientY,b&&px(b,e.clientX,e.clientY);let t=v(e.clientX,e.clientY);He({id:r,x:t.kind===`reorder`?t.x:null,mergeId:t.kind===`merge`?t.targetId:null})},ee=!1,O=()=>{if(!ee){ee=!0,window.removeEventListener(`pointermove`,T),window.removeEventListener(`pointerup`,te),window.removeEventListener(`pointercancel`,ne),l&&s.removeEventListener(`lostpointercapture`,ne);try{s.hasPointerCapture(c)&&s.releasePointerCapture(c)}catch{}C&&cancelAnimationFrame(C),document.body.classList.remove(`flow-reordering`),b?.remove(),b=null,ae.current=null,window.setTimeout(()=>s.removeEventListener(`click`,u,!0),0)}},te=e=>{if(e.pointerId!==c)return;let t=y;if(O(),t){let t=v(e.clientX,e.clientY);t.kind===`merge`?(Ue.current=Ke(),n(e=>_e(un(e,r,t.targetId)))):t.x!==null&&(Ue.current=Ke(),n(e=>cn(e,r,t.target,g)))}He(null)},ne=e=>{e&&e.pointerId!==c||(O(),He(null))};ae.current=()=>ne(),window.addEventListener(`pointermove`,T),window.addEventListener(`pointerup`,te),window.addEventListener(`pointercancel`,ne),l&&s.addEventListener(`lostpointercapture`,ne)},[p,t,Ke,_e]),Xe=g.useCallback((e,r)=>{if(p||e.button!==0)return;let i=_t(t,r);if(!i||i.groups.length<2)return;ae.current?.();let a=e.currentTarget,o=a.closest(`.flow-rail`),s=o instanceof HTMLElement?o:null,c=e.pointerId,l=e.pointerType===`mouse`,u=e.clientX,d=e.clientY,f=i.groups.findIndex(e=>e.id===r),m=e=>{e.preventDefault(),e.stopPropagation(),a.removeEventListener(`click`,m,!0)},g=!1,_=null,v=t.groups.filter(e=>e.id!==r),y=gt(v),b=gt(t.groups),x=RZ(t,p,h.current,t.maximizedGroupId)?.id??null,S=x&&i.id!==x?y.filter(e=>e.id!==x):y,C=e=>{let t=D.current.get(e.id);if(t)return t.getBoundingClientRect();let n=b.find(t=>t.groups.some(t=>t.id===e.groups[0].id));return n?D.current.get(n.id)?.getBoundingClientRect():void 0},w=e=>{let t=[...D.current.get(i.id)?.querySelectorAll(`[data-rail-gid]`)??[]].filter(e=>e.dataset.railGid!==r),n=0;for(;n<t.length;){let r=t[n].getBoundingClientRect();if(e<r.top+r.height/2)break;n+=1}return n},T=e=>{let t=S.map(e=>{let t=C(e);return{left:t?.left??1/0,right:t?.right??1/0,center:t?t.left+t.width/2:1/0}}),n=0;for(;n<t.length&&t[n].center<e;)n+=1;let r=n<t.length?t[n].left-6:t.length?t[t.length-1].right+6:e,i=n>=S.length?v.length:v.findIndex(e=>e.id===S[n].groups[0].id);return{toIndex:i<0?v.length:i,x:r}},ee=e=>{if(e.pointerId!==c)return;if(!g){if(Math.hypot(e.clientX-u,e.clientY-d)<5)return;if(g=!0,l&&s)try{s.setPointerCapture(c)}catch{}document.body.classList.add(`flow-reordering`),a.addEventListener(`click`,m,!0);let t=i.groups.find(e=>e.id===r);t&&(_=rT(t,{iconRoot:a}),document.body.appendChild(_),px(_,e.clientX,e.clientY))}e.cancelable&&e.preventDefault(),_&&px(_,e.clientX,e.clientY);let t=D.current.get(i.id)?.getBoundingClientRect(),n=t&&e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom;He({id:r,x:n?null:T(e.clientX).x,mergeId:null,railInsertAt:n?w(e.clientY):null})},E=!1,O=()=>{if(!E){E=!0,window.removeEventListener(`pointermove`,ee),window.removeEventListener(`pointerup`,te),window.removeEventListener(`pointercancel`,ne),l&&s&&s.removeEventListener(`lostpointercapture`,ne);try{s?.hasPointerCapture(c)&&s.releasePointerCapture(c)}catch{}document.body.classList.remove(`flow-reordering`),_?.remove(),_=null,ae.current=null,window.setTimeout(()=>a.removeEventListener(`click`,m,!0),0)}},te=e=>{if(e.pointerId!==c)return;let t=g;if(O(),t){let t=D.current.get(i.id)?.getBoundingClientRect();if(t&&e.clientX>=t.left&&e.clientX<=t.right&&e.clientY>=t.top&&e.clientY<=t.bottom){let t=w(e.clientY);t!==f&&n(e=>fn(e,r,t))}else Ue.current=Ke(),n(t=>_e(dn(t,r,T(e.clientX).toIndex)))}He(null)},ne=e=>{e&&e.pointerId!==c||(O(),He(null))};ae.current=()=>ne(),window.addEventListener(`pointermove`,ee,{passive:!1}),window.addEventListener(`pointerup`,te),window.addEventListener(`pointercancel`,ne),l&&s&&s.addEventListener(`lostpointercapture`,ne)},[p,t,Ke,_e]),[Ze,Qe]=g.useState(null),$e=g.useCallback(e=>Qe(t=>t?null:{anchor:e}),[]),et=g.useCallback(()=>{let e=se.current?.querySelector(`.flow-tabs-add`);Qe({anchor:e?.getBoundingClientRect()??new DOMRect(window.innerWidth/2,48)})},[]);g.useEffect(()=>{let e=(e,t)=>(t&&t!==window?[...document.querySelectorAll(`iframe.deck-frame`)].find(e=>e.contentWindow===t):e)?.closest?.(`.flow-group`)?.getAttribute(`data-group-id`)??null;return Xy(`pointermove`,t=>{let n=e(t.target,t.view);w.current=n,!S.current&&ee(e=>e===n?e:n)},{passive:!0})},[]);let rt=g.useMemo(()=>Ry({getState:()=>C.current,setState:n,spawn:ye,focusGroup:e=>Ce(e,{reveal:!0}),closeGroup:we,closeTab:Te,openPath:e=>xe(e),openNewGroupPicker:et,getHoveredGroupId:()=>w.current,toggleMaximize:Fe,togglePin:qe}),[ye,Ce,we,Te,xe,et,Fe,qe]),it=$y(rt),at=Math.max(0,t.groups.findIndex(e=>e.id===_));j.current={page:at,count:t.groups.length,ids:t.groups.map(e=>e.id)},g.useLayoutEffect(()=>{let e=se.current;if(!e)return;let t=Ge.current;t&&e.classList.add(`flow-dragging`),e.style.setProperty(`--flow-page`,String(at)),e.style.setProperty(`--flow-drag`,`0px`),t&&(Ge.current=!1,e.offsetHeight,requestAnimationFrame(()=>e.classList.remove(`flow-dragging`)))},[at,p]),xb(se),Tb(()=>Oe?(Ae(null),!0):Ze?(Qe(null),!0):!1,1);let ot=Oe?ht(t,Oe):null,st=ot?.tabs.find(e=>e.id===ot.activeTabId)??ot?.tabs[0],ct=st&&st.kind===`editor`?st.path??``:``;return(0,U.jsx)(bS,{value:Se,children:(0,U.jsx)(SZ.Provider,{value:e,children:(0,U.jsxs)(`div`,{ref:se,className:`flow-root${p?` is-mobile`:``}${y?` is-maximized`:``}${m?` is-fit`:``}`,children:[(0,U.jsx)(WZ,{state:t,activeId:_,operatorBadge:Be,mobile:p,layoutMode:r,showLayoutToggle:!p,onToggleLayoutMode:ve,onFocusGroup:Ce,onReorderGroup:Je,onNewGroup:$e}),(0,U.jsxs)(`div`,{className:`flow-workbench`,children:[(0,U.jsx)(`div`,{className:`flow-pin-dock`,ref:ne}),(0,U.jsx)(`div`,{className:`flow-scroller`,ref:oe,children:(0,U.jsx)(`div`,{className:`flow-field`,children:(0,U.jsx)(`div`,{className:`flow-row`,style:x?{"--flow-pin-inset":`${x}px`}:void 0,children:p?t.groups.map(e=>(0,U.jsx)(JZ,{group:e,active:e.id===_,mobile:p,pinned:!1,maximized:!1,hidden:!1,dragging:!1,hovered:e.id===T,fill:!1,showResize:!1,showPin:!1,getLifecycle:ce,registerEl:Le,onFocusGroup:Ce,onClose:we,onActivateTab:Ee,onCloseTab:Te,onReorderTab:De,onOpenMobileSwitch:je,onOpenInGroup:Ne,onSetTabView:Pe,onTogglePin:qe,onToggleMaximize:Fe,onStartDrag:Ye,onResize:Ie},e.id)):gt(t.groups).map(e=>(0,U.jsx)(`div`,{className:`flow-card-slot${b&&e.id===b.id?` is-docked`:``}`,ref:t=>ze(e.id,t)},e.id))})})}),!p&&gt(t.groups).map((e,r,i)=>{let a=e.groups.length>1,o=e.groups.find(e=>e.id===_)??e.groups[0],s=e.groups.some(e=>e.id===t.pinnedGroupId)&&!y,c=!!b&&e.id===b.id,l=e.groups.some(e=>e.id===y),u=y!==null&&!l,d=!!Ve?.id&&Ve.railInsertAt===void 0&&e.groups.some(e=>e.id===Ve.id),f=!!Ve?.mergeId&&e.groups.some(e=>e.id===Ve.mergeId),p=i[r+1],h=l?{flex:`1 1 auto`}:m?{flexGrow:o.w,"--flow-card-min":`${Ct(e)}px`}:{width:o.w,height:o.h},v=(0,U.jsxs)(U.Fragment,{children:[a?(0,U.jsx)(Xw,{groups:e.groups,activeGroupId:o.id,operatorBadge:Be,onActivate:e=>Ce(e),onUnstack:e=>n(t=>_e(dn(t,e,t.groups.length))),onPointerDown:Xe,reorder:Ve&&Ve.railInsertAt!==void 0&&e.groups.some(e=>e.id===Ve.id)?{dragId:Ve.id,insertAt:Ve.railInsertAt}:void 0}):null,e.groups.map(e=>(0,U.jsx)(JZ,{group:e,active:e.id===_,mobile:!1,pinned:s,maximized:l,hidden:u||e.id!==o.id,dragging:!1,hovered:e.id===T,fill:!0,showResize:!m&&!l&&e.id===o.id,showPin:!m,getLifecycle:ce,registerEl:Le,onFocusGroup:Ce,onClose:we,onActivateTab:Ee,onCloseTab:Te,onReorderTab:De,onOpenMobileSwitch:je,onOpenInGroup:Ne,onSetTabView:Pe,onTogglePin:qe,onToggleMaximize:Fe,onStartDrag:Ye,onResize:Ie},e.id))]});return(0,U.jsx)(g.Fragment,{children:(0,tb.createPortal)((0,U.jsxs)(`div`,{ref:t=>Re(e.id,t),"data-card-id":e.id,className:`flow-card${a?` is-stacked panel`:``}${o.id===_&&!y?` is-active`:``}${c?` pinned`:``}${l?` maximized`:``}${u?` hidden`:``}${d?` is-dragging`:``}${f?` is-drop-target`:``}`,style:h,children:[a?(0,U.jsx)(`div`,{className:`flow-card-stack`,children:v}):v,m&&!y&&p?(0,U.jsx)(fQ,{leftW:o.w,rightW:p.groups[0].w,leftMin:Ct(e),rightMin:Ct(p),onSplit:(e,t)=>n(n=>wn(n,o.id,p.groups[0].id,e,t))}):null]}),zZ(te.current,e.id))},e.id)})]}),Ve&&Ve.x!==null&&(()=>{let e=oe.current?.getBoundingClientRect(),n=_t(t,Ve.id),r=(n&&D.current.get(n.id)||E.current.get(Ve.id))?.getBoundingClientRect();if(!e||!r)return null;let i=Math.max(r.top,e.top+12+36),a=Math.min(r.bottom,e.bottom)-i;return a<=0?null:(0,U.jsx)(`div`,{className:`flow-drop-indicator`,style:{left:Ve.x,top:i,height:a}})})(),Ze&&(0,U.jsx)(dQ,{anchor:Ze.anchor,files:s??[],onOpenFile:e=>xe(e),onSpawnPanel:e=>ye(t=>Qt(t,e)),onSpawnClass:e=>ye(t=>Xt(t,e,me)),onClose:()=>Qe(null)}),Oe&&(0,U.jsx)(wT,{groupId:Oe,groupClass:tt(ot,me),currentFile:ct,files:s,recent:Lb(d.current),view:st?.view,onSetView:e=>{Oe&&st&&Pe(Oe,st.id,e)},onOpen:(e,t)=>xe(e,t),onClose:Me}),(0,U.jsx)(Ab,{openFile:e=>xe(e),openPanel:e=>ye(t=>Qt(t,e===`playtest`?`play`:e)),panels:tQ,getCommands:rt}),it?(0,U.jsxs)(`div`,{className:`chord-hint`,role:`status`,children:[(0,U.jsx)(`kbd`,{children:it}),(0,U.jsx)(`span`,{children:`waiting for the next key…`})]}):null]})})})}function WZ(e){let{state:t,activeId:n,operatorBadge:r,mobile:i,layoutMode:a,showLayoutToggle:o,onToggleLayoutMode:s,onFocusGroup:c,onReorderGroup:l,onNewGroup:u}=e,d=Db(),[f,p]=g.useState(!1),m=d?.title?.trim()||`Untitled deck`;vb(m,r),yb(r);let h=d?.visibility===`public`?Qb:d?.visibility===`unlisted`?Xb:Zb,_=d?.saving??`idle`,v=d?.saveError??null,y=d?.draftAutosaveState??null,b=y===`starting`||y===`saving`?`Saving draft…`:y===`dirty`?`Unsaved changes`:y===`error`?`Draft save failed`:y===`saved`?`Draft saved`:null,[x,S]=g.useState(null),C=g.useRef(!1);g.useEffect(()=>{x!==null&&(_===`working`&&(C.current=!0),_===`done`&&C.current&&S(`done`),v&&C.current&&S(`failed`))},[_,v,x]);let w=g.useCallback(()=>{C.current=!1,S(`pushing`),gb(`push`)},[]);return(0,U.jsxs)(U.Fragment,{children:[(0,U.jsxs)(`div`,{className:`flow-topbar`,children:[(0,U.jsxs)(`div`,{className:`flow-topbar-leading`,children:[OT()?null:(0,U.jsxs)(`div`,{className:`flow-castle-wrap`,children:[(0,U.jsx)(`button`,{type:`button`,className:`dock-control dock-control-icon dock-control-mark`,title:`Menu`,"aria-haspopup":`menu`,"aria-expanded":f,onClick:()=>p(e=>!e),children:ox}),f&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-menu-backdrop`,onClick:()=>p(!1)}),(0,U.jsxs)(`div`,{className:`menu flow-castle-menu`,role:`menu`,children:[(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{p(!1),gb(`back-to-decks`)},children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:ex}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:`Back to decks`})]}),(0,U.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`menu-item`,onClick:()=>{p(!1),gb(`new-deck`)},children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:Kb}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:`New deck`})]}),(0,U.jsx)(`div`,{className:`menu-separator flow-menu-narrow`}),(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,onClick:()=>{p(!1),gb(`open-settings`)},children:(0,U.jsx)(`span`,{className:`menu-item-label`,children:`Deck settings`})}),(0,U.jsx)(`button`,{type:`button`,role:`menuitem`,className:`menu-item flow-menu-narrow`,disabled:_===`working`,onClick:()=>{p(!1),w()},children:(0,U.jsx)(`span`,{className:`menu-item-label`,children:_===`working`?`Pushing…`:v?`Push failed — retry`:_===`done`?`Pushed ✓`:`Push to Castle`})})]})]})]}),(0,U.jsxs)(`button`,{type:`button`,className:`dock-control dock-control-quiet flow-deck-identity`,title:`Deck settings`,onClick:()=>gb(`open-settings`),children:[(0,U.jsx)(`span`,{className:`flow-deck-vis`,children:h}),(0,U.jsx)(`span`,{className:`flow-deck-name`,children:m}),(0,U.jsx)(`span`,{className:`flow-deck-caret`,children:tx})]}),b?i?y===`saved`?null:(0,U.jsx)(`span`,{className:`flow-draft-status is-compact is-${y}`,role:`status`,title:b,"aria-label":b}):(0,U.jsx)(`span`,{className:`flow-draft-status${y===`error`?` is-error`:``}`,role:`status`,children:b}):null]}),(0,U.jsxs)(`div`,{className:`flow-tabs-wrap`,children:[o?(0,U.jsx)(Gw,{layoutMode:a,onToggleLayoutMode:s,activeTabId:t.groups.find(e=>e.id===n)?.activeTabId??null}):null,(0,U.jsx)(Vw,{groups:t.groups,activeId:n,operatorBadge:r,onFocusGroup:c,onReorderGroup:l}),(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet flow-tabs-add flow-picker-trigger`,title:`New group`,"aria-label":`New group`,onClick:e=>u(e.currentTarget.getBoundingClientRect()),children:Kb})]}),(0,U.jsx)(`div`,{className:`flow-topbar-trailing`,children:(0,U.jsxs)(`button`,{type:`button`,className:`dock-control flow-preview-btn${v?` flow-preview-btn-failed`:``}`,title:v??`Publish this deck to your Castle account (sandbox edits stay local until pushed)`,disabled:_===`working`,onClick:()=>gb(`push`),children:[$b,(0,U.jsxs)(`span`,{className:`flow-preview-label`,children:[(0,U.jsx)(`span`,{className:`flow-preview-label-sizer`,"aria-hidden":`true`,children:`Push to Castle`}),(0,U.jsx)(`span`,{children:_===`working`?`Pushing…`:v?`Push failed`:_===`done`?`Pushed ✓`:`Push to Castle`})]})]})})]}),x!==null&&(0,U.jsx)(`div`,{className:`flow-push-modal-backdrop`,children:(0,U.jsx)(`div`,{className:`flow-push-modal`,role:`dialog`,"aria-modal":`true`,children:x===`failed`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-check flow-push-check-failed`,children:`!`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Push failed`}),(0,U.jsx)(`div`,{className:`flow-push-sub`,children:v}),(0,U.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>S(null),children:`Dismiss`})]}):x===`done`?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-check`,children:`✓`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Pushed to Castle`}),d?.shareUrl?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Your deck is live at`}),(0,U.jsx)(`a`,{className:`flow-push-url`,href:d.shareUrl,target:`_blank`,rel:`noreferrer`,children:d.shareUrl.replace(/^https?:\/\//,``)})]}):(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Saved to your Castle account.`}),(0,U.jsx)(`button`,{type:`button`,className:`flow-push-done`,onClick:()=>S(null),children:`Done`})]}):(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-push-spinner`}),(0,U.jsx)(`div`,{className:`flow-push-title`,children:`Pushing to Castle…`}),(0,U.jsx)(`div`,{className:`flow-push-sub`,children:`Publishing your latest changes.`})]})})})]})}function GZ(e,t){e.currentTarget.blur(),t()}function KZ(e,t,n){let r=g.useRef(null);return g.useEffect(()=>{let t=r.current;if(!t)return;let i=t=>{t.button===0&&n(e)};return t.addEventListener(`pointerdown`,i),()=>t.removeEventListener(`pointerdown`,i)},[e,n]),g.useCallback(n=>{r.current=n,t(e,n)},[e,t])}function qZ(e,t,n){let r=g.useRef(null);return g.useEffect(()=>{let i=r.current;if(!i)return;let a=r=>{Mw(r.target)&&(e||n(r,t))},o=e=>e.preventDefault();return i.addEventListener(`pointerdown`,a),i.addEventListener(`dragstart`,o),()=>{i.removeEventListener(`pointerdown`,a),i.removeEventListener(`dragstart`,o)}},[e,t,n]),r}var JZ=g.memo(function(e){let{group:t,active:n,mobile:r,pinned:i,maximized:a,hidden:o,dragging:s,hovered:c,fill:l,showResize:u,showPin:d,getLifecycle:f,registerEl:p}=e,{onFocusGroup:m,onClose:h}=e,_=et(t),v=pQ(t,e.onResize),[y,b]=g.useState(()=>_&&t.tabs.every($e)),x=g.useCallback(()=>b(e=>!e),[]),S=qZ(a,t.id,e.onStartDrag),C=KZ(t.id,p,m),w=r?void 0:l?{flex:`1 1 auto`,minWidth:0,height:`100%`}:a?{flex:`1 1 auto`}:{flex:`0 0 auto`,width:t.w,height:t.h},T=_?null:t.tabs[0],ee=(0,U.jsx)(`button`,{type:`button`,className:r?`button button-icon button-icon-large button-quiet`:`button button-icon button-quiet`,title:`Close`,"aria-label":`Close`,onClick:e=>GZ(e,()=>h(t.id)),children:qb}),E=n&&!r&&!a,D=T?.kind===`operator`;return(0,U.jsxs)(`div`,{ref:C,"data-group-id":t.id,className:`panel flow-group${E?` is-active`:``}${i&&!l?` pinned`:``}${a?` maximized`:``}${o?` hidden`:``}${s?` is-dragging`:``}${c?` is-hover`:``}${_?` is-editor`:``}`,style:w,children:[_?(0,U.jsx)(Iw,{group:t,mobile:r,pinned:i,maximized:a,onStartDrag:e.onStartDrag,onActivateTab:e.onActivateTab,onCloseTab:e.onCloseTab,onCloseGroup:h,onReorderTab:e.onReorderTab,onTogglePin:e.onTogglePin,onToggleMaximize:e.onToggleMaximize,onOpenMobileSwitch:e.onOpenMobileSwitch,onSetTabView:e.onSetTabView,drawerOpen:y,onToggleDrawer:x,showPin:d}):(0,U.jsxs)(`div`,{ref:S,className:`${D?`panel-tabs-header`:`panel-header`} flow-tabstrip${r?` flow-tabstrip-mobile`:``}`,children:[D?(0,U.jsx)(`div`,{className:`operator-chrome`,"data-operator-chrome":!0}):r?(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`panel-header-actions flow-mobile-strip-left`,children:(0,U.jsx)(BS,{tabId:T?.id})}),(0,U.jsxs)(`div`,{className:`panel-mobile-current`,children:[(0,U.jsx)(`span`,{className:`flow-tab-icon`,children:T&&Gb(T.kind,T.path)}),(0,U.jsx)(`span`,{className:`panel-mobile-current-label`,children:T?.label})]})]}):(0,U.jsxs)(`div`,{className:`panel-title`,children:[(0,U.jsx)(`span`,{className:`flow-tab-icon`,children:T&&Gb(T.kind,T.path)}),(0,U.jsx)(`span`,{children:T?.label})]}),(0,U.jsxs)(`div`,{className:`panel-header-actions${r?` flow-mobile-strip-right`:``}`,children:[d&&(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:i?`Unpin`:`Pin to left`,"aria-label":i?`Unpin`:`Pin to left`,"aria-pressed":i,onClick:n=>GZ(n,()=>e.onTogglePin(t.id)),children:Yb}),!r&&(0,U.jsx)(`button`,{type:`button`,className:`button button-icon button-quiet`,title:a?`Restore`:`Maximize`,"aria-label":a?`Restore`:`Maximize`,"aria-pressed":a,onClick:n=>GZ(n,()=>e.onToggleMaximize(t.id)),children:a?rx:nx}),ee]})]}),(0,U.jsx)(`div`,{className:`flow-panel-body`,children:t.tabs.map(i=>(0,U.jsx)(`div`,{className:`flow-tab-body${i.id===t.activeTabId?``:` inactive`}`,children:(0,U.jsx)(YZ,{tab:i,groupId:t.id,lifecycle:f(i.id),onOpenInGroup:e.onOpenInGroup,onSetTabView:e.onSetTabView,drawerOpen:y&&!r,mobile:r,active:n})},i.id))}),!r&&u&&(0,U.jsxs)(U.Fragment,{children:[(0,U.jsx)(`div`,{className:`flow-resize-e`,onPointerDown:v(`x`),title:`Drag to resize width`}),(0,U.jsx)(`div`,{className:`flow-resize-s`,onPointerDown:v(`y`),title:`Drag to resize height`}),(0,U.jsx)(`div`,{className:`flow-resize-se`,onPointerDown:v(`xy`),title:`Drag to resize`})]})]})}),YZ=g.memo(function(e){let{tab:t,groupId:n,lifecycle:r,onOpenInGroup:i,onSetTabView:a,drawerOpen:o,mobile:s,active:c}=e;if(t.kind===`editor`&&$e(t))return(0,U.jsxs)(`div`,{className:`flow-empty-editor`,children:[o?(0,U.jsx)(ZG,{currentFile:``,filterClass:t.classHint,onOpen:e=>i(n,e)}):null,(0,U.jsx)(`div`,{className:`flow-empty-editor-msg`,children:`Open a file`})]});switch(t.kind){case`editor`:return(0,U.jsx)(VG,{file:t.path,editorClass:t.view,lifecycle:r,hideContextBar:!0,drawerOpen:o,drawer:(0,U.jsx)(ZG,{currentFile:t.path??``,filterClass:t.path?me(t.path):void 0,onOpen:e=>i(n,e),view:t.view,onSetView:e=>a(n,t.id,e)})});case`play`:return(0,U.jsx)(YG,{lifecycle:r});case`terminal`:return(0,U.jsx)(XG,{lifecycle:r});case`files`:return(0,U.jsx)($K,{lifecycle:r});case`params`:return(0,U.jsx)(xw,{scope:t.path,lifecycle:r});case`operator`:return(0,U.jsx)(XZ,{mobile:s,active:c});default:return(0,U.jsx)(ZZ,{tab:t})}});function XZ(e){let t=g.useContext(SZ);return t?(0,U.jsx)(`div`,{className:`shell-root docked flow-operator-host`,style:{"--operator-col":`100%`},children:(0,U.jsx)(KX,{agent:t,mobile:e.mobile,active:e.active})}):(0,U.jsx)(`div`,{className:`flow-placeholder`,children:`operator unavailable`})}function ZZ(e){let{tab:t}=e;return(0,U.jsxs)(`div`,{className:`flow-placeholder kind-${t.kind}`,children:[(0,U.jsx)(`div`,{className:`flow-placeholder-icon`,children:Gb(t.kind,t.path)}),(0,U.jsx)(`div`,{className:`flow-placeholder-label`,children:t.label}),(0,U.jsx)(`div`,{className:`flow-placeholder-kind`,children:t.path??t.kind})]})}function QZ(e,t){g.useEffect(()=>{let n=n=>{n.target.closest(e)||t()},r=window.setTimeout(()=>document.addEventListener(`mousedown`,n),0);return()=>{window.clearTimeout(r),document.removeEventListener(`mousedown`,n)}},[e,t])}function $Z(e,t){return Math.max(8,Math.min(e,window.innerWidth-t-8))}var eQ=300,tQ=[...v?[]:[{kind:`operator`,label:`Operator`}],{kind:`play`,label:`Play`},...v?[]:[{kind:`terminal`,label:`Terminal`}],{kind:`files`,label:`Files`},{kind:`params`,label:`Parameters`}].map(({kind:e,label:t})=>({kind:e===`play`?`playtest`:e,label:t}));function nQ(e,t){return!t||e.toLowerCase().includes(t)}var rQ=[`Image`,`Video`,`Audio`],iQ=new Set(rQ.map(e=>`kit:${e}`));function aQ(e){let t=new Set;for(let n of e){let e=me(n);e!==`code`&&t.add(e)}return t}function oQ(e){let t=he(e);return{kind:`class`,classId:e,label:t.label,icon:t.icon}}function sQ(e,t){return[{kind:`panel`,panel:`play`,label:`Play`},...v?[]:[{kind:`panel`,panel:`operator`,label:`Operator`}],{kind:`panel`,panel:`files`,label:`Files`},oQ(fe),{kind:`panel`,panel:`params`,label:`Parameters`},...rQ.flatMap(t=>{let n=`kit:${t}`;return e.has(n)?[oQ(n)]:[]}),...v?[]:[{kind:`panel`,panel:`terminal`,label:`Terminal`}]].filter(e=>nQ(e.label,t))}function cQ(e,t){return[...e].filter(e=>!iQ.has(e)).map(oQ).filter(e=>nQ(e.label,t)).sort((e,t)=>e.label.localeCompare(t.label))}function lQ(e,t){let n=t.trim().toLowerCase(),r=aQ(e),i=[cQ(r,n),sQ(r,n),e.filter(e=>e.toLowerCase().includes(n)).slice(0,40).map(e=>({kind:`file`,path:e}))].filter(e=>e.length>0),a=[];for(let e=0;e<i.length;e++)e>0&&a.push({kind:`divider`}),a.push(...i[e]);return a}function uQ(e){return e.kind!==`divider`}function dQ(e){let{anchor:t,files:n,onOpenFile:r,onSpawnPanel:i,onSpawnClass:a,onClose:o}=e,[s,c]=g.useState(``),[l,u]=g.useState(0);QZ(`.flow-picker, .flow-picker-trigger`,o);let d=lQ(n,s),f=d.filter(uQ),p=Math.min(l,Math.max(0,f.length-1)),m=e=>{e.kind===`panel`?i(e.panel):e.kind===`class`?a(e.classId):r(e.path),o()},h=e=>{e.key===`Escape`?o():e.key===`ArrowDown`?(e.preventDefault(),u(e=>Math.min(e+1,f.length-1))):e.key===`ArrowUp`?(e.preventDefault(),u(e=>Math.max(e-1,0))):e.key===`Enter`&&f[p]&&m(f[p])},_=0;return(0,tb.createPortal)((0,U.jsxs)(`div`,{className:`menu flow-picker`,style:{top:t.bottom+4,left:$Z(t.left,eQ),width:eQ},onMouseDown:e=>e.stopPropagation(),children:[(0,U.jsx)(`input`,{className:`flow-picker-input`,autoFocus:!0,placeholder:`Open a file or panel…`,value:s,onChange:e=>{c(e.target.value),u(0)},onKeyDown:h}),(0,U.jsxs)(`div`,{className:`flow-picker-list`,children:[(0,U.jsx)(`div`,{className:`menu-separator`}),f.length===0&&(0,U.jsx)(`div`,{className:`flow-picker-empty`,children:`No matches`}),d.map((e,t)=>{if(e.kind===`divider`)return(0,U.jsx)(`div`,{className:`menu-separator`},`d:${t}`);let n=_++;return(0,U.jsxs)(`button`,{type:`button`,className:`menu-item${n===p?` is-hover`:``}`,onMouseEnter:()=>u(n),onClick:()=>m(e),children:[(0,U.jsx)(`span`,{className:`menu-icon`,children:e.kind===`panel`?Gb(e.panel):e.kind===`class`?Hb(e.icon):Gb(`editor`,e.path)}),(0,U.jsx)(`span`,{className:`menu-item-label`,children:e.kind===`panel`||e.kind===`class`?e.label:e.path})]},e.kind===`panel`?`p:${e.panel}`:e.kind===`class`?`c:${e.classId}`:`f:${e.path}`)})]})]}),document.body)}function fQ(e){let{leftW:t,rightW:n,leftMin:r,rightMin:i,onSplit:a}=e;return(0,U.jsx)(`div`,{className:`flow-splitter`,onPointerDown:e=>{e.preventDefault(),e.stopPropagation();let o=e.clientX,s=e.currentTarget,c=s.parentElement,l=c?.nextElementSibling,u=c?.getBoundingClientRect().width??t,d=l?.getBoundingClientRect().width??n;s.setPointerCapture(e.pointerId);let f=!1,p=e=>{let t=e.clientX-o;if(!f&&Math.abs(t)<5)return;f=!0;let n=u+t,s=d-t;n<r&&(s-=r-n,n=r),s<i&&(n-=i-s,s=i),!(n<r||s<i)&&a(n,s)},m=()=>{s.removeEventListener(`pointermove`,p),s.removeEventListener(`pointerup`,m)};s.addEventListener(`pointermove`,p),s.addEventListener(`pointerup`,m)},title:`Drag to resize`})}function pQ(e,t){return g.useCallback(n=>r=>{r.preventDefault(),r.stopPropagation();let i=r.clientX,a=r.clientY,o=e.w,s=e.h,c=r.currentTarget;c.setPointerCapture(r.pointerId);let l=!1,u=r=>{let c=r.clientX-i,u=r.clientY-a;if(!l&&Math.abs(c)<5&&Math.abs(u)<5)return;l=!0;let d=n===`y`?o:Math.max(200,o+c),f=n===`x`?s:Math.max(160,s+u);t(e.id,d,f)},d=()=>{c.removeEventListener(`pointermove`,u),c.removeEventListener(`pointerup`,d)};c.addEventListener(`pointermove`,u),c.addEventListener(`pointerup`,d)},[e.id,e.w,e.h,t])}function mQ(){let e=oe(),t=g.useRef(0);return Eb(()=>{let n=Date.now();n-t.current<1e3||(t.current=n,e.refreshUsage())}),(0,U.jsx)(UZ,{agent:e})}var hQ=document.getElementById(`root`);if(!hQ)throw Error(`Missing #root`);cK(),JF(),fS(),(0,_.createRoot)(hQ).render((0,U.jsx)(mQ,{}));