@fungi.computer/grove 0.2.1 → 0.2.2
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.
- package/dist/assets/{anthropic-messages-NIo9paF2.js → anthropic-messages-CR0lgZ06.js} +3 -3
- package/dist/assets/{azure-openai-responses-DVDapogw.js → azure-openai-responses-CiHqTiGl.js} +1 -1
- package/dist/assets/burger-DnR6BnTW.js +1 -0
- package/dist/assets/cat-CcSpd8IN.js +1 -0
- package/dist/assets/{compat-wIVDvT_3.js → compat-CXSKceKx.js} +2 -2
- package/dist/assets/{extension-hook-DCZVg8jj.js → extension-hook-CvLFlxpr.js} +117 -117
- package/dist/assets/extensions-p1H5H7ha.js +1 -0
- package/dist/assets/{google-generative-ai-CrPXPiH2.js → google-generative-ai-DoROu52Y.js} +1 -1
- package/dist/assets/{google-shared-CSSwo4u4.js → google-shared-BnaBv9x_.js} +1 -1
- package/dist/assets/{google-vertex-G6njJPqz.js → google-vertex-BJP4zrLk.js} +1 -1
- package/dist/assets/index-DhPnd7iW.js +171 -0
- package/dist/assets/{mistral-conversations-DYDnZWmT.js → mistral-conversations-Bx-ch8Fk.js} +1 -1
- package/dist/assets/{mushroom-CO06GGdJ.js → mushroom-CEqJ08xM.js} +1 -1
- package/dist/assets/{node.browser-BJm5CXR1.js → node.browser-CAoro5uc.js} +1 -1
- package/dist/assets/{openai-codex-responses-dWbmTJNd.js → openai-codex-responses-DRHaefx8.js} +1 -1
- package/dist/assets/{openai-completions-2Qvw2FRG.js → openai-completions-BnHZlDfo.js} +1 -1
- package/dist/assets/{openai-responses-BvoV9Y7s.js → openai-responses-DYr89tDb.js} +1 -1
- package/dist/assets/{openai-responses-shared-JWDc0New.js → openai-responses-shared-CIO9CkHC.js} +1 -1
- package/dist/assets/parakeet-conversation-B7BtxtaN.js +4 -0
- package/dist/assets/{renderer-DPA8RMmh.js → renderer-BHkhGf2O.js} +1 -1
- package/dist/assets/runtime-core-CLqMVcjU.js +1 -0
- package/dist/assets/{transform-messages-DdT3SC0y.js → transform-messages-iF4VkV1V.js} +1 -1
- package/dist/index.html +2 -2
- package/package.json +9 -9
- package/dist/assets/burger-CdmYCtZ0.js +0 -1
- package/dist/assets/cat-DPVVX4Jw.js +0 -1
- package/dist/assets/extensions-CVJs4Snj.js +0 -1
- package/dist/assets/index-BJuRfQVe.js +0 -171
- package/dist/assets/parakeet-conversation-CN_nK0S9.js +0 -4
- package/dist/assets/runtime-core-DlPx0Rnp.js +0 -1
|
@@ -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-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};
|
|
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-DhPnd7iW.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 g,Zn as ne,_ as re,a as _,at as v,bt as y,c as b,ct as x,d as ie,dt as S,er as C,et as ae,ft as w,g as T,gt as oe,h as E,ht as se,i as ce,ir as D,j as O,m as le,mi as k,mt as A,n as ue,o as de,or as j,ot as fe,p as M,pt as N,r as pe,s as P,sr as me,st as F,t as he,vt as ge,w as _e,xt as ve,y as I,yt as L}from"./Effect-BY0T-p9d.js";import{$ as ye,$a as be,$r as xe,$t as Se,A as Ce,Aa as R,An as we,At as Te,B as Ee,Bi as De,Br as Oe,Bt as ke,C as Ae,Cn as je,Ct as Me,D as Ne,Dr as z,Dt as Pe,E as Fe,Et as Ie,F as Le,Fa as Re,Fr as ze,Ft as Be,G as Ve,Ga as He,Gn as Ue,Gr as We,Gt as Ge,H as Ke,Ht as qe,I as Je,Ia as Ye,Ir as Xe,It as Ze,J as Qe,Ja as $e,Ji as et,Jn as B,Jt as tt,Ka as nt,Kn as rt,Kr as V,Kt as it,L as at,La as ot,Ln as st,Lt as ct,M as lt,Ma as ut,Mi as dt,Mr as ft,Mt as pt,N as mt,Nr as ht,Nt as gt,O as _t,On as vt,Or as yt,Ot as bt,P as xt,Pa as St,Pn as Ct,Pr as wt,Pt as Tt,Q as Et,Qa as Dt,Qi as Ot,Qn as H,Qr as kt,Qt as At,R as jt,Ra as Mt,Rn as Nt,Rt as Pt,S as Ft,St as It,T as Lt,Tn as Rt,Tr as zt,Tt as Bt,U as Vt,Ua as Ht,Un as Ut,Ur as Wt,Ut as Gt,V as Kt,Vt as qt,W as Jt,Wi as Yt,Wr as Xt,Wt as U,X as Zt,Xn as Qt,Xt as $t,Y as en,Ya as tn,Yn as nn,Yr as rn,Yt as an,Z as on,Za as sn,Zn as cn,Zt as ln,_ as un,_i as dn,_n as fn,_r as pn,_t as mn,a as hn,aa as gn,ai as _n,an as vn,at as yn,b as bn,bn as xn,br as Sn,bt as Cn,c as wn,cr as Tn,ct as En,d as Dn,di as On,dn as kn,dt as An,ei as jn,en as Mn,er as Nn,et as Pn,f as Fn,fi as In,fn as Ln,fr as Rn,ft as zn,g as Bn,ga as Vn,gi as Hn,gn as Un,gt as Wn,h as Gn,hn as Kn,hr as qn,ht as Jn,i as Yn,in as Xn,ir as Zn,it as Qn,j as $n,ja as er,jn as tr,jr as nr,jt as rr,k as ir,ka as ar,ki as or,kn as sr,kr as cr,kt as lr,l as ur,la as dr,ln as fr,lt as pr,m as mr,mi as hr,mn as gr,mt as _r,n as vr,na as yr,ni as W,nn as br,nr as xr,nt as Sr,o as Cr,oa as G,oi as wr,on as Tr,ot as Er,p as Dr,pi as Or,pn as kr,pt as Ar,q as jr,qa as Mr,qn as Nr,qr as Pr,qt as Fr,r as Ir,ra as K,rt as Lr,s as Rr,sa as zr,sn as Br,st as Vr,t as Hr,ta as Ur,tn as Wr,to as Gr,tt as Kr,u as qr,ui as q,un as Jr,ut as Yr,v as Xr,vn as Zr,vt as Qr,w as $r,wn as ei,wt as ti,x as ni,xn as ri,xt as ii,y as ai,yn as oi,yt as si,z as ci,zr as li,zt as ui}from"./extension-hook-CvLFlxpr.js";import{l as di,m as fi,p as pi}from"./preload-helper-DY31Aviq.js";import{d as mi,f as hi,u as gi}from"./index-DhPnd7iW.js";import{a as _i,i as vi,n as yi,o as bi,r as xi,t as Si}from"./extensions-p1H5H7ha.js";var Ci=gn(()=>Ji),wi=z(Ci),Ti=V({id:Oe,payload:ht}),Ei=V({...Ti.fields,schemas:yr(wi)});function Di(e){let t={};for(let[n,r]of Object.entries(e))Vn(r)&&a(t,n,r);return Object.keys(t).length===0?D():j(t)}var Oi=yr(Xt(We,jn)).pipe(hr(K(wt),{decode:ar(),encode:er(e=>f(e)||e.value===void 0?D():Di(e.value))})),ki=gn(()=>Mi),Ai=z(ki),ji={annotations:Oi,checks:Ai},Mi=xe([V({_tag:G(`Filter`),representation:Ei,annotations:Oi,aborted:cr}),V({_tag:G(`FilterGroup`),representation:yr(Ei),annotations:Oi,checks:li(ki)})]);function J(e){return V({_tag:G(e),...ji})}var Ni=V({_tag:G(`Declaration`),representation:Ti,annotations:Oi,typeParameters:wi,checks:Ai}),Pi=V({_tag:G(`Suspend`),annotations:Oi,checks:rn([]),thunk:Ci});function Fi(e,t){return t.pipe(hr(V({type:G(e),value:t}),{decode:R(e=>e.value),encode:R(t=>({type:e,value:t}))}))}var Ii=Fi(`string`,We),Li=Fi(`number`,Wt),Ri=V({_tag:G(`Literal`),...ji,literal:xe([Ii,Fi(`number`,nr),Fi(`bigint`,yt),Fi(`boolean`,cr)])}),zi=V({_tag:G(`UniqueSymbol`),...ji,symbol:Pr}),Bi=V({_tag:G(`Enum`),...ji,enums:z(rn([We,xe([Ii,Li])]))}),Vi=V({_tag:G(`TemplateLiteral`),...ji,parts:wi}),Hi=V({isOptional:cr,type:Ci,annotations:Oi}),Ui=V({_tag:G(`Arrays`),...ji,elements:z(Hi),rest:wi}),Wi=V({name:xe([Ii,Li,Fi(`symbol`,Pr)]),type:Ci,isOptional:cr,isMutable:cr,annotations:Oi}),Gi=V({parameter:Ci,type:Ci}),Ki=V({_tag:G(`Objects`),...ji,propertySignatures:z(Wi),indexSignatures:z(Gi)}),qi=V({_tag:G(`Union`),...ji,types:wi,options:K(V({mode:K(Xe([`anyOf`,`oneOf`]))}))}),Ji=xe([Ni,V({_tag:G(`Reference`),$ref:Oe}),Pi,J(`Null`),J(`Undefined`),J(`Void`),J(`Never`),J(`Unknown`),J(`Any`),J(`String`),J(`Number`),J(`Boolean`),J(`BigInt`),J(`Symbol`),J(`ObjectKeyword`),Ri,zi,Bi,Vi,Ui,Ki,qi]),Yi=Or(zr(V({representation:Ci,references:Xt(We,Ci)})));function Xi(e){return Yi(e)}var Zi=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function Qi(e){return e[Zi]?.()}var $i=3.5,ea=4800;function ta(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function na(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function ra(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:ea;return t}function ia(e){return Math.ceil(e.length/$i)}function aa(e){return Math.ceil(ra(e)/$i)}function oa(e){let t=0;if(e.role===`system`)return ia(fi(e))+la(e.toolsAdded)+la(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return aa(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+na(n.arguments).length;return Math.ceil(t/$i)}function sa(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`&&ta(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function ca(e){let t=`messages`in e?e.messages:e,n=sa(t);if(n){let e=ta(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=oa(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=oa(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function la(e){return!e||e.length===0?0:ia(na(e))}var ua=0xffffffffffff,da=(1n<<41n)-1n,fa=-1,Y;function pa(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>ua)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${ua}`);let n=e===void 0?Math.max(t,fa):e;e===void 0&&(fa=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===da)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 ma(e){return Mr(e,{onFailure:re,onSuccess:()=>m})}function ha(e,t){return h(e,{onFailure:e=>E(t).pipe(_(re(e))),onSuccess:()=>t})}function ga(e,t){let n={_tag:`open`},r=r=>ha(e,t).pipe(E,I(e=>N(()=>{r.result=e,n={_tag:`closed`}}).pipe(_(r.settled.open),_(ma(e)))),y);return w(()=>{if(n._tag===`closed`)return m;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(_(w(()=>{let t=e.result;return t===void 0?M(Error(`Agent close settlement was not recorded`)):ma(t)})))}let e={_tag:`running`,settled:pn(!1)};return n=e,r(e)})}function _a(e,t,n,r){let i=Lr(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=Qn(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:Kr(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:Ee(e,t)},progress:Kt(e,t,n.jobId),toolOutput:Ke(e,t,n.jobId)}}var va=new WeakMap;function ya(e,t){let n=Er(e,{sessionId:t}),r=Zt(n);return r.length===0?null:ca(r).tokens}function ba(e,t,n,r=!0){return O(function*(){let i=yield*ae(L({try:()=>pr(e.store,t),catch:e=>e}));if(i._tag===`Failure`){ri(`session-context.preference`,i.failure);return}let a=i.success,s=JSON.stringify(a),c=va.get(e)??new Map;va.set(e,c);let l=r?c.get(t):void 0,u=e.model.describe;if(l?.cursor===n&&l.preference===s){if(l.value===void 0||u===void 0)return l.value;let e=l.value;return yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:i})=>{if(e.window===i)return e;let a=Object.freeze({tokens:e.tokens,window:i});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:a}),a}),ie(t=>N(()=>(ri(`session-context.describe`,t),e))))}let d=yield*ae(L({try:()=>ya(e.store,t),catch:e=>e}));if(d._tag===`Failure`){ri(`session-context.figure`,d.failure);return}let f=d.success;if(f===null){r&&c.set(t,{cursor:n,preference:s,value:void 0});return}if(u===void 0){let e=Object.freeze({tokens:f,window:null});return r&&c.set(t,{cursor:n,preference:s,value:e}),e}r&&c.set(t,{cursor:n,preference:s,value:Object.freeze({tokens:f,window:null})});let p=yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:e})=>e),ie(e=>N(()=>(ri(`session-context.describe`,e),null)))),m=Object.freeze({tokens:f,window:p});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:m}),m})}function xa(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(_(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(_(e.extensions.call({scope:`agent`},t,n,r)))})}function Sa(e,t,n){return t.readQueueHead(n).pipe(I(r=>(r.state===`queued`?t.runningWork(r.jobId):S(null)).pipe(o(t=>_a(e.store,n,r,t)))))}function Ca(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function wa(e,t,n,r){return Sa(e,t,n).pipe(I(i=>$r(e.store,n,i,r,()=>t.extensions.project(n))),I(t=>ba(e,n,t.cursor,r?.before===void 0).pipe(o(e=>Ca(t,e)))))}function Ta(e,t,n){return e.assertOpen.pipe(_(L({try:()=>n(B(t)),catch:e=>e instanceof H?e:new H(`store`,`rejected`,`Session owner operation failed`)})))}function Ea(e,t){return L({try:()=>{let n=rt(t);if(n._tag===`Failure`)throw new H(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:B(e),command:n.success})},catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Session command is invalid`)})}function Da(e,t){return L({try:()=>Object.freeze({sessionId:B(e),options:Qt(t)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Subscribe options are invalid`)})}function Oa(e,t,n,r=!1){return t.assertOpen.pipe(_(wa(e,t,n,{includeSandboxFailures:r})),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function ka(e){return[[e],j({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function Aa(e,t,n,r,i,a,s=!1){return Rn({after:i,delivery:a,awaitSignal:!1},i=>(i.awaitSignal?n.awaitSignal.pipe(I(e=>n.pollSignal.pipe(o(t=>t===void 0?e:fn(e,t))))):n.pollSignal).pipe(I(a=>a===`closed`?S([[],D()]):a===`reset`?Oa(e,t,r,s).pipe(o(ka)):t.assertOpen.pipe(_(Sa(e,t,r)),I(c=>(n.setQueued(c.facts.queue.state===`queued`),a===`activity`&&i.delivery===`live`?S([[{kind:`activity`,activity:c.facts}],j({...i,awaitSignal:!0})]):a===`progress`&&i.delivery===`live`?S([[...c.progress===null?[]:[{kind:`progress`,progress:c.progress,activity:c.facts}],{kind:`tool_output`,toolOutput:c.toolOutput,activity:c.facts}],j({...i,awaitSignal:!0})]):Fe(e.store,r,i.after,i.delivery,c,()=>t.extensions.project(r),s).pipe(I(n=>{if(n.kind===`reset`)return Oa(e,t,r,s).pipe(o(ka));let a=n.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`?[]:[e.cursor]).at(-1),c={after:a??i.after,delivery:n.hasMore?i.delivery:`live`,awaitSignal:!n.hasMore};return(n.frames.some(e=>e.kind===`update`&&e.cursor!==i.after)&&!n.hasMore?ba(e,r,a??null):S(void 0)).pipe(o(e=>[e===void 0?n.frames:n.frames.map(t=>t.kind===`update`&&t.cursor===a?Object.freeze({...t,context:e}):t),j(c)]))}))))))))}function ja(e,t,n,r,i){return qn(t.assertOpen.pipe(_(Da(r,i)),I(r=>he(n.register(r.sessionId),e=>N(e.close)).pipe(o(n=>Aa(e,t,n,r.sessionId,r.options.after,`replay`,r.options.includeSandboxFailures===!0))))))}function Ma(e,t){return L({try:()=>Object.freeze({sessionId:B(e),options:Ue(t)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Watch options are invalid`)})}function Na(e,t,n,r,a){return t.assertOpen.pipe(_(Ma(r,a)),I(r=>ve(a=>O(function*(){let s=yield*n.register(r.sessionId);return yield*a(t.assertOpen.pipe(_(wa(e,t,r.sessionId,r.options)),o(n=>(s.setQueued(n.activity.queue.state===`queued`),Object.freeze({snapshot:n,changes:Aa(e,t,s,r.sessionId,n.cursor??void 0,`live`,r.options.includeSandboxFailures===!0).pipe(Tn(N(s.close))),close:N(s.close)}))))).pipe(i(()=>N(s.close)))}))))}function Pa(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(_(e.door.admit(o)),I(e=>e.status===`accepted`?S({status:`accepted`,commandId:e.commandId}):T(new H(`runtime`,`unavailable`,`Session command was not admitted`))))}function Fa(e,t,n,r,i){return t.assertOpen.pipe(_(Ta(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&Qe(e.store,t,r.commandId,Sr(e.store,e.meta.identityPath,i))})),_(Dr(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),I(e=>e===void 0?S({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(P({status:`accepted`,commandId:e.accepted.commandId}))))}function Ia(e,t,n,r){return t.assertOpen.pipe(_(t.commit(ur(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),I(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function La(e,t,n,r){return t.assertOpen.pipe(_(Fn(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),P(void 0))}function Ra(e,t,n,r){return t.assertOpen.pipe(_(un(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function za(e,t,n,r,i){return t.assertOpen.pipe(_(Ea(n,i)),I(t=>Ba(e,r).pipe(o(e=>({...t,checked:e})))),I(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Pa(t,n,r,i);case`abort`:return Ia(e,t,n,i).pipe(P(void 0));case`cancel`:return Fa(e,t,n,r,i);case`branch`:return La(e,t,n,r);case`fork`:return Ra(e,t,n,r);case`operator`:return t.assertOpen.pipe(_(lt(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),P(void 0));case`title`:return t.commit(Ta(t,n,t=>{zn(e.store,t,r.title)})).pipe(P(void 0))}}))}function Ba(e,t){return L({try:()=>t===void 0?void 0:je(e.meta,t),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Host metadata is invalid`)})}function Va(e,t){let n=Zr(e.store),r=(r,i)=>{function a(n){return za(e,t,r,i,n)}return Object.freeze({command:a,withdraw:e=>t.assertOpen.pipe(_(t.door.withdraw(r,e))),abort:a({type:`abort`}),send:(e,t)=>N(()=>t?.requestId??zt()).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 H(e.boundary,e.cause,e.message,n)))})),cancel:e=>a({type:`cancel`,...e}),latestPending:Ta(t,r,t=>Vt(e.store,t,e.meta?.identityPath===void 0||i===void 0?void 0:Sr(e.store,e.meta.identityPath,i))),modelPreference:Object.freeze({read:Ta(t,r,t=>pr(e.store,t)),set:n=>L({try:()=>Nn(n),catch:()=>new H(`contract`,`invalid`,`Model preference is invalid`)}).pipe(I(n=>t.commit(Ta(t,r,t=>(An(e.store,t,n),t))).pipe(A(t=>N(()=>{xn(e.store,t)})),b)))}),extension:e=>Object.freeze({call:(n,i)=>t.assertOpen.pipe(_(t.extensions.call({scope:`session`,sessionId:r},e,n,i)))}),read:n=>t.assertOpen.pipe(_(wa(e,t,r,n))),readSettlement:(i,a=0)=>x(O(function*(){yield*t.assertOpen;let s=yield*L({try:()=>({sessionId:B(r),...cn(nn({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*he(n.register(s.sessionId,`settlement`),e=>N(e.close)),l=Ft(e.store,s.sessionId,s.commandId),u=yield*l;return u!==void 0||s.timeoutMs===0?u:yield*O(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*T(new H(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(oe(s.timeoutMs),o(ne))})),subscribe:i=>ja(e,t,n,r,i),watch:i=>Na(e,t,n,r,i)})},i=Object.freeze({createSession:n=>t.assertOpen.pipe(_(mr(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(_(Bn(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(_(Lt(e.store,n))),extensions:xa(t),session:e=>r(e,void 0),close:t.beginClose.pipe(_(n.close))});return Object.freeze({...i,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>Ta(t,n,t=>e.store.transactionSync(()=>si(e.store,t,r))),read:n=>Ta(t,n,t=>Cn(e.store,t))}),withMeta:e=>Object.freeze({...i,session:t=>r(t,e)})})}function Ha(e,t,n,r,i,a){if(t.to.sessionId===void 0){if(r!==void 0||t.replyTo.length===0)throw Error(`Only delegated work can create a recipient Session`);return e.door.transact(r=>{let o=e.createSessionWithinTransaction(t.key),s=a?.(o);s!==void 0&&e.stageSessionGrantsWithinTransaction(o,s);let c={...t,to:{...t.to,sessionId:o}},l={sessionId:o,requireExistingSession:!0,command:{requestId:t.key,delivery:`followUp`,type:`prompt`,text:t.content},when:`now`,origin:{kind:`user`},mail:c,onAccepted:(e,n)=>{if(i===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);i(Jr(t,o,n,Date.now()))}},u=r(n===void 0?l:{...l,meta:n});if(u.status!==`accepted`)throw Error(`Sessionless addressed mail was not admitted`);return{status:`accepted`,commandId:u.commandId,sessionId:o}})}return Pa(e,t.to.sessionId,{requestId:t.key,delivery:r===void 0?`followUp`:`steer`,type:`prompt`,text:t.content},n,t,r)}var Ua=V({fork:Xe([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:ft.pipe(W(or(0)),W(De(2**53-1)))});function Wa(e,t){let n=Hn(e.schema)(t);if(n._tag===`Failure`)throw new vi({reason:`encode`,message:`Session document does not match its schema`});let r=q(ei)(n.success);if(r._tag===`Failure`)throw new vi({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 vi({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function Ga(e){return{...On(Ua)(e),schema:Xi(dr(e.schema)),initial:Wa(e,e.initial)}}var Ka=64,qa=Xe([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),Ja=z(qa).pipe(W(Yt(10))),Ya=V({protocol:ze(`shiitake.extension/v0`),id:Cr,version:wn,requests:Ja}),Xa=z(V({id:Cr,capabilities:Ja,grantKey:K(Cr)})).pipe(W(Yt(Ka))),Za=We.pipe(W(Ot(/^[a-z][A-Za-z0-9_]{0,63}$/u))),Qa=q(Ya,{onExcessProperty:`error`}),$a=q(Xa,{onExcessProperty:`error`}),eo=q(Za);function X(e){return new H(`extensions`,`invalid`,e)}function to(e){return new Set(e).size!==e.length}function no(e){return JSON.stringify(e,(e,t)=>k(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function ro(e){return ge({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 H(`extensions`,`rejected`,`Extension digest failed`)})}function io(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:Xi(dr(t.input)),output:Xi(dr(t.output))}])),projection:r.projection===null?null:Xi(dr(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,Xi(dr(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ga(t)]))};return o===void 0?c:{...c,catalog:o}}function ao(e){if(Qa(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(to(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`||eo(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 oo(e){return O(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*L({try:()=>{if(t.length>Ka)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=Qi(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(eo(e)._tag===`Failure`)throw X(`Session document name is invalid`);Ga(t)}let r=ao(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(to(e.map(({manifest:e})=>e.id)))throw new H(`extensions`,`conflict`,`Extension identities conflict`);let r=$a(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(to(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||to(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 H(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new H(`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 H?e:X(`Extension roster is invalid`)});return yield*_e(r,e=>O(function*(){let t=`sha256:${yield*ro(yield*L({try:()=>no(io(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*ro(no([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:On(Rr)(t),fingerprint:On(hn)(r)})}))})}function so(e){return ro(no({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}function co(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 lo(e){return co({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function uo(e){return new H(`model`,`rejected`,e)}function fo(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 po(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 mo(e,t,n){let r=lr(),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)Te(t,r);return r}function ho(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 go(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`&&!ho(e,a+1,n,i)&&r.push(a)}return r}function _o(e,t,n,r){let i=go(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=oa(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function vo(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 yo(e,t,n,r){let i=_o(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...vo(e,t,i)}}function bo(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=Pe(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=ca(po(e)).tokens,s=yo(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=mo(u,e,r);for(let e of d)Te(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 xo={enabled:!0,maxRetries:3,baseDelayMs:2e3};function So(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??pa()};return Ct(()=>Promise.resolve((r??Nt)(e,di(t),i)).then(e=>e.result()),xo,i.signal)}function Co(e){return{systemPrompt:Me,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function wo(e,t,n){let r=e.previousSummary??``,i=t?Bt:It,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${pt(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function To(e){return`# Conversation\n${pt(e.turnPrefixMessages)}\n\n# Instructions\n${ti}`}async function Eo(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await So(e,Co(r),o,a),c=Be(s,i);if(c!==void 0)throw Error(c);return s}function Do(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):Eo(t,n,r,wo(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function Oo(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):Eo(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,To(e),`Turn prefix summarization`,r)}function ko(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.`:pi(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${pi(n.content)}`,i=t===void 0?n.usage:fo(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=pi(t.content),i=t.usage}let a=bt(e.fileOps);return{summary:r+rr(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function Ao(e,t,n,r,i){return ko(e,await Do(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 Oo(e,t,n,i):void 0)}function jo(e,t,n,r){return ge({try:i=>Ao(e,t,i,r,n),catch:e=>uo(e instanceof Error?e.message:String(e))})}function Mo(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var No=new WeakMap;function Po(e){return No.has(e)}function Fo(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return Re(t,N(()=>{Lo(e,r)})).pipe(_(l(i,t)),o(t=>(r.fiber=t,No.set(e,r),r)))}function Io(e){let t=e.summary;return e.summary=void 0,t}function Lo(e,t){t.fiber=void 0,t.summary=void 0,No.get(e)===t&&No.delete(e)}function Ro(e){return new H(`runtime`,`rejected`,e)}var zo={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`},Bo=class extends H{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,zo[e]),this.phase=e,this.usage=t}get diagnostic(){return zo[this.phase]}};function Vo(e,t){let n=Wn(e,t),r=_r(e),i=[];for(let t of e){let e=Br(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:Xn(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:Tr(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 Ho(e,t,n){return L({try:()=>Er(e,{sessionId:t,workId:n}),catch:()=>Ro(`Woodstock selected lineage is unavailable`)})}function Uo(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return Zt([...e,i],r).reduce((e,t)=>e+oa(t),0)}function Wo(e,t,n){return w(()=>(jt(e.store,e.sessionId,n.trigger),Go(e,t,n).pipe(le(N(()=>{ci(e.store,e.sessionId)})))))}function Go(e,t,n){return O(function*(){let r=bo(Vo(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*jo(r,e.model,e.stream,n.instructions),o=yield*Jo(e,r,a,i.id);return yield*Zo(e,t,a,n,i.id,o)})}var Ko=xe([V({type:ze(`accepted`),receipt:br}),V({type:ze(`discarded_by_policy`)})]),qo=q(Ko);function Jo(e,t,n,r){return e.handoff===void 0?S(void 0):e.handoff.consume(Mo(t,n,e.sessionId,r)).pipe(p(()=>new Bo(`handoff`,n.usage)),I(e=>{let t=qo(e);return t._tag===`Failure`?T(new Bo(`handoffResult`,n.usage)):S(t.success.type===`accepted`?t.success.receipt:void 0)}))}function Yo(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=Uo(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[Ie(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 Xo(e,t,n){let r=[...t,n];return{path:r,messages:Zt(r,e.workId)}}function Zo(e,t,n,r,i,a){let s=Yo(e,t,n,r,i,a);return s===void 0?S(void 0):L({try:()=>Dn(e.store,s),catch:e=>e instanceof H?e.cause===`conflict`?new Bo(`conflict`):e:Ro(`Woodstock compaction append failed`)}).pipe(o(n=>Xo(e,t,n)))}function Qo(e){return e instanceof Bo?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function $o(e,t){return L({try:()=>{qr(e.store,t)},catch:e=>e instanceof H?e:Ro(`Compaction notice could not be recorded`)})}function es(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return $o(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:Qo(n),usage:n instanceof Bo?n.usage:void 0})}function ts(e,t,n){return ae(Wo(e,t,n)).pipe(I(t=>t._tag===`Success`?S(t.success):es(e,n.trigger,t.failure).pipe(P(void 0))))}var ns={trigger:`threshold`,resumesRun:!1};function rs(e,t,n,r){return t.stopped||Po(e.store)||!Tt(n,e.model.contextWindow,e.settings)?m:r.pipe(I(n=>is(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function is(e,t,n){let r=n.at(-1),i=bo(Vo(n,e.workId),e.settings);return r===void 0||i===void 0?S(void 0):Fo(e.store,t,t=>as(e,i,r.id,t))}function as(e,t,n,r){return w(()=>(jt(e.store,e.sessionId,`threshold`),jo(t,e.model,e.stream).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),le(N(()=>{ci(e.store,e.sessionId)})))))}function os(e,t,n,r){return w(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?S(void 0):(t.slot=void 0,ae(Sn(a).pipe(I(()=>cs(e,i)),I(t=>t===void 0?S(void 0):ls(e,t,n)))).pipe(I(n=>n._tag===`Success`&&n.success!==void 0?S(n.success):(t.stopped=!0,n._tag===`Success`?S(void 0):es(e,`threshold`,n.failure).pipe(P(void 0)))),le(N(()=>{Lo(e.store,i)}))))})}function ss(e,t,n){return $o(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(P(void 0))}function cs(e,t){let n=Io(t);if(n===void 0)return S(void 0);let{result:r,selectionTail:i}=n;return L({try:()=>on(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof H?e:Ro(`Woodstock compaction head is unavailable`)}).pipe(I(t=>t===`stale`?ss(e,r,`stale`):Jo(e,n.preparation,r,i).pipe(o(e=>({result:r,selectionTail:i,receipt:e})))),le(N(()=>{Lo(e.store,t)})))}function ls(e,t,n){return Ho(e.store,e.sessionId,e.workId).pipe(I(r=>{let i=Yo(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?S(void 0):gt(i.tokensAfter,e.model.contextWindow,e.settings)?ss(e,t.result,`insufficient`):L({try:()=>bn(e.store,i),catch:e=>e instanceof H?e.cause===`conflict`?new Bo(`conflict`):e:Ro(`Woodstock compaction append failed`)}).pipe(I(n=>n===`stale`?ss(e,t.result,`stale`):S(Xo(e,r,n))))}))}function us(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return S(n);let r=ca(e.messages).tokens;return gt(r,e.model.contextWindow,e.settings)?ts(e,e.path,ns).pipe(o(e=>e??n)):rs(e,t,r,S(e.path)).pipe(P(n))}function ds(e,t){let n=sr(e.message,t.contextWindow),r=st(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function fs(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function ps(e,t,n,r){if(!e.settings.enabled)return S(void 0);let i=gt(ca([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?Ho(e.store,e.sessionId,e.workId):S(void 0)}function ms(e,t,n){return(r,i)=>O(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=ca(r).tokens,s=gt(o,e.model.contextWindow,e.settings),c=yield*os(e,n,ns,s);if(c!==void 0)return a(c);let l=Ho(e.store,e.sessionId,e.workId);if(!s){yield*rs(e,n,o,l);return}let u=yield*ts(e,yield*l,ns);return u===void 0?void 0:a(u)})}function hs(e,t,n){return O(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,ms(e,t,n)),o=ds(a,e.model),s=o.retry&&!i,c=yield*os(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:fs(c.messages)},i=!0;continue}let l=yield*ps(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*ts(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:fs(u.messages)},i=!0}})}function gs(e){return O(function*(){let t={scope:yield*F,slot:void 0,stopped:!1};return yield*hs(e,e.settings.enabled?yield*us(e,t):e,t)})}function _s(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?S(`compacted`):Wo(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(se(t=>es(e,`manual`,t)),I(t=>t===void 0?es(e,`manual`,void 0).pipe(P(`nothing_to_compact`)):S(`compacted`)))}var vs=ft.pipe(W(dt(0)),W(De(2**53-1))),ys=V({reserveTokens:K(vs),keepRecentTokens:K(vs),backgroundTokens:K(vs)}),bs=V({enabled:K(cr),reserveTokens:K(vs),keepRecentTokens:K(vs),backgroundTokens:K(vs),modelOverrides:K(Xt(We,ys))}),xs=q(bs,{onExcessProperty:`error`});function Ss(e){let t=xs(e??{});if(t._tag===`Failure`)throw new H(`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??ii.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??ii.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??ii.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??ii.backgroundTokens}}}function Cs(e){return new H(`runtime`,`rejected`,e)}var ws={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},Ts=class extends H{phase;constructor(e){super(`runtime`,`rejected`,ws[e]),this.phase=e}get diagnostic(){return ws[this.phase]}};function Es(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+co({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,errorMessage:n}: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:n}}function Ds(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?T(new Ts(`missing`)):S([]):O(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=>mt(e.store,{sessionId:t,commandId:n},r).pipe(te),modules:[...s.modules,...l],tools:o,access:{...s.access,sessionGrants:()=>Cn(e.store,t)?.grants??{}}},c=yield*(yield*vt(s.execution===void 0?a:{...a,execution:s.execution}).pipe(p(()=>new Ts(`runtime`)))).acquire().pipe(p(()=>new Ts(`lease`)));return[c.executeTool,...c.tools]})}function Os(e,t,n,r,i,a,s){return x(O(function*(){let l=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),u=l.release;u!==void 0&&(yield*pe(()=>N(u)));let d=yield*gi(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),f=yield*Ds(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*ai(e.store,h,n),te=t=>Je(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 H?e.message:`Session control delivery failed`}))),g=t.resume,ne=Ss(e.compaction)(d.model),re,_=0;return{run:yield*gs({store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:d.model,stream:d.stream,handoff:a,settings:ne,path:t.path,messages:t.messages,resuming:g!==void 0,run:(t,n)=>{_=0;let r=g;g=void 0;let i,a=e=>{if(e.type===`run_end`&&e.outcome===`failed`)return i=e,m;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=d.providerError?.(e.value);if(t!==void 0)return ee({...e,value:{...e.value,providerError:t}})}return ee(e)},u={model:d.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??tr,retryAfterMs:d.retryAfterMs,retryable:d.retryable,systemPrompt:l.text,prepareSystemPrompt:()=>(s===void 0?S([]):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=>(t.type===`retry_finished`&&!t.success&&(_=t.attempt+1),$n(e.store,h,Es(t,d.model),t.turn))};return we.run(d.stream===void 0?u:{...u,stream:d.stream},a).pipe(c(e=>{if(i===void 0)return m;if(nt(e)){let t=e.value.modelLimitReason??d.failureReason?.(e.value.message)??lo(e.value);return re=(_>1&&e.value.modelLimitReason===void 0?`The model failed ${String(_)} times on this conversation: ${t}`:t).slice(0,200),ee(i,re)}let t=be(e.cause);return ee(i,C(t)&&t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):co({runId:i.run.value,provider:d.model.provider,model:d.model.id}))}),p(e=>e.phase===`model`?new H(`model`,`rejected`,e.message,void 0,e):Cs(`Mule rejected the durable command run`)))}}),failureReason:re}}))}function ks(e,t,n){return x(O(function*(){let r=yield*gi(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),i=t.command.entry;return yield*_s({store:e.store,sessionId:t.command.sessionId,workId:i.workId,model:r.model,stream:r.stream,handoff:n,settings:Ss(e.compaction)(r.model),path:t.path,instructions:vn(i)?i.instructions:void 0})}))}var As=Object.freeze({maxRecoveries:2});function js(e){return new H(`runtime`,`rejected`,e)}function Ms(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof Ts||e instanceof Bo||e instanceof Ve?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function Ns(e,t){return u(`shiitake_run_failed`,ut(t)).pipe(de({workId:e,reason:`${t.boundary}:${t.cause}`}))}function Ps(e,t,n,r){return O(function*(){xn(e.store,n.queue);let i=yield*L({try:()=>Ln(n),catch:()=>js(`Agent work payload is invalid`)}),a=yield*Xr(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(de({workId:n.jobId,terminal:`contract_changed: ${s}`})),yield*T(js(`contract_changed: ${s}`));let c=new Set(r?.runParticipants().map(([e])=>e)??[]);if(vn(a.command.entry))return yield*ks(e,a,r?.compactionHandoff(c)),yield*xt(e.store,{sessionId:a.command.sessionId,commandFactId:i.work.commandFactId,workId:a.command.entry.workId,outcome:`completed`}),{kind:`completed`};let l=yield*L({try:()=>Ae(e.store,i.work.sessionId,i.work.commandFactId,a.command.entry.workId),catch:()=>js(`Accepted run origin is unavailable`)}),d={sessionId:a.command.sessionId,workId:a.command.entry.workId,origin:l===null?null:{extensionId:On(Yn)(l.extensionId),correlation:l.correlation}},f=r===void 0?[]:yield*r.filesForRun(d,c),p=r===void 0?[]:yield*_e([...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=>Rt.grantAs(e,r))},catch:()=>js(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),m=r?.compactionHandoff(c),{run:h,failureReason:ee}=yield*Os(e,a,{core:f.length===0?t:yield*so(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??lo(h)}}}).pipe(ie(e=>Ns(n.jobId,e).pipe(P(Ms(e)))))}var Fs=q(Jt,{onExcessProperty:`error`}),Is=q(kt(cr)),Ls=q(fr,{onExcessProperty:`error`});function Rs(e){if(e.reply===void 0)return;let t=cn(Ls(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 H(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function zs(e){let t=t=>({sessionId:B(t.sessionId),requireExistingSession:cn(Is(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:cn(Ut(t.command),`Session command is invalid`),origin:cn(Fs(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:Rs(t),onAccepted:t.onAccepted,meta:t.meta===void 0?void 0:je(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(en(e.owner,r,a.requestId),t.requireExistingSession&&!ye(e.owner,r))throw new H(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&yn(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&yn(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=jr(e.owner,r,a,t.meta,i,e.contract(),s===void 0?n=>{e.enqueue(n,t.mail)}:void 0,s,t.reply);return t.onAccepted?.(r,c.accepted.commandId),n.set(r,(n.get(r)??!1)||c.delivery===`new`),Object.freeze({status:`accepted`,commandId:c.accepted.commandId,delivery:c.delivery})},r=(t,r)=>w(()=>{let i=new Map,a=L({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof H?e:new H(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(A(()=>N(()=>{for(let[t,n]of i)n&&xn(e.owner,t)})),A(()=>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:B(t),requestId:Nr({requestId:n})}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(I(t=>r(()=>Ar(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>L({try:()=>t(e),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Session command is invalid`)}).pipe(I(e=>r(t=>t(e),n??`request`)))})}var Bs=`core`,Vs=256,Hs=1048576,Us=512,Ws=64,Gs=new TextEncoder,Ks=q(z(V({name:We.pipe(W(Ot(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:We.pipe(W(et(1)),W(Ur(e=>Gs.encode(e).byteLength<=8192)))})).pipe(W(Yt(16)))),qs=class extends Error{};function Js(e){return e.length<=Us?e:`${e.slice(0,511)}…`}var Ys=wr(dn(ei));function Xs(e){return e instanceof _i?e.reason:`${e._tag}: ${e.message}`}function Zs(e){return e instanceof _i||e instanceof vi||e instanceof Si||e instanceof yi}function Qs(e,t){let r=be(t);if(C(r)){let t=r.value;return t instanceof _i?Js(t.reason):Js(Zs(t)?`${e}: ${Xs(t)}`:`${e} failed`)}let i=n(Dt(t));return C(i)?i.value instanceof Error?Js(i.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${i.value.message}`):Js(`${e} defect`):Js(`${e} was interrupted`)}function $s(e){let t=be(e);return f(t)||t.value instanceof _i}function Z(e,t){return new vi({reason:e,message:t})}function ec(e,t){return e.length>=1&&e.length<=Vs?S(e):T(Z(`bound`,`${t} must be 1..256 characters`))}function tc(e){let t=Js(e.message);if(e instanceof yi)switch(e.reason){case`invalid`:return new H(`contract`,`invalid`,t);case`conflict`:return new H(`store`,`conflict`,t);case`not_found`:return new H(`store`,`rejected`,t);case`rejected`:return new H(`extensions`,`rejected`,t)}if(e instanceof Si)switch(e.reason){case`invalid`:return new H(`contract`,`invalid`,t);case`conflict`:return new H(`contract`,`conflict`,t);case`closed`:return new H(`runtime`,`closed`,t)}return e.reason===`bound`?new H(`contract`,`invalid`,t):new H(`store`,`unavailable`,t)}function nc(e){let{owner:t}=e,n=new WeakMap,r=new Map,a=new Set,c,l=new Set,p=new Set,h,ne=e=>Object.freeze({extensionId:e}),v=e=>I(xi,t=>t.extensionId===e?m:M(Error(`Extension read used another extension's context`))),y=e=>I(bi,t=>{let r=n.get(t);return r?.extensionId===e?S(r):M(Error(`Extension write used outside its own core transaction`))}),b=e=>L({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),x=(e,t)=>e.admitted.grants.has(t)?m:T(Z(`unavailable`,`Extension is not granted ${t}`));function ae(e,n,r){let i=e.admitted.id,a=_n(dn(r.schema)),s=In(r.schema),l=e=>{let t=a(e);return t._tag===`Failure`?T(Z(`decode`,`Stored ${n} record is invalid`)):S(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=it(t,i,n,r);if(o===void 0)return D();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return j(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>Ws)throw Z(`bound`,`Page limit must be 1..64`);return Fr(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=>v(i).pipe(_(x(e,`state`)),_(b(()=>it(t,i,n,r))),I(e=>e===void 0?S(D()):l(e).pipe(o(j)))),page:r=>v(i).pipe(_(x(e,`state`)),_(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=Ws?m:T(Z(`bound`,`Page limit must be 1..64`))),_(b(()=>Fr(t,i,n,r))),I(e=>_e(e,l))),put:a=>y(i).pipe(_(x(e,`state`)),_(w(()=>{let e=s(a);if(e._tag===`Failure`)return T(Z(`encode`,`The ${n} record does not match its schema`));let o=JSON.stringify(e.success);if(Gs.encode(o).byteLength>Hs)return T(Z(`bound`,`The ${n} record exceeds 1 MiB`));let c=r.index?.(a)??null;return ce([ec(r.key(a),`A record key`),c===null?S(null):ec(c,`A record index`)]).pipe(I(([e,r])=>b(()=>{At(t,i,n,e,r,o)})))}))),remove:r=>y(i).pipe(_(x(e,`state`)),_(b(()=>{ke(t,i,n,r)})))})}function oe(e,n,r){let i=e.admitted.id,a=_n(dn(r.schema)),o=In(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>Vs)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=it(t,i,n,c(e));return r===void 0?D():j(u(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>Ws)throw Z(`bound`,`Page limit must be 1..64`);return Fr(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(Gs.encode(l).byteLength>Hs)throw Z(`bound`,`The ${n} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),At(t,i,n,c(r.key(e)),u,l)},remove:e=>{s(),ke(t,i,n,c(e))}})}function se(e){let n=e.admitted.id;return Object.freeze({set:(r,i)=>y(n).pipe(A(()=>x(e,`timers`)),A(()=>ec(r,`A timer key`)),A(()=>Number.isSafeInteger(i)&&i>=0?m:T(Z(`bound`,`A timer instant is invalid`))),I(e=>b(()=>{Wr(t,n,r,i),e.timersChanged=!0}))),cancel:r=>y(n).pipe(A(()=>x(e,`timers`)),I(e=>b(()=>{qt(t,n,r),e.timersChanged=!0}))),read:r=>v(n).pipe(_(x(e,`timers`)),_(b(()=>$t(t,n,r))),o(g))})}function le(n){let r=n.admitted.id,i=(i,a)=>y(r).pipe(A(()=>x(n,`attention`)),I(n=>L({try:()=>{B(i),a(),mn(t,i,e.readQueueHead(i)),n.observed.add(i)},catch:e=>e instanceof vi&&e.reason===`session_absent`?e:e instanceof H&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,n)=>{let a=q(xr,{onExcessProperty:`error`})(n);return a._tag===`Failure`?T(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!ye(t,e))throw Z(`session_absent`,`Attention Session is absent`);Un(t,e,r,a.success)})},clear:(e,n)=>ec(n,`An attention id`).pipe(_(i(e,()=>{kr(t,e,r,n)})))}}function k(e){let t=e.admitted.id;return n=>y(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 Si({reason:e instanceof H?e.cause===`conflict`?`conflict`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof H?e.message:`Session command is invalid`})}):T(new Si({reason:`closed`,message:`Extension is not granted send`}))))}function ue(r,i,a){return w(()=>{let s,c,l=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let t=ne(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=fe(i.pipe(d(bi,t),d(xi,t)))}finally{h=a,n.delete(t),p.delete(r.admitted.id)}if(He(s))throw l;return s.value},a).pipe(o(()=>{if(s===void 0)throw Error(`Extension transaction returned no exit`);return s}),ie(e=>s!==void 0&&He(s)?S(s):T(e)),A(n=>nt(n)&&c!==void 0?O(function*(){for(let e of c?.observed??[])xn(t,e);a===`request`&&c?.timersChanged===!0&&(yield*e.requestWake)}):m))})}function pe(n){let r=``;for(let i=0;i<Zn;i+=Ws){let i=gr(t,n,r);for(let n of i)mn(t,n,e.readQueueHead(n)),queueMicrotask(()=>{xn(t,n)});let a=i.at(-1);if(i.length<Ws||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=()=>{Mn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:a,revision:e.admitted.revision}),pe(e.admitted.id)};i===`own-transaction`?t.transactionSync(r):r()},catch:t=>new H(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)});return O(function*(){let t=yield*E(o);return yield*u(`shiitake_extension_stopped`).pipe(de({extensionId:e.admitted.id,reason:n,cause:r===void 0?null:ut(r),durable:nt(t)})),yield*t})}function he(e,n,r){e.status=`stopped`,e.reason=n,e.stoppedAt=Date.now();let i=()=>{Mn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:e.stoppedAt,revision:e.admitted.revision}),pe(e.admitted.id)};try{r===`own-transaction`?t.transactionSync(i):i()}catch(t){throw new H(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)}}function ge(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 B(t),h},a=a=>{i(a);let o=Vr(t,a,e.admitted.id,n)??Wa(r,r.initial);if(Gs.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=q(dn(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));Jn(t,o,e.admitted.id,n,Wa(r,l)),c.observed.add(o)}})}function ve(e){let n=new Set;return Object.freeze({collection:(t,n)=>ae(e,t,n),updateCollection:(t,n)=>oe(e,t,n),document:(t,n)=>ge(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 Ir(r,void 0)}finally{l.delete(i)}});for(let e of n)xn(t,e);return e}catch(t){if(!(t instanceof Hr))throw t;let n=t.message;throw he(e,n,`own-transaction`),new _i({reason:n})}finally{n.clear()}},observeUpdate:t=>{if(!l.has(e.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);n.add(B(t))},context:Object.freeze({manifest:e.admitted.manifest,revision:e.admitted.revision,grants:Object.freeze([...e.admitted.grants]),send:k(e),timers:se(e),attention:le(e),sessionPosition:n=>v(e.admitted.id).pipe(_(x(e,`state`)),_(b(()=>{let e=B(n);if(!ye(t,e))throw Z(`unavailable`,`Session timeline is unavailable`);return En(t,{sessionId:e})?.newestSequence??0}))),hasPendingSteer:n=>v(e.admitted.id).pipe(_(x(e,`run_tools`)),_(b(()=>Et(t,B(n.sessionId),n.workId)))),hasSuccessfulToolResult:(n,r)=>v(e.admitted.id).pipe(_(x(e,`run_tools`)),_(b(()=>Pn(t,B(n.sessionId),n.workId,r)))),observe:t=>y(e.admitted.id).pipe(o(e=>{e.observed.add(t)})),transact:t=>(e.status===`running`?ue(e,t,`request`).pipe(te):T(new _i({reason:e.reason??`Extension is stopped`}))).pipe(I(t=>{if(nt(t))return S(t.value);if(!$s(t.cause))return re(t.cause);let n=Qs(`transact`,t.cause);return F(e,n,t.cause,`own-transaction`).pipe(I(()=>T(new _i({reason:n}))))}))})})}function xe(e){let{id:n,definition:r,revision:i}=e.admitted,a=r.state.version,o=tt(t,n);if(o!==void 0&&o.version>a)throw new H(`extensions`,`conflict`,`Stored ${n} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=Gt(t,n).map(e=>({collection:e.collection,key:e.key,value:Ys(e.valueJson)}));for(let t=o.version;t<a;t+=1){let i=r.state.migrations[t];if(i===void 0)throw new H(`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 qs(`Failed ${n} state migration from ${String(t)}`,{cause:e})}}Pt(t,n);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new qs(`Migrated ${n} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new qs(`Migrated ${n} ${i.collection} record is invalid`);At(t,n,i.collection,i.key,a.success,JSON.stringify(i.value))}}Se(t,n,a,i)}function Ce(e,t,n=!1){let r=ve(e);return O(function*(){let i=yield*ot(t);e.scope=i;let a=yield*w(()=>e.admitted.definition.activate(r)).pipe(d(St,i),E);if(nt(a)){e.hooks=a.value;return}if(yield*Ye(i,a),n)return yield*T(new H(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${Gr(a.cause)}`));yield*F(e,Qs(`activation`,a.cause),a.cause,`own-transaction`)})}let R=e=>[...r.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function we(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 Te(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 E(n.pipe(d(xi,ne(e.admitted.id)))).pipe(I(n=>nt(n)?S(j(n.value)):F(e,Qs(t,n.cause),n.cause,`own-transaction`).pipe(P(D()))))}let De=(e,t,n)=>He(n)?F(e,Qs(t,n.cause),n.cause,`own-transaction`):m;function Oe(e){return L({try:()=>{t.transactionSync(()=>{xe(e);for(let[n,r]of Object.entries(e.admitted.documents))Ze(t,{extensionId:e.admitted.id,name:n,initialJson:Wa(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(A(()=>N(()=>{delete e.stateResetRequired})),P(!0),ie(t=>t instanceof H?t.cause===`state_reset_required`?(e.stateResetRequired=t,F(e,Js(t.message),sn(t),`own-transaction`).pipe(P(!1))):T(t):(t instanceof qs&&(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,Js(t instanceof Error?`migration: ${t.message}`:`migration failed`),tn(t),`own-transaction`).pipe(P(!1)))))}return O(function*(){let n=yield*Mt();function l(e,r){return O(function*(){let i=an(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(()=>{U(t,e.id)===void 0&&ct(t,e.id,U(t,`core`)??0)})},catch:()=>new H(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*Oe(o))||a?r?yield*T(new H(`extensions`,`rejected`,`Extension ${e.id} cannot start: ${o.reason??`stopped`}`)):o:(yield*L({try:()=>{t.transactionSync(()=>{Mn(t,e.id,{status:`running`,reason:null,stoppedAt:null,revision:e.revision}),pe(e.id)})},catch:()=>new H(`store`,`unavailable`,`Extension status is unavailable`)}),yield*Ce(o,n,r),o)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(i(()=>Ye(n,$e)));r.set(t.id,e)}yield*L({try:()=>{t.transactionSync(()=>{let n=Kn(t,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of n)pe(e)})},catch:()=>new H(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:e=>O(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*T(new H(`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=w(()=>_e([...o.values()].reverse(),e=>E(e.scope===void 0?m:Ye(e.scope,$e)),{concurrency:1}).pipe(A(()=>N(()=>{for(let t of e)r.has(t.id)||a.delete(t.id)})),I(Ht)));yield*O(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:w(()=>u?m:(u=!0,s)),apply:O(function*(){if(u)return yield*T(new H(`extensions`,`rejected`,`Roster transition already settled`));yield*L({try:()=>{t.transactionSync(()=>{for(let[e,n]of r)c.has(n.admitted.id)||ui(t,e);let n=Kn(t,e.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of n)pe(e)})},catch:()=>new H(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of r)c.has(t.admitted.id)||(t.scope!==void 0&&(yield*Ye(t.scope,$e)),r.delete(e),a.delete(t.admitted.id));for(let[e,t]of o)r.set(e,t);u=!0})}}),runParticipants:()=>[...r.values()].filter(Te).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...a],modulesForRun:(e,t)=>_e(R(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?S(D()):Ee(n,`moduleForRun`,w(()=>r(e))).pipe(o(s))}).pipe(o(e=>e.flatMap(me))),filesForRun:(e,t)=>O(function*(){let n=R(`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*T(new H(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*Ee(n,`filesForRun`,w(()=>r(e)));return f(i)?yield*T(new H(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...ee(i.value,()=>[])])}),promptSections:(e,t)=>O(function*(){let n=[],r=0;for(let i of R(`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*T(new H(`extensions`,`rejected`,`Extension prompt is unavailable`));let o=yield*E(vr(()=>a(e)).pipe(d(xi,ne(i.admitted.id))));if(He(o))return yield*F(i,Qs(`prompt`,o.cause),o.cause,`own-transaction`),yield*T(new H(`extensions`,`rejected`,`Extension prompt failed`));let s=Ks(o.value),c=s._tag===`Success`?s.success:[];if(r+=c.reduce((e,t)=>e+Gs.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*T(new H(`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=>R(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>R(`settled`).map(e=>({id:e.admitted.id,cursor:U(t,e.admitted.id)??0})),deliverSettled:(e,n)=>_e(R(`settled`),r=>w(()=>{let i=U(t,r.admitted.id)??0;if(n<=i)return m;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return ue(r,(o===void 0||a.length===0?m:o(a)).pipe(_(N(()=>{ct(t,r.admitted.id,n)}))),`reconcile`).pipe(I(e=>De(r,`onSettled`,e)))}),{discard:!0}),fireDueTimers:e=>O(function*(){let n=R(`timers`).map(({admitted:e})=>e.id),i=Ge(t,n,e,Ws);for(let n of i){let i=r.get(n.extensionId);if(i?.status!==`running`)continue;let a=i.hooks?.onTimer,o=yield*ue(i,w(()=>$t(t,n.extensionId,n.key)===n.dueAt?(qt(t,n.extensionId,n.key),a===void 0?m:a({key:n.key,dueAt:n.dueAt,firedAt:e})):m),`reconcile`);yield*De(i,`onTimer`,o)}return i.length===Ws}),timerWake:e=>ln(t,R(`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?j(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=Ir(()=>s(e),void 0);if(C(r)){let e=In(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=q(ei)(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=On(ei)(Ir(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?j(t):(he(n,Js(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),D())})();if(C(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)=>O(function*(){let a=r.get(t);if(a?.admitted.grants.has(`commands`)!==!0)return yield*T(new H(`extensions`,`unavailable`,`Extension is unavailable`));if(a.status!==`running`||a.hooks===void 0)return yield*T(a.stateResetRequired??new H(`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*T(new H(`contract`,`invalid`,`Extension command is unknown`));let c=e.scope===`session`?yield*L({try:()=>B(e.sessionId),catch:()=>new H(`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*T(new H(`contract`,`invalid`,`Extension command input is invalid`)):(yield*F(a,`command ${n} has no handler`,void 0,`own-transaction`),yield*T(new H(`extensions`,`unavailable`,`Extension is stopped`)));let u=l({sessionId:c,input:i});if(u._tag===`Failure`)return yield*T(new H(`contract`,`invalid`,`Extension command input is invalid`));let d=yield*ue(a,u.success(),`request`);if(nt(d))return d.value;let f=be(d.cause);if(C(f)&&!$s(d.cause))return yield*T(tc(f.value));let p=Qs(`command ${n}`,d.cause);return yield*F(a,p,d.cause,`own-transaction`),yield*T(new H(`extensions`,`unavailable`,`Extension ${t} is stopped: ${p}`))}),list:()=>[...r.values()].map(we),resume:i=>O(function*(){let a=r.get(i);return a===void 0?yield*T(new H(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*L({try:()=>{t.transactionSync(()=>{Mn(t,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),pe(a.admitted.id)})},catch:()=>new H(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*Oe(a))&&(yield*Ce(a,n)),yield*e.requestWake),we(a))}),close:Ye(n,$e)};return Object.freeze(u)})}var rc=64;function Q(e){return new H(`runtime`,`rejected`,e)}function ic(e,t,n){return t===void 0?m:O(function*(){let r=yield*L({try:()=>Ln(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`cancelled`?``:yield*_t(e,r.work),a=yield*Ce(e,r.work,n.outcome),o=n.outcome===`completed`||n.outcome===`cancelled`?void 0:yield*ir(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 ac(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?m:O(function*(){let r=yield*L({try:()=>Ln(t),catch:()=>Q(`Agent work payload is invalid`)});yield*xt(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function oc(e,t,n){return O(function*(){let r=yield*L({try:()=>Ln(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*Le(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(kn({work:{...e,recovery:As}}))}})})}function sc(e){return e===void 0?m:e.drainOutbox().pipe(p(()=>Q(`Agent reply delivery is unavailable`)))}function cc(e,t){return O(function*(){let n=yield*L({try:()=>Ln(t),catch:()=>Q(`Agent work payload is invalid`)}),i=yield*L({try:()=>Yr(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return i&&(yield*r(`shiitake_settlement_session_refused`).pipe(de({workId:t.jobId}))),i})}function lc(e,t){let n=Ln(t.job),r=Yr(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:Ae(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:On(Yn)(r.origin.extensionId),correlation:r.origin.correlation})})}function uc(e,t,n,r){return _e(r,r=>O(function*(){xn(e,r.job.queue),(yield*cc(e,r.job))||(yield*ac(e,r.job),yield*oc(e,t,r.job),yield*ic(e,n,r.job)),yield*L({try:()=>{ct(e,Bs,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function dc(e){return O(function*(){if((yield*e.watchdog.tick()).status===`busy`)return yield*T(Q(`Runtime reconciliation is already active`));let t=yield*L({try:()=>U(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(rc,r),a=yield*E(uc(e.store,e.watchdog,e.mailRoom,i.filter(({sequence:e})=>e>t))),o=yield*L({try:()=>{let t=U(e.store,`core`)??0;return i.filter(({sequence:e})=>e<=t).map(t=>lc(e.store,t))},catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(o,U(e.store,`core`)??0);let s=yield*e.extensions.fireDueTimers(Date.now());if((i.length===rc||s)&&(yield*e.requestWake),yield*sc(e.mailRoom),He(a))return yield*re(a.cause)}).pipe(p(e=>e instanceof H?e:Q(`Runtime reconciliation failed`)))}function $(e){return new H(`runtime`,`rejected`,e)}function fc(e,n,r,a){return O(function*(){if(e.hostJobs?.lane==="default")return yield*T($(`Host lane conflicts with Agent work`));let s=`open`,c,l,d=pn(!1),f=e=>N(()=>{s===`open`&&(c??=e)}),ee=w(()=>s===`open`?(s=`closing`,l=c,d.open):m).pipe(y),g={},ne={current:void 0},v=e,b,x=!1,C=w(()=>g.requestWake??T($(`Runtime host is unavailable`))),ae={current:void 0},oe=new Set,E=new Map,D={owner:e.store,isAlive:()=>S(!1),executor:{execute:t=>ue(N(()=>{let n=t.lane===e.hostJobs?.lane?{kind:`host`,lane:t.lane,jobId:t.jobId}:{kind:`session`,sessionId:t.queue,commandId:t.jobId};E.set(n.kind===`host`?`host`:`serial`,n),n.kind===`session`&&oe.add(t.queue),oi(e.store)}),()=>t.lane===e.hostJobs?.lane?ae.current?.execute(t)??T(new hi(`execution_failed`)):O(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*Ps(v,n,t,ne.current)}).pipe(se(e=>u(`configuration_apply_failed`,e)),p(()=>new hi(`execution_failed`))),()=>N(()=>{t.lane!==e.hostJobs?.lane&&oe.delete(t.queue),E.delete(t.lane===e.hostJobs?.lane?`host`:`serial`),oi(e.store)}))},wake:{recompute:()=>C.pipe(p(()=>new hi(`wake_unavailable`)))},project:t=>{Qr(e.store,t,Date.now())}},k=yield*(e.hostJobs===void 0?mi(D):mi({...D,concurrentLane:e.hostJobs.lane}).pipe(A(t=>N(()=>{ae.current=e.hostJobs?.open(t)})))).pipe(p(()=>$(`Watchdog is unavailable`))),de=()=>({core:n,extensions:[...ne.current?.runParticipants()??[]]});yield*L({try:()=>Ss(e.compaction),catch:e=>e instanceof H?e:$(`Compaction settings are unavailable`)});let j=yield*L({try:()=>at(e.storagePressure),catch:e=>e instanceof H?e:$(`Storage budget is unavailable`)}),fe=zs({owner:e.store,admitNew:j.admitNew,hostMeta:e.meta,contract:de,enqueue:(e,t)=>{let n={work:{...e,recovery:As}};k.transactional.enqueueAcceptedJob(kn(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>k.transactional.readQueueHead(e),commit:e=>w(()=>g.commit===void 0?T($(`Runtime host is unavailable`)):g.commit(e)),requestWake:C});yield*L({try:()=>{qe(e.store),U(e.store,`core`)===void 0&&e.store.transactionSync(()=>{ct(e.store,Bs,0)})},catch:()=>new H(`store`,`unavailable`,`Extension store is unavailable`)});let M=yield*nc({owner:e.store,readQueueHead:e=>k.transactional.readQueueHead(e),door:fe,admitted:r,requestWake:C});ne.current=M;let pe=dc({watchdog:k,store:e.store,extensions:M,requestWake:C,mailRoom:a}).pipe(se(f)),P=O(function*(){let t=yield*k.hasPendingWork,n=Date.now(),r=yield*L({try:()=>[U(e.store,`core`)??0,...M.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*k.readSettled(1,Math.min(...r))).length>0,o=yield*L({try:()=>M.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}}),me=yield*e.runtime.bind({reconcile:pe,pendingWork:P.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(i(()=>M.close.pipe(te))),F=w(()=>s===`open`?t(me.requestWake.pipe(ie(f)),d.await):m);return g.requestWake=F,g.commit=me.commit,yield*me.requestWake.pipe(i(()=>ce([me.close,M.close]).pipe(te))),Object.freeze({prepareConfiguration:e=>O(function*(){if(s!==`open`||x||b!==void 0)return yield*T($(`A configuration change is already pending, or the Agent is closing`));x=!0;let t=yield*oo(e.extensions).pipe(I(e=>M.stage(e)),i(()=>N(()=>{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 H?e:$(`Configuration commit failed`)}),discard:w(()=>n?m:(n=!0,x=!1,t.discard))}}),activeSessions:N(()=>[...oe]),runningWork:t=>k.read(t).pipe(o(t=>t.status===`found`?E.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`)??null:null),p(e=>new H(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:M,commit:me.commit,assertOpen:w(()=>s===`open`?m:T(new H(`runtime`,`closed`,`Shiitake is closed`))),beginClose:ee,door:fe,createSessionWithinTransaction:t=>Gn(e.store,t,j.admitNew),stageSessionGrantsWithinTransaction:(t,n)=>{si(e.store,t,n)},storage:j,recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>k.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(k.transactional.readQueueHead(e).state!==`idle`)throw new H(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof H?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>k.cancel({jobId:e,cancellationId:t}).pipe(I(e=>e.status===`recorded`||e.status===`replayed`?m:T($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>k.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>k.transactional.readQueueHead(e),requestWake:F,close:ee.pipe(_(h(me.close,{onFailure:e=>M.close.pipe(_(l===void 0?re(e):T(l))),onSuccess:()=>M.close.pipe(_(l===void 0?m:T(l)))})),le(N(()=>{s=`closed`})))})})}var pc=e({openRuntimeCore:()=>mc});function mc(e,t){return O(function*(){let n=yield*oo(e.extensions),r=yield*so([]);yield*ni(e.store);let i=yield*fc(e,r,n,t),a=Va(e,i),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:ga(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(_(Ft(e.store,t,n))),activeSessions:i.activeSessions,acceptMail:(e,n,r,a,o)=>Ha(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);v(t.postMail(e))}),o)})})}export{pa as n,mc as openRuntimeCore,ca as r,pc as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-
|
|
1
|
+
import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-CLqMVcjU.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-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-DhPnd7iW.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-
|
|
11
|
+
<link rel="modulepreload" crossorigin href="/assets/extension-hook-CvLFlxpr.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,18 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fungi.computer/grove",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
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",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@fungi.computer/agar": "0.3.
|
|
9
|
-
"@fungi.computer/approvals": "0.0
|
|
8
|
+
"@fungi.computer/agar": "0.3.1",
|
|
9
|
+
"@fungi.computer/approvals": "0.1.0",
|
|
10
10
|
"@fungi.computer/cairn": "0.1.0",
|
|
11
|
-
"@fungi.computer/caps": "0.
|
|
12
|
-
"@fungi.computer/knapsack": "0.
|
|
11
|
+
"@fungi.computer/caps": "0.3.0",
|
|
12
|
+
"@fungi.computer/knapsack": "0.3.0",
|
|
13
13
|
"@fungi.computer/maosaico": "0.1.0",
|
|
14
|
-
"@fungi.computer/parakeet": "0.
|
|
15
|
-
"@fungi.computer/shiitake": "0.
|
|
14
|
+
"@fungi.computer/parakeet": "0.3.0",
|
|
15
|
+
"@fungi.computer/shiitake": "0.4.0",
|
|
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.
|
|
29
|
+
"@fungi.computer/shiitake-extensions": "0.2.0",
|
|
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.
|
|
35
|
+
"@fungi.computer/parakeet-testing": "0.1.3",
|
|
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-DPA8RMmh.js";import{a as n,i as r}from"./base-face-Dc6wvM5e.js";import{n as i}from"./index-BJuRfQVe.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-DPA8RMmh.js";import{a as n,i as r}from"./base-face-Dc6wvM5e.js";import{t as i}from"./index-BJuRfQVe.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{$a as t,In as n,Ln as r,Rn as i,Vr as a,bn as o,c as s,hi as c,i as l,pi as u,ri as d,si as f}from"./extension-hook-DCZVg8jj.js";Object.freeze({module:n,operation:r,gate:i}),d(o),f(u(o));var p=class extends e()(`@fungi.computer/shiitake/ExtensionRead`){},m=class extends e()(`@fungi.computer/shiitake/ExtensionTx`){},h=class extends t(`ExtensionStateError`){},g=class extends t(`AdmissionError`){},_=class extends t(`ExtensionCommandError`){},v=class extends t(`ExtensionStop`){};t(`ExtensionActivationError`),f(l),f(s),c(a);export{v as a,h as i,_ as n,m as o,p as r,g as t};
|