@fungi.computer/grove 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist/assets/{anthropic-messages-BPUe3sjP.js → anthropic-messages-NIo9paF2.js} +3 -3
  2. package/dist/assets/{azure-openai-responses-qVCjcy57.js → azure-openai-responses-DVDapogw.js} +1 -1
  3. package/dist/assets/burger-CdmYCtZ0.js +1 -0
  4. package/dist/assets/cat-DPVVX4Jw.js +1 -0
  5. package/dist/assets/{compat-Dluy1HPa.js → compat-wIVDvT_3.js} +2 -2
  6. package/dist/assets/{extension-hook-Ce1QNicQ.js → extension-hook-DCZVg8jj.js} +112 -112
  7. package/dist/assets/extensions-CVJs4Snj.js +1 -0
  8. package/dist/assets/{google-generative-ai-D4EEWKtU.js → google-generative-ai-CrPXPiH2.js} +1 -1
  9. package/dist/assets/{google-shared-CvUYw8Za.js → google-shared-CSSwo4u4.js} +1 -1
  10. package/dist/assets/{google-vertex-MtdrRNuD.js → google-vertex-G6njJPqz.js} +1 -1
  11. package/dist/assets/{index--Y1OC0IE.js → index-BJuRfQVe.js} +14 -14
  12. package/dist/assets/{mistral-conversations-CI9T5Sz9.js → mistral-conversations-DYDnZWmT.js} +1 -1
  13. package/dist/assets/{mushroom-CstiBfYI.js → mushroom-CO06GGdJ.js} +1 -1
  14. package/dist/assets/{node.browser-DL9pz-ZD.js → node.browser-BJm5CXR1.js} +1 -1
  15. package/dist/assets/{openai-codex-responses-C1JF2nxc.js → openai-codex-responses-dWbmTJNd.js} +1 -1
  16. package/dist/assets/{openai-completions-DJRWblh-.js → openai-completions-2Qvw2FRG.js} +1 -1
  17. package/dist/assets/{openai-responses-DT9fG-Eg.js → openai-responses-BvoV9Y7s.js} +1 -1
  18. package/dist/assets/{openai-responses-shared-BDR0j8d9.js → openai-responses-shared-JWDc0New.js} +1 -1
  19. package/dist/assets/parakeet-conversation-CN_nK0S9.js +4 -0
  20. package/dist/assets/{renderer-l9sYXW5N.js → renderer-DPA8RMmh.js} +1 -1
  21. package/dist/assets/runtime-core-DlPx0Rnp.js +1 -0
  22. package/dist/assets/{transform-messages-ByuM-ZZe.js → transform-messages-DdT3SC0y.js} +1 -1
  23. package/dist/index.html +2 -2
  24. package/package.json +6 -6
  25. package/dist/assets/burger-CJ8nsj7v.js +0 -1
  26. package/dist/assets/cat-DCYVOD6V.js +0 -1
  27. package/dist/assets/extensions-D55BOb_a.js +0 -1
  28. package/dist/assets/parakeet-conversation-DFuwoFfN.js +0 -4
  29. package/dist/assets/runtime-core-BHRx5Fxu.js +0 -2
@@ -1 +1 @@
1
- import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{j as n,ma as r,pt as i,r as a,t as o}from"./Effect-BY0T-p9d.js";import{i as s,t as c}from"./document-DjWTbvB5.js";import{A as l,B as u,C as d,D as f,E as p,F as m,G as h,H as g,I as _,L as v,M as y,N as ee,O as b,P as x,R as S,S as C,T as te,U as w,V as T,W as ne,b as re,j as E,k as ie,w as ae,x as D,y as O,z as oe}from"./index--Y1OC0IE.js";var k=(e,t)=>{if(u(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},A=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),v(t))return n;if(x(+t))return+t;let r=t,i=e?e.labels:null,a=!ee(i),o=k(e,r),s=!v(o),c=ne.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return f(u,d,e[0])}return s?o:a?v(i[r])?n:i[r]:n};function j(e){return l((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function M(e,t,n,r,i,a){let o=x(e.duration)&&e.duration<=1e-11?n-w:n;t.composition&&p(t,o,1,1,h.AUTO);let s=r?new O(r,e,t,o,!1,i,a):new C(e,t,o);return t.composition&&s.init(!0),ie(t,s),E(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=j(t),t}var N=0,se=class extends C{constructor(e={}){super(e,null,0),++N,this.id=v(e.id)?N:e.id,this.duration=0,this.labels={};let t=e.defaults,n=T.defaults;this.defaults=t?S(t,n):n,this.composition=b(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=b(e.playbackEase,n.playbackEase);this._ease=r?re(r):null,this.iterationDuration=0}add(e,t,n){let r=m(t),i=m(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=T.editor&&T.editor.addTimelineChild,a=n&&n.type===`Stagger`&&T.editor,o=y(n)?n:null;if(o||a){let t=D(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||T.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,v(c)||(n.id=c+`-`+l);let i=A(this,f(e,l,t,null,this));M(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;M(t,this,A(this,a),e)}}else M(e,this,A(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(v(e)||e&&v(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!v(e)&&!v(e.persist)&&(e.persist=!0);let r=T.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return v(t)?this:(t.duration=w,t.composition=g.replace,this.add(e,t,n))}call(e,t){return v(e)||e&&!y(e)?this:(T.editor&&T.editor.addTimelineCall&&(t=T.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return v(e)||e&&!_(e)?this:(T.editor&&T.editor.addTimelineLabel&&(t=T.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=A(this,t),this)}remove(e,t){return ae(D(e),this,t),this}stretch(e){let t=this.duration;if(t===oe(e))return this;let n=e/t,r=this.labels;E(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return E(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),E(this,e=>e.revert,!0),te(this)}then(e){return super.then(e)}},ce=e=>T.editor?T.editor.addTimeline(e):new se(e).init(),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),I=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),R=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),F(),I());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),z=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),le=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),z());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(R());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),R(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(P(),F(),I(),L(),R(),z(),le(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=s(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}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=s(n.color);r&&(n.color=this.palette[r]);let i=s(n.backface);i&&(n.backface=this.palette[i]);let a=s(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=ce({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=d({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>n(function*(){let t=c.parse(e.document.data),n=yield*o(i(()=>e.target.ownerDocument.createElement(`canvas`)),e=>i(()=>{e.remove()}));n.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(n);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let l,u=!0,d=!1,f=()=>{u||d||l!==void 0||(l=s.requestAnimationFrame(e=>{l=void 0,m.tick(e)&&f()}))},p=()=>{d||(u?m.renderStill():f())},m=yield*o(i(()=>ye({target:n,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>i(()=>{e.destroy()}));yield*a(()=>i(()=>{d=!0,l!==void 0&&s.cancelAnimationFrame(l)})),m.pause(!0);let h=!1,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,i]of Object.entries(e.appearance)){let e=r().safeParse(i);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let i=JSON.stringify(n);i!==_&&(m.setPalette(n),_=i);let a=e.expression??t.defaultPresentation.expression;if(!a)throw Error(`Zdog avatar needs an expression`);let o=JSON.stringify([e.activity,a]);o!==g&&(m.present({activity:e.activity,expression:a}),g=o),h=e.timeMs!==void 0,e.timeMs!==void 0&&m.seek(e.timeMs),p()},pause(e){u=h||e,m.pause(u),u&&l!==void 0&&(s.cancelAnimationFrame(l),l=void 0),p()}}});export{be as t};
1
+ import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{j as n,ma as r,pt as i,r as a,t as o}from"./Effect-BY0T-p9d.js";import{i as s,t as c}from"./document-DjWTbvB5.js";import{A as l,B as u,C as d,D as f,E as p,F as m,G as h,H as g,I as _,L as v,M as y,N as ee,O as b,P as x,R as S,S as C,T as te,U as w,V as T,W as ne,b as re,j as E,k as ie,w as ae,x as D,y as O,z as oe}from"./index-BJuRfQVe.js";var k=(e,t)=>{if(u(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},A=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),v(t))return n;if(x(+t))return+t;let r=t,i=e?e.labels:null,a=!ee(i),o=k(e,r),s=!v(o),c=ne.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return f(u,d,e[0])}return s?o:a?v(i[r])?n:i[r]:n};function j(e){return l((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function M(e,t,n,r,i,a){let o=x(e.duration)&&e.duration<=1e-11?n-w:n;t.composition&&p(t,o,1,1,h.AUTO);let s=r?new O(r,e,t,o,!1,i,a):new C(e,t,o);return t.composition&&s.init(!0),ie(t,s),E(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=j(t),t}var N=0,se=class extends C{constructor(e={}){super(e,null,0),++N,this.id=v(e.id)?N:e.id,this.duration=0,this.labels={};let t=e.defaults,n=T.defaults;this.defaults=t?S(t,n):n,this.composition=b(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=b(e.playbackEase,n.playbackEase);this._ease=r?re(r):null,this.iterationDuration=0}add(e,t,n){let r=m(t),i=m(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=T.editor&&T.editor.addTimelineChild,a=n&&n.type===`Stagger`&&T.editor,o=y(n)?n:null;if(o||a){let t=D(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||T.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,v(c)||(n.id=c+`-`+l);let i=A(this,f(e,l,t,null,this));M(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;M(t,this,A(this,a),e)}}else M(e,this,A(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(v(e)||e&&v(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!v(e)&&!v(e.persist)&&(e.persist=!0);let r=T.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return v(t)?this:(t.duration=w,t.composition=g.replace,this.add(e,t,n))}call(e,t){return v(e)||e&&!y(e)?this:(T.editor&&T.editor.addTimelineCall&&(t=T.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return v(e)||e&&!_(e)?this:(T.editor&&T.editor.addTimelineLabel&&(t=T.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=A(this,t),this)}remove(e,t){return ae(D(e),this,t),this}stretch(e){let t=this.duration;if(t===oe(e))return this;let n=e/t,r=this.labels;E(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return E(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),E(this,e=>e.revert,!0),te(this)}then(e){return super.then(e)}},ce=e=>T.editor?T.editor.addTimeline(e):new se(e).init(),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),I=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),R=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),F(),I());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),z=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),le=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),z());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(R());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),R(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(P(),F(),I(),L(),R(),z(),le(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=s(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}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=s(n.color);r&&(n.color=this.palette[r]);let i=s(n.backface);i&&(n.backface=this.palette[i]);let a=s(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=ce({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=d({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>n(function*(){let t=c.parse(e.document.data),n=yield*o(i(()=>e.target.ownerDocument.createElement(`canvas`)),e=>i(()=>{e.remove()}));n.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(n);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let l,u=!0,d=!1,f=()=>{u||d||l!==void 0||(l=s.requestAnimationFrame(e=>{l=void 0,m.tick(e)&&f()}))},p=()=>{d||(u?m.renderStill():f())},m=yield*o(i(()=>ye({target:n,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>i(()=>{e.destroy()}));yield*a(()=>i(()=>{d=!0,l!==void 0&&s.cancelAnimationFrame(l)})),m.pause(!0);let h=!1,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,i]of Object.entries(e.appearance)){let e=r().safeParse(i);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let i=JSON.stringify(n);i!==_&&(m.setPalette(n),_=i);let a=e.expression??t.defaultPresentation.expression;if(!a)throw Error(`Zdog avatar needs an expression`);let o=JSON.stringify([e.activity,a]);o!==g&&(m.present({activity:e.activity,expression:a}),g=o),h=e.timeMs!==void 0,e.timeMs!==void 0&&m.seek(e.timeMs),p()},pause(e){u=h||e,m.pause(u),u&&l!==void 0&&(s.cancelAnimationFrame(l),l=void 0),p()}}});export{be as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,Bn as n,F as r,G as i,Gr as a,I as o,Jn as s,K as c,O as l,P as u,Q as d,Qn as f,R as p,St as m,V as h,Xn as ee,Y as te,Yn as ne,_ as re,a as g,bt as ie,c as _,ct as v,d as ae,dt as y,er as b,et as x,ft as S,g as C,h as w,ht as T,i as oe,ir as E,j as D,m as se,mi as ce,mt as O,n as le,o as ue,or as k,ot as A,p as de,pt as j,r as fe,s as M,sr as N,st as pe,t as me,vt as P,w as he,xt as F,y as I,yt as L}from"./Effect-BY0T-p9d.js";import{$ as ge,$i as R,$t as _e,A as ve,Aa as ye,Ar as be,At as xe,B as Se,Bi as z,Bn as Ce,Br as we,Bt as Te,C as Ee,Cr as B,Ct as De,D as Oe,Da as ke,Dn as Ae,Dr as je,Dt as Me,E as Ne,Ea as Pe,En as Fe,Et as Ie,F as Le,Fn as Re,Fr as ze,Ft as Be,Ga as Ve,Gn as V,Gr as He,Gt as Ue,H as We,Ha as Ge,Hn as Ke,Hr as H,Ht as qe,I as Je,Ii as Ye,Ir as Xe,It as Ze,J as Qe,Ja as $e,Ji as et,Jn as U,Jr as tt,Jt as nt,K as rt,Kn as it,Kt as at,L as ot,Lt as st,M as ct,Ma as lt,Mr as ut,Mt as dt,N as ft,Na as pt,Nt as mt,O as ht,Oa as gt,Oi as _t,Or as vt,Ot as yt,P as bt,Pa as xt,Pn as St,Pt as Ct,Q as wt,Qi as Tt,Qn as Et,Qr as W,Qt as Dt,R as Ot,Rt as kt,S as At,St as jt,T as Mt,Ta as Nt,Ti as Pt,Tn as Ft,Tr as It,Tt as Lt,U as Rt,Ua as zt,Un as Bt,Ur as Vt,Ut as Ht,V as Ut,Va as Wt,Vr as Gt,Vt as Kt,W as qt,Wa as Jt,Wi as Yt,Wn as Xt,Wt as Zt,X as Qt,Xn as $t,Xr as en,Xt as tn,Y as nn,Ya as rn,Yr as an,Yt as on,Z as sn,Za as cn,Zi as ln,Zt as un,_ as dn,_n as fn,_t as pn,a as mn,aa as hn,an as gn,at as _n,b as vn,bn as yn,bt as bn,c as xn,ci as Sn,cn as Cn,cr as wn,ct as Tn,d as En,dn as Dn,dr as On,dt as kn,en as An,er as jn,et as Mn,f as Nn,fa as Pn,fi as Fn,fn as In,ft as Ln,g as Rn,gn as G,gr as zn,gt as Bn,h as Vn,hn as Hn,ht as Un,i as Wn,in as Gn,ir as Kn,it as qn,j as Jn,ja as Yn,jn as Xn,jr as Zn,jt as Qn,k as $n,kr as er,kt as tr,l as nr,li as rr,ln as ir,lt as ar,m as or,mn as sr,mt as cr,n as lr,na as K,ni as ur,nt as dr,o as fr,oi as q,on as pr,ot as mr,p as hr,pi as gr,pn as _r,pr as vr,pt as yr,q as br,qa as xr,qn as Sr,qt as Cr,r as wr,ra as Tr,rn as Er,rt as Dr,s as Or,si as kr,sn as Ar,st as jr,t as Mr,ta as Nr,ti as Pr,tn as Fr,tt as Ir,u as Lr,ui as Rr,un as zr,ut as Br,v as Vr,vt as Hr,w as Ur,wn as Wr,wr as Gr,wt as Kr,x as qr,xn as Jr,xr as Yr,xt as Xr,y as Zr,yn as Qr,yt as $r,z as ei,za as ti,zr as ni,zt as ri}from"./extension-hook-DCZVg8jj.js";import{l as ii,m as ai,p as oi}from"./preload-helper-DY31Aviq.js";import{d as si,f as ci,u as li}from"./index-BJuRfQVe.js";import{a as ui,i as di,n as fi,o as pi,r as mi,t as hi}from"./extensions-CVJs4Snj.js";var gi=Nr(()=>Vi),_i=B(gi),vi=H({id:Xe,payload:er}),yi=H({...vi.fields,schemas:Tt(_i)});function bi(e){let t={};for(let[n,r]of Object.entries(e))Pn(r)&&a(t,n,r);return Object.keys(t).length===0?E():k(t)}var xi=Tt(we(Gt,en)).pipe(Rr(R(be),{decode:Nt(),encode:ke(e=>f(e)||e.value===void 0?E():bi(e.value))})),Si=Nr(()=>Ti),Ci=B(Si),wi={annotations:xi,checks:Ci},Ti=an([H({_tag:K(`Filter`),representation:yi,annotations:xi,aborted:It}),H({_tag:K(`FilterGroup`),representation:Tt(yi),annotations:xi,checks:ze(Si)})]);function J(e){return H({_tag:K(e),...wi})}var Ei=H({_tag:K(`Declaration`),representation:vi,annotations:xi,typeParameters:_i,checks:Ci}),Di=H({_tag:K(`Suspend`),annotations:xi,checks:He([]),thunk:gi});function Oi(e,t){return t.pipe(Rr(H({type:K(e),value:t}),{decode:Pe(e=>e.value),encode:Pe(t=>({type:e,value:t}))}))}var ki=Oi(`string`,Gt),Ai=Oi(`number`,ni),ji=H({_tag:K(`Literal`),...wi,literal:an([ki,Oi(`number`,je),Oi(`bigint`,Gr),Oi(`boolean`,It)])}),Mi=H({_tag:K(`UniqueSymbol`),...wi,symbol:Vt}),Ni=H({_tag:K(`Enum`),...wi,enums:B(He([Gt,an([ki,Ai])]))}),Pi=H({_tag:K(`TemplateLiteral`),...wi,parts:_i}),Fi=H({isOptional:It,type:gi,annotations:xi}),Ii=H({_tag:K(`Arrays`),...wi,elements:B(Fi),rest:_i}),Li=H({name:an([ki,Ai,Oi(`symbol`,Vt)]),type:gi,isOptional:It,isMutable:It,annotations:xi}),Ri=H({parameter:gi,type:gi}),zi=H({_tag:K(`Objects`),...wi,propertySignatures:B(Li),indexSignatures:B(Ri)}),Bi=H({_tag:K(`Union`),...wi,types:_i,options:R(H({mode:R(ut([`anyOf`,`oneOf`]))}))}),Vi=an([Ei,H({_tag:K(`Reference`),$ref:Xe}),Di,J(`Null`),J(`Undefined`),J(`Void`),J(`Never`),J(`Unknown`),J(`Any`),J(`String`),J(`Number`),J(`Boolean`),J(`BigInt`),J(`Symbol`),J(`ObjectKeyword`),ji,Mi,Ni,Pi,Ii,zi,Bi]),Hi=rr(Tr(H({representation:gi,references:we(Gt,gi)})));function Ui(e){return Hi(e)}var Wi=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function Gi(e){return e[Wi]?.()}var Ki=3.5,qi=4800;function Ji(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function Yi(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function Xi(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:qi;return t}function Zi(e){return Math.ceil(e.length/Ki)}function Qi(e){return Math.ceil(Xi(e)/Ki)}function $i(e){let t=0;if(e.role===`system`)return Zi(ai(e))+na(e.toolsAdded)+na(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return Qi(e.content);for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+Yi(n.arguments).length;return Math.ceil(t/Ki)}function ea(e){let t=-1/0,n;for(let r=0;r<e.length;r++){let i=e[r];if(i.role===`assistant`){let e=i;e.timestamp>=t&&e.stopReason!==`aborted`&&e.stopReason!==`error`&&Ji(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function ta(e){let t=`messages`in e?e.messages:e,n=ea(t);if(n){let e=Ji(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=$i(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=$i(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function na(e){return!e||e.length===0?0:Zi(Yi(e))}var ra=0xffffffffffff,ia=(1n<<41n)-1n,aa=-1,Y;function oa(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>ra)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${ra}`);let n=e===void 0?Math.max(t,aa):e;e===void 0&&(aa=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),Y===void 0)Y=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(Y===ia)throw RangeError(`UUIDv7 generator sequence exhausted`);Y++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(Y>>37n&15n),r[7]=Number(Y>>29n&255n),r[8]=128|Number(Y>>23n&63n),r[9]=Number(Y>>15n&255n),r[10]=Number(Y>>7n&255n),r[11]=Number((Y&127n)<<1n)|r[11]&1;let a=Array.from(r,e=>e.toString(16).padStart(2,`0`));return`${a.slice(0,4).join(``)}-${a.slice(4,6).join(``)}-${a.slice(6,8).join(``)}-${a.slice(8,10).join(``)}-${a.slice(10).join(``)}`}function sa(e){return zt(e,{onFailure:re,onSuccess:()=>m})}function ca(e,t){return h(e,{onFailure:e=>w(t).pipe(g(re(e))),onSuccess:()=>t})}function la(e,t){let n={_tag:`open`},r=r=>ca(e,t).pipe(w,I(e=>j(()=>{r.result=e,n={_tag:`closed`}}).pipe(g(r.settled.open),g(sa(e)))),ie);return S(()=>{if(n._tag===`closed`)return m;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(g(S(()=>{let t=e.result;return t===void 0?de(Error(`Agent close settlement was not recorded`)):sa(t)})))}let e={_tag:`running`,settled:vr(!1)};return n=e,r(e)})}function ua(e,t,n,r){let i=dr(e,t);if(n.state===`idle`)return{facts:{queue:{state:`idle`},cancellationRequested:!1,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};if(n.state===`queued`)return{facts:{queue:{state:`queued`,commandId:n.jobId,runningWork:r},cancellationRequested:n.cancellationRequested,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};let a=Dr(e,t,n.jobId),o=a?.event.type===`auto_retry_start`?{attempt:a.event.attempt,maxAttempts:a.event.maxAttempts,delayMs:a.event.delayMs,errorMessage:a.event.errorMessage,scheduledAt:a.timestamp}:null;return{facts:{queue:{state:`running`,commandId:n.jobId},cancellationRequested:n.cancellationRequested,retry:o,activeTool:Mn(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:ei(e,t)},progress:Se(e,t,n.jobId),toolOutput:Ut(e,t,n.jobId)}}function da(e,t){let n=_n(e,{sessionId:t}),r=nn(n);return r.length===0?null:ta(r).tokens}function fa(e,t){return D(function*(){let n=yield*x(L({try:()=>({tokens:da(e.store,t),preference:Tn(e.store,t)}),catch:e=>e}));if(n._tag===`Failure`||n.success.tokens===null)return;let{tokens:r,preference:i}=n.success,a=e.model.describe;if(a===void 0)return Object.freeze({tokens:r,window:null});let s=yield*a({sessionId:t,preference:i}).pipe(o(({contextWindow:e})=>e),ae(e=>j(()=>(fn(`session-context.describe`,e),null))));return Object.freeze({tokens:r,window:s})})}function pa(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(g(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(g(e.extensions.call({scope:`agent`},t,n,r)))})}function ma(e,t,n){return t.readQueueHead(n).pipe(I(r=>(r.state===`queued`?t.runningWork(r.jobId):y(null)).pipe(o(t=>ua(e.store,n,r,t)))))}function ha(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function ga(e,t,n,r){return ma(e,t,n).pipe(I(i=>Ee(e.store,n,i,r,()=>t.extensions.project(n))),I(t=>fa(e,n).pipe(o(e=>ha(t,e)))))}function _a(e,t,n){return e.assertOpen.pipe(g(L({try:()=>n(V(t)),catch:e=>e instanceof U?e:new U(`store`,`rejected`,`Session owner operation failed`)})))}function va(e,t){return L({try:()=>{let n=Bt(t);if(n._tag===`Failure`)throw new U(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:V(e),command:n.success})},catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Session command is invalid`)})}function ya(e,t){return L({try:()=>Object.freeze({sessionId:V(e),options:it(t)}),catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Subscribe options are invalid`)})}function ba(e,t,n,r=!1){return t.assertOpen.pipe(g(ga(e,t,n,{includeSandboxFailures:r})),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function xa(e){return[[e],k({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function Sa(e,t,n,r,i,a,s=!1){return wn({after:i,delivery:a,awaitSignal:!1},i=>(i.awaitSignal?n.awaitSignal.pipe(I(e=>n.pollSignal.pipe(o(t=>t===void 0?e:sr(e,t))))):n.pollSignal).pipe(I(n=>n===`closed`?y([[],E()]):n===`reset`?ba(e,t,r,s).pipe(o(xa)):t.assertOpen.pipe(g(ma(e,t,r)),I(a=>n===`progress`&&i.delivery===`live`?y([[...a.progress===null?[]:[{kind:`progress`,progress:a.progress,activity:a.facts}],{kind:`tool_output`,toolOutput:a.toolOutput,activity:a.facts}],k({...i,awaitSignal:!0})]):Mt(e.store,r,i.after,i.delivery,a,()=>t.extensions.project(r),s).pipe(I(n=>{if(n.kind===`reset`)return ba(e,t,r,s).pipe(o(xa));let a={after:n.frames.flatMap(e=>e.kind===`progress`||e.kind===`tool_output`?[]:[e.cursor]).at(-1)??i.after,delivery:n.hasMore?i.delivery:`live`,awaitSignal:!n.hasMore};return(n.frames.some(e=>e.kind===`update`)?fa(e,r):y(void 0)).pipe(o(e=>[e===void 0?n.frames:n.frames.map(t=>t.kind===`update`?Object.freeze({...t,context:e}):t),k(a)]))})))))))}function Ca(e,t,n,r,i){return On(t.assertOpen.pipe(g(ya(r,i)),I(r=>me(n.register(r.sessionId),e=>j(e.close)).pipe(o(n=>Sa(e,t,n,r.sessionId,r.options.after,`replay`,r.options.includeSandboxFailures===!0))))))}function wa(e,t){return L({try:()=>Object.freeze({sessionId:V(e),options:Ke(t)}),catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Watch options are invalid`)})}function Ta(e,t,n,r,a){return t.assertOpen.pipe(g(wa(r,a)),I(r=>F(a=>D(function*(){let s=yield*n.register(r.sessionId);return yield*a(t.assertOpen.pipe(g(ga(e,t,r.sessionId,r.options)),o(n=>Object.freeze({snapshot:n,changes:Sa(e,t,s,r.sessionId,n.cursor??void 0,`live`,r.options.includeSandboxFailures===!0).pipe(Kn(j(s.close))),close:j(s.close)})))).pipe(i(()=>j(s.close)))}))))}function Ea(e,t,n,r,i,a){let o={sessionId:t,command:n,when:`now`,origin:{kind:`user`}};return r!==void 0&&(o={...o,meta:r}),i!==void 0&&(o={...o,mail:i}),a!==void 0&&(o={...o,reply:a}),e.assertOpen.pipe(g(e.door.admit(o)),I(e=>e.status===`accepted`?y({status:`accepted`,commandId:e.commandId}):C(new U(`runtime`,`unavailable`,`Session command was not admitted`))))}function Da(e,t,n,r,i){return t.assertOpen.pipe(g(_a(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&br(e.store,t,r.commandId,Ir(e.store,e.meta.identityPath,i))})),g(hr(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),I(e=>e===void 0?y({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(M({status:`accepted`,commandId:e.accepted.commandId}))))}function Oa(e,t,n,r){return t.assertOpen.pipe(g(t.commit(nr(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),I(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function ka(e,t,n,r){return t.assertOpen.pipe(g(Nn(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),M(void 0))}function Aa(e,t,n,r){return t.assertOpen.pipe(g(Rn(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function ja(e,t,n,r,i){return t.assertOpen.pipe(g(va(n,i)),I(t=>Ma(e,r).pipe(o(e=>({...t,checked:e})))),I(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Ea(t,n,r,i);case`abort`:return Oa(e,t,n,i).pipe(M(void 0));case`cancel`:return Da(e,t,n,r,i);case`branch`:return ka(e,t,n,r);case`fork`:return Aa(e,t,n,r);case`operator`:return t.assertOpen.pipe(g(Jn(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),M(void 0));case`title`:return t.commit(_a(t,n,t=>{kn(e.store,t,r.title)})).pipe(M(void 0))}}))}function Ma(e,t){return L({try:()=>t===void 0?void 0:Qr(e.meta,t),catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Host metadata is invalid`)})}function Na(e,t){let n=Hn(e.store),r=(r,i)=>{function a(n){return ja(e,t,r,i,n)}return Object.freeze({command:a,withdraw:e=>t.assertOpen.pipe(g(t.door.withdraw(r,e))),abort:a({type:`abort`}),send:(e,t)=>j(()=>t?.requestId??Yr()).pipe(I(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return a(t?.images===void 0?r:{...r,images:t.images}).pipe(p(e=>e.requestId===n?e:new U(e.boundary,e.cause,e.message,n)))})),cancel:e=>a({type:`cancel`,...e}),latestPending:_a(t,r,t=>We(e.store,t,e.meta?.identityPath===void 0||i===void 0?void 0:Ir(e.store,e.meta.identityPath,i))),modelPreference:Object.freeze({read:_a(t,r,t=>Tn(e.store,t)),set:n=>L({try:()=>$t(n),catch:()=>new U(`contract`,`invalid`,`Model preference is invalid`)}).pipe(I(n=>t.commit(_a(t,r,t=>(Br(e.store,t,n),t))).pipe(O(t=>j(()=>{G(e.store,t)})),_)))}),extension:e=>Object.freeze({call:(n,i)=>t.assertOpen.pipe(g(t.extensions.call({scope:`session`,sessionId:r},e,n,i)))}),read:n=>t.assertOpen.pipe(g(ga(e,t,r,n))),subscribe:i=>Ca(e,t,n,r,i),watch:i=>Ta(e,t,n,r,i)})},i=Object.freeze({createSession:n=>t.assertOpen.pipe(g(or(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(g(Vn(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(g(Ur(e.store,n))),extensions:pa(t),session:e=>r(e,void 0),close:t.beginClose.pipe(g(n.close))});return Object.freeze({...i,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>_a(t,n,t=>e.store.transactionSync(()=>Hr(e.store,t,r))),read:n=>_a(t,n,t=>$r(e.store,t))}),withMeta:e=>Object.freeze({...i,session:t=>r(t,e)})})}function Pa(e,t,n,r){return Ea(e,t.to.sessionId,{requestId:t.key,delivery:r===void 0?`followUp`:`steer`,type:`prompt`,text:t.content},n,t,r)}var Fa=H({fork:ut([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:vt.pipe(W(Pt(0)),W(Ye(2**53-1)))});function Ia(e,t){let n=Fn(e.schema)(t);if(n._tag===`Failure`)throw new di({reason:`encode`,message:`Session document does not match its schema`});let r=q(yn)(n.success);if(r._tag===`Failure`)throw new di({reason:`encode`,message:`Session document must encode finite JSON`});let i=JSON.stringify(r.success);if(new TextEncoder().encode(i).byteLength>e.maxBytes)throw new di({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function La(e){return{...kr(Fa)(e),schema:Ui(hn(e.schema)),initial:Ia(e,e.initial)}}var Ra=64,za=ut([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),Ba=B(za).pipe(W(z(10))),Va=H({protocol:Zn(`shiitake.extension/v0`),id:fr,version:xn,requests:Ba}),Ha=B(H({id:fr,capabilities:Ba,grantKey:R(fr)})).pipe(W(z(Ra))),Ua=Gt.pipe(W(et(/^[a-z][A-Za-z0-9_]{0,63}$/u))),Wa=q(Va,{onExcessProperty:`error`}),Ga=q(Ha,{onExcessProperty:`error`}),Ka=q(Ua);function X(e){return new U(`extensions`,`invalid`,e)}function qa(e){return new Set(e).size!==e.length}function Ja(e){return JSON.stringify(e,(e,t)=>ce(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function Ya(e){return P({try:async()=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,`0`)).join(``)},catch:()=>new U(`extensions`,`rejected`,`Extension digest failed`)})}function Xa(e,t){let{manifest:n,contract:r,state:i,config:a,catalog:o}=e,s={manifest:{protocol:n.protocol,id:n.id,version:n.version,requests:[...n.requests].sort()},commands:Object.fromEntries(Object.entries(r.commands).map(([e,t])=>[e,{scope:t.scope,input:Ui(hn(t.input)),output:Ui(hn(t.output))}])),projection:r.projection===null?null:Ui(hn(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,Ui(hn(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,La(t)]))};return o===void 0?c:{...c,catalog:o}}function Za(e){if(Wa(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(qa(t.requests))throw X(`Extension capability requests are invalid`);if(e.contract.id!==t.id)throw X(`Extension contract identity does not match its manifest`);if(!Number.isSafeInteger(e.state.version)||e.state.version<1)throw X(`Extension state version is invalid`);for(let t of Object.keys(e.state.collections))if(t===`update`||t===`read`||t===`observe`||Ka(t)._tag===`Failure`)throw X(`Extension collection name is invalid`);if(e.catalog!==void 0&&!t.requests.includes(`commands`))throw X(`An extension catalog requires the commands capability`);return t}function Qa(e){return D(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*L({try:()=>{if(t.length>Ra)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=Gi(e);if(t===void 0)throw X(`Extension roster entry was not defined`);let n=t.documents??{};for(let[e,t]of Object.entries(n)){if(Ka(e)._tag===`Failure`)throw X(`Session document name is invalid`);La(t)}let r=Za(t);if(Object.keys(n).length>0&&!r.requests.includes(`state`))throw X(`Session documents require the state capability`);return{definition:t,documents:n,manifest:r}});if(qa(e.map(({manifest:e})=>e.id)))throw new U(`extensions`,`conflict`,`Extension identities conflict`);let r=Ga(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(qa(r.success.map(({id:e})=>e)))throw X(`Extension grant identities are invalid`);let i=new Map;for(let t of r.success){let n=e.find(({manifest:e})=>e.id===t.id);if(n===void 0||qa(t.capabilities)||t.capabilities.some(e=>!n.manifest.requests.includes(e)))throw X(`Extension grant is invalid`);i.set(t.id,t.capabilities)}if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`compaction_handoff`)).length>1)throw new U(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new U(`extensions`,`conflict`,`Files slot is already owned`);return e.map(e=>({...e,grants:i.get(e.manifest.id)??[]})).sort((e,t)=>e.manifest.id<t.manifest.id?-1:+(e.manifest.id>t.manifest.id))},catch:e=>e instanceof U?e:X(`Extension roster is invalid`)});return yield*he(r,e=>D(function*(){let t=`sha256:${yield*Ya(yield*L({try:()=>Ja(Xa(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*Ya(Ja([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:kr(Or)(t),fingerprint:kr(mn)(r)})}))})}function $a(e){return Ya(Ja({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}function eo(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function to(e){return eo({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function no(e){return new U(`model`,`rejected`,e)}function ro(e,t){let n={input:e.input+t.input,output:e.output+t.output,cacheRead:e.cacheRead+t.cacheRead,cacheWrite:e.cacheWrite+t.cacheWrite,totalTokens:e.totalTokens+t.totalTokens,cost:{input:e.cost.input+t.cost.input,output:e.cost.output+t.cost.output,cacheRead:e.cost.cacheRead+t.cost.cacheRead,cacheWrite:e.cost.cacheWrite+t.cost.cacheWrite,total:e.cost.total+t.cost.total}};return(e.cacheWrite1h!==void 0||t.cacheWrite1h!==void 0)&&(n.cacheWrite1h=(e.cacheWrite1h??0)+(t.cacheWrite1h??0)),(e.reasoning!==void 0||t.reasoning!==void 0)&&(n.reasoning=(e.reasoning??0)+(t.reasoning??0)),n}function io(e){let t;for(let n of e)n.kind===`compaction`&&(t=n);let n=t,r=n===void 0?0:Math.max(0,e.findIndex(({id:e})=>e===n.head)),i=e.flatMap((e,t)=>e.kind===`message`&&t>=r?[e.message]:[]);return n===void 0?i:[n.model,...i]}function ao(e,t,n){let r=yt(),i=t[n];if(i?.kind===`compaction`&&i.details!==void 0){for(let e of i.details.readFiles)r.read.add(e);for(let e of i.details.modifiedFiles)r.edited.add(e)}for(let t of e)tr(t,r);return r}function oo(e,t,n,r){for(let i=t;i<n;i+=1){let t=e[i];if(t?.kind===`message`){if(t.message.role===`assistant`)return!1;if(t.message.role===`toolResult`&&r.has(t.message.toolCallId))return!0}}return!1}function so(e,t,n){let r=[],i=new Set;for(let a=t;a<n;a+=1){let t=e[a];if(t?.kind!==`message`)continue;let o=t.message;o.role===`assistant`?(r.push(a),i=new Set(o.content.flatMap(e=>e.type===`toolCall`?[e.id]:[]))):o.role===`user`&&!oo(e,a+1,n,i)&&r.push(a)}return r}function co(e,t,n,r){let i=so(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=$i(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function lo(e,t,n){let r=e[n],i=r?.kind===`message`&&r.message.role===`user`,a=-1;if(!i)for(let r=n;r>=t;--r){let t=e[r];if(t?.kind===`message`&&t.message.role===`user`){a=r;break}}return{isSplitTurn:!i&&a>=0,turnStartIndex:a}}function uo(e,t,n,r){let i=co(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...lo(e,t,i)}}function fo(e,t){if(e.at(-1)?.kind===`compaction`)return;let n,r=-1,i=0;for(let t=e.length-1;t>=0;--t){let a=e[t];if(a?.kind===`compaction`){n=Ie(a.model),r=t;let o=e.findIndex(e=>e.id===a.head);i=o>=0?o:t+1;break}}let a=e.flatMap((e,t)=>e.kind===`message`&&t>=i?[e]:[]),o=ta(io(e)).tokens,s=uo(a,0,a.length,t.keepRecentTokens),c=a[s.firstKeptEntryIndex];if(c?.kind!==`message`)return;let l=s.isSplitTurn?s.turnStartIndex:s.firstKeptEntryIndex,u=Object.freeze(a.slice(0,l).map(({message:e})=>e)),d=Object.freeze(s.isSplitTurn?a.slice(s.turnStartIndex,s.firstKeptEntryIndex).map(({message:e})=>e):[]);if(u.length===0&&d.length===0)return;let f=ao(u,e,r);for(let e of d)tr(e,f);let p={firstKeptEntryId:c.id,messagesToSummarize:u,turnPrefixMessages:d,isSplitTurn:s.isSplitTurn,tokensBefore:o,fileOps:f,settings:t};return n===void 0?p:{...p,previousSummary:n}}var po={enabled:!0,maxRetries:3,baseDelayMs:2e3};function mo(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??oa()};return Xn(()=>Promise.resolve((r??Re)(e,ii(t),i)).then(e=>e.result()),po,i.signal)}function ho(e){return{systemPrompt:jt,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function go(e,t,n){let r=e.previousSummary??``,i=t?Kr:Xr,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${Qn(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function _o(e){return`# Conversation\n${Qn(e.turnPrefixMessages)}\n\n# Instructions\n${De}`}async function vo(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await mo(e,ho(r),o,a),c=Ct(s,i);if(c!==void 0)throw Error(c);return s}function yo(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):vo(t,n,r,go(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function bo(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):vo(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,_o(e),`Turn prefix summarization`,r)}function xo(e,t,n){let r,i;if(e.isSplitTurn){if(n===void 0)throw Error(`Split-turn compaction did not produce a prefix summary`);r=`${t===void 0?e.previousSummary??`No prior history.`:oi(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${oi(n.content)}`,i=t===void 0?n.usage:ro(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=oi(t.content),i=t.usage}let a=Me(e.fileOps);return{summary:r+xe(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function So(e,t,n,r,i){return xo(e,await yo(e,t,Math.min(Math.floor(.8*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,r,i),e.isSplitTurn&&e.turnPrefixMessages.length>0?await bo(e,t,n,i):void 0)}function Co(e,t,n,r){return P({try:i=>So(e,t,i,r,n),catch:e=>no(e instanceof Error?e.message:String(e))})}function wo(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var To=new WeakMap;function Eo(e){return To.has(e)}function Do(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return Yn(t,j(()=>{ko(e,r)})).pipe(g(l(i,t)),o(t=>(r.fiber=t,To.set(e,r),r)))}function Oo(e){let t=e.summary;return e.summary=void 0,t}function ko(e,t){t.fiber=void 0,t.summary=void 0,To.get(e)===t&&To.delete(e)}function Ao(e){return new U(`runtime`,`rejected`,e)}var jo={handoff:`The compaction handoff failed; the conversation context is unchanged`,handoffResult:`The compaction handoff failed: it returned an invalid result; the conversation context is unchanged`,conflict:`The Session changed during compaction; the conversation context is unchanged`},Mo=class extends U{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,jo[e]),this.phase=e,this.usage=t}get diagnostic(){return jo[this.phase]}};function No(e,t){let n=Un(e,t),r=yr(e),i=[];for(let t of e){let e=pr(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:Er(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:gn(t.entry)});continue}if(t.entry.kind===`message`){n.has(t.id)&&i.push({id:t.id,kind:`message`,message:t.entry.value});continue}if(t.entry.kind===`compaction`){let e={id:t.id,kind:`compaction`,head:t.entry.head,model:t.entry.model[0],usage:t.entry.data.usage};i.push(t.entry.data.details===void 0?e:{...e,details:t.entry.data.details})}}return i}function Po(e,t,n){return L({try:()=>_n(e,{sessionId:t,workId:n}),catch:()=>Ao(`Woodstock selected lineage is unavailable`)})}function Fo(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return nn([...e,i],r).reduce((e,t)=>e+$i(t),0)}function Io(e,t,n){return S(()=>(ot(e.store,e.sessionId,n.trigger),Lo(e,t,n).pipe(se(j(()=>{Ot(e.store,e.sessionId)})))))}function Lo(e,t,n){return D(function*(){let r=fo(No(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*Co(r,e.model,e.stream,n.instructions),o=yield*Bo(e,r,a,i.id);return yield*Uo(e,t,a,n,i.id,o)})}var Ro=an([H({type:Zn(`accepted`),receipt:Fr}),H({type:Zn(`discarded_by_policy`)})]),zo=q(Ro);function Bo(e,t,n,r){return e.handoff===void 0?y(void 0):e.handoff.consume(wo(t,n,e.sessionId,r)).pipe(p(()=>new Mo(`handoff`,n.usage)),I(e=>{let t=zo(e);return t._tag===`Failure`?C(new Mo(`handoffResult`,n.usage)):y(t.success.type===`accepted`?t.success.receipt:void 0)}))}function Vo(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=Fo(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[Lt(n.summary,Date.now())],data:{reason:r.trigger,resumesRun:r.resumesRun,tokensBefore:n.tokensBefore,tokensAfter:0,usage:n.usage,contextRevision:i}},e.workId),c={sessionId:e.sessionId,resumesRun:r.resumesRun,trigger:r.trigger,tokensAfter:s,expectedLeafId:o.id,workId:e.workId,head:n.firstKeptEntryId,summary:n.summary,tokensBefore:n.tokensBefore,usage:n.usage,contextRevision:i,details:n.details};return a===void 0?c:{...c,receipt:a}}function Ho(e,t,n){let r=[...t,n];return{path:r,messages:nn(r,e.workId)}}function Uo(e,t,n,r,i,a){let s=Vo(e,t,n,r,i,a);return s===void 0?y(void 0):L({try:()=>En(e.store,s),catch:e=>e instanceof U?e.cause===`conflict`?new Mo(`conflict`):e:Ao(`Woodstock compaction append failed`)}).pipe(o(n=>Ho(e,t,n)))}function Wo(e){return e instanceof Mo?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function Go(e,t){return L({try:()=>{Lr(e.store,t)},catch:e=>e instanceof U?e:Ao(`Compaction notice could not be recorded`)})}function Ko(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return Go(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:Wo(n),usage:n instanceof Mo?n.usage:void 0})}function qo(e,t,n){return x(Io(e,t,n)).pipe(I(t=>t._tag===`Success`?y(t.success):Ko(e,n.trigger,t.failure).pipe(M(void 0))))}var Jo={trigger:`threshold`,resumesRun:!1};function Yo(e,t,n,r){return t.stopped||Eo(e.store)||!mt(n,e.model.contextWindow,e.settings)?m:r.pipe(I(n=>Xo(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function Xo(e,t,n){let r=n.at(-1),i=fo(No(n,e.workId),e.settings);return r===void 0||i===void 0?y(void 0):Do(e.store,t,t=>Zo(e,i,r.id,t))}function Zo(e,t,n,r){return S(()=>(ot(e.store,e.sessionId,`threshold`),Co(t,e.model,e.stream).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),se(j(()=>{Ot(e.store,e.sessionId)})))))}function Qo(e,t,n,r){return S(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?y(void 0):(t.slot=void 0,x(zn(a).pipe(I(()=>es(e,i)),I(t=>t===void 0?y(void 0):ts(e,t,n)))).pipe(I(n=>n._tag===`Success`&&n.success!==void 0?y(n.success):(t.stopped=!0,n._tag===`Success`?y(void 0):Ko(e,`threshold`,n.failure).pipe(M(void 0)))),se(j(()=>{ko(e.store,i)}))))})}function $o(e,t,n){return Go(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(M(void 0))}function es(e,t){let n=Oo(t);if(n===void 0)return y(void 0);let{result:r,selectionTail:i}=n;return L({try:()=>Qt(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof U?e:Ao(`Woodstock compaction head is unavailable`)}).pipe(I(t=>t===`stale`?$o(e,r,`stale`):Bo(e,n.preparation,r,i).pipe(o(e=>({result:r,selectionTail:i,receipt:e})))),se(j(()=>{ko(e.store,t)})))}function ts(e,t,n){return Po(e.store,e.sessionId,e.workId).pipe(I(r=>{let i=Vo(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?y(void 0):dt(i.tokensAfter,e.model.contextWindow,e.settings)?$o(e,t.result,`insufficient`):L({try:()=>Zr(e.store,i),catch:e=>e instanceof U?e.cause===`conflict`?new Mo(`conflict`):e:Ao(`Woodstock compaction append failed`)}).pipe(I(n=>n===`stale`?$o(e,t.result,`stale`):y(Ho(e,r,n))))}))}function ns(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return y(n);let r=ta(e.messages).tokens;return dt(r,e.model.contextWindow,e.settings)?qo(e,e.path,Jo).pipe(o(e=>e??n)):Yo(e,t,r,y(e.path)).pipe(M(n))}function rs(e,t){let n=Ft(e.message,t.contextWindow),r=St(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function is(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function as(e,t,n,r){if(!e.settings.enabled)return y(void 0);let i=dt(ta([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?Po(e.store,e.sessionId,e.workId):y(void 0)}function os(e,t,n){return(r,i)=>D(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=ta(r).tokens,s=dt(o,e.model.contextWindow,e.settings),c=yield*Qo(e,n,Jo,s);if(c!==void 0)return a(c);let l=Po(e.store,e.sessionId,e.workId);if(!s){yield*Yo(e,n,o,l);return}let u=yield*qo(e,yield*l,Jo);return u===void 0?void 0:a(u)})}function ss(e,t,n){return D(function*(){let r=t,i=t.path.some(({entry:t})=>t.kind===`compaction`&&t.workId===e.workId&&t.data.resumesRun);for(;;){let t={path:r.path,messages:r.messages,newMessageCount:0},a=yield*e.run(t.messages,os(e,t,n)),o=rs(a,e.model),s=o.retry&&!i,c=yield*Qo(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:is(c.messages)},i=!0;continue}let l=yield*as(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*qo(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:is(u.messages)},i=!0}})}function cs(e){return D(function*(){let t={scope:yield*pe,slot:void 0,stopped:!1};return yield*ss(e,e.settings.enabled?yield*ns(e,t):e,t)})}function ls(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?y(`compacted`):Io(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(T(t=>Ko(e,`manual`,t)),I(t=>t===void 0?Ko(e,`manual`,void 0).pipe(M(`nothing_to_compact`)):y(`compacted`)))}var us=vt.pipe(W(_t(0)),W(Ye(2**53-1))),ds=H({reserveTokens:R(us),keepRecentTokens:R(us),backgroundTokens:R(us)}),fs=H({enabled:R(It),reserveTokens:R(us),keepRecentTokens:R(us),backgroundTokens:R(us),modelOverrides:R(we(Gt,ds))}),ps=q(fs,{onExcessProperty:`error`});function ms(e){let t=ps(e??{});if(t._tag===`Failure`)throw new U(`contract`,`invalid`,`Compaction settings must be non-negative whole token counts`);let n=t.success;return e=>{let t=n.modelOverrides?.[`${e.provider}/${e.id}`];return{enabled:n.enabled??bn.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??bn.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??bn.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??bn.backgroundTokens}}}function hs(e){return new U(`runtime`,`rejected`,e)}var gs={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},_s=class extends U{phase;constructor(e){super(`runtime`,`rejected`,gs[e]),this.phase=e}get diagnostic(){return gs[this.phase]}};function vs(e){return e.type===`retry_attempt_started`?{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt}:e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,errorMessage:e.errorMessage}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:e.finalError}}function ys(e,t,n,r,i,a,o){let s=e.tools,c=i.modules??[],l=[...c,...a];return s===void 0?c.length>0||o.length>0?C(new _s(`missing`)):y([]):D(function*(){let i={sessionId:t,commandId:n};r!==void 0&&(i={...i,meta:r});let a={sources:s.sources,session:i,sandbox:s.sandbox,onSandboxFailure:r=>ct(e.store,{sessionId:t,commandId:n},r).pipe(te),modules:[...s.modules,...l],tools:o,access:{...s.access,sessionGrants:()=>$r(e.store,t)?.grants??{}}},c=yield*(yield*Wr(s.execution===void 0?a:{...a,execution:s.execution}).pipe(p(()=>new _s(`runtime`)))).acquire().pipe(p(()=>new _s(`lease`)));return[c.executeTool,...c.tools]})}function bs(e,t,n,r,i,a,s){return v(D(function*(){let l=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),u=l.release;u!==void 0&&(yield*fe(()=>j(u)));let d=yield*li(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),f=yield*ys(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,l,r,i),h=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),ee=yield*Vr(e.store,h,n),te=t=>Le(e.store,{sessionId:h.sessionId,workId:h.commandId,delivery:t}).pipe(o(e=>e.map(({message:e})=>e)),p(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof U?e.message:`Session control delivery failed`}))),ne=t.resume,re=ms(e.compaction)(d.model),g;return{run:yield*cs({store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:d.model,stream:d.stream,handoff:a,settings:re,path:t.path,messages:t.messages,resuming:ne!==void 0,run:(t,n)=>{let r=ne;ne=void 0;let i,a=e=>e.type===`run_end`&&e.outcome===`failed`?(i=e,m):ee(e),u={model:d.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs??3e5,retry:e.retry??Ae,retryAfterMs:d.retryAfterMs,retryable:d.retryable,systemPrompt:l.text,prepareSystemPrompt:()=>(s===void 0?y([]):s()).pipe(o(e=>l.text+e.map(({name:e,text:t})=>`\n\n[extension:${e}]\n${t}`).join(``)),p(e=>({_tag:`MuleError`,phase:`model`,message:`Extension prompt is unavailable`,cause:e}))),messages:t,resume:r,tools:f,getSteeringMessages:()=>te(`steer`),prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(p(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>ve(e.store,h,vs(t),t.turn)};return Fe.run(d.stream===void 0?u:{...u,stream:d.stream},a).pipe(c(e=>{if(i===void 0)return m;if(Ge(e))return g=(d.failureReason?.(e.value.message)??to(e.value)).slice(0,200),ee(i,g);let t=rn(e.cause);return ee(i,b(t)&&t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):eo({runId:i.run.value,provider:d.model.provider,model:d.model.id}))}),p(e=>e.phase===`model`?new U(`model`,`rejected`,e.message,void 0,e):hs(`Mule rejected the durable command run`)))}}),failureReason:g}}))}function xs(e,t,n){return v(D(function*(){let r=yield*li(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),i=t.command.entry;return yield*ls({store:e.store,sessionId:t.command.sessionId,workId:i.workId,model:r.model,stream:r.stream,handoff:n,settings:ms(e.compaction)(r.model),path:t.path,instructions:Gn(i)?i.instructions:void 0})}))}var Ss=Object.freeze({maxRecoveries:2});function Cs(e){return new U(`runtime`,`rejected`,e)}function ws(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof _s||e instanceof Mo||e instanceof qt?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function Ts(e,t){return u(`shiitake_run_failed`,gt(t)).pipe(ue({workId:e,reason:`${t.boundary}:${t.cause}`}))}function Es(e,t,n,r){return D(function*(){G(e.store,n.queue);let i=yield*L({try:()=>ir(n),catch:()=>Cs(`Agent work payload is invalid`)}),a=yield*dn(e.store,i.work);if(a.abnormalTerminal!==void 0)return{kind:a.abnormalTerminal};let s=r?.incompatibleMigrations()[0];if(s!==void 0)return yield*u(`shiitake_run_contract_changed`).pipe(ue({workId:n.jobId,terminal:`contract_changed: ${s}`})),yield*C(Cs(`contract_changed: ${s}`));let c=new Set(r?.runParticipants().map(([e])=>e)??[]);if(Gn(a.command.entry))return yield*xs(e,a,r?.compactionHandoff(c)),yield*ft(e.store,{sessionId:a.command.sessionId,commandFactId:i.work.commandFactId,workId:a.command.entry.workId,outcome:`completed`}),{kind:`completed`};let l=yield*L({try:()=>At(e.store,i.work.sessionId,i.work.commandFactId,a.command.entry.workId),catch:()=>Cs(`Accepted run origin is unavailable`)}),d={sessionId:a.command.sessionId,workId:a.command.entry.workId,origin:l===null?null:{extensionId:kr(Wn)(l.extensionId),correlation:l.correlation}},f=r===void 0?[]:yield*r.filesForRun(d,c),p=r===void 0?[]:yield*he([...c],t=>r.modulesForRun(d,new Set([t])).pipe(I(n=>L({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>Jr.grantAs(e,r))},catch:()=>Cs(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),m=r?.compactionHandoff(c),{run:h,failureReason:ee}=yield*bs(e,a,{core:f.length===0?t:yield*$a(f.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},p,f,m,r===void 0?void 0:()=>r.promptSections(d,c));switch(h.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:ee??to(h)}}}).pipe(ae(e=>Ts(n.jobId,e).pipe(M(ws(e)))))}var Ds=q(Rt,{onExcessProperty:`error`}),Os=q(tt(It)),ks=q(Ar,{onExcessProperty:`error`});function As(e){if(e.reply===void 0)return;let t=Sr(ks(e.reply),`Verified Agent reply is invalid`),n=e.mail;if(n?.replyTo.length!==0||n.from.agentId!==t.agentId||n.from.sessionId!==t.sessionId||e.command.type!==`prompt`||e.command.delivery!==`steer`)throw new U(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function js(e){let t=t=>({sessionId:V(t.sessionId),requireExistingSession:Sr(Os(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:Sr(Ce(t.command),`Session command is invalid`),origin:Sr(Ds(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:As(t),meta:t.meta===void 0?void 0:Qr(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(Qe(e.owner,r,a.requestId),t.requireExistingSession&&!wt(e.owner,r))throw new U(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&qn(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&qn(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested?o.jobId:void 0,c=rt(e.owner,r,a,t.meta,i,e.contract(),s===void 0?n=>{e.enqueue(n,t.mail)}:void 0,s,t.reply);return n.set(r,(n.get(r)??!1)||c.delivery===`new`),Object.freeze({status:`accepted`,commandId:c.accepted.commandId,delivery:c.delivery})},r=(t,r)=>S(()=>{let i=new Map,a=L({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof U?e:new U(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(O(()=>j(()=>{for(let[t,n]of i)n&&G(e.owner,t)})),O(()=>i.size>0?e.requestWake:m))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>L({try:()=>({sessionId:V(t),requestId:Xt({requestId:n})}),catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(I(t=>r(()=>Ln(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>L({try:()=>t(e),catch:e=>e instanceof U?e:new U(`contract`,`invalid`,`Session command is invalid`)}).pipe(I(e=>r(t=>t(e),n??`request`)))})}var Ms=`core`,Ns=256,Ps=1048576,Fs=512,Is=64,Ls=new TextEncoder,Rs=q(B(H({name:Gt.pipe(W(et(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:Gt.pipe(W(Yt(1)),W(ln(e=>Ls.encode(e).byteLength<=8192)))})).pipe(W(z(16)))),zs=class extends Error{};function Bs(e){return e.length<=Fs?e:`${e.slice(0,511)}…`}var Vs=ur(gr(yn));function Hs(e){return e instanceof ui?e.reason:`${e._tag}: ${e.message}`}function Us(e){return e instanceof ui||e instanceof di||e instanceof hi||e instanceof fi}function Ws(e,t){let r=rn(t);if(b(r)){let t=r.value;return t instanceof ui?Bs(t.reason):Bs(Us(t)?`${e}: ${Hs(t)}`:`${e} failed`)}let i=n($e(t));return b(i)?i.value instanceof Error?Bs(i.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${i.value.message}`):Bs(`${e} defect`):Bs(`${e} was interrupted`)}function Gs(e){let t=rn(e);return f(t)||t.value instanceof ui}function Z(e,t){return new di({reason:e,message:t})}function Ks(e,t){return e.length>=1&&e.length<=Ns?y(e):C(Z(`bound`,`${t} must be 1..256 characters`))}function qs(e){let t=Bs(e.message);if(e instanceof fi)switch(e.reason){case`invalid`:return new U(`contract`,`invalid`,t);case`conflict`:return new U(`store`,`conflict`,t);case`not_found`:return new U(`store`,`rejected`,t);case`rejected`:return new U(`extensions`,`rejected`,t)}if(e instanceof hi)switch(e.reason){case`invalid`:return new U(`contract`,`invalid`,t);case`conflict`:return new U(`contract`,`conflict`,t);case`closed`:return new U(`runtime`,`closed`,t)}return e.reason===`bound`?new U(`contract`,`invalid`,t):new U(`store`,`unavailable`,t)}function Js(e){let{owner:t}=e,n=new WeakMap,r=new Map,a=new Set,c,l=new Set,p=new Set,h,ie=e=>Object.freeze({extensionId:e}),_=e=>I(mi,t=>t.extensionId===e?m:de(Error(`Extension read used another extension's context`))),v=e=>I(pi,t=>{let r=n.get(t);return r?.extensionId===e?y(r):de(Error(`Extension write used outside its own core transaction`))}),x=e=>L({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),T=(e,t)=>e.admitted.grants.has(t)?m:C(Z(`unavailable`,`Extension is not granted ${t}`));function se(e,n,r){let i=e.admitted.id,a=Pr(gr(r.schema)),s=Sn(r.schema),l=e=>{let t=a(e);return t._tag===`Failure`?C(Z(`decode`,`Stored ${n} record is invalid`)):y(t.success)};return Object.freeze({peek:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);let o=Ue(t,i,n,r);if(o===void 0)return E();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return k(s.success)},peekPage:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);if(!Number.isSafeInteger(r.limit)||r.limit<1||r.limit>Is)throw Z(`bound`,`Page limit must be 1..64`);return at(t,i,n,r).map(e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success})},get:r=>_(i).pipe(g(T(e,`state`)),g(x(()=>Ue(t,i,n,r))),I(e=>e===void 0?y(E()):l(e).pipe(o(k)))),page:r=>_(i).pipe(g(T(e,`state`)),g(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=Is?m:C(Z(`bound`,`Page limit must be 1..64`))),g(x(()=>at(t,i,n,r))),I(e=>he(e,l))),put:a=>v(i).pipe(g(T(e,`state`)),g(S(()=>{let e=s(a);if(e._tag===`Failure`)return C(Z(`encode`,`The ${n} record does not match its schema`));let o=JSON.stringify(e.success);if(Ls.encode(o).byteLength>Ps)return C(Z(`bound`,`The ${n} record exceeds 1 MiB`));let c=r.index?.(a)??null;return oe([Ks(r.key(a),`A record key`),c===null?y(null):Ks(c,`A record index`)]).pipe(I(([e,r])=>x(()=>{un(t,i,n,e,r,o)})))}))),remove:r=>v(i).pipe(g(T(e,`state`)),g(x(()=>{ri(t,i,n,r)})))})}function ce(e,n,r){let i=e.admitted.id,a=Pr(gr(r.schema)),o=Sn(r.schema),s=()=>{if(!l.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>Ns)throw Z(`bound`,`A record key must be 1..256 characters`);return e},u=e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success};return Object.freeze({get:e=>{s();let r=Ue(t,i,n,c(e));return r===void 0?E():k(u(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>Is)throw Z(`bound`,`Page limit must be 1..64`);return at(t,i,n,e).map(u)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${n} record does not match its schema`);let l=JSON.stringify(a.success);if(Ls.encode(l).byteLength>Ps)throw Z(`bound`,`The ${n} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),un(t,i,n,c(r.key(e)),u,l)},remove:e=>{s(),ri(t,i,n,c(e))}})}function le(e){let n=e.admitted.id;return Object.freeze({set:(r,i)=>v(n).pipe(O(()=>T(e,`timers`)),O(()=>Ks(r,`A timer key`)),O(()=>Number.isSafeInteger(i)&&i>=0?m:C(Z(`bound`,`A timer instant is invalid`))),I(e=>x(()=>{An(t,n,r,i),e.timersChanged=!0}))),cancel:r=>v(n).pipe(O(()=>T(e,`timers`)),I(e=>x(()=>{Te(t,n,r),e.timersChanged=!0}))),read:r=>_(n).pipe(g(T(e,`timers`)),g(x(()=>on(t,n,r))),o(ne))})}function fe(n){let r=n.admitted.id,i=(i,a)=>v(r).pipe(O(()=>T(n,`attention`)),I(n=>L({try:()=>{V(i),a(),Bn(t,i,e.readQueueHead(i)),n.observed.add(i)},catch:e=>e instanceof di&&e.reason===`session_absent`?e:e instanceof U&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,n)=>{let a=q(Et,{onExcessProperty:`error`})(n);return a._tag===`Failure`?C(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!wt(t,e))throw Z(`session_absent`,`Attention Session is absent`);_r(t,e,r,a.success)})},clear:(e,n)=>Ks(n,`An attention id`).pipe(g(i(e,()=>{zr(t,e,r,n)})))}}function pe(e){let t=e.admitted.id;return n=>v(t).pipe(I(r=>e.admitted.grants.has(`send`)?L({try:()=>{let{requireExistingSession:e=!1}=n,i=r.admit({sessionId:n.sessionId,requireExistingSession:e,command:{type:`prompt`,requestId:n.prompt.requestId,delivery:n.prompt.delivery,text:n.prompt.text},when:n.when,origin:{kind:`extension`,extensionId:t,correlation:n.correlation??null}});return i.status===`accepted`?{_tag:`Accepted`,commandId:i.commandId,delivery:i.delivery}:{_tag:`NotReady`}},catch:e=>new hi({reason:e instanceof U?e.cause===`conflict`?`conflict`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof U?e.message:`Session command is invalid`})}):C(new hi({reason:`closed`,message:`Extension is not granted send`}))))}function me(r,i,a){return S(()=>{let s,c,l=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let t=ie(r.admitted.id);c={extensionId:r.admitted.id,admit:e,observed:new Set,timersChanged:!1},n.set(t,c),p.add(r.admitted.id);let a=h;h=c;try{s=A(i.pipe(d(pi,t),d(mi,t)))}finally{h=a,n.delete(t),p.delete(r.admitted.id)}if(Wt(s))throw l;return s.value},a).pipe(o(()=>{if(s===void 0)throw Error(`Extension transaction returned no exit`);return s}),ae(e=>s!==void 0&&Wt(s)?y(s):C(e)),O(n=>Ge(n)&&c!==void 0?D(function*(){for(let e of c?.observed??[])G(t,e);a===`request`&&c?.timersChanged===!0&&(yield*e.requestWake)}):m))})}function P(n){let r=``;for(let i=0;i<jn;i+=Is){let i=Dn(t,n,r);for(let n of i)Bn(t,n,e.readQueueHead(n)),queueMicrotask(()=>{G(t,n)});let a=i.at(-1);if(i.length<Is||a===void 0)return;r=a}}function F(e,n,r,i){let a=Date.now();e.status=`stopped`,e.reason=n,e.stoppedAt=a;let o=L({try:()=>{let r=()=>{_e(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:a,revision:e.admitted.revision}),P(e.admitted.id)};i===`own-transaction`?t.transactionSync(r):r()},catch:t=>new U(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)});return D(function*(){let t=yield*w(o);return yield*u(`shiitake_extension_stopped`).pipe(ue({extensionId:e.admitted.id,reason:n,cause:r===void 0?null:gt(r),durable:Ge(t)})),yield*t})}function R(e,n,r){e.status=`stopped`,e.reason=n,e.stoppedAt=Date.now();let i=()=>{_e(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:e.stoppedAt,revision:e.admitted.revision}),P(e.admitted.id)};try{r===`own-transaction`?t.transactionSync(i):i()}catch(t){throw new U(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)}}function ve(e,n,r){let i=t=>{if(h?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return V(t),h},a=a=>{i(a);let o=mr(t,a,e.admitted.id,n)??Ia(r,r.initial);if(Ls.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=q(gr(r.schema))(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored session document does not match its schema`);return s.success};return Object.freeze({read:a,update:(o,s)=>{let c=i(o),l=s(a(o));cr(t,o,e.admitted.id,n,Ia(r,l)),c.observed.add(o)}})}function be(e){let n=new Set;return Object.freeze({collection:(t,n)=>se(e,t,n),updateCollection:(t,n)=>ce(e,t,n),document:(t,n)=>ve(e,t,n),update:r=>{let i=e.admitted.id;if(e.status!==`running`||!e.admitted.grants.has(`state`)||l.has(i)||p.has(i)||c===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let e=t.transactionSync(()=>{l.add(i);try{return wr(r,void 0)}finally{l.delete(i)}});for(let e of n)G(t,e);return e}catch(t){if(!(t instanceof Mr))throw t;let n=t.message;throw R(e,n,`own-transaction`),new ui({reason:n})}finally{n.clear()}},observeUpdate:t=>{if(!l.has(e.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);n.add(V(t))},context:Object.freeze({manifest:e.admitted.manifest,revision:e.admitted.revision,grants:Object.freeze([...e.admitted.grants]),send:pe(e),timers:le(e),attention:fe(e),sessionPosition:n=>_(e.admitted.id).pipe(g(T(e,`state`)),g(x(()=>{let e=V(n);if(!wt(t,e))throw Z(`unavailable`,`Session timeline is unavailable`);return jr(t,{sessionId:e})?.newestSequence??0}))),hasPendingSteer:n=>_(e.admitted.id).pipe(g(T(e,`run_tools`)),g(x(()=>sn(t,V(n.sessionId),n.workId)))),hasSuccessfulToolResult:(n,r)=>_(e.admitted.id).pipe(g(T(e,`run_tools`)),g(x(()=>ge(t,V(n.sessionId),n.workId,r)))),observe:t=>v(e.admitted.id).pipe(o(e=>{e.observed.add(t)})),transact:t=>(e.status===`running`?me(e,t,`request`).pipe(te):C(new ui({reason:e.reason??`Extension is stopped`}))).pipe(I(t=>{if(Ge(t))return y(t.value);if(!Gs(t.cause))return re(t.cause);let n=Ws(`transact`,t.cause);return F(e,n,t.cause,`own-transaction`).pipe(I(()=>C(new ui({reason:n}))))}))})})}function xe(e){let{id:n,definition:r,revision:i}=e.admitted,a=r.state.version,o=Cr(t,n);if(o!==void 0&&o.version>a)throw new U(`extensions`,`conflict`,`Stored ${n} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=qe(t,n).map(e=>({collection:e.collection,key:e.key,value:Vs(e.valueJson)}));for(let t=o.version;t<a;t+=1){let i=r.state.migrations[t];if(i===void 0)throw new U(`extensions`,`state_reset_required`,`State reset required for ${n}: stored version ${String(o.version)}, declared version ${String(a)}. An operator must authorize the reset; stored records have not been changed.`);try{e=e.flatMap(e=>i(e))}catch(e){throw new zs(`Failed ${n} state migration from ${String(t)}`,{cause:e})}}st(t,n);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new zs(`Migrated ${n} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new zs(`Migrated ${n} ${i.collection} record is invalid`);un(t,n,i.collection,i.key,a.success,JSON.stringify(i.value))}}Dt(t,n,a,i)}function Se(e,t,n=!1){let r=be(e);return D(function*(){let i=yield*pt(t);e.scope=i;let a=yield*S(()=>e.admitted.definition.activate(r)).pipe(d(ye,i),w);if(Ge(a)){e.hooks=a.value;return}if(yield*lt(i,a),n)return yield*C(new U(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${cn(a.cause)}`));yield*F(e,Ws(`activation`,a.cause),a.cause,`own-transaction`)})}let z=e=>[...r.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function Ce(e){return Object.freeze({id:e.admitted.id,version:e.admitted.manifest.version,revision:e.admitted.revision,status:e.status,reason:e.reason,stoppedAt:e.stoppedAt})}function we(e){return e.status===`running`&&e.hooks!==void 0&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))}function Ee(e,t,n){return w(n.pipe(d(mi,ie(e.admitted.id)))).pipe(I(n=>Ge(n)?y(k(n.value)):F(e,Ws(t,n.cause),n.cause,`own-transaction`).pipe(M(E()))))}let B=(e,t,n)=>Wt(n)?F(e,Ws(t,n.cause),n.cause,`own-transaction`):m;function De(e){return L({try:()=>{t.transactionSync(()=>{xe(e);for(let[n,r]of Object.entries(e.admitted.documents))Be(t,{extensionId:e.admitted.id,name:n,initialJson:Ia(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(O(()=>j(()=>{delete e.stateResetRequired})),M(!0),ae(t=>t instanceof U?t.cause===`state_reset_required`?(e.stateResetRequired=t,F(e,Bs(t.message),xr(t),`own-transaction`).pipe(M(!1))):C(t):(t instanceof zs&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&a.add(e.admitted.id),F(e,Bs(t instanceof Error?`migration: ${t.message}`:`migration failed`),Ve(t),`own-transaction`).pipe(M(!1)))))}return D(function*(){let n=yield*xt();function l(e,r){return D(function*(){let i=nt(t,e.id),a=i?.status===`stopped`&&i.revision===e.revision,o={admitted:e,hooks:void 0,status:a?`stopped`:`running`,reason:a?i.reason:null,stoppedAt:a?i.stoppedAt:null};return yield*L({try:()=>{e.grants.has(`settled`)&&t.transactionSync(()=>{Ht(t,e.id)===void 0&&Ze(t,e.id,Ht(t,`core`)??0)})},catch:()=>new U(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*De(o))||a?r?yield*C(new U(`extensions`,`rejected`,`Extension ${e.id} cannot start: ${o.reason??`stopped`}`)):o:(yield*L({try:()=>{t.transactionSync(()=>{_e(t,e.id,{status:`running`,reason:null,stoppedAt:null,revision:e.revision}),P(e.id)})},catch:()=>new U(`store`,`unavailable`,`Extension status is unavailable`)}),yield*Se(o,n,r),o)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(i(()=>lt(n,Jt)));r.set(t.id,e)}yield*L({try:()=>{t.transactionSync(()=>{let n=In(t,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of n)P(e)})},catch:()=>new U(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:e=>D(function*(){let n=e.filter(e=>{let t=r.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(n.length>0)return yield*C(new U(`extensions`,`rejected`,`Extensions ${n.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,s=S(()=>he([...o.values()].reverse(),e=>w(e.scope===void 0?m:lt(e.scope,Jt)),{concurrency:1}).pipe(O(()=>j(()=>{for(let t of e)r.has(t.id)||a.delete(t.id)})),I(ti)));yield*D(function*(){for(let t of e)r.has(t.id)||o.set(t.id,yield*l(t,!0))}).pipe(i(()=>s));let c=new Set(e.map(({id:e})=>e)),u=!1;return{discard:S(()=>u?m:(u=!0,s)),apply:D(function*(){if(u)return yield*C(new U(`extensions`,`rejected`,`Roster transition already settled`));yield*L({try:()=>{t.transactionSync(()=>{for(let[e,n]of r)c.has(n.admitted.id)||kt(t,e);let n=In(t,e.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of n)P(e)})},catch:()=>new U(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of r)c.has(t.admitted.id)||(t.scope!==void 0&&(yield*lt(t.scope,Jt)),r.delete(e),a.delete(t.admitted.id));for(let[e,t]of o)r.set(e,t);u=!0})}}),runParticipants:()=>[...r.values()].filter(we).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...a],modulesForRun:(e,t)=>he(z(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?y(E()):Ee(n,`moduleForRun`,S(()=>r(e))).pipe(o(s))}).pipe(o(e=>e.flatMap(N))),filesForRun:(e,t)=>D(function*(){let n=z(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*F(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*C(new U(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*Ee(n,`filesForRun`,S(()=>r(e)));return f(i)?yield*C(new U(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...ee(i.value,()=>[])])}),promptSections:(e,t)=>D(function*(){let n=[],r=0;for(let i of z(`prompt`)){if(!t.has(i.admitted.id))continue;let a=i.hooks?.prompt;if(a===void 0)return yield*F(i,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*C(new U(`extensions`,`rejected`,`Extension prompt is unavailable`));let o=yield*w(lr(()=>a(e)).pipe(d(mi,ie(i.admitted.id))));if(Wt(o))return yield*F(i,Ws(`prompt`,o.cause),o.cause,`own-transaction`),yield*C(new U(`extensions`,`rejected`,`Extension prompt failed`));let s=Rs(o.value),c=s._tag===`Success`?s.success:[];if(r+=c.reduce((e,t)=>e+Ls.encode(t.text).byteLength,0),s._tag===`Failure`||new Set(c.map(({name:e})=>e)).size!==c.length||r>65536)return yield*F(i,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*C(new U(`extensions`,`rejected`,`Extension prompt is invalid`));n.push(...[...c].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${i.admitted.id}.${e.name}`,text:e.text})))}return n}),compactionHandoff:e=>z(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>z(`settled`).map(e=>({id:e.admitted.id,cursor:Ht(t,e.admitted.id)??0})),deliverSettled:(e,n)=>he(z(`settled`),r=>S(()=>{let i=Ht(t,r.admitted.id)??0;if(n<=i)return m;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return me(r,(o===void 0||a.length===0?m:o(a)).pipe(g(j(()=>{Ze(t,r.admitted.id,n)}))),`reconcile`).pipe(I(e=>B(r,`onSettled`,e)))}),{discard:!0}),fireDueTimers:e=>D(function*(){let n=z(`timers`).map(({admitted:e})=>e.id),i=Zt(t,n,e,Is);for(let n of i){let i=r.get(n.extensionId);if(i?.status!==`running`)continue;let a=i.hooks?.onTimer,o=yield*me(i,S(()=>on(t,n.extensionId,n.key)===n.dueAt?(Te(t,n.extensionId,n.key),a===void 0?m:a({key:n.key,dueAt:n.dueAt,firedAt:e})):m),`reconcile`);yield*B(i,`onTimer`,o)}return i.length===Is}),timerWake:e=>tn(t,z(`timers`).map(({admitted:e})=>e.id),e),project:e=>{let t={};for(let n of r.values()){let r=n.admitted.grants.has(`projection`),i=n.admitted.grants.has(`commands`)?n.admitted.definition.catalog:void 0;if(!r&&i===void 0)continue;let a=n.admitted.revision,o=n.admitted.definition.contract.projection,s=n.hooks?.project;if(n.status===`running`&&n.hooks!==void 0){let l=!r||s===void 0||o===null?k(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=wr(()=>s(e),void 0);if(b(r)){let e=Sn(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=q(yn)(e.success);if(a._tag===`Failure`)throw Error(`Extension projection is not JSON`);t=a.success;let s=n.hooks.projectCatalog;i!==void 0&&s!==void 0&&(i=kr(yn)(wr(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?k(t):(R(n,Bs(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),E())})();if(b(l)){t[n.admitted.id]=Object.freeze(i===void 0?{status:`running`,revision:a,value:l.value}:{status:`running`,revision:a,value:l.value,catalog:i});continue}}t[n.admitted.id]=Object.freeze({status:`stopped`,revision:a,reason:n.reason??`Extension did not activate`})}return Object.freeze(t)},call:(e,t,n,i)=>D(function*(){let a=r.get(t);if(a?.admitted.grants.has(`commands`)!==!0)return yield*C(new U(`extensions`,`unavailable`,`Extension is unavailable`));if(a.status!==`running`||a.hooks===void 0)return yield*C(a.stateResetRequired??new U(`extensions`,`unavailable`,`Extension ${t} is stopped: ${a.reason??`not activated`}`));let o=a.admitted.definition.contract.commands,s=Object.hasOwn(o,n)?o[n]:void 0;if(s?.scope!==e.scope)return yield*C(new U(`contract`,`invalid`,`Extension command is unknown`));let c=e.scope===`session`?yield*L({try:()=>V(e.sessionId),catch:()=>new U(`contract`,`invalid`,`Session id is invalid`)}):null,l=a.hooks.commands.get(n);if(l===void 0)return q(s.input,{onExcessProperty:`error`})(i)._tag===`Failure`?yield*C(new U(`contract`,`invalid`,`Extension command input is invalid`)):(yield*F(a,`command ${n} has no handler`,void 0,`own-transaction`),yield*C(new U(`extensions`,`unavailable`,`Extension is stopped`)));let u=l({sessionId:c,input:i});if(u._tag===`Failure`)return yield*C(new U(`contract`,`invalid`,`Extension command input is invalid`));let d=yield*me(a,u.success(),`request`);if(Ge(d))return d.value;let f=rn(d.cause);if(b(f)&&!Gs(d.cause))return yield*C(qs(f.value));let p=Ws(`command ${n}`,d.cause);return yield*F(a,p,d.cause,`own-transaction`),yield*C(new U(`extensions`,`unavailable`,`Extension ${t} is stopped: ${p}`))}),list:()=>[...r.values()].map(Ce),resume:i=>D(function*(){let a=r.get(i);return a===void 0?yield*C(new U(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*L({try:()=>{t.transactionSync(()=>{_e(t,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),P(a.admitted.id)})},catch:()=>new U(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*De(a))&&(yield*Se(a,n)),yield*e.requestWake),Ce(a))}),close:lt(n,Jt)};return Object.freeze(u)})}var Ys=64;function Q(e){return new U(`runtime`,`rejected`,e)}function Xs(e,t,n){return t===void 0?m:D(function*(){let r=yield*L({try:()=>ir(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`cancelled`?``:yield*Oe(e,r.work),a=yield*$n(e,r.work,n.outcome),o=n.outcome===`completed`||n.outcome===`cancelled`?void 0:yield*ht(e,r.work),s=o===void 0?{job:n,content:i}:{job:n,content:i,diagnostic:o};yield*t.fanOut(a===void 0?s:{...s,meta:a}).pipe(p(()=>Q(`Agent reply fan-out is unavailable`)))})}function Zs(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?m:D(function*(){let r=yield*L({try:()=>ir(t),catch:()=>Q(`Agent work payload is invalid`)});yield*ft(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function Qs(e,t,n){return D(function*(){let r=yield*L({try:()=>ir(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*bt(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(Cn({work:{...e,recovery:Ss}}))}})})}function $s(e){return e===void 0?m:e.drainOutbox().pipe(p(()=>Q(`Agent reply delivery is unavailable`)))}function ec(e,t){return D(function*(){let n=yield*L({try:()=>ir(t),catch:()=>Q(`Agent work payload is invalid`)}),i=yield*L({try:()=>ar(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return i&&(yield*r(`shiitake_settlement_session_refused`).pipe(ue({workId:t.jobId}))),i})}function tc(e,t){let n=ir(t.job),r=ar(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:At(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):Ne(e,n.work.sessionId,n.work.commandFactId,t.job.jobId);return Object.freeze({sequence:t.sequence,sessionId:n.work.sessionId,workId:t.job.jobId,outcome:t.job.outcome,terminal:r.terminal,toolCalls:r.toolCalls,origin:r.origin===null?null:Object.freeze({extensionId:kr(Wn)(r.origin.extensionId),correlation:r.origin.correlation})})}function nc(e,t,n,r){return he(r,r=>D(function*(){G(e,r.job.queue),(yield*ec(e,r.job))||(yield*Zs(e,r.job),yield*Qs(e,t,r.job),yield*Xs(e,n,r.job)),yield*L({try:()=>{Ze(e,Ms,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function rc(e){return D(function*(){if((yield*e.watchdog.tick()).status===`busy`)return yield*C(Q(`Runtime reconciliation is already active`));let t=yield*L({try:()=>Ht(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),n=e.extensions.settledConsumers(),r=Math.min(t,...n.map(({cursor:e})=>e)),i=yield*e.watchdog.readSettled(Ys,r),a=yield*w(nc(e.store,e.watchdog,e.mailRoom,i.filter(({sequence:e})=>e>t))),o=yield*L({try:()=>{let t=Ht(e.store,`core`)??0;return i.filter(({sequence:e})=>e<=t).map(t=>tc(e.store,t))},catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(o,Ht(e.store,`core`)??0);let s=yield*e.extensions.fireDueTimers(Date.now());if((i.length===Ys||s)&&(yield*e.requestWake),yield*$s(e.mailRoom),Wt(a))return yield*re(a.cause)}).pipe(p(e=>e instanceof U?e:Q(`Runtime reconciliation failed`)))}function $(e){return new U(`runtime`,`rejected`,e)}function ic(e,n,r,a){return D(function*(){if(e.hostJobs?.lane==="default")return yield*C($(`Host lane conflicts with Agent work`));let s=`open`,c,l,d=vr(!1),f=e=>j(()=>{s===`open`&&(c??=e)}),ee=S(()=>s===`open`?(s=`closing`,l=c,d.open):m).pipe(ie),ne={},_={current:void 0},v=e,b,x=!1,w=S(()=>ne.requestWake??C($(`Runtime host is unavailable`))),E={current:void 0},ce=new Set,ue=new Map,k={owner:e.store,isAlive:()=>y(!1),executor:{execute:t=>le(j(()=>{let n=t.lane===e.hostJobs?.lane?{kind:`host`,lane:t.lane,jobId:t.jobId}:{kind:`session`,sessionId:t.queue,commandId:t.jobId};ue.set(n.kind===`host`?`host`:`serial`,n),n.kind===`session`&&ce.add(t.queue),G(e.store,null)}),()=>t.lane===e.hostJobs?.lane?E.current?.execute(t)??C(new ci(`execution_failed`)):D(function*(){let r=b;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;v={...n,...r.configuration},b=void 0}return yield*Es(v,n,t,_.current)}).pipe(T(e=>u(`configuration_apply_failed`,e)),p(()=>new ci(`execution_failed`))),()=>j(()=>{t.lane!==e.hostJobs?.lane&&ce.delete(t.queue),ue.delete(t.lane===e.hostJobs?.lane?`host`:`serial`),G(e.store,null)}))},wake:{recompute:()=>w.pipe(p(()=>new ci(`wake_unavailable`)))},project:t=>{pn(e.store,t,Date.now())}},A=yield*(e.hostJobs===void 0?si(k):si({...k,concurrentLane:e.hostJobs.lane}).pipe(O(t=>j(()=>{E.current=e.hostJobs?.open(t)})))).pipe(p(()=>$(`Watchdog is unavailable`))),de=()=>({core:n,extensions:[..._.current?.runParticipants()??[]]});yield*L({try:()=>ms(e.compaction),catch:e=>e instanceof U?e:$(`Compaction settings are unavailable`)});let fe=yield*L({try:()=>Je(e.storagePressure),catch:e=>e instanceof U?e:$(`Storage budget is unavailable`)}),M=js({owner:e.store,admitNew:fe.admitNew,hostMeta:e.meta,contract:de,enqueue:(e,t)=>{let n={work:{...e,recovery:Ss}};A.transactional.enqueueAcceptedJob(Cn(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>A.transactional.readQueueHead(e),commit:e=>S(()=>ne.commit===void 0?C($(`Runtime host is unavailable`)):ne.commit(e)),requestWake:w});yield*L({try:()=>{Kt(e.store),Ht(e.store,`core`)===void 0&&e.store.transactionSync(()=>{Ze(e.store,Ms,0)})},catch:()=>new U(`store`,`unavailable`,`Extension store is unavailable`)});let N=yield*Js({owner:e.store,readQueueHead:e=>A.transactional.readQueueHead(e),door:M,admitted:r,requestWake:w});_.current=N;let pe=rc({watchdog:A,store:e.store,extensions:N,requestWake:w,mailRoom:a}).pipe(T(f)),me=D(function*(){let t=yield*A.hasPendingWork,n=Date.now(),r=yield*L({try:()=>[Ht(e.store,`core`)??0,...N.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*A.readSettled(1,Math.min(...r))).length>0,o=yield*L({try:()=>N.timerWake(n),catch:()=>$(`Extension timers are unavailable`)}),s=a===void 0?void 0:yield*a.nextWakeAt().pipe(p(()=>$(`Reply retry wake is unavailable`))),c=o.nextWakeAt===null?s??null:s===void 0?o.nextWakeAt:Math.min(o.nextWakeAt,s);return{pending:t||i||o.due||s!==void 0&&s<=n,nextWakeAt:c}}),P=yield*e.runtime.bind({reconcile:pe,pendingWork:me.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(i(()=>N.close.pipe(te))),he=S(()=>s===`open`?t(P.requestWake.pipe(ae(f)),d.await):m);return ne.requestWake=he,ne.commit=P.commit,yield*P.requestWake.pipe(i(()=>oe([P.close,N.close]).pipe(te))),Object.freeze({prepareConfiguration:e=>D(function*(){if(s!==`open`||x||b!==void 0)return yield*C($(`A configuration change is already pending, or the Agent is closing`));x=!0;let t=yield*Qa(e.extensions).pipe(I(e=>N.stage(e)),i(()=>j(()=>{x=!1}))),n=!1;return{commit:L({try:()=>{if(n||s!==`open`)throw $(`Configuration preparation is no longer available`);b={configuration:e,apply:t.apply},n=!0,x=!1},catch:e=>e instanceof U?e:$(`Configuration commit failed`)}),discard:S(()=>n?m:(n=!0,x=!1,t.discard))}}),activeSessions:j(()=>[...ce]),runningWork:t=>A.read(t).pipe(o(t=>t.status===`found`?ue.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`)??null:null),p(e=>new U(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:N,commit:P.commit,assertOpen:S(()=>s===`open`?m:C(new U(`runtime`,`closed`,`Shiitake is closed`))),beginClose:ee,door:M,storage:fe,recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>A.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(A.transactional.readQueueHead(e).state!==`idle`)throw new U(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof U?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>A.cancel({jobId:e,cancellationId:t}).pipe(I(e=>e.status===`recorded`||e.status===`replayed`?m:C($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>A.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>A.transactional.readQueueHead(e),requestWake:he,close:ee.pipe(g(h(P.close,{onFailure:e=>N.close.pipe(g(l===void 0?re(e):C(l))),onSuccess:()=>N.close.pipe(g(l===void 0?m:C(l)))})),se(j(()=>{s=`closed`})))})})}var ac=e({openRuntimeCore:()=>oc});function oc(e,t){return D(function*(){let n=yield*Qa(e.extensions),r=yield*$a([]);yield*vn(e.store);let i=yield*ic(e,r,n,t),a=Na(e,i),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:la(a.close,i.close)}),s=Object.freeze({...o,prepareConfiguration:i.prepareConfiguration,grants:a.grants,withMeta:e=>Object.freeze({...o,session:a.withMeta(e).session})});return Object.freeze({agent:s,readSettlement:(t,n)=>i.assertOpen.pipe(g(qr(e.store,t,n))),activeSessions:i.activeSessions,acceptMail:(e,t,n)=>Pa(i,e,t,n)})})}export{oa as n,oc as openRuntimeCore,ta as r,ac as t};
@@ -1 +1 @@
1
- import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-BHRx5Fxu.js";function n(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}var r=n();function i(){return r?`pi (${r.platform()} ${r.release()}; ${r.arch()})`:`pi (browser)`}var a=class extends Error{},o=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e){if(!s(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function l(e){return s(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>l(e)):!1}function u(e,t){if(!s(e))throw new a(`boolean schemas are unsupported`);for(let t of o)if(e[t]!==void 0)throw new a(`${t} schemas are unsupported`);if(t){for(let[n,r]of Object.entries(e))if(t(n,r))throw new a(`${n}: ${JSON.stringify(r)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new a(`anyOf must contain at least one schema`);for(let n of e.anyOf){if(c(n))throw new a(`object and array unions are unsupported`);u(n,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new a(`tuple schemas are unsupported`);u(e.items,t)}let n=e.type===`object`;if(e.properties!==void 0&&!n)throw new a(`properties require type object`);if(!n)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new a(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!s(e.properties))throw new a(`object properties must be a schema map`);if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(e=>typeof e!=`string`)))throw new a(`object required must be a string array`);let r=e.properties??{},i=Object.keys(r),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!i.includes(e)))throw new a(`required contains an unknown property`);for(let[e,n]of Object.entries(r))u(n,t),!d.has(e)&&!l(n)&&(r[e]={anyOf:[n,{type:`null`}]});e.required=i,e.additionalProperties=!1}function d(e,t){let n=structuredClone(e);if(!s(n)||(u(n,t),n.type!==`object`))throw new a(`root schema must have type object`);return n}function f(e,t){return t===!0?d(e.parameters):e.parameters}function p(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function m(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function h(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function g(e,t,n){let r=e.constrainedSampling;if(!(!r||r.type!==`json_schema`)){if(t)try{return d(e.parameters,n),!0}catch(t){if(!(t instanceof a))throw t;if(r.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(r.strict===`require`)throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function _(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:h(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function v(e,t){let n=new Map;for(let r of e??[]){let e=_(r,t);e&&n.set(r.name,e.inputProperty)}return n}var y=4096,b=1;function x(e,n,r){if(e.contextWindow<=0)return Math.max(b,r);let i=e.contextWindow-t(n).tokens-y;return Math.min(r,Math.max(b,i))}function S(t,n,r){let i=e(t,n),a=t.samplingParamsByThinkingLevel?.[i];return t.samplingParams||a||r?{...t.samplingParams,...a,...r}:void 0}function C(e,t,n,r){let i=S(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:x(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,onProviderStreamEvent:n?.onProviderStreamEvent,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}var w=1024,T={minimal:1024,low:2048,medium:8192,high:16384};function E(e){return e===`xhigh`||e===`max`?`high`:e}function D(e,t){return{...T,...t}[E(e)]}function O(e,t){return Math.min(e,Math.max(0,t-w))}function k(e,t,n,r){let i=D(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=O(i,a)),{maxTokens:a,thinkingBudget:i}}var A=`(image omitted: model does not support images)`,j=`(tool image omitted: model does not support images)`,M=`(image attached after the tool results)`;function N(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:P(e.content,M),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function P(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function F(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:P(e.content,A)}:e.role===`toolResult`?{...e,content:P(e.content,j)}:e)}function I(e,t,n){let r=new Map,i=F(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`system`||e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return a?e.redacted||e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:e:[];if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=[],l=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}a.push(...c),c.length=0};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){l();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):t.role===`system`?o.length>0?c.push(t):a.push(t):(t.role===`user`&&l(),a.push(t))}return l(),a}export{x as a,D as c,p as d,f,i as h,C as i,m as l,g as m,I as n,O as o,_ as p,k as r,S as s,N as t,v as u};
1
+ import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-DlPx0Rnp.js";function n(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}var r=n();function i(){return r?`pi (${r.platform()} ${r.release()}; ${r.arch()})`:`pi (browser)`}var a=class extends Error{},o=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e){if(!s(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function l(e){return s(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>l(e)):!1}function u(e,t){if(!s(e))throw new a(`boolean schemas are unsupported`);for(let t of o)if(e[t]!==void 0)throw new a(`${t} schemas are unsupported`);if(t){for(let[n,r]of Object.entries(e))if(t(n,r))throw new a(`${n}: ${JSON.stringify(r)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new a(`anyOf must contain at least one schema`);for(let n of e.anyOf){if(c(n))throw new a(`object and array unions are unsupported`);u(n,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new a(`tuple schemas are unsupported`);u(e.items,t)}let n=e.type===`object`;if(e.properties!==void 0&&!n)throw new a(`properties require type object`);if(!n)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new a(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!s(e.properties))throw new a(`object properties must be a schema map`);if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(e=>typeof e!=`string`)))throw new a(`object required must be a string array`);let r=e.properties??{},i=Object.keys(r),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!i.includes(e)))throw new a(`required contains an unknown property`);for(let[e,n]of Object.entries(r))u(n,t),!d.has(e)&&!l(n)&&(r[e]={anyOf:[n,{type:`null`}]});e.required=i,e.additionalProperties=!1}function d(e,t){let n=structuredClone(e);if(!s(n)||(u(n,t),n.type!==`object`))throw new a(`root schema must have type object`);return n}function f(e,t){return t===!0?d(e.parameters):e.parameters}function p(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function m(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function h(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function g(e,t,n){let r=e.constrainedSampling;if(!(!r||r.type!==`json_schema`)){if(t)try{return d(e.parameters,n),!0}catch(t){if(!(t instanceof a))throw t;if(r.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(r.strict===`require`)throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function _(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:h(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function v(e,t){let n=new Map;for(let r of e??[]){let e=_(r,t);e&&n.set(r.name,e.inputProperty)}return n}var y=4096,b=1;function x(e,n,r){if(e.contextWindow<=0)return Math.max(b,r);let i=e.contextWindow-t(n).tokens-y;return Math.min(r,Math.max(b,i))}function S(t,n,r){let i=e(t,n),a=t.samplingParamsByThinkingLevel?.[i];return t.samplingParams||a||r?{...t.samplingParams,...a,...r}:void 0}function C(e,t,n,r){let i=S(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:x(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,onProviderStreamEvent:n?.onProviderStreamEvent,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}var w=1024,T={minimal:1024,low:2048,medium:8192,high:16384};function E(e){return e===`xhigh`||e===`max`?`high`:e}function D(e,t){return{...T,...t}[E(e)]}function O(e,t){return Math.min(e,Math.max(0,t-w))}function k(e,t,n,r){let i=D(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=O(i,a)),{maxTokens:a,thinkingBudget:i}}var A=`(image omitted: model does not support images)`,j=`(tool image omitted: model does not support images)`,M=`(image attached after the tool results)`;function N(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:P(e.content,M),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function P(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function F(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:P(e.content,A)}:e.role===`toolResult`?{...e,content:P(e.content,j)}:e)}function I(e,t,n){let r=new Map,i=F(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`system`||e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return a?e.redacted||e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:e:[];if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=[],l=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}a.push(...c),c.length=0};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){l();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):t.role===`system`?o.length>0?c.push(t):a.push(t):(t.role===`user`&&l(),a.push(t))}return l(),a}export{x as a,D as c,p as d,f,i as h,C as i,m as l,g as m,I as n,O as o,_ as p,k as r,S as s,N as t,v as u};
package/dist/index.html CHANGED
@@ -4,11 +4,11 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1" />
6
6
  <title>Inbox</title>
7
- <script type="module" crossorigin src="/assets/index--Y1OC0IE.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-BJuRfQVe.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
9
9
  <link rel="modulepreload" crossorigin href="/assets/Effect-BY0T-p9d.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/preload-helper-DY31Aviq.js">
11
- <link rel="modulepreload" crossorigin href="/assets/extension-hook-Ce1QNicQ.js">
11
+ <link rel="modulepreload" crossorigin href="/assets/extension-hook-DCZVg8jj.js">
12
12
  <link rel="modulepreload" crossorigin href="/assets/document-DjWTbvB5.js">
13
13
  <link rel="modulepreload" crossorigin href="/assets/base-face-Dc6wvM5e.js">
14
14
  <link rel="stylesheet" crossorigin href="/assets/index-BmdZJzrt.css">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fungi.computer/grove",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "author": "Levi <levi@technomancy.dev>",
5
5
  "type": "module",
6
6
  "description": "Grove: conversations with agents that call your other Apps, for Oyster",
@@ -9,10 +9,10 @@
9
9
  "@fungi.computer/approvals": "0.0.2",
10
10
  "@fungi.computer/cairn": "0.1.0",
11
11
  "@fungi.computer/caps": "0.2.0",
12
- "@fungi.computer/knapsack": "0.2.0",
12
+ "@fungi.computer/knapsack": "0.2.1",
13
13
  "@fungi.computer/maosaico": "0.1.0",
14
- "@fungi.computer/parakeet": "0.2.0",
15
- "@fungi.computer/shiitake": "0.3.0",
14
+ "@fungi.computer/parakeet": "0.2.1",
15
+ "@fungi.computer/shiitake": "0.3.1",
16
16
  "@fungi.computer/sigils": "0.2.0",
17
17
  "@fungi.computer/sprite": "0.2.0",
18
18
  "@fungi.computer/sprite-zdog": "0.2.0",
@@ -26,13 +26,13 @@
26
26
  "react": "18.3.1",
27
27
  "react-dom": "18.3.1",
28
28
  "zod": "4.4.3",
29
- "@fungi.computer/shiitake-extensions": "0.1.0",
29
+ "@fungi.computer/shiitake-extensions": "0.1.1",
30
30
  "@fungi.computer/gills": "0.2.0"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@fungi.computer/watchdog": "0.1.0",
34
34
  "@cloudflare/workers-types": "5.20260828.1",
35
- "@fungi.computer/parakeet-testing": "0.1.1",
35
+ "@fungi.computer/parakeet-testing": "0.1.2",
36
36
  "@ladle/react": "5.1.1",
37
37
  "@tailwindcss/vite": "4.2.1",
38
38
  "@types/react": "18.3.3",
@@ -1 +0,0 @@
1
- import{a as e}from"./document-DjWTbvB5.js";import{t}from"./renderer-l9sYXW5N.js";import{a as n,i as r}from"./base-face-Dc6wvM5e.js";import{n as i}from"./index--Y1OC0IE.js";var a=r(i),o={document:e.parse(n(a)),render:t};export{o as default};
@@ -1 +0,0 @@
1
- import{a as e}from"./document-DjWTbvB5.js";import{t}from"./renderer-l9sYXW5N.js";import{a as n,i as r}from"./base-face-Dc6wvM5e.js";import{t as i}from"./index--Y1OC0IE.js";var a=r(i),o={document:e.parse(n(a)),render:t};export{o as default};
@@ -1 +0,0 @@
1
- import{En as e}from"./Effect-BY0T-p9d.js";import{Br as t,Fn as n,In as r,Ln as i,Qa as a,bn as o,c as s,fi as c,i as l,mi as u,ni as d,oi as f}from"./extension-hook-Ce1QNicQ.js";Object.freeze({module:n,operation:r,gate:i}),d(o),f(c(o));var p=class extends e()(`@fungi.computer/shiitake/ExtensionRead`){},m=class extends e()(`@fungi.computer/shiitake/ExtensionTx`){},h=class extends a(`ExtensionStateError`){},g=class extends a(`AdmissionError`){},_=class extends a(`ExtensionCommandError`){},v=class extends a(`ExtensionStop`){};a(`ExtensionActivationError`),f(l),f(s),u(t);export{v as a,h as i,_ as n,m as o,p as r,g as t};
@@ -1,4 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Qn as t,Wi as n,aa as r,ca as i,er as a,ia as o,la as s,ma as c,pa as l,pt as u,va as d,ya as f}from"./Effect-BY0T-p9d.js";import{Ar as p,Br as m,Di as h,Dr as g,Fi as _,Jr as v,Lr as y,Or as b,Qi as x,Qr as ee,Rr as S,Sr as C,Ui as w,Vr as T,Xi as te,Yr as ne,Zi as re,Zr as E,br as ie,ci as ae,fi as D,hi as oe,i as O,ii as se,ji as ce,jr as k,oi as A,qi as j,wi as le,wr as M,xr as ue,zi as N,zr as de}from"./extension-hook-Ce1QNicQ.js";import{$ as fe,J as pe,K as me,Q as P,X as he,Y as F,Z as ge,_ as I,a as _e,at as ve,c as ye,et as be,g as xe,h as Se,i as L,it as Ce,l as we,m as Te,nt as R,o as Ee,ot as De,p as Oe,q as z,r as ke,rt as Ae,s as je,tt as Me,v as B}from"./index--Y1OC0IE.js";import"./extensions-D55BOb_a.js";var V=m.check(w(1),N(256)),Ne=g.check(h(1),_(2**53-1)),H=g.check(h(0),_(2**53-1)),Pe=k([`write`,`external`]),Fe=T({module:y(V),access:Pe}),Ie=T({agentId:y(V)}),Le=T({principalId:V,agentId:y(V),sessionId:y(V),displayName:V}),Re=T({title:m.check(w(1),N(512)),inputBytes:g.check(h(0)),inputSha256:m.check(j(/^[a-f0-9]{64}$/))}),ze=T({kind:p(`pending_approval`),recordId:V,description:Re}),Be=k([`requested`,`pending`,`approved`,`claimed`,`applied`,`denied`,`expired`,`outcome_unknown`]),Ve=k([`not-found`,`not-eligible`,`already-answered`,`stale-revision`,`expired`,`declined`,`fenced`,`not-granted`,`read-only`,`pending`,`in-flight`,`outcome-unknown`,`identity-conflict`]),He=C(T({kind:p(`artifact`),ref:m.check(j(/^sha256:[a-f0-9]{64}$/)),mediaType:p(`image/png`),bytes:g.check(h(1),_(5242880))})).check(N(4)),Ue=T({recordId:V,requester:Le,module:V,operation:V,access:Pe,description:Re,evidence:x(He),authorityFence:V,reversibility:k([`reversible`,`irreversible-external`]),state:Be,by:y(v([T({kind:p(`human`),memberId:V}),T({kind:p(`policy`)})])),reason:y(Ve),requestedAt:H,expiresAt:H,updatedAt:H,revision:Ne}),We=T({record:Ue,canAnswer:M,canSetAutoApprove:M});T({state:x(Be),cursor:x(V),limit:x(g.check(h(1),_(100)))}),T({recordId:V}),T({recordId:V,decision:k([`approve`,`deny`]),expectedRevision:Ne});var Ge=T({scope:Ie,family:Fe,enabled:M});T({kind:p(`refused`),reason:Ve}),A(D(Ue),{onExcessProperty:`error`}),ae(D(Ue)),A(T({record_json:m})),A(D(b)),ae(D(b)),A(T({input_json:m,output_json:y(m)}));var Ke=T({kind:p(`refused`),reason:Ve}),qe=T({items:C(We),nextCursor:y(m)}),Je=v([T({kind:p(`answered`),view:We}),Ke]),Ye=v([T({kind:p(`updated`),rule:Ge}),Ke]),U=e=>be(d().transform(t=>A(e,{onExcessProperty:`error`})(t))),W=Ae(`approvals`,1,o(()=>Me({list:R(U(qe)),get:R(U(y(We))),answer:R(U(Je)),setAutoApprove:R(U(Ye))}))),G=ee(e=>xe.safeParse(e).success,{representation:{id:`@fungi.computer/whistle/catalog-step/v1`,payload:null}});u(()=>ie());var K=m.pipe(E(w(1)),E(N(4e3)),E(j(/\S/u,{message:`Goal objective is blank`}))),Xe=m.pipe(E(w(1)),E(N(1e3)),E(j(/\S/u))),Ze=m.pipe(E(w(1)),E(N(256))),Qe=g.check(h(0)),$e=T({kind:k([`person`,`blocked`,`stalled`,`cancelled`,`failed`,`no-terminal`]),detail:y(m)}),q=T({revision:m,objective:K,state:k([`active`,`paused`]),startedAt:Qe,pauseCause:y($e)}),et=T({sequence:g.check(le(0)),objective:K,outcome:k([`achieved`,`cleared`]),reason:y(Xe),endedAt:Qe,afterSequence:g.check(h(0))}),tt=v([T({action:p(`set`),objective:K,requestId:Ze,expectedRevision:re(y(m)),confirmed:re(M)}),T({action:k([`pause`,`resume`,`replace`,`clear`])}),T({})]),nt=T({goal:y(q),ended:C(et).check(N(16)),omitted:g.check(h(0))}),rt={id:O.make(`botanical-session-goal`),commands:{goal:{scope:`session`,input:tt,output:G},pause:{scope:`session`,input:T({}),output:q},resume:{scope:`session`,input:T({}),output:q},clear:{scope:`session`,input:T({}),output:T({})},set:{scope:`session`,input:T({objective:K,expectedRevision:y(m),requestId:Ze}),output:T({goal:q,accepted:T({status:p(`accepted`),commandId:m})})}},projection:{schema:nt}},J=e=>{let t=e.replace(/\s+/gu,` `).trim();return t.length<=80?t:`${t.slice(0,79)}…`},it=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 ${it(e.startedAt)}`:`Goal paused (/goal resume)`,r=!t&&e.pauseCause?.detail!=null?[J(e.pauseCause.detail)]:[],i={id:`goal`,title:[n,J(e.objective),...r].join(` · `),tone:t?`running`:`muted`,actions:[{id:`goal`,label:t?`Pause goal`:`Resume goal`,input:{action:t?`pause`:`resume`}}]};return J(e.objective)===e.objective?i:{...i,detail:e.objective.slice(0,1024)}}function ot(e){let t={id:`goal-ended`,title:`${e.outcome===`achieved`?`Goal achieved`:`Goal cleared`} · ${J(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 st=I(rt,{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(ot),omitted:r},waiting:null}}}),Y=m.pipe(E(w(1)),E(N(262144))),ct=m.pipe(E(w(1)),E(N(200))),lt=T({expression:m.pipe(E(w(1)),E(N(256))),timeZone:m.pipe(E(w(1)),E(N(128)))}),X=T({loopId:m,origin:k([`human`,`model`]),expiresAt:y(g),prompt:Y,mode:k([`self_paced`,`fixed_interval`]),cron:y(lt),state:k([`active`,`paused`,`finished`,`failed`,`cancelled`]),commandId:m,reason:y(m),nextDueAt:y(g),lastError:y(m)}),ut=T({loop:X,accepted:T({status:p(`accepted`),commandId:m})}),dt=v([T({action:p(`start`),text:Y,requestId:ct}),T({action:k([`status`,`pause`,`resume`,`stop`,`new`])}),T({})]),ft=T({loop:X}),pt={id:O.make(`botanical-session-loop`),commands:{loop:{scope:`session`,input:dt,output:G},startSelfPaced:{scope:`session`,input:T({prompt:Y,requestId:ct}),output:ut},startFixedInterval:{scope:`session`,input:T({prompt:Y,requestId:ct,...lt.fields}),output:ut},pause:{scope:`session`,input:T({}),output:X},resume:{scope:`session`,input:T({}),output:X},stop:{scope:`session`,input:T({}),output:X}},projection:{schema:ft}},mt=e=>{let t=e.replace(/\s+/gu,` `).trim();return t.length<=60?t:`${t.slice(0,59)}…`},ht=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),_t=I(pt,{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:ht(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)}`} · ${mt(t.prompt)}`,detail:[t.reason,t.prompt].filter(e=>e!==null).join(`
2
- `).slice(0,1024),tone:ht(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`}}}:null}}});function vt(e){return T({nextSequence:g.check(le(0)),omitted:g.check(h(0)),events:C(T({id:m,sequence:g,at:g,commandId:y(m),event:e}))})}new TextEncoder;var yt=T({explanation:x(m.pipe(E(N(2e3)))),steps:C(T({step:m.pipe(E(w(1)),E(N(500))),status:k([`pending`,`in_progress`,`completed`])})).pipe(E(N(50)))});yt.pipe(E(te(e=>e.steps.filter(e=>e.status===`in_progress`).length<=1||`At most one plan step may be in progress`)));function bt(e){return e.steps.some(e=>e.status!==`completed`)}var xt=T({plan:yt,history:vt(yt)}),St=v([T({action:p(`clear`)}),T({})]),Ct={id:O.make(`botanical-session-plan`),commands:{plan:{scope:`session`,input:St,output:G}},projection:{schema:xt}},wt=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)}`}},Tt=e=>e.steps.map((e,t)=>({id:String(t),title:e.step,tone:e.status===`completed`?`settled`:e.status===`in_progress`?`running`:`muted`})),Et=I(Ct,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null||!bt(e.value.plan)?[]:[{id:`plan`,...wt(e.value.plan),actions:[{id:`plan`,label:`Clear plan`,input:{action:`clear`}}],inspection:{commandId:`plan`,title:`Plan`,rows:Tt(e.value.plan)}}],timeline:{cells:[],omitted:0},waiting:null})}),Z=e=>m.check(w(1),N(e),j(/\S/u)),Dt=T({id:Z(32).check(j(/^[a-z][a-z0-9]*(?:[-_.][a-z0-9]+)*$/u)),header:Z(12),question:Z(1e3),options:C(T({label:Z(60),description:Z(300)})).check(w(2),N(4),te(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:x(M)}),Ot=C(Dt).check(w(1),N(4),te(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}})),kt=T({askId:m,questions:Ot,status:k([`live`,`parked`]),createdAt:S,expiresAt:y(S)}),At=T({asks:C(kt).check(N(4))}),jt=Z(256),Mt=de(Dt.fields.id,T({selected:C(Z(60)).check(N(4)),text:x(m.check(N(4e3)))})),Nt=T({askId:Z(256),requestId:jt,answers:Mt}),Pt=T({askId:Z(256),requestId:jt,note:x(m.check(N(4e3)))}),Ft=k([`answered`,`declined`,`withdrawn`,`expired`,`cancelled`,`undeliverable`]),It=v([T({result:p(`accepted`),via:k([`in_turn`,`follow_up`])}),T({result:p(`closed`),status:Ft}),T({result:p(`not_found`)})]),Lt={askId:Nt.fields.askId,requestId:jt,index:S.check(ce(),oe({minimum:0,maximum:3})),answers:Mt},Rt=v([T({stage:p(`multiple`),...Lt,selection:m.check(N(1e3))}),T({stage:p(`selection`),...Lt,selection:m.check(N(1e3))}),T({stage:p(`text`),...Lt,selected:Mt.value.fields.selected,text:m.check(N(4e3))}),T({askId:Nt.fields.askId}),T({})]),zt={id:O.make(`botanical-session-question`),commands:{answerFlow:{scope:`session`,input:Rt,output:G},answer:{scope:`session`,input:Nt,output:It},decline:{scope:`session`,input:Pt,output:It},list:{scope:`session`,input:T({}),output:At}},projection:{schema:At}},Bt=I(zt,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:e.value.asks.map(e=>{let t=e.questions[0];return{id:e.askId,title:`${t?.question??`Question`}${e.questions.length>1?` (+${String(e.questions.length-1)} more)`:``}`,detail:t?.options.map(e=>e.label).join(` · `)??``,tone:`attention`,actions:[{id:`answerFlow`,label:`Answer`,input:{askId:e.askId}}]}}),timeline:{cells:[],omitted:0},waiting:null})}),Vt=m.check(w(1),N(256)),Ht=k([`working`,`waiting`,`idle`,`failed`,`unavailable`]),Ut=T({agentId:Vt,name:Vt,sessionId:y(Vt),state:Ht,attention:x(m.check(N(200)))}),Wt=T({agents:C(Ut).check(N(16)),more:g.check(h(0)),expanded:M}),Gt={agents:{scope:`session`,input:T({}),output:G}},Kt={id:O.make(`botanical-session-subagents`),commands:Gt,projection:{schema:Wt}},qt={working:{label:`working`,tone:`running`,status:`info`},waiting:{label:`waiting on you`,tone:`attention`,status:`warning`},idle:{label:`idle`,tone:`settled`,status:`success`},failed:{label:`failed`,tone:`error`,status:`error`},unavailable:{label:`unavailable`,tone:`muted`,status:`neutral`}};function Jt(e){let t=qt[e.state],n={id:e.agentId,title:`${e.name} · ${t.label}`,tone:t.tone,status:{label:t.label,tone:t.status}},r=e.attention===void 0?n:{...n,detail:e.attention};return e.sessionId===null?{...r,detail:e.attention??`not messaged yet`}:{...r,open:{params:[{key:`agent`,value:e.agentId},{key:`session`,value:e.sessionId}]}}}function Yt(e){let t=t=>e.agents.filter(e=>e.state===t).length,n=[`working`,`waiting`,`failed`,`unavailable`].map(e=>[e,t(e)]).filter(([,e])=>e>0).map(([e,t])=>`${String(t)} ${qt[e].label}`),r=e.agents.length+e.more,i=t(`waiting`)>0?`attention`:t(`failed`)>0?`error`:t(`working`)>0?`running`:`muted`;return{id:`summary`,title:[`${String(r)} sub-agent${r===1?``:`s`}`,...n,`/agents shows them`].join(` · `),tone:i}}var Xt=I(Kt,{contribute:e=>({chips:[],panel:e.status!==`running`||e.value===null?[]:e.value.agents.length>0&&!e.value.expanded?[Yt(e.value)]:[...e.value.agents.map(Jt),...e.value.more===0?[]:[{id:`more`,title:`${String(e.value.more)} more sub-agent${e.value.more===1?``:`s`}`,tone:`muted`}]],timeline:{cells:[],omitted:0},waiting:null})});function Zt(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 Qt(e,t){e!==null&&e.showToast({message:t.message,tone:t.variant}).catch(e=>{console.error(`Chat toast failed`,e)})}var Q=e(De(),1),$=ve();function $t(e){if(e.name!==`execute`||e.status!==`completed`)return;let n=e.result?.content;if(n?.length!==1||n[0]?.type!==`text`)return;let r=se(D(ne))(n[0].text);if(t(r))return;let i=Se.safeParse(r.value);return i.success?i.data.file:void 0}function en({item:e,ui:t}){let n=$t(e),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1);if(!n)return null;let s=async()=>{i(!0),o(!1);try{await t.openNavigation(n)}catch(e){console.error(`Chat file navigation failed`,e),o(!0)}finally{i(!1)}};return(0,$.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,$.jsx)(B,{variant:`ghost`,size:`sm`,disabled:r,onClick:()=>void s(),type:`button`,children:r?`Opening file…`:`Open ${n.path} in Inkcap`}),a?(0,$.jsx)(`p`,{role:`alert`,children:`The file could not be opened. Try again.`}):null]})}var tn=l({kind:r(`generated`),file:l({computerId:c().min(1),path:c().min(1)}),format:n([`png`,`jpeg`,`gif`,`webp`,`mp4`]),width:i(),height:i(),bytes:i(),costMilliunits:i(),receipt:c()});function nn(e){if(e.name!==`execute`||e.status!==`completed`)return;let n=e.result?.content??[],r=n.at(0);if(r?.type!==`text`||n.slice(1).some(e=>e.type!==`image`))return;let i=se(D(ne))(r.text);if(t(i))return;let a=tn.safeParse(i.value);return a.success?a.data:void 0}function rn({item:e,ui:t}){let n=nn(e),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1);if(!n)return null;let s=async()=>{i(!0),o(!1);try{await t.openNavigation(n.file)}catch(e){console.error(`Chat image navigation failed`,e),o(!0)}finally{i(!1)}};return(0,$.jsxs)(`div`,{className:`px-3 py-2`,children:[(0,$.jsx)(B,{variant:`ghost`,size:`sm`,disabled:r,onClick:()=>void s(),type:`button`,children:r?`Opening file…`:`Open ${n.file.path} in Inkcap`}),a?(0,$.jsx)(`p`,{role:`alert`,children:`The file could not be opened. Try again.`}):null]})}var an={requested:`Approval requested`,pending:`Pending approval`,approved:`Approved. Waiting to run.`,applied:`Applied`,denied:`Denied`,expired:`Expired`,claimed:`Dispatch in progress`,outcome_unknown:`Outcome unknown. Reconcile before trying again.`};function on(e){let{view:t,scope:n}=e,r=JSON.stringify([t.record.recordId,t.record.revision,t.canAnswer,t.canSetAutoApprove,n.agentId]);return(0,$.jsx)(sn,{...e},r)}function sn({view:e,scope:t,capabilities:n,onViewChange:r}){let{record:i}=e,a=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let o=(0,Q.useRef)(!1),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(),[d,f]=(0,Q.useState)(),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),y=e.canAnswer&&i.state===`pending`&&!p&&!_;async function b(e,t){if(!o.current){o.current=!0,c(!0),u(void 0),f(void 0);try{await e()}catch{u(t)}finally{o.current=!1,c(!1)}}}function x(e){if(y)return b(async()=>{let t=await n.require(W).answer({recordId:i.recordId,decision:e,expectedRevision:i.revision});m(!0),t.kind===`answered`&&a.current?r(t.view):t.kind===`refused`&&u(`Decision refused. Refresh this approval before answering again.`)},`Couldn't submit the decision. Try again.`)}function ee(){if(!(!e.canSetAutoApprove||h||_))return b(async()=>{let e=await n.require(W).setAutoApprove({scope:t,family:{module:i.module,access:i.access},enabled:!0});g(!0),e.kind===`updated`?f(`Automatic approval enabled for this family.`):u(`Policy change refused. Refresh this approval before trying again.`)},`Couldn't change approval policy. Try again.`)}function S(){return b(async()=>{let e=n.require(W),t=(await e.list({state:`pending`,limit:100})).items.find(e=>e.record.recordId===i.recordId)??await e.get({recordId:i.recordId});a.current&&(v(t===null),t!==null&&(m(!1),g(!1),r(t)))},`Couldn't refresh this approval. Try again.`)}let C=(0,$.jsx)(B,{variant:`ghost`,disabled:s,onClick:()=>void S(),children:`Refresh approval`});return _?(0,$.jsxs)(z,{role:`group`,"aria-label":`Approval request`,"aria-busy":s,density:`compact`,children:[(0,$.jsxs)(pe,{children:[(0,$.jsx)(`p`,{role:`status`,children:`Approval unavailable.`}),l===void 0?null:(0,$.jsx)(`p`,{role:`alert`,children:l})]}),(0,$.jsx)(F,{children:C})]}):(0,$.jsxs)(z,{role:`group`,"aria-label":`Approval request`,"aria-busy":s,density:`compact`,children:[(0,$.jsxs)(he,{children:[(0,$.jsx)(ge,{children:i.operation}),(0,$.jsxs)(`p`,{children:[`Requester: `,i.requester.displayName]})]}),(0,$.jsxs)(pe,{className:`min-w-0 space-y-2`,children:[(0,$.jsxs)(`p`,{children:[`Authority: `,i.module,` · `,i.access]}),(0,$.jsxs)(`p`,{children:[`Can answer: `,e.canAnswer?`Yes`:`No`]}),(0,$.jsxs)(`p`,{children:[`Can set auto-approve: `,e.canSetAutoApprove?`Yes`:`No`]}),(0,$.jsx)(L,{children:i.reversibility===`reversible`?`Reversible`:`Cannot be undone`}),i.by?.kind===`policy`?(0,$.jsx)(L,{children:`Auto-approved by policy`}):null,(0,$.jsx)(`p`,{children:i.description.title}),(0,$.jsxs)(`p`,{className:`break-all`,children:[i.description.inputBytes,` bytes · SHA-256`,` `,i.description.inputSha256]}),(0,$.jsx)(`p`,{role:`status`,children:an[i.state]}),e.canSetAutoApprove?(0,$.jsxs)(`p`,{children:[`Policy scope:`,` `,t.agentId===null?`whole home`:`agent ${t.agentId}`]}):null,d===void 0?null:(0,$.jsx)(`p`,{role:`status`,children:d}),l===void 0?null:(0,$.jsx)(`p`,{role:`alert`,children:l})]}),(0,$.jsxs)(F,{className:`flex flex-wrap gap-2`,children:[(0,$.jsx)(B,{variant:`outline`,disabled:s||!y,onClick:()=>void x(`deny`),children:`Deny`}),(0,$.jsx)(B,{disabled:s||!y,onClick:()=>void x(`approve`),children:`Approve`}),e.canSetAutoApprove?(0,$.jsx)(B,{variant:`ghost`,disabled:s||h,onClick:()=>void ee(),children:`Always approve this family`}):null,C]})]})}var cn=(0,Q.forwardRef)(function({heading:e,eyebrow:t,cover:n,action:r,children:i,className:a,...o},s){return(0,$.jsxs)(z,{...o,className:P(`caps-game-share`,a),ref:s,children:[n?(0,$.jsx)(`div`,{className:`caps-game-share-cover`,children:n}):null,(0,$.jsxs)(he,{children:[t,(0,$.jsx)(`h3`,{className:`caps-game-share-heading`,children:e})]}),(0,$.jsx)(pe,{className:`gap-sm`,children:i}),(0,$.jsx)(F,{children:(0,$.jsx)(B,{asChild:!0,variant:`primary`,className:`caps-game-share-action`,children:r})})]})});function ln(e){let t=0;return e.map(e=>{let n={...e,offset:t};return t+=e.text.length,n})}function un({value:e,label:t,fieldLabel:n,displayValue:r,layout:i,title:a,tokens:o,className:s,...c}){let l=(0,Q.useId)(),[u,d]=(0,Q.useState)({kind:`ready`}),f=o?o.map(e=>e.text).join(``):e,p=async()=>{d(await navigator.clipboard.writeText(f).then(()=>({kind:`copied`}),e=>({kind:`failed`,cause:e})))};if(n!==void 0)return(0,$.jsxs)(`div`,{...c,className:P(`caps-copy-field-input`,s),children:[(0,$.jsx)(je,{htmlFor:l,children:n}),(0,$.jsxs)(Ee,{children:[(0,$.jsx)(_e,{className:`caps-copy-field-control`,"aria-label":n,id:l,onFocus:e=>{e.currentTarget.select()},readOnly:!0,value:r??f}),(0,$.jsx)(B,{onClick:()=>void p(),size:`sm`,variant:`outline`,children:u.kind===`copied`?`Copied`:t??`Copy`})]}),u.kind===`failed`?(0,$.jsx)(`span`,{role:`status`,children:`Could not copy. Select the text to copy it.`}):null]});let m=u.kind===`copied`?`Copied`:u.kind===`failed`?`Copy failed`:t??`Copy`;return i===`block`?(0,$.jsxs)(`figure`,{...c,className:P(`caps-copy-field-block`,s),"data-state":u.kind,children:[(0,$.jsxs)(`figcaption`,{className:`caps-copy-field-header`,children:[(0,$.jsx)(`span`,{className:`caps-copy-field-title`,children:a}),(0,$.jsxs)(B,{onClick:()=>void p(),size:`sm`,variant:u.kind===`copied`?`ghost`:`outline`,children:[u.kind===`copied`?(0,$.jsx)(we,{"aria-hidden":`true`,size:15}):(0,$.jsx)(ye,{"aria-hidden":`true`,size:15}),m]}),(0,$.jsx)(me,{role:`status`,children:u.kind===`copied`?`Copied to the clipboard`:u.kind===`failed`?`Could not copy. Select the code to copy it.`:``})]}),(0,$.jsx)(`pre`,{className:`caps-copy-field-code`,tabIndex:0,children:(0,$.jsx)(`code`,{children:o?ln(o).map(e=>(0,$.jsx)(`span`,{className:`caps-copy-field-token`,"data-kind":e.kind,children:e.text},e.offset)):f})})]}):(0,$.jsxs)(`div`,{...c,className:P(`caps-copy-field`,s),children:[(0,$.jsx)(`code`,{className:`caps-copy-field-value`,children:f}),(0,$.jsxs)(B,{"aria-label":`${m}: ${f}`,onClick:()=>void p(),size:`sm`,variant:`outline`,children:[u.kind===`copied`?(0,$.jsx)(we,{size:15}):(0,$.jsx)(ye,{size:15}),m]})]})}var dn=s({game:s({title:c().min(1),summary:c(),coverUrl:f().nullable(),shareUrl:f()})});function fn(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 pn(e){return fn(e)?e.split(`
3
- `).filter(e=>!/^\s*Share:\s*/iu.test(e)).join(`
4
- `).trim():e}function mn(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 hn({reply:e,previewGame:t}){let n=fn(e),r=n?mn(n):null,{data:i}=Ce({queryKey:fe.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=dn.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,$.jsxs)(cn,{"data-game-share-card":`true`,"data-theme":`vishnu`,heading:a?.title??`Your game is ready`,eyebrow:(0,$.jsx)(L,{tone:`secondary`,variant:`quiet`,children:`Made with your Agent`}),cover:c?(0,$.jsx)(`img`,{alt:`A scene from ${a?.title??`your game`}`,src:c}):null,action:(0,$.jsx)(`a`,{href:n,rel:`noopener noreferrer`,target:`_blank`,children:`Play ↗`}),children:[a?.summary?(0,$.jsx)(`p`,{className:`text-sm`,children:a.summary}):null,(0,$.jsx)(un,{displayValue:s,fieldLabel:`Share link`,label:`Copy link`,value:n})]})}var gn=se(D(ze),{onExcessProperty:`error`});function _n(e){if(!(e.status!==`completed`||e.result?.isError))for(let t of e.result?.content??[]){if(t.type!==`text`)continue;let e=gn(t.text);if(a(e))return e.value.recordId}}function vn({recordId:e,agentId:t,capabilities:n}){let[r,i]=(0,Q.useState)(),[a,o]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{let t=!0;async function r(){try{let r=await n.require(W).get({recordId:e});t&&i({capabilities:n,recordId:e,view:r,failed:!1})}catch(r){console.warn(`Grove could not read the approval`,r),t&&i({capabilities:n,recordId:e,view:null,failed:!0})}}return r(),()=>{t=!1}},[n,e,a]),r?.capabilities!==n||r.recordId!==e?null:r.failed?(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`p`,{role:`alert`,children:`Couldn't load this approval. Try again.`}),(0,$.jsx)(B,{variant:`ghost`,onClick:()=>{o(e=>e+1)},children:`Refresh approval`})]}):r.view===null||r.view.record.state===`expired`?null:(0,$.jsx)(on,{view:r.view,scope:{agentId:t},capabilities:n,onViewChange:t=>{i({capabilities:n,recordId:e,view:t,failed:!1})}})}var yn=[st,_t,Et,Bt,Xt],bn=e=>(0,$.jsx)(hn,{reply:e});function xn({prefill:e,onPrefilled:t}){let n=Te(),r=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{!e||r.current===e.requestId||(r.current=e.requestId,n.setDraft(e.text),t())},[n.setDraft,t,e]),null}function Sn({session:e,draftIdentity:t,connection:n,commands:r,prefill:i=null,onPrefilled:a=()=>void 0,onOpen:o}){let s=n?.ui??null,c=n?.capabilities,l=(0,Q.useCallback)(e=>Zt(s,e),[s]),u=(0,Q.useCallback)(e=>{let n=_n(e);return n!==void 0&&c!==void 0?(0,$.jsx)(vn,{recordId:n,agentId:t.agentId,capabilities:c},n):s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(en,{item:e,ui:s}),(0,$.jsx)(rn,{item:e,ui:s})]}):null},[s,c,t.agentId]),d=(0,Q.useCallback)(e=>{Qt(s,e)},[s]);return(0,$.jsxs)(Oe,{session:e,draftIdentity:t,clients:yn,authorOf:ue,onToast:d,children:[(0,$.jsx)(xn,{prefill:i,onPrefilled:a}),(0,$.jsx)(ke,{onLink:l,onOpen:o,composerActionVariant:`outline`,commands:r,renderAssistantAttachment:bn,formatAssistantText:pn,renderToolActions:u})]})}export{Sn as ParakeetConversation};