@fungi.computer/grove 0.7.0 → 0.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/{Effect-CtszBD7f.js → Effect-CsknxyoC.js} +1 -1
- package/dist/assets/animation-Ca8A_H2p.js +1 -0
- package/dist/assets/{anthropic-messages-CDm0hoBV.js → anthropic-messages-CVTSajCf.js} +3 -3
- package/dist/assets/{azure-openai-responses-BjoRAOlM.js → azure-openai-responses-Bl0qLprn.js} +1 -1
- package/dist/assets/{base-face-DzmOsdaJ.js → base-face-BYNJAADF.js} +1 -1
- package/dist/assets/burger-CkHWi49Z.js +1 -0
- package/dist/assets/cat-DyLB0vqU.js +1 -0
- package/dist/assets/compat-CqXUS3Sf.js +2 -0
- package/dist/assets/{document-Bagsf-XI.js → document-Bq-ilh6h.js} +1 -1
- package/dist/assets/extension-hook-CI69uLQY.js +809 -0
- package/dist/assets/{google-generative-ai-xdelq2ko.js → google-generative-ai-CNNdplPY.js} +1 -1
- package/dist/assets/{google-shared-P7z8Pe9d.js → google-shared-BIcQKTFY.js} +1 -1
- package/dist/assets/{google-vertex-8hsu6Eaf.js → google-vertex-DDdvFanV.js} +1 -1
- package/dist/assets/index-CCFVxQrP.js +117 -0
- package/dist/assets/{mistral-conversations-JKMpJrPb.js → mistral-conversations-DyAgbR7r.js} +1 -1
- package/dist/assets/{mushroom-ur0TNKww.js → mushroom-Bm99-6Un.js} +1 -1
- package/dist/assets/{node.browser-GHKlzSn3.js → node.browser-ILUZE1xW.js} +1 -1
- package/dist/assets/{openai-codex-responses-CidQ12Xa.js → openai-codex-responses-D3R6a8BL.js} +1 -1
- package/dist/assets/openai-codex.models-B_MCwO6E.js +1 -0
- package/dist/assets/{openai-completions-D9RzypE9.js → openai-completions-mxaKYcNn.js} +1 -1
- package/dist/assets/{openai-responses-BXeaL2BV.js → openai-responses-Bm0Qs189.js} +1 -1
- package/dist/assets/{openai-responses-shared-Da1jFqQB.js → openai-responses-shared-D6bv6hF3.js} +1 -1
- package/dist/assets/parakeet-DuJ3iiSB.js +36 -0
- package/dist/assets/parakeet-conversation-CDEkPNoL.js +4 -0
- package/dist/assets/renderer-B77qG8Ri.js +1 -0
- package/dist/assets/runtime-core-Dev7cGsf.js +40 -0
- package/dist/assets/sigil-B438LdFL.js +31 -0
- package/dist/assets/{transform-messages-YmXk5TtR.js → transform-messages-BYFvCqeV.js} +1 -1
- package/dist/assets/website-conversation-BaqjHBp1.js +1 -0
- package/dist/index.html +7 -5
- package/package.json +12 -12
- package/dist/assets/burger-DGewjCsv.js +0 -1
- package/dist/assets/cat-CRMM8U8H.js +0 -1
- package/dist/assets/compat-tatm8WJ0.js +0 -2
- package/dist/assets/extension-hook-CmoMuW6C.js +0 -819
- package/dist/assets/extensions-CrmxvtfG.js +0 -1
- package/dist/assets/index-CCJvRnqn.js +0 -174
- package/dist/assets/parakeet-conversation-DYlN7oL9.js +0 -4
- package/dist/assets/renderer-BKCye2Ev.js +0 -1
- package/dist/assets/runtime-core-DKpk6tKT.js +0 -40
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{ht as n,j as r,r as i,t as a,xa as o}from"./Effect-CsknxyoC.js";import{i as s,t as c}from"./document-Bq-ilh6h.js";import{B as l,C as u,D as d,E as f,F as p,L as m,O as h,P as g,R as _,S as v,T as y,V as ee,_ as b,a as x,c as te,d as S,i as C,k as ne,l as re,m as ie,o as ae,r as oe,s as w,t as T,u as se,w as E,x as D}from"./animation-Ca8A_H2p.js";var ce=(e,t)=>{if(g(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),d(t))return n;if(E(+t))return+t;let r=t,i=e?e.labels:null,a=!u(i),o=ce(e,r),s=!d(o),c=l.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 se(u,d,e[0])}return s?o:a?d(i[r])?n:i[r]:n};function le(e){return b((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function k(e,t,n,r,i,a){let o=E(e.duration)&&e.duration<=1e-11?n-_:n;t.composition&&re(t,o,1,1,ee.AUTO);let s=r?new T(r,e,t,o,!1,i,a):new x(e,t,o);return t.composition&&s.init(!0),ie(t,s),D(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 x{constructor(e={}){super(e,null,0),++A,this.id=d(e.id)?A:e.id,this.duration=0,this.labels={};let t=e.defaults,n=p.defaults;this.defaults=t?h(t,n):n,this.composition=S(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=S(e.playbackEase,n.playbackEase);this._ease=r?oe(r):null,this.iterationDuration=0}add(e,t,n){let r=y(t),i=y(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=p.editor&&p.editor.addTimelineChild,a=n&&n.type===`Stagger`&&p.editor,o=v(n)?n:null;if(o||a){let t=C(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,f=i?i(e,r,this.id,n,u):null,m=o||p.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...f||r};this.duration=a,this.iterationDuration=s,d(c)||(n.id=c+`-`+l);let i=O(this,m(e,l,t,null,this));k(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;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(d(e)||e&&d(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!d(e)&&!d(e.persist)&&(e.persist=!0);let r=p.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 d(t)?this:(t.duration=_,t.composition=m.replace,this.add(e,t,n))}call(e,t){return d(e)||e&&!v(e)?this:(p.editor&&p.editor.addTimelineCall&&(t=p.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return d(e)||e&&!f(e)?this:(p.editor&&p.editor.addTimelineLabel&&(t=p.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=O(this,t),this)}remove(e,t){return w(C(e),this,t),this}stretch(e){let t=this.duration;if(t===ne(e))return this;let n=e/t,r=this.labels;D(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return D(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),D(this,e=>e.revert,!0),te(this)}then(e){return super.then(e)}},M=e=>p.editor?p.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=ae({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>r(function*(){let t=c.parse(e.document.data),r=yield*a(n(()=>e.target.ownerDocument.createElement(`canvas`)),e=>n(()=>{e.remove()}));r.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(r);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let 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*a(n(()=>ye({target:r,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>n(()=>{e.destroy()}));yield*i(()=>n(()=>{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,r]of Object.entries(e.appearance)){let e=o().safeParse(r);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let r=JSON.stringify(n);r!==_&&(m.setPalette(n),_=r);let i=e.expression??t.defaultPresentation.expression;if(!i)throw Error(`Zdog avatar needs an expression`);let a=JSON.stringify([e.activity,i]);a!==g&&(m.present({activity:e.activity,expression:i}),g=a),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,Ct as n,D as r,F as i,G as a,I as o,J as s,K as c,N as l,O as u,P as d,Qr as f,R as p,St as m,V as h,Y as g,Z as _,Zi as v,_ as ee,_a as y,_t as te,a as b,ar as ne,ba as x,bt as re,c as ie,ct as ae,d as oe,da as se,dr as S,dt as ce,et as le,f as C,fa as w,ft as T,g as E,ga as ue,gt as D,h as O,ht as k,i as de,ir as fe,j as A,lt as pe,m as j,mr as me,mt as M,n as he,nr as ge,o as N,ot as _e,p as ve,pa as ye,pr as P,pt as F,qn as be,r as xe,ra as Se,rr as Ce,s as I,sr as we,st as Te,t as Ee,tr as De,tt as Oe,vt as ke,w as Ae,wa as je,wt as L,xa as R,xi as Me,xt as z,y as B}from"./Effect-CsknxyoC.js";import{$ as Ne,$n as Pe,$t as Fe,A as Ie,Ai as Le,An as Re,Ao as ze,Ar as Be,At as Ve,B as He,Ba as Ue,Bn as We,Br as Ge,Bt as Ke,C as qe,Ci as V,Cn as Je,Co as Ye,Cr as H,Ct as Xe,D as Ze,Dn as Qe,Dt as $e,E as et,Ei as tt,En as nt,Eo as rt,Et as it,F as at,Fo as ot,Fr as st,Ft as ct,G as lt,Gi as ut,Gn as dt,Gr as ft,Gt as pt,H as mt,Hi as ht,Hn as gt,Hr as _t,Ht as vt,I as yt,Ia as bt,Ii as xt,In as St,It as Ct,J as wt,Ja as Tt,Ji as Et,Jn as Dt,Jt as Ot,K as kt,Kn as At,Kr as jt,Kt as Mt,L as Nt,La as U,Li as Pt,Ln as Ft,Lo as It,Lr as Lt,Lt as Rt,M as zt,Ma as Bt,Mn as Vt,Mo as Ht,Mt as Ut,N as Wt,Na as Gt,Ni as W,Nn as Kt,No as qt,Nt as Jt,O as Yt,On as Xt,Oo as Zt,Or as Qt,Ot as $t,P as en,Pa as G,Pn as tn,Po as nn,Pr as rn,Pt as an,Q as on,Qn as sn,Qt as cn,R as ln,Ra as un,Rn as dn,Rt as fn,S as pn,Si as mn,Sn as hn,Sr as gn,St as _n,T as vn,Ta as yn,Tn as bn,To as xn,Tr as Sn,Tt as Cn,U as wn,Ui as Tn,Un as En,Ut as Dn,V as On,Vi as K,Vn as kn,Vr as An,Vt as jn,W as Mn,Wi as Nn,Wn as Pn,Wt as Fn,X as In,Xn as Ln,Xr as Rn,Xt as zn,Y as Bn,Yn as Vn,Yt as Hn,Z as Un,Zn as Wn,Zt as Gn,_ as Kn,_a as qn,_i as Jn,_n as Yn,_r as Xn,_t as Zn,a as Qn,ai as $n,an as er,at as tr,b as nr,bi as rr,bn as ir,br as ar,bt as or,c as sr,ci as cr,cn as lr,co as ur,ct as dr,di as fr,dn as pr,do as mr,dr as hr,dt as gr,ei as _r,en as vr,er as yr,et as br,fi as xr,fn as Sr,fo as Cr,ft as wr,g as Tr,gi as Er,gn as Dr,go as Or,gr as kr,gt as Ar,h as jr,hn as Mr,ho as Nr,hr as Pr,ht as Fr,i as Ir,ii as Lr,in as Rr,ir as zr,it as Br,j as Vr,ji as Hr,jn as Ur,jo as Wr,jr as Gr,jt as Kr,k as qr,ka as Jr,ki as Yr,kn as Xr,ko as Zr,kt as Qr,la as $r,li as ei,ln as ti,lo as ni,lt as ri,mn as ii,mo as ai,mt as oi,n as si,ni as ci,nn as li,nr as ui,nt as di,o as fi,oa as pi,oi as mi,on as q,ot as hi,pi as gi,pn as _i,po as vi,pt as yi,q as bi,qi as xi,qn as Si,qr as Ci,qt as wi,r as Ti,ri as Ei,rn as Di,rr as Oi,rt as ki,s as Ai,sn as ji,so as Mi,sr as Ni,st as Pi,t as Fi,ti as Ii,tn as Li,tr as Ri,tt as zi,ui as Bi,un as Vi,uo as Hi,ur as Ui,ut as Wi,v as Gi,vn as Ki,vr as qi,vt as Ji,w as Yi,wi as Xi,wn as Zi,wo as Qi,wt as $i,x as ea,xa as ta,xi as na,xn as ra,xr as ia,xt as aa,y as oa,yn as sa,yr as J,yt as ca,z as la,zn as ua,zr as da,zt as fa}from"./extension-hook-CI69uLQY.js";import{l as pa,m as ma,p as ha}from"./preload-helper-DY31Aviq.js";import{a as ga,c as _a,d as va,i as ya,l as ba,o as xa,r as Sa,s as Ca,u as wa}from"./index-CCFVxQrP.js";var Ta=bt(()=>Xa),Ea=Lr(Ta),Da=V({id:Jn,payload:Bi}),Oa=V({...Da.fields,schemas:Gt(Ea)});function ka(e){let t={};for(let[n,r]of Object.entries(e))Tt(r)&&f(t,n,r);return Object.keys(t).length===0?S():P(t)}var Aa=Gt(na(mn,Hr)).pipe(ut(G(fr),{decode:Mi(),encode:ni(e=>ne(e)||e.value===void 0?S():ka(e.value))})),ja=bt(()=>Pa),Ma=Lr(ja),Na={annotations:Aa,checks:Ma},Pa=Le([V({_tag:U(`Filter`),representation:Oa,annotations:Aa,aborted:mi}),V({_tag:U(`FilterGroup`),representation:Gt(Oa),annotations:Aa,checks:Er(ja)})]);function Y(e){return V({_tag:U(e),...Na})}var Fa=V({_tag:U(`Declaration`),representation:Da,annotations:Aa,typeParameters:Ea,checks:Ma}),Ia=V({_tag:U(`Suspend`),annotations:Aa,checks:tt([]),thunk:Ta});function La(e,t){return t.pipe(ut(V({type:U(e),value:t}),{decode:ur(e=>e.value),encode:ur(t=>({type:e,value:t}))}))}var Ra=La(`string`,mn),za=La(`number`,rr),Ba=V({_tag:U(`Literal`),...Na,literal:Le([Ra,La(`number`,cr),La(`bigint`,$n),La(`boolean`,mi)])}),Va=V({_tag:U(`UniqueSymbol`),...Na,symbol:Xi}),Ha=V({_tag:U(`Enum`),...Na,enums:Lr(tt([mn,Le([Ra,za])]))}),Ua=V({_tag:U(`TemplateLiteral`),...Na,parts:Ea}),Wa=V({isOptional:mi,type:Ta,annotations:Aa}),Ga=V({_tag:U(`Arrays`),...Na,elements:Lr(Wa),rest:Ea}),Ka=V({name:Le([Ra,za,La(`symbol`,Xi)]),type:Ta,isOptional:mi,isMutable:mi,annotations:Aa}),qa=V({parameter:Ta,type:Ta}),Ja=V({_tag:U(`Objects`),...Na,propertySignatures:Lr(Ka),indexSignatures:Lr(qa)}),Ya=V({_tag:U(`Union`),...Na,types:Ea,options:G(V({mode:G(gi([`anyOf`,`oneOf`]))}))}),Xa=Le([Fa,V({_tag:U(`Reference`),$ref:Jn}),Ia,Y(`Null`),Y(`Undefined`),Y(`Void`),Y(`Never`),Y(`Unknown`),Y(`Any`),Y(`String`),Y(`Number`),Y(`Boolean`),Y(`BigInt`),Y(`Symbol`),Y(`ObjectKeyword`),Ba,Va,Ha,Ua,Ga,Ja,Ya]),Za=Nn(un(V({representation:Ta,references:na(mn,Ta)})));function Qa(e){return Za(e)}function $a(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 eo=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function to(e){return e[eo]?.()}var no=3.5,ro=4800;function io(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function ao(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function oo(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:ro;return t}function so(e){return Math.ceil(e.length/no)}function co(e){return Math.ceil(oo(e)/no)}function lo(e){let t=0;if(e.role===`system`)return so(ma(e))+po(e.toolsAdded)+po(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return co(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+ao(n.arguments).length;return Math.ceil(t/no)}function uo(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`&&io(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function fo(e){let t=`messages`in e?e.messages:e,n=uo(t);if(n){let e=io(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=lo(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=lo(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function po(e){return!e||e.length===0?0:so(ao(e))}var mo=0xffffffffffff,ho=(1n<<41n)-1n,go=-1,_o;function vo(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>mo)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${mo}`);let n=e===void 0?Math.max(t,go):e;e===void 0&&(go=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),_o===void 0)_o=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(_o===ho)throw RangeError(`UUIDv7 generator sequence exhausted`);_o++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(_o>>37n&15n),r[7]=Number(_o>>29n&255n),r[8]=128|Number(_o>>23n&63n),r[9]=Number(_o>>15n&255n),r[10]=Number(_o>>7n&255n),r[11]=Number((_o&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 yo(e){return Zt(e,{onFailure:ee,onSuccess:()=>L})}function bo(e,t){return h(e,{onFailure:e=>O(t).pipe(b(ee(e))),onSuccess:()=>t})}function xo(e,t){let n={_tag:`open`},r=r=>bo(e,t).pipe(O,B(e=>k(()=>{r.result=e,n={_tag:`closed`}}).pipe(b(r.settled.open),b(yo(e)))),m);return M(()=>{if(n._tag===`closed`)return L;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(b(M(()=>{let t=e.result;return t===void 0?ve(Error(`Agent close settlement was not recorded`)):yo(t)})))}let e={_tag:`running`,settled:Ci(!1)};return n=e,r(e)})}function So(e,t,n){let{facts:r}=Co(e,t,n,null);return r.cancellationRequested?`cancelling`:We(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`&&In(e,t,n.jobId)?`streaming`:`thinking`:`running_tool`}function Co(e,t,n,r){let i=Ar(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=Zn(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:oi(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:Bn(e,t)},readProgress:()=>Ne(e,t,n.jobId),toolOutput:br(e,t,n.jobId)}}var wo=new WeakMap;function To(e,t){let n=ca(e,{sessionId:t}),r=dr(n);return r.length===0?null:fo(r).tokens}function Eo(e,t,n,r=!0){let i;try{i=_n(e.store,t)}catch(e){return Vn(`session-context.preference`,e),F(void 0)}let a=JSON.stringify(i),s=wo.get(e)??new Map;wo.set(e,s);let c=r?s.get(t):void 0,l=e.model.describe;if(c?.cursor===n&&c.preference===a){if(c.value===void 0||l===void 0)return F(c.value);let e=c.value;return l({sessionId:t,preference:i}).pipe(o(({contextWindow:i})=>{if(e.window===i)return e;let o=Object.freeze({tokens:e.tokens,window:i});return r&&s.get(t)?.cursor===n&&s.set(t,{cursor:n,preference:a,value:o}),o}),oe(t=>k(()=>(Vn(`session-context.describe`,t),e))))}let u;try{u=To(e.store,t)}catch(e){return Vn(`session-context.figure`,e),F(void 0)}if(u===null)return r&&s.set(t,{cursor:n,preference:a,value:void 0}),F(void 0);if(l===void 0){let e=Object.freeze({tokens:u,window:null});return r&&s.set(t,{cursor:n,preference:a,value:e}),F(e)}return r&&s.set(t,{cursor:n,preference:a,value:Object.freeze({tokens:u,window:null})}),l({sessionId:t,preference:i}).pipe(o(({contextWindow:e})=>e),oe(e=>k(()=>(Vn(`session-context.describe`,e),null))),o(e=>{let i=Object.freeze({tokens:u,window:e});return r&&s.get(t)?.cursor===n&&s.set(t,{cursor:n,preference:a,value:i}),i}))}function Do(e,t){return e.readQueueHead(t).pipe(B(t=>(t.state===`queued`?e.runningWork(t.jobId):F(null)).pipe(o(e=>({head:t,runningWork:e})))))}function Oo(e,t,n){return Do(t,n).pipe(o(({head:t,runningWork:r})=>Co(e.store,n,t,r)))}function ko(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function Ao(e,t,n,r,i={}){return Do(t,n).pipe(B(({head:a,runningWork:o})=>(i.beforeRead?.(),Vr(e.store,n,()=>Co(e.store,n,a,o),r,()=>t.extensions.project(n),t=>({snapshot:t,context:Eo(e,n,t.cursor,r?.before===void 0)})))),B(({snapshot:e,context:t})=>(i.afterRead?.(),t.pipe(o(t=>ko(e,t))))))}function jo(e,t){return z({try:()=>Object.freeze({sessionId:J(e),options:ia(t)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Subscribe options are invalid`)})}function Mo(e,t,n,r=!1,i={}){return t.assertOpen.pipe(b(Ao(e,t,n,{includeSandboxFailures:r},i)),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function No(e){return[[e],P({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function Po(e,t,n,r,i,a=!1){let s=i.kind===`live`?i.registration:void 0,c=i.kind===`live`?Un(i.progress):null,l=[],u=()=>Mo(e,t,n,a,i.kind===`replay`?{beforeRead:i.checkpoint}:{afterRead:i.stamp}).pipe(o(e=>(c=Un(e.baseline.progress),l=e.baseline.toolOutput,i.kind===`replay`?[[e],S()]:No(e)))),d=t=>{let r=t.facts.queue,i=r.state===`running`?on(e.store,n,r.commandId,c):null;if(i===void 0)return;let a=[];return i!==null&&(a.push({kind:`progress`,progress:i,activity:t.facts}),c={messageId:i.messageId,revision:i.revision,text:i.text.offset+i.text.append.length,thinking:i.thinking.offset+i.thinking.append.length}),(l.length!==t.toolOutput.length||l.some((e,n)=>e!==t.toolOutput[n]))&&(l=t.toolOutput,a.push({kind:`tool_output`,toolOutput:l,activity:t.facts})),a},f={after:r,delivery:i.kind,awaitSignal:i.kind===`live`};return An(f,r=>(s===void 0?F(void 0):r.awaitSignal?s.awaitSignal.pipe(B(e=>s.pollSignal.pipe(o(t=>t===void 0?e:Pn(e,t))))):s.pollSignal).pipe(B(c=>c===`closed`?F([[],S()]):c===`reset`?u():t.assertOpen.pipe(b(Oo(e,t,n)),B(f=>{if(i.kind===`replay`&&i.checkpoint(),s?.setQueued(f.facts.queue.state===`queued`),(c===`progress`||c===`activity`)&&r.delivery===`live`){let e=d(f);return e===void 0?u():(i.kind===`live`&&i.stamp(),F([[...c===`activity`?[{kind:`activity`,activity:f.facts}]:[],...e],P({...r,awaitSignal:!0})]))}return Wt(e.store,n,r.after,r.delivery,f,()=>t.extensions.project(n),a,t=>{let i=t.kind===`page`?t.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`||e.kind===`heartbeat`?[]:[e.cursor]).at(-1):void 0;return{page:t,latestCursor:i,context:t.kind===`page`&&!t.hasMore&&t.frames.some(e=>e.kind===`update`&&e.cursor!==r.after)?Eo(e,n,i??null):F(void 0)}}).pipe(B(({page:e,latestCursor:t,context:n})=>{if(e.kind===`reset`)return u();i.kind===`live`&&i.stamp(),e.hasMore||(l=f.toolOutput);let a=e.hasMore?[]:d(f);if(a===void 0)return u();let s={after:t??r.after,delivery:e.hasMore?r.delivery:`live`,awaitSignal:!e.hasMore};return n.pipe(o(n=>[[...n===void 0?e.frames:e.frames.map(e=>e.kind===`update`&&e.cursor===t?Object.freeze({...e,context:n}):e),...a],i.kind===`replay`&&!e.hasMore?S():P(s)]))}))})))))}function Fo(e,t,r,i){let s=new Map,c=Or(),l=0,d=(o,l)=>M(()=>{let f=s.get(o);f===void 0&&(f={lock:jt(1),feed:void 0},s.set(o,f));let p=f;return p.lock.withPermit(n(n=>A(function*(){if(s.get(o)!==p)return yield*d(o,l);let f=p.feed;if(f===void 0){let l=yield*r.register(o).pipe(a(()=>k(()=>{s.get(o)===p&&s.delete(o)}))),d={stopped:!1},m=At(()=>{h()}),h=()=>{d.stopped||(d.stopped=!0,l.close(),d.producer?.interruptUnsafe(),d.heartbeat?.interruptUnsafe(),m.end(),p.feed=void 0,s.get(o)===p&&s.delete(o))};f={registration:l,frames:m,stop:h},p.feed=f;let g=yield*n(Ao(e,t,o,{includeSandboxFailures:!0})).pipe(a(()=>k(h)));l.setQueued(g.activity.queue.state===`queued`);let _=l.revision;d.producer=yield*u(Po(e,t,o,g.cursor??void 0,{kind:`live`,registration:l,progress:g.progress,stamp:()=>{_=l.revision}},!0).pipe(_t(e=>k(()=>{m.publish(e,_)})),oe(e=>k(()=>{m.end(e)})),j(k(h))),c,{uninterruptible:!1}).pipe(ce(i)),d.stopped||(d.heartbeat=yield*u(da(T(Gr).pipe(I({kind:`heartbeat`}))).pipe(_t(e=>k(()=>{m.publish(e)}))),c,{uninterruptible:!1}).pipe(ce(i)))}let m=f.frames.register(l);return{feed:f,queue:m}})))});return{acquire:(e,t)=>n(n=>M(()=>{if(l>=64)return E(new H(`runtime`,`rejected`,`Observation capacity is exhausted`));l+=1;let r=!1,i=()=>{r||(r=!0,--l)};return n(d(e,t)).pipe(o(({feed:e,queue:t})=>({feed:e,queue:Object.freeze({...t,close:()=>{i(),t.close()}})})),a(()=>k(i)))})),close:k(()=>{for(let e of s.values())e.feed?.stop();s.clear()}).pipe(b(vi(c,ze)))}}function Io(e){return An(null,()=>e.take.pipe(o(e=>e===`closed`?[[],S()]:[[e],P(null)])))}function Lo(e,t,n,r){let i=t,a=Un(n);return e.pipe(Ge(e=>A(function*(){let t=e===`reset`?yield*r():e;if(t.kind===`heartbeat`)return[t];if(t.kind===`progress`){let e=a?.messageId===t.progress.messageId?a:null;if(e!==null&&e.revision>=t.progress.revision)return[];let n=e?.text??0,i=e?.thinking??0;t.progress.text.offset>n||t.progress.thinking.offset>i?t=yield*r():a={messageId:t.progress.messageId,revision:t.progress.revision,text:t.progress.text.offset+t.progress.text.append.length,thinking:t.progress.thinking.offset+t.progress.thinking.append.length}}if(t.kind===`reset`)return i=t.cursor,a=Un(t.baseline.progress),[t];if(t.kind!==`update`)return[t];let n=i===null?void 0:Zi(i),o=t.cursor===null?void 0:Zi(t.cursor);if(n!==void 0&&o!==void 0&&n.generation!==o.generation){let e=yield*r();return i=e.cursor,a=Un(e.baseline.progress),[e]}let s=n?.sequence??0,c=o!==void 0&&o.sequence>s?t.cursor:i,l=e=>e?.some(e=>e.sequence<=s)===!0;if(c===t.cursor&&!l(t.messages)&&!l(t.terminals)&&!t.compactions?.some(e=>zi(e)<=s)&&!l(t.compactionNotices))return i=t.cursor,[t];let u={...t,cursor:c,messages:t.messages.filter(e=>e.sequence>s),terminals:t.terminals.filter(e=>e.sequence>s)};return t.compactions!==void 0&&(u.compactions=t.compactions.filter(e=>zi(e)>s)),t.compactionNotices!==void 0&&(u.compactionNotices=t.compactionNotices.filter(e=>e.sequence>s)),i=u.cursor,[u]})),Lt)}function Ro(e,t,n,r,i){return ft(t.assertOpen.pipe(b(jo(r,i)),B(r=>Ee(n.acquire(r.sessionId,r.options.includeSandboxFailures===!0),({queue:e})=>k(e.close)).pipe(o(({feed:n,queue:i})=>{let a=()=>{i.checkpoint(n.registration.revision)};return Lo(Po(e,t,r.sessionId,r.options.after,{kind:`replay`,checkpoint:a},r.options.includeSandboxFailures===!0).pipe(rn(Io(i))),r.options.after??null,null,()=>Mo(e,t,r.sessionId,r.options.includeSandboxFailures===!0,{beforeRead:a}))})))))}function zo(e,t){return z({try:()=>Object.freeze({sessionId:J(e),options:kr(t)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Watch options are invalid`)})}function Bo(e,t,r,i,s){return t.assertOpen.pipe(b(zo(i,s)),B(i=>n(n=>A(function*(){let{feed:s,queue:c}=yield*r.acquire(i.sessionId,i.options.includeSandboxFailures===!0),l=()=>{c.checkpoint(s.registration.revision)};return yield*n(t.assertOpen.pipe(b(Ao(e,t,i.sessionId,i.options,{beforeRead:l})),o(n=>Object.freeze({snapshot:n,changes:Lo(Io(c),n.cursor,n.progress,()=>Mo(e,t,i.sessionId,i.options.includeSandboxFailures===!0,{beforeRead:l})).pipe(st(k(c.close))),close:k(c.close)})))).pipe(a(()=>k(c.close)))}))))}function Vo(e,t,n,r){let i=Fo(e,t,n,r);return Object.freeze({read:(n,r)=>Ao(e,t,n,r),subscribe:(n,r)=>Ro(e,t,i,n,r),watch:(n,r)=>Bo(e,t,i,n,r),close:i.close})}function Ho(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(b(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(b(e.extensions.call({scope:`agent`},t,n,r)))})}function Uo(e,t,n){return e.assertOpen.pipe(b(z({try:()=>n(J(t)),catch:e=>e instanceof H?e:new H(`store`,`rejected`,`Session owner operation failed`)})))}function Wo(e,t){return z({try:()=>{let n=Xn(t);if(n._tag===`Failure`)throw new H(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:J(e),command:n.success})},catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Session command is invalid`)})}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(b(e.door.admit(o)),B(e=>e.status===`accepted`?F({status:`accepted`,commandId:e.commandId}):E(new H(`runtime`,`unavailable`,`Session command was not admitted`))))}function Ko(e,t,n,r,i){return t.assertOpen.pipe(b(Uo(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&hi(e.store,t,r.commandId,Fr(e.store,e.meta.identityPath,i))})),b(nr(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),B(e=>e===void 0?F({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(I({status:`accepted`,commandId:e.accepted.commandId}))))}function qo(e,t,n,r){return t.assertOpen.pipe(b(t.commit(Tr(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),B(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function Jo(e,t,n,r){return t.assertOpen.pipe(b(oa(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),I(void 0))}function Yo(e,t,n,r){return t.assertOpen.pipe(b(Yi(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function Xo(e,t,n,r,i){return t.assertOpen.pipe(b(Wo(n,i)),B(t=>Zo(e,r).pipe(o(e=>({...t,checked:e})))),B(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Go(t,n,r,i);case`abort`:return qo(e,t,n,i).pipe(I(void 0));case`cancel`:return Ko(e,t,n,r,i);case`branch`:return Jo(e,t,n,r);case`fork`:return Yo(e,t,n,r);case`operator`:return t.assertOpen.pipe(b(He(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),I(void 0));case`title`:return t.commit(Uo(t,n,t=>{Cn(e.store,t,r.title)})).pipe(D(()=>k(()=>{Si(e.store)})),I(void 0))}}))}function Zo(e,t){return z({try:()=>t===void 0?void 0:sn(e.meta,t),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Host metadata is invalid`)})}function Qo(e,t,n){let r=dt(e.store),i=Vo(e,t,r,n),a=(n,a)=>{function s(r){return Xo(e,t,n,a,r)}return Object.freeze({command:s,withdraw:e=>t.assertOpen.pipe(b(t.door.withdraw(n,e))),abort:s({type:`abort`}),send:(e,t)=>k(()=>t?.requestId??Ei()).pipe(B(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return s(t?.images===void 0?r:{...r,images:t.images}).pipe(p(e=>e.requestId===n?e:new H(e.boundary,e.cause,e.message,n)))})),cancel:e=>s({type:`cancel`,...e}),latestPending:Uo(t,n,t=>di(e.store,t,e.meta?.identityPath===void 0||a===void 0?void 0:Fr(e.store,e.meta.identityPath,a))),modelPreference:Object.freeze({read:Uo(t,n,t=>_n(e.store,t)),set:r=>z({try:()=>Sn(r),catch:()=>new H(`contract`,`invalid`,`Model preference is invalid`)}).pipe(B(r=>t.commit(Uo(t,n,t=>($i(e.store,t,r),t))).pipe(D(t=>k(()=>{Dt(e.store,t)})),ie)))}),extension:e=>Object.freeze({call:(r,i,a)=>t.assertOpen.pipe(b(t.extensions.call({scope:`session`,sessionId:n},e,r,i,a)))}),read:e=>t.assertOpen.pipe(b(i.read(n,e))),readSettlement:(i,a=0)=>pe(A(function*(){yield*t.assertOpen;let s=yield*z({try:()=>({sessionId:J(n),...gn(ar({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*Ee(r.register(s.sessionId,`settlement`),e=>k(e.close)),l=qr(e.store,s.sessionId,s.commandId),u=yield*l;return u!==void 0||s.timeoutMs===0?u:yield*A(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*E(new H(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(ke(s.timeoutMs),o(fe))})),subscribe:e=>i.subscribe(n,e),watch:e=>i.watch(n,e)})},s=Object.freeze({createSession:n=>t.assertOpen.pipe(b(ea(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(b(qe(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(b(zt(e.store,n))),extensions:Ho(t),session:e=>a(e,void 0),close:t.beginClose.pipe(b(i.close),b(r.close))});return Object.freeze({...s,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>Uo(t,n,t=>e.store.transactionSync(()=>Jt(e.store,t,r))),read:n=>Uo(t,n,t=>an(e.store,t))}),withMeta:e=>Object.freeze({...s,session:t=>a(t,e)})})}function $o(e){let t=_r.safeParse(e.meta);return t.success&&t.data.delegation?.steer===!0}function es(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(Kt(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||$o(t)?`steer`:`followUp`,type:`prompt`,text:t.content},n,t,r)}var ts=V({fork:gi([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:ei.pipe(W(pi(0)),W(qn(2**53-1)))});function ns(e,t){let n=xi(e.schema)(t);if(n._tag===`Failure`)throw new Ca({reason:`encode`,message:`Session document does not match its schema`});let r=K(Pe)(n.success);if(r._tag===`Failure`)throw new Ca({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 Ca({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function rs(e){return{...ht(ts)(e),schema:Qa(Ue(e.schema)),initial:ns(e,e.initial)}}var is=64,as=gi([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),os=Lr(as).pipe(W(ta(10))),ss=V({protocol:xr(`shiitake.extension/v0`),id:fi,version:sr,requests:os}),cs=Lr(V({id:fi,capabilities:os,grantKey:G(fi)})).pipe(W(ta(is))),ls=mn.pipe(W(Jr(/^[a-z][A-Za-z0-9_]{0,63}$/u))),us=K(ss,{onExcessProperty:`error`}),ds=K(cs,{onExcessProperty:`error`}),fs=K(ls);function X(e){return new H(`extensions`,`invalid`,e)}function ps(e){return new Set(e).size!==e.length}function ms(e){return JSON.stringify(e,(e,t)=>Me(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function hs(e){return re({try:async()=>{let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return Array.from(new Uint8Array(t),e=>e.toString(16).padStart(2,`0`)).join(``)},catch:()=>new H(`extensions`,`rejected`,`Extension digest failed`)})}function gs(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:Qa(Ue(t.input)),output:Qa(Ue(t.output))}])),projection:r.projection===null?null:Qa(Ue(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,Qa(Ue(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,rs(t)]))};return o===void 0?c:{...c,catalog:o}}function _s(e){if(us(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(ps(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`||fs(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 vs(e){return A(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*z({try:()=>{if(t.length>is)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=to(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(fs(e)._tag===`Failure`)throw X(`Session document name is invalid`);rs(t)}let r=_s(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(ps(e.map(({manifest:e})=>e.id)))throw new H(`extensions`,`conflict`,`Extension identities conflict`);let r=ds(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(ps(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||ps(t.capabilities)||t.capabilities.some(e=>!n.manifest.requests.includes(e)))throw X(`Extension grant is invalid`);i.set(t.id,t.capabilities)}if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`compaction_handoff`)).length>1)throw new H(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new H(`extensions`,`conflict`,`Files slot is already owned`);return e.map(e=>({...e,grants:i.get(e.manifest.id)??[]})).sort((e,t)=>e.manifest.id<t.manifest.id?-1:+(e.manifest.id>t.manifest.id))},catch:e=>e instanceof H?e:X(`Extension roster is invalid`)});return yield*Ae(r,e=>A(function*(){let t=`sha256:${yield*hs(yield*z({try:()=>ms(gs(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*hs(ms([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:ht(Ai)(t),fingerprint:ht(Qn)(r)})}))})}function ys(e){return hs(ms({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}var bs=R().min(1).max(256),xs=v([`create`,`manage`,`read`,`send`,`delegate`]),Ss=w(()=>x({actor:bs,workflowRunId:bs.optional(),toolCallInputDigest:R().regex(/^[a-f0-9]{64}$/).optional(),session:x({agentId:bs,sessionId:bs}).optional()}));w(()=>x({agents:je([ye(`all`),Se(bs)]),actions:Se(xs).max(5),expiresAt:ue().int().nonnegative(),provenance:Ss,meta:se().optional(),maxDepth:ue().int().min(1).max(8).optional()})),ci({family:`agent`,version:1,kinds:{agent:{prefix:`agent`}}}),w(()=>x({agent_id:R(),name:R(),actor_user_id:R(),created_by:R().min(1).max(256).nullable(),created_at:ue().int().nonnegative(),updated_at:ue().int().nonnegative()})),w(()=>x({request_id:R(),actor_user_id:R(),name:R(),agent_id:R(),computer_mode:R().min(1).max(4096)})),w(()=>x({name:R().min(1).max(256),requestId:R().min(1).max(256),configuration:R().min(1).max(4096),createdBy:R().min(1).max(256).nullable().optional()})),w(()=>x({name:R().min(1).max(256)}));var Cs=class extends Error{status;code;constructor(e,t){super(t),this.status=e,this.code=t}};w(()=>x({requestId:bs,agentId:bs,sessionId:bs.optional(),delivery:v([`followUp`,`steer`]).optional(),goal:je([R().min(1).max(4e3),ye(!1)]).optional(),text:R().min(1).max(262144)}).refine(({goal:e,sessionId:t,delivery:n})=>e===void 0||t===void 0&&n!==`steer`,{path:[`goal`],error:`goal requires a new-Session follow-up`})),y({delegation:_r.shape.delegation});var ws=w(()=>x({input:R(),mail:R(),state:v([`pending`,`held`,`accepted`,`undeliverable`]),receipt:R().nullable()})),Ts=ht(Et(Vt));function Es(e){let t=$a(e).unsettled()[0];if(t===void 0)return;let n=ws.parse(t),r=Ts(n.mail),i=r.to.sessionId;if(i===void 0)throw new Cs(503,`partial_init`);return{agentId:r.to.agentId,sessionId:i,commandId:jr(R().parse(n.receipt)).commandId}}function Ds(e){return new H(`model`,`rejected`,e)}function Os(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 ks(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 As(e,t,n){let r=Dn(),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)Fn(t,r);return r}function js(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 Ms(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`&&!js(e,a+1,n,i)&&r.push(a)}return r}function Ns(e,t,n,r){let i=Ms(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=lo(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function Ps(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 Fs(e,t,n,r){let i=Ns(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...Ps(e,t,i)}}function Is(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=jn(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=fo(ks(e)).tokens,s=Fs(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=As(u,e,r);for(let e of d)Fn(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 Ls={enabled:!0,maxRetries:3,baseDelayMs:2e3};function Rs(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??vo()};return Ni(()=>Promise.resolve((r??hr)(e,pa(t),i)).then(e=>e.result()),Ls,i.signal)}function zs(e){return{systemPrompt:Rt,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function Bs(e,t,n){let r=e.previousSummary??``,i=t?fa:Ct,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${Mt(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function Vs(e){return`# Conversation\n${Mt(e.turnPrefixMessages)}\n\n# Instructions\n${fn}`}async function Hs(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await Rs(e,zs(r),o,a),c=Hn(s,i);if(c!==void 0)throw Error(c);return s}function Us(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):Hs(t,n,r,Bs(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function Ws(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,Vs(e),`Turn prefix summarization`,r)}function Gs(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.`:ha(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${ha(n.content)}`,i=t===void 0?n.usage:Os(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=ha(t.content),i=t.usage}let a=vt(e.fileOps);return{summary:r+pt(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function Ks(e,t,n,r,i){return Gs(e,await Us(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 Ws(e,t,n,i):void 0)}function qs(e,t,n,r,i){return M(()=>{let a;return re({try:i=>{let o=Ks(e,t,i,r,n);return a=o,o},catch:e=>Ds(e instanceof Error?e.message:String(e))}).pipe(s(()=>{let e=a;return e===void 0||i===void 0?L:_(()=>new Promise(t=>{let n=setTimeout(()=>{t(!1)},i.graceMs),r=()=>{clearTimeout(n),t(!0)};e.then(r,r)})).pipe(B(e=>e?L:i.onUndrained))}))})}function Js(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var Ys=new WeakMap;function Xs(e){return Ys.has(e)}function Zs(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return Cr(t,k(()=>{$s(e,r)})).pipe(b(u(i,t)),o(t=>(r.fiber=t,Ys.set(e,r),r)))}function Qs(e){let t=e.summary;return e.summary=void 0,t}function $s(e,t){t.fiber=void 0,t.summary=void 0,Ys.get(e)===t&&Ys.delete(e)}function ec(e){return new H(`runtime`,`rejected`,e)}var tc={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`},nc=class extends H{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,tc[e]),this.phase=e,this.usage=t}get diagnostic(){return tc[this.phase]}};function rc(e,t){let n=Qr(e,t),r=$e(e),i=[];for(let t of e){let e=hn(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:sa(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:ra(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 ic(e,t,n){return z({try:()=>ca(e,{sessionId:t,workId:n}),catch:()=>ec(`Woodstock selected lineage is unavailable`)})}function ac(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return dr([...e,i],r).reduce((e,t)=>e+lo(t),0)}function oc(e,t,n){return M(()=>(bi(e.store,e.sessionId,n.trigger),sc(e,t,n).pipe(j(k(()=>{wt(e.store,e.sessionId)})))))}function sc(e,t,n){return A(function*(){let r=Is(rc(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*qs(r,e.model,e.stream,n.instructions,e.cleanup),o=yield*uc(e,r,a,i.id);return yield*pc(e,t,a,n,i.id,o)})}var cc=Le([V({type:xr(`accepted`),receipt:Ki}),V({type:xr(`discarded_by_policy`)})]),lc=K(cc);function uc(e,t,n,r){return e.handoff===void 0?F(void 0):e.handoff.consume(Js(t,n,e.sessionId,r)).pipe(s(()=>e.cleanup?.onUndrained??L),p(()=>new nc(`handoff`,n.usage)),B(e=>{let t=lc(e);return t._tag===`Failure`?E(new nc(`handoffResult`,n.usage)):F(t.success.type===`accepted`?t.success.receipt:void 0)}))}function dc(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=ac(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[Ke(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 fc(e,t,n){let r=[...t,n];return{path:r,messages:dr(r,e.workId)}}function pc(e,t,n,r,i,a){let s=dc(e,t,n,r,i,a);return s===void 0?F(void 0):z({try:()=>Gi(e.store,s),catch:e=>e instanceof H?e.cause===`conflict`?new nc(`conflict`):e:ec(`Woodstock compaction append failed`)}).pipe(o(n=>fc(e,t,n)))}function mc(e){return e instanceof nc?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function hc(e,t){return z({try:()=>{Kn(e.store,t)},catch:e=>e instanceof H?e:ec(`Compaction notice could not be recorded`)})}function gc(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return hc(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:mc(n),usage:n instanceof nc?n.usage:void 0})}function _c(e,t,n){return Oe(oc(e,t,n)).pipe(B(t=>t._tag===`Success`?F(t.success):gc(e,n.trigger,t.failure).pipe(I(void 0))))}var vc={trigger:`threshold`,resumesRun:!1};function yc(e,t,n,r){return t.stopped||Xs(e.store)||!Ot(n,e.model.contextWindow,e.settings)?L:r.pipe(B(n=>bc(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function bc(e,t,n){let r=n.at(-1),i=Is(rc(n,e.workId),e.settings);return r===void 0||i===void 0?F(void 0):Zs(e.store,t,t=>xc(e,i,r.id,t))}function xc(e,t,n,r){return M(()=>(bi(e.store,e.sessionId,`threshold`),qs(t,e.model,e.stream,void 0,e.cleanup).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),j(k(()=>{wt(e.store,e.sessionId)})))))}function Sc(e,t,n,r){return M(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?F(void 0):(t.slot=void 0,Oe(Rn(a).pipe(B(()=>wc(e,i)),B(t=>t===void 0?F(void 0):Tc(e,t,n)))).pipe(B(n=>n._tag===`Success`&&n.success!==void 0?F(n.success):(t.stopped=!0,n._tag===`Success`?F(void 0):gc(e,`threshold`,n.failure).pipe(I(void 0)))),j(k(()=>{$s(e.store,i)}))))})}function Cc(e,t,n){return hc(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(I(void 0))}function wc(e,t){let n=Qs(t);if(n===void 0)return F(void 0);let{result:r,selectionTail:i}=n;return z({try:()=>ri(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof H?e:ec(`Woodstock compaction head is unavailable`)}).pipe(B(t=>t===`stale`?Cc(e,r,`stale`):uc(e,n.preparation,r,i).pipe(o(e=>({result:r,selectionTail:i,receipt:e})))),j(k(()=>{$s(e.store,t)})))}function Tc(e,t,n){return ic(e.store,e.sessionId,e.workId).pipe(B(r=>{let i=dc(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?F(void 0):wi(i.tokensAfter,e.model.contextWindow,e.settings)?Cc(e,t.result,`insufficient`):z({try:()=>Ze(e.store,i),catch:e=>e instanceof H?e.cause===`conflict`?new nc(`conflict`):e:ec(`Woodstock compaction append failed`)}).pipe(B(n=>n===`stale`?Cc(e,t.result,`stale`):F(fc(e,r,n))))}))}function Ec(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return F(n);let r=fo(e.messages).tokens;return wi(r,e.model.contextWindow,e.settings)?_c(e,e.path,vc).pipe(o(e=>e??n)):yc(e,t,r,F(e.path)).pipe(I(n))}function Dc(e,t){let n=ui(e.message,t.contextWindow),r=Ui(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function Oc(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function kc(e,t,n,r){if(!e.settings.enabled)return F(void 0);let i=wi(fo([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?ic(e.store,e.sessionId,e.workId):F(void 0)}function Ac(e,t,n){return(r,i)=>A(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=fo(r).tokens,s=wi(o,e.model.contextWindow,e.settings),c=yield*Sc(e,n,vc,s);if(c!==void 0)return a(c);let l=ic(e.store,e.sessionId,e.workId);if(!s){yield*yc(e,n,o,l);return}let u=yield*_c(e,yield*l,vc);return u===void 0?void 0:a(u)})}function jc(e,t,n){return A(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,Ac(e,t,n)),o=Dc(a,e.model),s=o.retry&&!i,c=yield*Sc(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:Oc(c.messages)},i=!0;continue}let l=yield*kc(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*_c(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:Oc(u.messages)},i=!0}})}function Mc(e){return A(function*(){let t={scope:yield*ae,slot:void 0,stopped:!1};return yield*jc(e,e.settings.enabled?yield*Ec(e,t):e,t)})}function Nc(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?F(`compacted`):oc(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(te(t=>gc(e,`manual`,t)),B(t=>t===void 0?gc(e,`manual`,void 0).pipe(I(`nothing_to_compact`)):F(`compacted`)))}var Pc=ei.pipe(W($r(0)),W(qn(2**53-1))),Fc=V({reserveTokens:G(Pc),keepRecentTokens:G(Pc),backgroundTokens:G(Pc)}),Ic=V({enabled:G(mi),reserveTokens:G(Pc),keepRecentTokens:G(Pc),backgroundTokens:G(Pc),modelOverrides:G(na(mn,Fc))}),Lc=K(Ic,{onExcessProperty:`error`});function Rc(e){let t=Lc(e??{});if(t._tag===`Failure`)throw new H(`contract`,`invalid`,`Compaction settings must be non-negative whole token counts`);let n=t.success;return e=>{let t=n.modelOverrides?.[`${e.provider}/${e.id}`];return{enabled:n.enabled??ct.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??ct.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??ct.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??ct.backgroundTokens}}}var zc=1e3;function Bc(e,t,n,i){return A(function*(){let a=yield*r(n);(yield*le(Rn(a).pipe(I(!0)),T(1e3).pipe(I(!1))))||(i.released=!1,yield*d(`shiitake_run_finalizer_hung`).pipe(N({workId:t,finalizer:e})))})}function Vc(e,t,n){return Sa(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference}).pipe(o(e=>({...e,release:Bc(`model`,t.command.entry.workId,e.release,n)}))))}var Hc={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},Uc=class extends H{phase;constructor(e){super(`runtime`,`rejected`,Hc[e]),this.phase=e}get diagnostic(){return Hc[this.phase]}},Wc={model:`model-failed`,tool:`tool-failed`,control:`control-failed`,listener:`listener-failed`},Gc=class extends H{reason;constructor(e,t){super(`runtime`,`rejected`,`Mule rejected the durable command run`,void 0,t),this.reason=e}get diagnostic(){return Wc[this.reason]}};function Kc(e){return new Gc(e.phase,e)}function qc(e,n,r,i,a,o,s,c){let l=e.tools,u=a.modules??[],d=[...u,...o];return l===void 0?u.length>0||s.length>0?E(new Uc(`missing`)):F([]):A(function*(){let a={sessionId:n,commandId:r};i!==void 0&&(a={...a,meta:i});let o={sources:l.sources,session:a,sandbox:l.sandbox,onSandboxFailure:t=>On(e.store,{sessionId:n,commandId:r},t).pipe(g),modules:[...l.modules,...d],tools:s,access:{...l.access,sessionGrants:()=>an(e.store,n)?.grants??{}}},u=yield*Nr();yield*xe(()=>Bc(`tools`,r,vi(u,Zr(void 0)),c));let f=yield*(yield*Ri(l.execution===void 0?o:{...o,execution:l.execution}).pipe(t(mr,u),p(()=>new Uc(`runtime`)))).acquire().pipe(t(mr,u),p(()=>new Uc(`lease`)));return[f.executeTool,...f.tools]})}function Jc(e,t,n,r,i,a,l,u){return pe(A(function*(){let d=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),f=d.release;f!==void 0&&(yield*xe(()=>Bc(`instructions`,t.command.entry.workId,k(f),l))),l.released=!0;let m=yield*Vc(e,t,l),h=yield*qc(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,d,r,i,l),g=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),_=yield*et(e.store,g,n,m.model),v=t=>Mn(e.store,{sessionId:g.sessionId,workId:g.commandId,delivery:t}).pipe(o(e=>e.map(({message:e})=>e)),p(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof H?e.message:`Session control delivery failed`}))),ee=t.resume,y=Rc(e.compaction)(m.model),te,b=0;return{run:yield*Mc({cleanup:{graceMs:zc,onUndrained:k(()=>{l.released=!1})},store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:m.model,stream:m.stream,handoff:a,settings:y,path:t.path,messages:t.messages,resuming:ee!==void 0,run:(t,n)=>{b=0;let r=ee;ee=void 0;let i,a=e=>{if(l.isStopping()&&e.type===`run_end`&&e.outcome===`cancelled`)return L;if(e.type===`run_end`&&e.outcome===`failed`)return i=e,L;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=m.providerError?.(e.value);if(t!==void 0)return _({...e,value:{...e.value,providerError:t}})}return _(e)},f={onUndrained:k(()=>{l.released=!1}),model:m.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??zr,retryAfterMs:m.retryAfterMs,retryable:m.retryable,systemPrompt:d.text,prepareSystemPrompt:()=>(u===void 0?F([]):u().pipe(s(()=>k(()=>{l.released=!1})))).pipe(o(e=>d.text+e.map(({name:e,text:t})=>`\n\n[extension:${e}]\n${t}`).join(``)),p(e=>({_tag:`MuleError`,phase:`model`,message:`Extension prompt is unavailable`,cause:e}))),messages:t,resume:r,tools:h,getSteeringMessages:()=>v(`steer`),prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(p(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>l.isStopping()&&t.type===`retry_finished`&&!t.success?L:(t.type===`retry_finished`&&!t.success&&(b=t.attempt+1),la(e.store,g,lt(t,m.model),t.turn))};return Oi.run(m.stream===void 0?f:{...f,stream:m.stream},a).pipe(c(e=>{if(i===void 0)return L;if(rt(e)){let t=e.value.modelLimitReason??m.failureReason?.(e.value.message)??Ln(e.value);return te=(b>1&&e.value.modelLimitReason===void 0&&m.rejection?.(e.value.message)?.code!==`usage-limit-reached`?`The model failed ${String(b)} times on this conversation: ${t}`:t).slice(0,200),_(i,te)}let t=nn(e.cause);return _(i,ne(t)?Wn({runId:i.run.value,provider:m.model.provider,model:m.model.id}):t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):`runtime:rejected: ${Kc(t.value).diagnostic}`)}),p(e=>e.phase===`model`?new H(`model`,`rejected`,e.message,void 0,e):Kc(e)))}}),failureReason:te}}))}function Yc(e,t,n,r){return pe(A(function*(){r.released=!0;let i=yield*Vc(e,t,r),a=t.command.entry;return yield*Nc({cleanup:{graceMs:zc,onUndrained:k(()=>{r.released=!1})},store:e.store,sessionId:t.command.sessionId,workId:a.workId,model:i.model,stream:i.stream,handoff:n,settings:Rc(e.compaction)(i.model),path:t.path,instructions:ir(a)?a.instructions:void 0})}))}var Xc=Object.freeze({maxRecoveries:2,windowMs:6e4});function Zc(e){return new H(`runtime`,`rejected`,e)}function Qc(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof Uc||e instanceof Gc||e instanceof nc||e instanceof Br?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function $c(e,t){return d(`shiitake_run_failed`,Hi(t)).pipe(N({workId:e,reason:`${t.boundary}:${t.cause}`}))}function el(e,t,n,r,i){return A(function*(){Dt(e.store,n.queue);let a=yield*z({try:()=>St(n),catch:()=>Zc(`Agent work payload is invalid`)}),s=yield*vn(e.store,a.work);if(s.abnormalTerminal!==void 0)return{kind:s.abnormalTerminal};let c=r?.incompatibleMigrations()[0];if(c!==void 0)return yield*d(`shiitake_run_contract_changed`).pipe(N({workId:n.jobId,terminal:`contract_changed: ${c}`})),yield*E(Zc(`contract_changed: ${c}`));let l=new Set(r?.runParticipants().map(([e])=>e)??[]);if(ir(s.command.entry))return yield*Yc(e,s,r?.compactionHandoff(l),i),yield*mt(e.store,{sessionId:s.command.sessionId,commandFactId:a.work.commandFactId,workId:s.command.entry.workId,outcome:`completed`}),{kind:`completed`};let u=yield*z({try:()=>Ie(e.store,a.work.sessionId,a.work.commandFactId,s.command.entry.workId),catch:()=>Zc(`Accepted run origin is unavailable`)}),f={sessionId:s.command.sessionId,workId:s.command.entry.workId,origin:u===null?null:{extensionId:ht(Ir)(u.extensionId),correlation:u.correlation}},p=r===void 0?[]:yield*r.filesForRun(f,l),m=r===void 0?[]:yield*Ae([...l],t=>r.modulesForRun(f,new Set([t])).pipe(B(n=>z({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>yr.grantAs(e,r))},catch:()=>Zc(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),h=r?.compactionHandoff(l),{run:g,failureReason:_}=yield*Jc(e,s,{core:p.length===0?t:yield*ys(p.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},m,p,h,i,r===void 0?void 0:()=>r.promptSections(f,l));switch(g.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:_??Ln(g)}}}).pipe(oe(e=>$c(n.jobId,e).pipe(I(Qc(e)))))}var tl=K(ki,{onExcessProperty:`error`}),nl=K(Yr(mi)),rl=K(Je,{onExcessProperty:`error`});function il(e){if(e.reply===void 0)return;let t=gn(rl(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 H(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function al(e,t){let n=t.mail;return n?.from.kind===`agent`&&n.replyTo.length>0?{agentId:n.from.agentId,sessionId:n.from.sessionId,name:Ii(t.meta)?.name??n.from.agentId}:t.continuesWorkId===void 0?t.origin.kind===`extension`?bn(e,t.sessionId):void 0:Xt(e,t.sessionId,t.continuesWorkId)}function ol(e){let t=t=>({sessionId:J(t.sessionId),requireExistingSession:gn(nl(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:gn(Pr(t.command),`Session command is invalid`),origin:gn(tl(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:il(t),onAccepted:t.onAccepted,continuesWorkId:t.continuesWorkId,meta:t.meta===void 0?void 0:sn(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(Pi(e.owner,r,a.requestId),t.requireExistingSession&&!wr(e.owner,r))throw new H(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&Ji(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&Ji(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested&&!gr(e.owner,r,o.jobId)?o.jobId:void 0,c=tr(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=al(e.owner,t);n!==void 0&&Xr(e.owner,r,c.accepted.commandId,n)}return c.delivery===`new`&&t.onAccepted?.(r,c.accepted.commandId),n.set(r,(n.get(r)??!1)||c.delivery===`new`),Object.freeze({status:`accepted`,commandId:c.accepted.commandId,delivery:c.delivery})},r=(t,r)=>M(()=>{let i=new Map,a=z({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof H?e:new H(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(D(()=>k(()=>{for(let[t,n]of i)n&&Dt(e.owner,t)})),D(()=>i.size>0?e.requestWake:L))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>z({try:()=>({sessionId:J(t),requestId:qi({requestId:n})}),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(B(t=>r(()=>it(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>z({try:()=>t(e),catch:e=>e instanceof H?e:new H(`contract`,`invalid`,`Session command is invalid`)}).pipe(B(e=>r(t=>t(e),n??`request`)))})}var sl=`core`,cl=`core-report`,ll=256,ul=1048576,dl=512,fl=64,pl=new TextEncoder,ml=K(Lr(V({name:mn.pipe(W(Jr(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:mn.pipe(W(yn(1)),W(Bt(e=>pl.encode(e).byteLength<=8192)))})).pipe(W(ta(16)))),hl=class extends Error{};function gl(e){return e.length<=dl?e:`${e.slice(0,511)}…`}var _l=Pt(Et(Pe));function vl(e){return e instanceof _a?e.reason:`${e._tag}: ${e.message}`}function yl(e){return e instanceof _a||e instanceof Ca||e instanceof ya||e instanceof ga}function bl(e,t){let n=nn(t);if(we(n)){let t=n.value;return t instanceof _a?gl(t.reason):gl(yl(t)?`${e}: ${vl(t)}`:`${e} failed`)}let r=be(qt(t));return we(r)?r.value instanceof Error?gl(r.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${r.value.message}`):gl(`${e} defect`):gl(`${e} was interrupted`)}function xl(e){let t=nn(e);return ne(t)||t.value instanceof _a}function Z(e,t){return new Ca({reason:e,message:t})}function Sl(e,t){return e.length>=1&&e.length<=ll?F(e):E(Z(`bound`,`${t} must be 1..256 characters`))}function Cl(e){let t=gl(e.message);if(e instanceof ga)switch(e.reason){case`invalid`:return new H(`contract`,`invalid`,t);case`conflict`:return new H(`store`,`conflict`,t);case`not_found`:return new H(`store`,`rejected`,t);case`rejected`:return new H(`extensions`,`rejected`,t)}if(e instanceof ya)switch(e.reason){case`invalid`:return new H(`contract`,`invalid`,t);case`conflict`:return new H(`contract`,`conflict`,t);case`closed`:return new H(`runtime`,`closed`,t)}return e.reason===`bound`?new H(`contract`,`invalid`,t):new H(`store`,`unavailable`,t)}function wl(e){let{owner:n}=e,r=new WeakMap,i=new Map,s=new Set,c,u=new Set,f=new Set,p,m=e=>Object.freeze({extensionId:e}),h=e=>B(xa,t=>t.extensionId===e?L:ve(Error(`Extension read used another extension's context`))),_=e=>B(ba,t=>{let n=r.get(t);return n?.extensionId===e?F(n):ve(Error(`Extension write used outside its own core transaction`))}),v=e=>z({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),y=(e,t)=>e.admitted.grants.has(t)?L:E(Z(`unavailable`,`Extension is not granted ${t}`));function te(e,t,r){let i=e.admitted.id,a=xt(Et(r.schema)),s=Tn(r.schema),l=e=>{let n=a(e);return n._tag===`Failure`?E(Z(`decode`,`Stored ${t} record is invalid`)):F(n.success)};return Object.freeze({peek:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);let o=ji(n,i,t,r);if(o===void 0)return S();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return P(s.success)},peekPage:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);if(!Number.isSafeInteger(r.limit)||r.limit<1||r.limit>fl)throw Z(`bound`,`Page limit must be 1..64`);return lr(n,i,t,r).map(e=>{let n=a(e);if(n._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return n.success})},get:r=>h(i).pipe(b(y(e,`state`)),b(v(()=>ji(n,i,t,r))),B(e=>e===void 0?F(S()):l(e).pipe(o(P)))),page:r=>h(i).pipe(b(y(e,`state`)),b(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=fl?L:E(Z(`bound`,`Page limit must be 1..64`))),b(v(()=>lr(n,i,t,r))),B(e=>Ae(e,l))),put:a=>_(i).pipe(b(y(e,`state`)),b(M(()=>{let e=s(a);if(e._tag===`Failure`)return E(Z(`encode`,`The ${t} record does not match its schema`));let o=JSON.stringify(e.success);if(pl.encode(o).byteLength>ul)return E(Z(`bound`,`The ${t} record exceeds 1 MiB`));let c=r.index?.(a)??null;return de([Sl(r.key(a),`A record key`),c===null?F(null):Sl(c,`A record index`)]).pipe(B(([e,r])=>v(()=>{ii(n,i,t,e,r,o)})))}))),remove:r=>_(i).pipe(b(y(e,`state`)),b(v(()=>{Li(n,i,t,r)})))})}function x(e,t,r){let i=e.admitted.id,a=xt(Et(r.schema)),o=Tn(r.schema),s=()=>{if(!u.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>ll)throw Z(`bound`,`A record key must be 1..256 characters`);return e},l=e=>{let n=a(e);if(n._tag===`Failure`)throw Z(`decode`,`Stored ${t} record is invalid`);return n.success};return Object.freeze({get:e=>{s();let r=ji(n,i,t,c(e));return r===void 0?S():P(l(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>fl)throw Z(`bound`,`Page limit must be 1..64`);return lr(n,i,t,e).map(l)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${t} record does not match its schema`);let l=JSON.stringify(a.success);if(pl.encode(l).byteLength>ul)throw Z(`bound`,`The ${t} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),ii(n,i,t,c(r.key(e)),u,l)},remove:e=>{s(),Li(n,i,t,c(e))}})}function re(t){let r=t.admitted.id;return Object.freeze({set:(i,a)=>_(r).pipe(D(()=>y(t,`timers`)),D(()=>Sl(i,`A timer key`)),D(()=>Number.isSafeInteger(a)&&a>=0?L:E(Z(`bound`,`A timer instant is invalid`))),B(t=>v(()=>{Yn(n,e.watchdog,r,i,a),t.timersChanged=!0}))),cancel:i=>_(r).pipe(D(()=>y(t,`timers`)),B(t=>v(()=>{li(n,e.watchdog,r,i),t.timersChanged=!0}))),read:i=>h(r).pipe(b(y(t,`timers`)),b(v(()=>pr(n,e.watchdog,r,i))),o(ge))})}function ie(t){let r=t.admitted.id,i=(i,a)=>_(r).pipe(D(()=>y(t,`attention`)),B(t=>z({try:()=>{J(i),a(),Ve(n,i,e.readQueueHead(i)),t.observed.add(i)},catch:e=>e instanceof Ca&&e.reason===`session_absent`?e:e instanceof H&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,t)=>{let a=K(Qt,{onExcessProperty:`error`})(t.waitingOn===void 0?t:{...t,inbox:!1});return a._tag===`Failure`?E(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!wr(n,e))throw Z(`session_absent`,`Attention Session is absent`);gt(n,e,r,a.success)})},awaitsDecision:e=>h(r).pipe(D(()=>y(t,`attention`)),b(v(()=>dn(n,e)))),clear:(e,t)=>Sl(t,`An attention id`).pipe(b(i(e,()=>{Ft(n,e,r,t)})))}}function ae(e){let t=e.admitted.id;return n=>_(t).pipe(B(r=>e.admitted.grants.has(`send`)?z({try:()=>{let{requireExistingSession:e=!1}=n,i=r.admit({sessionId:n.sessionId,requireExistingSession:e,command:{type:`prompt`,requestId:n.prompt.requestId,delivery:n.prompt.delivery,text:n.prompt.text},when:n.when,origin:{kind:`extension`,extensionId:t,correlation:n.correlation??null},continuesWorkId:n.continuesWorkId});return i.status===`accepted`?{_tag:`Accepted`,commandId:i.commandId,delivery:i.delivery}:{_tag:`NotReady`}},catch:e=>new ya({reason:e instanceof H?e.cause===`conflict`?`conflict`:e.cause===`archived`?`archived`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof H?e.message:`Session command is invalid`})}):E(new ya({reason:`closed`,message:`Extension is not granted send`}))))}function se(i,a,s){return M(()=>{let c,l,u=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let n=m(i.admitted.id);l={extensionId:i.admitted.id,admit:e,observed:new Set,timersChanged:!1},r.set(n,l),f.add(i.admitted.id);let o=p;p=l;try{c=Te(a.pipe(t(ba,n),t(xa,n)))}finally{p=o,r.delete(n),f.delete(i.admitted.id)}if(xn(c))throw u;return c.value},s).pipe(o(()=>{if(c===void 0)throw Error(`Extension transaction returned no exit`);return c}),oe(e=>c!==void 0&&xn(c)?F(c):E(e)),D(t=>rt(t)&&l!==void 0?A(function*(){for(let e of l?.observed??[])Dt(n,e);s===`request`&&l?.timersChanged===!0&&(yield*e.requestWake)}):L))})}function ce(e,n,r){return l(n)?se(e,n,r):O(n.prepare.pipe(t(xa,m(e.admitted.id)))).pipe(B(t=>xn(t)?F(Qi(t.cause)):e.status===`running`?se(e,t.value,r):E(new H(`extensions`,`unavailable`,`Extension is stopped`))))}function le(t){let r=``;for(let i=0;i<Be;i+=fl){let i=ua(n,t,r);for(let t of i)Ve(n,t,e.readQueueHead(t)),queueMicrotask(()=>{Dt(n,t)});let a=i.at(-1);if(i.length<fl||a===void 0)return;r=a}}function C(t,r,i,a){let o=Date.now();t.status=`stopped`,t.reason=r,t.stoppedAt=o;let s=z({try:()=>{let i=()=>{Dr(n,t.admitted.id,{status:`stopped`,reason:r,stoppedAt:o,revision:t.admitted.revision}),cn(n,e.watchdog,t.admitted.id),le(t.admitted.id)};a===`own-transaction`?n.transactionSync(i):i()},catch:e=>new H(`store`,`unavailable`,`Extension ${t.admitted.id} stop status is unavailable`,void 0,e)});return A(function*(){let e=yield*O(s);return yield*d(`shiitake_extension_stopped`).pipe(N({extensionId:t.admitted.id,reason:r,cause:i===void 0?null:Hi(i),durable:rt(e)})),yield*e})}function w(t,r,i){t.status=`stopped`,t.reason=r,t.stoppedAt=Date.now();let a=()=>{Dr(n,t.admitted.id,{status:`stopped`,reason:r,stoppedAt:t.stoppedAt,revision:t.admitted.revision}),cn(n,e.watchdog,t.admitted.id),le(t.admitted.id)};try{i===`own-transaction`?n.transactionSync(a):a()}catch(e){throw new H(`store`,`unavailable`,`Extension ${t.admitted.id} stop status is unavailable`,void 0,e)}}function T(e,t,r){let i=t=>{if(p?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return J(t),p},a=a=>{i(a);let o=or(n,a,e.admitted.id,t)??ns(r,r.initial);if(pl.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=K(Et(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));$t(n,o,e.admitted.id,t,ns(r,l)),c.observed.add(o)}})}function ue(t){let r=new Set;return Object.freeze({collection:(e,n)=>te(t,e,n),updateCollection:(e,n)=>x(t,e,n),document:(e,n)=>T(t,e,n),update:e=>{let i=t.admitted.id;if(t.status!==`running`||!t.admitted.grants.has(`state`)||u.has(i)||f.has(i)||c===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let t=n.transactionSync(()=>{u.add(i);try{return Ti(e,void 0)}finally{u.delete(i)}});for(let e of r)Dt(n,e);return t}catch(e){if(!(e instanceof Fi))throw e;let n=e.message;throw w(t,n,`own-transaction`),new _a({reason:n})}finally{r.clear()}},observeUpdate:e=>{if(!u.has(t.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);r.add(J(e))},context:Object.freeze({manifest:t.admitted.manifest,revision:t.admitted.revision,grants:Object.freeze([...t.admitted.grants]),send:ae(t),timers:re(t),attention:ie(t),isObserved:e=>t.status===`running`&&En(n,e),sessionPosition:e=>h(t.admitted.id).pipe(b(y(t,`state`)),b(v(()=>{let t=J(e);if(!wr(n,t))throw Z(`unavailable`,`Session timeline is unavailable`);return aa(n,{sessionId:t})?.newestSequence??0}))),hasPendingSteer:e=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>Wi(n,J(e.sessionId),e.workId)))),workSender:e=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>Xt(n,J(e.sessionId),e.workId)??null))),sessionParent:e=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>bn(n,J(e))??null))),recipientStatus:n=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(e.recipientStatus?.(n)??F(`unknown`))),recipientParent:n=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(e.recipientParent?.(n)??E(Z(`unavailable`,`Recipient parent is unavailable`)))),hasSuccessfulToolResult:(e,r)=>h(t.admitted.id).pipe(b(y(t,`run_tools`)),b(v(()=>yi(n,J(e.sessionId),e.workId,r)))),observe:e=>_(t.admitted.id).pipe(o(t=>{t.observed.add(e)})),transact:e=>(t.status===`running`?ce(t,e,`request`).pipe(g):E(new _a({reason:t.reason??`Extension is stopped`}))).pipe(B(e=>{if(rt(e))return F(e.value);if(!xl(e.cause))return ee(e.cause);let n=bl(`transact`,e.cause);return C(t,n,e.cause,`own-transaction`).pipe(B(()=>E(new _a({reason:n}))))}))})})}function fe(e){let{id:t,definition:r,revision:i}=e.admitted,a=r.state.version,o=ti(n,t);if(o!==void 0&&o.version>a)throw new H(`extensions`,`conflict`,`Stored ${t} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=er(n,t).map(e=>({collection:e.collection,key:e.key,value:_l(e.valueJson)}));for(let n=o.version;n<a;n+=1){let i=r.state.migrations[n];if(i===void 0)throw new H(`extensions`,`state_reset_required`,`State reset required for ${t}: stored version ${String(o.version)}, declared version ${String(a)}. An operator must authorize the reset; stored records have not been changed.`);try{e=e.flatMap(e=>i(e))}catch(e){throw new hl(`Failed ${t} state migration from ${String(n)}`,{cause:e})}}Fe(n,t);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new hl(`Migrated ${t} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new hl(`Migrated ${t} ${i.collection} record is invalid`);ii(n,t,i.collection,i.key,a.success,JSON.stringify(i.value))}}Mr(n,t,a,i)}function pe(e,n,r=!1){let i=ue(e);return A(function*(){let a=yield*ai(n);e.scope=a;let o=yield*M(()=>e.admitted.definition.activate(i)).pipe(t(mr,a),O);if(rt(o)){e.hooks=o.value;return}if(yield*vi(a,o),r)return yield*E(new H(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${It(o.cause)}`));yield*C(e,bl(`activation`,o.cause),o.cause,`own-transaction`)})}let j=e=>[...i.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function he(e){return Object.freeze({id:e.admitted.id,version:e.admitted.manifest.version,revision:e.admitted.revision,status:e.status,reason:e.reason,stoppedAt:e.stoppedAt})}function _e(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 ye(e,n,r){return O(r.pipe(t(xa,m(e.admitted.id)))).pipe(B(t=>rt(t)?F(P(t.value)):C(e,bl(n,t.cause),t.cause,`own-transaction`).pipe(I(S()))))}let be=(e,t,n)=>xn(n)?C(e,bl(t,n.cause),n.cause,`own-transaction`):L;function xe(e){return z({try:()=>{n.transactionSync(()=>{fe(e);for(let[t,r]of Object.entries(e.admitted.documents))zn(n,{extensionId:e.admitted.id,name:t,initialJson:ns(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(D(()=>k(()=>{delete e.stateResetRequired})),I(!0),oe(t=>t instanceof H?t.cause===`state_reset_required`?(e.stateResetRequired=t,C(e,gl(t.message),Ht(t),`own-transaction`).pipe(I(!1))):E(t):(t instanceof hl&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&s.add(e.admitted.id),C(e,gl(t instanceof Error?`migration: ${t.message}`:`migration failed`),Wr(t),`own-transaction`).pipe(I(!1)))))}return A(function*(){let r=yield*Nr();function l(t,i){return A(function*(){let a=Vi(n,t.id),o=a?.status===`stopped`&&a.revision===t.revision,s={admitted:t,hooks:void 0,status:o?`stopped`:`running`,reason:o?a.reason:null,stoppedAt:o?a.stoppedAt:null};return yield*z({try:()=>{t.grants.has(`settled`)&&n.transactionSync(()=>{q(n,t.id)===void 0&&Gn(n,t.id,q(n,`core`)??0)})},catch:()=>new H(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*xe(s))||o?i?yield*E(new H(`extensions`,`rejected`,`Extension ${t.id} cannot start: ${s.reason??`stopped`}`)):s:(yield*z({try:()=>{n.transactionSync(()=>{Dr(n,t.id,{status:`running`,reason:null,stoppedAt:null,revision:t.revision}),_i(n,e.watchdog,t.id),le(t.id)})},catch:()=>new H(`store`,`unavailable`,`Extension status is unavailable`)}),yield*pe(s,r,i),s)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(a(()=>vi(r,ze)));i.set(t.id,e)}yield*z({try:()=>{n.transactionSync(()=>{let t=kn(n,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of t)le(e)})},catch:()=>new H(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:t=>A(function*(){let r=t.filter(e=>{let t=i.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(r.length>0)return yield*E(new H(`extensions`,`rejected`,`Extensions ${r.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,c=M(()=>Ae([...o.values()].reverse(),e=>O(e.scope===void 0?L:vi(e.scope,ze)),{concurrency:1}).pipe(D(()=>k(()=>{for(let e of t)i.has(e.id)||s.delete(e.id)})),B(Ye)));yield*A(function*(){for(let e of t)i.has(e.id)||o.set(e.id,yield*l(e,!0))}).pipe(a(()=>c));let u=new Set(t.map(({id:e})=>e)),d=!1;return{discard:M(()=>d?L:(d=!0,c)),apply:A(function*(){if(d)return yield*E(new H(`extensions`,`rejected`,`Roster transition already settled`));yield*z({try:()=>{n.transactionSync(()=>{for(let[t,r]of i)u.has(r.admitted.id)||vr(n,e.watchdog,t);let r=kn(n,t.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of r)le(e)})},catch:()=>new H(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of i)u.has(t.admitted.id)||(t.scope!==void 0&&(yield*vi(t.scope,ze)),i.delete(e),s.delete(t.admitted.id));for(let[e,t]of o)i.set(e,t);d=!0})}}),runParticipants:()=>[...i.values()].filter(_e).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...s],modulesForRun:(e,t)=>Ae(j(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?F(S()):ye(n,`moduleForRun`,M(()=>r(e))).pipe(o(De))}).pipe(o(e=>e.flatMap(me))),filesForRun:(e,t)=>A(function*(){let n=j(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*C(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*E(new H(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*ye(n,`filesForRun`,M(()=>r(e)));return ne(i)?yield*E(new H(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...Ce(i.value,()=>[])])}),promptSections:(e,n)=>A(function*(){let r=[],i=0;for(let a of j(`prompt`)){if(!n.has(a.admitted.id))continue;let o=a.hooks?.prompt;if(o===void 0)return yield*C(a,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*E(new H(`extensions`,`rejected`,`Extension prompt is unavailable`));let s=yield*O(si(()=>o(e)).pipe(t(xa,m(a.admitted.id))));if(xn(s))return yield*C(a,bl(`prompt`,s.cause),s.cause,`own-transaction`),yield*E(new H(`extensions`,`rejected`,`Extension prompt failed`));let c=ml(s.value),l=c._tag===`Success`?c.success:[];if(i+=l.reduce((e,t)=>e+pl.encode(t.text).byteLength,0),c._tag===`Failure`||new Set(l.map(({name:e})=>e)).size!==l.length||i>65536)return yield*C(a,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*E(new H(`extensions`,`rejected`,`Extension prompt is invalid`));r.push(...[...l].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${a.admitted.id}.${e.name}`,text:e.text})))}return r}),compactionHandoff:e=>j(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>j(`settled`).map(e=>({id:e.admitted.id,cursor:q(n,e.admitted.id)??0})),deliverSettled:(e,t)=>Ae(j(`settled`),r=>M(()=>{let i=q(n,r.admitted.id)??0;if(t<=i)return L;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return se(r,(o===void 0||a.length===0?L:o(a)).pipe(b(k(()=>{Gn(n,r.admitted.id,t)}))),`reconcile`).pipe(B(e=>be(r,`onSettled`,e)))}),{discard:!0}),executeTimer:t=>A(function*(){let r=ht(V({extensionId:mn,key:mn}))(t.payload),a=i.get(r.extensionId);if(a?.status!==`running`||!a.admitted.grants.has(`timers`)||Sr(n,r.extensionId,r.key)!==t.jobId)return;let s=a.hooks?.onTimer,c=yield*ce(a,{prepare:(s===void 0?F(L):s({key:r.key,dueAt:t.notBefore??0,firedAt:Date.now()})).pipe(o(i=>M(()=>Sr(n,r.extensionId,r.key)===t.jobId?(li(n,e.watchdog,r.extensionId,r.key),i):L)))},`reconcile`);yield*be(a,`onTimer`,c)}),project:e=>{let t={};for(let n of i.values()){let r=n.admitted.grants.has(`projection`),i=n.admitted.grants.has(`commands`)?n.admitted.definition.catalog:void 0;if(!r&&i===void 0)continue;let a=n.admitted.revision,o=n.admitted.definition.contract.projection,s=n.hooks?.project;if(n.status===`running`&&n.hooks!==void 0){let l=!r||s===void 0||o===null?P(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=Ti(()=>s(e),void 0);if(we(r)){let e=Tn(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=K(Pe)(e.success);if(a._tag===`Failure`)throw Error(`Extension projection is not JSON`);t=a.success;let s=n.hooks.projectCatalog;i!==void 0&&s!==void 0&&(i=ht(Pe)(Ti(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?P(t):(w(n,gl(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),S())})();if(we(l)){t[n.admitted.id]=Object.freeze(i===void 0?{status:`running`,revision:a,value:l.value}:{status:`running`,revision:a,value:l.value,catalog:i});continue}}t[n.admitted.id]=Object.freeze({status:`stopped`,revision:a,reason:n.reason??`Extension did not activate`})}return Object.freeze(t)},call:(e,t,n,r,a)=>A(function*(){let o=i.get(t);if(o?.admitted.grants.has(`commands`)!==!0)return yield*E(new H(`extensions`,`unavailable`,`Extension is unavailable`));if(o.status!==`running`||o.hooks===void 0)return yield*E(o.stateResetRequired??new H(`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 H(`contract`,`invalid`,`Extension command is unknown`));let l=e.scope===`session`?yield*z({try:()=>J(e.sessionId),catch:()=>new H(`contract`,`invalid`,`Session id is invalid`)}):null,u=o.hooks.commands.get(n);if(u===void 0)return K(c.input,{onExcessProperty:`error`})(r)._tag===`Failure`?yield*E(new H(`contract`,`invalid`,`Extension command input is invalid`)):(yield*C(o,`command ${n} has no handler`,void 0,`own-transaction`),yield*E(new H(`extensions`,`unavailable`,`Extension is stopped`)));let d=u(a===void 0?{sessionId:l,input:r}:{sessionId:l,input:r,caller:a});if(d._tag===`Failure`)return yield*E(new H(`contract`,`invalid`,`Extension command input is invalid`));let f=yield*ce(o,{prepare:d.success},`request`);if(rt(f))return f.value;let p=nn(f.cause);if(we(p)&&!xl(f.cause))return yield*E(Cl(p.value));let m=bl(`command ${n}`,f.cause);return yield*C(o,m,f.cause,`own-transaction`),yield*E(new H(`extensions`,`unavailable`,`Extension ${t} is stopped: ${m}`))}),list:()=>[...i.values()].map(he),resume:t=>A(function*(){let a=i.get(t);return a===void 0?yield*E(new H(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*z({try:()=>{n.transactionSync(()=>{Dr(n,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),_i(n,e.watchdog,a.admitted.id),le(a.admitted.id)})},catch:()=>new H(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*xe(a))&&(yield*pe(a,r)),yield*e.requestWake),he(a))}),close:vi(r,ze)};return Object.freeze(u)})}var Tl=64;function Q(e){return new H(`runtime`,`rejected`,e)}function El(e,t,n){return A(function*(){let r=yield*Dl(t),i=t.outcome===`cancelled`?``:yield*at(e,r.work),a=yield*Nt(e,r.work,t.outcome),o=t.outcome===`completed`||t.outcome===`cancelled`?void 0:yield*yt(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 Dl(e){return z({try:()=>St(e),catch:()=>Q(`Agent work payload is invalid`)})}function Ol(e,t){return e.fanOut(t).pipe(p(()=>Q(`Agent reply fan-out is unavailable`)))}function kl(e,t,n){return t===void 0?L:A(function*(){let r=yield*Dl(n);(r.mail?.replyTo.length??0)!==0&&(yield*Ol(t,yield*El(e,n,z({try:()=>Qe(e,r.work.sessionId,r.work.commandFactId),catch:()=>Q(`Session attention is unavailable`)}))))})}function Al(e,t,n,r){return n===void 0?L:A(function*(){let i=yield*Dl(r),a=i.mail;if(a!==void 0&&a.replyTo.length>0||(yield*t.readQueueHead(r.queue).pipe(p(()=>Q(`Session queue head is unavailable`)))).state!==`idle`)return;let o=yield*z({try:()=>Re(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;if(s!==void 0&&!(s.kind===`agent`&&o.replyTo.some(({agentId:e})=>e===s.agentId)))return;let c=yield*El(e,r,z({try:()=>nt(e,i.work.sessionId,o.replyTo),catch:()=>Q(`Session attention is unavailable`)})),l=r.outcome===`cancelled`?``:yield*ln(e,i.work);yield*Ol(n,{...c,content:l,delegator:o})})}function jl(e,t,n,r){return Ae(r,(i,a)=>A(function*(){!r.slice(a+1).some(({job:e})=>e.queue===i.job.queue)&&!(yield*Pl(e,i.job))&&(yield*Al(e,t,n,i.job)),yield*z({try:()=>{Gn(e,cl,i.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function Ml(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?L:A(function*(){let r=yield*z({try:()=>St(t),catch:()=>Q(`Agent work payload is invalid`)});yield*mt(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function Nl(e,t,n){return A(function*(){let r=yield*z({try:()=>St(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*wn(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(tn({work:{...e,recovery:Xc},delivery:e.delivery}))}})})}function Pl(e,t){return A(function*(){let n=yield*z({try:()=>St(t),catch:()=>Q(`Agent work payload is invalid`)}),r=yield*z({try:()=>Xe(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return r&&(yield*i(`shiitake_settlement_session_refused`).pipe(N({workId:t.jobId}))),r})}function Fl(e,t){let n=St(t.job),r=Xe(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:Ie(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):en(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:ht(Ir)(r.origin.extensionId),correlation:r.origin.correlation})})}function Il(e,t,n,r){return Ae(r,r=>A(function*(){Dt(e,r.job.queue),(yield*Pl(e,r.job))||(yield*Ml(e,r.job),yield*Nl(e,t,r.job),yield*kl(e,n,r.job)),yield*z({try:()=>{Gn(e,sl,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function Ll(e){return A(function*(){let t=yield*e.watchdog.tick();if(t.status===`stopped`)return;if(t.status===`busy`)return yield*E(Q(`Runtime reconciliation is already active`));let n=yield*z({try:()=>q(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),r=yield*z({try:()=>q(e.store,`core-report`)??n,catch:()=>Q(`Settled cursor is unavailable`)}),i=e.extensions.settledConsumers(),a=Math.min(n,r,...i.map(({cursor:e})=>e)),o=yield*e.watchdog.readSettled(Tl,a,`default`),s=yield*O(Il(e.store,e.watchdog,e.mailRoom,o.filter(({sequence:e})=>e>n))),c=yield*z({try:()=>q(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),l=yield*z({try:()=>o.filter(({sequence:e})=>e<=c).map(t=>Fl(e.store,t)),catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(l,c);let u=yield*O(jl(e.store,e.watchdog,e.mailRoom,o.filter(({sequence:e})=>e>r&&e<=c)));if(o.length===Tl&&(yield*e.requestWake),xn(s))return yield*ee(s.cause);if(xn(u))return yield*ee(u.cause)}).pipe(p(e=>e instanceof H?e:Q(`Runtime reconciliation failed`)))}function $(e){return new H(`runtime`,`rejected`,e)}function Rl(e,t,n,r){return A(function*(){if(e.hostJobs?.lane==="default"||e.hostJobs?.lane===`extension_timer`)return yield*E($(`Host lane conflicts with Agent work`));let i=`open`,o,s,l=Ci(!1),u=e=>k(()=>{i===`open`&&(o??=e)}),f=M(()=>i===`open`?(i=`closing`,s=o,l.open):L).pipe(m),_={},v={current:void 0},y=e,ne,x=!1,re=M(()=>_.requestWake??E($(`Runtime host is unavailable`))),ae={current:void 0},se=new Set,S=new Map,ce=new Map,C={owner:e.store,isAlive:()=>F(!1),executor:{replaySafe:e=>e.lane===Di,retryPolicy:t=>t.lane===e.hostJobs?.lane?ae.current?.retryPolicy?.(t)??F(void 0):F(void 0),isDrained:e=>k(()=>{if(e.lane===`extension_timer`)return!0;let t=ce.get(e.jobId);return ce.delete(e.jobId),t?.released===!0}),execute:(n,r)=>n.lane===`extension_timer`?M(()=>v.current?.executeTimer(n)??E($(`Extension runtime is unavailable`))).pipe(I({kind:`completed`}),p(e=>new va(`execution_failed`,e))):he(k(()=>{let t=n.lane===e.hostJobs?.lane?{kind:`host`,lane:n.lane,jobId:n.jobId}:{kind:`session`,sessionId:n.queue,commandId:n.jobId};S.set(t.kind===`host`?`host`:`serial`,t);let r={isStopping:()=>i!==`open`,released:!1};return t.kind===`session`&&(se.add(n.queue),ce.set(n.jobId,r)),Si(e.store),r}),i=>n.lane===e.hostJobs?.lane?ae.current?.execute(n,r)??E(new va(`execution_failed`)):A(function*(){let r=ne;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;y={...n,...r.configuration},ne=void 0}return yield*el(y,t,n,v.current,i)}).pipe(te(e=>d(`configuration_apply_failed`,e)),p(()=>new va(`execution_failed`))),()=>k(()=>{n.lane!==e.hostJobs?.lane&&se.delete(n.queue),S.delete(n.lane===e.hostJobs?.lane?`host`:`serial`),Si(e.store)})).pipe(c(e=>k(()=>{(i===`open`||rt(e)||!ot(e.cause))&&ce.delete(n.jobId)})))},wake:{recompute:()=>re.pipe(p(()=>new va(`wake_unavailable`)))},project:t=>{Kr(e.store,t,Date.now())}},w=L,T=yield*(e.hostJobs===void 0?wa(C):wa({...C,concurrentLane:e.hostJobs.lane}).pipe(D(t=>k(()=>{ae.current=e.hostJobs?.open(t),w=t.tickConcurrent().pipe(ie,p(()=>$(`Host delivery is unavailable`)))})))).pipe(p(()=>$(`Watchdog is unavailable`))),ue=()=>({core:t,extensions:[...v.current?.runParticipants()??[]]});yield*z({try:()=>Rc(e.compaction),catch:e=>e instanceof H?e:$(`Compaction settings are unavailable`)});let fe=yield*z({try:()=>kt(e.storagePressure),catch:e=>e instanceof H?e:$(`Storage budget is unavailable`)}),pe=()=>{e.admission?.assertOpen(),fe.admitNew()},me=()=>{let t;do{let n=Ut(e.store,t);for(let e of n.sessions){if(e.state===`unavailable`)throw new H(`store`,`unavailable`,`Session ${e.sessionId} is unreadable`);let t=T.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=Es(e.store);return n===void 0?void 0:{kind:`delegation`,...n}},ge=ol({owner:e.store,admitNew:pe,hostMeta:e.meta,contract:ue,enqueue:(e,t)=>{let n={work:{...e,recovery:Xc},delivery:e.delivery};T.transactional.enqueueAcceptedJob(tn(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>T.transactional.readQueueHead(e),commit:e=>M(()=>_.commit===void 0?E($(`Runtime host is unavailable`)):_.commit(e)),requestWake:re});yield*z({try:()=>{Rr(e.store),q(e.store,`core`)===void 0&&e.store.transactionSync(()=>{Gn(e.store,sl,0)}),q(e.store,`core-report`)===void 0&&e.store.transactionSync(()=>{Gn(e.store,cl,q(e.store,`core`)??0)})},catch:()=>new H(`store`,`unavailable`,`Extension store is unavailable`)});let N=yield*wl({owner:e.store,watchdog:T.transactional,readQueueHead:e=>T.transactional.readQueueHead(e),door:ge,admitted:n,requestWake:re,recipientStatus:e.recipientStatus,recipientParent:e.recipientParent});v.current=N;let _e=Ll({watchdog:T,store:e.store,extensions:N,requestWake:re,mailRoom:r}).pipe(te(u)),ve=A(function*(){let t=Date.now(),n=yield*T.wakeState(t),r=yield*z({try:()=>[q(e.store,`core`)??0,q(e.store,`core-report`)??0,...N.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*T.readSettled(1,Math.min(...r),`default`)).length>0;return{pending:n.pending||i,nextWakeAt:n.nextWakeAt}}),ye=yield*e.runtime.bind({reconcile:_e,reconcileHost:e.hostJobs===void 0?void 0:w.pipe(te(u)),pendingWork:ve.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(a(()=>N.close.pipe(g))),P=M(()=>i===`open`?le(ye.requestWake.pipe(oe(u)),l.await):L);return _.requestWake=P,_.commit=ye.commit,yield*ye.requestWake.pipe(a(()=>de([ye.close,N.close]).pipe(g))),Object.freeze({prepareConfiguration:e=>A(function*(){if(i!==`open`||x||ne!==void 0)return yield*E($(`A configuration change is already pending, or the Agent is closing`));x=!0;let t=yield*vs(e.extensions).pipe(B(e=>N.stage(e)),a(()=>k(()=>{x=!1}))),n=!1;return{commit:z({try:()=>{if(n||i!==`open`)throw $(`Configuration preparation is no longer available`);ne={configuration:e,apply:t.apply},n=!0,x=!1},catch:e=>e instanceof H?e:$(`Configuration commit failed`)}),discard:M(()=>n?L:(n=!0,x=!1,t.discard))}}),activeSessions:k(()=>[...se]),busySync:me,runningWork:t=>T.read(t).pipe(B(t=>{let n=t.status===`found`?S.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`):void 0;return n===void 0?F(null):n.kind===`host`?F({phase:`thinking`}):z({try:()=>({phase:So(e.store,n.sessionId,T.transactional.readQueueHead(n.sessionId))}),catch:e=>new H(`runtime`,`rejected`,`Running phase is unavailable`,void 0,e)})}),p(e=>new H(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:N,commit:ye.commit,assertOpen:M(()=>i===`open`?L:E(new H(`runtime`,`closed`,`Shiitake is closed`))),beginClose:f,door:ge,createSessionWithinTransaction:t=>pn(e.store,t,pe),recordCreatedSessionDelegatorWithinTransaction:(t,n)=>{Ur(e.store,t,n)},stageSessionGrantsWithinTransaction:(t,n)=>{Jt(e.store,t,n)},storage:{admitNew:pe},recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>T.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(T.transactional.readQueueHead(e).state!==`idle`)throw new H(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof H?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>T.cancel({jobId:e,cancellationId:t}).pipe(B(e=>e.status===`recorded`||e.status===`replayed`||e.status===`decided`?L:E($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>T.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>T.transactional.readQueueHead(e),requestWake:P,close:f.pipe(b(h(de([O(T.close.pipe(p(()=>$(`Runtime execution did not drain`)))),O(ye.close)],{concurrency:`unbounded`}).pipe(B(e=>{let t=e.find(xn);return t===void 0?L:ee(t.cause)})),{onFailure:e=>N.close.pipe(b(s===void 0?ee(e):E(s))),onSuccess:()=>N.close.pipe(b(s===void 0?L:E(s)))})),j(k(()=>{i=`closed`})))})})}var zl=e({openRuntimeCore:()=>Bl});function Bl(e,t){return A(function*(){let n=yield*vs(e.extensions),r=yield*ys([]);yield*Yt(e.store);let i=yield*Rl(e,r,n,t),a=Qo(e,i,yield*C()),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:xo(a.close,i.close)}),s=Object.freeze({...o,prepareConfiguration:i.prepareConfiguration,grants:a.grants,withMeta:e=>Object.freeze({...o,session:a.withMeta(e).session})});return Object.freeze({agent:s,readSettlement:(t,n)=>i.assertOpen.pipe(b(qr(e.store,t,n))),activeSessions:i.activeSessions,busySync:i.busySync,acceptMail:(e,n,r,a,o)=>es(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);_e(t.postMail(e))}),o)})})}export{vo as n,Bl as openRuntimeCore,fo as r,zl as t};
|