@fungi.computer/grove 0.16.1 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/dist/assets/{Effect-DeiDqvoz.js → Effect-pxRavrBh.js} +11 -11
  2. package/dist/assets/{anthropic-messages-DQiQ4Cgh.js → anthropic-messages-CkLFXbme.js} +3 -3
  3. package/dist/assets/{azure-openai-responses-BdsogfXX.js → azure-openai-responses-BjItkyTn.js} +1 -1
  4. package/dist/assets/{base-face-BYExcFAP.js → base-face-CsIbc1by.js} +1 -1
  5. package/dist/assets/burger-BgftDtiM.js +1 -0
  6. package/dist/assets/cat-CfNEurUg.js +1 -0
  7. package/dist/assets/{classifier-shared-BCGGOIh6.js → classifier-shared-JiMD88Sh.js} +1 -1
  8. package/dist/assets/{cloudflare-workers-ai-system-one-BjlnhHlD.js → cloudflare-workers-ai-system-one-tEpgPfLW.js} +1 -1
  9. package/dist/assets/compat-CxZajpXB.js +2 -0
  10. package/dist/assets/conversation-toast-DUFOMoQ9.js +33 -0
  11. package/dist/assets/{document-EWUYmKg3.js → document-BBvRlLC3.js} +1 -1
  12. package/dist/assets/{document-BiiUDQ73.js → document-Bpcy9TTA.js} +1 -1
  13. package/dist/assets/extension-hook-Da3ATgkY.js +890 -0
  14. package/dist/assets/extensions-D2Z9guoO.js +1 -0
  15. package/dist/assets/{google-generative-ai-DZR_Ze6f.js → google-generative-ai-DJB3dC5c.js} +1 -1
  16. package/dist/assets/{google-shared-BpSgfzOZ.js → google-shared-DVq-_IDX.js} +1 -1
  17. package/dist/assets/{google-vertex-ghIH-83b.js → google-vertex-CYm5wNps.js} +1 -1
  18. package/dist/assets/index-BaCEAFz2.js +117 -0
  19. package/dist/assets/index-CIiuRnlU.css +1 -0
  20. package/dist/assets/{mistral-conversations-Dz3sIOsn.js → mistral-conversations-DDg7eeLe.js} +1 -1
  21. package/dist/assets/{mushroom-CjQXC8r7.js → mushroom-FKArpulr.js} +1 -1
  22. package/dist/assets/{node.browser-Bg-Udc28.js → node.browser-CdLsHXpS.js} +1 -1
  23. package/dist/assets/{openai-codex-responses-CsLh-FB3.js → openai-codex-responses-H7WhI66H.js} +1 -1
  24. package/dist/assets/{openai-completions-F-1Tomjo.js → openai-completions-CkqQ2fFp.js} +1 -1
  25. package/dist/assets/{openai-decisions-BMWT3gOP.js → openai-decisions-DMV8tZy4.js} +1 -1
  26. package/dist/assets/{openai-responses-CZ6dqUTL.js → openai-responses-Csql8sEY.js} +1 -1
  27. package/dist/assets/{openai-responses-shared-Btjx9mL_.js → openai-responses-shared-DAZ5Qapp.js} +1 -1
  28. package/dist/assets/{openrouter-images-D5Uqwk0h.js → openrouter-images-DFWtFOvI.js} +1 -1
  29. package/dist/assets/parakeet-BUkzxkvS.js +35 -0
  30. package/dist/assets/parakeet-conversation-D8vRtIjX.js +4 -0
  31. package/dist/assets/{pi-messages-1JTpG1Us.js → pi-messages-DoPiztqV.js} +1 -1
  32. package/dist/assets/{renderer-DOUDAFcS.js → renderer-BVZdPJB6.js} +1 -1
  33. package/dist/assets/runtime-core-U8lOfyYX.js +40 -0
  34. package/dist/assets/{system-one-shared-qsmpMW29.js → system-one-shared-D7AS4c2W.js} +1 -1
  35. package/dist/assets/{transform-messages-AGWoIDpj.js → transform-messages-CCZNew0k.js} +1 -1
  36. package/dist/assets/{typesafe-system-one-D8FWi62S.js → typesafe-system-one-Cl52u7Mq.js} +1 -1
  37. package/dist/assets/{website-conversation-kQbo5VTI.js → website-conversation-CpPJ8N_o.js} +1 -1
  38. package/dist/index.html +9 -8
  39. package/package.json +9 -9
  40. package/dist/assets/burger-Bn2ocNTG.js +0 -1
  41. package/dist/assets/cat-x9tMcsRE.js +0 -1
  42. package/dist/assets/compat-CAkhM7lX.js +0 -2
  43. package/dist/assets/conversation-toast-BLAWHMmE.js +0 -32
  44. package/dist/assets/extension-hook-BEwrceUI.js +0 -869
  45. package/dist/assets/index-BaZH2cO3.js +0 -117
  46. package/dist/assets/index-ODpmGtEN.css +0 -1
  47. package/dist/assets/parakeet-Cq96KyZe.js +0 -36
  48. package/dist/assets/parakeet-conversation-m2Bl3XXj.js +0 -4
  49. package/dist/assets/runtime-core-DDK2YKwN.js +0 -40
@@ -1 +1 @@
1
- import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{ht as n,j as r,r as i,t as a,xa as o}from"./Effect-DeiDqvoz.js";import{A as s,B as c,C as l,D as u,E as d,H as f,I as p,L as m,O as h,T as g,U as _,a as ee,c as v,d as y,f as te,g as ne,j as re,k as b,l as x,o as S,p as C,r as ie,s as w,u as ae,w as T,y as E,z as oe}from"./document-EWUYmKg3.js";import{i as D,t as se}from"./document-BiiUDQ73.js";var O=(e,t)=>{if(p(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},k=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),b(t))return n;if(d(+t))return+t;let r=t,i=e?e.labels:null,a=!g(i),o=O(e,r),s=!b(o),c=f.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return te(u,d,e[0])}return s?o:a?b(i[r])?n:i[r]:n};function A(e){return E((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function j(e,t,n,r,i,a){let o=d(e.duration)&&e.duration<=1e-11?n-c:n;t.composition&&y(t,o,1,1,_.AUTO);let s=r?new ie(r,e,t,o,!1,i,a):new w(e,t,o);return t.composition&&s.init(!0),ne(t,s),l(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=A(t),t}var M=0,ce=class extends w{constructor(e={}){super(e,null,0),++M,this.id=b(e.id)?M:e.id,this.duration=0,this.labels={};let t=e.defaults,n=m.defaults;this.defaults=t?s(t,n):n,this.composition=C(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=C(e.playbackEase,n.playbackEase);this._ease=r?ee(r):null,this.iterationDuration=0}add(e,t,n){let r=u(t),i=u(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=m.editor&&m.editor.addTimelineChild,a=n&&n.type===`Stagger`&&m.editor,o=T(n)?n:null;if(o||a){let t=S(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||m.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,b(c)||(n.id=c+`-`+l);let i=k(this,f(e,l,t,null,this));j(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;j(t,this,k(this,a),e)}}else j(e,this,k(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(b(e)||e&&b(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!b(e)&&!b(e.persist)&&(e.persist=!0);let r=m.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return b(t)?this:(t.duration=c,t.composition=oe.replace,this.add(e,t,n))}call(e,t){return b(e)||e&&!T(e)?this:(m.editor&&m.editor.addTimelineCall&&(t=m.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return b(e)||e&&!h(e)?this:(m.editor&&m.editor.addTimelineLabel&&(t=m.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=k(this,t),this)}remove(e,t){return x(S(e),this,t),this}stretch(e){let t=this.duration;if(t===re(e))return this;let n=e/t,r=this.labels;l(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return l(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),l(this,e=>e.revert,!0),ae(this)}then(e){return super.then(e)}},le=e=>m.editor?m.editor.addTimeline(e):new ce(e).init(),N=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),I=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),P(),F());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),R=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),z=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),R());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(I());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),L(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(N(),P(),F(),I(),L(),R(),z(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=D(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}seek(e){if(X(e,`timeMs`),e<0)throw RangeError(`timeMs must be nonnegative`);this.pause(!0);for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])t?.seek(e);this.dirty=!0,this.renderStill()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=D(n.color);r&&(n.color=this.palette[r]);let i=D(n.backface);i&&(n.backface=this.palette[i]);let a=D(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=le({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=v({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>r(function*(){let t=se.parse(e.document.data),r=yield*a(n(()=>e.target.ownerDocument.createElement(`canvas`)),e=>n(()=>{e.remove()}));r.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(r);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let c,l=!0,u=!1,d=()=>{l||u||c!==void 0||(c=s.requestAnimationFrame(e=>{c=void 0,p.tick(e)&&d()}))},f=()=>{u||(l?p.renderStill():d())},p=yield*a(n(()=>ye({target:r,scene:t,onInvalidate:f,maxPixels:e.maxPixels})),e=>n(()=>{e.destroy()}));yield*i(()=>n(()=>{u=!0,c!==void 0&&s.cancelAnimationFrame(c)})),p.pause(!0);let m=!1,h,g;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,r]of Object.entries(e.appearance)){let e=o().safeParse(r);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let r=JSON.stringify(n);r!==g&&(p.setPalette(n),g=r);let i=e.expression??t.defaultPresentation.expression;if(!i)throw Error(`Zdog avatar needs an expression`);let a=JSON.stringify([e.activity,i]);a!==h&&(p.present({activity:e.activity,expression:i}),h=a),m=e.timeMs!==void 0,e.timeMs!==void 0&&p.seek(e.timeMs),f()},pause(e){l=m||e,p.pause(l),l&&c!==void 0&&(s.cancelAnimationFrame(c),c=void 0),f()}}});export{be as t};
1
+ import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{ht as n,j as r,r as i,t as a,xa as o}from"./Effect-pxRavrBh.js";import{A as s,B as c,C as l,D as u,E as d,H as f,I as p,L as m,O as h,T as g,U as _,a as ee,c as v,d as y,f as te,g as ne,j as re,k as b,l as x,o as S,p as C,r as ie,s as w,u as ae,w as T,y as E,z as oe}from"./document-BBvRlLC3.js";import{i as D,t as se}from"./document-Bpcy9TTA.js";var O=(e,t)=>{if(p(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},k=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),b(t))return n;if(d(+t))return+t;let r=t,i=e?e.labels:null,a=!g(i),o=O(e,r),s=!b(o),c=f.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return te(u,d,e[0])}return s?o:a?b(i[r])?n:i[r]:n};function A(e){return E((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function j(e,t,n,r,i,a){let o=d(e.duration)&&e.duration<=1e-11?n-c:n;t.composition&&y(t,o,1,1,_.AUTO);let s=r?new ie(r,e,t,o,!1,i,a):new w(e,t,o);return t.composition&&s.init(!0),ne(t,s),l(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=A(t),t}var M=0,ce=class extends w{constructor(e={}){super(e,null,0),++M,this.id=b(e.id)?M:e.id,this.duration=0,this.labels={};let t=e.defaults,n=m.defaults;this.defaults=t?s(t,n):n,this.composition=C(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=C(e.playbackEase,n.playbackEase);this._ease=r?ee(r):null,this.iterationDuration=0}add(e,t,n){let r=u(t),i=u(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=m.editor&&m.editor.addTimelineChild,a=n&&n.type===`Stagger`&&m.editor,o=T(n)?n:null;if(o||a){let t=S(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||m.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,b(c)||(n.id=c+`-`+l);let i=k(this,f(e,l,t,null,this));j(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;j(t,this,k(this,a),e)}}else j(e,this,k(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(b(e)||e&&b(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!b(e)&&!b(e.persist)&&(e.persist=!0);let r=m.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return b(t)?this:(t.duration=c,t.composition=oe.replace,this.add(e,t,n))}call(e,t){return b(e)||e&&!T(e)?this:(m.editor&&m.editor.addTimelineCall&&(t=m.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return b(e)||e&&!h(e)?this:(m.editor&&m.editor.addTimelineLabel&&(t=m.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=k(this,t),this)}remove(e,t){return x(S(e),this,t),this}stretch(e){let t=this.duration;if(t===re(e))return this;let n=e/t,r=this.labels;l(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return l(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),l(this,e=>e.revert,!0),ae(this)}then(e){return super.then(e)}},le=e=>m.editor?m.editor.addTimeline(e):new ce(e).init(),N=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),I=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),P(),F());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),R=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),z=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),R());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(I());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),L(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),I(),B(),L(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(N(),L(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(N(),P(),F(),I(),L(),R(),z(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=D(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}seek(e){if(X(e,`timeMs`),e<0)throw RangeError(`timeMs must be nonnegative`);this.pause(!0);for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])t?.seek(e);this.dirty=!0,this.renderStill()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=D(n.color);r&&(n.color=this.palette[r]);let i=D(n.backface);i&&(n.backface=this.palette[i]);let a=D(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=le({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=v({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>r(function*(){let t=se.parse(e.document.data),r=yield*a(n(()=>e.target.ownerDocument.createElement(`canvas`)),e=>n(()=>{e.remove()}));r.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(r);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let c,l=!0,u=!1,d=()=>{l||u||c!==void 0||(c=s.requestAnimationFrame(e=>{c=void 0,p.tick(e)&&d()}))},f=()=>{u||(l?p.renderStill():d())},p=yield*a(n(()=>ye({target:r,scene:t,onInvalidate:f,maxPixels:e.maxPixels})),e=>n(()=>{e.destroy()}));yield*i(()=>n(()=>{u=!0,c!==void 0&&s.cancelAnimationFrame(c)})),p.pause(!0);let m=!1,h,g;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,r]of Object.entries(e.appearance)){let e=o().safeParse(r);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let r=JSON.stringify(n);r!==g&&(p.setPalette(n),g=r);let i=e.expression??t.defaultPresentation.expression;if(!i)throw Error(`Zdog avatar needs an expression`);let a=JSON.stringify([e.activity,i]);a!==h&&(p.present({activity:e.activity,expression:i}),h=a),m=e.timeMs!==void 0,e.timeMs!==void 0&&p.seek(e.timeMs),f()},pause(e){l=m||e,p.pause(l),l&&c!==void 0&&(s.cancelAnimationFrame(c),c=void 0),f()}}});export{be as t};
@@ -0,0 +1,40 @@
1
+ import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,Ct as n,D as r,F as i,G as a,I as o,J as s,K as c,N as l,O as u,P as d,Qr as f,R as p,St as m,V as h,Y as g,Z as _,Zi as v,_ as ee,_a as y,_t as te,a as b,ar as ne,ba as x,bt as re,c as ie,ct as ae,d as oe,da as se,dr as S,dt as ce,et as le,f as C,fa as w,ft as ue,g as T,ga as de,gt as E,h as D,ht as O,i as fe,ir as pe,j as k,lt as A,m as j,mr as me,mt as M,n as he,nr as ge,o as _e,ot as ve,p as ye,pa as N,pr as P,pt as F,qn as be,r as xe,ra as Se,rr as Ce,s as I,sr as we,st as Te,t as Ee,tr as De,tt as Oe,vt as ke,w as Ae,wa as je,wt as L,xa as R,xi as Me,xt as z,y as B}from"./Effect-pxRavrBh.js";import{$ as Ne,$i as V,$n as Pe,$r as Fe,$t as Ie,A as Le,An as Re,Ao as ze,At as Be,B as Ve,Bn as He,Bo as Ue,Br as We,Bt as Ge,C as Ke,Ci as qe,Cn as Je,Cr as Ye,Ct as Xe,D as Ze,Dn as Qe,Do as $e,Dr as et,Dt as tt,E as nt,En as rt,Eo as it,Er as at,Et as ot,F as st,Fi as H,Fn as ct,Ft as lt,G as ut,Ga as dt,Gi as U,Gn as ft,Go as pt,Gr as mt,Gt as ht,H as gt,Hi as _t,Hn as vt,Ho as yt,Ht as bt,I as xt,Ii as St,In as Ct,Ir as wt,It as Tt,J as Et,Ja as Dt,Ji as Ot,Jn as kt,Jo as At,Jr as jt,Jt as Mt,K as Nt,Ka as W,Kn as Pt,Ko as Ft,Kr as It,Kt as Lt,L as Rt,La as zt,Ln as Bt,Lo as Vt,Lr as Ht,Lt as Ut,M as Wt,Mi as Gt,Mn as Kt,Mt as qt,N as Jt,Na as Yt,Ni as Xt,Nn as Zt,Nt as Qt,O as $t,Oi as en,On as tn,Oo as nn,Or as rn,Ot as an,P as on,Pi as sn,Pn as cn,Pr as ln,Pt as un,Q as dn,Qa as fn,Qn as pn,Qr as mn,Qt as hn,R as gn,Ri as _n,Rn as vn,Ro as yn,Rt as bn,S as xn,Si as Sn,Sn as Cn,So as wn,Sr as Tn,St as En,T as Dn,Ti as On,Tn as kn,To as An,Tr as G,Tt as jn,U as Mn,Ui as Nn,Un as Pn,Uo as Fn,Ur as In,Ut as Ln,V as Rn,Va as zn,Vi as Bn,Vn,Vr as Hn,Vt as Un,W as Wn,Wa as Gn,Wn as Kn,Wo as qn,Wt as Jn,X as Yn,Xa as Xn,Xn as Zn,Xt as Qn,Y as $n,Ya as K,Yi as er,Yn as tr,Yo as nr,Yt as rr,Z as ir,Zn as ar,Zo as or,Zr as sr,Zt as cr,_ as lr,_i as ur,_n as dr,_t as fr,a as pr,aa as mr,an as hr,ar as gr,at as _r,b as vr,bi as yr,bn as br,bo as xr,bt as Sr,c as Cr,cn as q,cr as wr,ct as Tr,di as Er,dn as Dr,dr as Or,dt as kr,ea as Ar,en as jr,er as Mr,et as Nr,fi as Pr,fn as Fr,ft as Ir,g as Lr,gi as Rr,gn as zr,gt as Br,h as Vr,hi as Hr,hn as Ur,hr as Wr,ht as Gr,i as Kr,in as qr,ir as Jr,it as Yr,j as Xr,jn as Zr,jr as Qr,jt as $r,k as ei,ka as ti,ki as ni,kn as ri,ko as ii,kr as J,kt as ai,ln as oi,lt as si,mi as ci,mn as li,mr as ui,mt as di,n as fi,na as pi,ni as mi,nn as hi,nr as gi,nt as _i,o as vi,oa as yi,on as bi,or as xi,ot as Si,pn as Ci,pt as wi,q as Ti,qn as Ei,qo as Di,qr as Oi,qt as ki,r as Ai,ra as ji,rn as Mi,rr as Ni,rt as Pi,s as Fi,sn as Ii,so as Li,sr as Ri,st as zi,t as Bi,ta as Vi,tn as Hi,tr as Ui,tt as Wi,un as Gi,ut as Ki,v as qi,va as Ji,vi as Yi,vn as Xi,vt as Zi,w as Qi,wi as $i,wn as ea,wo as ta,wr as na,wt as ra,x as ia,xa as aa,xi as oa,xn as sa,xo as ca,xr as la,xt as ua,y as da,yn as fa,yt as pa,z as ma,zo as ha,zt as ga}from"./extension-hook-Da3ATgkY.js";import{a as _a,d as va,i as ya,n as ba,o as xa,r as Sa,t as Ca}from"./extensions-D2Z9guoO.js";import{t as wa}from"./text-_WthCHzw.js";import{c as Ta}from"./preload-helper-CfILh1TC.js";import{a as Ea,i as Da,r as Oa}from"./index-BaCEAFz2.js";import{n as ka,t as Aa}from"./estimate-DElUjJag.js";var ja=Dt(()=>no),Ma=Rr(ja),Na=H({id:ni,payload:Sn}),Pa=H({...Na.fields,schemas:dt(Ma)});function Fa(e){let t={};for(let[n,r]of Object.entries(e))Li(r)&&f(t,n,r);return Object.keys(t).length===0?S():P(t)}var Ia=dt(Xt(sn,Nn)).pipe(ji(W(qe),{decode:xr(),encode:wn(e=>ne(e)||e.value===void 0?S():Fa(e.value))})),La=Dt(()=>Ba),Ra=Rr(La),za={annotations:Ia,checks:Ra},Ba=_t([H({_tag:K(`Filter`),representation:Pa,annotations:Ia,aborted:Yi}),H({_tag:K(`FilterGroup`),representation:dt(Pa),annotations:Ia,checks:en(La)})]);function Y(e){return H({_tag:K(e),...za})}var Va=H({_tag:K(`Declaration`),representation:Na,annotations:Ia,typeParameters:Ma,checks:Ra}),Ha=H({_tag:K(`Suspend`),annotations:Ia,checks:_n([]),thunk:ja});function Ua(e,t){return t.pipe(ji(H({type:K(e),value:t}),{decode:ca(e=>e.value),encode:ca(t=>({type:e,value:t}))}))}var Wa=Ua(`string`,sn),Ga=Ua(`number`,Gt),Ka=H({_tag:K(`Literal`),...za,literal:_t([Wa,Ua(`number`,yr),Ua(`bigint`,ur),Ua(`boolean`,Yi)])}),qa=H({_tag:K(`UniqueSymbol`),...za,symbol:St}),Ja=H({_tag:K(`Enum`),...za,enums:Rr(_n([sn,_t([Wa,Ga])]))}),Ya=H({_tag:K(`TemplateLiteral`),...za,parts:Ma}),Xa=H({isOptional:Yi,type:ja,annotations:Ia}),Za=H({_tag:K(`Arrays`),...za,elements:Rr(Xa),rest:Ma}),Qa=H({name:_t([Wa,Ga,Ua(`symbol`,St)]),type:ja,isOptional:Yi,isMutable:Yi,annotations:Ia}),$a=H({parameter:ja,type:ja}),eo=H({_tag:K(`Objects`),...za,propertySignatures:Rr(Qa),indexSignatures:Rr($a)}),to=H({_tag:K(`Union`),...za,types:Ma,options:W(H({mode:W(On([`anyOf`,`oneOf`]))}))}),no=_t([Va,H({_tag:K(`Reference`),$ref:ni}),Ha,Y(`Null`),Y(`Undefined`),Y(`Void`),Y(`Never`),Y(`Unknown`),Y(`Any`),Y(`String`),Y(`Number`),Y(`Boolean`),Y(`BigInt`),Y(`Symbol`),Y(`ObjectKeyword`),Ka,qa,Ja,Ya,Za,eo,to]),ro=pi(Xn(H({representation:ja,references:Xt(sn,ja)})));function io(e){return ro(e)}function ao(e){return e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_fleet_delegations (
2
+ request_id TEXT PRIMARY KEY, input TEXT NOT NULL, mail TEXT NOT NULL,
3
+ receipt TEXT
4
+ ) STRICT`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_fleet_held_delegations (
5
+ request_id TEXT PRIMARY KEY
6
+ ) STRICT`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_fleet_undeliverable_delegations (
7
+ request_id TEXT PRIMARY KEY
8
+ ) STRICT`),e.sql.exec(`CREATE TABLE IF NOT EXISTS shiitake_fleet_settled_delegations (
9
+ request_id TEXT PRIMARY KEY
10
+ ) STRICT`),{read:t=>e.sql.exec(`SELECT delegation.input, delegation.mail,
11
+ CASE
12
+ WHEN terminal.request_id IS NOT NULL THEN 'undeliverable'
13
+ WHEN held.request_id IS NOT NULL THEN 'held'
14
+ WHEN delegation.receipt IS NOT NULL THEN 'accepted'
15
+ ELSE 'pending'
16
+ END AS state,
17
+ delegation.receipt
18
+ FROM shiitake_fleet_delegations AS delegation
19
+ LEFT JOIN shiitake_fleet_held_delegations AS held
20
+ ON held.request_id = delegation.request_id
21
+ LEFT JOIN shiitake_fleet_undeliverable_delegations AS terminal
22
+ ON terminal.request_id = delegation.request_id
23
+ WHERE delegation.request_id = ?`,t).toArray()[0],unsettled:()=>e.sql.exec(`SELECT input, mail, 'accepted' AS state, receipt
24
+ FROM shiitake_fleet_delegations AS delegation
25
+ WHERE receipt IS NOT NULL
26
+ AND NOT EXISTS (
27
+ SELECT 1 FROM shiitake_fleet_settled_delegations AS settled
28
+ WHERE settled.request_id = delegation.request_id
29
+ )
30
+ ORDER BY delegation.rowid DESC`).toArray(),recordSettled(t){e.transactionSync(()=>{if(e.sql.exec(`SELECT 1 FROM shiitake_fleet_delegations WHERE request_id = ? AND receipt IS NOT NULL`,t).toArray().length!==1)throw Error(`Cannot record settlement without acceptance`);e.sql.exec(`INSERT OR IGNORE INTO shiitake_fleet_settled_delegations(request_id) VALUES(?)`,t)})},reserve(t,n,r){e.transactionSync(()=>{e.sql.exec(`INSERT OR IGNORE INTO shiitake_fleet_delegations(request_id, input, mail) VALUES (?, ?, ?)`,t,n,r)})},recordReceipt(t,n,r,i){e.transactionSync(()=>{let a=e.sql.exec(`SELECT mail, receipt FROM shiitake_fleet_delegations WHERE request_id = ?`,t).toArray()[0];if(a===void 0)throw Error(`Cannot record acceptance without frozen delegation mail`);if(a.receipt!==null){if(a.receipt===n&&a.mail===i)return;throw Error(`Delegation acceptance conflicts with its recorded receipt`)}if(a.mail!==r)throw Error(`Delegation mail changed before acceptance was recorded`);e.sql.exec(`UPDATE shiitake_fleet_delegations SET mail = ?, receipt = ? WHERE request_id = ? AND receipt IS NULL`,i,n,t),e.sql.exec(`DELETE FROM shiitake_fleet_held_delegations WHERE request_id = ?`,t)})},recordHeld(t){e.transactionSync(()=>{e.sql.exec(`INSERT OR IGNORE INTO shiitake_fleet_held_delegations (request_id)
31
+ SELECT request_id FROM shiitake_fleet_delegations
32
+ WHERE request_id = ? AND receipt IS NULL
33
+ AND NOT EXISTS (
34
+ SELECT 1 FROM shiitake_fleet_undeliverable_delegations
35
+ WHERE request_id = ?
36
+ )`,t,t)})},recordUndeliverable(t){return e.transactionSync(()=>e.sql.exec(`SELECT delegation.request_id
37
+ FROM shiitake_fleet_delegations AS delegation
38
+ JOIN shiitake_fleet_held_delegations AS held
39
+ ON held.request_id = delegation.request_id
40
+ WHERE delegation.request_id = ? AND delegation.receipt IS NULL`,t).toArray()[0]!==void 0&&(e.sql.exec(`INSERT OR IGNORE INTO shiitake_fleet_undeliverable_delegations(request_id) VALUES (?)`,t),e.sql.exec(`DELETE FROM shiitake_fleet_held_delegations WHERE request_id = ?`,t),!0))}}}var oo=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function so(e){return e[oo]?.()}var co=0xffffffffffff,lo=(1n<<41n)-1n,uo=-1,fo;function po(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>co)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${co}`);let n=e===void 0?Math.max(t,uo):e;e===void 0&&(uo=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),fo===void 0)fo=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(fo===lo)throw RangeError(`UUIDv7 generator sequence exhausted`);fo++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(fo>>37n&15n),r[7]=Number(fo>>29n&255n),r[8]=128|Number(fo>>23n&63n),r[9]=Number(fo>>15n&255n),r[10]=Number(fo>>7n&255n),r[11]=Number((fo&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 mo(e){return yt(e,{onFailure:ee,onSuccess:()=>L})}function ho(e,t){return h(e,{onFailure:e=>D(t).pipe(b(ee(e))),onSuccess:()=>t})}function go(e,t){let n={_tag:`open`},r=r=>ho(e,t).pipe(D,B(e=>O(()=>{r.result=e,n={_tag:`closed`}}).pipe(b(r.settled.open),b(mo(e)))),m);return M(()=>{if(n._tag===`closed`)return L;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(b(M(()=>{let t=e.result;return t===void 0?ye(Error(`Agent close settlement was not recorded`)):mo(t)})))}let e={_tag:`running`,settled:Fe(!1)};return n=e,r(e)})}function _o(e,t,n){let{facts:r}=vo(e,t,n,null);return r.cancellationRequested?`cancelling`:Kn(e,t).some(e=>e.inbox!==!1&&e.waitingOn===void 0)?`waiting_on_you`:r.compaction!==null||r.retry!==null?`thinking`:r.activeTool===null?n.state===`running`&&Yn(e,t,n.jobId)?`streaming`:`thinking`:`running_tool`}function vo(e,t,n,r){let i=fr(e,t);if(n.state===`idle`)return{facts:{queue:{state:`idle`},cancellationRequested:!1,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},readProgress:()=>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},readProgress:()=>null,toolOutput:[]};let a=Zi(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:Gr(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:$n(e,t)},readProgress:()=>Ne(e,t,n.jobId),toolOutput:Nr(e,t,n.jobId)}}var yo=new WeakMap;function bo(e,t){let n=Sr(e,{sessionId:t}),r=si(n);return r.length===0?null:Aa(r).tokens}function xo(e,t,n,r=!0){let i;try{i=Xe(e.store,t)}catch(e){return Pe(`session-context.preference`,e),F(void 0)}let a=JSON.stringify(i),s=yo.get(e)??new Map;yo.set(e,s);let c=r?s.get(t):void 0,l=e.model.describe;if(c?.cursor===n&&c.preference===a){if(c.value===void 0||l===void 0)return F(c.value);let e=c.value;return l({sessionId:t,preference:i}).pipe(o(({contextWindow:i})=>{if(e.window===i)return e;let o=Object.freeze({tokens:e.tokens,window:i});return r&&s.get(t)?.cursor===n&&s.set(t,{cursor:n,preference:a,value:o}),o}),oe(t=>O(()=>(Pe(`session-context.describe`,t),e))))}let u;try{u=bo(e.store,t)}catch(e){return Pe(`session-context.figure`,e),F(void 0)}if(u===null)return r&&s.set(t,{cursor:n,preference:a,value:void 0}),F(void 0);if(l===void 0){let e=Object.freeze({tokens:u,window:null});return r&&s.set(t,{cursor:n,preference:a,value:e}),F(e)}return r&&s.set(t,{cursor:n,preference:a,value:Object.freeze({tokens:u,window:null})}),l({sessionId:t,preference:i}).pipe(o(({contextWindow:e})=>e),oe(e=>O(()=>(Pe(`session-context.describe`,e),null))),o(e=>{let i=Object.freeze({tokens:u,window:e});return r&&s.get(t)?.cursor===n&&s.set(t,{cursor:n,preference:a,value:i}),i}))}function So(e,t){return e.readQueueHead(t).pipe(B(t=>(t.state===`queued`?e.runningWork(t.jobId):F(null)).pipe(o(e=>({head:t,runningWork:e})))))}function Co(e,t,n){return So(t,n).pipe(o(({head:t,runningWork:r})=>vo(e.store,n,t,r)))}function wo(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function To(e,t,n,r,i={}){return So(t,n).pipe(B(({head:a,runningWork:o})=>(i.beforeRead?.(),Xr(e.store,n,()=>vo(e.store,n,a,o),r,()=>t.extensions.project(n),t=>({snapshot:t,context:xo(e,n,t.cursor,r?.before===void 0)}),e.createdBy))),B(({snapshot:e,context:t})=>(i.afterRead?.(),t.pipe(o(t=>wo(e,t))))))}function Eo(e,t){return z({try:()=>Object.freeze({sessionId:G(e),options:et(t)}),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Subscribe options are invalid`)})}function Do(e,t,n,r=!1,i={}){return t.assertOpen.pipe(b(To(e,t,n,{includeSandboxFailures:r},i)),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function Oo(e){return[[e],P({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function ko(e,t,n,r,i,a=!1){let s=i.kind===`live`?i.registration:void 0,c=i.kind===`live`?ir(i.progress):null,l=[],u=()=>Do(e,t,n,a,i.kind===`replay`?{beforeRead:i.checkpoint}:{afterRead:i.stamp}).pipe(o(e=>(c=ir(e.baseline.progress),l=e.baseline.toolOutput,i.kind===`replay`?[[e],S()]:Oo(e)))),d=t=>{let r=t.facts.queue,i=r.state===`running`?dn(e.store,n,r.commandId,c):null;if(i===void 0)return;let a=[];return i!==null&&(a.push({kind:`progress`,progress:i,activity:t.facts}),c={messageId:i.messageId,revision:i.revision,text:i.text.offset+i.text.append.length,thinking:i.thinking.offset+i.thinking.append.length}),(l.length!==t.toolOutput.length||l.some((e,n)=>e!==t.toolOutput[n]))&&(l=t.toolOutput,a.push({kind:`tool_output`,toolOutput:l,activity:t.facts})),a},f={after:r,delivery:i.kind,awaitSignal:i.kind===`live`};return Oi(f,r=>(s===void 0?F(void 0):r.awaitSignal?s.awaitSignal.pipe(B(e=>s.pollSignal.pipe(o(t=>t===void 0?e:kt(e,t))))):s.pollSignal).pipe(B(c=>c===`closed`?F([[],S()]):c===`reset`?u():t.assertOpen.pipe(b(Co(e,t,n)),B(f=>{if(i.kind===`replay`&&i.checkpoint(),s?.setQueued(f.facts.queue.state===`queued`),(c===`progress`||c===`activity`)&&r.delivery===`live`){let e=d(f);return e===void 0?u():(i.kind===`live`&&i.stamp(),F([[...c===`activity`?[{kind:`activity`,activity:f.facts}]:[],...e],P({...r,awaitSignal:!0})]))}return Jt(e.store,n,r.after,r.delivery,f,()=>t.extensions.project(n),a,t=>{let i=t.kind===`page`?t.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`||e.kind===`heartbeat`?[]:[e.cursor]).at(-1):void 0;return{page:t,latestCursor:i,context:t.kind===`page`&&!t.hasMore&&t.frames.some(e=>e.kind===`update`&&e.cursor!==r.after)?xo(e,n,i??null):F(void 0)}}).pipe(B(({page:e,latestCursor:t,context:n})=>{if(e.kind===`reset`)return u();i.kind===`live`&&i.stamp(),e.hasMore||(l=f.toolOutput);let a=e.hasMore?[]:d(f);if(a===void 0)return u();let s={after:t??r.after,delivery:e.hasMore?r.delivery:`live`,awaitSignal:!e.hasMore};return n.pipe(o(n=>[[...n===void 0?e.frames:e.frames.map(e=>e.kind===`update`&&e.cursor===t?Object.freeze({...e,context:n}):e),...a],i.kind===`replay`&&!e.hasMore?S():P(s)]))}))})))))}function Ao(e,t,r,i){let s=new Map,c=ze(),l=0,d=(o,l)=>M(()=>{let f=s.get(o);f===void 0&&(f={lock:mn(1),feed:void 0},s.set(o,f));let p=f;return p.lock.withPermit(n(n=>k(function*(){if(s.get(o)!==p)return yield*d(o,l);let f=p.feed;if(f===void 0){let l=yield*r.register(o).pipe(a(()=>O(()=>{s.get(o)===p&&s.delete(o)}))),d={stopped:!1},m=Zn(()=>{h()}),h=()=>{d.stopped||(d.stopped=!0,l.close(),d.producer?.interruptUnsafe(),d.heartbeat?.interruptUnsafe(),m.end(),p.feed=void 0,s.get(o)===p&&s.delete(o))};f={registration:l,frames:m,stop:h},p.feed=f;let g=yield*n(To(e,t,o,{includeSandboxFailures:!0})).pipe(a(()=>O(h)));l.setQueued(g.activity.queue.state===`queued`);let _=l.revision;d.producer=yield*u(ko(e,t,o,g.cursor??void 0,{kind:`live`,registration:l,progress:g.progress,stamp:()=>{_=l.revision}},!0).pipe(jt(e=>O(()=>{m.publish(e,_)})),oe(e=>O(()=>{m.end(e)})),j(O(h))),c,{uninterruptible:!1}).pipe(ce(i)),d.stopped||(d.heartbeat=yield*u(mt(ue(Ht).pipe(I({kind:`heartbeat`}))).pipe(jt(e=>O(()=>{m.publish(e)}))),c,{uninterruptible:!1}).pipe(ce(i)))}let m=f.frames.register(l);return{feed:f,queue:m}})))});return{acquire:(e,t)=>n(n=>M(()=>{if(l>=64)return T(new J(`runtime`,`rejected`,`Observation capacity is exhausted`));l+=1;let r=!1,i=()=>{r||(r=!0,--l)};return n(d(e,t)).pipe(o(({feed:e,queue:t})=>({feed:e,queue:Object.freeze({...t,close:()=>{i(),t.close()}})})),a(()=>O(i)))})),close:O(()=>{for(let e of s.values())e.feed?.stop();s.clear()}).pipe(b($e(c,qn)))}}function jo(e){return Oi(null,()=>e.take.pipe(o(e=>e===`closed`?[[],S()]:[[e],P(null)])))}function Mo(e,t,n,r){let i=t,a=ir(n);return e.pipe(It(e=>k(function*(){let t=e===`reset`?yield*r():e;if(t.kind===`heartbeat`)return[t];if(t.kind===`progress`){let e=a?.messageId===t.progress.messageId?a:null;if(e!==null&&e.revision>=t.progress.revision)return[];let n=e?.text??0,i=e?.thinking??0;t.progress.text.offset>n||t.progress.thinking.offset>i?t=yield*r():a={messageId:t.progress.messageId,revision:t.progress.revision,text:t.progress.text.offset+t.progress.text.append.length,thinking:t.progress.thinking.offset+t.progress.thinking.append.length}}if(t.kind===`reset`)return i=t.cursor,a=ir(t.baseline.progress),[t];if(t.kind!==`update`)return[t];let n=i===null?void 0:rt(i),o=t.cursor===null?void 0:rt(t.cursor);if(n!==void 0&&o!==void 0&&n.generation!==o.generation){let e=yield*r();return i=e.cursor,a=ir(e.baseline.progress),[e]}let s=n?.sequence??0,c=o!==void 0&&o.sequence>s?t.cursor:i,l=e=>e?.some(e=>e.sequence<=s)===!0;if(c===t.cursor&&!l(t.messages)&&!l(t.terminals)&&!t.compactions?.some(e=>Wi(e)<=s)&&!l(t.compactionNotices))return i=t.cursor,[t];let u={...t,cursor:c,messages:t.messages.filter(e=>e.sequence>s),terminals:t.terminals.filter(e=>e.sequence>s)};return t.compactions!==void 0&&(u.compactions=t.compactions.filter(e=>Wi(e)>s)),t.compactionNotices!==void 0&&(u.compactionNotices=t.compactionNotices.filter(e=>e.sequence>s)),i=u.cursor,[u]})),In)}function No(e,t,n,r,i){return sr(t.assertOpen.pipe(b(Eo(r,i)),B(r=>Ee(n.acquire(r.sessionId,r.options.includeSandboxFailures===!0),({queue:e})=>O(e.close)).pipe(o(({feed:n,queue:i})=>{let a=()=>{i.checkpoint(n.registration.revision)};return Mo(ko(e,t,r.sessionId,r.options.after,{kind:`replay`,checkpoint:a},r.options.includeSandboxFailures===!0).pipe(We(jo(i))),r.options.after??null,null,()=>Do(e,t,r.sessionId,r.options.includeSandboxFailures===!0,{beforeRead:a}))})))))}function Po(e,t){return z({try:()=>Object.freeze({sessionId:G(e),options:Tn(t)}),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Watch options are invalid`)})}function Fo(e,t,r,i,s){return t.assertOpen.pipe(b(Po(i,s)),B(i=>n(n=>k(function*(){let{feed:s,queue:c}=yield*r.acquire(i.sessionId,i.options.includeSandboxFailures===!0),l=()=>{c.checkpoint(s.registration.revision)};return yield*n(t.assertOpen.pipe(b(To(e,t,i.sessionId,i.options,{beforeRead:l})),o(n=>Object.freeze({snapshot:n,changes:Mo(jo(c),n.cursor,n.progress,()=>Do(e,t,i.sessionId,i.options.includeSandboxFailures===!0,{beforeRead:l})).pipe(Hn(O(c.close))),close:O(c.close)})))).pipe(a(()=>O(c.close)))}))))}function Io(e,t,n,r){let i=Ao(e,t,n,r);return Object.freeze({read:(n,r)=>To(e,t,n,r),subscribe:(n,r)=>No(e,t,i,n,r),watch:(n,r)=>Fo(e,t,i,n,r),close:i.close})}function Lo(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(b(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(b(e.extensions.call({scope:`agent`},t,n,r)))})}function Ro(e,t,n){return e.assertOpen.pipe(b(z({try:()=>n(G(t)),catch:e=>e instanceof J?e:new J(`store`,`rejected`,`Session owner operation failed`)})))}function zo(e,t){return z({try:()=>{let n=Ye(t);if(n._tag===`Failure`)throw new J(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:G(e),command:n.success})},catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Session command is invalid`)})}function Bo(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(b(e.door.admit(o)),B(e=>e.status===`accepted`?F({status:`accepted`,commandId:e.commandId}):T(new J(`runtime`,`unavailable`,`Session command was not admitted`))))}function Vo(e,t,n,r,i){return t.assertOpen.pipe(b(Ro(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&zi(e.store,t,r.commandId,Br(e.store,e.meta.identityPath,i))})),b(vr(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),B(e=>e===void 0?F({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(I({status:`accepted`,commandId:e.accepted.commandId}))))}function Ho(e,t,n,r){return t.assertOpen.pipe(b(t.commit(Lr(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),B(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function Uo(e,t,n,r){return t.assertOpen.pipe(b(da(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),I(void 0))}function Wo(e,t,n,r){return t.assertOpen.pipe(b(Qi(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function Go(e,t,n,r,i){return t.assertOpen.pipe(b(zo(n,i)),B(t=>Ko(e,r).pipe(o(e=>({...t,checked:e})))),B(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Bo(t,n,r,i);case`abort`:return Ho(e,t,n,i).pipe(I(void 0));case`cancel`:return Vo(e,t,n,r,i);case`branch`:return Uo(e,t,n,r);case`fork`:return Wo(e,t,n,r);case`operator`:return t.assertOpen.pipe(b(Ve(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),I(void 0));case`title`:return t.commit(Ro(t,n,t=>{ot(e.store,t,r.title)})).pipe(E(()=>O(()=>{ar(e.store)})),I(void 0))}}))}function Ko(e,t){return z({try:()=>t===void 0?void 0:gi(e.meta,t),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Host metadata is invalid`)})}function qo(e,t,n){let r=tr(e.store),i=Io(e,t,r,n),a=(n,a)=>{function s(r){return Go(e,t,n,a,r)}return Object.freeze({command:s,withdraw:e=>t.assertOpen.pipe(b(t.door.withdraw(n,e))),abort:s({type:`abort`}),send:(e,t)=>O(()=>t?.requestId??Hr()).pipe(B(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return s(t?.images===void 0?r:{...r,images:t.images}).pipe(p(e=>e.requestId===n?e:new J(e.boundary,e.cause,e.message,n)))})),cancel:e=>s({type:`cancel`,...e}),latestPending:Ro(t,n,t=>_i(e.store,t,e.meta?.identityPath===void 0||a===void 0?void 0:Br(e.store,e.meta.identityPath,a))),modelPreference:Object.freeze({read:Ro(t,n,t=>Xe(e.store,t)),set:r=>z({try:()=>Qr(r),catch:()=>new J(`contract`,`invalid`,`Model preference is invalid`)}).pipe(B(r=>t.commit(Ro(t,n,t=>(jn(e.store,t,r),t))).pipe(E(t=>O(()=>{pn(e.store,t)})),ie)))}),extension:e=>Object.freeze({call:(r,i,a)=>t.assertOpen.pipe(b(t.extensions.call({scope:`session`,sessionId:n},e,r,i,a)))}),read:e=>t.assertOpen.pipe(b(i.read(n,e))),readSettlement:(i,a=0)=>A(k(function*(){yield*t.assertOpen;let s=yield*z({try:()=>({sessionId:G(n),...rn(at({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*Ee(r.register(s.sessionId,`settlement`),e=>O(e.close)),l=ei(e.store,s.sessionId,s.commandId),u=yield*l;return u!==void 0||s.timeoutMs===0?u:yield*k(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*T(new J(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(ke(s.timeoutMs),o(pe))})),subscribe:e=>i.subscribe(n,e),watch:e=>i.watch(n,e)})},s=Object.freeze({createSession:n=>t.assertOpen.pipe(b(ia(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(b(Ke(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(b(Wt(e.store,n))),extensions:Lo(t),session:e=>a(e,void 0),close:t.beginClose.pipe(b(i.close),b(r.close))});return Object.freeze({...s,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>Ro(t,n,t=>e.store.transactionSync(()=>lt(e.store,t,r))),read:n=>Ro(t,n,t=>Tt(e.store,t))}),withMeta:e=>Object.freeze({...s,session:t=>a(t,e)})})}function Jo(e){let t=Er.safeParse(e.meta);return t.success&&t.data.delegation?.steer===!0}function Yo(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(Bt(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 e.recordCreatedSessionDelegatorWithinTransaction(o,c),{status:`accepted`,commandId:u.commandId,sessionId:o}})}return Bo(e,t.to.sessionId,{requestId:t.key,delivery:r!==void 0||Jo(t)?`steer`:`followUp`,type:`prompt`,text:t.content},n,t,r)}var Xo=H({fork:On([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:oa.pipe(U(Ji(0)),U(ti(2**53-1)))});function Zo(e,t){let n=mr(e.schema)(t);if(n._tag===`Failure`)throw new ya({reason:`encode`,message:`Session document does not match its schema`});let r=V(Ni)(n.success);if(r._tag===`Failure`)throw new ya({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 ya({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function Qo(e){return{...Ar(Xo)(e),schema:io(fn(e.schema)),initial:Zo(e,e.initial)}}var $o=64,es=On([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),ts=Rr(es).pipe(U(Yt(10))),ns=H({protocol:$i(`shiitake.extension/v0`),id:vi,version:Cr,requests:ts}),rs=Rr(H({id:vi,capabilities:ts,grantKey:W(vi)})).pipe(U(Yt($o))),is=sn.pipe(U(zn(/^[a-z][A-Za-z0-9_]{0,63}$/u))),as=V(ns,{onExcessProperty:`error`}),os=V(rs,{onExcessProperty:`error`}),ss=V(is);function X(e){return new J(`extensions`,`invalid`,e)}function cs(e){return new Set(e).size!==e.length}function ls(e){return JSON.stringify(e,(e,t)=>Me(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function us(e){return re({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 J(`extensions`,`rejected`,`Extension digest failed`)})}function ds(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:io(fn(t.input)),output:io(fn(t.output))}])),projection:r.projection===null?null:io(fn(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,io(fn(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Qo(t)]))};return o===void 0?c:{...c,catalog:o}}function fs(e){if(as(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(cs(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`||ss(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 ps(e){return k(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*z({try:()=>{if(t.length>$o)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=so(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(ss(e)._tag===`Failure`)throw X(`Session document name is invalid`);Qo(t)}let r=fs(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(cs(e.map(({manifest:e})=>e.id)))throw new J(`extensions`,`conflict`,`Extension identities conflict`);let r=os(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(cs(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||cs(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 J(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new J(`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 J?e:X(`Extension roster is invalid`)});return yield*Ae(r,e=>k(function*(){let t=`sha256:${yield*us(yield*z({try:()=>ls(ds(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*us(ls([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:Ar(Fi)(t),fingerprint:Ar(pr)(r)})}))})}function ms(e){return us(ls({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}function hs(e){return new J(`model`,`rejected`,e)}function gs(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 _s(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 vs(e,t,n){let r=ht(),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)Lt(t,r);return r}function ys(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 bs(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`&&!ys(e,a+1,n,i)&&r.push(a)}return r}function xs(e,t,n,r){let i=bs(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=ka(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function Ss(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 Cs(e,t,n,r){let i=xs(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...Ss(e,t,i)}}function ws(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=Ln(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=Aa(_s(e)).tokens,s=Cs(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=vs(u,e,r);for(let e of d)Lt(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 Ts={enabled:!0,maxRetries:3,baseDelayMs:2e3};function Es(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??po()};return Or(()=>Promise.resolve((r??Wr)(e,Ta(t),i)).then(e=>e.result()),Ts,i.signal)}function Ds(e){return{systemPrompt:ga,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function Os(e,t,n){let r=e.previousSummary??``,i=t?Un:bn,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${Mt(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function ks(e){return`# Conversation\n${Mt(e.turnPrefixMessages)}\n\n# Instructions\n${Ge}`}async function As(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await Es(e,Ds(r),o,a),c=cr(s,i);if(c!==void 0)throw Error(c);return s}function js(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):As(t,n,r,Os(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function Ms(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):As(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,ks(e),`Turn prefix summarization`,r)}function Ns(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.`:wa(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${wa(n.content)}`,i=t===void 0?n.usage:gs(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=wa(t.content),i=t.usage}let a=Jn(e.fileOps);return{summary:r+ki(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function Ps(e,t,n,r,i){return Ns(e,await js(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 Ms(e,t,n,i):void 0)}function Fs(e,t,n,r,i){return M(()=>{let a;return re({try:i=>{let o=Ps(e,t,i,r,n);return a=o,o},catch:e=>hs(e instanceof Error?e.message:String(e))}).pipe(s(()=>{let e=a;return e===void 0||i===void 0?L:_(()=>new Promise(t=>{let n=setTimeout(()=>{t(!1)},i.graceMs),r=()=>{clearTimeout(n),t(!0)};e.then(r,r)})).pipe(B(e=>e?L:i.onUndrained))}))})}function Is(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var Ls=new WeakMap;function Rs(e){return Ls.has(e)}function zs(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return it(t,O(()=>{Vs(e,r)})).pipe(b(u(i,t)),o(t=>(r.fiber=t,Ls.set(e,r),r)))}function Bs(e){let t=e.summary;return e.summary=void 0,t}function Vs(e,t){t.fiber=void 0,t.summary=void 0,Ls.get(e)===t&&Ls.delete(e)}function Hs(e){return new J(`runtime`,`rejected`,e)}var Us={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`},Ws=class extends J{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,Us[e]),this.phase=e,this.usage=t}get diagnostic(){return Us[this.phase]}};function Gs(e,t){let n=$r(e,t),r=ai(e),i=[];for(let t of e){let e=ea(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:sa(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:Je(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 Ks(e,t,n){return z({try:()=>Sr(e,{sessionId:t,workId:n}),catch:()=>Hs(`Woodstock selected lineage is unavailable`)})}function qs(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return si([...e,i],r).reduce((e,t)=>e+ka(t),0)}function Js(e,t,n,r){return z({try:()=>Si(e.store,{sessionId:e.sessionId,workId:e.workId,trigger:n.trigger,resumesRun:n.resumesRun,head:t.firstKeptEntryId,contextRevision:r,summary:t.summary,tokensBefore:t.tokensBefore,usage:t.usage,details:t.details}),catch:e=>e instanceof J?e:Hs(`Woodstock compaction checkpoint append failed`)})}function Ys(e,t,n,r){let i={summary:n.summary,firstKeptEntryId:n.head,tokensBefore:n.tokensBefore,usage:n.usage,details:n.details},a=t.findIndex(({id:e})=>e===n.contextRevision),o=a<0?void 0:ws(Gs(t.slice(0,a+1),e.workId),e.settings);return o?.firstKeptEntryId===n.head?hc(e,o,i,n.contextRevision).pipe(B(t=>t===void 0?F(void 0):gc(e,t,r))):pc(e,i,`stale`)}function Xs(e,t,n){return M(()=>(Ti(e.store,e.sessionId,n.trigger),Zs(e,t,n).pipe(j(O(()=>{Et(e.store,e.sessionId)})))))}function Zs(e,t,n){return k(function*(){let r=ws(Gs(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*Fs(r,e.model,e.stream,n.instructions,e.cleanup),o=yield*Js(e,a,n,i.id),s=yield*ec(e,r,a,i.id);return yield*rc(e,[...t,o],a,n,i.id,s)})}var Qs=_t([H({type:$i(`accepted`),receipt:br}),H({type:$i(`discarded_by_policy`)})]),$s=V(Qs);function ec(e,t,n,r){return e.handoff===void 0?F(void 0):e.handoff.consume(Is(t,n,e.sessionId,r)).pipe(s(()=>e.cleanup?.onUndrained??L),p(()=>new Ws(`handoff`,n.usage)),B(e=>{let t=$s(e);return t._tag===`Failure`?T(new Ws(`handoffResult`,n.usage)):F(t.success.type===`accepted`?t.success.receipt:void 0)}))}function tc(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=qs(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[bt(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 nc(e,t,n){let r=[...t,n];return{path:r,messages:si(r,e.workId)}}function rc(e,t,n,r,i,a){let s=tc(e,t,n,r,i,a);return s===void 0?F(void 0):z({try:()=>qi(e.store,s),catch:e=>e instanceof J?e.cause===`conflict`?new Ws(`conflict`):e:Hs(`Woodstock compaction append failed`)}).pipe(o(n=>nc(e,t,n)))}function ic(e){return e instanceof Ws?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function ac(e,t){return z({try:()=>{lr(e.store,t)},catch:e=>e instanceof J?e:Hs(`Compaction notice could not be recorded`)})}function oc(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return ac(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:ic(n),usage:n instanceof Ws?n.usage:void 0})}function sc(e,t,n){return Oe(Xs(e,t,n)).pipe(B(t=>t._tag===`Success`?F(t.success):oc(e,n.trigger,t.failure).pipe(I(void 0))))}var cc={trigger:`threshold`,resumesRun:!1};function lc(e,t,n,r){return t.stopped||Rs(e.store)||!Qn(n,e.model.contextWindow,e.settings)?L:r.pipe(B(n=>uc(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function uc(e,t,n){let r=n.at(-1),i=ws(Gs(n,e.workId),e.settings);return r===void 0||i===void 0?F(void 0):zs(e.store,t,t=>dc(e,i,r.id,t))}function dc(e,t,n,r){return M(()=>(Ti(e.store,e.sessionId,`threshold`),Fs(t,e.model,e.stream,void 0,e.cleanup).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),j(O(()=>{Et(e.store,e.sessionId)})))))}function fc(e,t,n,r){return M(()=>{let i=t.recovered;if(i!==void 0&&t.slot===void 0)return t.recovered=void 0,Ks(e.store,e.sessionId,e.workId).pipe(B(t=>Ys(e,t,i,n)),Oe,B(n=>n._tag===`Success`?F(n.success):(t.stopped=!0,oc(e,i.trigger,n.failure).pipe(I(void 0)))));let a=t.slot,o=a?.fiber;return a===void 0||o===void 0||!r&&o.pollUnsafe()===void 0?F(void 0):(t.slot=void 0,Oe(mi(o).pipe(B(()=>mc(e,a)),B(t=>t===void 0?F(void 0):gc(e,t,n)))).pipe(B(n=>n._tag===`Success`&&n.success!==void 0?F(n.success):(t.stopped=!0,n._tag===`Success`?F(void 0):oc(e,`threshold`,n.failure).pipe(I(void 0)))),j(O(()=>{Vs(e.store,a)}))))})}function pc(e,t,n){return ac(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(I(void 0))}function mc(e,t){let n=Bs(t);if(n===void 0)return F(void 0);let{result:r,selectionTail:i}=n;return Js(e,r,cc,i).pipe(B(()=>hc(e,n.preparation,r,i)),j(O(()=>{Vs(e.store,t)})))}function hc(e,t,n,r){return z({try:()=>Ki(e.store,{sessionId:e.sessionId,head:n.firstKeptEntryId}),catch:e=>e instanceof J?e:Hs(`Woodstock compaction head is unavailable`)}).pipe(B(i=>i===`stale`?pc(e,n,`stale`):ec(e,t,n,r).pipe(o(e=>({result:n,selectionTail:r,receipt:e})))))}function gc(e,t,n){return Ks(e.store,e.sessionId,e.workId).pipe(B(r=>{let i=tc(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?F(void 0):rr(i.tokensAfter,e.model.contextWindow,e.settings)?pc(e,t.result,`insufficient`):z({try:()=>Ze(e.store,i),catch:e=>e instanceof J?e.cause===`conflict`?new Ws(`conflict`):e:Hs(`Woodstock compaction append failed`)}).pipe(B(n=>n===`stale`?pc(e,t.result,`stale`):F(nc(e,r,n))))}))}function _c(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return F(n);if(t.recovered!==void 0)return fc(e,t,cc,!0).pipe(B(n=>n===void 0?_c(e,t):F(n)));let r=Aa(e.messages).tokens;return rr(r,e.model.contextWindow,e.settings)?sc(e,e.path,cc).pipe(o(e=>e??n)):lc(e,t,r,F(e.path)).pipe(I(n))}function vc(e,t){let n=xi(e.message,t.contextWindow),r=ui(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function yc(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function bc(e,t,n,r){if(!e.settings.enabled)return F(void 0);let i=rr(Aa([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?Ks(e.store,e.sessionId,e.workId):F(void 0)}function xc(e,t,n){return(r,i)=>k(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=Aa(r).tokens,s=rr(o,e.model.contextWindow,e.settings),c=yield*fc(e,n,cc,s);if(c!==void 0)return a(c);let l=Ks(e.store,e.sessionId,e.workId);if(!s){yield*lc(e,n,o,l);return}let u=yield*sc(e,yield*l,cc);return u===void 0?void 0:a(u)})}function Sc(e,t,n){return k(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,xc(e,t,n)),o=vc(a,e.model),s=o.retry&&!i,c=yield*fc(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:yc(c.messages)},i=!0;continue}let l=yield*bc(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*sc(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:yc(u.messages)},i=!0}})}function Cc(e){return k(function*(){let t={scope:yield*ae,slot:void 0,stopped:!1,recovered:tt(e.path)};return yield*Sc(e,e.settings.enabled?yield*_c(e,t):e,t)})}function wc(e){if(e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId))return F(`compacted`);let t={trigger:`manual`,resumesRun:!1},n=tt(e.path);return n?.workId===e.workId?Ys(e,e.path,n,t).pipe(te(t=>oc(e,`manual`,t)),B(t=>t===void 0?oc(e,`manual`,void 0).pipe(I(`nothing_to_compact`)):F(`compacted`))):Xs(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(te(t=>oc(e,`manual`,t)),B(t=>t===void 0?oc(e,`manual`,void 0).pipe(I(`nothing_to_compact`)):F(`compacted`)))}var Tc=oa.pipe(U(aa(0)),U(ti(2**53-1))),Ec=H({reserveTokens:W(Tc),keepRecentTokens:W(Tc),backgroundTokens:W(Tc)}),Dc=H({enabled:W(Yi),reserveTokens:W(Tc),keepRecentTokens:W(Tc),backgroundTokens:W(Tc),modelOverrides:W(Xt(sn,Ec))}),Oc=V(Dc,{onExcessProperty:`error`});function kc(e){let t=Oc(e??{});if(t._tag===`Failure`)throw new J(`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??Ut.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??Ut.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??Ut.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??Ut.backgroundTokens}}}function Ac(e,t){let n=!1;return()=>k(function*(){if(n)return[];let r=yield*z({try:()=>Zr(e,t.command.sessionId,t.command.entry.workId),catch:()=>new J(`store`,`unavailable`,`Work sender is unavailable`)});return r===void 0||(yield*st(e,{sessionId:t.command.sessionId,commandFactId:t.command.id}))!==``?[]:(n=!0,[{role:`user`,content:`Your turn ended without a reply to ${r.name}. Reply now with your result in at most 5 lines.`,timestamp:Date.now()}])}).pipe(p(()=>({_tag:`MuleError`,phase:`control`,message:`Delegated reply state is unavailable`})))}var jc=1e3;function Mc(e,t,n,i){return k(function*(){let a=yield*r(n);(yield*le(mi(a).pipe(I(!0)),ue(1e3).pipe(I(!1))))||(i.released=!1,yield*d(`shiitake_run_finalizer_hung`).pipe(_e({workId:t,finalizer:e})))})}function Nc(e,t,n){return Oa(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference}).pipe(o(e=>({...e,release:Mc(`model`,t.command.entry.workId,e.release,n)}))))}var Pc={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},Fc=class extends J{phase;constructor(e){super(`runtime`,`rejected`,Pc[e]),this.phase=e}get diagnostic(){return Pc[this.phase]}},Ic={model:`model-failed`,tool:`tool-failed`,control:`control-failed`,listener:`listener-failed`},Lc=class extends J{reason;constructor(e,t){super(`runtime`,`rejected`,`Mule rejected the durable command run`,void 0,t),this.reason=e}get diagnostic(){return Ic[this.reason]}};function Rc(e){return new Lc(e.phase,e)}function zc(e,n,r,i,a,o,s,c){let l=e.tools,u=a.modules??[],d=[...u,...o];return l===void 0?u.length>0||s.length>0?T(new Fc(`missing`)):F([]):k(function*(){let a={sessionId:n,commandId:r};i!==void 0&&(a={...a,meta:i});let o={sources:l.sources,session:a,sandbox:l.sandbox,onSandboxFailure:t=>Rn(e.store,{sessionId:n,commandId:r},t).pipe(g),modules:[...l.modules,...d],tools:s,access:{...l.access,sessionGrants:()=>Tt(e.store,n)?.grants??{}}},u=yield*ii();yield*xe(()=>Mc(`tools`,r,$e(u,Fn(void 0)),c));let f=yield*(yield*gr(l.execution===void 0?o:{...o,execution:l.execution}).pipe(t(An,u),p(()=>new Fc(`runtime`)))).acquire().pipe(t(An,u),p(()=>new Fc(`lease`)));return[f.executeTool,...f.tools]})}function Bc(e,t,n,r,i,a,l,u){return A(k(function*(){let d=yield*e.instructions.load({track:e=>{l.pending.push(e)},sessionId:t.command.sessionId,commandId:t.command.entry.workId}),f=d.release;f!==void 0&&(yield*xe(()=>Mc(`instructions`,t.command.entry.workId,O(f),l)));let m=yield*Nc(e,t,l),h=yield*zc(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,d,r,i,l),g=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),_=yield*nt(e.store,g,n,m.model,t.recoveredPartial),v=t=>Wn(e.store,{sessionId:g.sessionId,workId:g.commandId,delivery:t}).pipe(o(e=>e.map(({message:e})=>e)),p(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof J?e.message:`Session control delivery failed`}))),ee=t.resume,y=kc(e.compaction)(m.model),te,b=0,x=Ac(e.store,t);return{run:yield*Cc({cleanup:{graceMs:jc,onUndrained:O(()=>{l.released=!1})},store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:m.model,stream:m.stream,handoff:a,settings:y,path:t.path,messages:t.messages,resuming:ee!==void 0,run:(t,n)=>{b=0;let r=ee;ee=void 0;let i,a=e=>{if(l.isStopping()&&e.type===`run_end`&&e.outcome===`cancelled`)return L;if(e.type===`run_end`&&e.outcome===`failed`)return i=e,L;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=m.providerError?.(e.value),n=m.rejection?.(e.value);return _({...e,value:{...e.value,...t!==void 0&&{providerError:t},...n!==void 0&&{modelFailure:{provider:e.value.provider,cause:n}}}})}return _(e)},f={onUndrained:O(()=>{l.released=!1}),model:m.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??wr,retryAfterMs:m.retryAfterMs,retryable:m.retryable,systemPrompt:d.text,prepareSystemPrompt:()=>(u===void 0?F([]):u().pipe(s(()=>O(()=>{l.released=!1})))).pipe(o(e=>d.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:h,getSteeringMessages:()=>v(`steer`),getFollowUpMessages:x,prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(p(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>l.isStopping()&&t.type===`retry_finished`&&!t.success?L:(t.type===`retry_finished`&&!t.success&&(b=t.attempt+1),ma(e.store,g,ut(t,m.model),t.turn))};return Ri.run(m.stream===void 0?f:{...f,stream:m.stream},a).pipe(c(e=>{if(i===void 0)return L;if(Ue(e)){let t=e.value.modelLimitReason??m.failureReason?.(e.value.message)??Mr(e.value);return te=(b>1&&e.value.modelLimitReason===void 0&&m.rejection?.(e.value.message)?.code!==`usage-limit-reached`?`The model failed ${String(b)} times on this conversation: ${t}`:t).slice(0,200),_(i,te)}let t=At(e.cause);return _(i,ne(t)?Ui({runId:i.run.value,provider:m.model.provider,model:m.model.id}):t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):`runtime:rejected: ${Rc(t.value).diagnostic}`)}),p(e=>e.phase===`model`?new J(`model`,`rejected`,e.message,void 0,e):Rc(e)))}}),failureReason:te}}))}function Vc(e,t,n,r){return A(k(function*(){let i=yield*Nc(e,t,r),a=t.command.entry;return yield*wc({cleanup:{graceMs:jc,onUndrained:O(()=>{r.released=!1})},store:e.store,sessionId:t.command.sessionId,workId:a.workId,model:i.model,stream:i.stream,handoff:n,settings:kc(e.compaction)(i.model),path:t.path,instructions:Cn(a)?a.instructions:void 0})}))}var Hc=R().min(1).max(256),Uc=v([`create`,`manage`,`read`,`send`,`delegate`]),Wc=w(()=>x({actor:Hc,workflowRunId:Hc.optional(),toolCallInputDigest:R().regex(/^[a-f0-9]{64}$/).optional(),session:x({agentId:Hc,sessionId:Hc}).optional()}));w(()=>x({agents:je([N(`all`),Se(Hc)]),actions:Se(Uc).max(5),expiresAt:de().int().nonnegative(),provenance:Wc,meta:se().optional(),maxDepth:de().int().min(1).max(8).optional()})),ci({family:`agent`,version:1,kinds:{agent:{prefix:`agent`}}}),w(()=>x({agent_id:R(),name:R(),actor_user_id:R(),created_by:R().min(1).max(256).nullable(),created_at:de().int().nonnegative(),updated_at:de().int().nonnegative()})),w(()=>x({request_id:R(),actor_user_id:R(),name:R(),agent_id:R(),computer_mode:R().min(1).max(4096)})),w(()=>x({name:va,requestId:R().min(1).max(256),configuration:R().min(1).max(4096),createdBy:R().min(1).max(256).nullable().optional()})),w(()=>x({name:va}));var Gc=class extends Error{status;code;constructor(e,t){super(t),this.status=e,this.code=t}};w(()=>x({requestId:Hc,agentId:Hc,sessionId:Hc.optional(),delivery:v([`followUp`,`steer`]).optional(),goal:je([R().min(1).max(4e3),N(!1)]).optional(),text:R().min(1).max(262144)}).refine(({goal:e,sessionId:t,delivery:n})=>e===void 0||t===void 0&&n!==`steer`,{path:[`goal`],error:`goal requires a new-Session follow-up`})),y({delegation:Er.shape.delegation});var Kc=w(()=>x({input:R(),mail:R(),state:v([`pending`,`held`,`accepted`,`undeliverable`]),receipt:R().nullable()})),qc=Ar(yi(Ct));function Jc(e){let t=ao(e).unsettled()[0];if(t===void 0)return;let n=Kc.parse(t),r=qc(n.mail),i=r.to.sessionId;if(i===void 0)throw new Gc(503,`partial_init`);return{agentId:r.to.agentId,sessionId:i,commandId:Vr(R().parse(n.receipt)).commandId}}var Yc=Object.freeze({maxRecoveries:2,windowMs:6e4});function Xc(e){return new J(`runtime`,`rejected`,e)}function Zc(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof Fc||e instanceof Lc||e instanceof Ws||e instanceof Yr?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function Qc(e,t){return d(`shiitake_run_failed`,ta(t)).pipe(_e({workId:e,reason:`${t.boundary}:${t.cause}`}))}function $c(e,t,n,r,i){return k(function*(){pn(e.store,n.queue);let a=yield*z({try:()=>He(n),catch:()=>Xc(`Agent work payload is invalid`)}),s=yield*Dn(e.store,a.work);if(s.abnormalTerminal!==void 0)return{kind:s.abnormalTerminal};let c=r?.incompatibleMigrations()[0];if(c!==void 0)return yield*d(`shiitake_run_contract_changed`).pipe(_e({workId:n.jobId,terminal:`contract_changed: ${c}`})),yield*T(Xc(`contract_changed: ${c}`));let l=new Set(r?.runParticipants().map(([e])=>e)??[]);if(Cn(s.command.entry))return yield*Vc(e,s,r?.compactionHandoff(l),i),yield*gt(e.store,{sessionId:s.command.sessionId,commandFactId:a.work.commandFactId,workId:s.command.entry.workId,outcome:`completed`}),{kind:`completed`};let u=yield*z({try:()=>Le(e.store,a.work.sessionId,a.work.commandFactId,s.command.entry.workId),catch:()=>Xc(`Accepted run origin is unavailable`)}),f={sessionId:s.command.sessionId,workId:s.command.entry.workId,origin:u===null?null:{extensionId:Ar(Kr)(u.extensionId),correlation:u.correlation}},p=r===void 0?[]:yield*r.filesForRun(f,l),m=r===void 0?[]:yield*Ae([...l],t=>r.modulesForRun(f,new Set([t])).pipe(B(n=>z({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>Jr.grantAs(e,r))},catch:()=>Xc(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),h=r?.compactionHandoff(l),{run:g,failureReason:_}=yield*Bc(e,s,{core:p.length===0?t:yield*ms(p.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},m,p,h,i,r===void 0?void 0:()=>r.promptSections(f,l));switch(g.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:_??Mr(g)}}}).pipe(oe(e=>Qc(n.jobId,e).pipe(I(Zc(e)))))}var el=V(Pi,{onExcessProperty:`error`}),tl=V(Bn(Yi)),nl=V(kn,{onExcessProperty:`error`});function rl(e){if(e.reply===void 0)return;let t=rn(nl(e.reply),`Verified Agent reply is invalid`),n=e.mail,r=n?.from.kind===`agent`&&n.from.agentId===t.agentId&&n.from.sessionId===t.sessionId,i=n?.from.kind===`system`&&t.outcome===`undeliverable`&&t.reason===`recipient_offline`;if(n?.replyTo.length!==0||!r&&!i||e.command.type!==`prompt`||e.command.delivery!==`steer`)throw new J(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function il(e,t,n){let r=t.mail;if(r?.from.kind===`agent`&&r.replyTo.length>0)return{agentId:r.from.agentId,sessionId:r.from.sessionId,name:Pr(t.meta)?.name??r.from.agentId};let i=t.continuesWorkId===void 0?void 0:Zr(e,t.sessionId,t.continuesWorkId);return i===void 0?t.origin.kind===`extension`?tn(e,t.sessionId,n):Qe(e,t.sessionId,n):i}function al(e){let t=t=>({sessionId:G(t.sessionId),requireExistingSession:rn(tl(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:rn(la(t.command),`Session command is invalid`),origin:rn(el(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:rl(t),onAccepted:t.onAccepted,continuesWorkId:t.continuesWorkId,meta:t.meta===void 0?void 0:gi(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(Tr(e.owner,r,a.requestId),t.requireExistingSession&&!wi(e.owner,r))throw new J(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&pa(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&pa(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested&&!Ir(e.owner,r,o.jobId)?o.jobId:void 0,c=_r(e.owner,r,a,t.meta,i,e.contract(),s===void 0?n=>{e.enqueue(n,t.mail)}:void 0,s,t.reply);if(c.delivery===`new`&&s===void 0){let n=il(e.owner,t,e.createdBy);n!==void 0&&Zt(e.owner,r,c.accepted.commandId,n)}return c.delivery===`new`&&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)=>M(()=>{let i=new Map,a=z({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof J?e:new J(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(E(()=>O(()=>{for(let[t,n]of i)n&&pn(e.owner,t)})),E(()=>i.size>0?e.requestWake:L))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>z({try:()=>({sessionId:G(t),requestId:na({requestId:n})}),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(B(t=>r(()=>an(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>z({try:()=>t(e),catch:e=>e instanceof J?e:new J(`contract`,`invalid`,`Session command is invalid`)}).pipe(B(e=>r(t=>t(e),n??`request`)))})}var ol=`core`,sl=`core-report`,cl=256,ll=1048576,ul=512,dl=64,fl=new TextEncoder,pl=V(Rr(H({name:sn.pipe(U(zn(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:sn.pipe(U(zt(1)),U(Gn(e=>fl.encode(e).byteLength<=8192)))})).pipe(U(Yt(16)))),ml=class extends Error{};function hl(e){return e.length<=ul?e:`${e.slice(0,511)}…`}var gl=er(yi(Ni));function _l(e){return e instanceof _a?e.reason:`${e._tag}: ${e.message}`}function vl(e){return e instanceof _a||e instanceof ya||e instanceof Ca||e instanceof ba}function yl(e,t){let n=At(t);if(we(n)){let t=n.value;return t instanceof _a?hl(t.reason):hl(vl(t)?`${e}: ${_l(t)}`:`${e} failed`)}let r=be(Di(t));return we(r)?r.value instanceof Error?hl(r.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${r.value.message}`):hl(`${e} defect`):hl(`${e} was interrupted`)}function bl(e){let t=At(e);return ne(t)||t.value instanceof _a}function Z(e,t){return new ya({reason:e,message:t})}function xl(e,t){return e.length>=1&&e.length<=cl?F(e):T(Z(`bound`,`${t} must be 1..256 characters`))}function Sl(e){let t=hl(e.message);if(e instanceof ba)switch(e.reason){case`invalid`:return new J(`contract`,`invalid`,t);case`conflict`:return new J(`store`,`conflict`,t);case`not_found`:return new J(`store`,`rejected`,t);case`rejected`:return new J(`extensions`,`rejected`,t)}if(e instanceof Ca)switch(e.reason){case`invalid`:return new J(`contract`,`invalid`,t);case`conflict`:return new J(`contract`,`conflict`,t);case`closed`:return new J(`runtime`,`closed`,t)}return e.reason===`bound`?new J(`contract`,`invalid`,t):new J(`store`,`unavailable`,t)}function Cl(e){let{owner:n}=e,r=new WeakMap,i=new Map,s=new Set,c,u=new Set,f=new Set,p,m=e=>Object.freeze({extensionId:e}),h=e=>B(Sa,t=>t.extensionId===e?L:ye(Error(`Extension read used another extension's context`))),_=e=>B(xa,t=>{let n=r.get(t);return n?.extensionId===e?F(n):ye(Error(`Extension write used outside its own core transaction`))}),v=e=>z({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),y=(e,t)=>e.admitted.grants.has(t)?L:T(Z(`unavailable`,`Extension is not granted ${t}`));function te(e,t,r){let i=e.admitted.id,a=Ot(yi(r.schema)),s=Vi(r.schema),l=e=>{let n=a(e);return n._tag===`Failure`?T(Z(`decode`,`Stored ${t} record is invalid`)):F(n.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=oi(n,i,t,r);if(o===void 0)return S();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return P(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>dl)throw Z(`bound`,`Page limit must be 1..64`);return Gi(n,i,t,r).map(e=>{let n=a(e);if(n._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return n.success})},get:r=>h(i).pipe(b(y(e,`state`)),b(v(()=>oi(n,i,t,r))),B(e=>e===void 0?F(S()):l(e).pipe(o(P)))),page:r=>h(i).pipe(b(y(e,`state`)),b(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=dl?L:T(Z(`bound`,`Page limit must be 1..64`))),b(v(()=>Gi(n,i,t,r))),B(e=>Ae(e,l))),put:a=>_(i).pipe(b(y(e,`state`)),b(M(()=>{let e=s(a);if(e._tag===`Failure`)return T(Z(`encode`,`The ${t} record does not match its schema`));let o=JSON.stringify(e.success);if(fl.encode(o).byteLength>ll)return T(Z(`bound`,`The ${t} record exceeds 1 MiB`));let c=r.index?.(a)??null;return fe([xl(r.key(a),`A record key`),c===null?F(null):xl(c,`A record index`)]).pipe(B(([e,r])=>v(()=>{zr(n,i,t,e,r,o)})))}))),remove:r=>_(i).pipe(b(y(e,`state`)),b(v(()=>{Mi(n,i,t,r)})))})}function x(e,t,r){let i=e.admitted.id,a=Ot(yi(r.schema)),o=Vi(r.schema),s=()=>{if(!u.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>cl)throw Z(`bound`,`A record key must be 1..256 characters`);return e},l=e=>{let n=a(e);if(n._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return n.success};return Object.freeze({get:e=>{s();let r=oi(n,i,t,c(e));return r===void 0?S():P(l(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>dl)throw Z(`bound`,`Page limit must be 1..64`);return Gi(n,i,t,e).map(l)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${t} record does not match its schema`);let l=JSON.stringify(a.success);if(fl.encode(l).byteLength>ll)throw Z(`bound`,`The ${t} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),zr(n,i,t,c(r.key(e)),u,l)},remove:e=>{s(),Mi(n,i,t,c(e))}})}function re(t){let r=t.admitted.id;return Object.freeze({set:(i,a)=>_(r).pipe(E(()=>y(t,`timers`)),E(()=>xl(i,`A timer key`)),E(()=>Number.isSafeInteger(a)&&a>=0?L:T(Z(`bound`,`A timer instant is invalid`))),B(t=>v(()=>{fa(n,e.watchdog,r,i,a),t.timersChanged=!0}))),cancel:i=>_(r).pipe(E(()=>y(t,`timers`)),B(t=>v(()=>{qr(n,e.watchdog,r,i),t.timersChanged=!0}))),read:i=>h(r).pipe(b(y(t,`timers`)),b(v(()=>Ci(n,e.watchdog,r,i))),o(ge))})}function ie(t){let r=t.admitted.id,i=(i,a)=>_(r).pipe(E(()=>y(t,`attention`)),B(t=>z({try:()=>{G(i),a(),qt(n,i,e.readQueueHead(i)),t.observed.add(i)},catch:e=>e instanceof ya&&e.reason===`session_absent`?e:e instanceof J&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,t)=>{let a=V(ln,{onExcessProperty:`error`})(t.waitingOn===void 0?t:{...t,inbox:!1});return a._tag===`Failure`?T(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!wi(n,e))throw Z(`session_absent`,`Attention Session is absent`);Pt(n,e,r,a.success)})},awaitsDecision:e=>h(r).pipe(E(()=>y(t,`attention`)),b(v(()=>vt(n,e)))),clear:(e,t)=>xl(t,`An attention id`).pipe(b(i(e,()=>{Vn(n,e,r,t)})))}}function ae(e){let t=e.admitted.id;return n=>_(t).pipe(B(r=>e.admitted.grants.has(`send`)?z({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},continuesWorkId:n.continuesWorkId});return i.status===`accepted`?{_tag:`Accepted`,commandId:i.commandId,delivery:i.delivery}:{_tag:`NotReady`}},catch:e=>new Ca({reason:e instanceof J?e.cause===`conflict`?`conflict`:e.cause===`archived`?`archived`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof J?e.message:`Session command is invalid`})}):T(new Ca({reason:`closed`,message:`Extension is not granted send`}))))}function se(i,a,s){return M(()=>{let c,l,u=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let n=m(i.admitted.id);l={extensionId:i.admitted.id,admit:e,observed:new Set,timersChanged:!1},r.set(n,l),f.add(i.admitted.id);let o=p;p=l;try{c=Te(a.pipe(t(xa,n),t(Sa,n)))}finally{p=o,r.delete(n),f.delete(i.admitted.id)}if(ha(c))throw u;return c.value},s).pipe(o(()=>{if(c===void 0)throw Error(`Extension transaction returned no exit`);return c}),oe(e=>c!==void 0&&ha(c)?F(c):T(e)),E(t=>Ue(t)&&l!==void 0?k(function*(){for(let e of l?.observed??[])pn(n,e);s===`request`&&l?.timersChanged===!0&&(yield*e.requestWake)}):L))})}function ce(e,n,r){return l(n)?se(e,n,r):D(n.prepare.pipe(t(Sa,m(e.admitted.id)))).pipe(B(t=>ha(t)?F(yn(t.cause)):e.status===`running`?se(e,t.value,r):T(new J(`extensions`,`unavailable`,`Extension is stopped`))))}function le(t){let r=``;for(let i=0;i<wt;i+=dl){let i=Pn(n,t,r);for(let t of i)qt(n,t,e.readQueueHead(t)),queueMicrotask(()=>{pn(n,t)});let a=i.at(-1);if(i.length<dl||a===void 0)return;r=a}}function C(t,r,i,a){let o=Date.now();t.status=`stopped`,t.reason=r,t.stoppedAt=o;let s=z({try:()=>{let i=()=>{Xi(n,t.admitted.id,{status:`stopped`,reason:r,stoppedAt:o,revision:t.admitted.revision}),jr(n,e.watchdog,t.admitted.id),le(t.admitted.id)};a===`own-transaction`?n.transactionSync(i):i()},catch:e=>new J(`store`,`unavailable`,`Extension ${t.admitted.id} stop status is unavailable`,void 0,e)});return k(function*(){let e=yield*D(s);return yield*d(`shiitake_extension_stopped`).pipe(_e({extensionId:t.admitted.id,reason:r,cause:i===void 0?null:ta(i),durable:Ue(e)})),yield*e})}function w(t,r,i){t.status=`stopped`,t.reason=r,t.stoppedAt=Date.now();let a=()=>{Xi(n,t.admitted.id,{status:`stopped`,reason:r,stoppedAt:t.stoppedAt,revision:t.admitted.revision}),jr(n,e.watchdog,t.admitted.id),le(t.admitted.id)};try{i===`own-transaction`?n.transactionSync(a):a()}catch(e){throw new J(`store`,`unavailable`,`Extension ${t.admitted.id} stop status is unavailable`,void 0,e)}}function ue(e,t,r){let i=t=>{if(p?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return G(t),p},a=a=>{i(a);let o=ua(n,a,e.admitted.id,t)??Zo(r,r.initial);if(fl.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=V(yi(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));Be(n,o,e.admitted.id,t,Zo(r,l)),c.observed.add(o)}})}function de(t){let r=new Set;return Object.freeze({collection:(e,n)=>te(t,e,n),updateCollection:(e,n)=>x(t,e,n),document:(e,n)=>ue(t,e,n),update:e=>{let i=t.admitted.id;if(t.status!==`running`||!t.admitted.grants.has(`state`)||u.has(i)||f.has(i)||c===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let t=n.transactionSync(()=>{u.add(i);try{return Ai(e,void 0)}finally{u.delete(i)}});for(let e of r)pn(n,e);return t}catch(e){if(!(e instanceof Bi))throw e;let n=e.message;throw w(t,n,`own-transaction`),new _a({reason:n})}finally{r.clear()}},observeUpdate:e=>{if(!u.has(t.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);r.add(G(e))},context:Object.freeze({manifest:t.admitted.manifest,revision:t.admitted.revision,grants:Object.freeze([...t.admitted.grants]),send:ae(t),timers:re(t),attention:ie(t),isObserved:e=>t.status===`running`&&Ei(n,e),sessionPosition:e=>h(t.admitted.id).pipe(b(y(t,`state`)),b(v(()=>{let t=G(e);if(!wi(n,t))throw Z(`unavailable`,`Session timeline is unavailable`);return En(n,{sessionId:t})?.newestSequence??0}))),hasPendingSteer:e=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>kr(n,G(e.sessionId),e.workId)))),workSender:e=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>Zr(n,G(e.sessionId),e.workId)??null))),sessionParent:r=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>tn(n,G(r),e.createdBy)??null))),sessionMaker:r=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>Qe(n,G(r),e.createdBy)??null))),recipientStatus:n=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(e.recipientStatus?.(n)??F(`unknown`))),recipientParent:n=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(e.recipientParent?.(n)??T(Z(`unavailable`,`Recipient parent is unavailable`)))),hasSuccessfulToolResult:(e,r)=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>di(n,G(e.sessionId),e.workId,r)))),observe:e=>_(t.admitted.id).pipe(o(t=>{t.observed.add(e)})),transact:e=>(t.status===`running`?ce(t,e,`request`).pipe(g):T(new _a({reason:t.reason??`Extension is stopped`}))).pipe(B(e=>{if(Ue(e))return F(e.value);if(!bl(e.cause))return ee(e.cause);let n=yl(`transact`,e.cause);return C(t,n,e.cause,`own-transaction`).pipe(B(()=>T(new _a({reason:n}))))}))})})}function pe(e){let{id:t,definition:r,revision:i}=e.admitted,a=r.state.version,o=Dr(n,t);if(o!==void 0&&o.version>a)throw new J(`extensions`,`conflict`,`Stored ${t} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=Ii(n,t).map(e=>({collection:e.collection,key:e.key,value:gl(e.valueJson)}));for(let n=o.version;n<a;n+=1){let i=r.state.migrations[n];if(i===void 0)throw new J(`extensions`,`state_reset_required`,`State reset required for ${t}: 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 ml(`Failed ${t} state migration from ${String(n)}`,{cause:e})}}Hi(n,t);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new ml(`Migrated ${t} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new ml(`Migrated ${t} ${i.collection} record is invalid`);zr(n,t,i.collection,i.key,a.success,JSON.stringify(i.value))}}dr(n,t,a,i)}function A(e,n,r=!1){let i=de(e);return k(function*(){let a=yield*nn(n);e.scope=a;let o=yield*M(()=>e.admitted.definition.activate(i)).pipe(t(An,a),D);if(Ue(o)){e.hooks=o.value;return}if(yield*$e(a,o),r)return yield*T(new J(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${or(o.cause)}`));yield*C(e,yl(`activation`,o.cause),o.cause,`own-transaction`)})}let j=e=>[...i.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function he(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 ve(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 N(e,n,r){return D(r.pipe(t(Sa,m(e.admitted.id)))).pipe(B(t=>Ue(t)?F(P(t.value)):C(e,yl(n,t.cause),t.cause,`own-transaction`).pipe(I(S()))))}let be=(e,t,n)=>ha(n)?C(e,yl(t,n.cause),n.cause,`own-transaction`):L;function xe(e){return z({try:()=>{n.transactionSync(()=>{pe(e);for(let[t,r]of Object.entries(e.admitted.documents))hn(n,{extensionId:e.admitted.id,name:t,initialJson:Zo(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(E(()=>O(()=>{delete e.stateResetRequired})),I(!0),oe(t=>t instanceof J?t.cause===`state_reset_required`?(e.stateResetRequired=t,C(e,hl(t.message),Ft(t),`own-transaction`).pipe(I(!1))):T(t):(t instanceof ml&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&s.add(e.admitted.id),C(e,hl(t instanceof Error?`migration: ${t.message}`:`migration failed`),pt(t),`own-transaction`).pipe(I(!1)))))}return k(function*(){let r=yield*ii();function l(t,i){return k(function*(){let a=Fr(n,t.id),o=a?.status===`stopped`&&a.revision===t.revision,s={admitted:t,hooks:void 0,status:o?`stopped`:`running`,reason:o?a.reason:null,stoppedAt:o?a.stoppedAt:null};return yield*z({try:()=>{t.grants.has(`settled`)&&n.transactionSync(()=>{q(n,t.id)===void 0&&Ie(n,t.id,q(n,`core`)??0)})},catch:()=>new J(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*xe(s))||o?i?yield*T(new J(`extensions`,`rejected`,`Extension ${t.id} cannot start: ${s.reason??`stopped`}`)):s:(yield*z({try:()=>{n.transactionSync(()=>{Xi(n,t.id,{status:`running`,reason:null,stoppedAt:null,revision:t.revision}),Ur(n,e.watchdog,t.id),le(t.id)})},catch:()=>new J(`store`,`unavailable`,`Extension status is unavailable`)}),yield*A(s,r,i),s)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(a(()=>$e(r,qn)));i.set(t.id,e)}yield*z({try:()=>{n.transactionSync(()=>{let t=ft(n,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of t)le(e)})},catch:()=>new J(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:t=>k(function*(){let r=t.filter(e=>{let t=i.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(r.length>0)return yield*T(new J(`extensions`,`rejected`,`Extensions ${r.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,c=M(()=>Ae([...o.values()].reverse(),e=>D(e.scope===void 0?L:$e(e.scope,qn)),{concurrency:1}).pipe(E(()=>O(()=>{for(let e of t)i.has(e.id)||s.delete(e.id)})),B(Vt)));yield*k(function*(){for(let e of t)i.has(e.id)||o.set(e.id,yield*l(e,!0))}).pipe(a(()=>c));let u=new Set(t.map(({id:e})=>e)),d=!1;return{discard:M(()=>d?L:(d=!0,c)),apply:k(function*(){if(d)return yield*T(new J(`extensions`,`rejected`,`Roster transition already settled`));yield*z({try:()=>{n.transactionSync(()=>{for(let[t,r]of i)u.has(r.admitted.id)||hi(n,e.watchdog,t);let r=ft(n,t.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of r)le(e)})},catch:()=>new J(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of i)u.has(t.admitted.id)||(t.scope!==void 0&&(yield*$e(t.scope,qn)),i.delete(e),s.delete(t.admitted.id));for(let[e,t]of o)i.set(e,t);d=!0})}}),runParticipants:()=>[...i.values()].filter(ve).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...s],modulesForRun:(e,t)=>Ae(j(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?F(S()):N(n,`moduleForRun`,M(()=>r(e))).pipe(o(De))}).pipe(o(e=>e.flatMap(me))),filesForRun:(e,t)=>k(function*(){let n=j(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*C(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*T(new J(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*N(n,`filesForRun`,M(()=>r(e)));return ne(i)?yield*T(new J(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...Ce(i.value,()=>[])])}),promptSections:(e,n)=>k(function*(){let r=[],i=0;for(let a of j(`prompt`)){if(!n.has(a.admitted.id))continue;let o=a.hooks?.prompt;if(o===void 0)return yield*C(a,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*T(new J(`extensions`,`rejected`,`Extension prompt is unavailable`));let s=yield*D(fi(()=>o(e)).pipe(t(Sa,m(a.admitted.id))));if(ha(s))return yield*C(a,yl(`prompt`,s.cause),s.cause,`own-transaction`),yield*T(new J(`extensions`,`rejected`,`Extension prompt failed`));let c=pl(s.value),l=c._tag===`Success`?c.success:[];if(i+=l.reduce((e,t)=>e+fl.encode(t.text).byteLength,0),c._tag===`Failure`||new Set(l.map(({name:e})=>e)).size!==l.length||i>65536)return yield*C(a,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*T(new J(`extensions`,`rejected`,`Extension prompt is invalid`));r.push(...[...l].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${a.admitted.id}.${e.name}`,text:e.text})))}return r}),compactionHandoff:e=>j(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>j(`settled`).map(e=>({id:e.admitted.id,cursor:q(n,e.admitted.id)??0})),deliverSettled:(e,t)=>Ae(j(`settled`),r=>M(()=>{let i=q(n,r.admitted.id)??0;if(t<=i)return L;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return se(r,(o===void 0||a.length===0?L:o(a)).pipe(b(O(()=>{Ie(n,r.admitted.id,t)}))),`reconcile`).pipe(B(e=>be(r,`onSettled`,e)))}),{discard:!0}),executeTimer:t=>k(function*(){let r=Ar(H({extensionId:sn,key:sn}))(t.payload),a=i.get(r.extensionId);if(a?.status!==`running`||!a.admitted.grants.has(`timers`)||li(n,r.extensionId,r.key)!==t.jobId)return;let s=a.hooks?.onTimer,c=yield*ce(a,{prepare:(s===void 0?F(L):s({key:r.key,dueAt:t.notBefore??0,firedAt:Date.now()})).pipe(o(i=>M(()=>li(n,r.extensionId,r.key)===t.jobId?(qr(n,e.watchdog,r.extensionId,r.key),i):L)))},`reconcile`);yield*be(a,`onTimer`,c)}),project:e=>{let t={};for(let n of i.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?P(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=Ai(()=>s(e),void 0);if(we(r)){let e=Vi(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=V(Ni)(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=Ar(Ni)(Ai(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?P(t):(w(n,hl(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),S())})();if(we(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,r,a)=>k(function*(){let o=i.get(t);if(o?.admitted.grants.has(`commands`)!==!0)return yield*T(new J(`extensions`,`unavailable`,`Extension is unavailable`));if(o.status!==`running`||o.hooks===void 0)return yield*T(o.stateResetRequired??new J(`extensions`,`unavailable`,`Extension ${t} is stopped: ${o.reason??`not activated`}`));let s=o.admitted.definition.contract.commands,c=Object.hasOwn(s,n)?s[n]:void 0;if(c?.scope!==e.scope)return yield*T(new J(`contract`,`invalid`,`Extension command is unknown`));let l=e.scope===`session`?yield*z({try:()=>G(e.sessionId),catch:()=>new J(`contract`,`invalid`,`Session id is invalid`)}):null,u=o.hooks.commands.get(n);if(u===void 0)return V(c.input,{onExcessProperty:`error`})(r)._tag===`Failure`?yield*T(new J(`contract`,`invalid`,`Extension command input is invalid`)):(yield*C(o,`command ${n} has no handler`,void 0,`own-transaction`),yield*T(new J(`extensions`,`unavailable`,`Extension is stopped`)));let d=u(a===void 0?{sessionId:l,input:r}:{sessionId:l,input:r,caller:a});if(d._tag===`Failure`)return yield*T(new J(`contract`,`invalid`,`Extension command input is invalid`));let f=yield*ce(o,{prepare:d.success},`request`);if(Ue(f))return f.value;let p=At(f.cause);if(we(p)&&!bl(f.cause))return yield*T(Sl(p.value));let m=yl(`command ${n}`,f.cause);return yield*C(o,m,f.cause,`own-transaction`),yield*T(new J(`extensions`,`unavailable`,`Extension ${t} is stopped: ${m}`))}),list:()=>[...i.values()].map(he),resume:t=>k(function*(){let a=i.get(t);return a===void 0?yield*T(new J(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*z({try:()=>{n.transactionSync(()=>{Xi(n,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),Ur(n,e.watchdog,a.admitted.id),le(a.admitted.id)})},catch:()=>new J(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*xe(a))&&(yield*A(a,r)),yield*e.requestWake),he(a))}),close:$e(r,qn)};return Object.freeze(u)})}var wl=64;function Q(e){return new J(`runtime`,`rejected`,e)}function Tl(e,t,n){return k(function*(){let r=yield*El(t),i=t.outcome===`cancelled`?``:yield*st(e,r.work),a=yield*Rt(e,r.work,t.outcome),o=t.outcome===`completed`||t.outcome===`cancelled`?void 0:yield*xt(e,r.work),s={job:t,content:i};o!==void 0&&(s={...s,diagnostic:o});let c=t.outcome===`cancelled`?[]:yield*n;return c.length>0&&(s={...s,waitingOnYou:c}),a===void 0?s:{...s,meta:a}})}function El(e){return z({try:()=>He(e),catch:()=>Q(`Agent work payload is invalid`)})}function Dl(e,t){return e.fanOut(t).pipe(p(()=>Q(`Agent reply fan-out is unavailable`)))}function Ol(e,t,n){return t===void 0?L:k(function*(){let r=yield*El(n);(r.mail?.replyTo.length??0)!==0&&(yield*Dl(t,yield*Tl(e,n,z({try:()=>Re(e,r.work.sessionId,r.work.commandFactId),catch:()=>Q(`Session attention is unavailable`)}))))})}function kl(e,t,n,r,i){return n===void 0?L:k(function*(){let a=yield*El(r),o=a.mail;if(o!==void 0&&o.replyTo.length>0||(yield*t.readQueueHead(r.queue).pipe(p(()=>Q(`Session queue head is unavailable`)))).state!==`idle`)return;let s=(yield*z({try:()=>cn(e,a.work.sessionId),catch:()=>Q(`Session delegator is unavailable`)}))??(yield*jl(e,t,a.work.sessionId,i));if(s===void 0)return;let c=o?.reply===void 0?o?.from:void 0;if(c!==void 0&&!(c.kind===`agent`&&s.replyTo.some(({agentId:e})=>e===c.agentId)))return;let l=yield*Tl(e,r,z({try:()=>ri(e,a.work.sessionId,s.replyTo),catch:()=>Q(`Session attention is unavailable`)})),u=r.outcome===`cancelled`?``:yield*gn(e,a.work);yield*Dl(n,{...l,content:u,delegator:s})})}var Al=16;function jl(e,t,n,r){return r===void 0?F(void 0):k(function*(){let i=yield*z({try:()=>Kt(e,n,r,Al),catch:()=>Q(`Session senders are unavailable`)});for(let e of i){let n=yield*t.read(e).pipe(p(()=>Q(`Agent work is unavailable`)));if(n.status!==`found`)continue;let i=(yield*El(n.job)).mail;if(i?.from.kind===`agent`&&i.from.agentId===r&&i.reply===void 0&&i.replyTo.length>0)return{key:i.key,agentId:i.to.agentId,replyTo:i.replyTo}}})}function Ml(e,t,n,r,i){return Ae(r,(a,o)=>k(function*(){!r.slice(o+1).some(({job:e})=>e.queue===a.job.queue)&&!(yield*Fl(e,a.job))&&(yield*kl(e,t,n,a.job,i)),yield*z({try:()=>{Ie(e,sl,a.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function Nl(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?L:k(function*(){let r=yield*z({try:()=>He(t),catch:()=>Q(`Agent work payload is invalid`)});yield*gt(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function Pl(e,t,n){return k(function*(){let r=yield*z({try:()=>He(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*Mn(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(vn({work:{...e,recovery:Yc},delivery:e.delivery}))}})})}function Fl(e,t){return k(function*(){let n=yield*z({try:()=>He(t),catch:()=>Q(`Agent work payload is invalid`)}),r=yield*z({try:()=>ra(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return r&&(yield*i(`shiitake_settlement_session_refused`).pipe(_e({workId:t.jobId}))),r})}function Il(e,t){let n=He(t.job),r=ra(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:Le(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):on(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:Ar(Kr)(r.origin.extensionId),correlation:r.origin.correlation})})}function Ll(e,t,n,r){return Ae(r,r=>k(function*(){pn(e,r.job.queue),(yield*Fl(e,r.job))||(yield*Nl(e,r.job),yield*Pl(e,t,r.job),yield*Ol(e,n,r.job)),yield*z({try:()=>{Ie(e,ol,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function Rl(e){return k(function*(){let t=yield*e.watchdog.tick();if(t.status===`stopped`)return;if(t.status===`busy`)return yield*T(Q(`Runtime reconciliation is already active`));let n=yield*z({try:()=>q(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),r=yield*z({try:()=>q(e.store,`core-report`)??n,catch:()=>Q(`Settled cursor is unavailable`)}),i=e.extensions.settledConsumers(),a=Math.min(n,r,...i.map(({cursor:e})=>e)),o=yield*e.watchdog.readSettled(wl,a,`default`),s=yield*D(Ll(e.store,e.watchdog,e.mailRoom,o.filter(({sequence:e})=>e>n))),c=yield*z({try:()=>q(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),l=yield*z({try:()=>o.filter(({sequence:e})=>e<=c).map(t=>Il(e.store,t)),catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(l,c);let u=yield*D(Ml(e.store,e.watchdog,e.mailRoom,o.filter(({sequence:e})=>e>r&&e<=c),e.createdBy));if(o.length===wl&&(yield*e.requestWake),ha(s))return yield*ee(s.cause);if(ha(u))return yield*ee(u.cause)}).pipe(p(e=>e instanceof J?e:Q(`Runtime reconciliation failed`)))}function $(e){return new J(`runtime`,`rejected`,e)}function zl(e,t,n,r){return k(function*(){if(e.hostJobs?.lane==="default"||e.hostJobs?.lane===`extension_timer`)return yield*T($(`Host lane conflicts with Agent work`));let i=`open`,o,s,l=Fe(!1),u=e=>O(()=>{i===`open`&&(o??=e)}),f=M(()=>i===`open`?(i=`closing`,s=o,l.open):L).pipe(m),v={},y=Fe(!1),ne={current:void 0},x=e,re,ae=!1,se=M(()=>v.requestWake??T($(`Runtime host is unavailable`))),S={current:void 0},ce=new Set,C=new Map,w=new Map,de={owner:e.store,isAlive:()=>F(!1),executor:{replaySafe:e=>e.lane===hr,retryPolicy:t=>t.lane===e.hostJobs?.lane?S.current?.retryPolicy?.(t)??F(void 0):F(void 0),isDrained:e=>M(()=>{if(e.lane===`extension_timer`)return F(!0);let t=w.get(e.jobId);return w.delete(e.jobId),t?.released===!0?t.pending.length===0?F(!0):le(_(()=>Promise.all(t.pending)).pipe(I(!0)),ue(jc).pipe(I(!1))):F(!1)}),execute:(n,r)=>n.lane===`extension_timer`?M(()=>ne.current?.executeTimer(n)??T($(`Extension runtime is unavailable`))).pipe(I({kind:`completed`}),p(e=>new Ea(`execution_failed`,e))):he(O(()=>{let t=n.lane===e.hostJobs?.lane?{kind:`host`,lane:n.lane,jobId:n.jobId}:{kind:`session`,sessionId:n.queue,commandId:n.jobId};C.set(t.kind===`host`?`host`:`serial`,t);let r={isStopping:()=>i!==`open`,pending:[],released:!0};return t.kind===`session`&&(ce.add(n.queue),w.set(n.jobId,r)),ar(e.store),r}),i=>n.lane===e.hostJobs?.lane?S.current?.execute(n,r)??T(new Ea(`execution_failed`)):k(function*(){let r=re;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;x={...n,...r.configuration},re=void 0}return yield*$c(x,t,n,ne.current,i)}).pipe(te(e=>d(`configuration_apply_failed`,e)),p(()=>new Ea(`execution_failed`))),()=>O(()=>{n.lane!==e.hostJobs?.lane&&ce.delete(n.queue),C.delete(n.lane===e.hostJobs?.lane?`host`:`serial`),ar(e.store)})).pipe(c(e=>O(()=>{(i===`open`||Ue(e)||!nr(e.cause))&&w.delete(n.jobId)})))},wake:{recompute:()=>se.pipe(p(()=>new Ea(`wake_unavailable`)))},project:t=>{Qt(e.store,t,Date.now())}},pe=L,A=yield*(e.hostJobs===void 0?Da(de):Da({...de,concurrentLane:e.hostJobs.lane}).pipe(E(t=>O(()=>{S.current=e.hostJobs?.open(t),pe=t.tickConcurrent().pipe(ie,p(()=>$(`Host delivery is unavailable`)))})))).pipe(p(()=>$(`Watchdog is unavailable`))),me=()=>({core:t,extensions:[...ne.current?.runParticipants()??[]]});yield*z({try:()=>kc(e.compaction),catch:e=>e instanceof J?e:$(`Compaction settings are unavailable`)});let ge=yield*z({try:()=>Nt(e.storagePressure),catch:e=>e instanceof J?e:$(`Storage budget is unavailable`)}),_e=()=>{e.admission?.assertOpen(),ge.admitNew()},ve=()=>{let t;do{let n=un(e.store,t);for(let e of n.sessions){if(e.state===`unavailable`)throw new J(`store`,`unavailable`,`Session ${e.sessionId} is unreadable`);let t=A.transactional.readQueueHead(e.sessionId);if(t.state!==`idle`)return{kind:`session`,sessionId:e.sessionId,commandId:t.jobId}}t=n.next}while(t!==void 0);let n=Jc(e.store);return n===void 0?void 0:{kind:`delegation`,...n}},ye=al({owner:e.store,createdBy:e.createdBy,admitNew:_e,hostMeta:e.meta,contract:me,enqueue:(e,t)=>{let n={work:{...e,recovery:Yc},delivery:e.delivery};A.transactional.enqueueAcceptedJob(vn(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>A.transactional.readQueueHead(e),commit:e=>y.await.pipe(b(M(()=>v.commit===void 0?T($(`Runtime host is unavailable`)):v.commit(e)))),requestWake:se});yield*z({try:()=>{bi(e.store),q(e.store,`core`)===void 0&&e.store.transactionSync(()=>{Ie(e.store,ol,0)}),q(e.store,`core-report`)===void 0&&e.store.transactionSync(()=>{Ie(e.store,sl,q(e.store,`core`)??0)})},catch:()=>new J(`store`,`unavailable`,`Extension store is unavailable`)});let N=yield*Cl({owner:e.store,watchdog:A.transactional,readQueueHead:e=>A.transactional.readQueueHead(e),door:ye,admitted:n,requestWake:se,recipientStatus:e.recipientStatus,recipientParent:e.recipientParent,createdBy:e.createdBy});ne.current=N;let P=Rl({watchdog:A,store:e.store,createdBy:e.createdBy,extensions:N,requestWake:se,mailRoom:r}).pipe(te(u)),be=k(function*(){let t=Date.now(),n=yield*A.wakeState(t),r=yield*z({try:()=>[q(e.store,`core`)??0,q(e.store,`core-report`)??0,...N.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*A.readSettled(1,Math.min(...r),`default`)).length>0;return{pending:n.pending||i,nextWakeAt:n.nextWakeAt}}),xe=yield*e.runtime.bind({reconcile:P,reconcileHost:e.hostJobs===void 0?void 0:pe.pipe(te(u)),pendingWork:be.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(a(()=>N.close.pipe(g))),Se=M(()=>i===`open`?le(xe.requestWake.pipe(oe(u)),l.await):L);return v.requestWake=Se,v.commit=xe.commit,yield*y.open,yield*xe.requestWake.pipe(a(()=>fe([xe.close,N.close]).pipe(g))),Object.freeze({prepareConfiguration:e=>k(function*(){if(i!==`open`||ae||re!==void 0)return yield*T($(`A configuration change is already pending, or the Agent is closing`));ae=!0;let t=yield*ps(e.extensions).pipe(B(e=>N.stage(e)),a(()=>O(()=>{ae=!1}))),n=!1;return{commit:z({try:()=>{if(n||i!==`open`)throw $(`Configuration preparation is no longer available`);re={configuration:e,apply:t.apply},n=!0,ae=!1},catch:e=>e instanceof J?e:$(`Configuration commit failed`)}),discard:M(()=>n?L:(n=!0,ae=!1,t.discard))}}),activeSessions:O(()=>[...ce]),busySync:ve,runningWork:t=>A.read(t).pipe(B(t=>{let n=t.status===`found`?C.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`):void 0;return n===void 0?F(null):n.kind===`host`?F({phase:`thinking`}):z({try:()=>({phase:_o(e.store,n.sessionId,A.transactional.readQueueHead(n.sessionId))}),catch:e=>new J(`runtime`,`rejected`,`Running phase is unavailable`,void 0,e)})}),p(e=>new J(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:N,commit:xe.commit,assertOpen:M(()=>i===`open`?L:T(new J(`runtime`,`closed`,`Shiitake is closed`))),beginClose:f,door:ye,createSessionWithinTransaction:t=>xn(e.store,t,_e),recordCreatedSessionDelegatorWithinTransaction:(t,n)=>{ct(e.store,t,n)},stageSessionGrantsWithinTransaction:(t,n)=>{lt(e.store,t,n)},storage:{admitNew:_e},recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>A.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(A.transactional.readQueueHead(e).state!==`idle`)throw new J(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof J?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>A.cancel({jobId:e,cancellationId:t}).pipe(B(e=>e.status===`recorded`||e.status===`replayed`||e.status===`decided`?L:T($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>A.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>A.transactional.readQueueHead(e),requestWake:Se,close:f.pipe(b(h(fe([D(A.close.pipe(p(()=>$(`Runtime execution did not drain`)))),D(xe.close)],{concurrency:`unbounded`}).pipe(B(e=>{let t=e.find(ha);return t===void 0?L:ee(t.cause)})),{onFailure:e=>N.close.pipe(b(s===void 0?ee(e):T(s))),onSuccess:()=>N.close.pipe(b(s===void 0?L:T(s)))})),j(O(()=>{i=`closed`})))})})}var Bl=e({openRuntimeCore:()=>Vl});function Vl(e,t){return k(function*(){let n=yield*ps(e.extensions),r=yield*ms([]);yield*$t(e.store);let i=yield*zl(e,r,n,t),a=qo(e,i,yield*C()),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:go(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(b(ei(e.store,t,n))),activeSessions:i.activeSessions,busySync:i.busySync,acceptMail:(e,n,r,a,o)=>Yo(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);ve(t.postMail(e))}),o)})})}export{po as n,Vl as openRuntimeCore,Bl as t};
@@ -1 +1 @@
1
- import{n as e,t}from"./error-body-C7MTmn8e.js";import{i as n,n as r,r as i,t as a}from"./classifier-shared-BCGGOIh6.js";var o={"TypeSafe-Danger-Zone-Images":`true`};function s(e,t,r){if(!a(t))throw Error(`${e} returned invalid probabilities for ${r}`);return Object.fromEntries(Object.entries(t).map(([t,i])=>[t,n(e,i,`probability for ${r}.${t}`)]))}function c(e,t,r){if(!a(t))throw Error(`${e} returned an unexpected response`);let i=[];for(let[o,c]of Object.entries(r.questions)){let r=t[o];if(!a(r))throw Error(`${e} did not return an answer for ${o}`);if(c.type===`choice`){if(r.type!==`choice`||typeof r.choice!=`string`)throw Error(`${e} did not return a choice answer for ${o}`);i.push([o,{type:`choice`,choice:r.choice,probabilities:s(e,r.probabilities,o),confidence:n(e,r.confidence,`confidence for ${o}`)}])}else if(c.type===`score`){if(r.type!==`score`)throw Error(`${e} did not return a score answer for ${o}`);i.push([o,{type:`score`,score:n(e,r.score,`score for ${o}`),confidence:n(e,r.confidence,`confidence for ${o}`)}])}else{if(r.type!==`noul`)throw Error(`${e} did not return a bool answer for ${o}`);i.push([o,{type:`bool`,probability:n(e,r.noul,`probability for ${o}`)}])}}return Object.fromEntries(i)}var l={"image/png":`png`,"image/jpeg":`jpeg`},u=new Set([`image/png`,`image/jpeg`,`image/webp`]),d=4;function f(e,t,n,r,i){if(n===`images`){if(r.length>d)throw Error(`${e} accepts at most ${d} images for ${t.id}, got ${r.length}`);i.images=r.map(n=>{if(!u.has(n.mimeType))throw Error(`${e} accepts PNG, JPEG, and WebP images for ${t.id}, got ${n.mimeType}`);return`data:${n.mimeType};base64,${n.data}`});return}if(n===`state-image-urls`){i.state=[...r.map(e=>({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})),i.state];return}let a={};r.forEach((n,r)=>{let i=l[n.mimeType];if(!i)throw Error(`${e} accepts PNG and JPEG images for ${t.id}, got ${n.mimeType}`);a[`<image-${r+1}>`]={type:`image`,format:i,data_base64:n.data}}),i.assets=a,i.state=[...Object.keys(a),i.state]}function p(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([e,t])=>[e,t.type===`bool`?{...t,type:`noul`}:t]))}}async function m(n,a,s,l){let u={api:a.api,provider:a.provider,model:a.id,answers:{},stopReason:`stop`,timestamp:Date.now()};try{if(a.api!==n.api)throw Error(`Unsupported classifier API: ${a.api}`);let e=p(s),t=l;if(s.images?.length){if(!a.input.includes(`image`))throw Error(`${n.label} does not support image input for ${a.id}`);let r=n.detectCompat(a),i=a.compat?.imageInput??r.imageInput;f(n.label,a,i,s.images,e),(a.compat?.sendImageOptInHeader??r.sendImageOptInHeader)&&(t={...l,headers:{...o,...l?.headers}})}let d=await i(n.label,n.url(a),a,n.payload(a,e),t),m=n.output(d),h=r(m.usage,a);return h&&(u.usage=h),u.answers=c(n.label,m.answers,s),u}catch(r){return u.stopReason=l?.signal?.aborted?`aborted`:`error`,u.errorMessage=t(e(r),`${n.label} error`),u}}export{m as t};
1
+ import{n as e,t}from"./error-body-C7MTmn8e.js";import{i as n,n as r,r as i,t as a}from"./classifier-shared-JiMD88Sh.js";var o={"TypeSafe-Danger-Zone-Images":`true`};function s(e,t,r){if(!a(t))throw Error(`${e} returned invalid probabilities for ${r}`);return Object.fromEntries(Object.entries(t).map(([t,i])=>[t,n(e,i,`probability for ${r}.${t}`)]))}function c(e,t,r){if(!a(t))throw Error(`${e} returned an unexpected response`);let i=[];for(let[o,c]of Object.entries(r.questions)){let r=t[o];if(!a(r))throw Error(`${e} did not return an answer for ${o}`);if(c.type===`choice`){if(r.type!==`choice`||typeof r.choice!=`string`)throw Error(`${e} did not return a choice answer for ${o}`);i.push([o,{type:`choice`,choice:r.choice,probabilities:s(e,r.probabilities,o),confidence:n(e,r.confidence,`confidence for ${o}`)}])}else if(c.type===`score`){if(r.type!==`score`)throw Error(`${e} did not return a score answer for ${o}`);i.push([o,{type:`score`,score:n(e,r.score,`score for ${o}`),confidence:n(e,r.confidence,`confidence for ${o}`)}])}else{if(r.type!==`noul`)throw Error(`${e} did not return a bool answer for ${o}`);i.push([o,{type:`bool`,probability:n(e,r.noul,`probability for ${o}`)}])}}return Object.fromEntries(i)}var l={"image/png":`png`,"image/jpeg":`jpeg`},u=new Set([`image/png`,`image/jpeg`,`image/webp`]),d=4;function f(e,t,n,r,i){if(n===`images`){if(r.length>d)throw Error(`${e} accepts at most ${d} images for ${t.id}, got ${r.length}`);i.images=r.map(n=>{if(!u.has(n.mimeType))throw Error(`${e} accepts PNG, JPEG, and WebP images for ${t.id}, got ${n.mimeType}`);return`data:${n.mimeType};base64,${n.data}`});return}if(n===`state-image-urls`){i.state=[...r.map(e=>({type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}})),i.state];return}let a={};r.forEach((n,r)=>{let i=l[n.mimeType];if(!i)throw Error(`${e} accepts PNG and JPEG images for ${t.id}, got ${n.mimeType}`);a[`<image-${r+1}>`]={type:`image`,format:i,data_base64:n.data}}),i.assets=a,i.state=[...Object.keys(a),i.state]}function p(e){return{state:e.state,questions:Object.fromEntries(Object.entries(e.questions).map(([e,t])=>[e,t.type===`bool`?{...t,type:`noul`}:t]))}}async function m(n,a,s,l){let u={api:a.api,provider:a.provider,model:a.id,answers:{},stopReason:`stop`,timestamp:Date.now()};try{if(a.api!==n.api)throw Error(`Unsupported classifier API: ${a.api}`);let e=p(s),t=l;if(s.images?.length){if(!a.input.includes(`image`))throw Error(`${n.label} does not support image input for ${a.id}`);let r=n.detectCompat(a),i=a.compat?.imageInput??r.imageInput;f(n.label,a,i,s.images,e),(a.compat?.sendImageOptInHeader??r.sendImageOptInHeader)&&(t={...l,headers:{...o,...l?.headers}})}let d=await i(n.label,n.url(a),a,n.payload(a,e),t),m=n.output(d),h=r(m.usage,a);return h&&(u.usage=h),u.answers=c(n.label,m.answers,s),u}catch(r){return u.stopReason=l?.signal?.aborted?`aborted`:`error`,u.errorMessage=t(e(r),`${n.label} error`),u}}export{m as t};
@@ -1 +1 @@
1
- import{t as e}from"./estimate-DElUjJag.js";import{clampThinkingLevel as t}from"./compat-CAkhM7lX.js";var n=class extends Error{},r=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(e){if(!i(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 o(e){return i(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=>o(e)):!1}function s(e,t){if(!i(e))throw new n(`boolean schemas are unsupported`);for(let t of r)if(e[t]!==void 0)throw new n(`${t} schemas are unsupported`);if(t){for(let[r,i]of Object.entries(e))if(t(r,i))throw new n(`${r}: ${JSON.stringify(i)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new n(`anyOf must contain at least one schema`);for(let r of e.anyOf){if(a(r))throw new n(`object and array unions are unsupported`);s(r,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new n(`tuple schemas are unsupported`);s(e.items,t)}let c=e.type===`object`;if(e.properties!==void 0&&!c)throw new n(`properties require type object`);if(!c)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new n(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!i(e.properties))throw new n(`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 n(`object required must be a string array`);let l=e.properties??{},u=Object.keys(l),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!u.includes(e)))throw new n(`required contains an unknown property`);for(let[e,n]of Object.entries(l))s(n,t),!d.has(e)&&!o(n)&&(l[e]={anyOf:[n,{type:`null`}]});e.required=u,e.additionalProperties=!1}function c(e,t){let r=structuredClone(e);if(!i(r)||(s(r,t),r.type!==`object`))throw new n(`root schema must have type object`);return r}function l(e){let t=e.constrainedSampling;return!!t&&t.type===`json_schema`&&t.strict===`prefer`}function u(e,t){return t===!0?c(e.parameters):e.parameters}function d(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 f(e,t,n){if(e.closed)throw Error(`grammar tool input for property "${t}" changed after it was closed`);if(n.length!==0)return e.input+=n,m(e,t)+JSON.stringify(n).slice(1,-1)}function p(e,t,n){if(e.closed){if(n===void 0||n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(n!==void 0&&!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let r=n===void 0?``:n.slice(e.input.length);return n!==void 0&&(e.input=n),e.closed=!0,`${m(e,t)}${JSON.stringify(r).slice(1,-1)}"}`}function m(e,t){return e.started?``:(e.started=!0,`{${JSON.stringify(t)}:"`)}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,r){let i=e.constrainedSampling;if(!(!i||i.type!==`json_schema`)){if(t)try{return c(e.parameters,r),!0}catch(t){if(!(t instanceof n))throw t;if(i.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(i.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=.15,x=32768,S=1;function C(t,n,r){if(t.contextWindow<=0)return Math.max(S,r);let i=e(n).tokens,a=Math.max(y,Math.ceil(i*b)),o=t.contextWindow-i-a;return o<x&&(o=Math.min(x,t.contextWindow-i-y)),Math.min(r,Math.max(S,o))}function w(e,n,r){let i=t(e,n),a=e.samplingParamsByThinkingLevel?.[i];return e.samplingParams||a||r?{...e.samplingParams,...a,...r}:void 0}function T(e,t,n,r){let i=w(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:C(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetry:n?.telemetry,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,disableContinuation:n?.disableContinuation,headers:n?.headers,identity:n?.identity,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 E=1024,D={minimal:1024,low:2048,medium:8192,high:16384};function O(e){return e===`xhigh`||e===`max`?`high`:e}function k(e,t){return{...D,...t}[O(e)]}function A(e,t){return Math.min(e,Math.max(0,t-E))}function j(e,t,n,r){let i=k(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=A(i,a)),{maxTokens:a,thinkingBudget:i}}var M=`(image omitted: model does not support images)`,N=`(tool image omitted: model does not support images)`,P=`(image attached after the tool results)`;function F(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:I(e.content,P),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function I(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 L(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:I(e.content,M)}:e.role===`toolResult`?{...e,content:I(e.content,N)}:e)}function R(e,t,n){let r=new Map,i=L(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{C as a,k as c,v as d,d as f,g,_ as h,T as i,f as l,l as m,R as n,A as o,u as p,j as r,w as s,F as t,p as u};
1
+ import{t as e}from"./estimate-DElUjJag.js";import{clampThinkingLevel as t}from"./compat-CxZajpXB.js";var n=class extends Error{},r=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function i(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function a(e){if(!i(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 o(e){return i(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=>o(e)):!1}function s(e,t){if(!i(e))throw new n(`boolean schemas are unsupported`);for(let t of r)if(e[t]!==void 0)throw new n(`${t} schemas are unsupported`);if(t){for(let[r,i]of Object.entries(e))if(t(r,i))throw new n(`${r}: ${JSON.stringify(i)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new n(`anyOf must contain at least one schema`);for(let r of e.anyOf){if(a(r))throw new n(`object and array unions are unsupported`);s(r,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new n(`tuple schemas are unsupported`);s(e.items,t)}let c=e.type===`object`;if(e.properties!==void 0&&!c)throw new n(`properties require type object`);if(!c)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new n(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!i(e.properties))throw new n(`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 n(`object required must be a string array`);let l=e.properties??{},u=Object.keys(l),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!u.includes(e)))throw new n(`required contains an unknown property`);for(let[e,n]of Object.entries(l))s(n,t),!d.has(e)&&!o(n)&&(l[e]={anyOf:[n,{type:`null`}]});e.required=u,e.additionalProperties=!1}function c(e,t){let r=structuredClone(e);if(!i(r)||(s(r,t),r.type!==`object`))throw new n(`root schema must have type object`);return r}function l(e){let t=e.constrainedSampling;return!!t&&t.type===`json_schema`&&t.strict===`prefer`}function u(e,t){return t===!0?c(e.parameters):e.parameters}function d(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 f(e,t,n){if(e.closed)throw Error(`grammar tool input for property "${t}" changed after it was closed`);if(n.length!==0)return e.input+=n,m(e,t)+JSON.stringify(n).slice(1,-1)}function p(e,t,n){if(e.closed){if(n===void 0||n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(n!==void 0&&!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let r=n===void 0?``:n.slice(e.input.length);return n!==void 0&&(e.input=n),e.closed=!0,`${m(e,t)}${JSON.stringify(r).slice(1,-1)}"}`}function m(e,t){return e.started?``:(e.started=!0,`{${JSON.stringify(t)}:"`)}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,r){let i=e.constrainedSampling;if(!(!i||i.type!==`json_schema`)){if(t)try{return c(e.parameters,r),!0}catch(t){if(!(t instanceof n))throw t;if(i.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(i.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=.15,x=32768,S=1;function C(t,n,r){if(t.contextWindow<=0)return Math.max(S,r);let i=e(n).tokens,a=Math.max(y,Math.ceil(i*b)),o=t.contextWindow-i-a;return o<x&&(o=Math.min(x,t.contextWindow-i-y)),Math.min(r,Math.max(S,o))}function w(e,n,r){let i=t(e,n),a=e.samplingParamsByThinkingLevel?.[i];return e.samplingParams||a||r?{...e.samplingParams,...a,...r}:void 0}function T(e,t,n,r){let i=w(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:C(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetry:n?.telemetry,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,disableContinuation:n?.disableContinuation,headers:n?.headers,identity:n?.identity,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 E=1024,D={minimal:1024,low:2048,medium:8192,high:16384};function O(e){return e===`xhigh`||e===`max`?`high`:e}function k(e,t){return{...D,...t}[O(e)]}function A(e,t){return Math.min(e,Math.max(0,t-E))}function j(e,t,n,r){let i=k(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=A(i,a)),{maxTokens:a,thinkingBudget:i}}var M=`(image omitted: model does not support images)`,N=`(tool image omitted: model does not support images)`,P=`(image attached after the tool results)`;function F(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:I(e.content,P),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function I(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 L(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:I(e.content,M)}:e.role===`toolResult`?{...e,content:I(e.content,N)}:e)}function R(e,t,n){let r=new Map,i=L(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{C as a,k as c,v as d,d as f,g,_ as h,T as i,f as l,l as m,R as n,A as o,u as p,j as r,w as s,F as t,p as u};
@@ -1 +1 @@
1
- import{t as e}from"./classifier-shared-BCGGOIh6.js";import{t}from"./system-one-shared-qsmpMW29.js";var n={api:`typesafe-system-one`,label:`System One API`,detectCompat:e=>e.provider===`openrouter`||e.baseUrl.includes(`openrouter.ai`)?{imageInput:`state-image-urls`,sendImageOptInHeader:!1}:{imageInput:`assets`,sendImageOptInHeader:!0},url:e=>new URL(`systemone`,`${e.baseUrl.replace(/\/+$/u,``)}/`),payload:(e,t)=>({model:e.id,...t}),output:t=>{if(!e(t))throw Error(`System One API returned an unexpected response`);return t}},r=(e,r,i)=>t(n,e,r,i);export{r as classify};
1
+ import{t as e}from"./classifier-shared-JiMD88Sh.js";import{t}from"./system-one-shared-D7AS4c2W.js";var n={api:`typesafe-system-one`,label:`System One API`,detectCompat:e=>e.provider===`openrouter`||e.baseUrl.includes(`openrouter.ai`)?{imageInput:`state-image-urls`,sendImageOptInHeader:!1}:{imageInput:`assets`,sendImageOptInHeader:!0},url:e=>new URL(`systemone`,`${e.baseUrl.replace(/\/+$/u,``)}/`),payload:(e,t)=>({model:e.id,...t}),output:t=>{if(!e(t))throw Error(`System One API returned an unexpected response`);return t}},r=(e,r,i)=>t(n,e,r,i);export{r as classify};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{Ar as t,B as n,I as r,L as i,Mi as a,P as o,R as s,U as c,qi as l,t as u,z as d}from"./conversation-toast-BLAWHMmE.js";import{ai as f}from"./extension-hook-BEwrceUI.js";import{t as p}from"./parakeet-Cq96KyZe.js";var m=e(l(),1),h=a();function g({inbox:e,ui:a}){let{selected:l,session:g,action:_,canManage:v}=e,[y,b]=(0,m.useState)(null);(0,m.useEffect)(()=>{b(null)},[l?.bindingId,l?.conversation.sessionId,v]);let x=_.error;if((0,m.useEffect)(()=>{x!==null&&u(a,{variant:`error`,message:`This conversation changed or website access was removed. Refresh and try again.`})},[x,a]),l===void 0)return null;let S=l.conversation;return(0,h.jsxs)(`section`,{className:`flex min-h-0 flex-1 flex-col`,"aria-label":`Website conversation`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-base-300 p-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 flex-1 text-sm`,children:S.heldByYou?`You're replying. The Agent is paused.`:S.held?`${S.heldByName??`A teammate`} is replying.`:`The Agent is replying. Take over to answer as yourself.`}),v?(0,h.jsx)(t,{size:`sm`,disabled:_.isPending,onClick:()=>{let e={bindingId:l.bindingId,sessionId:S.sessionId};S.heldByYou?_.mutate({kind:`release`,...e,expectedVersion:S.holdVersion,confirm:!1}):S.held?b({...e,version:S.holdVersion,name:S.heldByName??`A teammate`}):_.mutate({kind:`hold`,...e,expectedVersion:S.holdVersion,confirm:!1})},children:S.heldByYou?`Hand back to Agent`:`Take over`}):null]}),(0,h.jsx)(o,{open:y!==null,onOpenChange:e=>{e||b(null)},children:(0,h.jsxs)(i,{children:[(0,h.jsxs)(n,{children:[(0,h.jsxs)(c,{children:[y?.name,` is replying — take over?`]}),(0,h.jsx)(s,{children:`You will reply as yourself. Their replies stop until they take over again.`})]}),(0,h.jsxs)(d,{children:[(0,h.jsx)(r,{render:(0,h.jsx)(t,{variant:`outline`}),children:`Cancel`}),(0,h.jsx)(t,{disabled:_.isPending||!v,onClick:()=>{y!==null&&(_.mutate({kind:`hold`,bindingId:y.bindingId,sessionId:y.sessionId,expectedVersion:y.version,confirm:!0}),b(null))},children:`Take over`})]})]})}),v?null:(0,h.jsx)(`p`,{className:`p-3 text-sm`,children:`Allow takeover in Grove's App permissions to reply. Your Team permissions still apply.`}),g?(0,h.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,h.jsx)(p,{authorOf:f,disambiguateAuthors:!0,session:g,markdownPolicy:`visitor`,composerActionVariant:`outline`},`${l.bindingId}:${S.sessionId}`)}):null]})}export{g as WebsiteConversation};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{B as t,Ca as n,Ea as r,G as i,H as a,K as o,Ni as s,U as c,W as l,Y as u,t as d}from"./conversation-toast-DUFOMoQ9.js";import{fi as f}from"./extension-hook-Da3ATgkY.js";import{t as p}from"./parakeet-BUkzxkvS.js";var m=e(r(),1),h=n();function g({inbox:e,ui:n}){let{selected:r,session:g,action:_,canManage:v}=e,[y,b]=(0,m.useState)(null);(0,m.useEffect)(()=>{b(null)},[r?.bindingId,r?.conversation.sessionId,v]);let x=_.error;if((0,m.useEffect)(()=>{x!==null&&d(n,{variant:`error`,message:`This conversation changed or website access was removed. Refresh and try again.`})},[x,n]),r===void 0)return null;let S=r.conversation;return(0,h.jsxs)(`section`,{className:`flex min-h-0 flex-1 flex-col`,"aria-label":`Website conversation`,children:[(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-base-300 p-2`,children:[(0,h.jsx)(`span`,{className:`min-w-0 flex-1 text-sm`,children:S.heldByYou?`You're replying. The Agent is paused.`:S.held?`${S.heldByName??`A teammate`} is replying.`:`The Agent is replying. Take over to answer as yourself.`}),v?(0,h.jsx)(s,{size:`sm`,disabled:_.isPending,onClick:()=>{let e={bindingId:r.bindingId,sessionId:S.sessionId};S.heldByYou?_.mutate({kind:`release`,...e,expectedVersion:S.holdVersion,confirm:!1}):S.held?b({...e,version:S.holdVersion,name:S.heldByName??`A teammate`}):_.mutate({kind:`hold`,...e,expectedVersion:S.holdVersion,confirm:!1})},children:S.heldByYou?`Hand back to Agent`:`Take over`}):null]}),(0,h.jsx)(t,{open:y!==null,onOpenChange:e=>{e||b(null)},children:(0,h.jsxs)(c,{children:[(0,h.jsxs)(o,{children:[(0,h.jsxs)(u,{children:[y?.name,` is replying — take over?`]}),(0,h.jsx)(l,{children:`You will reply as yourself. Their replies stop until they take over again.`})]}),(0,h.jsxs)(i,{children:[(0,h.jsx)(a,{render:(0,h.jsx)(s,{variant:`outline`}),children:`Cancel`}),(0,h.jsx)(s,{disabled:_.isPending||!v,onClick:()=>{y!==null&&(_.mutate({kind:`hold`,bindingId:y.bindingId,sessionId:y.sessionId,expectedVersion:y.version,confirm:!0}),b(null))},children:`Take over`})]})]})}),v?null:(0,h.jsx)(`p`,{className:`p-3 text-sm`,children:`Allow takeover in Grove's App permissions to reply. Your Team permissions still apply.`}),g?(0,h.jsx)(`div`,{className:`min-h-0 flex-1`,children:(0,h.jsx)(p,{authorOf:f,disambiguateAuthors:!0,session:g,markdownPolicy:`visitor`,composerActionVariant:`outline`},`${r.bindingId}:${S.sessionId}`)}):null]})}export{g as WebsiteConversation};
package/dist/index.html CHANGED
@@ -4,17 +4,18 @@
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-BaZH2cO3.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-BaCEAFz2.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
9
- <link rel="modulepreload" crossorigin href="/assets/Effect-DeiDqvoz.js">
9
+ <link rel="modulepreload" crossorigin href="/assets/Effect-pxRavrBh.js">
10
10
  <link rel="modulepreload" crossorigin href="/assets/text-_WthCHzw.js">
11
11
  <link rel="modulepreload" crossorigin href="/assets/preload-helper-CfILh1TC.js">
12
- <link rel="modulepreload" crossorigin href="/assets/extension-hook-BEwrceUI.js">
13
- <link rel="modulepreload" crossorigin href="/assets/document-EWUYmKg3.js">
14
- <link rel="modulepreload" crossorigin href="/assets/conversation-toast-BLAWHMmE.js">
15
- <link rel="modulepreload" crossorigin href="/assets/document-BiiUDQ73.js">
16
- <link rel="modulepreload" crossorigin href="/assets/base-face-BYExcFAP.js">
17
- <link rel="stylesheet" crossorigin href="/assets/index-ODpmGtEN.css">
12
+ <link rel="modulepreload" crossorigin href="/assets/extension-hook-Da3ATgkY.js">
13
+ <link rel="modulepreload" crossorigin href="/assets/document-BBvRlLC3.js">
14
+ <link rel="modulepreload" crossorigin href="/assets/conversation-toast-DUFOMoQ9.js">
15
+ <link rel="modulepreload" crossorigin href="/assets/extensions-D2Z9guoO.js">
16
+ <link rel="modulepreload" crossorigin href="/assets/document-Bpcy9TTA.js">
17
+ <link rel="modulepreload" crossorigin href="/assets/base-face-CsIbc1by.js">
18
+ <link rel="stylesheet" crossorigin href="/assets/index-CIiuRnlU.css">
18
19
  </head>
19
20
  <body>
20
21
  <div id="inbox-root"></div>