@fungi.computer/grove 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/Effect-TOXKEWei.js +76 -0
- package/dist/assets/{anthropic-messages-BC32dQ9I.js → anthropic-messages-BTv37DKo.js} +3 -3
- package/dist/assets/{azure-openai-responses-CxbiKRMB.js → azure-openai-responses-CLI5CTea.js} +1 -1
- package/dist/assets/{base-face-BEjKYyJe.js → base-face-CD4oLBv-.js} +1 -1
- package/dist/assets/burger-BrMTWnA6.js +1 -0
- package/dist/assets/cat-Ce0yvAsw.js +1 -0
- package/dist/assets/compat-BQZx9Jx3.js +2 -0
- package/dist/assets/{document-CI1e8oXD.js → document-aOA3zT2S.js} +1 -1
- package/dist/assets/extension-hook-UDdYbDsl.js +819 -0
- package/dist/assets/extensions-DF9U5f_Z.js +1 -0
- package/dist/assets/{google-generative-ai-0DBJk_8o.js → google-generative-ai-_8qHW2IX.js} +1 -1
- package/dist/assets/{google-shared-BL1Pe-wK.js → google-shared-BjptlrJn.js} +1 -1
- package/dist/assets/{google-vertex-CPgYcjfH.js → google-vertex-C6JPlmUK.js} +1 -1
- package/dist/assets/index-DM8ziIjn.js +174 -0
- package/dist/assets/index-DRqG5MfY.css +1 -0
- package/dist/assets/{mistral-conversations-C3vHwl30.js → mistral-conversations-C_XYmgUS.js} +1 -1
- package/dist/assets/{mushroom-D2oxknl9.js → mushroom-BTxbn3Sf.js} +1 -1
- package/dist/assets/{node.browser-C4Y5T0IC.js → node.browser-Bc9i4viB.js} +1 -1
- package/dist/assets/{openai-codex-responses-BJGSPctB.js → openai-codex-responses-C0Thlbgz.js} +1 -1
- package/dist/assets/{openai-completions-2akGjxPU.js → openai-completions-CJJn6-l3.js} +1 -1
- package/dist/assets/{openai-responses-D6H3TRtV.js → openai-responses-BuHYr0Ip.js} +1 -1
- package/dist/assets/{openai-responses-shared-DZesysou.js → openai-responses-shared-px8hA25N.js} +1 -1
- package/dist/assets/parakeet-conversation-gakMmXhW.js +4 -0
- package/dist/assets/renderer-69rvqVnj.js +1 -0
- package/dist/assets/runtime-core-CHfIZEOV.js +40 -0
- package/dist/assets/{transform-messages-CgFTI6NF.js → transform-messages-zEOZxc_F.js} +1 -1
- package/dist/index.html +6 -6
- package/package.json +20 -10
- package/dist/assets/Effect-BY0T-p9d.js +0 -76
- package/dist/assets/Effect-Bibd7o64.js +0 -76
- package/dist/assets/anthropic-messages-BrTyy87S.js +0 -19
- package/dist/assets/azure-openai-responses-Cxq6500u.js +0 -1
- package/dist/assets/base-face-Dc6wvM5e.js +0 -1
- package/dist/assets/burger-DCM1Ryjl.js +0 -1
- package/dist/assets/burger-Zw2lKYST.js +0 -1
- package/dist/assets/cat-D2ceQOG1.js +0 -1
- package/dist/assets/cat-Dg3HQp8e.js +0 -1
- package/dist/assets/compat-CNGE3olg.js +0 -2
- package/dist/assets/compat-DgqxVOn_.js +0 -2
- package/dist/assets/document-DjWTbvB5.js +0 -1
- package/dist/assets/extension-hook-C8RQgls9.js +0 -741
- package/dist/assets/extension-hook-CBuX_bUG.js +0 -721
- package/dist/assets/extensions-DEfvRHbZ.js +0 -1
- package/dist/assets/extensions-DYjwCmO5.js +0 -1
- package/dist/assets/google-generative-ai-C-fVQ8eG.js +0 -1
- package/dist/assets/google-shared-CRsSlHta.js +0 -8
- package/dist/assets/google-vertex-DFCQBu0N.js +0 -1
- package/dist/assets/index-26gTYfVj.js +0 -171
- package/dist/assets/index-DIRtUgKp.css +0 -1
- package/dist/assets/index-HgPChePI.js +0 -171
- package/dist/assets/index-u-fIUxtz.css +0 -1
- package/dist/assets/mistral-conversations-Dx6vubnB.js +0 -4
- package/dist/assets/mushroom-DcQ2lek6.js +0 -1
- package/dist/assets/node.browser-DF9afU1k.js +0 -1
- package/dist/assets/openai-codex-responses-CK2Z6kMm.js +0 -9
- package/dist/assets/openai-completions-C35dP-q-.js +0 -5
- package/dist/assets/openai-responses-DPFd_3HO.js +0 -1
- package/dist/assets/openai-responses-shared-DaKV5GAS.js +0 -10
- package/dist/assets/parakeet-conversation-DKtvvfd-.js +0 -4
- package/dist/assets/parakeet-conversation-Di3EPCdu.js +0 -4
- package/dist/assets/renderer-BHU7Ec4o.js +0 -1
- package/dist/assets/renderer-cVoUiOqk.js +0 -1
- package/dist/assets/runtime-core-COw0PWwZ.js +0 -1
- package/dist/assets/runtime-core-DOL1texL.js +0 -1
- package/dist/assets/transform-messages-utWG7TCG.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{j as n,ma as r,pt as i,r as a,t as o}from"./Effect-TOXKEWei.js";import{i as s,t as c}from"./document-aOA3zT2S.js";import{$ as l,B as u,F as d,G as f,H as p,I as m,J as h,K as g,L as _,M as ee,N as v,P as y,Q as te,R as ne,U as b,V as re,W as x,X as S,Y as C,Z as ie,et as ae,j as oe,nt as se,q as w,rt as T,tt as E,z as ce}from"./index-DM8ziIjn.js";var D=(e,t)=>{if(te(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},O=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),C(t))return n;if(g(+t))return+t;let r=t,i=e?e.labels:null,a=!f(i),o=D(e,r),s=!C(o),c=se.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 ce(u,d,e[0])}return s?o:a?C(i[r])?n:i[r]:n};function le(e){return p((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function k(e,t,n,r,i,a){let o=g(e.duration)&&e.duration<=1e-11?n-E:n;t.composition&&ne(t,o,1,1,T.AUTO);let s=r?new oe(r,e,t,o,!1,i,a):new y(e,t,o);return t.composition&&s.init(!0),re(t,s),b(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=le(t),t}var A=0,j=class extends y{constructor(e={}){super(e,null,0),++A,this.id=C(e.id)?A:e.id,this.duration=0,this.labels={};let t=e.defaults,n=l.defaults;this.defaults=t?S(t,n):n,this.composition=u(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=u(e.playbackEase,n.playbackEase);this._ease=r?ee(r):null,this.iterationDuration=0}add(e,t,n){let r=w(t),i=w(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=l.editor&&l.editor.addTimelineChild,a=n&&n.type===`Stagger`&&l.editor,o=x(n)?n:null;if(o||a){let t=v(e),a=this.duration,s=this.iterationDuration,c=r.id,u=0,d=t.length,f=i?i(e,r,this.id,n,d):null,p=o||l.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...f||r};this.duration=a,this.iterationDuration=s,C(c)||(n.id=c+`-`+u);let i=O(this,p(e,u,t,null,this));k(n,this,i,e,u,t),u++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;k(t,this,O(this,a),e)}}else k(e,this,O(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(C(e)||e&&C(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!C(e)&&!C(e.persist)&&(e.persist=!0);let r=l.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 C(t)?this:(t.duration=E,t.composition=ae.replace,this.add(e,t,n))}call(e,t){return C(e)||e&&!x(e)?this:(l.editor&&l.editor.addTimelineCall&&(t=l.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return C(e)||e&&!h(e)?this:(l.editor&&l.editor.addTimelineLabel&&(t=l.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=O(this,t),this)}remove(e,t){return m(v(e),this,t),this}stretch(e){let t=this.duration;if(t===ie(e))return this;let n=e/t,r=this.labels;b(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return b(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),b(this,e=>e.revert,!0),_(this)}then(e){return super.then(e)}},M=e=>l.editor?l.editor.addTimeline(e):new j(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=s(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}seek(e){if(X(e,`timeMs`),e<0)throw RangeError(`timeMs must be nonnegative`);this.pause(!0);for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])t?.seek(e);this.dirty=!0,this.renderStill()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=s(n.color);r&&(n.color=this.palette[r]);let i=s(n.backface);i&&(n.backface=this.palette[i]);let a=s(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=M({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=d({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>n(function*(){let t=c.parse(e.document.data),n=yield*o(i(()=>e.target.ownerDocument.createElement(`canvas`)),e=>i(()=>{e.remove()}));n.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(n);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let l,u=!0,d=!1,f=()=>{u||d||l!==void 0||(l=s.requestAnimationFrame(e=>{l=void 0,m.tick(e)&&f()}))},p=()=>{d||(u?m.renderStill():f())},m=yield*o(i(()=>ye({target:n,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>i(()=>{e.destroy()}));yield*a(()=>i(()=>{d=!0,l!==void 0&&s.cancelAnimationFrame(l)})),m.pause(!0);let h=!1,g,_;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,i]of Object.entries(e.appearance)){let e=r().safeParse(i);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let i=JSON.stringify(n);i!==_&&(m.setPalette(n),_=i);let a=e.expression??t.defaultPresentation.expression;if(!a)throw Error(`Zdog avatar needs an expression`);let o=JSON.stringify([e.activity,a]);o!==g&&(m.present({activity:e.activity,expression:a}),g=o),h=e.timeMs!==void 0,e.timeMs!==void 0&&m.seek(e.timeMs),p()},pause(e){u=h||e,m.pause(u),u&&l!==void 0&&(s.cancelAnimationFrame(l),l=void 0),p()}}});export{be as t};
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,Bn as n,D as r,F as i,G as a,Gr as o,I as s,Jn as c,K as l,O as u,P as d,Q as f,Qn as p,R as m,St as h,V as g,Wi as _,Xi as v,Xn as ee,Y as te,Yn as ne,Zn as y,_ as re,_a as b,a as x,aa as S,at as ie,bt as ae,c as oe,ct as C,d as se,dt as w,er as ce,et as le,ft as T,g as E,gt as D,h as O,ht as k,i as ue,ia as de,ir as A,j,la as fe,m as pe,ma as M,mi as me,mt as N,n as he,o as ge,oa as _e,or as P,ot as ve,p as ye,pa as F,pt as I,r as be,s as L,sr as xe,st as Se,t as Ce,ua as we,ut as Te,vt as Ee,w as De,xt as Oe,y as R,yt as z}from"./Effect-TOXKEWei.js";import{$ as ke,$a as Ae,$r as B,$t as je,A as Me,An as Ne,Ar as Pe,At as Fe,B as Ie,Ba as Le,Bn as Re,Br as ze,Bt as Be,C as Ve,Ca as He,Ci as Ue,Cn as We,Cr as Ge,Ct as Ke,D as qe,Dn as Je,Dt as Ye,E as Xe,En as Ze,Er as Qe,Et as $e,F as et,Fn as tt,Fr as nt,Ft as rt,G as it,Gn as at,Gt as ot,H as st,Ha as ct,Hn as lt,Hr as ut,Ht as dt,I as ft,Ia as pt,Ii as mt,In as ht,Ir as gt,It as _t,J as vt,Jn as yt,Jt as bt,K as xt,Kn as St,Kr as Ct,Kt as wt,L as Tt,La as Et,Ln as Dt,Lt as Ot,M as kt,Mn as At,Mr as jt,Mt,N as Nt,Nn as Pt,Nr as Ft,Nt as It,O as Lt,On as Rt,Ot as zt,P as Bt,Pn as Vt,Pr as Ht,Pt as Ut,Q as Wt,Qa as Gt,Qr as Kt,Qt as qt,R as Jt,Ra as Yt,Rn as Xt,Rr as Zt,Rt as Qt,S as $t,Sn as en,Sr as tn,St as nn,T as rn,Tn as an,Tt as on,U as sn,Ua as cn,Un as ln,Ur as un,Ut as dn,V as fn,Va as pn,Vn as mn,Vr as hn,Vt as gn,W as _n,Wa as vn,Wn as yn,Wt as bn,X as xn,Xa as Sn,Xr as Cn,Xt as wn,Y as Tn,Ya as En,Yt as Dn,Z as On,Za as kn,Zi as An,Zn as jn,Zr as Mn,Zt as Nn,_ as Pn,_i as V,_n as Fn,_r as In,_t as Ln,a as Rn,aa as zn,ai as Bn,an as Vn,ar as Hn,at as Un,b as Wn,bi as Gn,bn as Kn,br as qn,bt as Jn,c as Yn,ca as Xn,cn as Zn,cr as Qn,ct as $n,dn as er,dr as tr,dt as nr,ei as rr,en as ir,eo as ar,er as or,et as sr,fa as cr,fi as lr,fn as ur,fr as dr,ft as fr,g as pr,ga as mr,gn as hr,gt as gr,h as _r,hn as vr,hr as yr,ht as br,i as xr,in as Sr,io as Cr,it as wr,j as Tr,jn as Er,jr as Dr,jt as Or,k as kr,kn as Ar,kt as jr,la as Mr,li as H,ln as Nr,lr as U,lt as Pr,ma as Fr,mn as Ir,mr as Lr,mt as Rr,n as zr,ni as Br,nn as Vr,no as Hr,nt as Ur,o as Wr,oi as Gr,on as Kr,oo as qr,or as Jr,ot as Yr,pa as W,pi as Xr,pn as Zr,pr as G,pt as Qr,q as $r,qi as ei,qn as ti,qr as ni,qt as ri,r as ii,rn as ai,ro as oi,rt as si,s as ci,si as li,sn as ui,sr as di,st as fi,t as pi,ta as mi,tn as K,to as hi,tr as gi,tt as _i,ua as q,un as vi,ur as yi,ut as bi,v as xi,vi as Si,vn as Ci,vt as wi,w as Ti,wi as Ei,wt as Di,x as Oi,xi as ki,xn as Ai,xt as ji,y as Mi,yi as Ni,yn as Pi,yr as Fi,yt as Ii,z as Li,za as Ri,zi,zn as Bi,zr as Vi,zt as Hi}from"./extension-hook-UDdYbDsl.js";import{l as Ui,m as Wi,p as Gi}from"./preload-helper-DY31Aviq.js";import{b as Ki,x as qi,y as Ji}from"./index-DM8ziIjn.js";import{a as Yi,i as Xi,n as Zi,o as Qi,r as $i,t as ea}from"./extensions-DF9U5f_Z.js";var ta=cr(()=>Ea),na=Ht(ta),ra=B({id:ni,payload:ze}),ia=B({...ra.fields,schemas:Mr(na)});function aa(e){let t={};for(let[n,r]of Object.entries(e))He(r)&&o(t,n,r);return Object.keys(t).length===0?A():P(t)}var oa=Mr(Mn(Kt,li)).pipe(ki(q(hn),{decode:pt(),encode:Yt(e=>p(e)||e.value===void 0?A():aa(e.value))})),sa=cr(()=>ua),ca=Ht(sa),la={annotations:oa,checks:ca},ua=Gr([B({_tag:W(`Filter`),representation:ia,annotations:oa,aborted:gt}),B({_tag:W(`FilterGroup`),representation:Mr(ia),annotations:oa,checks:Ct(sa)})]);function J(e){return B({_tag:W(e),...la})}var da=B({_tag:W(`Declaration`),representation:ra,annotations:oa,typeParameters:na,checks:ca}),fa=B({_tag:W(`Suspend`),annotations:oa,checks:Br([]),thunk:ta});function pa(e,t){return t.pipe(ki(B({type:W(e),value:t}),{decode:Et(e=>e.value),encode:Et(t=>({type:e,value:t}))}))}var ma=pa(`string`,Kt),ha=pa(`number`,Cn),ga=B({_tag:W(`Literal`),...la,literal:Gr([ma,pa(`number`,Zt),pa(`bigint`,nt),pa(`boolean`,gt)])}),_a=B({_tag:W(`UniqueSymbol`),...la,symbol:rr}),va=B({_tag:W(`Enum`),...la,enums:Ht(Br([Kt,Gr([ma,ha])]))}),ya=B({_tag:W(`TemplateLiteral`),...la,parts:na}),ba=B({isOptional:gt,type:ta,annotations:oa}),xa=B({_tag:W(`Arrays`),...la,elements:Ht(ba),rest:na}),Sa=B({name:Gr([ma,ha,pa(`symbol`,rr)]),type:ta,isOptional:gt,isMutable:gt,annotations:oa}),Ca=B({parameter:ta,type:ta}),wa=B({_tag:W(`Objects`),...la,propertySignatures:Ht(Sa),indexSignatures:Ht(Ca)}),Ta=B({_tag:W(`Union`),...la,types:na,options:q(B({mode:q(un([`anyOf`,`oneOf`]))}))}),Ea=Gr([da,B({_tag:W(`Reference`),$ref:ni}),fa,J(`Null`),J(`Undefined`),J(`Void`),J(`Never`),J(`Unknown`),J(`Any`),J(`String`),J(`Number`),J(`Boolean`),J(`BigInt`),J(`Symbol`),J(`ObjectKeyword`),ga,_a,va,ya,xa,wa,Ta]),Da=Gn(Fr(B({representation:ta,references:Mn(Kt,ta)})));function Oa(e){return Da(e)}function ka(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 Aa=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function ja(e){return e[Aa]?.()}var Ma=3.5,Na=4800;function Pa(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function Fa(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function Ia(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:Na;return t}function La(e){return Math.ceil(e.length/Ma)}function Ra(e){return Math.ceil(Ia(e)/Ma)}function za(e){let t=0;if(e.role===`system`)return La(Wi(e))+Ha(e.toolsAdded)+Ha(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return Ra(e.content);for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+Fa(n.arguments).length;return Math.ceil(t/Ma)}function Ba(e){let t=-1/0,n;for(let r=0;r<e.length;r++){let i=e[r];if(i.role===`assistant`){let e=i;e.timestamp>=t&&e.stopReason!==`aborted`&&e.stopReason!==`error`&&Pa(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function Va(e){let t=`messages`in e?e.messages:e,n=Ba(t);if(n){let e=Pa(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=za(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=za(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function Ha(e){return!e||e.length===0?0:La(Fa(e))}var Ua=0xffffffffffff,Wa=(1n<<41n)-1n,Ga=-1,Y;function Ka(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>Ua)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${Ua}`);let n=e===void 0?Math.max(t,Ga):e;e===void 0&&(Ga=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),Y===void 0)Y=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(Y===Wa)throw RangeError(`UUIDv7 generator sequence exhausted`);Y++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(Y>>37n&15n),r[7]=Number(Y>>29n&255n),r[8]=128|Number(Y>>23n&63n),r[9]=Number(Y>>15n&255n),r[10]=Number(Y>>7n&255n),r[11]=Number((Y&127n)<<1n)|r[11]&1;let a=Array.from(r,e=>e.toString(16).padStart(2,`0`));return`${a.slice(0,4).join(``)}-${a.slice(4,6).join(``)}-${a.slice(6,8).join(``)}-${a.slice(8,10).join(``)}-${a.slice(10).join(``)}`}function qa(e){return Gt(e,{onFailure:re,onSuccess:()=>h})}function Ja(e,t){return g(e,{onFailure:e=>O(t).pipe(x(re(e))),onSuccess:()=>t})}function Ya(e,t){let n={_tag:`open`},r=r=>Ja(e,t).pipe(O,R(e=>I(()=>{r.result=e,n={_tag:`closed`}}).pipe(x(r.settled.open),x(qa(e)))),ae);return T(()=>{if(n._tag===`closed`)return h;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(x(T(()=>{let t=e.result;return t===void 0?ye(Error(`Agent close settlement was not recorded`)):qa(t)})))}let e={_tag:`running`,settled:Ge(!1)};return n=e,r(e)})}function Xa(e,t,n){let{facts:r}=Za(e,t,n,null);return r.cancellationRequested?`cancelling`:Pt(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`&&vt(e,t,n.jobId)?`streaming`:`thinking`:`running_tool`}function Za(e,t,n,r){let i=Qr(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=Rr(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:nr(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:$r(e,t)},readProgress:()=>On(e,t,n.jobId),toolOutput:Wt(e,t,n.jobId)}}var Qa=new WeakMap;function $a(e,t){let n=gr(e,{sessionId:t}),r=Un(n);return r.length===0?null:Va(r).tokens}function eo(e,t,n,r=!0){let i;try{i=Ii(e.store,t)}catch(e){return mn(`session-context.preference`,e),w(void 0)}let a=JSON.stringify(i),o=Qa.get(e)??new Map;Qa.set(e,o);let c=r?o.get(t):void 0,l=e.model.describe;if(c?.cursor===n&&c.preference===a){if(c.value===void 0||l===void 0)return w(c.value);let e=c.value;return l({sessionId:t,preference:i}).pipe(s(({contextWindow:i})=>{if(e.window===i)return e;let s=Object.freeze({tokens:e.tokens,window:i});return r&&o.get(t)?.cursor===n&&o.set(t,{cursor:n,preference:a,value:s}),s}),se(t=>I(()=>(mn(`session-context.describe`,t),e))))}let u;try{u=$a(e.store,t)}catch(e){return mn(`session-context.figure`,e),w(void 0)}if(u===null)return r&&o.set(t,{cursor:n,preference:a,value:void 0}),w(void 0);if(l===void 0){let e=Object.freeze({tokens:u,window:null});return r&&o.set(t,{cursor:n,preference:a,value:e}),w(e)}return r&&o.set(t,{cursor:n,preference:a,value:Object.freeze({tokens:u,window:null})}),l({sessionId:t,preference:i}).pipe(s(({contextWindow:e})=>e),se(e=>I(()=>(mn(`session-context.describe`,e),null))),s(e=>{let i=Object.freeze({tokens:u,window:e});return r&&o.get(t)?.cursor===n&&o.set(t,{cursor:n,preference:a,value:i}),i}))}function to(e){return Object.freeze({list:e.assertOpen.pipe(s(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(x(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(x(e.extensions.call({scope:`agent`},t,n,r)))})}function no(e,t){return e.readQueueHead(t).pipe(R(t=>(t.state===`queued`?e.runningWork(t.jobId):w(null)).pipe(s(e=>({head:t,runningWork:e})))))}function ro(e,t,n){return no(t,n).pipe(s(({head:t,runningWork:r})=>Za(e.store,n,t,r)))}function io(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function ao(e,t,n,r){return no(t,n).pipe(R(({head:i,runningWork:a})=>Tr(e.store,n,()=>Za(e.store,n,i,a),r,()=>t.extensions.project(n),t=>({snapshot:t,context:eo(e,n,t.cursor,r?.before===void 0)}))),R(({snapshot:e,context:t})=>t.pipe(s(t=>io(e,t)))))}function oo(e,t,n){return e.assertOpen.pipe(x(z({try:()=>n(U(t)),catch:e=>e instanceof G?e:new G(`store`,`rejected`,`Session owner operation failed`)})))}function so(e,t){return z({try:()=>{let n=di(t);if(n._tag===`Failure`)throw new G(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:U(e),command:n.success})},catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Session command is invalid`)})}function co(e,t){return z({try:()=>Object.freeze({sessionId:U(e),options:tr(t)}),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Subscribe options are invalid`)})}function lo(e,t,n,r=!1){return t.assertOpen.pipe(x(ao(e,t,n,{includeSandboxFailures:r})),s(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function uo(e){return[[e],P({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function fo(e,t,n,r,i,a,o=!1,c=null){let l=Tn(c),u=[],d=()=>lo(e,t,r,o).pipe(s(e=>(l=Tn(e.baseline.progress),u=e.baseline.toolOutput,uo(e)))),f=t=>{let n=t.facts.queue,i=n.state===`running`?xn(e.store,r,n.commandId,l):null;if(i===void 0)return;let a=[];return i!==null&&(a.push({kind:`progress`,progress:i,activity:t.facts}),l={messageId:i.messageId,revision:i.revision,text:i.text.offset+i.text.append.length,thinking:i.thinking.offset+i.thinking.append.length}),(u.length!==t.toolOutput.length||u.some((e,n)=>e!==t.toolOutput[n]))&&(u=t.toolOutput,a.push({kind:`tool_output`,toolOutput:u,activity:t.facts})),a};return qn({after:i,delivery:a,awaitSignal:!1},i=>(i.awaitSignal?n.awaitSignal.pipe(R(e=>n.pollSignal.pipe(s(t=>t===void 0?e:Dt(e,t))))):n.pollSignal).pipe(R(a=>a===`closed`?w([[],A()]):a===`reset`?d():t.assertOpen.pipe(x(ro(e,t,r)),R(c=>{if(n.setQueued(c.facts.queue.state===`queued`),(a===`progress`||a===`activity`)&&i.delivery===`live`){let e=f(c);return e===void 0?d():w([[...a===`activity`?[{kind:`activity`,activity:c.facts}]:[],...e],P({...i,awaitSignal:!0})])}return Nt(e.store,r,i.after,i.delivery,c,()=>t.extensions.project(r),o,t=>{let n=t.kind===`page`?t.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`?[]:[e.cursor]).at(-1):void 0;return{page:t,latestCursor:n,context:t.kind===`page`&&!t.hasMore&&t.frames.some(e=>e.kind===`update`&&e.cursor!==i.after)?eo(e,r,n??null):w(void 0)}}).pipe(R(({page:e,latestCursor:t,context:n})=>{if(e.kind===`reset`)return d();e.hasMore||(u=c.toolOutput);let r=e.hasMore?[]:f(c);if(r===void 0)return d();let a={after:t??i.after,delivery:e.hasMore?i.delivery:`live`,awaitSignal:!e.hasMore};return n.pipe(s(n=>[[...n===void 0?e.frames:e.frames.map(e=>e.kind===`update`&&e.cursor===t?Object.freeze({...e,context:n}):e),...r],P(a)]))}))})))))}function po(e,t,n,r,i){return tn(t.assertOpen.pipe(x(co(r,i)),R(r=>Ce(n.register(r.sessionId),e=>I(e.close)).pipe(s(n=>fo(e,t,n,r.sessionId,r.options.after,`replay`,r.options.includeSandboxFailures===!0))))))}function mo(e,t){return z({try:()=>Object.freeze({sessionId:U(e),options:Jr(t)}),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Watch options are invalid`)})}function ho(e,t,n,r,i){return t.assertOpen.pipe(x(mo(r,i)),R(r=>Oe(i=>j(function*(){let o=yield*n.register(r.sessionId);return yield*i(t.assertOpen.pipe(x(ao(e,t,r.sessionId,r.options)),s(n=>(o.setQueued(n.activity.queue.state===`queued`),Object.freeze({snapshot:n,changes:fo(e,t,o,r.sessionId,n.cursor??void 0,`live`,r.options.includeSandboxFailures===!0,n.progress).pipe(Fi(I(o.close))),close:I(o.close)}))))).pipe(a(()=>I(o.close)))}))))}function go(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(x(e.door.admit(o)),R(e=>e.status===`accepted`?w({status:`accepted`,commandId:e.commandId}):E(new G(`runtime`,`unavailable`,`Session command was not admitted`))))}function _o(e,t,n,r,i){return t.assertOpen.pipe(x(oo(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&si(e.store,t,r.commandId,fr(e.store,e.meta.identityPath,i))})),x(Wn(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),R(e=>e===void 0?w({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(L({status:`accepted`,commandId:e.accepted.commandId}))))}function vo(e,t,n,r){return t.assertOpen.pipe(x(t.commit(pr(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),R(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function yo(e,t,n,r){return t.assertOpen.pipe(x(Mi(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),L(void 0))}function bo(e,t,n,r){return t.assertOpen.pipe(x(Ti(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function xo(e,t,n,r,i){return t.assertOpen.pipe(x(so(n,i)),R(t=>So(e,r).pipe(s(e=>({...t,checked:e})))),R(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return go(t,n,r,i);case`abort`:return vo(e,t,n,i).pipe(L(void 0));case`cancel`:return _o(e,t,n,r,i);case`branch`:return yo(e,t,n,r);case`fork`:return bo(e,t,n,r);case`operator`:return t.assertOpen.pipe(x(Li(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),L(void 0));case`title`:return t.commit(oo(t,n,t=>{nn(e.store,t,r.title)})).pipe(N(()=>I(()=>{Bi(e.store)})),L(void 0))}}))}function So(e,t){return z({try:()=>t===void 0?void 0:lt(e.meta,t),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Host metadata is invalid`)})}function Co(e,t){let n=Xt(e.store),r=(r,i)=>{function a(n){return xo(e,t,r,i,n)}return Object.freeze({command:a,withdraw:e=>t.assertOpen.pipe(x(t.door.withdraw(r,e))),abort:a({type:`abort`}),send:(e,t)=>I(()=>t?.requestId??Dr()).pipe(R(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return a(t?.images===void 0?r:{...r,images:t.images}).pipe(m(e=>e.requestId===n?e:new G(e.boundary,e.cause,e.message,n)))})),cancel:e=>a({type:`cancel`,...e}),latestPending:oo(t,r,t=>ke(e.store,t,e.meta?.identityPath===void 0||i===void 0?void 0:fr(e.store,e.meta.identityPath,i))),modelPreference:Object.freeze({read:oo(t,r,t=>Ii(e.store,t)),set:n=>z({try:()=>Lr(n),catch:()=>new G(`contract`,`invalid`,`Model preference is invalid`)}).pipe(R(n=>t.commit(oo(t,r,t=>(ji(e.store,t,n),t))).pipe(N(t=>I(()=>{Re(e.store,t)})),oe)))}),extension:e=>Object.freeze({call:(n,i,a)=>t.assertOpen.pipe(x(t.extensions.call({scope:`session`,sessionId:r},e,n,i,a)))}),read:n=>t.assertOpen.pipe(x(ao(e,t,r,n))),readSettlement:(i,a=0)=>C(j(function*(){yield*t.assertOpen;let o=yield*z({try:()=>({sessionId:U(r),...dr(yi({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*Ce(n.register(o.sessionId,`settlement`),e=>I(e.close)),l=kr(e.store,o.sessionId,o.commandId),u=yield*l;return u!==void 0||o.timeoutMs===0?u:yield*j(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*E(new G(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(D(o.timeoutMs),s(y))})),subscribe:i=>po(e,t,n,r,i),watch:i=>ho(e,t,n,r,i)})},i=Object.freeze({createSession:n=>t.assertOpen.pipe(x(Oi(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(x(Ve(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(x(kt(e.store,n))),extensions:to(t),session:e=>r(e,void 0),close:t.beginClose.pipe(x(n.close))});return Object.freeze({...i,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>oo(t,n,t=>e.store.transactionSync(()=>Fe(e.store,t,r))),read:n=>oo(t,n,t=>Or(e.store,t))}),withMeta:e=>Object.freeze({...i,session:t=>r(t,e)})})}function wo(e){let t=jt.safeParse(e.meta);return t.success&&t.data.delegation?.steer===!0}function To(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(en(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 go(e,t.to.sessionId,{requestId:t.key,delivery:r!==void 0||wo(t)?`steer`:`followUp`,type:`prompt`,text:t.content},n,t,r)}var Eo=B({fork:un([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:Vi.pipe(H(mt(0)),H(ei(2**53-1)))});function Do(e,t){let n=Ue(e.schema)(t);if(n._tag===`Failure`)throw new Xi({reason:`encode`,message:`Session document does not match its schema`});let r=V(ln)(n.success);if(r._tag===`Failure`)throw new Xi({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 Xi({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function Oo(e){return{...Si(Eo)(e),schema:Oa(mr(e.schema)),initial:Do(e,e.initial)}}var ko=64,Ao=un([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),jo=Ht(Ao).pipe(H(An(10))),Mo=B({protocol:ut(`shiitake.extension/v0`),id:Wr,version:Yn,requests:jo}),No=Ht(B({id:Wr,capabilities:jo,grantKey:q(Wr)})).pipe(H(An(ko))),Po=Kt.pipe(H(zn(/^[a-z][A-Za-z0-9_]{0,63}$/u))),Fo=V(Mo,{onExcessProperty:`error`}),Io=V(No,{onExcessProperty:`error`}),Lo=V(Po);function X(e){return new G(`extensions`,`invalid`,e)}function Ro(e){return new Set(e).size!==e.length}function zo(e){return JSON.stringify(e,(e,t)=>me(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function Bo(e){return Ee({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 G(`extensions`,`rejected`,`Extension digest failed`)})}function Vo(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:Oa(mr(t.input)),output:Oa(mr(t.output))}])),projection:r.projection===null?null:Oa(mr(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,Oa(mr(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Oo(t)]))};return o===void 0?c:{...c,catalog:o}}function Ho(e){if(Fo(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(Ro(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`||Lo(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 Uo(e){return j(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*z({try:()=>{if(t.length>ko)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=ja(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(Lo(e)._tag===`Failure`)throw X(`Session document name is invalid`);Oo(t)}let r=Ho(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(Ro(e.map(({manifest:e})=>e.id)))throw new G(`extensions`,`conflict`,`Extension identities conflict`);let r=Io(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(Ro(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||Ro(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 G(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new G(`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 G?e:X(`Extension roster is invalid`)});return yield*De(r,e=>j(function*(){let t=`sha256:${yield*Bo(yield*z({try:()=>zo(Vo(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*Bo(zo([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:Si(ci)(t),fingerprint:Si(Rn)(r)})}))})}function Wo(e){return Bo(zo({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}var Go=M().min(1).max(256),Ko=_([`create`,`manage`,`read`,`send`,`delegate`]),qo=S(()=>F({actor:Go,workflowRunId:Go.optional(),toolCallInputDigest:M().regex(/^[a-f0-9]{64}$/).optional(),session:F({agentId:Go,sessionId:Go}).optional()}));S(()=>F({agents:b([_e(`all`),v(Go)]),actions:v(Ko).max(5),expiresAt:fe().int().nonnegative(),provenance:qo,meta:de().optional(),maxDepth:fe().int().min(1).max(8).optional()})),Pe({family:`agent`,version:1,kinds:{agent:{prefix:`agent`}}}),S(()=>F({agent_id:M(),name:M(),actor_user_id:M(),created_by:M().min(1).max(256).nullable(),created_at:fe().int().nonnegative(),updated_at:fe().int().nonnegative()})),S(()=>F({request_id:M(),actor_user_id:M(),name:M(),agent_id:M(),computer_mode:M().min(1).max(4096)})),S(()=>F({name:M().min(1).max(256),requestId:M().min(1).max(256),configuration:M().min(1).max(4096),createdBy:M().min(1).max(256).nullable().optional()})),S(()=>F({name:M().min(1).max(256)}));var Jo=class extends Error{status;code;constructor(e,t){super(t),this.status=e,this.code=t}};S(()=>F({requestId:Go,agentId:Go,sessionId:Go.optional(),delivery:_([`followUp`,`steer`]).optional(),goal:b([M().min(1).max(4e3),_e(!1)]).optional(),text:M().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`})),we({delegation:jt.shape.delegation});var Yo=S(()=>F({input:M(),mail:M(),state:_([`pending`,`held`,`accepted`,`undeliverable`]),receipt:M().nullable()})),Xo=Si(Ei(Ai));function Zo(e){let t=ka(e).unsettled()[0];if(t===void 0)return;let n=Yo.parse(t),r=Xo(n.mail),i=r.to.sessionId;if(i===void 0)throw new Jo(503,`partial_init`);return{agentId:r.to.agentId,sessionId:i,commandId:_r(M().parse(n.receipt)).commandId}}function Qo(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function $o(e){return Qo({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function es(e){return new G(`model`,`rejected`,e)}function ts(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 ns(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 rs(e,t,n){let r=Be(),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)gn(t,r);return r}function is(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 as(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`&&!is(e,a+1,n,i)&&r.push(a)}return r}function os(e,t,n,r){let i=as(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=za(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=os(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...ss(e,t,i)}}function ls(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=Qt(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=Va(ns(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=rs(u,e,r);for(let e of d)gn(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 us={enabled:!0,maxRetries:3,baseDelayMs:2e3};function ds(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??Ka()};return jn(()=>Promise.resolve((r??gi)(e,Ui(t),i)).then(e=>e.result()),us,i.signal)}function fs(e){return{systemPrompt:Ut,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function ps(e,t,n){let r=e.previousSummary??``,i=t?_t:It,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${dn(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function ms(e){return`# Conversation\n${dn(e.turnPrefixMessages)}\n\n# Instructions\n${rt}`}async function hs(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await ds(e,fs(r),o,a),c=wt(s,i);if(c!==void 0)throw Error(c);return s}function gs(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):hs(t,n,r,ps(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function _s(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):hs(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,ms(e),`Turn prefix summarization`,r)}function vs(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.`:Gi(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${Gi(n.content)}`,i=t===void 0?n.usage:ts(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=Gi(t.content),i=t.usage}let a=Hi(e.fileOps);return{summary:r+dt(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function ys(e,t,n,r,i){return vs(e,await gs(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 _s(e,t,n,i):void 0)}function bs(e,t,n,r){return Ee({try:i=>ys(e,t,i,r,n),catch:e=>es(e instanceof Error?e.message:String(e))})}function xs(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var Ss=new WeakMap;function Cs(e){return Ss.has(e)}function ws(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return pn(t,I(()=>{Es(e,r)})).pipe(x(u(i,t)),s(t=>(r.fiber=t,Ss.set(e,r),r)))}function Ts(e){let t=e.summary;return e.summary=void 0,t}function Es(e,t){t.fiber=void 0,t.summary=void 0,Ss.get(e)===t&&Ss.delete(e)}function Ds(e){return new G(`runtime`,`rejected`,e)}var Os={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`},ks=class extends G{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,Os[e]),this.phase=e,this.usage=t}get diagnostic(){return Os[this.phase]}};function As(e,t){let n=$e(e,t),r=Di(e),i=[];for(let t of e){let e=Fn(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:Ir(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:hr(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 js(e,t,n){return z({try:()=>gr(e,{sessionId:t,workId:n}),catch:()=>Ds(`Woodstock selected lineage is unavailable`)})}function Ms(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return Un([...e,i],r).reduce((e,t)=>e+za(t),0)}function Ns(e,t,n){return T(()=>(it(e.store,e.sessionId,n.trigger),Ps(e,t,n).pipe(pe(I(()=>{xt(e.store,e.sessionId)})))))}function Ps(e,t,n){return j(function*(){let r=ls(As(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*bs(r,e.model,e.stream,n.instructions),o=yield*Ls(e,r,a,i.id);return yield*Bs(e,t,a,n,i.id,o)})}var Fs=Gr([B({type:ut(`accepted`),receipt:Zr}),B({type:ut(`discarded_by_policy`)})]),Is=V(Fs);function Ls(e,t,n,r){return e.handoff===void 0?w(void 0):e.handoff.consume(xs(t,n,e.sessionId,r)).pipe(m(()=>new ks(`handoff`,n.usage)),R(e=>{let t=Is(e);return t._tag===`Failure`?E(new ks(`handoffResult`,n.usage)):w(t.success.type===`accepted`?t.success.receipt:void 0)}))}function Rs(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=Ms(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[Ot(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 zs(e,t,n){let r=[...t,n];return{path:r,messages:Un(r,e.workId)}}function Bs(e,t,n,r,i,a){let o=Rs(e,t,n,r,i,a);return o===void 0?w(void 0):z({try:()=>xi(e.store,o),catch:e=>e instanceof G?e.cause===`conflict`?new ks(`conflict`):e:Ds(`Woodstock compaction append failed`)}).pipe(s(n=>zs(e,t,n)))}function Vs(e){return e instanceof ks?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function Hs(e,t){return z({try:()=>{Pn(e.store,t)},catch:e=>e instanceof G?e:Ds(`Compaction notice could not be recorded`)})}function Us(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return Hs(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:Vs(n),usage:n instanceof ks?n.usage:void 0})}function Ws(e,t,n){return le(Ns(e,t,n)).pipe(R(t=>t._tag===`Success`?w(t.success):Us(e,n.trigger,t.failure).pipe(L(void 0))))}var Gs={trigger:`threshold`,resumesRun:!1};function Ks(e,t,n,r){return t.stopped||Cs(e.store)||!ot(n,e.model.contextWindow,e.settings)?h:r.pipe(R(n=>qs(e,t.scope,n)),s(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function qs(e,t,n){let r=n.at(-1),i=ls(As(n,e.workId),e.settings);return r===void 0||i===void 0?w(void 0):ws(e.store,t,t=>Js(e,i,r.id,t))}function Js(e,t,n,r){return T(()=>(it(e.store,e.sessionId,`threshold`),bs(t,e.model,e.stream).pipe(s(e=>{r({preparation:t,result:e,selectionTail:n})}),pe(I(()=>{xt(e.store,e.sessionId)})))))}function Ys(e,t,n,r){return T(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?w(void 0):(t.slot=void 0,le(Qe(a).pipe(R(()=>Zs(e,i)),R(t=>t===void 0?w(void 0):Qs(e,t,n)))).pipe(R(n=>n._tag===`Success`&&n.success!==void 0?w(n.success):(t.stopped=!0,n._tag===`Success`?w(void 0):Us(e,`threshold`,n.failure).pipe(L(void 0)))),pe(I(()=>{Es(e.store,i)}))))})}function Xs(e,t,n){return Hs(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(L(void 0))}function Zs(e,t){let n=Ts(t);if(n===void 0)return w(void 0);let{result:r,selectionTail:i}=n;return z({try:()=>Yr(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof G?e:Ds(`Woodstock compaction head is unavailable`)}).pipe(R(t=>t===`stale`?Xs(e,r,`stale`):Ls(e,n.preparation,r,i).pipe(s(e=>({result:r,selectionTail:i,receipt:e})))),pe(I(()=>{Es(e.store,t)})))}function Qs(e,t,n){return js(e.store,e.sessionId,e.workId).pipe(R(r=>{let i=Rs(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?w(void 0):bn(i.tokensAfter,e.model.contextWindow,e.settings)?Xs(e,t.result,`insufficient`):z({try:()=>qe(e.store,i),catch:e=>e instanceof G?e.cause===`conflict`?new ks(`conflict`):e:Ds(`Woodstock compaction append failed`)}).pipe(R(n=>n===`stale`?Xs(e,t.result,`stale`):w(zs(e,r,n))))}))}function $s(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return w(n);let r=Va(e.messages).tokens;return bn(r,e.model.contextWindow,e.settings)?Ws(e,e.path,Gs).pipe(s(e=>e??n)):Ks(e,t,r,w(e.path)).pipe(L(n))}function ec(e,t){let n=St(e.message,t.contextWindow),r=or(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function tc(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function nc(e,t,n,r){if(!e.settings.enabled)return w(void 0);let i=bn(Va([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?js(e.store,e.sessionId,e.workId):w(void 0)}function rc(e,t,n){return(r,i)=>j(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=Va(r).tokens,s=bn(o,e.model.contextWindow,e.settings),c=yield*Ys(e,n,Gs,s);if(c!==void 0)return a(c);let l=js(e.store,e.sessionId,e.workId);if(!s){yield*Ks(e,n,o,l);return}let u=yield*Ws(e,yield*l,Gs);return u===void 0?void 0:a(u)})}function ic(e,t,n){return j(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,rc(e,t,n)),o=ec(a,e.model),s=o.retry&&!i,c=yield*Ys(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:tc(c.messages)},i=!0;continue}let l=yield*nc(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*Ws(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:tc(u.messages)},i=!0}})}function ac(e){return j(function*(){let t={scope:yield*Se,slot:void 0,stopped:!1};return yield*ic(e,e.settings.enabled?yield*$s(e,t):e,t)})}function oc(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?w(`compacted`):Ns(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(k(t=>Us(e,`manual`,t)),R(t=>t===void 0?Us(e,`manual`,void 0).pipe(L(`nothing_to_compact`)):w(`compacted`)))}var sc=Vi.pipe(H(zi(0)),H(ei(2**53-1))),cc=B({reserveTokens:q(sc),keepRecentTokens:q(sc),backgroundTokens:q(sc)}),lc=B({enabled:q(gt),reserveTokens:q(sc),keepRecentTokens:q(sc),backgroundTokens:q(sc),modelOverrides:q(Mn(Kt,cc))}),uc=V(lc,{onExcessProperty:`error`});function dc(e){let t=uc(e??{});if(t._tag===`Failure`)throw new G(`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??Mt.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??Mt.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??Mt.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??Mt.backgroundTokens}}}function fc(e,n,i){return j(function*(){let a=yield*r(i);(yield*t(Qe(a).pipe(L(!0)),Te(1e3).pipe(L(!1))))||(yield*d(`shiitake_run_finalizer_hung`).pipe(ge({workId:n,finalizer:e})))})}var pc={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},mc=class extends G{phase;constructor(e){super(`runtime`,`rejected`,pc[e]),this.phase=e}get diagnostic(){return pc[this.phase]}},hc={model:`model-failed`,tool:`tool-failed`,control:`control-failed`,listener:`listener-failed`},gc=class extends G{reason;constructor(e,t){super(`runtime`,`rejected`,`Mule rejected the durable command run`,void 0,t),this.reason=e}get diagnostic(){return hc[this.reason]}};function _c(e){return new gc(e.phase,e)}function vc(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+Qo({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function yc(e,t,n,r,i,a,o){let s=e.tools,c=i.modules??[],l=[...c,...a];return s===void 0?c.length>0||o.length>0?E(new mc(`missing`)):w([]):j(function*(){let i={sessionId:t,commandId:n};r!==void 0&&(i={...i,meta:r});let a={sources:s.sources,session:i,sandbox:s.sandbox,onSandboxFailure:r=>Ie(e.store,{sessionId:t,commandId:n},r).pipe(te),modules:[...s.modules,...l],tools:o,access:{...s.access,sessionGrants:()=>Or(e.store,t)?.grants??{}}},c=yield*vn();yield*be(()=>fc(`tools`,n,ct(c,Ae(void 0))));let u=yield*(yield*at(s.execution===void 0?a:{...a,execution:s.execution}).pipe(f(Le,c),m(()=>new mc(`runtime`)))).acquire().pipe(f(Le,c),m(()=>new mc(`lease`)));return[u.executeTool,...u.tools]})}function bc(e,t,n,r,i,a,o){return C(j(function*(){let c=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),u=c.release;u!==void 0&&(yield*be(()=>fc(`instructions`,t.command.entry.workId,I(u))));let d=yield*Ji(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference}).pipe(s(e=>({...e,release:fc(`model`,t.command.entry.workId,e.release)})))),f=yield*yc(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,c,r,i),g=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),_=yield*Xe(e.store,g,n),v=t=>sn(e.store,{sessionId:g.sessionId,workId:g.commandId,delivery:t}).pipe(s(e=>e.map(({message:e})=>e)),m(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof G?e.message:`Session control delivery failed`}))),ee=t.resume,te=dc(e.compaction)(d.model),ne,y=0;return{run:yield*ac({store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:d.model,stream:d.stream,handoff:a,settings:te,path:t.path,messages:t.messages,resuming:ee!==void 0,run:(t,n)=>{y=0;let r=ee;ee=void 0;let i,a=e=>{if(e.type===`run_end`&&e.outcome===`failed`)return i=e,h;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=d.providerError?.(e.value);if(t!==void 0)return _({...e,value:{...e.value,providerError:t}})}return _(e)},u={model:d.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??yt,retryAfterMs:d.retryAfterMs,retryable:d.retryable,systemPrompt:c.text,prepareSystemPrompt:()=>(o===void 0?w([]):o()).pipe(s(e=>c.text+e.map(({name:e,text:t})=>`\n\n[extension:${e}]\n${t}`).join(``)),m(e=>({_tag:`MuleError`,phase:`model`,message:`Extension prompt is unavailable`,cause:e}))),messages:t,resume:r,tools:f,getSteeringMessages:()=>v(`steer`),prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(m(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>(t.type===`retry_finished`&&!t.success&&(y=t.attempt+1),Jt(e.store,g,vc(t,d.model),t.turn))};return ti.run(d.stream===void 0?u:{...u,stream:d.stream},a).pipe(l(e=>{if(i===void 0)return h;if(kn(e)){let t=e.value.modelLimitReason??d.failureReason?.(e.value.message)??$o(e.value);return ne=(y>1&&e.value.modelLimitReason===void 0&&d.rejection?.(e.value.message)?.code!==`usage-limit-reached`?`The model failed ${String(y)} times on this conversation: ${t}`:t).slice(0,200),_(i,ne)}let t=Cr(e.cause);return _(i,p(t)?Qo({runId:i.run.value,provider:d.model.provider,model:d.model.id}):t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):`runtime:rejected: ${_c(t.value).diagnostic}`)}),m(e=>e.phase===`model`?new G(`model`,`rejected`,e.message,void 0,e):_c(e)))}}),failureReason:ne}}))}function xc(e,t,n){return C(j(function*(){let r=yield*Ji(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),i=t.command.entry;return yield*oc({store:e.store,sessionId:t.command.sessionId,workId:i.workId,model:r.model,stream:r.stream,handoff:n,settings:dc(e.compaction)(r.model),path:t.path,instructions:vr(i)?i.instructions:void 0})}))}var Sc=Object.freeze({maxRecoveries:2});function Cc(e){return new G(`runtime`,`rejected`,e)}function wc(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof mc||e instanceof gc||e instanceof ks||e instanceof _i?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function Tc(e,t){return d(`shiitake_run_failed`,Ri(t)).pipe(ge({workId:e,reason:`${t.boundary}:${t.cause}`}))}function Ec(e,t,n,r){return j(function*(){Re(e.store,n.queue);let i=yield*z({try:()=>an(n),catch:()=>Cc(`Agent work payload is invalid`)}),a=yield*rn(e.store,i.work);if(a.abnormalTerminal!==void 0)return{kind:a.abnormalTerminal};let o=r?.incompatibleMigrations()[0];if(o!==void 0)return yield*d(`shiitake_run_contract_changed`).pipe(ge({workId:n.jobId,terminal:`contract_changed: ${o}`})),yield*E(Cc(`contract_changed: ${o}`));let c=new Set(r?.runParticipants().map(([e])=>e)??[]);if(vr(a.command.entry))return yield*xc(e,a,r?.compactionHandoff(c)),yield*fn(e.store,{sessionId:a.command.sessionId,commandFactId:i.work.commandFactId,workId:a.command.entry.workId,outcome:`completed`}),{kind:`completed`};let l=yield*z({try:()=>Me(e.store,i.work.sessionId,i.work.commandFactId,a.command.entry.workId),catch:()=>Cc(`Accepted run origin is unavailable`)}),u={sessionId:a.command.sessionId,workId:a.command.entry.workId,origin:l===null?null:{extensionId:Si(xr)(l.extensionId),correlation:l.correlation}},f=r===void 0?[]:yield*r.filesForRun(u,c),p=r===void 0?[]:yield*De([...c],t=>r.modulesForRun(u,new Set([t])).pipe(R(n=>z({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>yn.grantAs(e,r))},catch:()=>Cc(`Extension tools are invalid`)})))).pipe(s(e=>e.flat())),m=r?.compactionHandoff(c),{run:h,failureReason:g}=yield*bc(e,a,{core:f.length===0?t:yield*Wo(f.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},p,f,m,r===void 0?void 0:()=>r.promptSections(u,c));switch(h.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:g??$o(h)}}}).pipe(se(e=>Tc(n.jobId,e).pipe(L(wc(e)))))}var Dc=V(sr,{onExcessProperty:`error`}),Oc=V(Bn(gt)),kc=V(Ci,{onExcessProperty:`error`});function Ac(e){if(e.reply===void 0)return;let t=dr(kc(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 G(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function jc(e,t){let n=t.mail;return n?.from.kind===`agent`&&n.replyTo.length>0?{agentId:n.from.agentId,sessionId:n.from.sessionId,name:Ft(t.meta)?.name??n.from.agentId}:t.continuesWorkId===void 0?void 0:Rt(e,t.sessionId,t.continuesWorkId)}function Mc(e){let t=t=>({sessionId:U(t.sessionId),requireExistingSession:dr(Oc(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:dr(Hn(t.command),`Session command is invalid`),origin:dr(Dc(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:Ac(t),onAccepted:t.onAccepted,continuesWorkId:t.continuesWorkId,meta:t.meta===void 0?void 0:lt(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(wr(e.owner,r,a.requestId),t.requireExistingSession&&!Pr(e.owner,r))throw new G(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&br(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&br(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested&&!$n(e.owner,r,o.jobId)?o.jobId:void 0,c=Ur(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=jc(e.owner,t);n!==void 0&&Ar(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)=>T(()=>{let i=new Map,a=z({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof G?e:new G(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(N(()=>I(()=>{for(let[t,n]of i)n&&Re(e.owner,t)})),N(()=>i.size>0?e.requestWake:h))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>z({try:()=>({sessionId:U(t),requestId:Qn({requestId:n})}),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(R(t=>r(()=>Ke(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>z({try:()=>t(e),catch:e=>e instanceof G?e:new G(`contract`,`invalid`,`Session command is invalid`)}).pipe(R(e=>r(t=>t(e),n??`request`)))})}var Nc=`core`,Pc=`core-report`,Fc=256,Ic=1048576,Lc=512,Rc=64,zc=new TextEncoder,Bc=V(Ht(B({name:Kt.pipe(H(zn(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:Kt.pipe(H(mi(1)),H(Xn(e=>zc.encode(e).byteLength<=8192)))})).pipe(H(An(16)))),Vc=class extends Error{};function Hc(e){return e.length<=Lc?e:`${e.slice(0,511)}…`}var Uc=Xr(Ei(ln));function Wc(e){return e instanceof Yi?e.reason:`${e._tag}: ${e.message}`}function Gc(e){return e instanceof Yi||e instanceof Xi||e instanceof ea||e instanceof Zi}function Kc(e,t){let r=Cr(t);if(ce(r)){let t=r.value;return t instanceof Yi?Hc(t.reason):Hc(Gc(t)?`${e}: ${Wc(t)}`:`${e} failed`)}let i=n(oi(t));return ce(i)?i.value instanceof Error?Hc(i.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${i.value.message}`):Hc(`${e} defect`):Hc(`${e} was interrupted`)}function qc(e){let t=Cr(e);return p(t)||t.value instanceof Yi}function Z(e,t){return new Xi({reason:e,message:t})}function Jc(e,t){return e.length>=1&&e.length<=Fc?w(e):E(Z(`bound`,`${t} must be 1..256 characters`))}function Yc(e){let t=Hc(e.message);if(e instanceof Zi)switch(e.reason){case`invalid`:return new G(`contract`,`invalid`,t);case`conflict`:return new G(`store`,`conflict`,t);case`not_found`:return new G(`store`,`rejected`,t);case`rejected`:return new G(`extensions`,`rejected`,t)}if(e instanceof ea)switch(e.reason){case`invalid`:return new G(`contract`,`invalid`,t);case`conflict`:return new G(`contract`,`conflict`,t);case`closed`:return new G(`runtime`,`closed`,t)}return e.reason===`bound`?new G(`contract`,`invalid`,t):new G(`store`,`unavailable`,t)}function Xc(e){let{owner:t}=e,n=new WeakMap,r=new Map,i=new Set,o,l=new Set,u=new Set,m,g=e=>Object.freeze({extensionId:e}),_=e=>R($i,t=>t.extensionId===e?h:ye(Error(`Extension read used another extension's context`))),v=e=>R(Qi,t=>{let r=n.get(t);return r?.extensionId===e?w(r):ye(Error(`Extension write used outside its own core transaction`))}),y=e=>z({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),b=(e,t)=>e.admitted.grants.has(t)?h:E(Z(`unavailable`,`Extension is not granted ${t}`));function S(e,n,r){let i=e.admitted.id,a=lr(Ei(r.schema)),c=Ni(r.schema),l=e=>{let t=a(e);return t._tag===`Failure`?E(Z(`decode`,`Stored ${n} record is invalid`)):w(t.success)};return Object.freeze({peek:r=>{if(o!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);let s=ai(t,i,n,r);if(s===void 0)return A();let c=a(s);if(c._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return P(c.success)},peekPage:r=>{if(o!==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>Rc)throw Z(`bound`,`Page limit must be 1..64`);return Sr(t,i,n,r).map(e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success})},get:r=>_(i).pipe(x(b(e,`state`)),x(y(()=>ai(t,i,n,r))),R(e=>e===void 0?w(A()):l(e).pipe(s(P)))),page:r=>_(i).pipe(x(b(e,`state`)),x(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=Rc?h:E(Z(`bound`,`Page limit must be 1..64`))),x(y(()=>Sr(t,i,n,r))),R(e=>De(e,l))),put:a=>v(i).pipe(x(b(e,`state`)),x(T(()=>{let e=c(a);if(e._tag===`Failure`)return E(Z(`encode`,`The ${n} record does not match its schema`));let o=JSON.stringify(e.success);if(zc.encode(o).byteLength>Ic)return E(Z(`bound`,`The ${n} record exceeds 1 MiB`));let s=r.index?.(a)??null;return ue([Jc(r.key(a),`A record key`),s===null?w(null):Jc(s,`A record index`)]).pipe(R(([e,r])=>y(()=>{Nr(t,i,n,e,r,o)})))}))),remove:r=>v(i).pipe(x(b(e,`state`)),x(y(()=>{Nn(t,i,n,r)})))})}function ie(e,n,r){let i=e.admitted.id,a=lr(Ei(r.schema)),o=Ni(r.schema),s=()=>{if(!l.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>Fc)throw Z(`bound`,`A record key must be 1..256 characters`);return e},u=e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success};return Object.freeze({get:e=>{s();let r=ai(t,i,n,c(e));return r===void 0?A():P(u(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>Rc)throw Z(`bound`,`Page limit must be 1..64`);return Sr(t,i,n,e).map(u)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${n} record does not match its schema`);let l=JSON.stringify(a.success);if(zc.encode(l).byteLength>Ic)throw Z(`bound`,`The ${n} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),Nr(t,i,n,c(r.key(e)),u,l)},remove:e=>{s(),Nn(t,i,n,c(e))}})}function ae(e){let n=e.admitted.id;return Object.freeze({set:(r,i)=>v(n).pipe(N(()=>b(e,`timers`)),N(()=>Jc(r,`A timer key`)),N(()=>Number.isSafeInteger(i)&&i>=0?h:E(Z(`bound`,`A timer instant is invalid`))),R(e=>y(()=>{ur(t,n,r,i),e.timersChanged=!0}))),cancel:r=>v(n).pipe(N(()=>b(e,`timers`)),R(e=>y(()=>{qt(t,n,r),e.timersChanged=!0}))),read:r=>_(n).pipe(x(b(e,`timers`)),x(y(()=>ui(t,n,r))),s(ne))})}function oe(n){let r=n.admitted.id,i=(i,a)=>v(r).pipe(N(()=>b(n,`attention`)),R(n=>z({try:()=>{U(i),a(),Ye(t,i,e.readQueueHead(i)),n.observed.add(i)},catch:e=>e instanceof Xi&&e.reason===`session_absent`?e:e instanceof G&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,n)=>{let a=V(yr,{onExcessProperty:`error`})(n.waitingOn===void 0?n:{...n,inbox:!1});return a._tag===`Failure`?E(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!Pr(t,e))throw Z(`session_absent`,`Attention Session is absent`);tt(t,e,r,a.success)})},awaitsPerson:e=>_(r).pipe(N(()=>b(n,`attention`)),x(y(()=>Er(t,e)))),clear:(e,n)=>Jc(n,`An attention id`).pipe(x(i(e,()=>{Ne(t,e,r,n)})))}}function C(e){let t=e.admitted.id;return n=>v(t).pipe(R(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 ea({reason:e instanceof G?e.cause===`conflict`?`conflict`:e.cause===`archived`?`archived`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof G?e.message:`Session command is invalid`})}):E(new ea({reason:`closed`,message:`Extension is not granted send`}))))}function le(r,i,a){return T(()=>{let o,c,l=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let t=g(r.admitted.id);c={extensionId:r.admitted.id,admit:e,observed:new Set,timersChanged:!1},n.set(t,c),u.add(r.admitted.id);let a=m;m=c;try{o=ve(i.pipe(f(Qi,t),f($i,t)))}finally{m=a,n.delete(t),u.delete(r.admitted.id)}if(Sn(o))throw l;return o.value},a).pipe(s(()=>{if(o===void 0)throw Error(`Extension transaction returned no exit`);return o}),se(e=>o!==void 0&&Sn(o)?w(o):E(e)),N(n=>kn(n)&&c!==void 0?j(function*(){for(let e of c?.observed??[])Re(t,e);a===`request`&&c?.timersChanged===!0&&(yield*e.requestWake)}):h))})}function D(n){let r=``;for(let i=0;i<In;i+=Rc){let i=At(t,n,r);for(let n of i)Ye(t,n,e.readQueueHead(n)),queueMicrotask(()=>{Re(t,n)});let a=i.at(-1);if(i.length<Rc||a===void 0)return;r=a}}function k(e,n,r,i){let a=Date.now();e.status=`stopped`,e.reason=n,e.stoppedAt=a;let o=z({try:()=>{let r=()=>{er(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:a,revision:e.admitted.revision}),D(e.admitted.id)};i===`own-transaction`?t.transactionSync(r):r()},catch:t=>new G(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)});return j(function*(){let t=yield*O(o);return yield*d(`shiitake_extension_stopped`).pipe(ge({extensionId:e.admitted.id,reason:n,cause:r===void 0?null:Ri(r),durable:kn(t)})),yield*t})}function de(e,n,r){e.status=`stopped`,e.reason=n,e.stoppedAt=Date.now();let i=()=>{er(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:e.stoppedAt,revision:e.admitted.revision}),D(e.admitted.id)};try{r===`own-transaction`?t.transactionSync(i):i()}catch(t){throw new G(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)}}function fe(e,n,r){let i=t=>{if(m?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return U(t),m},a=a=>{i(a);let o=Ln(t,a,e.admitted.id,n)??Do(r,r.initial);if(zc.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=V(Ei(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));on(t,o,e.admitted.id,n,Do(r,l)),c.observed.add(o)}})}function pe(e){let n=new Set;return Object.freeze({collection:(t,n)=>S(e,t,n),updateCollection:(t,n)=>ie(e,t,n),document:(t,n)=>fe(e,t,n),update:r=>{let i=e.admitted.id;if(e.status!==`running`||!e.admitted.grants.has(`state`)||l.has(i)||u.has(i)||o===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let e=t.transactionSync(()=>{l.add(i);try{return ii(r,void 0)}finally{l.delete(i)}});for(let e of n)Re(t,e);return e}catch(t){if(!(t instanceof pi))throw t;let n=t.message;throw de(e,n,`own-transaction`),new Yi({reason:n})}finally{n.clear()}},observeUpdate:t=>{if(!l.has(e.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);n.add(U(t))},context:Object.freeze({manifest:e.admitted.manifest,revision:e.admitted.revision,grants:Object.freeze([...e.admitted.grants]),send:C(e),timers:ae(e),attention:oe(e),isObserved:n=>e.status===`running`&&ht(t,n),sessionPosition:n=>_(e.admitted.id).pipe(x(b(e,`state`)),x(y(()=>{let e=U(n);if(!Pr(t,e))throw Z(`unavailable`,`Session timeline is unavailable`);return wi(t,{sessionId:e})?.newestSequence??0}))),hasPendingSteer:n=>_(e.admitted.id).pipe(x(b(e,`run_tools`)),x(y(()=>fi(t,U(n.sessionId),n.workId)))),workSender:n=>_(e.admitted.id).pipe(x(b(e,`run_tools`)),x(y(()=>Rt(t,U(n.sessionId),n.workId)??null))),hasSuccessfulToolResult:(n,r)=>_(e.admitted.id).pipe(x(b(e,`run_tools`)),x(y(()=>bi(t,U(n.sessionId),n.workId,r)))),observe:t=>v(e.admitted.id).pipe(s(e=>{e.observed.add(t)})),transact:t=>(e.status===`running`?le(e,t,`request`).pipe(te):E(new Yi({reason:e.reason??`Extension is stopped`}))).pipe(R(t=>{if(kn(t))return w(t.value);if(!qc(t.cause))return re(t.cause);let n=Kc(`transact`,t.cause);return k(e,n,t.cause,`own-transaction`).pipe(R(()=>E(new Yi({reason:n}))))}))})})}function M(e){let{id:n,definition:r,revision:i}=e.admitted,a=r.state.version,o=Vn(t,n);if(o!==void 0&&o.version>a)throw new G(`extensions`,`conflict`,`Stored ${n} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=ir(t,n).map(e=>({collection:e.collection,key:e.key,value:Uc(e.valueJson)}));for(let t=o.version;t<a;t+=1){let i=r.state.migrations[t];if(i===void 0)throw new G(`extensions`,`state_reset_required`,`State reset required for ${n}: stored version ${String(o.version)}, declared version ${String(a)}. An operator must authorize the reset; stored records have not been changed.`);try{e=e.flatMap(e=>i(e))}catch(e){throw new Vc(`Failed ${n} state migration from ${String(t)}`,{cause:e})}}Dn(t,n);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new Vc(`Migrated ${n} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new Vc(`Migrated ${n} ${i.collection} record is invalid`);Nr(t,n,i.collection,i.key,a.success,JSON.stringify(i.value))}}vi(t,n,a,i)}function me(e,t,n=!1){let r=pe(e);return j(function*(){let i=yield*cn(t);e.scope=i;let a=yield*T(()=>e.admitted.definition.activate(r)).pipe(f(Le,i),O);if(kn(a)){e.hooks=a.value;return}if(yield*ct(i,a),n)return yield*E(new G(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${qr(a.cause)}`));yield*k(e,Kc(`activation`,a.cause),a.cause,`own-transaction`)})}let he=e=>[...r.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function _e(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 F(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 be(e,t,n){return O(n.pipe(f($i,g(e.admitted.id)))).pipe(R(n=>kn(n)?w(P(n.value)):k(e,Kc(t,n.cause),n.cause,`own-transaction`).pipe(L(A()))))}let Se=(e,t,n)=>Sn(n)?k(e,Kc(t,n.cause),n.cause,`own-transaction`):h;function Ce(e){return z({try:()=>{t.transactionSync(()=>{M(e);for(let[n,r]of Object.entries(e.admitted.documents))ri(t,{extensionId:e.admitted.id,name:n,initialJson:Do(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(N(()=>I(()=>{delete e.stateResetRequired})),L(!0),se(t=>t instanceof G?t.cause===`state_reset_required`?(e.stateResetRequired=t,k(e,Hc(t.message),Hr(t),`own-transaction`).pipe(L(!1))):E(t):(t instanceof Vc&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&i.add(e.admitted.id),k(e,Hc(t instanceof Error?`migration: ${t.message}`:`migration failed`),hi(t),`own-transaction`).pipe(L(!1)))))}return j(function*(){let n=yield*vn();function l(e,r){return j(function*(){let i=Kr(t,e.id),a=i?.status===`stopped`&&i.revision===e.revision,o={admitted:e,hooks:void 0,status:a?`stopped`:`running`,reason:a?i.reason:null,stoppedAt:a?i.stoppedAt:null};return yield*z({try:()=>{e.grants.has(`settled`)&&t.transactionSync(()=>{K(t,e.id)===void 0&&bt(t,e.id,K(t,`core`)??0)})},catch:()=>new G(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*Ce(o))||a?r?yield*E(new G(`extensions`,`rejected`,`Extension ${e.id} cannot start: ${o.reason??`stopped`}`)):o:(yield*z({try:()=>{t.transactionSync(()=>{er(t,e.id,{status:`running`,reason:null,stoppedAt:null,revision:e.revision}),D(e.id)})},catch:()=>new G(`store`,`unavailable`,`Extension status is unavailable`)}),yield*me(o,n,r),o)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(a(()=>ct(n,ar)));r.set(t.id,e)}yield*z({try:()=>{t.transactionSync(()=>{let n=Vt(t,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of n)D(e)})},catch:()=>new G(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:e=>j(function*(){let n=e.filter(e=>{let t=r.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(n.length>0)return yield*E(new G(`extensions`,`rejected`,`Extensions ${n.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,s=T(()=>De([...o.values()].reverse(),e=>O(e.scope===void 0?h:ct(e.scope,ar)),{concurrency:1}).pipe(N(()=>I(()=>{for(let t of e)r.has(t.id)||i.delete(t.id)})),R(En)));yield*j(function*(){for(let t of e)r.has(t.id)||o.set(t.id,yield*l(t,!0))}).pipe(a(()=>s));let c=new Set(e.map(({id:e})=>e)),u=!1;return{discard:T(()=>u?h:(u=!0,s)),apply:j(function*(){if(u)return yield*E(new G(`extensions`,`rejected`,`Roster transition already settled`));yield*z({try:()=>{t.transactionSync(()=>{for(let[e,n]of r)c.has(n.admitted.id)||wn(t,e);let n=Vt(t,e.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of n)D(e)})},catch:()=>new G(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of r)c.has(t.admitted.id)||(t.scope!==void 0&&(yield*ct(t.scope,ar)),r.delete(e),i.delete(t.admitted.id));for(let[e,t]of o)r.set(e,t);u=!0})}}),runParticipants:()=>[...r.values()].filter(F).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...i],modulesForRun:(e,t)=>De(he(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?w(A()):be(n,`moduleForRun`,T(()=>r(e))).pipe(s(c))}).pipe(s(e=>e.flatMap(xe))),filesForRun:(e,t)=>j(function*(){let n=he(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*k(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*E(new G(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*be(n,`filesForRun`,T(()=>r(e)));return p(i)?yield*E(new G(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...ee(i.value,()=>[])])}),promptSections:(e,t)=>j(function*(){let n=[],r=0;for(let i of he(`prompt`)){if(!t.has(i.admitted.id))continue;let a=i.hooks?.prompt;if(a===void 0)return yield*k(i,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*E(new G(`extensions`,`rejected`,`Extension prompt is unavailable`));let o=yield*O(zr(()=>a(e)).pipe(f($i,g(i.admitted.id))));if(Sn(o))return yield*k(i,Kc(`prompt`,o.cause),o.cause,`own-transaction`),yield*E(new G(`extensions`,`rejected`,`Extension prompt failed`));let s=Bc(o.value),c=s._tag===`Success`?s.success:[];if(r+=c.reduce((e,t)=>e+zc.encode(t.text).byteLength,0),s._tag===`Failure`||new Set(c.map(({name:e})=>e)).size!==c.length||r>65536)return yield*k(i,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*E(new G(`extensions`,`rejected`,`Extension prompt is invalid`));n.push(...[...c].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${i.admitted.id}.${e.name}`,text:e.text})))}return n}),compactionHandoff:e=>he(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>he(`settled`).map(e=>({id:e.admitted.id,cursor:K(t,e.admitted.id)??0})),deliverSettled:(e,n)=>De(he(`settled`),r=>T(()=>{let i=K(t,r.admitted.id)??0;if(n<=i)return h;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return le(r,(o===void 0||a.length===0?h:o(a)).pipe(x(I(()=>{bt(t,r.admitted.id,n)}))),`reconcile`).pipe(R(e=>Se(r,`onSettled`,e)))}),{discard:!0}),fireDueTimers:e=>j(function*(){let n=he(`timers`).map(({admitted:e})=>e.id),i=Vr(t,n,e,Rc);for(let n of i){let i=r.get(n.extensionId);if(i?.status!==`running`)continue;let a=i.hooks?.onTimer,o=yield*le(i,T(()=>ui(t,n.extensionId,n.key)===n.dueAt?(qt(t,n.extensionId,n.key),a===void 0?h:a({key:n.key,dueAt:n.dueAt,firedAt:e})):h),`reconcile`);yield*Se(i,`onTimer`,o)}return i.length===Rc}),timerWake:e=>Zn(t,he(`timers`).map(({admitted:e})=>e.id),e),project:e=>{let t={};for(let n of r.values()){let r=n.admitted.grants.has(`projection`),i=n.admitted.grants.has(`commands`)?n.admitted.definition.catalog:void 0;if(!r&&i===void 0)continue;let a=n.admitted.revision,s=n.admitted.definition.contract.projection,c=n.hooks?.project;if(n.status===`running`&&n.hooks!==void 0){let l=!r||c===void 0||s===null?P(null):(()=>{let t=null,r;o=n.admitted.id;try{let r=ii(()=>c(e),void 0);if(ce(r)){let e=Ni(s.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=V(ln)(e.success);if(a._tag===`Failure`)throw Error(`Extension projection is not JSON`);t=a.success;let o=n.hooks.projectCatalog;i!==void 0&&o!==void 0&&(i=Si(ln)(ii(()=>o(a.success),void 0)))}}catch(e){r=e}finally{o=void 0}return r===void 0?P(t):(de(n,Hc(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),A())})();if(ce(l)){t[n.admitted.id]=Object.freeze(i===void 0?{status:`running`,revision:a,value:l.value}:{status:`running`,revision:a,value:l.value,catalog:i});continue}}t[n.admitted.id]=Object.freeze({status:`stopped`,revision:a,reason:n.reason??`Extension did not activate`})}return Object.freeze(t)},call:(e,t,n,i,a)=>j(function*(){let o=r.get(t);if(o?.admitted.grants.has(`commands`)!==!0)return yield*E(new G(`extensions`,`unavailable`,`Extension is unavailable`));if(o.status!==`running`||o.hooks===void 0)return yield*E(o.stateResetRequired??new G(`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*E(new G(`contract`,`invalid`,`Extension command is unknown`));let l=e.scope===`session`?yield*z({try:()=>U(e.sessionId),catch:()=>new G(`contract`,`invalid`,`Session id is invalid`)}):null,u=o.hooks.commands.get(n);if(u===void 0)return V(c.input,{onExcessProperty:`error`})(i)._tag===`Failure`?yield*E(new G(`contract`,`invalid`,`Extension command input is invalid`)):(yield*k(o,`command ${n} has no handler`,void 0,`own-transaction`),yield*E(new G(`extensions`,`unavailable`,`Extension is stopped`)));let d=u(a===void 0?{sessionId:l,input:i}:{sessionId:l,input:i,caller:a});if(d._tag===`Failure`)return yield*E(new G(`contract`,`invalid`,`Extension command input is invalid`));let f=yield*le(o,d.success(),`request`);if(kn(f))return f.value;let p=Cr(f.cause);if(ce(p)&&!qc(f.cause))return yield*E(Yc(p.value));let m=Kc(`command ${n}`,f.cause);return yield*k(o,m,f.cause,`own-transaction`),yield*E(new G(`extensions`,`unavailable`,`Extension ${t} is stopped: ${m}`))}),list:()=>[...r.values()].map(_e),resume:i=>j(function*(){let a=r.get(i);return a===void 0?yield*E(new G(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*z({try:()=>{t.transactionSync(()=>{er(t,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),D(a.admitted.id)})},catch:()=>new G(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*Ce(a))&&(yield*me(a,n)),yield*e.requestWake),_e(a))}),close:ct(n,ar)};return Object.freeze(u)})}var Zc=64;function Q(e){return new G(`runtime`,`rejected`,e)}function Qc(e,t,n){return j(function*(){let r=yield*$c(t),i=t.outcome===`cancelled`?``:yield*et(e,r.work),a=yield*Tt(e,r.work,t.outcome),o=t.outcome===`completed`||t.outcome===`cancelled`?void 0:yield*ft(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 $c(e){return z({try:()=>an(e),catch:()=>Q(`Agent work payload is invalid`)})}function el(e,t){return e.fanOut(t).pipe(m(()=>Q(`Agent reply fan-out is unavailable`)))}function tl(e,t,n){return t===void 0?h:j(function*(){let r=yield*$c(n);(r.mail?.replyTo.length??0)!==0&&(yield*el(t,yield*Qc(e,n,z({try:()=>Je(e,r.work.sessionId,r.work.commandFactId),catch:()=>Q(`Session attention is unavailable`)}))))})}function nl(e,t,n,r){return n===void 0?h:j(function*(){let i=yield*$c(r),a=i.mail;if(a!==void 0&&a.replyTo.length>0||(yield*t.readQueueHead(r.queue).pipe(m(()=>Q(`Session queue head is unavailable`)))).state!==`idle`)return;let o=yield*z({try:()=>Pi(e,i.work.sessionId),catch:()=>Q(`Session delegator is unavailable`)});if(o===void 0)return;let s=a?.reply===void 0?a?.from:void 0;s!==void 0&&!(s.kind===`agent`&&o.replyTo.some(({agentId:e})=>e===s.agentId))||(yield*el(n,{...yield*Qc(e,r,z({try:()=>Ze(e,i.work.sessionId,o.replyTo),catch:()=>Q(`Session attention is unavailable`)})),delegator:o}))})}function rl(e,t,n,r){return De(r,(i,a)=>j(function*(){!r.slice(a+1).some(({job:e})=>e.queue===i.job.queue)&&!(yield*sl(e,i.job))&&(yield*nl(e,t,n,i.job)),yield*z({try:()=>{bt(e,Pc,i.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function il(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?h:j(function*(){let r=yield*z({try:()=>an(t),catch:()=>Q(`Agent work payload is invalid`)});yield*fn(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function al(e,t,n){return j(function*(){let r=yield*z({try:()=>an(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*st(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(We({work:{...e,recovery:Sc},delivery:e.delivery}))}})})}function ol(e){return e===void 0?h:e.drainOutbox().pipe(m(()=>Q(`Agent reply delivery is unavailable`)))}function sl(e,t){return j(function*(){let n=yield*z({try:()=>an(t),catch:()=>Q(`Agent work payload is invalid`)}),r=yield*z({try:()=>Jn(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return r&&(yield*i(`shiitake_settlement_session_refused`).pipe(ge({workId:t.jobId}))),r})}function cl(e,t){let n=an(t.job),r=Jn(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:Me(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):Bt(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:Si(xr)(r.origin.extensionId),correlation:r.origin.correlation})})}function ll(e,t,n,r){return De(r,r=>j(function*(){Re(e,r.job.queue),(yield*sl(e,r.job))||(yield*il(e,r.job),yield*al(e,t,r.job),yield*tl(e,n,r.job)),yield*z({try:()=>{bt(e,Nc,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function ul(e){return j(function*(){if((yield*e.watchdog.tick()).status===`busy`)return yield*E(Q(`Runtime reconciliation is already active`));let t=yield*z({try:()=>K(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),n=yield*z({try:()=>K(e.store,`core-report`)??t,catch:()=>Q(`Settled cursor is unavailable`)}),r=e.extensions.settledConsumers(),i=Math.min(t,n,...r.map(({cursor:e})=>e)),a=yield*e.watchdog.readSettled(Zc,i),o=yield*O(ll(e.store,e.watchdog,e.mailRoom,a.filter(({sequence:e})=>e>t))),s=yield*z({try:()=>K(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),c=yield*z({try:()=>a.filter(({sequence:e})=>e<=s).map(t=>cl(e.store,t)),catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(c,s);let l=yield*O(rl(e.store,e.watchdog,e.mailRoom,a.filter(({sequence:e})=>e>n&&e<=s))),u=yield*e.extensions.fireDueTimers(Date.now());if((a.length===Zc||u)&&(yield*e.requestWake),yield*ol(e.mailRoom),Sn(o))return yield*re(o.cause);if(Sn(l))return yield*re(l.cause)}).pipe(m(e=>e instanceof G?e:Q(`Runtime reconciliation failed`)))}function $(e){return new G(`runtime`,`rejected`,e)}function dl(e,n,r,i){return j(function*(){if(e.hostJobs?.lane==="default")return yield*E($(`Host lane conflicts with Agent work`));let o=`open`,s,c,l=Ge(!1),u=e=>I(()=>{o===`open`&&(s??=e)}),f=T(()=>o===`open`?(o=`closing`,c=s,l.open):h).pipe(ae),p={},_={current:void 0},v=e,ee,ne=!1,y=T(()=>p.requestWake??E($(`Runtime host is unavailable`))),b={current:void 0},S=new Set,ie=new Map,oe={owner:e.store,isAlive:()=>w(!1),executor:{execute:t=>he(I(()=>{let n=t.lane===e.hostJobs?.lane?{kind:`host`,lane:t.lane,jobId:t.jobId}:{kind:`session`,sessionId:t.queue,commandId:t.jobId};ie.set(n.kind===`host`?`host`:`serial`,n),n.kind===`session`&&S.add(t.queue),Bi(e.store)}),()=>t.lane===e.hostJobs?.lane?b.current?.execute(t)??E(new qi(`execution_failed`)):j(function*(){let r=ee;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;v={...n,...r.configuration},ee=void 0}return yield*Ec(v,n,t,_.current)}).pipe(k(e=>d(`configuration_apply_failed`,e)),m(()=>new qi(`execution_failed`))),()=>I(()=>{t.lane!==e.hostJobs?.lane&&S.delete(t.queue),ie.delete(t.lane===e.hostJobs?.lane?`host`:`serial`),Bi(e.store)}))},wake:{recompute:()=>y.pipe(m(()=>new qi(`wake_unavailable`)))},project:t=>{zt(e.store,t,Date.now())}},C=yield*(e.hostJobs===void 0?Ki(oe):Ki({...oe,concurrentLane:e.hostJobs.lane}).pipe(N(t=>I(()=>{b.current=e.hostJobs?.open(t)})))).pipe(m(()=>$(`Watchdog is unavailable`))),ce=()=>({core:n,extensions:[..._.current?.runParticipants()??[]]});yield*z({try:()=>dc(e.compaction),catch:e=>e instanceof G?e:$(`Compaction settings are unavailable`)});let le=yield*z({try:()=>_n(e.storagePressure),catch:e=>e instanceof G?e:$(`Storage budget is unavailable`)}),D=()=>{e.admission?.assertOpen(),le.admitNew()},O=()=>{let t;do{let n=jr(e.store,t);for(let e of n.sessions){if(e.state===`unavailable`)throw new G(`store`,`unavailable`,`Session ${e.sessionId} is unreadable`);let t=C.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=Zo(e.store);return n===void 0?void 0:{kind:`delegation`,...n}},de=Mc({owner:e.store,admitNew:D,hostMeta:e.meta,contract:ce,enqueue:(e,t)=>{let n={work:{...e,recovery:Sc},delivery:e.delivery};C.transactional.enqueueAcceptedJob(We(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>C.transactional.readQueueHead(e),commit:e=>T(()=>p.commit===void 0?E($(`Runtime host is unavailable`)):p.commit(e)),requestWake:y});yield*z({try:()=>{je(e.store),K(e.store,`core`)===void 0&&e.store.transactionSync(()=>{bt(e.store,Nc,0)}),K(e.store,`core-report`)===void 0&&e.store.transactionSync(()=>{bt(e.store,Pc,K(e.store,`core`)??0)})},catch:()=>new G(`store`,`unavailable`,`Extension store is unavailable`)});let A=yield*Xc({owner:e.store,readQueueHead:e=>C.transactional.readQueueHead(e),door:de,admitted:r,requestWake:y});_.current=A;let fe=ul({watchdog:C,store:e.store,extensions:A,requestWake:y,mailRoom:i}).pipe(k(u)),M=j(function*(){let t=yield*C.hasPendingWork,n=Date.now(),r=yield*z({try:()=>[K(e.store,`core`)??0,K(e.store,`core-report`)??0,...A.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),a=(yield*C.readSettled(1,Math.min(...r))).length>0,o=yield*z({try:()=>A.timerWake(n),catch:()=>$(`Extension timers are unavailable`)}),s=i===void 0?void 0:yield*i.nextWakeAt().pipe(m(()=>$(`Reply retry wake is unavailable`))),c=o.nextWakeAt===null?s??null:s===void 0?o.nextWakeAt:Math.min(o.nextWakeAt,s);return{pending:t||a||o.due||s!==void 0&&s<=n,nextWakeAt:c}}),me=yield*e.runtime.bind({reconcile:fe,pendingWork:M.pipe(m(()=>$(`Pending work is unavailable`)))}).pipe(a(()=>A.close.pipe(te))),ge=T(()=>o===`open`?t(me.requestWake.pipe(se(u)),l.await):h);return p.requestWake=ge,p.commit=me.commit,yield*me.requestWake.pipe(a(()=>ue([me.close,A.close]).pipe(te))),Object.freeze({prepareConfiguration:e=>j(function*(){if(o!==`open`||ne||ee!==void 0)return yield*E($(`A configuration change is already pending, or the Agent is closing`));ne=!0;let t=yield*Uo(e.extensions).pipe(R(e=>A.stage(e)),a(()=>I(()=>{ne=!1}))),n=!1;return{commit:z({try:()=>{if(n||o!==`open`)throw $(`Configuration preparation is no longer available`);ee={configuration:e,apply:t.apply},n=!0,ne=!1},catch:e=>e instanceof G?e:$(`Configuration commit failed`)}),discard:T(()=>n?h:(n=!0,ne=!1,t.discard))}}),activeSessions:I(()=>[...S]),busySync:O,runningWork:t=>C.read(t).pipe(R(t=>{let n=t.status===`found`?ie.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`):void 0;return n===void 0?w(null):n.kind===`host`?w({phase:`thinking`}):z({try:()=>({phase:Xa(e.store,n.sessionId,C.transactional.readQueueHead(n.sessionId))}),catch:e=>new G(`runtime`,`rejected`,`Running phase is unavailable`,void 0,e)})}),m(e=>new G(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:A,commit:me.commit,assertOpen:T(()=>o===`open`?h:E(new G(`runtime`,`closed`,`Shiitake is closed`))),beginClose:f,door:de,createSessionWithinTransaction:t=>$t(e.store,t,D),recordCreatedSessionDelegatorWithinTransaction:(t,n)=>{Kn(e.store,t,n)},stageSessionGrantsWithinTransaction:(t,n)=>{Fe(e.store,t,n)},storage:{admitNew:D},recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>C.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(C.transactional.readQueueHead(e).state!==`idle`)throw new G(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof G?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>C.cancel({jobId:e,cancellationId:t}).pipe(R(e=>e.status===`recorded`||e.status===`replayed`?h:E($(`Cancellation is unavailable`))),m(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>C.readQueueHead(e).pipe(m(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>C.transactional.readQueueHead(e),requestWake:ge,close:f.pipe(x(g(me.close,{onFailure:e=>A.close.pipe(x(c===void 0?re(e):E(c))),onSuccess:()=>A.close.pipe(x(c===void 0?h:E(c)))})),pe(I(()=>{o=`closed`})))})})}var fl=e({openRuntimeCore:()=>pl});function pl(e,t){return j(function*(){let n=yield*Uo(e.extensions),r=yield*Wo([]);yield*Lt(e.store);let i=yield*dl(e,r,n,t),a=Co(e,i),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:Ya(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(x(kr(e.store,t,n))),activeSessions:i.activeSessions,busySync:i.busySync,acceptMail:(e,n,r,a,o)=>To(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);ie(t.postMail(e))}),o)})})}export{Ka as n,pl as openRuntimeCore,Va as r,fl as t};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-
|
|
1
|
+
import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-CHfIZEOV.js";function n(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}var r=n();function i(){return r?`pi (${r.platform()} ${r.release()}; ${r.arch()})`:`pi (browser)`}var a=class extends Error{},o=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e){if(!s(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function l(e){return s(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>l(e)):!1}function u(e,t){if(!s(e))throw new a(`boolean schemas are unsupported`);for(let t of o)if(e[t]!==void 0)throw new a(`${t} schemas are unsupported`);if(t){for(let[n,r]of Object.entries(e))if(t(n,r))throw new a(`${n}: ${JSON.stringify(r)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new a(`anyOf must contain at least one schema`);for(let n of e.anyOf){if(c(n))throw new a(`object and array unions are unsupported`);u(n,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new a(`tuple schemas are unsupported`);u(e.items,t)}let n=e.type===`object`;if(e.properties!==void 0&&!n)throw new a(`properties require type object`);if(!n)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new a(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!s(e.properties))throw new a(`object properties must be a schema map`);if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(e=>typeof e!=`string`)))throw new a(`object required must be a string array`);let r=e.properties??{},i=Object.keys(r),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!i.includes(e)))throw new a(`required contains an unknown property`);for(let[e,n]of Object.entries(r))u(n,t),!d.has(e)&&!l(n)&&(r[e]={anyOf:[n,{type:`null`}]});e.required=i,e.additionalProperties=!1}function d(e,t){let n=structuredClone(e);if(!s(n)||(u(n,t),n.type!==`object`))throw new a(`root schema must have type object`);return n}function f(e,t){return t===!0?d(e.parameters):e.parameters}function p(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function m(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function h(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function g(e,t,n){let r=e.constrainedSampling;if(!(!r||r.type!==`json_schema`)){if(t)try{return d(e.parameters,n),!0}catch(t){if(!(t instanceof a))throw t;if(r.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(r.strict===`require`)throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function _(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:h(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function v(e,t){let n=new Map;for(let r of e??[]){let e=_(r,t);e&&n.set(r.name,e.inputProperty)}return n}var y=4096,b=1;function x(e,n,r){if(e.contextWindow<=0)return Math.max(b,r);let i=e.contextWindow-t(n).tokens-y;return Math.min(r,Math.max(b,i))}function S(t,n,r){let i=e(t,n),a=t.samplingParamsByThinkingLevel?.[i];return t.samplingParams||a||r?{...t.samplingParams,...a,...r}:void 0}function C(e,t,n,r){let i=S(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:x(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,onProviderStreamEvent:n?.onProviderStreamEvent,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}var w=1024,T={minimal:1024,low:2048,medium:8192,high:16384};function E(e){return e===`xhigh`||e===`max`?`high`:e}function D(e,t){return{...T,...t}[E(e)]}function O(e,t){return Math.min(e,Math.max(0,t-w))}function k(e,t,n,r){let i=D(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=O(i,a)),{maxTokens:a,thinkingBudget:i}}var A=`(image omitted: model does not support images)`,j=`(tool image omitted: model does not support images)`,M=`(image attached after the tool results)`;function N(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:P(e.content,M),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function P(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function F(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:P(e.content,A)}:e.role===`toolResult`?{...e,content:P(e.content,j)}:e)}function I(e,t,n){let r=new Map,i=F(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`system`||e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return a?e.redacted||e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:e:[];if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=[],l=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}a.push(...c),c.length=0};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){l();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):t.role===`system`?o.length>0?c.push(t):a.push(t):(t.role===`user`&&l(),a.push(t))}return l(),a}export{x as a,D as c,p as d,f,i as h,C as i,m as l,g as m,I as n,O as o,_ as p,k as r,S as s,N as t,v as u};
|
package/dist/index.html
CHANGED
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
<meta charset="UTF-8" />
|
|
5
5
|
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
6
6
|
<title>Inbox</title>
|
|
7
|
-
<script type="module" crossorigin src="/assets/index-
|
|
7
|
+
<script type="module" crossorigin src="/assets/index-DM8ziIjn.js"></script>
|
|
8
8
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
|
9
|
-
<link rel="modulepreload" crossorigin href="/assets/Effect-
|
|
9
|
+
<link rel="modulepreload" crossorigin href="/assets/Effect-TOXKEWei.js">
|
|
10
10
|
<link rel="modulepreload" crossorigin href="/assets/preload-helper-DY31Aviq.js">
|
|
11
|
-
<link rel="modulepreload" crossorigin href="/assets/extension-hook-
|
|
12
|
-
<link rel="modulepreload" crossorigin href="/assets/document-
|
|
13
|
-
<link rel="modulepreload" crossorigin href="/assets/base-face-
|
|
14
|
-
<link rel="stylesheet" crossorigin href="/assets/index-
|
|
11
|
+
<link rel="modulepreload" crossorigin href="/assets/extension-hook-UDdYbDsl.js">
|
|
12
|
+
<link rel="modulepreload" crossorigin href="/assets/document-aOA3zT2S.js">
|
|
13
|
+
<link rel="modulepreload" crossorigin href="/assets/base-face-CD4oLBv-.js">
|
|
14
|
+
<link rel="stylesheet" crossorigin href="/assets/index-DRqG5MfY.css">
|
|
15
15
|
</head>
|
|
16
16
|
<body>
|
|
17
17
|
<div id="inbox-root"></div>
|
package/package.json
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fungi.computer/grove",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.1",
|
|
4
4
|
"author": "Levi <levi@technomancy.dev>",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Grove: conversations with agents that call your other Apps, for Oyster",
|
|
7
7
|
"dependencies": {
|
|
8
|
-
"@fungi.computer/agar": "0.
|
|
8
|
+
"@fungi.computer/agar": "0.6.1",
|
|
9
9
|
"@fungi.computer/approvals": "0.2.0",
|
|
10
10
|
"@fungi.computer/cairn": "0.1.0",
|
|
11
|
-
"@fungi.computer/caps": "0.
|
|
12
|
-
"@fungi.computer/knapsack": "0.4.
|
|
11
|
+
"@fungi.computer/caps": "0.6.0",
|
|
12
|
+
"@fungi.computer/knapsack": "0.4.2",
|
|
13
13
|
"@fungi.computer/maosaico": "0.1.0",
|
|
14
|
-
"@fungi.computer/parakeet": "0.
|
|
15
|
-
"@fungi.computer/shiitake": "0.
|
|
16
|
-
"@fungi.computer/sigils": "0.2.
|
|
14
|
+
"@fungi.computer/parakeet": "0.6.1",
|
|
15
|
+
"@fungi.computer/shiitake": "0.8.0",
|
|
16
|
+
"@fungi.computer/sigils": "0.2.1",
|
|
17
17
|
"@fungi.computer/sprite": "0.2.0",
|
|
18
|
-
"@fungi.computer/sprite-zdog": "0.
|
|
18
|
+
"@fungi.computer/sprite-zdog": "0.3.0",
|
|
19
19
|
"@fungi.computer/stipe": "0.1.0",
|
|
20
20
|
"@fungi.computer/whistle": "0.3.0",
|
|
21
21
|
"@tanstack/react-query": "5.102.8",
|
|
@@ -26,13 +26,13 @@
|
|
|
26
26
|
"react": "18.3.1",
|
|
27
27
|
"react-dom": "18.3.1",
|
|
28
28
|
"zod": "4.4.3",
|
|
29
|
-
"@fungi.computer/shiitake-extensions": "0.
|
|
29
|
+
"@fungi.computer/shiitake-extensions": "0.6.0",
|
|
30
30
|
"@fungi.computer/gills": "0.2.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@fungi.computer/watchdog": "0.1.0",
|
|
34
34
|
"@cloudflare/workers-types": "5.20260828.1",
|
|
35
|
-
"@fungi.computer/parakeet-testing": "0.2.
|
|
35
|
+
"@fungi.computer/parakeet-testing": "0.2.2",
|
|
36
36
|
"@ladle/react": "5.1.1",
|
|
37
37
|
"@tailwindcss/vite": "4.2.1",
|
|
38
38
|
"@types/react": "18.3.3",
|
|
@@ -133,6 +133,15 @@
|
|
|
133
133
|
},
|
|
134
134
|
"palette": {}
|
|
135
135
|
}
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"id": "set-draft",
|
|
139
|
+
"title": "Set draft",
|
|
140
|
+
"category": "Conversation",
|
|
141
|
+
"description": "Replace the open writable Grove conversation's draft without sending it",
|
|
142
|
+
"projections": {
|
|
143
|
+
"agent": {}
|
|
144
|
+
}
|
|
136
145
|
}
|
|
137
146
|
],
|
|
138
147
|
"displayName": "Grove",
|
|
@@ -191,6 +200,7 @@
|
|
|
191
200
|
"lint": "eslint src workbench test backend .ladle --max-warnings=0",
|
|
192
201
|
"test:workbench": "node test/workbench.browser.mjs && node test/rails.browser.mjs && node test/narrow.browser.mjs && node test/avatars.browser.mjs && node test/agents.browser.mjs && node test/inbox-order.browser.mjs",
|
|
193
202
|
"test:slash": "node test/slash.browser.mjs",
|
|
203
|
+
"test:composer-parity": "node test/composer-parity.browser.mjs",
|
|
194
204
|
"workbench:build": "ladle build --outDir ../../.botanical/grove-website-ladle",
|
|
195
205
|
"test:websites": "node --import tsx ../../tooling/repository/scripts/workbench-proofs.mjs --output ../../.botanical/grove-website-ladle --origin-env GROVE_WORKBENCH_URL test/websites.browser.mjs",
|
|
196
206
|
"format:check": "node ../../tooling/repository/scripts/format-package-check.mjs",
|