@fungi.computer/grove 0.14.4 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/assets/{anthropic-messages-By4Z1bIQ.js → anthropic-messages-BoQicMvu.js} +3 -3
  2. package/dist/assets/{azure-openai-responses-BsDOUkgl.js → azure-openai-responses-FDabgA7u.js} +1 -1
  3. package/dist/assets/base-face-BYExcFAP.js +1 -0
  4. package/dist/assets/burger-B7R4zMC1.js +1 -0
  5. package/dist/assets/cat-IVcMI3Kr.js +1 -0
  6. package/dist/assets/{classifier-shared-DvEpCno6.js → classifier-shared-Deocnyea.js} +1 -1
  7. package/dist/assets/{cloudflare-workers-ai-system-one-DPsBwamJ.js → cloudflare-workers-ai-system-one-CGH_pK-e.js} +1 -1
  8. package/dist/assets/{compat-CUOPBfwj.js → compat-CfHbT1sC.js} +2 -2
  9. package/dist/assets/conversation-toast-BrxLLwNS.js +32 -0
  10. package/dist/assets/document-BiiUDQ73.js +1 -0
  11. package/dist/assets/document-EWUYmKg3.js +1 -0
  12. package/dist/assets/{extension-hook-CejZHRxr.js → extension-hook-Cmt9U0vD.js} +129 -129
  13. package/dist/assets/{google-generative-ai-DUCr7VeE.js → google-generative-ai-Ceyomei_.js} +1 -1
  14. package/dist/assets/{google-shared-frBE3xCX.js → google-shared-Ck6ywoif.js} +1 -1
  15. package/dist/assets/{google-vertex-CD8r-zzv.js → google-vertex-BnLh-cet.js} +1 -1
  16. package/dist/assets/index-Du7GFgpE.js +117 -0
  17. package/dist/assets/{mistral-conversations-Bw8p4PjN.js → mistral-conversations-DpJGrx0P.js} +1 -1
  18. package/dist/assets/{mushroom-a_sE2Lmz.js → mushroom-CjQXC8r7.js} +1 -1
  19. package/dist/assets/{node.browser-BZ5SwBMx.js → node.browser-CrrUeMCV.js} +1 -1
  20. package/dist/assets/{openai-codex-responses-Dle2iCls.js → openai-codex-responses-BMXymyOJ.js} +1 -1
  21. package/dist/assets/{openai-codex.models-2MmGMdv7.js → openai-codex.models-DXmil0i7.js} +1 -1
  22. package/dist/assets/{openai-completions-B4WqFHby.js → openai-completions-FGvQd2Wf.js} +1 -1
  23. package/dist/assets/{openai-decisions-CVKh6c0B.js → openai-decisions-D2COFIXF.js} +1 -1
  24. package/dist/assets/{openai-responses-shared-Clw6C8fA.js → openai-responses-shared-DpDj6Ky1.js} +1 -1
  25. package/dist/assets/{openai-responses-CkPbCkKF.js → openai-responses-ySTmwOIj.js} +1 -1
  26. package/dist/assets/{openrouter-images-BjBROYh8.js → openrouter-images-BU5Yii-E.js} +1 -1
  27. package/dist/assets/parakeet-CXq4unKH.js +36 -0
  28. package/dist/assets/parakeet-conversation-UnWYlJ1w.js +4 -0
  29. package/dist/assets/{pi-messages-9oLqnyFC.js → pi-messages-RlRIpxdV.js} +1 -1
  30. package/dist/assets/renderer-DOUDAFcS.js +1 -0
  31. package/dist/assets/{runtime-core-Bfm0wdUM.js → runtime-core-Nu5SPlul.js} +2 -2
  32. package/dist/assets/{system-one-shared-Bv09betA.js → system-one-shared-BncCsH1N.js} +1 -1
  33. package/dist/assets/{transform-messages-Btz1iqkc.js → transform-messages-DXxBwHSL.js} +1 -1
  34. package/dist/assets/{typesafe-system-one-DbReeYyW.js → typesafe-system-one-aoUo0GON.js} +1 -1
  35. package/dist/assets/{website-conversation-MEoi-Lrs.js → website-conversation-CtgsyFag.js} +1 -1
  36. package/dist/index.html +6 -6
  37. package/package.json +9 -9
  38. package/dist/assets/animation-Ca8A_H2p.js +0 -1
  39. package/dist/assets/base-face-Biu4f93I.js +0 -1
  40. package/dist/assets/burger-X7GJ8_Mj.js +0 -1
  41. package/dist/assets/cat-CNPpI38P.js +0 -1
  42. package/dist/assets/conversation-toast-D_EnORj5.js +0 -31
  43. package/dist/assets/document-CEriO-BY.js +0 -1
  44. package/dist/assets/index-D_xvnJKX.js +0 -117
  45. package/dist/assets/parakeet-DopRJWw7.js +0 -36
  46. package/dist/assets/parakeet-conversation-2EAHj4_-.js +0 -4
  47. package/dist/assets/renderer-BvWy-oBw.js +0 -1
@@ -0,0 +1,4 @@
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Ar as t,Gr as n,Ir as r,Kr as i,M as a,Mi as o,S as s,Ur as c,Wi as l,Wr as u,Yr as d,_t as f,g as p,m,qi as h,t as g}from"./conversation-toast-BrxLLwNS.js";import{Ea as _,Ta as ee,Zi as v,_a as y,ar as b,ba as te,da as ne,fa as re,ht as ie,ra as ae,xa as x,ya as oe}from"./Effect-DeiDqvoz.js";import{Ci as S,Di as C,Ei as w,Fi as se,Ia as ce,Ji as le,Ki as T,La as E,Li as D,Na as O,Nr as ue,Pi as k,Qi as A,Ra as j,Ri as de,Ta as M,Ti as fe,Wi as pe,_a as me,_i as N,ai as he,ci as P,gi as F,i as I,jr as ge,ka as L,mi as _e,pa as R,pi as z,si as ve,ta as ye,ua as B,ui as V,wi as be,xa as H,xi as xe}from"./extension-hook-Cmt9U0vD.js";import{a as Se,c as Ce,d as U,i as we,l as Te,n as Ee,o as De,r as Oe,s as ke,u as Ae}from"./parakeet-CXq4unKH.js";import{_ as je,g as W,h as Me,m as Ne,p as Pe,t as Fe,v as Ie,y as Le}from"./index-Du7GFgpE.js";var G=e(h(),1),K=o(),q=w.check(L(1),M(256)),Re=z.check(R(1),H(2**53-1)),ze=z.check(R(0),H(2**53-1)),Be=N([`write`,`external`]),Ve=C({module:S(q),access:Be}),He=C({agentId:S(q)}),Ue=C({principalId:q,agentId:S(q),sessionId:S(q),displayName:q}),We=C({title:w.check(L(1),M(512)),app:j(C({displayName:w.check(L(1),M(80)),operationLabel:w.check(L(1),M(1e3))})),inputBytes:z.check(R(0)),inputSha256:w.check(O(/^[a-f0-9]{64}$/))});C({kind:F(`pending_approval`),recordId:q,description:We});var Ge=N([`requested`,`pending`,`approved`,`claimed`,`applied`,`denied`,`expired`,`outcome_unknown`]),Ke=N([`not-found`,`not-eligible`,`already-answered`,`stale-revision`,`expired`,`declined`,`fenced`,`not-granted`,`read-only`,`pending`,`in-flight`,`outcome-unknown`,`identity-conflict`]),qe=w.check(L(1),M(512),O(/^(?=.*\S)[^\p{Cc}\u2028\u2029]*$/u)),Je=P(C({kind:F(`artifact`),ref:w.check(O(/^sha256:[a-f0-9]{64}$/)),mediaType:F(`image/png`),bytes:z.check(R(1),H(5242880))})).check(M(4)),Ye=C({recordId:q,requester:Ue,module:q,operation:q,access:Be,description:We,evidence:j(Je),authorityFence:q,reversibility:N([`reversible`,`irreversible-external`]),state:Ge,by:S(k([C({kind:F(`human`),memberId:q}),C({kind:F(`policy`)})])),reason:S(Ke),denialNote:j(qe),requestedAt:ze,expiresAt:ze,updatedAt:ze,revision:Re}),Xe=C({record:Ye,canAnswer:V,canSetAutoApprove:V});C({state:j(Ge),cursor:j(q),limit:j(z.check(R(1),H(100)))}),C({recordId:q}),C({recordId:q,decision:N([`approve`,`deny`]),expectedRevision:Re,denialNote:j(qe)});var Ze=C({scope:He,family:Ve,enabled:V}),Qe=C({kind:F(`refused`),reason:Ke,denialNote:j(qe)});T(A(Ye),{onExcessProperty:`error`}),le(A(Ye)),T(C({record_json:w})),T(A(_e)),le(A(_e)),T(C({input_json:w,output_json:S(w)}));var $e=Qe,et=C({items:P(Xe),nextCursor:S(w)}),tt=k([C({kind:F(`answered`),view:Xe}),$e]),nt=k([C({kind:F(`updated`),rule:Ze}),$e]),rt=e=>Ne(ee().transform(t=>T(e,{onExcessProperty:`error`})(t))),it=Ie(`approvals`,1,re(()=>Me({list:W(rt(et)),get:W(rt(S(Xe))),answer:W(rt(tt)),setAutoApprove:W(rt(nt))}))),at=(e,t)=>{if(e.length<=t)return e;let n=Math.max(1,Math.floor((t-1)/2));return`${e.slice(0,n)}…${e.slice(-(t-n-1))}`},ot=(e,t)=>e.length<=t?e:`${e.slice(0,t-1)}…`,st=e=>e.map(([e,t])=>({label:e,value:t}));function ct(e,t){let{record:n}=e,r=Math.max(0,n.expiresAt-t);return[[`Agent`,`${n.requester.displayName} · ${n.requester.agentId??`none`}`],[`Session`,n.requester.sessionId??`none`],[`Requester`,n.requester.principalId],[`Request`,`${n.module}.${n.operation} · ${n.access}`],[`Input`,`${n.description.inputBytes.toLocaleString()} bytes · SHA-256 ${n.description.inputSha256.slice(0,8)}…${n.description.inputSha256.slice(-6)}`],[`Expires`,`in ${String(Math.floor(r/36e5))} h ${String(Math.floor(r%36e5/6e4))} m`],[`Record`,`${n.recordId} · revision ${String(n.revision)}`]]}function lt(e){return[`Undo`,e.record.reversibility===`irreversible-external`?`Can't be undone`:`Can be undone`]}function ut(e){let t=e.operationLabel.trim().replace(/\.$/,``);return t.length===0||/[.!?\n]/.test(t)?`Allow ${e.displayName} · ${e.operationLabel}?`:`Allow ${e.displayName} to ${t.charAt(0).toLowerCase()}${t.slice(1)}?`}function dt(e,t){let{record:n}=e;return{content:{title:n.description.app===void 0?`Allow ${n.module} · ${n.operation}?`:ut(n.description.app),summary:`${n.requester.displayName} wants to use a connected tool.`,facts:[{label:`Effect`,value:(n.access===`write`?`Changes data in Fungi`:`Changes things outside Fungi`)+(n.reversibility===`irreversible-external`?` · can't be undone`:``)}],details:st([lt(e),...ct(e,t)])}}}function ft(e,t,n,r,i){let a=t.prefix?.join(` `),o=a!==void 0&&t.alwaysAllowUnavailableReason===void 0,s=t.command,c=`Allow \`${s}\`?`.length<=n?`Allow \`${s}\`?`:`Allow this command?`,l=t.cwd===r?`~`:t.cwd.startsWith(`${r}/`)?`~${t.cwd.slice(r.length)}`:t.cwd,u=Math.max(8,(n-8)*2-2),d=t.justification.length<=u?`“${t.justification}”`:`“${t.justification.slice(0,u-1)}…”`,f=[[`Folder`,at(l,Math.max(8,n-10))],[`Why`,d]];t.kind===`extension-install`&&f.push([`Note`,`Extensions run inside Fungi with access to every Agent.`]),o&&t.alwaysAllowCoverage!==void 0&&f.push([`Scope`,ot(t.alwaysAllowCoverage,Math.max(8,n-12))]),!o&&t.risk!==void 0&&f.push([`Risk`,t.risk.summary]);let p=o?`Always allow “${at(a,Math.max(8,n-5-32))}” in this project…`:void 0,m=[[`Command`,s]];return t.argv!==void 0&&m.push([`Arguments`,JSON.stringify(t.argv)]),m.push([`Folder`,t.cwd],[`Runs`,`Outside the sandbox, as you`],lt(e)),!o&&t.alwaysAllowUnavailableReason!==void 0?m.push([`Rule`,t.alwaysAllowUnavailableReason]):t.form===`shell`?m.push([`Rule`,`Shell command: no Always-allow rule can match it.`]):o&&(m.push([`Rule`,`“${a}” would match \`${a} …\` in this project`]),t.alwaysAllowCoverage!==void 0&&m.push([`Coverage`,t.alwaysAllowCoverage])),t.risk!==void 0&&m.push([`Risk`,t.risk.detail]),m.push(...ct(e,i)),{content:{title:c,body:c===`Allow this command?`?s:void 0,bodyLabel:c===`Allow this command?`?`Command`:void 0,summary:`${e.record.requester.displayName} wants to run this outside the sandbox, as you.`,facts:st(f),details:st(m)},always:p===void 0?void 0:ot(p,Math.max(12,n-5)),confirmation:o?{title:`Always allow “${a}” in this project?`,body:ot(t.alwaysAllowCoverage??`Any Workspace Agent here can then run \`${a} …\` without asking.`,Math.max(12,(n-8)*2-2))}:void 0,confirmWarning:o?t.risk?.summary:void 0,confirmYes:o?`Always allow “${a}” and run it now`:void 0}}function pt(e,t,n){let r=Math.min(n.width,60);return t===void 0?dt(e,n.now):ft(e,t,r,n.home,n.now)}function mt(e,t){switch(e){case`stale-revision`:case`already-answered`:case`not-pending`:return`This request changed. Look again before answering.`;case`expired`:return`This request expired. Nothing ran.`;case`not-found`:return`This request is gone. Nothing ran. Ask the Agent to try again.`;case`declined`:return`This request was already denied. Nothing ran.`;case`not-eligible`:return t===`always-allow`?`Always allow isn't available for this command. Approve once or deny.`:`You can't answer this request. Nothing ran. Ask whoever owns it.`;case`not-granted`:case`read-only`:return`You aren't allowed to answer this request. Nothing ran. Ask whoever owns it.`;case`fenced`:case`identity-conflict`:return`This request no longer matches what you saw. Nothing ran. Refresh and look again.`;case`pending`:return`This request hasn't been answered yet. Answer it first.`;case`in-flight`:return`This is already running. Wait for it to finish.`;case`outcome-unknown`:return`We can't tell whether this ran. Check before trying again.`;case`not-attached`:return`This session isn't connected anymore. Reconnect and try again. Nothing ran.`;default:return`Couldn't answer this request. Nothing ran. Try again.`}}var ht=`Couldn't send your answer. It may not have been recorded.`;async function gt(e,t){let{view:n,source:r}=t,i=pt(n,r.review,{width:t.width,home:t.home,now:t.now}),a=n.record;try{let n,o,s=!1;for(;n===void 0;){let c=await e.prompt({type:`decision`,message:i.content.title,summary:s?`Automatic approval is on for ${a.description.app?.displayName??`this tool`}.`:i.content.summary,facts:i.content.facts?.map(e=>({...e})),body:i.content.body,bodyLabel:i.content.bodyLabel,details:i.content.details?.map(e=>({...e})),options:[{value:`approve`,label:`Approve once`},...i.always===void 0?[]:[{value:`always`,label:i.always}],...r.family===void 0||s?[]:[{value:`family`,label:r.family.label}],{value:`deny`,label:`Deny`}],other:{label:`Deny and say why…`,placeholder:`A short reason for the Agent (optional)`,maxLength:t.noteLimit,blank:`deny`}});if(!t.stillCurrent())return{kind:`abandoned`};if(c.text!==void 0)o=c.text.trim()||void 0,n=`deny`;else if(c.selected[0]===`always`){let r=i.confirmation,a=await e.prompt({type:`decision`,message:r?.title??i.content.title,summary:i.confirmWarning,body:r?.body,options:[{value:`back`,label:`Back`},{value:`always-allow`,label:i.confirmYes??`Always allow`}],escape:`back`});if(!t.stillCurrent())return{kind:`abandoned`};a.selected[0]===`always-allow`&&(n=`always-allow`)}else if(c.selected[0]===`family`&&r.family!==void 0){let n=await e.prompt({type:`decision`,message:`${r.family.label}?`,summary:`All ${a.description.app?.displayName??`this tool`} requests that ${a.access===`write`?`change data in Fungi`:`reach outside Fungi`} will run without asking, not just this action.`,options:[{value:`back`,label:`Back`},{value:`family`,label:r.family.label}],escape:`back`});if(!t.stillCurrent()||n.selected[0]===`family`&&(s=await r.family.enable(),!t.stillCurrent()))return{kind:`abandoned`}}else c.selected[0]===`approve`?n=`approve`:c.selected[0]===`deny`&&(n=`deny`)}let c={recordId:a.recordId,decision:n,expectedRevision:a.revision},l=await r.answer(o===void 0?c:{...c,denialNote:o});return t.stillCurrent()?l.kind===`refused`?{kind:`refused`,message:mt(l.reason??`unknown`,n)}:{kind:`answered`}:{kind:`abandoned`}}catch(n){return e.signal.aborted?{kind:`abandoned`}:(t.onFailure(n),{kind:`refused`,message:ht})}}var _t=()=>void 0,vt=()=>()=>void 0;function yt(e){let{source:t,store:n,enabled:r,home:i,width:a,noteLimit:o,onFailure:s}=e,c=(0,G.useRef)(s);c.current=s;let l=(0,G.useRef)({home:i,width:a,noteLimit:o});l.current={home:i,width:a,noteLimit:o};let u=(0,G.useSyncExternalStore)(t?.subscribe??vt,t?.snapshot??_t),d=(0,G.useRef)(u);d.current=u;let f=u===void 0?void 0:JSON.stringify([`approval`,u.record.recordId,u.record.revision,u.canAnswer]);(0,G.useEffect)(()=>{let e=d.current;if(!r||t===void 0||e===void 0||!e.canAnswer||f===void 0)return;let{home:i,width:a,noteLimit:o}=l.current,s=Te({title:`Approval`}),u=s.begin(),p=()=>{let n=t.snapshot();return!u.interaction.signal.aborted&&n?.record.recordId===e.record.recordId&&n.record.revision===e.record.revision&&n.canAnswer},m=n.awaiting.add({key:f,kind:`approval`,arrivedAt:Date.now(),host:s});return gt(u.interaction,{view:e,source:t,home:i,width:a,now:Date.now(),noteLimit:o,stillCurrent:p,onFailure:e=>{c.current(e)}}).then(e=>{e.kind===`refused`?u.settle({status:`failed`,message:e.message}):(m(),u.settle(e.kind===`answered`?{status:`handled`}:{status:`cancelled`}))}),()=>{m(),s.cancel()}},[t,f,r,n])}var J=de(e=>Ae.safeParse(e).success,{representation:{id:`@fungi.computer/whistle/catalog-step/v1`,payload:null}});ie(()=>ve());var bt=w.pipe(D(L(1)),D(M(4e3)),D(O(/\S/u,{message:`Goal objective is blank`}))),xt=w.pipe(D(L(1)),D(M(1e3)),D(O(/\S/u))),St=w.pipe(D(L(1)),D(M(256))),Ct=z.check(R(0)),wt=C({kind:N([`person`,`delegator`,`blocked`,`stalled`,`cancelled`,`failed`,`no-terminal`]),detail:S(w)}),Y=C({revision:w,objective:bt,state:N([`active`,`paused`]),startedAt:Ct,pauseCause:S(wt)}),Tt=C({sequence:z.check(B(0)),objective:bt,outcome:N([`achieved`,`cleared`]),reason:S(xt),clearedBy:j(xe.check(M(256))),endedAt:Ct,afterSequence:z.check(R(0))}),Et=k([C({action:F(`set`),objective:bt,requestId:St,expectedRevision:E(S(w)),confirmed:E(V)}),C({action:N([`pause`,`resume`,`replace`,`clear`,`clear-ask`]),confirmed:E(V)}),C({})]),Dt=C({goal:S(Y),ended:P(Tt).check(M(16)),omitted:z.check(R(0))}),Ot={id:I.make(`botanical-session-goal`),commands:{controlAgent:{scope:`session`,input:C({action:N([`pause`,`resume`,`clear`]),reason:xt}),output:k([C({result:F(`paused`),goal:Y}),C({result:F(`resumed`),goal:Y}),C({result:F(`cleared`)}),C({result:F(`no_goal`)}),C({result:F(`refused`),reason:N([`not_delegator`,`not_paused_by_delegator`])})])},goal:{scope:`session`,input:Et,output:J},pause:{scope:`session`,input:C({}),output:Y},resume:{scope:`session`,input:C({}),output:Y},clear:{scope:`session`,input:C({}),output:C({})},set:{scope:`session`,input:C({objective:bt,expectedRevision:S(w),requestId:St,adoptCommandId:j(St)}),output:C({goal:Y,accepted:C({status:F(`accepted`),commandId:w})})}},projection:{schema:Dt}},X=e=>{let t=e.replace(/\s+/gu,` `).trim();return t.length<=80?t:`${t.slice(0,79)}…`},kt=e=>{let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`};function At(e){let t=e.state===`active`,n=t?`Pursuing goal since ${kt(e.startedAt)}`:e.pauseCause?.kind===`delegator`?`Goal paused by ${X(e.pauseCause.detail??`delegator`)} (/goal resume)`:`Goal paused (/goal resume)`,r=!t&&e.pauseCause?.kind!==`delegator`&&e.pauseCause?.detail!=null?[X(e.pauseCause.detail)]:[],i={id:`goal`,title:[n,X(e.objective),...r].join(` · `),tone:t?`running`:`muted`,actions:[{id:`goal`,label:t?`Pause goal`:`Resume goal`,input:{action:t?`pause`:`resume`}}]};return X(e.objective)===e.objective?i:{...i,detail:e.objective.slice(0,1024)}}function jt(e){let t={id:`goal-ended`,title:`${e.outcome===`achieved`?`Goal achieved`:`Goal cleared`} · ${X(e.objective)}`,tone:e.outcome===`achieved`?`settled`:`muted`},n=e.reason===null?t:{...t,detail:e.reason};return{id:String(e.sequence),sequence:e.sequence,at:e.endedAt,commandId:null,afterSequence:e.afterSequence,rows:[n]}}var Mt=U(Ot,{promptPresentation:`footer`,contribute:e=>{if(e.status!==`running`||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{goal:t,ended:n,omitted:r}=e.value;return{chips:[],panel:t===null?[]:[At(t)],timeline:{cells:n.map(jt),omitted:r},waiting:null}}}),Nt=w.pipe(D(L(1)),D(M(256))),Pt=w.pipe(D(L(1)),D(M(262144))),Ft=C({expression:w.pipe(D(L(1)),D(M(256))),timeZone:w.pipe(D(L(1)),D(M(128)))}),Z=C({loopId:w,origin:N([`human`,`model`]),expiresAt:S(z),prompt:Pt,mode:N([`self_paced`,`fixed_interval`]),cron:S(Ft),state:N([`active`,`paused`,`finished`,`failed`,`cancelled`]),commandId:w,reason:S(w),nextDueAt:S(z),lastError:S(w),consecutiveFailures:z.pipe(D(R(0)))}),It=C({after:j(Nt),limit:j(z.pipe(D(ye({minimum:1,maximum:64}))))}),Lt=w.pipe(D(L(1)),D(M(200))),Rt=C({loop:Z,accepted:C({status:F(`accepted`),commandId:w})}),zt=k([C({action:F(`start`),text:Pt,requestId:Lt}),C({action:N([`status`,`pause`,`resume`,`stop`,`stop-ask`,`new`]),confirmed:E(V)}),C({})]),Bt=C({loop:Z}),Vt=C({sessionId:Nt,loopId:Z.fields.loopId}),Ht={id:I.make(`botanical-session-loop`),commands:{list:{scope:`agent`,input:It,output:P(C({...Z.fields,sessionId:Nt})).pipe(D(M(64)))},pauseLoop:{scope:`agent`,input:Vt,output:Z},resumeLoop:{scope:`agent`,input:Vt,output:Z},stopLoop:{scope:`agent`,input:Vt,output:Z},loop:{scope:`session`,input:zt,output:J},startSelfPaced:{scope:`session`,input:C({prompt:Pt,requestId:Lt}),output:Rt},startFixedInterval:{scope:`session`,input:C({prompt:Pt,requestId:Lt,...Ft.fields}),output:Rt},pause:{scope:`session`,input:C({}),output:Z},resume:{scope:`session`,input:C({}),output:Z},stop:{scope:`session`,input:C({}),output:Z}},projection:{schema:Bt}},Ut=e=>{let t=e.replace(/\s+/gu,` `).trim();return t.length<=60?t:`${t.slice(0,59)}…`},Wt=e=>e.state===`failed`?`error`:e.state===`active`?`running`:e.state===`paused`?`muted`:`settled`,Gt=e=>new Intl.DateTimeFormat(void 0,{year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,timeZoneName:`short`}).format(e),Kt=U(Ht,{promptPresentation:`footer`,contribute:e=>{if(e.status!==`running`||e.value===null)return{chips:[],panel:[],timeline:{cells:[],omitted:0},waiting:null};let{loop:t}=e.value,n=t.state===`active`&&t.nextDueAt!==null;return{chips:t.state!==`active`&&t.state!==`paused`?[]:[{id:`loop`,order:2,row:{id:`loop`,title:`Loop ${t.mode===`self_paced`?`self-paced`:`fixed`}${n?` (waiting)`:``}`,tone:Wt(t)}}],panel:[{id:`loop`,title:`Loop · ${t.state} · ${t.mode===`self_paced`?`self-paced`:`${t.cron?.expression??`fixed`} ${t.cron?.timeZone??``}`}${t.nextDueAt===null?``:` · Next ${Gt(t.nextDueAt)}`} · ${Ut(t.prompt)}`,detail:[t.reason,t.prompt].filter(e=>e!==null).join(`
2
+ `).slice(0,1024),tone:Wt(t)},...t.lastError===null?[]:[{id:`error`,title:t.lastError.slice(0,4096),tone:`error`}]],timeline:{cells:[],omitted:0},waiting:n?{summary:`Waiting until ${Gt(t.nextDueAt)}`,cancel:{id:`loop`,label:`stop loop`,input:{action:`stop-ask`}}}:null}}});function qt(e){return C({nextSequence:z.check(B(0)),omitted:z.check(R(0)),events:P(C({id:w,sequence:z,at:z,commandId:S(w),event:e}))})}new TextEncoder;var Jt=C({explanation:j(w.pipe(D(M(2e3)))),steps:P(C({step:w.pipe(D(L(1)),D(M(500))),status:N([`pending`,`in_progress`,`completed`])})).pipe(D(M(50)))});Jt.pipe(D(ce(e=>e.steps.filter(e=>e.status===`in_progress`).length<=1||`At most one plan step may be in progress`)));function Yt(e){return e.steps.some(e=>e.status!==`completed`)}var Xt=C({plan:Jt,history:qt(Jt)}),Zt=k([C({action:F(`clear`)}),C({})]),Qt={id:I.make(`botanical-session-plan`),commands:{plan:{scope:`session`,input:Zt,output:J}},projection:{schema:Xt}},$t=e=>{let t=e.steps.findIndex(e=>e.status===`in_progress`),n=e.steps.filter(e=>e.status===`completed`).length;return{title:(t<0?e.steps.find(e=>e.status===`pending`):e.steps[t])?.step??`Plan complete`,detail:`${String(t<0?n:t+1)}/${String(e.steps.length)}`}},en=e=>e.steps.map((e,t)=>({id:String(t),title:e.step,tone:e.status===`completed`?`settled`:e.status===`in_progress`?`running`:`muted`})),tn=U(Qt,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null||!Yt(e.value.plan)?[]:[{id:`plan`,...$t(e.value.plan),actions:[{id:`plan`,label:`Clear plan`,input:{action:`clear`}}],inspection:{commandId:`plan`,title:`Plan`,rows:en(e.value.plan)}}],timeline:{cells:[],omitted:0},waiting:null})}),Q=e=>w.check(L(1),M(e),O(/\S/u)),nn=C({id:Q(32).check(O(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u)),header:Q(12),question:Q(1e3),options:P(C({label:Q(60),description:Q(300)})).check(L(2),M(4),ce(e=>new Set(e.map(e=>e.label)).size===e.length||`Option labels must be unique`,{representation:{id:`botanical/ask/unique-option-labels`,payload:null}})),multiple:j(V)}),rn=P(nn).check(L(1),M(4),ce(e=>new Set(e.map(e=>e.id)).size===e.length||`Question ids must be unique`,{representation:{id:`botanical/ask/unique-question-ids`,payload:null}})),an=C({askId:w,waitingOn:j(ue),escalated:j(ge),questions:rn,status:N([`live`,`parked`]),createdAt:be,expiresAt:S(be)}),on=C({asks:P(an).check(M(4))}),sn=Q(256),cn=fe(nn.fields.id,C({selected:P(Q(60)).check(M(4)),text:j(w.check(M(4e3)))})),ln=C({askId:Q(256),requestId:sn,answers:cn}),un=C({askId:Q(256),requestId:sn,note:j(w.check(M(4e3)))}),dn=N([`answered`,`declined`,`withdrawn`,`expired`,`cancelled`,`undeliverable`]),fn=k([C({result:F(`accepted`),via:N([`in_turn`,`follow_up`]),commandId:j(Q(256))}),C({result:F(`closed`),status:dn}),C({result:F(`not_found`)})]),pn=C({result:F(`refused`),reason:F(`not_sender`)}),mn=k([fn,pn]),hn=C({kind:F(`agent`),agentId:Q(256)}),gn=k([C({result:F(`escalated`),to:F(`agent`),waitingOn:ue}),C({result:F(`escalated`),to:F(`person`)}),C({result:F(`closed`),status:dn}),C({result:F(`not_found`)}),pn]),_n=C({askId:Q(256),note:E(w.check(M(1e3)))}),vn={askId:ln.fields.askId,requestId:sn,index:be.check(me(),ye({minimum:0,maximum:3})),answers:cn},yn=k([C({stage:F(`decision`),...vn,answer:cn.value}),C({askId:ln.fields.askId}),C({})]),bn={id:I.make(`botanical-session-question`),commands:{answerFlow:{scope:`session`,input:yn,output:J},answer:{scope:`session`,input:ln,output:fn},answerAgent:{scope:`session`,input:ln,output:C({result:mn,answeredBy:hn})},escalateAgent:{scope:`session`,input:_n,output:gn},decline:{scope:`session`,input:un,output:fn},list:{scope:`session`,input:C({}),output:on}},projection:{schema:on}},xn=U(bn,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:e.value.asks.map(e=>{let t=e.questions[0],n=`${t?.question??`Question`}${e.questions.length>1?` (+${String(e.questions.length-1)} more)`:``}`,r=t?.options.map(e=>e.label).join(` · `)??``;if(e.escalated!==void 0){let{by:t,reason:i,note:a}=e.escalated;n=`${i===`escalated`?`escalated by ${t.name}`:i===`sender_archived`?`${t.name} archived`:`${t.name} is gone`} · ${n}`,a!==void 0&&(r=`${r}\n${a}`)}return e.waitingOn===void 0?{id:e.askId,title:n,detail:r,tone:`attention`,actions:[{id:`answerFlow`,label:`Answer`,input:{askId:e.askId},awaiting:`question`}]}:{id:e.askId,title:`waiting on ${e.waitingOn.name} · ${n}`,detail:r,tone:`muted`,actions:[{id:`answerFlow`,label:`Answer`,input:{askId:e.askId}}]}}),timeline:{cells:[],omitted:0},waiting:null})}),$=w.check(L(1),M(256)),Sn=N([`escalated`,`sender_archived`,`sender_absent`]),Cn=N([`working`,`waiting_on_agent`,`needs_you`,`idle`,`failed`,`unavailable`]),wn=C({agentId:$,name:$,sessionId:S($),state:Cn,attention:j(w.check(M(200))),waitingOn:j($),escalated:j(C({by:$,reason:Sn})),ask:j(C({askId:$,questions:rn}))}),Tn=C({agents:P(wn).check(M(16)),more:z.check(R(0)),uncounted:z.check(R(0)),counts:C({working:z.check(R(0)),waiting_on_agent:z.check(R(0)),needs_you:z.check(R(0)),idle:z.check(R(0)),failed:z.check(R(0)),unavailable:z.check(R(0))}),escalated:z.check(R(0)),waitingOn:P(C({name:$,count:z.check(B(0))})),escalatedBy:P(C({name:$,reason:Sn,count:z.check(B(0))})),expanded:V}),En={agentId:$,sessionId:$},Dn=k(yn.members.map(e=>C({...e.fields,...En}))),On={agents:{scope:`session`,input:C({}),output:J},answerChild:{scope:`session`,input:Dn,output:J}},kn={id:I.make(`botanical-session-subagents`),commands:On,projection:{schema:Tn}};function An(e){if(e!==void 0)return e.reason===`escalated`?`escalated by ${e.by}`:e.reason===`sender_archived`?`${e.by} archived`:`${e.by} is gone`}var jn={working:{label:`working`,tone:`running`,status:`info`},waiting_on_agent:{label:`waiting`,tone:`muted`,status:`neutral`},needs_you:{label:`needs you`,tone:`attention`,status:`warning`},idle:{label:`idle`,tone:`settled`,status:`success`},failed:{label:`failed`,tone:`error`,status:`error`},unavailable:{label:`unavailable`,tone:`muted`,status:`neutral`}};function Mn(e){let t=e.state===`waiting_on_agent`?`waiting on ${e.waitingOn??`its parent`}`:jn[e.state].label,n=An(e.escalated);return n===void 0?t:`${t} · ${n}`}function Nn(e){let t=jn[e.state],n={id:e.agentId,title:`${e.name} · ${Mn(e)}`,tone:t.tone,status:{label:Mn(e),tone:t.status}},r=e.ask?.questions[0]?.question??e.attention,i=r===void 0?n:{...n,detail:r.slice(0,200)};if(e.sessionId===null)return{...i,detail:e.attention??`not messaged yet`};let a={...i,open:{params:[{key:`agent`,value:e.agentId},{key:`session`,value:e.sessionId}]}};if(e.ask===void 0)return a;let o={id:`answerChild`,label:`Answer`,input:{agentId:e.agentId,sessionId:e.sessionId,askId:e.ask.askId}};return{...a,actions:[e.state===`needs_you`?{...o,awaiting:`question`}:o]}}function Pn(e){let t=t=>e.counts[t],n=e.waitingOn.map(({name:e,count:t})=>`${String(t)} waiting on ${e}`),r=e.escalatedBy.map(({name:n,reason:r,count:i})=>{let a=An({by:n,reason:r});return e.escalated===t(`needs_you`)&&e.escalatedBy.length===1?a:`${String(i)} ${a}`}),i=r.length===0?`needs you`:`needs you (${r.join(`; `)})`,a=[...[`working`].map(e=>[e,t(e)]).filter(([,e])=>e>0).map(([e,t])=>`${String(t)} ${jn[e].label}`),...n,...[`needs_you`,`failed`,`unavailable`].map(e=>[e,t(e)]).filter(([,e])=>e>0).map(([e,t])=>`${String(t)} ${e===`needs_you`?i:jn[e].label}`)],o=t(`working`)+t(`needs_you`),s=t(`needs_you`)>0?`attention`:t(`failed`)>0?`error`:t(`working`)>0?`running`:`muted`;return{id:`summary`,title:[`${String(o)} sub-agent${o===1?``:`s`}`,...a,...e.uncounted>0?[`${String(e.uncounted)} not read`]:[],`/agents shows them`].join(` · `),tone:s}}var Fn=U(kn,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:e.value.agents.length>0&&!e.value.expanded?[Pn(e.value)]:[...e.value.agents.map(Nn),...e.value.more===0&&e.value.uncounted===0?[]:[{id:`more`,title:[...e.value.more===0?[]:[`${String(e.value.more)} more sub-agent${e.value.more===1?``:`s`}`],...e.value.uncounted===0?[]:[`${String(e.value.uncounted)} not read`]].join(` · `),tone:`muted`}]],timeline:{cells:[],omitted:0},waiting:null})});function In(e,t){if(e===null||!URL.canParse(t))return!1;let n=new URL(t);return n.protocol!==`https:`||n.hash!==`#team-billing`?!1:(e.openTeamBilling().catch(t=>(console.error(`Chat Billing navigation failed`,t),e.showToast({message:`Billing could not be opened. Please try again.`,tone:`error`}))),!0)}function Ln(e){if(e.name!==`execute`||e.status!==`completed`)return;let t=e.result?.content;if(t?.length!==1||t[0]?.type!==`text`)return;let n=pe(A(se))(t[0].text);if(b(n))return;let r=f.safeParse(n.value);return r.success?r.data.file:void 0}function Rn({item:e,ui:n}){let r=Ln(e),[i,a]=(0,G.useState)(!1);if(!r)return null;let o=async()=>{a(!0);try{await n.openNavigation(r)}catch(e){console.error(`Chat file navigation failed`,e),g(n,{variant:`error`,message:`The file could not be opened. Try again.`})}finally{a(!1)}};return(0,K.jsx)(`div`,{className:`px-3 py-2`,children:(0,K.jsx)(t,{variant:`ghost`,size:`sm`,disabled:i,onClick:()=>void o(),type:`button`,children:i?`Opening file…`:`Open ${r.path} in Inkcap`})})}var zn=k([C({kind:F(`compose`),text:w.pipe(D(L(1)),D(M(2e3)))}),C({kind:F(`navigate`),params:P(C({key:w.pipe(D(L(1)),D(M(64))),value:w.pipe(D(M(1024)))})).pipe(D(M(16)))})]);k([C({role:w.pipe(D(L(1)),D(M(80))),intent:zn}),C({appId:w.pipe(D(L(1)),D(M(128))),intent:zn})],{mode:`oneOf`});var Bn=te({displayName:x().min(1).max(80).nullable()}).nullable(),Vn=Ie(`apps.open`,1,re(()=>Me({open:je,role:W(Ne(Bn))}))),Hn=(e,t)=>e.require(Vn).open(t);Ie(`apps.call`,1,re(()=>Me({call:W(Ne(ee().transform(e=>l(e))))})));var Un=y({printId:x().min(1).max(256),destination:te({computerId:x().min(1),path:x().min(1)}),format:v([`png`,`jpeg`,`gif`,`webp`])}),Wn=ne(),Gn=ae(Wn).or(oe(x(),Wn).transform(e=>Object.values(e)));function Kn(e,t){let n=Un.safeParse(e);if(n.success)return[n.data];if(t>=3)return[];let r=Gn.safeParse(e);return r.success?r.data.flatMap(e=>Kn(e,t+1)):[]}var qn=Wn.transform(e=>Kn(e,0)).pipe(ae(Un).min(1).max(8));function Jn(e){if(e.name!==`execute`||e.status!==`completed`||e.result===void 0)return;let t=e.result.content,n=t.at(0);if(n?.type!==`text`||t.slice(1).some(e=>e.type!==`image`))return;let r=pe(A(se))(n.text);if(b(r))return;let i=qn.safeParse(r.value);return i.success?i.data:void 0}function Yn(e){return Jn(e)!==void 0}function Xn({printId:e,pictures:n,capabilities:r,ui:i}){let[a,o]=(0,G.useState)(!1),s=async()=>{o(!0);try{await Hn(r,{role:`media`,intent:{kind:`navigate`,params:[{key:`print`,value:e}]}})}catch(e){console.error(`Chat print navigation failed`,e),g(i,{variant:`error`,message:`Prints could not be opened. Try again.`})}finally{o(!1)}};return(0,K.jsxs)(`div`,{className:`flex flex-col items-start gap-2 px-3 py-2`,children:[n.map((e,t)=>(0,K.jsx)(`img`,{alt:`Panel saved in Prints`,className:`max-w-full rounded-box`,src:`data:${e.mimeType};base64,${e.data}`,style:{maxHeight:320}},t)),(0,K.jsx)(t,{variant:`outline`,size:`sm`,disabled:a,onClick:()=>void s(),type:`button`,children:a?`Opening Prints…`:`Open in Prints`})]})}function Zn({item:e,capabilities:t,ui:n}){let r=Jn(e);if(r&&t){let i=(e.result?.content??[]).flatMap(e=>e.type===`image`?[e]:[]),a=i.length===r.length;return(0,K.jsx)(K.Fragment,{children:r.map((e,r)=>(0,K.jsx)(Xn,{printId:e.printId,pictures:a?i.slice(r,r+1):r===0?i:[],capabilities:t,ui:n},e.printId))})}return null}var Qn=2e3;function $n(e,t,n,r){let[i,a]=(0,G.useState)([]);return(0,G.useEffect)(()=>{if(e===void 0){a([]);return}let i=e,o=!0;async function s(){try{let e=(await i.require(it).list({state:`pending`,limit:100})).items.filter(e=>e.record.requester.agentId===t&&e.record.requester.sessionId===n).map(e=>e.record.recordId);o&&a(t=>t.join()===e.join()?t:e)}catch(e){console.warn(`Grove could not list pending approvals`,e)}}if(s(),!r)return()=>{o=!1};let c=setInterval(()=>void s(),Qn);return()=>{o=!1,clearInterval(c)}},[e,t,n,r]),i}var er=`Couldn't send your answer. It may not have been recorded.`;function tr({recordId:e,capabilities:t,agentId:n}){let r=ke(),[i,a]=(0,G.useState)(),o=(0,G.useRef)(void 0),s=(0,G.useRef)(new Set),c=(0,G.useCallback)(e=>{o.current=e??void 0,a(e);for(let e of s.current)e()},[]);(0,G.useEffect)(()=>{o.current=void 0,a(void 0)},[t]),(0,G.useEffect)(()=>{let n=!0;async function r(){try{let r=await t.require(it).get({recordId:e});n&&c(r)}catch(e){console.warn(`Grove could not read the approval`,e)}}return r(),()=>{n=!1}},[t,e,c]);let l=i?.canAnswer===!0&&i.record.state===`pending`,u=i?.canSetAutoApprove===!0,d=i?.record.module,f=i?.record.access,p=i?.record.description.app?.displayName??`this App`;return yt({source:(0,G.useMemo)(()=>{if(l)return{snapshot:()=>o.current,subscribe:e=>(s.current.add(e),()=>{s.current.delete(e)}),answer:async e=>{let n=t.require(it),r=e.decision===`always-allow`?void 0:{recordId:e.recordId,decision:e.decision,expectedRevision:e.expectedRevision};if(r===void 0)return{kind:`refused`,reason:`not-eligible`};let i=await n.answer(e.denialNote===void 0?r:{...r,denialNote:e.denialNote});return i.kind===`answered`&&c(i.view),i},family:!u||d===void 0||f===void 0?void 0:{label:`Always allow ${p} to ${f===`write`?`change data`:`act outside Fungi`}`,enable:async()=>(await t.require(it).setAutoApprove({scope:{agentId:n},family:{module:d,access:f},enabled:!0})).kind===`updated`}}},[l,t,n,u,d,f,p,c]),store:r,enabled:!0,home:``,width:72,noteLimit:512,onFailure:nr}),null}function nr(e){console.warn(er,e)}function rr({capabilities:e,agentId:t,sessionId:n,children:r}){let i=Ce(),a=$n(e,t,n,(0,G.useMemo)(()=>[...i.settled,...i.tail].some(e=>e.kind===`tool_group`&&e.tools.some(e=>e.status===`running`)),[i.settled,i.tail]));return(0,K.jsxs)(K.Fragment,{children:[e===void 0?null:a.map(n=>(0,K.jsx)(tr,{recordId:n,capabilities:e,agentId:t},n)),r]})}var ir=(0,G.forwardRef)(function({heading:e,eyebrow:r,cover:a,action:o,children:s,className:l,...f},p){return(0,K.jsxs)(c,{...f,className:d(`caps-game-share`,l),ref:p,children:[a?(0,K.jsx)(`div`,{className:`caps-game-share-cover`,children:a}):null,(0,K.jsxs)(i,{children:[r,(0,K.jsx)(`h3`,{className:`caps-game-share-heading`,children:e})]}),(0,K.jsx)(u,{className:`gap-sm`,children:s}),(0,K.jsx)(n,{children:(0,K.jsx)(t,{asChild:!0,variant:`primary`,className:`caps-game-share-action`,children:o})})]})});function ar(e){let t=0;return e.map(e=>{let n={...e,offset:t};return t+=e.text.length,n})}function or({value:e,label:n,fieldLabel:i,displayValue:o,layout:c,title:l,tokens:u,className:f,...h}){let g=(0,G.useId)(),[_,ee]=(0,G.useState)({kind:`ready`}),v=u?u.map(e=>e.text).join(``):e,y=async()=>{ee(await navigator.clipboard.writeText(v).then(()=>({kind:`copied`}),e=>({kind:`failed`,cause:e})))};if(i!==void 0)return(0,K.jsxs)(`div`,{...h,className:d(`caps-copy-field-input`,f),children:[(0,K.jsx)(p,{htmlFor:g,children:i}),(0,K.jsxs)(m,{children:[(0,K.jsx)(s,{className:`caps-copy-field-control`,"aria-label":i,id:g,onFocus:e=>{e.currentTarget.select()},readOnly:!0,value:o??v}),(0,K.jsx)(t,{onClick:()=>void y(),variant:`outline`,children:_.kind===`copied`?`Copied`:n??`Copy`})]}),_.kind===`failed`?(0,K.jsx)(`span`,{role:`status`,children:`Could not copy. Select the text to copy it.`}):null]});let b=_.kind===`copied`?`Copied`:_.kind===`failed`?`Copy failed`:n??`Copy`;return c===`block`?(0,K.jsxs)(`figure`,{...h,className:d(`caps-copy-field-block`,f),"data-state":_.kind,children:[(0,K.jsxs)(`figcaption`,{className:`caps-copy-field-header`,children:[(0,K.jsx)(`span`,{className:`caps-copy-field-title`,children:l}),(0,K.jsxs)(t,{onClick:()=>void y(),size:`sm`,variant:_.kind===`copied`?`ghost`:`outline`,children:[_.kind===`copied`?(0,K.jsx)(a,{"aria-hidden":`true`,size:15}):(0,K.jsx)(we,{"aria-hidden":`true`,size:15}),b]}),(0,K.jsx)(r,{role:`status`,children:_.kind===`copied`?`Copied to the clipboard`:_.kind===`failed`?`Could not copy. Select the code to copy it.`:``})]}),(0,K.jsx)(`pre`,{className:`caps-copy-field-code`,tabIndex:0,children:(0,K.jsx)(`code`,{children:u?ar(u).map(e=>(0,K.jsx)(`span`,{className:`caps-copy-field-token`,"data-kind":e.kind,children:e.text},e.offset)):v})})]}):(0,K.jsxs)(`div`,{...h,className:d(`caps-copy-field`,f),children:[(0,K.jsx)(`code`,{className:`caps-copy-field-value`,children:v}),(0,K.jsxs)(t,{"aria-label":`${b}: ${v}`,onClick:()=>void y(),size:`sm`,variant:`outline`,children:[_.kind===`copied`?(0,K.jsx)(a,{size:15}):(0,K.jsx)(we,{size:15}),b]})]})}var sr=y({game:y({title:x().min(1),summary:x(),coverUrl:_().nullable(),shareUrl:_()})});function cr(e){let t=/(?:^|\n)\s*Share:\s*(https?:\/\/[^\s<>]+)/iu.exec(e);if(!t?.[1])return null;let n=t[1].replace(/[.,;!?]+$/u,``);if(!URL.canParse(n))return null;let r=new URL(n);return r.username||r.password||r.hash||r.protocol===`http:`&&![`localhost`,`127.0.0.1`].includes(r.hostname)?null:r.href}function lr(e){return cr(e)?e.split(`
3
+ `).filter(e=>!/^\s*Share:\s*/iu.test(e)).join(`
4
+ `).trim():e}function ur(e){let t=new URL(e),n=/^\/([a-z0-9]+(?:-[a-z0-9]+)*)\/?$/u.exec(t.pathname)?.[1];return!n||t.search?null:new URL(`/api/games/${n}`,t.origin)}function dr({reply:e,previewGame:t}){let n=cr(e),r=n?ur(n):null,{data:i}=Le({queryKey:Pe.of(null,`game-share`,n),enabled:r!==null&&t===void 0,queryFn:async({signal:e})=>{if(!r)return null;let t=await fetch(r,{signal:e});if(!t.ok)return null;let i=sr.safeParse(await t.json());return i.success&&i.data.game.shareUrl===n?i.data.game:null}}),a=t??i;if(!n)return null;let o=new URL(n),s=`${o.host}${o.pathname.replace(/\/$/u,``)}`,c=a?.coverUrl&&r?t?a.coverUrl:new URL(`${r.pathname}/cover`,r.origin).href:null;return(0,K.jsxs)(ir,{"data-game-share-card":`true`,"data-theme":`vishnu`,heading:a?.title??`Your game is ready`,eyebrow:(0,K.jsx)(Oe,{tone:`secondary`,variant:`quiet`,children:`Made with your Agent`}),cover:c?(0,K.jsx)(`img`,{alt:`A scene from ${a?.title??`your game`}`,src:c}):null,action:(0,K.jsx)(`a`,{href:n,rel:`noopener noreferrer`,target:`_blank`,children:`Play ↗`}),children:[a?.summary?(0,K.jsx)(`p`,{className:`text-sm`,children:a.summary}):null,(0,K.jsx)(or,{displayValue:s,fieldLabel:`Share link`,label:`Copy link`,value:n})]})}var fr=[Mt,Kt,tn,xn,Fn],pr=e=>(0,K.jsx)(dr,{reply:e});function mr({prefill:e,onPrefilled:t}){let n=De(),r=(0,G.useRef)(null);return(0,G.useEffect)(()=>{!e||r.current===e.requestId||(r.current=e.requestId,n.setDraft(e.text),e.send===!0&&n.send(),t())},[n.setDraft,n.send,t,e]),null}function hr({session:e,draftIdentity:t,connection:n,commands:r,prefill:i=null,onPrefilled:a=()=>void 0,onOpen:o,models:s,autoFocus:c}){let l=n?.ui??null,u=n?.capabilities,d=(0,G.useMemo)(()=>({modelSetup:s===void 0?void 0:{state:s,fix:{label:`Add a model key`,onSelect:()=>{l?.openSetup(`model`).catch(e=>{console.error(`Grove could not open model setup`,e)})}}},starters:Fe}),[s,l]),f=(0,G.useCallback)(e=>In(l,e),[l]),p=(0,G.useCallback)(e=>l?(0,K.jsxs)(K.Fragment,{children:[(0,K.jsx)(Rn,{item:e,ui:l}),(0,K.jsx)(Zn,{item:e,capabilities:u,ui:l})]}):null,[l,u]),m=(0,G.useCallback)(e=>u!==void 0&&Yn(e),[u]),h=(0,G.useCallback)(e=>{g(l,e)},[l]);return(0,K.jsxs)(Se,{session:e,draftIdentity:t,clients:fr,authorOf:he,onToast:h,children:[(0,K.jsx)(mr,{prefill:i,onPrefilled:a}),(0,K.jsx)(rr,{capabilities:u,agentId:t.agentId,sessionId:t.sessionId,children:(0,K.jsx)(Ee,{onLink:f,onOpen:o,hostFacts:d,autoFocus:c,composerActionVariant:`outline`,commands:r,renderAssistantAttachment:pr,formatAssistantText:lr,renderToolActions:p,claimsToolMedia:m})},t.sessionId)]})}export{hr as ParakeetConversation};
@@ -1,4 +1,4 @@
1
- import{r as e}from"./text-_WthCHzw.js";import{t}from"./provider-env-CcCbsTJq.js";import{a as n,n as r,t as i}from"./diagnostics-CxvqSC4Q.js";import{n as a,t as o}from"./headers-FK4rgixo.js";import{n as s}from"./streaming-json-Dg-jk7Sx.js";import{getIdentityHeaders as c}from"./compat-CUOPBfwj.js";var l=class extends Error{code;diagnosticDetails;constructor(e,t,n){super(e),this.name=`PiMessagesResponseError`,this.code=t,this.diagnosticDetails=n}};function u(e){try{let t=JSON.parse(e),n=t?.error;return t&&typeof n==`object`&&n&&!Array.isArray(n)?t:void 0}catch{return}}function d(t){let n=8192;return t.length>n?`${e(t,0,n)}…`:t}function f(e,t,n){let r=typeof n?.error?.message==`string`?n.error.message:void 0,i=typeof n?.error?.code==`string`?n.error.code:void 0,a=r??t,o=i?` (${i})`:``;return`${e.status} ${e.statusText}: ${a}${o}`}function p(e,t,n,r){let i=u(r),a=typeof i?.error?.code==`string`?i.error.code:void 0;return new l(f(n,r,i),a,{version:1,provider:e.provider,model:e.id,url:t.toString(),status:n.status,statusText:n.statusText,...i?.error===void 0?{}:{error:i.error},...i?{}:{body:d(r)},timestampMs:Date.now()})}function m(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function h(e,t){t&&i(e,{type:`pi_messages_rewrite`,timestamp:Date.now(),details:{...t}})}function g(e){let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:m(),stopReason:`pending`,timestamp:Date.now()},n=new Map;return e=>{if(`contentIndex`in e){let n=e.contentIndex,r=e.type.endsWith(`_start`)?t.content.length:t.content.length-1;if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>r)throw Error(`Invalid contentIndex ${JSON.stringify(n)} in pi-messages ${e.type} event`)}switch(e.type){case`done`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),h(t,e.rewrite),{type:`done`,reason:e.reason,message:t};case`error`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),h(t,e.rewrite),{type:`error`,reason:e.reason,error:t};case`start`:break;case`text_start`:t.content[e.contentIndex]={type:`text`,text:``};break;case`text_delta`:t.content[e.contentIndex].text+=e.delta;break;case`text_end`:Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case`thinking_start`:t.content[e.contentIndex]={type:`thinking`,thinking:``};break;case`thinking_delta`:t.content[e.contentIndex].thinking+=e.delta;break;case`thinking_end`:Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case`toolcall_start`:t.content[e.contentIndex]={type:`toolCall`,id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,new s);break;case`toolcall_delta`:{let r=n.get(e.contentIndex);r!==void 0&&(t.content[e.contentIndex].arguments=r.append(e.delta));break}case`toolcall_end`:return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:`toolcall_end`,contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*_(e){let t=new TextDecoder,n=e.getReader(),r=``;try{for(;;){let{done:e,value:i}=await n.read();r+=e?t.decode():t.decode(i,{stream:!0}),r=r.replace(/\r\n/g,`
1
+ import{r as e}from"./text-_WthCHzw.js";import{t}from"./provider-env-CcCbsTJq.js";import{a as n,n as r,t as i}from"./diagnostics-CxvqSC4Q.js";import{n as a,t as o}from"./headers-FK4rgixo.js";import{n as s}from"./streaming-json-Dg-jk7Sx.js";import{getIdentityHeaders as c}from"./compat-CfHbT1sC.js";var l=class extends Error{code;diagnosticDetails;constructor(e,t,n){super(e),this.name=`PiMessagesResponseError`,this.code=t,this.diagnosticDetails=n}};function u(e){try{let t=JSON.parse(e),n=t?.error;return t&&typeof n==`object`&&n&&!Array.isArray(n)?t:void 0}catch{return}}function d(t){let n=8192;return t.length>n?`${e(t,0,n)}…`:t}function f(e,t,n){let r=typeof n?.error?.message==`string`?n.error.message:void 0,i=typeof n?.error?.code==`string`?n.error.code:void 0,a=r??t,o=i?` (${i})`:``;return`${e.status} ${e.statusText}: ${a}${o}`}function p(e,t,n,r){let i=u(r),a=typeof i?.error?.code==`string`?i.error.code:void 0;return new l(f(n,r,i),a,{version:1,provider:e.provider,model:e.id,url:t.toString(),status:n.status,statusText:n.statusText,...i?.error===void 0?{}:{error:i.error},...i?{}:{body:d(r)},timestampMs:Date.now()})}function m(){return{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}}}function h(e,t){t&&i(e,{type:`pi_messages_rewrite`,timestamp:Date.now(),details:{...t}})}function g(e){let t={role:`assistant`,content:[],api:e.api,provider:e.provider,model:e.id,usage:m(),stopReason:`pending`,timestamp:Date.now()},n=new Map;return e=>{if(`contentIndex`in e){let n=e.contentIndex,r=e.type.endsWith(`_start`)?t.content.length:t.content.length-1;if(typeof n!=`number`||!Number.isInteger(n)||n<0||n>r)throw Error(`Invalid contentIndex ${JSON.stringify(n)} in pi-messages ${e.type} event`)}switch(e.type){case`done`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),h(t,e.rewrite),{type:`done`,reason:e.reason,message:t};case`error`:return Object.assign(t,{stopReason:e.reason,usage:e.usage,errorMessage:e.errorMessage,responseId:e.responseId}),e.responseModel!==void 0&&(t.responseModel=e.responseModel),e.providerThinkingLevel!==void 0&&(t.providerThinkingLevel=e.providerThinkingLevel),h(t,e.rewrite),{type:`error`,reason:e.reason,error:t};case`start`:break;case`text_start`:t.content[e.contentIndex]={type:`text`,text:``};break;case`text_delta`:t.content[e.contentIndex].text+=e.delta;break;case`text_end`:Object.assign(t.content[e.contentIndex],{text:e.content,textSignature:e.contentSignature});break;case`thinking_start`:t.content[e.contentIndex]={type:`thinking`,thinking:``};break;case`thinking_delta`:t.content[e.contentIndex].thinking+=e.delta;break;case`thinking_end`:Object.assign(t.content[e.contentIndex],{thinking:e.content,thinkingSignature:e.contentSignature,redacted:e.redacted});break;case`toolcall_start`:t.content[e.contentIndex]={type:`toolCall`,id:e.id,name:e.toolName,arguments:{}},n.set(e.contentIndex,new s);break;case`toolcall_delta`:{let r=n.get(e.contentIndex);r!==void 0&&(t.content[e.contentIndex].arguments=r.append(e.delta));break}case`toolcall_end`:return Object.assign(t.content[e.contentIndex],e.toolCall),n.delete(e.contentIndex),{type:`toolcall_end`,contentIndex:e.contentIndex,toolCall:t.content[e.contentIndex],partial:t}}return{...e,partial:t}}}async function*_(e){let t=new TextDecoder,n=e.getReader(),r=``;try{for(;;){let{done:e,value:i}=await n.read();r+=e?t.decode():t.decode(i,{stream:!0}),r=r.replace(/\r\n/g,`
2
2
  `);let a=r.indexOf(`
3
3
 
4
4
  `);for(;a!==-1;){let e=v(r.slice(0,a));e&&(yield e),r=r.slice(a+2),a=r.indexOf(`
@@ -0,0 +1 @@
1
+ import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{ht as n,j as r,r as i,t as a,xa as o}from"./Effect-DeiDqvoz.js";import{A as s,B as c,C as l,D as u,E as d,H as f,I as p,L as m,O as h,T as g,U as _,a as ee,c as v,d as y,f as te,g as ne,j as re,k as b,l as x,o as S,p as C,r as ie,s as w,u as ae,w as T,y as E,z as oe}from"./document-EWUYmKg3.js";import{i as D,t as se}from"./document-BiiUDQ73.js";var O=(e,t)=>{if(p(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},k=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),b(t))return n;if(d(+t))return+t;let r=t,i=e?e.labels:null,a=!g(i),o=O(e,r),s=!b(o),c=f.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return te(u,d,e[0])}return s?o:a?b(i[r])?n:i[r]:n};function A(e){return E((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function j(e,t,n,r,i,a){let o=d(e.duration)&&e.duration<=1e-11?n-c:n;t.composition&&y(t,o,1,1,_.AUTO);let s=r?new ie(r,e,t,o,!1,i,a):new w(e,t,o);return t.composition&&s.init(!0),ne(t,s),l(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=A(t),t}var M=0,ce=class extends w{constructor(e={}){super(e,null,0),++M,this.id=b(e.id)?M:e.id,this.duration=0,this.labels={};let t=e.defaults,n=m.defaults;this.defaults=t?s(t,n):n,this.composition=C(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=C(e.playbackEase,n.playbackEase);this._ease=r?ee(r):null,this.iterationDuration=0}add(e,t,n){let r=u(t),i=u(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=m.editor&&m.editor.addTimelineChild,a=n&&n.type===`Stagger`&&m.editor,o=T(n)?n:null;if(o||a){let t=S(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||m.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,b(c)||(n.id=c+`-`+l);let i=k(this,f(e,l,t,null,this));j(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;j(t,this,k(this,a),e)}}else j(e,this,k(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(b(e)||e&&b(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!b(e)&&!b(e.persist)&&(e.persist=!0);let r=m.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return b(t)?this:(t.duration=c,t.composition=oe.replace,this.add(e,t,n))}call(e,t){return b(e)||e&&!T(e)?this:(m.editor&&m.editor.addTimelineCall&&(t=m.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return b(e)||e&&!h(e)?this:(m.editor&&m.editor.addTimelineLabel&&(t=m.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=k(this,t),this)}remove(e,t){return x(S(e),this,t),this}stretch(e){let t=this.duration;if(t===re(e))return this;let n=e/t,r=this.labels;l(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return l(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),l(this,e=>e.revert,!0),ae(this)}then(e){return super.then(e)}},le=e=>m.editor?m.editor.addTimeline(e):new ce(e).init(),N=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),I=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),P(),F());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),R=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),z=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),R());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(I());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),L(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(N(),P(),F(),I(),L(),R(),z(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=D(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}seek(e){if(X(e,`timeMs`),e<0)throw RangeError(`timeMs must be nonnegative`);this.pause(!0);for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])t?.seek(e);this.dirty=!0,this.renderStill()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=D(n.color);r&&(n.color=this.palette[r]);let i=D(n.backface);i&&(n.backface=this.palette[i]);let a=D(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=le({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=v({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>r(function*(){let t=se.parse(e.document.data),r=yield*a(n(()=>e.target.ownerDocument.createElement(`canvas`)),e=>n(()=>{e.remove()}));r.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(r);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let c,l=!0,u=!1,d=()=>{l||u||c!==void 0||(c=s.requestAnimationFrame(e=>{c=void 0,p.tick(e)&&d()}))},f=()=>{u||(l?p.renderStill():d())},p=yield*a(n(()=>ye({target:r,scene:t,onInvalidate:f,maxPixels:e.maxPixels})),e=>n(()=>{e.destroy()}));yield*i(()=>n(()=>{u=!0,c!==void 0&&s.cancelAnimationFrame(c)})),p.pause(!0);let m=!1,h,g;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,r]of Object.entries(e.appearance)){let e=o().safeParse(r);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let r=JSON.stringify(n);r!==g&&(p.setPalette(n),g=r);let i=e.expression??t.defaultPresentation.expression;if(!i)throw Error(`Zdog avatar needs an expression`);let a=JSON.stringify([e.activity,i]);a!==h&&(p.present({activity:e.activity,expression:i}),h=a),m=e.timeMs!==void 0,e.timeMs!==void 0&&p.seek(e.timeMs),f()},pause(e){l=m||e,p.pause(l),l&&c!==void 0&&(s.cancelAnimationFrame(c),c=void 0),f()}}});export{be as t};