@fungi.computer/grove 0.4.0 → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets/Effect-TOXKEWei.js +76 -0
- package/dist/assets/{anthropic-messages-BC32dQ9I.js → anthropic-messages-BTv37DKo.js} +3 -3
- package/dist/assets/{azure-openai-responses-CxbiKRMB.js → azure-openai-responses-CLI5CTea.js} +1 -1
- package/dist/assets/{base-face-BEjKYyJe.js → base-face-CD4oLBv-.js} +1 -1
- package/dist/assets/burger-BrMTWnA6.js +1 -0
- package/dist/assets/cat-Ce0yvAsw.js +1 -0
- package/dist/assets/compat-BQZx9Jx3.js +2 -0
- package/dist/assets/{document-CI1e8oXD.js → document-aOA3zT2S.js} +1 -1
- package/dist/assets/extension-hook-UDdYbDsl.js +819 -0
- package/dist/assets/extensions-DF9U5f_Z.js +1 -0
- package/dist/assets/{google-generative-ai-0DBJk_8o.js → google-generative-ai-_8qHW2IX.js} +1 -1
- package/dist/assets/{google-shared-BL1Pe-wK.js → google-shared-BjptlrJn.js} +1 -1
- package/dist/assets/{google-vertex-CPgYcjfH.js → google-vertex-C6JPlmUK.js} +1 -1
- package/dist/assets/index-DM8ziIjn.js +174 -0
- package/dist/assets/index-DRqG5MfY.css +1 -0
- package/dist/assets/{mistral-conversations-C3vHwl30.js → mistral-conversations-C_XYmgUS.js} +1 -1
- package/dist/assets/{mushroom-D2oxknl9.js → mushroom-BTxbn3Sf.js} +1 -1
- package/dist/assets/{node.browser-C4Y5T0IC.js → node.browser-Bc9i4viB.js} +1 -1
- package/dist/assets/{openai-codex-responses-BJGSPctB.js → openai-codex-responses-C0Thlbgz.js} +1 -1
- package/dist/assets/{openai-completions-2akGjxPU.js → openai-completions-CJJn6-l3.js} +1 -1
- package/dist/assets/{openai-responses-D6H3TRtV.js → openai-responses-BuHYr0Ip.js} +1 -1
- package/dist/assets/{openai-responses-shared-DZesysou.js → openai-responses-shared-px8hA25N.js} +1 -1
- package/dist/assets/parakeet-conversation-gakMmXhW.js +4 -0
- package/dist/assets/renderer-69rvqVnj.js +1 -0
- package/dist/assets/runtime-core-CHfIZEOV.js +40 -0
- package/dist/assets/{transform-messages-CgFTI6NF.js → transform-messages-zEOZxc_F.js} +1 -1
- package/dist/index.html +6 -6
- package/package.json +20 -10
- package/dist/assets/Effect-BY0T-p9d.js +0 -76
- package/dist/assets/Effect-Bibd7o64.js +0 -76
- package/dist/assets/anthropic-messages-BrTyy87S.js +0 -19
- package/dist/assets/azure-openai-responses-Cxq6500u.js +0 -1
- package/dist/assets/base-face-Dc6wvM5e.js +0 -1
- package/dist/assets/burger-DCM1Ryjl.js +0 -1
- package/dist/assets/burger-Zw2lKYST.js +0 -1
- package/dist/assets/cat-D2ceQOG1.js +0 -1
- package/dist/assets/cat-Dg3HQp8e.js +0 -1
- package/dist/assets/compat-CNGE3olg.js +0 -2
- package/dist/assets/compat-DgqxVOn_.js +0 -2
- package/dist/assets/document-DjWTbvB5.js +0 -1
- package/dist/assets/extension-hook-C8RQgls9.js +0 -741
- package/dist/assets/extension-hook-CBuX_bUG.js +0 -721
- package/dist/assets/extensions-DEfvRHbZ.js +0 -1
- package/dist/assets/extensions-DYjwCmO5.js +0 -1
- package/dist/assets/google-generative-ai-C-fVQ8eG.js +0 -1
- package/dist/assets/google-shared-CRsSlHta.js +0 -8
- package/dist/assets/google-vertex-DFCQBu0N.js +0 -1
- package/dist/assets/index-26gTYfVj.js +0 -171
- package/dist/assets/index-DIRtUgKp.css +0 -1
- package/dist/assets/index-HgPChePI.js +0 -171
- package/dist/assets/index-u-fIUxtz.css +0 -1
- package/dist/assets/mistral-conversations-Dx6vubnB.js +0 -4
- package/dist/assets/mushroom-DcQ2lek6.js +0 -1
- package/dist/assets/node.browser-DF9afU1k.js +0 -1
- package/dist/assets/openai-codex-responses-CK2Z6kMm.js +0 -9
- package/dist/assets/openai-completions-C35dP-q-.js +0 -5
- package/dist/assets/openai-responses-DPFd_3HO.js +0 -1
- package/dist/assets/openai-responses-shared-DaKV5GAS.js +0 -10
- package/dist/assets/parakeet-conversation-DKtvvfd-.js +0 -4
- package/dist/assets/parakeet-conversation-Di3EPCdu.js +0 -4
- package/dist/assets/renderer-BHU7Ec4o.js +0 -1
- package/dist/assets/renderer-cVoUiOqk.js +0 -1
- package/dist/assets/runtime-core-COw0PWwZ.js +0 -1
- package/dist/assets/runtime-core-DOL1texL.js +0 -1
- package/dist/assets/transform-messages-utWG7TCG.js +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as e,t}from"./rolldown-runtime-hePW80VL.js";import{j as n,ma as r,pt as i,r as a,t as o}from"./Effect-BY0T-p9d.js";import{i as s,t as c}from"./document-DjWTbvB5.js";import{A as l,B as u,C as d,D as f,E as p,F as m,G as h,H as g,I as _,L as v,M as y,N as ee,O as b,P as x,R as S,S as C,T as te,U as w,V as T,W as ne,b as re,j as E,k as ie,w as ae,x as D,y as O,z as oe}from"./index-HgPChePI.js";var k=(e,t)=>{if(u(t,`<`)){let n=t[1]===`<`,r=e._tail,i=r?r._offset+r._delay:0;return n?i:i+r.duration}},A=(e,t)=>{let n=e.iterationDuration;if(n===1e-11&&(n=0),v(t))return n;if(x(+t))return+t;let r=t,i=e?e.labels:null,a=!ee(i),o=k(e,r),s=!v(o),c=ne.exec(r);if(c){let e=c[0],t=r.split(e),l=a&&t[0]?i[t[0]]:n,u=s?o:a?l:n,d=+t[1];return f(u,d,e[0])}return s?o:a?v(i[r])?n:i[r]:n};function j(e){return l((e.iterationDuration+e._loopDelay)*e.iterationCount-e._loopDelay)||1e-11}function M(e,t,n,r,i,a){let o=x(e.duration)&&e.duration<=1e-11?n-w:n;t.composition&&p(t,o,1,1,h.AUTO);let s=r?new O(r,e,t,o,!1,i,a):new C(e,t,o);return t.composition&&s.init(!0),ie(t,s),E(t,e=>{let n=e._offset+e._delay+e.duration;n>t.iterationDuration&&(t.iterationDuration=n)}),t.duration=j(t),t}var N=0,se=class extends C{constructor(e={}){super(e,null,0),++N,this.id=v(e.id)?N:e.id,this.duration=0,this.labels={};let t=e.defaults,n=T.defaults;this.defaults=t?S(t,n):n,this.composition=b(e.composition,!0),this.onRender=e.onRender||n.onRender;let r=b(e.playbackEase,n.playbackEase);this._ease=r?re(r):null,this.iterationDuration=0}add(e,t,n){let r=m(t),i=m(e);if(r||i){if(this._hasChildren=!0,r){let r=t,i=T.editor&&T.editor.addTimelineChild,a=n&&n.type===`Stagger`&&T.editor,o=y(n)?n:null;if(o||a){let t=D(e),a=this.duration,s=this.iterationDuration,c=r.id,l=0,u=t.length,d=i?i(e,r,this.id,n,u):null,f=o||T.editor.resolveStagger(n.defaultValue);t.forEach(e=>{let n={...d||r};this.duration=a,this.iterationDuration=s,v(c)||(n.id=c+`-`+l);let i=A(this,f(e,l,t,null,this));M(n,this,i,e,l,t),l++})}else{let t=i?i(e,r,this.id,n):r,a=n&&n.type?n.defaultValue:n;M(t,this,A(this,a),e)}}else M(e,this,A(this,t));return this.composition&&this.init(!0),this}}sync(e,t){if(v(e)||e&&v(e.pause))return this;e.pause();let n=+(e.effect?e.effect.getTiming().duration:e.duration);!v(e)&&!v(e.persist)&&(e.persist=!0);let r=T.editor,i=r&&r.addTimelineChild;r&&r.addTimelineSync&&(t=r.addTimelineSync(e,t,this.id),r.addTimelineChild=null);let a=this.add(e,{currentTime:[0,n],duration:n,delay:0,ease:`linear`,playbackEase:`linear`},t);return r&&(r.addTimelineChild=i),a}set(e,t,n){return v(t)?this:(t.duration=w,t.composition=g.replace,this.add(e,t,n))}call(e,t){return v(e)||e&&!y(e)?this:(T.editor&&T.editor.addTimelineCall&&(t=T.editor.addTimelineCall(e,t,this.id)),this.add({duration:0,delay:0,onComplete:()=>e(this)},t))}label(e,t){return v(e)||e&&!_(e)?this:(T.editor&&T.editor.addTimelineLabel&&(t=T.editor.addTimelineLabel(e,t,this.id)),this.labels[e]=A(this,t),this)}remove(e,t){return ae(D(e),this,t),this}stretch(e){let t=this.duration;if(t===oe(e))return this;let n=e/t,r=this.labels;E(this,e=>e.stretch(e.duration*n));for(let e in r)r[e]*=n;return super.stretch(e)}refresh(){return E(this,e=>{e.refresh&&e.refresh()}),this}revert(){return super.revert(),E(this,e=>e.revert,!0),te(this)}then(e){return super.then(e)}},ce=e=>T.editor?T.editor.addTimeline(e):new se(e).init(),P=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog=n()})(e,function(){var e={};e.TAU=Math.PI*2,e.extend=function(e,t){for(var n in t)e[n]=t[n];return e},e.lerp=function(e,t,n){return(t-e)*n+e},e.modulo=function(e,t){return(e%t+t)%t};var t={2:function(e){return e*e},3:function(e){return e*e*e},4:function(e){return e*e*e*e},5:function(e){return e*e*e*e*e}};return e.easeInOut=function(e,n){if(n==1)return e;e=Math.max(0,Math.min(1,e));var r=e<.5,i=r?e:1-e;i/=.5;var a=(t[n]||t[2])(i);return a/=2,r?a:1-a},e})})),F=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.CanvasRenderer=n()})(e,function(){var e={isCanvas:!0};return e.begin=function(e){e.beginPath()},e.move=function(e,t,n){e.moveTo(n.x,n.y)},e.line=function(e,t,n){e.lineTo(n.x,n.y)},e.bezier=function(e,t,n,r,i){e.bezierCurveTo(n.x,n.y,r.x,r.y,i.x,i.y)},e.closePath=function(e){e.closePath()},e.setPath=function(){},e.renderPath=function(t,n,r,i){this.begin(t,n),r.forEach(function(r){r.render(t,n,e)}),i&&this.closePath(t,n)},e.stroke=function(e,t,n,r,i){n&&(e.strokeStyle=r,e.lineWidth=i,e.stroke())},e.fill=function(e,t,n,r){n&&(e.fillStyle=r,e.fill())},e.end=function(){},e})})),I=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.SvgRenderer=n()})(e,function(){var e={isSvg:!0},t=e.round=function(e){return Math.round(e*1e3)/1e3};function n(e){return t(e.x)+`,`+t(e.y)+` `}return e.begin=function(){},e.move=function(e,t,r){return`M`+n(r)},e.line=function(e,t,r){return`L`+n(r)},e.bezier=function(e,t,r,i,a){return`C`+n(r)+n(i)+n(a)},e.closePath=function(){return`Z`},e.setPath=function(e,t,n){t.setAttribute(`d`,n)},e.renderPath=function(t,n,r,i){var a=``;r.forEach(function(r){a+=r.render(t,n,e)}),i&&(a+=this.closePath(t,n)),this.setPath(t,n,a)},e.stroke=function(e,t,n,r,i){n&&(t.setAttribute(`stroke`,r),t.setAttribute(`stroke-width`,i))},e.fill=function(e,t,n,r){var i=n?r:`none`;t.setAttribute(`fill`,i)},e.end=function(e,t){e.appendChild(t)},e})})),L=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P());else{var r=e.Zdog;r.Vector=n(r)}})(e,function(e){function t(e){this.set(e)}var n=e.TAU;t.prototype.set=function(e){return this.x=e&&e.x||0,this.y=e&&e.y||0,this.z=e&&e.z||0,this},t.prototype.write=function(e){return e?(this.x=e.x==null?this.x:e.x,this.y=e.y==null?this.y:e.y,this.z=e.z==null?this.z:e.z,this):this},t.prototype.rotate=function(e){if(e)return this.rotateZ(e.z),this.rotateY(e.y),this.rotateX(e.x),this},t.prototype.rotateZ=function(e){r(this,e,`x`,`y`)},t.prototype.rotateX=function(e){r(this,e,`y`,`z`)},t.prototype.rotateY=function(e){r(this,e,`x`,`z`)};function r(e,t,r,i){if(!(!t||t%n===0)){var a=Math.cos(t),o=Math.sin(t),s=e[r],c=e[i];e[r]=s*a-c*o,e[i]=c*a+s*o}}t.prototype.isSame=function(e){return e?this.x===e.x&&this.y===e.y&&this.z===e.z:!1},t.prototype.add=function(e){return e?(this.x+=e.x||0,this.y+=e.y||0,this.z+=e.z||0,this):this},t.prototype.subtract=function(e){return e?(this.x-=e.x||0,this.y-=e.y||0,this.z-=e.z||0,this):this},t.prototype.multiply=function(e){return e==null||(typeof e==`number`?(this.x*=e,this.y*=e,this.z*=e):(this.x*=e.x==null?1:e.x,this.y*=e.y==null?1:e.y,this.z*=e.z==null?1:e.z)),this},t.prototype.transform=function(e,t,n){return this.multiply(n),this.rotate(t),this.add(e),this},t.prototype.lerp=function(t,n){return this.x=e.lerp(this.x,t.x||0,n),this.y=e.lerp(this.y,t.y||0,n),this.z=e.lerp(this.z,t.z||0,n),this},t.prototype.magnitude=function(){return i(this.x*this.x+this.y*this.y+this.z*this.z)};function i(e){return Math.abs(e-1)<1e-8?1:Math.sqrt(e)}return t.prototype.magnitude2d=function(){return i(this.x*this.x+this.y*this.y)},t.prototype.copy=function(){return new t(this)},t})})),R=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),F(),I());else{var r=e.Zdog;r.Anchor=n(r,r.Vector,r.CanvasRenderer,r.SvgRenderer)}})(e,function(e,t,n,r){var i=e.TAU,a={x:1,y:1,z:1};function o(e){this.create(e||{})}o.prototype.create=function(n){this.children=[],e.extend(this,this.constructor.defaults),this.setOptions(n),this.translate=new t(n.translate),this.rotate=new t(n.rotate),this.scale=new t(a).multiply(this.scale),this.origin=new t,this.renderOrigin=new t,this.addTo&&this.addTo.addChild(this)},o.defaults={},o.optionKeys=Object.keys(o.defaults).concat([`rotate`,`translate`,`scale`,`addTo`]),o.prototype.setOptions=function(e){var t=this.constructor.optionKeys;for(var n in e)t.indexOf(n)!=-1&&(this[n]=e[n])},o.prototype.addChild=function(e){this.children.indexOf(e)==-1&&(e.remove(),e.addTo=this,this.children.push(e))},o.prototype.removeChild=function(e){var t=this.children.indexOf(e);t!=-1&&this.children.splice(t,1)},o.prototype.remove=function(){this.addTo&&this.addTo.removeChild(this)},o.prototype.update=function(){this.reset(),this.children.forEach(function(e){e.update()}),this.transform(this.translate,this.rotate,this.scale)},o.prototype.reset=function(){this.renderOrigin.set(this.origin)},o.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.children.forEach(function(r){r.transform(e,t,n)})},o.prototype.updateGraph=function(){this.update(),this.updateFlatGraph(),this.flatGraph.forEach(function(e){e.updateSortValue()}),this.flatGraph.sort(o.shapeSorter)},o.shapeSorter=function(e,t){return e.sortValue-t.sortValue},Object.defineProperty(o.prototype,"flatGraph",{get:function(){return this._flatGraph||this.updateFlatGraph(),this._flatGraph},set:function(e){this._flatGraph=e}}),o.prototype.updateFlatGraph=function(){this.flatGraph=this.getFlatGraph()},o.prototype.getFlatGraph=function(){var e=[this];return this.addChildFlatGraph(e)},o.prototype.addChildFlatGraph=function(e){return this.children.forEach(function(t){var n=t.getFlatGraph();Array.prototype.push.apply(e,n)}),e},o.prototype.updateSortValue=function(){this.sortValue=this.renderOrigin.z},o.prototype.render=function(){},o.prototype.renderGraphCanvas=function(e){if(!e)throw Error(`ctx is `+e+`. Canvas context required for render. Check .renderGraphCanvas( ctx ).`);this.flatGraph.forEach(function(t){t.render(e,n)})},o.prototype.renderGraphSvg=function(e){if(!e)throw Error(`svg is `+e+`. SVG required for render. Check .renderGraphSvg( svg ).`);this.flatGraph.forEach(function(t){t.render(e,r)})},o.prototype.copy=function(t){var n={};this.constructor.optionKeys.forEach(function(e){n[e]=this[e]},this),e.extend(n,t);var r=this.constructor;return new r(n)},o.prototype.copyGraph=function(e){var t=this.copy(e);return this.children.forEach(function(e){e.copyGraph({addTo:t})}),t},o.prototype.normalizeRotate=function(){this.rotate.x=e.modulo(this.rotate.x,i),this.rotate.y=e.modulo(this.rotate.y,i),this.rotate.z=e.modulo(this.rotate.z,i)};function s(t){return function(n){function r(e){this.create(e||{})}return r.prototype=Object.create(t.prototype),r.prototype.constructor=r,r.defaults=e.extend({},t.defaults),e.extend(r.defaults,n),r.optionKeys=t.optionKeys.slice(0),Object.keys(r.defaults).forEach(function(e){!r.optionKeys.indexOf(e)!=1&&r.optionKeys.push(e)}),r.subclass=s(r),r}}return o.subclass=s(o),o})})),z=t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n():e.Zdog.Dragger=n()})(e,function(){var e=typeof window<`u`,t=`mousedown`,n=`mousemove`,r=`mouseup`;e&&(window.PointerEvent?(t=`pointerdown`,n=`pointermove`,r=`pointerup`):`ontouchstart`in window&&(t=`touchstart`,n=`touchmove`,r=`touchend`));function i(){}function a(e){this.create(e||{})}return a.prototype.create=function(e){this.onDragStart=e.onDragStart||i,this.onDragMove=e.onDragMove||i,this.onDragEnd=e.onDragEnd||i,this.bindDrag(e.startElement)},a.prototype.bindDrag=function(e){e=this.getQueryElement(e),e&&(e.style.touchAction=`none`,e.addEventListener(t,this))},a.prototype.getQueryElement=function(e){return typeof e==`string`&&(e=document.querySelector(e)),e},a.prototype.handleEvent=function(e){var t=this[`on`+e.type];t&&t.call(this,e)},a.prototype.onmousedown=a.prototype.onpointerdown=function(e){this.dragStart(e,e)},a.prototype.ontouchstart=function(e){this.dragStart(e,e.changedTouches[0])},a.prototype.dragStart=function(t,i){t.preventDefault(),this.dragStartX=i.pageX,this.dragStartY=i.pageY,e&&(window.addEventListener(n,this),window.addEventListener(r,this)),this.onDragStart(i)},a.prototype.ontouchmove=function(e){this.dragMove(e,e.changedTouches[0])},a.prototype.onmousemove=a.prototype.onpointermove=function(e){this.dragMove(e,e)},a.prototype.dragMove=function(e,t){e.preventDefault();var n=t.pageX-this.dragStartX,r=t.pageY-this.dragStartY;this.onDragMove(t,n,r)},a.prototype.onmouseup=a.prototype.onpointerup=a.prototype.ontouchend=a.prototype.dragEnd=function(){window.removeEventListener(n,this),window.removeEventListener(r,this),this.onDragEnd()},a})})),le=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),z());else{var r=e.Zdog;r.Illustration=n(r,r.Anchor,r.Dragger)}})(e,function(e,t,n){function r(){}var i=e.TAU,a=t.subclass({element:void 0,centered:!0,zoom:1,dragRotate:!1,resize:!1,onPrerender:r,onDragStart:r,onDragMove:r,onDragEnd:r,onResize:r});e.extend(a.prototype,n.prototype),a.prototype.create=function(e){t.prototype.create.call(this,e),n.prototype.create.call(this,e),this.setElement(this.element),this.setDragRotate(this.dragRotate),this.setResize(this.resize)},a.prototype.setElement=function(e){if(e=this.getQueryElement(e),!e)throw Error(`Zdog.Illustration element required. Set to `+e);var t=e.nodeName.toLowerCase();t==`canvas`?this.setCanvas(e):t==`svg`&&this.setSvg(e)},a.prototype.setSize=function(e,t){e=Math.round(e),t=Math.round(t),this.isCanvas?this.setSizeCanvas(e,t):this.isSvg&&this.setSizeSvg(e,t)},a.prototype.setResize=function(e){this.resize=e,this.resizeListener||=this.onWindowResize.bind(this),e?(window.addEventListener(`resize`,this.resizeListener),this.onWindowResize()):window.removeEventListener(`resize`,this.resizeListener)},a.prototype.onWindowResize=function(){this.setMeasuredSize(),this.onResize(this.width,this.height)},a.prototype.setMeasuredSize=function(){var e,t;if(this.resize==`fullscreen`)e=window.innerWidth,t=window.innerHeight;else{var n=this.element.getBoundingClientRect();e=n.width,t=n.height}this.setSize(e,t)},a.prototype.renderGraph=function(e){this.isCanvas?this.renderGraphCanvas(e):this.isSvg&&this.renderGraphSvg(e)},a.prototype.updateRenderGraph=function(e){this.updateGraph(),this.renderGraph(e)},a.prototype.setCanvas=function(e){this.element=e,this.isCanvas=!0,this.ctx=this.element.getContext(`2d`),this.setSizeCanvas(e.width,e.height)},a.prototype.setSizeCanvas=function(e,t){this.width=e,this.height=t;var n=this.pixelRatio=window.devicePixelRatio||1;this.element.width=this.canvasWidth=e*n,this.element.height=this.canvasHeight=t*n,n>1&&!this.resize&&(this.element.style.width=e+`px`,this.element.style.height=t+`px`)},a.prototype.renderGraphCanvas=function(e){e||=this,this.prerenderCanvas(),t.prototype.renderGraphCanvas.call(e,this.ctx),this.postrenderCanvas()},a.prototype.prerenderCanvas=function(){var e=this.ctx;if(e.lineCap=`round`,e.lineJoin=`round`,e.clearRect(0,0,this.canvasWidth,this.canvasHeight),e.save(),this.centered){var t=this.width/2*this.pixelRatio,n=this.height/2*this.pixelRatio;e.translate(t,n)}var r=this.pixelRatio*this.zoom;e.scale(r,r),this.onPrerender(e)},a.prototype.postrenderCanvas=function(){this.ctx.restore()},a.prototype.setSvg=function(e){this.element=e,this.isSvg=!0,this.pixelRatio=1;var t=e.getAttribute(`width`),n=e.getAttribute(`height`);this.setSizeSvg(t,n)},a.prototype.setSizeSvg=function(e,t){this.width=e,this.height=t;var n=e/this.zoom,r=t/this.zoom,i=this.centered?-n/2:0,a=this.centered?-r/2:0;this.element.setAttribute(`viewBox`,i+` `+a+` `+n+` `+r),this.resize?(this.element.removeAttribute(`width`),this.element.removeAttribute(`height`)):(this.element.setAttribute(`width`,e),this.element.setAttribute(`height`,t))},a.prototype.renderGraphSvg=function(e){e||=this,o(this.element),this.onPrerender(this.element),t.prototype.renderGraphSvg.call(e,this.element)};function o(e){for(;e.firstChild;)e.removeChild(e.firstChild)}return a.prototype.setDragRotate=function(e){if(e)e===!0&&(e=this);else return;this.dragRotate=e,this.bindDrag(this.element)},a.prototype.dragStart=function(){this.dragStartRX=this.dragRotate.rotate.x,this.dragStartRY=this.dragRotate.rotate.y,n.prototype.dragStart.apply(this,arguments)},a.prototype.dragMove=function(e,t){var r=t.pageX-this.dragStartX,a=t.pageY-this.dragStartY,o=Math.min(this.width,this.height),s=r/o*i,c=a/o*i;this.dragRotate.rotate.x=this.dragStartRX-c,this.dragRotate.rotate.y=this.dragStartRY-s,n.prototype.dragMove.apply(this,arguments)},a})})),B=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(L());else{var r=e.Zdog;r.PathCommand=n(r.Vector)}})(e,function(e){function t(t,i,a){this.method=t,this.points=i.map(n),this.renderPoints=i.map(r),this.previousPoint=a,this.endRenderPoint=this.renderPoints[this.renderPoints.length-1],t==`arc`&&(this.controlPoints=[new e,new e])}function n(t){return t instanceof e?t:new e(t)}function r(t){return new e(t)}t.prototype.reset=function(){var e=this.points;this.renderPoints.forEach(function(t,n){var r=e[n];t.set(r)})},t.prototype.transform=function(e,t,n){this.renderPoints.forEach(function(r){r.transform(e,t,n)})},t.prototype.render=function(e,t,n){return this[this.method](e,t,n)},t.prototype.move=function(e,t,n){return n.move(e,t,this.renderPoints[0])},t.prototype.line=function(e,t,n){return n.line(e,t,this.renderPoints[0])},t.prototype.bezier=function(e,t,n){var r=this.renderPoints[0],i=this.renderPoints[1],a=this.renderPoints[2];return n.bezier(e,t,r,i,a)};var i=9/16;return t.prototype.arc=function(e,t,n){var r=this.previousPoint,a=this.renderPoints[0],o=this.renderPoints[1],s=this.controlPoints[0],c=this.controlPoints[1];return s.set(r).lerp(a,i),c.set(o).lerp(a,i),n.bezier(e,t,s,c,o)},t})})),V=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R());else{var r=e.Zdog;r.Shape=n(r,r.Vector,r.PathCommand,r.Anchor)}})(e,function(e,t,n,r){var i=r.subclass({stroke:1,fill:!1,color:`#333`,closed:!0,visible:!0,path:[{}],front:{z:1},backface:!0});i.prototype.create=function(e){r.prototype.create.call(this,e),this.updatePath(),this.front=new t(e.front||this.front),this.renderFront=new t(this.front),this.renderNormal=new t};var a=[`move`,`line`,`bezier`,`arc`];i.prototype.updatePath=function(){this.setPath(),this.updatePathCommands()},i.prototype.setPath=function(){},i.prototype.updatePathCommands=function(){var e;this.pathCommands=this.path.map(function(t,r){var i=Object.keys(t),o=i[0],s=t[o];(i.length!=1||a.indexOf(o)==-1)&&(o=`line`,s=t),(o==`line`||o==`move`)&&!Array.isArray(s)&&(s=[s]),o=r===0?`move`:o;var c=new n(o,s,e);return e=c.endRenderPoint,c})},i.prototype.reset=function(){this.renderOrigin.set(this.origin),this.renderFront.set(this.front),this.pathCommands.forEach(function(e){e.reset()})},i.prototype.transform=function(e,t,n){this.renderOrigin.transform(e,t,n),this.renderFront.transform(e,t,n),this.renderNormal.set(this.renderOrigin).subtract(this.renderFront),this.pathCommands.forEach(function(r){r.transform(e,t,n)}),this.children.forEach(function(r){r.transform(e,t,n)})},i.prototype.updateSortValue=function(){var e=this.pathCommands.length,t=this.pathCommands[0].endRenderPoint,n=this.pathCommands[e-1].endRenderPoint;e>2&&t.isSame(n)&&--e;for(var r=0,i=0;i<e;i++)r+=this.pathCommands[i].endRenderPoint.z;this.sortValue=r/e},i.prototype.render=function(e,t){var n=this.pathCommands.length;if(!(!this.visible||!n)&&(this.isFacingBack=this.renderNormal.z>0,!(!this.backface&&this.isFacingBack))){if(!t)throw Error(`Zdog renderer required. Set to `+t);var r=n==1;t.isCanvas&&r?this.renderCanvasDot(e,t):this.renderPath(e,t)}};var o=e.TAU;i.prototype.renderCanvasDot=function(e){var t=this.getLineWidth();if(t){e.fillStyle=this.getRenderColor();var n=this.pathCommands[0].endRenderPoint;e.beginPath();var r=t/2;e.arc(n.x,n.y,r,0,o),e.fill()}},i.prototype.getLineWidth=function(){return this.stroke?this.stroke==1?1:this.stroke:0},i.prototype.getRenderColor=function(){return typeof this.backface==`string`&&this.isFacingBack?this.backface:this.color},i.prototype.renderPath=function(e,t){var n=this.getRenderElement(e,t),r=(this.pathCommands.length!=2||this.pathCommands[1].method!=`line`)&&this.closed,i=this.getRenderColor();t.renderPath(e,n,this.pathCommands,r),t.stroke(e,n,this.stroke,i,this.getLineWidth()),t.fill(e,n,this.fill,i),t.end(e,n)};var s=`http://www.w3.org/2000/svg`;return i.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||(this.svgElement=document.createElementNS(s,`path`),this.svgElement.setAttribute(`stroke-linecap`,`round`),this.svgElement.setAttribute(`stroke-linejoin`,`round`)),this.svgElement},i})})),H=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(R());else{var r=e.Zdog;r.Group=n(r.Anchor)}})(e,function(e){var t=e.subclass({updateSort:!1,visible:!0});return t.prototype.updateSortValue=function(){var t=0;this.flatGraph.forEach(function(e){e.updateSortValue(),t+=e.sortValue}),this.sortValue=t/this.flatGraph.length,this.updateSort&&this.flatGraph.sort(e.shapeSorter)},t.prototype.render=function(e,t){this.visible&&this.flatGraph.forEach(function(n){n.render(e,t)})},t.prototype.updateFlatGraph=function(){var e=[];this.flatGraph=this.addChildFlatGraph(e)},t.prototype.getFlatGraph=function(){return[this]},t})})),U=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Rect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2;this.path=[{x:-e,y:-t},{x:e,y:-t},{x:e,y:t},{x:-e,y:t}]},t})})),ue=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.RoundedRect=n(r.Shape)}})(e,function(e){var t=e.subclass({width:1,height:1,cornerRadius:.25,closed:!1});return t.prototype.setPath=function(){var e=this.width/2,t=this.height/2,n=Math.min(e,t),r=Math.min(this.cornerRadius,n),i=e-r,a=t-r,o=[{x:i,y:-t},{arc:[{x:e,y:-t},{x:e,y:-a}]}];a&&o.push({x:e,y:a}),o.push({arc:[{x:e,y:t},{x:i,y:t}]}),i&&o.push({x:-i,y:t}),o.push({arc:[{x:-e,y:t},{x:-e,y:a}]}),a&&o.push({x:-e,y:-a}),o.push({arc:[{x:-e,y:-t},{x:-i,y:-t}]}),i&&o.push({x:i,y:-t}),this.path=o},t})})),W=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(V());else{var r=e.Zdog;r.Ellipse=n(r.Shape)}})(e,function(e){var t=e.subclass({diameter:1,width:void 0,height:void 0,quarters:4,closed:!1});return t.prototype.setPath=function(){var e=this.width==null?this.diameter:this.width,t=this.height==null?this.diameter:this.height,n=e/2,r=t/2;this.path=[{x:0,y:-r},{arc:[{x:n,y:-r},{x:n,y:0}]}],this.quarters>1&&this.path.push({arc:[{x:n,y:r},{x:0,y:r}]}),this.quarters>2&&this.path.push({arc:[{x:-n,y:r},{x:-n,y:0}]}),this.quarters>3&&this.path.push({arc:[{x:-n,y:-r},{x:0,y:-r}]})},t})})),de=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),V());else{var r=e.Zdog;r.Polygon=n(r,r.Shape)}})(e,function(e,t){var n=t.subclass({sides:3,radius:.5}),r=e.TAU;return n.prototype.setPath=function(){this.path=[];for(var e=0;e<this.sides;e++){var t=e/this.sides*r-r/4,n=Math.cos(t)*this.radius,i=Math.sin(t)*this.radius;this.path.push({x:n,y:i})}},n})})),fe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),R(),W());else{var r=e.Zdog;r.Hemisphere=n(r,r.Vector,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r){var i=r.subclass({fill:!0}),a=e.TAU;i.prototype.create=function(){r.prototype.create.apply(this,arguments),this.apex=new n({addTo:this,translate:{z:this.diameter/2}}),this.renderCentroid=new t},i.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,3/8),this.sortValue=this.renderCentroid.z},i.prototype.render=function(e,t){this.renderDome(e,t),r.prototype.render.apply(this,arguments)},i.prototype.renderDome=function(e,t){if(this.visible){var n=this.getDomeRenderElement(e,t),r=Math.atan2(this.renderNormal.y,this.renderNormal.x),i=this.diameter/2*this.renderNormal.magnitude(),o=this.renderOrigin.x,s=this.renderOrigin.y;if(t.isCanvas){var c=r+a/4,l=r-a/4;e.beginPath(),e.arc(o,s,i,c,l)}else t.isSvg&&(r=(r-a/4)/a*360,this.domeSvgElement.setAttribute(`d`,`M `+-i+`,0 A `+i+`,`+i+` 0 0 1 `+i+`,0`),this.domeSvgElement.setAttribute(`transform`,`translate(`+o+`,`+s+` ) rotate(`+r+`)`));t.stroke(e,n,this.stroke,this.color,this.getLineWidth()),t.fill(e,n,this.fill,this.color),t.end(e,n)}};var o=`http://www.w3.org/2000/svg`;return i.prototype.getDomeRenderElement=function(e,t){if(t.isSvg)return this.domeSvgElement||(this.domeSvgElement=document.createElementNS(o,`path`),this.domeSvgElement.setAttribute(`stroke-linecap`,`round`),this.domeSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.domeSvgElement},i})})),pe=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),B(),V(),H(),W());else{var r=e.Zdog;r.Cylinder=n(r,r.PathCommand,r.Shape,r.Group,r.Ellipse)}})(e,function(e,t,n,r,i){function a(){}var o=r.subclass({color:`#333`,updateSort:!0});o.prototype.create=function(){r.prototype.create.apply(this,arguments),this.pathCommands=[new t(`move`,[{}]),new t(`line`,[{}])]},o.prototype.render=function(e,t){this.renderCylinderSurface(e,t),r.prototype.render.apply(this,arguments)},o.prototype.renderCylinderSurface=function(e,t){if(this.visible){var n=this.getRenderElement(e,t),r=this.frontBase,i=this.rearBase,a=r.renderNormal.magnitude(),o=r.diameter*a+r.getLineWidth();this.pathCommands[0].renderPoints[0].set(r.renderOrigin),this.pathCommands[1].renderPoints[0].set(i.renderOrigin),t.isCanvas&&(e.lineCap=`butt`),t.renderPath(e,n,this.pathCommands),t.stroke(e,n,!0,this.color,o),t.end(e,n),t.isCanvas&&(e.lineCap=`round`)}};var s=`http://www.w3.org/2000/svg`;o.prototype.getRenderElement=function(e,t){if(t.isSvg)return this.svgElement||=document.createElementNS(s,`path`),this.svgElement},o.prototype.copyGraph=a;var c=i.subclass();c.prototype.copyGraph=a;var l=n.subclass({diameter:1,length:1,frontFace:void 0,fill:!0}),u=e.TAU;return l.prototype.create=function(){n.prototype.create.apply(this,arguments),this.group=new o({addTo:this,color:this.color,visible:this.visible});var e=this.length/2,t=this.backface||!0;this.frontBase=this.group.frontBase=new i({addTo:this.group,diameter:this.diameter,translate:{z:e},rotate:{y:u/2},color:this.color,stroke:this.stroke,fill:this.fill,backface:this.frontFace||t,visible:this.visible}),this.rearBase=this.group.rearBase=this.frontBase.copy({translate:{z:-e},rotate:{y:0},backface:t})},l.prototype.render=function(){},[`stroke`,`fill`,`color`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(l.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.frontBase&&(this.frontBase[e]=n,this.rearBase[e]=n,this.group[e]=n)}})}),l})})),me=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),L(),B(),R(),W());else{var r=e.Zdog;r.Cone=n(r,r.Vector,r.PathCommand,r.Anchor,r.Ellipse)}})(e,function(e,t,n,r,i){var a=i.subclass({length:1,fill:!0}),o=e.TAU;a.prototype.create=function(){i.prototype.create.apply(this,arguments),this.apex=new r({addTo:this,translate:{z:this.length}}),this.renderApex=new t,this.renderCentroid=new t,this.tangentA=new t,this.tangentB=new t,this.surfacePathCommands=[new n(`move`,[{}]),new n(`line`,[{}]),new n(`line`,[{}])]},a.prototype.updateSortValue=function(){this.renderCentroid.set(this.renderOrigin).lerp(this.apex.renderOrigin,1/3),this.sortValue=this.renderCentroid.z},a.prototype.render=function(e,t){this.renderConeSurface(e,t),i.prototype.render.apply(this,arguments)},a.prototype.renderConeSurface=function(e,t){if(this.visible){this.renderApex.set(this.apex.renderOrigin).subtract(this.renderOrigin);var n=this.renderNormal.magnitude(),r=this.renderApex.magnitude2d(),i=this.renderNormal.magnitude2d(),a=Math.acos(i/n),s=Math.sin(a),c=this.diameter/2*n;if(c*s<r){var l=Math.atan2(this.renderNormal.y,this.renderNormal.x)+o/2,u=r/s,d=Math.acos(c/u),f=this.tangentA,p=this.tangentB;f.x=Math.cos(d)*c*s,f.y=Math.sin(d)*c,p.set(this.tangentA),p.y*=-1,f.rotateZ(l),p.rotateZ(l),f.add(this.renderOrigin),p.add(this.renderOrigin),this.setSurfaceRenderPoint(0,f),this.setSurfaceRenderPoint(1,this.apex.renderOrigin),this.setSurfaceRenderPoint(2,p);var m=this.getSurfaceRenderElement(e,t);t.renderPath(e,m,this.surfacePathCommands),t.stroke(e,m,this.stroke,this.color,this.getLineWidth()),t.fill(e,m,this.fill,this.color),t.end(e,m)}}};var s=`http://www.w3.org/2000/svg`;return a.prototype.getSurfaceRenderElement=function(e,t){if(t.isSvg)return this.surfaceSvgElement||(this.surfaceSvgElement=document.createElementNS(s,`path`),this.surfaceSvgElement.setAttribute(`stroke-linecap`,`round`),this.surfaceSvgElement.setAttribute(`stroke-linejoin`,`round`)),this.surfaceSvgElement},a.prototype.setSurfaceRenderPoint=function(e,t){this.surfacePathCommands[e].renderPoints[0].set(t)},a})})),he=t(((e,t)=>{(function(e,n){if(typeof t==`object`&&t.exports)t.exports=n(P(),R(),V(),U());else{var r=e.Zdog;r.Box=n(r,r.Anchor,r.Shape,r.Rect)}})(e,function(e,t,n,r){var i=r.subclass();i.prototype.copyGraph=function(){};var a=e.TAU,o=[`frontFace`,`rearFace`,`leftFace`,`rightFace`,`topFace`,`bottomFace`],s=e.extend({},n.defaults);delete s.path,o.forEach(function(e){s[e]=!0}),e.extend(s,{width:1,height:1,depth:1,fill:!0});var c=t.subclass(s);return c.prototype.create=function(e){t.prototype.create.call(this,e),this.updatePath(),this.fill=this.fill},c.prototype.updatePath=function(){o.forEach(function(e){this[e]=this[e]},this)},o.forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,this.setFace(e,n)}})}),c.prototype.setFace=function(e,t){var n=e+`Rect`,r=this[n];if(!t){this.removeChild(r);return}var a=this.getFaceOptions(e);a.color=typeof t==`string`?t:this.color,r?r.setOptions(a):r=this[n]=new i(a),r.updatePath(),this.addChild(r)},c.prototype.getFaceOptions=function(e){return{frontFace:{width:this.width,height:this.height,translate:{z:this.depth/2}},rearFace:{width:this.width,height:this.height,translate:{z:-this.depth/2},rotate:{y:a/2}},leftFace:{width:this.depth,height:this.height,translate:{x:-this.width/2},rotate:{y:-a/4}},rightFace:{width:this.depth,height:this.height,translate:{x:this.width/2},rotate:{y:a/4}},topFace:{width:this.width,height:this.depth,translate:{y:-this.height/2},rotate:{x:-a/4}},bottomFace:{width:this.width,height:this.depth,translate:{y:this.height/2},rotate:{x:a/4}}}[e]},[`color`,`stroke`,`fill`,`backface`,`front`,`visible`].forEach(function(e){var t=`_`+e;Object.defineProperty(c.prototype,e,{get:function(){return this[t]},set:function(n){this[t]=n,o.forEach(function(t){var r=this[t+`Rect`],i=typeof this[t]==`string`;r&&!(e==`color`&&i)&&(r[e]=n)},this)}})}),c})})),G=e(t(((e,t)=>{(function(e,n){typeof t==`object`&&t.exports?t.exports=n(P(),F(),I(),L(),R(),z(),le(),B(),V(),H(),U(),ue(),W(),de(),fe(),pe(),me(),he()):typeof define==`function`&&define.amd&&define(`zdog`,[],e.Zdog)})(e,function(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){return e.CanvasRenderer=t,e.SvgRenderer=n,e.Vector=r,e.Anchor=i,e.Dragger=a,e.Illustration=o,e.PathCommand=s,e.Shape=c,e.Group=l,e.Rect=u,e.RoundedRect=d,e.Ellipse=f,e.Polygon=p,e.Hemisphere=m,e.Cylinder=h,e.Cone=g,e.Box=_,e})}))(),1),K=new Map([[`idle`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:2e3,repeat:`yoyo`},mouseInfluence:1}],[`listening`,{geometry:{},motion:{target:`root`,rotate:{x:-.2},durationMs:300,repeat:`yoyo`},mouseInfluence:.3}],[`processing`,{geometry:{},mouseInfluence:.2}],[`speaking`,{geometry:{},motion:{target:`root`,translate:{y:.5},durationMs:1500,repeat:`yoyo`},mouseInfluence:0,mouthCycle:[{durationMs:100,mouth:`open`},{durationMs:150,mouth:`base`},{durationMs:100,mouth:`open`},{durationMs:200,mouth:`base`}]}],[`thinking`,{geometry:{},motion:{target:`root`,rotate:{z:.1},durationMs:800,repeat:`yoyo`},mouseInfluence:0}],[`error`,{geometry:{expression:`dead`},mouseInfluence:.1}]]),ge=48,q=(e,t)=>Math.min(e,t)/ge,J=e=>e!==void 0&&e>0?e:1,Y=(e,t,n,r)=>{let i=Math.min(1,Math.sqrt(n/(e*t*r*r)));return[Math.max(1,Math.floor(e*i)),Math.max(1,Math.floor(t*i))]},X=(e,t)=>{if(!Number.isFinite(e))throw Error(`Sprite ${t} must be finite`)},Z=(e,t)=>{let n=e.ownerDocument.defaultView,r=n?.getComputedStyle(e)?.[t]??``,i=Number.parseFloat(r);if(i>0&&r.trim().endsWith(`px`))return i;let a=e.style[t],o=Number.parseFloat(a);if(o>0&&a.trim().endsWith(`px`))return o;let s=e.getBoundingClientRect(),c=t===`width`?s.width:s.height;if(c>0)return c;for(let r=e.parentElement;r;r=r.parentElement){let e=n?.getComputedStyle(r)[t],i=Number.parseFloat(e??``);if(i>0&&e?.trim().endsWith(`px`))return i}return e[t]||48},Q=e=>{if(!e)return{};let t={};return e.x!==void 0&&(t.x=e.x),e.y!==void 0&&(t.y=e.y),e.z!==void 0&&(t.z=e.z),t},$=e=>e?e<=.5?`small`:e<=.8?`medium`:`big`:`off`,_e=e=>{let t=new Map,n=new Map;for(let r of e.nodes){let e=r.parent===void 0?void 0:t.get(r.parent),i={kind:r.kind,name:r.options.name,children:[],options:r.options};t.set(r.id,i),i.name&&n.set(i.name,i),e?.children.push(i)}let r=t.get(e.root);if(!r)throw Error(`Portable Zdog scene has no root`);let i=new Map;for(let[n,r]of Object.entries(e.variants)){let e=new Map;for(let[n,i]of Object.entries(r)){let r=t.get(i);if(!r)throw Error(`Portable Zdog variant node is missing: ${i}`);e.set(n,r)}i.set(n,e)}return{root:r,nodesByName:n,variants:i,palette:e.palette,activities:e.activities,expressions:e.expressions}},ve=class{internals;target;view;onInvalidate;maxPixels;originalStyle;originalHasInlineWidth;originalHasInlineHeight;originalWidthAttribute;originalHeightAttribute;illustration;avatar;animationPivot;items=new Map;variantItems=new Map;palette;mouseListener;resizeObserver;animationTween=null;mouthCycleTimeline=null;entryTween=null;mouseX=0;mouseY=0;mouseInfluence=1;dirty=!0;destroyed=!1;paused=!1;lastRenderTime=0;constructor({target:e,scene:t,onInvalidate:n,palette:r,maxPixels:i}){this.target=e,this.view=e.ownerDocument.defaultView,this.onInvalidate=n,this.maxPixels=i,this.originalStyle=e.getAttribute(`style`),this.originalHasInlineWidth=e.style.width!==``,this.originalHasInlineHeight=e.style.height!==``,this.originalWidthAttribute=e.getAttribute(`width`),this.originalHeightAttribute=e.getAttribute(`height`),this.internals=_e(t),this.palette={...this.internals.palette};for(let[e,t]of Object.entries(r??{})){if(!(e in this.internals.palette))throw Error(`Unknown Sprite palette slot: ${e}`);t!==void 0&&(this.palette[e]=t)}let a=Z(e,`width`),o=Z(e,`height`),[s,c]=Y(a,o,i,J(this.view?.devicePixelRatio));e.width=Math.round(s),e.height=Math.round(c),this.illustration=new G.Illustration({element:e,resize:!1,zoom:q(s,c)}),this.illustration.setSize(s,c),this.preserveCanvasStyle(a,o),this.avatar=new G.Group({addTo:this.illustration,rotate:{x:-G.TAU/1.05}}),this.animationPivot=new G.Group({addTo:this.avatar}),this.createScene(this.internals.root,this.animationPivot),this.indexVariants(),this.mouseListener=e=>{this.onMouseMove(e)},this.view?.addEventListener(`mousemove`,this.mouseListener);let l=globalThis.ResizeObserver;this.resizeObserver=new l(()=>{this.destroyed||this.resize()});try{this.resizeObserver.observe(e),this.present({activity:t.defaultPresentation.activity,expression:t.defaultPresentation.expression})}catch(e){throw this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect(),e}}present(e){if(this.assertAlive(),!(e.expression in this.internals.expressions))throw Error(`Unknown Sprite expression: ${e.expression}`);if(!(e.activity in this.internals.activities)&&!K.has(e.activity))throw Error(`Unknown Sprite activity: ${e.activity}`);this.stopAnimations();let t=this.activitySpec(e.activity),n=this.internals.expressions[e.expression],r=t.geometry?.expression??e.expression,i=this.internals.expressions[r]??n;this.mouseInfluence=t.mouseInfluence??1,this.applyVariants(i,t.geometry),this.resetPivot(),t.motion&&this.startMotion(t.motion,!0),i?.motion&&this.startMotion(i.motion,!1),t.mouthCycle&&this.internals.variants.get(`mouth`)?.size&&this.startMouthCycle(t.mouthCycle,i),this.dirty=!0,this.pause(this.paused)}setPalette(e){this.assertAlive();for(let t of Object.keys(e))if(!Object.hasOwn(this.internals.palette,t))throw Error(`Unknown Sprite palette slot: ${t}`);Object.assign(this.palette,this.internals.palette,e);for(let[e,t]of this.items){for(let n of[`color`,`backface`,`frontFace`]){let r=e.options[n],i=s(r);i&&(t[n]=this.palette[i])}e.kind===`cylinder`&&t.frontBase!==void 0&&t.rearBase!==void 0&&(t.frontFace?t.frontBase.backface=t.frontFace:t.backface?t.frontBase.backface=t.backface:t.frontBase.backface=!0,t.backface?t.rearBase.backface=t.backface:t.rearBase.backface=!0)}this.dirty=!0,this.onInvalidate()}pause(e){this.paused=e;for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])e?t?.pause():t?.resume()}seek(e){if(X(e,`timeMs`),e<0)throw RangeError(`timeMs must be nonnegative`);this.pause(!0);for(let t of[this.animationTween,this.mouthCycleTimeline,this.entryTween])t?.seek(e);this.dirty=!0,this.renderStill()}tick(e){if(this.destroyed||!this.illustration.ctx)return!1;let t=this.hasActiveTween();return(this.dirty||t||this.mouseNeedsRender())&&e-this.lastRenderTime>=1e3/24&&(this.updateMouseTracking(),this.illustration.updateRenderGraph(),this.lastRenderTime=e,this.dirty=!1),this.dirty||this.hasActiveTween()||this.mouseNeedsRender()}renderStill(){this.destroyed||!this.dirty||!this.illustration.ctx||(this.illustration.updateRenderGraph(),this.dirty=!1)}resize(){this.assertAlive();let e=Z(this.target,`width`),t=Z(this.target,`height`),[n,r]=Y(e,t,this.maxPixels,J(this.view?.devicePixelRatio));this.illustration.zoom=q(n,r),this.illustration.setSize(n,r),this.preserveCanvasStyle(e,t),this.dirty=!0,this.onInvalidate()}destroy(){if(this.destroyed)throw Error(`Sprite instance has already been destroyed`);this.destroyed=!0,this.stopAnimations(),this.view?.removeEventListener(`mousemove`,this.mouseListener),this.resizeObserver.disconnect();let e=this.target.getContext(`2d`);e&&e.clearRect(0,0,this.target.width,this.target.height),this.restoreCanvasAttributes()}createScene(e,t){let n={...e.options};delete n.parent,delete n.name,delete n.x,delete n.y,delete n.z,n.addTo=t,n.translate?n.translate=Q(n.translate):(e.options.x!==void 0||e.options.y!==void 0||e.options.z!==void 0)&&(n.translate=Q({x:e.options.x,y:e.options.y,z:e.options.z}));let r=s(n.color);r&&(n.color=this.palette[r]);let i=s(n.backface);i&&(n.backface=this.palette[i]);let a=s(n.frontFace);a&&(n.frontFace=this.palette[a]);let o;switch(e.kind){case`group`:o=new G.Group(n);break;case`shape`:n.path=n.path??[{}],o=new G.Shape(n);break;case`ellipse`:o=new G.Ellipse(n);break;case`hemisphere`:o=new G.Hemisphere(n);break;case`cylinder`:o=new G.Cylinder(n)}this.items.set(e,o);for(let t of e.children)this.createScene(t,o);return o}indexVariants(){for(let[e,t]of this.internals.variants.entries()){let n=new Map;for(let[e,r]of t.entries()){let t=this.items.get(r);t&&n.set(e,t)}this.variantItems.set(e,n)}}applyVariants(e,t){for(let e of this.variantItems.values())for(let t of e.values())t.visible=!1;let n={...e?.variants};for(let[t,r]of Object.entries(e?.variantChoices??{})){let e=r[Math.min(r.length-1,Math.floor(Math.random()*r.length))];e!==void 0&&(n[t]=e)}t?.eyes&&(n.eyes=t.eyes),t?.mouth&&(n.mouth=t.mouth),t?.blush===void 0?e?.blush!==void 0&&(n.blush=$(e.blush)):n.blush=$(t.blush);for(let[e,t]of Object.entries(n)){let n=this.variantItems.get(e)?.get(t);n&&(n.visible=!0)}}activitySpec(e){let t=K.get(e)??{geometry:{},mouseInfluence:1},n=this.internals.activities[e];if(!n)return t;let r=n.motion??t.motion,i=n.mouthCycle??t.mouthCycle,a={...t,...n,geometry:{...t.geometry,...n.geometry}};return r!==void 0&&(a.motion=r),i!==void 0&&(a.mouthCycle=i),a}startMotion(e,t){let n=this.internals.nodesByName.get(e.target),r=n===this.internals.root?this.animationPivot:n?this.items.get(n):void 0;if(!r)return;let i=ce({loop:e.repeat===`loop`||e.repeat===`yoyo`,alternate:e.repeat===`yoyo`}),a=e.durationMs??1e3;e.translate&&i.add(r.translate,{...Q(e.translate),duration:a,ease:`inOutSine`},0),e.rotate&&i.add(r.rotate,{...Q(e.rotate),duration:a,ease:`inOutSine`},0),t?this.animationTween=i:this.entryTween=i}startMouthCycle(e,t){let n=[],r=0;for(let i of e)X(i.durationMs,`mouthCycle.durationMs`),r+=i.durationMs,n.push({until:r,mouth:i.mouth===`open`?`open`:t?.variants?.mouth});let i;this.mouthCycleTimeline=d({duration:r,loop:!0,onUpdate:e=>{let t=n.find(t=>e.iterationCurrentTime<t.until)?.mouth;t&&t!==i&&(i=t,this.showVariant(`mouth`,t))},onLoop:()=>{i=void 0}})}showVariant(e,t){let n=this.variantItems.get(e);if(n===void 0)return;let r=n.get(t);if(r!==void 0){for(let e of n.values())e.visible=!1;r.visible=!0,this.dirty=!0}}resetPivot(){Object.assign(this.animationPivot.rotate,{x:0,y:0,z:0}),Object.assign(this.animationPivot.translate,{x:0,y:0,z:0}),Object.assign(this.avatar.rotate,{x:-G.TAU/1.05,y:0,z:0})}stopAnimations(){this.animationTween?.cancel(),this.mouthCycleTimeline?.cancel(),this.entryTween?.cancel(),this.animationTween=null,this.mouthCycleTimeline=null,this.entryTween=null}hasActiveTween(){return[this.animationTween,this.mouthCycleTimeline,this.entryTween].some(e=>e!==null&&!e.paused&&!e.completed&&!e.cancelled)}onMouseMove(e){if(this.destroyed||this.paused)return;let t=this.target.getBoundingClientRect(),n=t.width||1,r=t.height||1;this.mouseX=Math.max(-1,Math.min(1,(e.clientX-t.left-n/2)/(n/2))),this.mouseY=Math.max(-1,Math.min(1,(e.clientY-t.top-r/2)/(r/2))),this.dirty=!0,this.onInvalidate()}updateMouseTracking(){let e=-this.mouseX*.4*this.mouseInfluence,t=-G.TAU/1.05-this.mouseY*.2*this.mouseInfluence,n=(e-this.avatar.rotate.y)*.08,r=(t-this.avatar.rotate.x)*.08;this.avatar.rotate.y+=n,this.avatar.rotate.x+=r,(Math.abs(n)>.001||Math.abs(r)>.001)&&(this.dirty=!0)}mouseNeedsRender(){return Math.abs(this.avatar.rotate.y+this.mouseX*.4*this.mouseInfluence)>.001||Math.abs(this.avatar.rotate.x+G.TAU/1.05+this.mouseY*.2*this.mouseInfluence)>.001}assertAlive(){if(this.destroyed)throw Error(`Sprite instance has been destroyed`)}restoreCanvasAttributes(){this.originalStyle===null?this.target.removeAttribute(`style`):this.target.setAttribute(`style`,this.originalStyle),this.originalWidthAttribute===null?this.target.removeAttribute(`width`):this.target.setAttribute(`width`,this.originalWidthAttribute),this.originalHeightAttribute===null?this.target.removeAttribute(`height`):this.target.setAttribute(`height`,this.originalHeightAttribute)}preserveCanvasStyle(e,t){this.originalStyle!==null&&this.target.setAttribute(`style`,this.originalStyle),this.originalHasInlineWidth||(this.target.style.width=`${String(Math.round(e))}px`),this.originalHasInlineHeight||(this.target.style.height=`${String(Math.round(t))}px`)}},ye=e=>new ve(e),be=e=>n(function*(){let t=c.parse(e.document.data),n=yield*o(i(()=>e.target.ownerDocument.createElement(`canvas`)),e=>i(()=>{e.remove()}));n.style.cssText=`width:100%;height:100%;display:block`,e.target.replaceChildren(n);let s=e.target.ownerDocument.defaultView;if(!s)throw Error(`Zdog avatar requires a browser window`);let l,u=!0,d=!1,f=()=>{u||d||l!==void 0||(l=s.requestAnimationFrame(e=>{l=void 0,m.tick(e)&&f()}))},p=()=>{d||(u?m.renderStill():f())},m=yield*o(i(()=>ye({target:n,scene:t,onInvalidate:p,maxPixels:e.maxPixels})),e=>i(()=>{e.destroy()}));yield*a(()=>i(()=>{d=!0,l!==void 0&&s.cancelAnimationFrame(l)})),m.pause(!0);let h=!1,g,_;return{activities:[`idle`,`listening`,`processing`,`speaking`,`thinking`,`error`,...Object.keys(t.activities)],expressions:[t.defaultPresentation.expression,...Object.keys(t.expressions)].filter((e,t,n)=>n.indexOf(e)===t),set(e){let n={};for(let[t,i]of Object.entries(e.appearance)){let e=r().safeParse(i);if(!e.success)throw Error(`Zdog palette value must be a color: ${t}`);n[t]=e.data}let i=JSON.stringify(n);i!==_&&(m.setPalette(n),_=i);let a=e.expression??t.defaultPresentation.expression;if(!a)throw Error(`Zdog avatar needs an expression`);let o=JSON.stringify([e.activity,a]);o!==g&&(m.present({activity:e.activity,expression:a}),g=o),h=e.timeMs!==void 0,e.timeMs!==void 0&&m.seek(e.timeMs),p()},pause(e){u=h||e,m.pause(u),u&&l!==void 0&&(s.cancelAnimationFrame(l),l=void 0),p()}}});export{be as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,Bn as n,F as r,G as i,Gr as a,I as o,Jn as s,K as c,O as l,P as u,Q as d,Qn as f,R as p,St as m,V as h,Xn as ee,Y as te,Yn as ne,Zn as g,_ as re,a as _,at as v,bt as y,c as b,ct as x,d as ie,dt as S,er as ae,et as oe,ft as C,g as w,gt as se,h as T,ht as ce,i as le,ir as E,j as D,m as ue,mi as O,mt as k,n as de,o as fe,or as A,ot as pe,p as j,pt as M,r as me,s as N,sr as he,st as P,t as ge,vt as _e,w as ve,xt as ye,y as F,yt as I}from"./Effect-Bibd7o64.js";import{$ as be,$t as xe,A as Se,An as Ce,Ar as L,At as we,B as Te,Bn as Ee,Br as De,Bt as Oe,C as ke,Ci as Ae,Cn as je,Ct as Me,D as Ne,Dn as Pe,Dr as Fe,Dt as Ie,E as Le,Ei as Re,En as ze,Et as Be,F as Ve,Ft as He,G as Ue,Gr as We,Gt as Ge,H as Ke,Ha as qe,Ht as Je,I as Ye,Ir as Xe,It as Ze,J as Qe,Ja as $e,Jr as et,Jt as tt,Ka as nt,Kn as rt,Kr as it,Kt as at,L as ot,Ln as st,Lr as ct,Lt as lt,M as ut,Mn as dt,Mt as ft,N as pt,Nn as mt,Nt as ht,O as gt,Oa as _t,Oi as vt,On as yt,Ot as bt,P as xt,Pn as St,Pt as Ct,Q as wt,Qi as Tt,Qn as Et,Qr as Dt,Qt as Ot,R as kt,Rn as At,Rr as jt,Rt as Mt,S as Nt,Si as R,Sn as Pt,Sr as Ft,St as It,T as Lt,Ti as Rt,Tn as zt,Tr as Bt,Tt as Vt,U as Ht,Ua as Ut,Un as Wt,Ur as Gt,Ut as Kt,V as qt,Va as Jt,Vi as Yt,Vr as Xt,Vt as Zt,W as Qt,Wa as $t,Wi as en,Wr as tn,Wt as z,X as nn,Xa as rn,Xt as an,Y as on,Ya as sn,Yt as cn,Z as ln,Zr as un,Zt as dn,_ as fn,_a as pn,_i as mn,_n as hn,_t as gn,a as _n,ai as vn,an as yn,ao as bn,ar as xn,at as Sn,b as Cn,bn as wn,bt as Tn,c as En,ct as Dn,d as On,di as kn,dn as An,do as jn,dr as Mn,dt as Nn,en as Pn,er as Fn,et as In,f as Ln,fi as Rn,fn as zn,ft as Bn,g as Vn,gn as Hn,gt as Un,h as Wn,ha as B,hn as Gn,ht as Kn,i as qn,ii as V,in as Jn,io as Yn,ir as Xn,it as Zn,j as Qn,jt as $n,k as er,ki as tr,kn as nr,kt as rr,l as ir,ln as ar,lo as or,lr as sr,lt as cr,m as lr,ma as ur,mi as H,mr as dr,mt as fr,n as pr,na as mr,ni as hr,nn as gr,nr as _r,nt as vr,o as yr,oa as br,on as xr,oo as Sr,or as Cr,ot as wr,p as Tr,pa as Er,pn as Dr,po as Or,pt as kr,q as Ar,qa as jr,qn as Mr,qr as Nr,qt as Pr,r as Fr,ri as Ir,ro as Lr,rr as U,rt as Rr,s as zr,si as Br,sn as Vr,so as Hr,sr as W,st as Ur,t as Wr,ti as Gr,tn as Kr,to as qr,tr as Jr,tt as Yr,u as Xr,ua as Zr,ui as Qr,un as $r,uo as ei,ut as ti,v as ni,va as G,vi as ri,vn as ii,vr as ai,vt as oi,w as si,wi as ci,wn as li,wt as ui,x as di,xa as fi,xn as pi,xt as mi,y as hi,ya as gi,yn as _i,yt as vi,z as yi,zn as bi,zr as K,zt as xi}from"./extension-hook-C8RQgls9.js";import{l as Si,m as Ci,p as wi}from"./preload-helper-DY31Aviq.js";import{d as Ti,f as Ei,u as Di}from"./index-26gTYfVj.js";import{a as Oi,i as ki,n as Ai,o as ji,r as Mi,t as Ni}from"./extensions-DYjwCmO5.js";var Pi=pn(()=>aa),Fi=K(Pi),Ii=V({id:Dt,payload:We}),Li=V({...Ii.fields,schemas:ur(Fi)});function Ri(e){let t={};for(let[n,r]of Object.entries(e))_t(r)&&a(t,n,r);return Object.keys(t).length===0?E():A(t)}var zi=ur(hr(Ir,Rn)).pipe(Re(B(it),{decode:Jt(),encode:Ut(e=>f(e)||e.value===void 0?E():Ri(e.value))})),Bi=pn(()=>Ui),Vi=K(Bi),Hi={annotations:zi,checks:Vi},Ui=kn([V({_tag:G(`Filter`),representation:Li,annotations:zi,aborted:Xt}),V({_tag:G(`FilterGroup`),representation:ur(Li),annotations:zi,checks:un(Bi)})]);function q(e){return V({_tag:G(e),...Hi})}var Wi=V({_tag:G(`Declaration`),representation:Ii,annotations:zi,typeParameters:Fi,checks:Vi}),Gi=V({_tag:G(`Suspend`),annotations:zi,checks:Br([]),thunk:Pi});function Ki(e,t){return t.pipe(Re(V({type:G(e),value:t}),{decode:qe(e=>e.value),encode:qe(t=>({type:e,value:t}))}))}var qi=Ki(`string`,Ir),Ji=Ki(`number`,Gr),Yi=V({_tag:G(`Literal`),...Hi,literal:kn([qi,Ki(`number`,Gt),Ki(`bigint`,De),Ki(`boolean`,Xt)])}),Xi=V({_tag:G(`UniqueSymbol`),...Hi,symbol:vn}),Zi=V({_tag:G(`Enum`),...Hi,enums:K(Br([Ir,kn([qi,Ji])]))}),Qi=V({_tag:G(`TemplateLiteral`),...Hi,parts:Fi}),$i=V({isOptional:Xt,type:Pi,annotations:zi}),ea=V({_tag:G(`Arrays`),...Hi,elements:K($i),rest:Fi}),ta=V({name:kn([qi,Ji,Ki(`symbol`,vn)]),type:Pi,isOptional:Xt,isMutable:Xt,annotations:zi}),na=V({parameter:Pi,type:Pi}),ra=V({_tag:G(`Objects`),...Hi,propertySignatures:K(ta),indexSignatures:K(na)}),ia=V({_tag:G(`Union`),...Hi,types:Fi,options:B(V({mode:B(et([`anyOf`,`oneOf`]))}))}),aa=kn([Wi,V({_tag:G(`Reference`),$ref:Dt}),Gi,q(`Null`),q(`Undefined`),q(`Void`),q(`Never`),q(`Unknown`),q(`Any`),q(`String`),q(`Number`),q(`Boolean`),q(`BigInt`),q(`Symbol`),q(`ObjectKeyword`),Yi,Xi,Zi,Qi,ea,ra,ia]),oa=Rt(gi(V({representation:Pi,references:hr(Ir,Pi)})));function sa(e){return oa(e)}var ca=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function la(e){return e[ca]?.()}var ua=3.5,da=4800;function fa(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function pa(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function ma(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:da;return t}function ha(e){return Math.ceil(e.length/ua)}function ga(e){return Math.ceil(ma(e)/ua)}function _a(e){let t=0;if(e.role===`system`)return ha(Ci(e))+ba(e.toolsAdded)+ba(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return ga(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+pa(n.arguments).length;return Math.ceil(t/ua)}function va(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`&&fa(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function ya(e){let t=`messages`in e?e.messages:e,n=va(t);if(n){let e=fa(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=_a(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=_a(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function ba(e){return!e||e.length===0?0:ha(pa(e))}var xa=0xffffffffffff,Sa=(1n<<41n)-1n,Ca=-1,J;function wa(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>xa)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${xa}`);let n=e===void 0?Math.max(t,Ca):e;e===void 0&&(Ca=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),J===void 0)J=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(J===Sa)throw RangeError(`UUIDv7 generator sequence exhausted`);J++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(J>>37n&15n),r[7]=Number(J>>29n&255n),r[8]=128|Number(J>>23n&63n),r[9]=Number(J>>15n&255n),r[10]=Number(J>>7n&255n),r[11]=Number((J&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 Ta(e){return bn(e,{onFailure:re,onSuccess:()=>m})}function Ea(e,t){return h(e,{onFailure:e=>T(t).pipe(_(re(e))),onSuccess:()=>t})}function Da(e,t){let n={_tag:`open`},r=r=>Ea(e,t).pipe(T,F(e=>M(()=>{r.result=e,n={_tag:`closed`}}).pipe(_(r.settled.open),_(Ta(e)))),y);return C(()=>{if(n._tag===`closed`)return m;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(_(C(()=>{let t=e.result;return t===void 0?j(Error(`Agent close settlement was not recorded`)):Ta(t)})))}let e={_tag:`running`,settled:Fe(!1)};return n=e,r(e)})}function Oa(e,t,n,r){let i=Rr(e,t);if(n.state===`idle`)return{facts:{queue:{state:`idle`},cancellationRequested:!1,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};if(n.state===`queued`)return{facts:{queue:{state:`queued`,commandId:n.jobId,runningWork:r},cancellationRequested:n.cancellationRequested,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};let a=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:Yr(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:Te(e,t)},progress:qt(e,t,n.jobId),toolOutput:Ke(e,t,n.jobId)}}var ka=new WeakMap;function Aa(e,t){let n=wr(e,{sessionId:t}),r=nn(n);return r.length===0?null:ya(r).tokens}function ja(e,t,n,r=!0){return D(function*(){let i=yield*oe(I({try:()=>cr(e.store,t),catch:e=>e}));if(i._tag===`Failure`){Ce(`session-context.preference`,i.failure);return}let a=i.success,s=JSON.stringify(a),c=ka.get(e)??new Map;ka.set(e,c);let l=r?c.get(t):void 0,u=e.model.describe;if(l?.cursor===n&&l.preference===s){if(l.value===void 0||u===void 0)return l.value;let e=l.value;return yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:i})=>{if(e.window===i)return e;let a=Object.freeze({tokens:e.tokens,window:i});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:a}),a}),ie(t=>M(()=>(Ce(`session-context.describe`,t),e))))}let d=yield*oe(I({try:()=>Aa(e.store,t),catch:e=>e}));if(d._tag===`Failure`){Ce(`session-context.figure`,d.failure);return}let f=d.success;if(f===null){r&&c.set(t,{cursor:n,preference:s,value:void 0});return}if(u===void 0){let e=Object.freeze({tokens:f,window:null});return r&&c.set(t,{cursor:n,preference:s,value:e}),e}r&&c.set(t,{cursor:n,preference:s,value:Object.freeze({tokens:f,window:null})});let p=yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:e})=>e),ie(e=>M(()=>(Ce(`session-context.describe`,e),null)))),m=Object.freeze({tokens:f,window:p});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:m}),m})}function Ma(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(_(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(_(e.extensions.call({scope:`agent`},t,n,r)))})}function Na(e,t,n){return t.readQueueHead(n).pipe(F(r=>(r.state===`queued`?t.runningWork(r.jobId):S(null)).pipe(o(t=>Oa(e.store,n,r,t)))))}function Pa(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function Fa(e,t,n,r){return Na(e,t,n).pipe(F(i=>si(e.store,n,i,r,()=>t.extensions.project(n))),F(t=>ja(e,n,t.cursor,r?.before===void 0).pipe(o(e=>Pa(t,e)))))}function Ia(e,t,n){return e.assertOpen.pipe(_(I({try:()=>n(U(t)),catch:e=>e instanceof W?e:new W(`store`,`rejected`,`Session owner operation failed`)})))}function La(e,t){return I({try:()=>{let n=Jr(t);if(n._tag===`Failure`)throw new W(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:U(e),command:n.success})},catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Session command is invalid`)})}function Ra(e,t){return I({try:()=>Object.freeze({sessionId:U(e),options:xn(t)}),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Subscribe options are invalid`)})}function za(e,t,n,r=!1){return t.assertOpen.pipe(_(Fa(e,t,n,{includeSandboxFailures:r})),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function Ba(e){return[[e],A({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function Va(e,t,n,r,i,a,s=!1){return Ft({after:i,delivery:a,awaitSignal:!1},i=>(i.awaitSignal?n.awaitSignal.pipe(F(e=>n.pollSignal.pipe(o(t=>t===void 0?e:ze(e,t))))):n.pollSignal).pipe(F(a=>a===`closed`?S([[],E()]):a===`reset`?za(e,t,r,s).pipe(o(Ba)):t.assertOpen.pipe(_(Na(e,t,r)),F(c=>(n.setQueued(c.facts.queue.state===`queued`),a===`activity`&&i.delivery===`live`?S([[{kind:`activity`,activity:c.facts}],A({...i,awaitSignal:!0})]):a===`progress`&&i.delivery===`live`?S([[...c.progress===null?[]:[{kind:`progress`,progress:c.progress,activity:c.facts}],{kind:`tool_output`,toolOutput:c.toolOutput,activity:c.facts}],A({...i,awaitSignal:!0})]):Le(e.store,r,i.after,i.delivery,c,()=>t.extensions.project(r),s).pipe(F(n=>{if(n.kind===`reset`)return za(e,t,r,s).pipe(o(Ba));let a=n.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`?[]:[e.cursor]).at(-1),c={after:a??i.after,delivery:n.hasMore?i.delivery:`live`,awaitSignal:!n.hasMore};return(n.frames.some(e=>e.kind===`update`&&e.cursor!==i.after)&&!n.hasMore?ja(e,r,a??null):S(void 0)).pipe(o(e=>[e===void 0?n.frames:n.frames.map(t=>t.kind===`update`&&t.cursor===a?Object.freeze({...t,context:e}):t),A(c)]))}))))))))}function Ha(e,t,n,r,i){return Bt(t.assertOpen.pipe(_(Ra(r,i)),F(r=>ge(n.register(r.sessionId),e=>M(e.close)).pipe(o(n=>Va(e,t,n,r.sessionId,r.options.after,`replay`,r.options.includeSandboxFailures===!0))))))}function Ua(e,t){return I({try:()=>Object.freeze({sessionId:U(e),options:Fn(t)}),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Watch options are invalid`)})}function Wa(e,t,n,r,a){return t.assertOpen.pipe(_(Ua(r,a)),F(r=>ye(a=>D(function*(){let s=yield*n.register(r.sessionId);return yield*a(t.assertOpen.pipe(_(Fa(e,t,r.sessionId,r.options)),o(n=>(s.setQueued(n.activity.queue.state===`queued`),Object.freeze({snapshot:n,changes:Va(e,t,s,r.sessionId,n.cursor??void 0,`live`,r.options.includeSandboxFailures===!0).pipe(ai(M(s.close))),close:M(s.close)}))))).pipe(i(()=>M(s.close)))}))))}function Ga(e,t,n,r,i,a){let o={sessionId:t,command:n,when:`now`,origin:{kind:`user`}};return r!==void 0&&(o={...o,meta:r}),i!==void 0&&(o={...o,mail:i}),a!==void 0&&(o={...o,reply:a}),e.assertOpen.pipe(_(e.door.admit(o)),F(e=>e.status===`accepted`?S({status:`accepted`,commandId:e.commandId}):w(new W(`runtime`,`unavailable`,`Session command was not admitted`))))}function Ka(e,t,n,r,i){return t.assertOpen.pipe(_(Ia(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&Qe(e.store,t,r.commandId,vr(e.store,e.meta.identityPath,i))})),_(Tr(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),F(e=>e===void 0?S({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(N({status:`accepted`,commandId:e.accepted.commandId}))))}function qa(e,t,n,r){return t.assertOpen.pipe(_(t.commit(ir(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),F(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function Ja(e,t,n,r){return t.assertOpen.pipe(_(Ln(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),N(void 0))}function Ya(e,t,n,r){return t.assertOpen.pipe(_(fn(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function Xa(e,t,n,r,i){return t.assertOpen.pipe(_(La(n,i)),F(t=>Za(e,r).pipe(o(e=>({...t,checked:e})))),F(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Ga(t,n,r,i);case`abort`:return qa(e,t,n,i).pipe(N(void 0));case`cancel`:return Ka(e,t,n,r,i);case`branch`:return Ja(e,t,n,r);case`fork`:return Ya(e,t,n,r);case`operator`:return t.assertOpen.pipe(_(ut(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),N(void 0));case`title`:return t.commit(Ia(t,n,t=>{Bn(e.store,t,r.title)})).pipe(N(void 0))}}))}function Za(e,t){return I({try:()=>t===void 0?void 0:dt(e.meta,t),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Host metadata is invalid`)})}function Qa(e,t){let n=Pe(e.store),r=(r,i)=>{function a(n){return Xa(e,t,r,i,n)}return Object.freeze({command:a,withdraw:e=>t.assertOpen.pipe(_(t.door.withdraw(r,e))),abort:a({type:`abort`}),send:(e,t)=>M(()=>t?.requestId??Xe()).pipe(F(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return a(t?.images===void 0?r:{...r,images:t.images}).pipe(p(e=>e.requestId===n?e:new W(e.boundary,e.cause,e.message,n)))})),cancel:e=>a({type:`cancel`,...e}),latestPending:Ia(t,r,t=>Ht(e.store,t,e.meta?.identityPath===void 0||i===void 0?void 0:vr(e.store,e.meta.identityPath,i))),modelPreference:Object.freeze({read:Ia(t,r,t=>cr(e.store,t)),set:n=>I({try:()=>sr(n),catch:()=>new W(`contract`,`invalid`,`Model preference is invalid`)}).pipe(F(n=>t.commit(Ia(t,r,t=>(Nn(e.store,t,n),t))).pipe(k(t=>M(()=>{nr(e.store,t)})),b)))}),extension:e=>Object.freeze({call:(n,i,a)=>t.assertOpen.pipe(_(t.extensions.call({scope:`session`,sessionId:r},e,n,i,a)))}),read:n=>t.assertOpen.pipe(_(Fa(e,t,r,n))),readSettlement:(i,a=0)=>x(D(function*(){yield*t.assertOpen;let s=yield*I({try:()=>({sessionId:U(r),...Cr(Xn({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*ge(n.register(s.sessionId,`settlement`),e=>M(e.close)),l=Nt(e.store,s.sessionId,s.commandId),u=yield*l;return u!==void 0||s.timeoutMs===0?u:yield*D(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*w(new W(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(se(s.timeoutMs),o(g))})),subscribe:i=>Ha(e,t,n,r,i),watch:i=>Wa(e,t,n,r,i)})},i=Object.freeze({createSession:n=>t.assertOpen.pipe(_(lr(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(_(Vn(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(_(Lt(e.store,n))),extensions:Ma(t),session:e=>r(e,void 0),close:t.beginClose.pipe(_(n.close))});return Object.freeze({...i,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>Ia(t,n,t=>e.store.transactionSync(()=>vi(e.store,t,r))),read:n=>Ia(t,n,t=>Tn(e.store,t))}),withMeta:e=>Object.freeze({...i,session:t=>r(t,e)})})}function $a(e){let t=ct.safeParse(e.meta);return t.success&&t.data.delegation?.steer===!0}function eo(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(zn(t,o,n,Date.now()))}},u=r(n===void 0?l:{...l,meta:n});if(u.status!==`accepted`)throw Error(`Sessionless addressed mail was not admitted`);return{status:`accepted`,commandId:u.commandId,sessionId:o}})}return Ga(e,t.to.sessionId,{requestId:t.key,delivery:r!==void 0||$a(t)?`steer`:`followUp`,type:`prompt`,text:t.content},n,t,r)}var to=V({fork:et([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:tn.pipe(H(Yt(0)),H(Tt(2**53-1)))});function no(e,t){let n=vt(e.schema)(t);if(n._tag===`Failure`)throw new ki({reason:`encode`,message:`Session document does not match its schema`});let r=R(mt)(n.success);if(r._tag===`Failure`)throw new ki({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 ki({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function ro(e){return{...Ae(to)(e),schema:sa(fi(e.schema)),initial:no(e,e.initial)}}var io=64,ao=et([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),oo=K(ao).pipe(H(mr(10))),so=V({protocol:Nr(`shiitake.extension/v0`),id:yr,version:En,requests:oo}),co=K(V({id:yr,capabilities:oo,grantKey:B(yr)})).pipe(H(mr(io))),lo=Ir.pipe(H(Zr(/^[a-z][A-Za-z0-9_]{0,63}$/u))),uo=R(so,{onExcessProperty:`error`}),fo=R(co,{onExcessProperty:`error`}),po=R(lo);function Y(e){return new W(`extensions`,`invalid`,e)}function mo(e){return new Set(e).size!==e.length}function ho(e){return JSON.stringify(e,(e,t)=>O(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function go(e){return _e({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 W(`extensions`,`rejected`,`Extension digest failed`)})}function _o(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:sa(fi(t.input)),output:sa(fi(t.output))}])),projection:r.projection===null?null:sa(fi(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,sa(fi(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,ro(t)]))};return o===void 0?c:{...c,catalog:o}}function vo(e){if(uo(e.manifest)._tag===`Failure`)throw Y(`Extension manifest is invalid`);let t=e.manifest;if(mo(t.requests))throw Y(`Extension capability requests are invalid`);if(e.contract.id!==t.id)throw Y(`Extension contract identity does not match its manifest`);if(!Number.isSafeInteger(e.state.version)||e.state.version<1)throw Y(`Extension state version is invalid`);for(let t of Object.keys(e.state.collections))if(t===`update`||t===`read`||t===`observe`||po(t)._tag===`Failure`)throw Y(`Extension collection name is invalid`);if(e.catalog!==void 0&&!t.requests.includes(`commands`))throw Y(`An extension catalog requires the commands capability`);return t}function yo(e){return D(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*I({try:()=>{if(t.length>io)throw Y(`Extension roster is invalid`);let e=t.map(e=>{let t=la(e);if(t===void 0)throw Y(`Extension roster entry was not defined`);let n=t.documents??{};for(let[e,t]of Object.entries(n)){if(po(e)._tag===`Failure`)throw Y(`Session document name is invalid`);ro(t)}let r=vo(t);if(Object.keys(n).length>0&&!r.requests.includes(`state`))throw Y(`Session documents require the state capability`);return{definition:t,documents:n,manifest:r}});if(mo(e.map(({manifest:e})=>e.id)))throw new W(`extensions`,`conflict`,`Extension identities conflict`);let r=fo(n);if(r._tag===`Failure`)throw Y(`Extension grants are invalid`);if(mo(r.success.map(({id:e})=>e)))throw Y(`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||mo(t.capabilities)||t.capabilities.some(e=>!n.manifest.requests.includes(e)))throw Y(`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 W(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new W(`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 W?e:Y(`Extension roster is invalid`)});return yield*ve(r,e=>D(function*(){let t=`sha256:${yield*go(yield*I({try:()=>ho(_o(e.definition,e.documents)),catch:()=>Y(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*go(ho([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:Ae(zr)(t),fingerprint:Ae(_n)(r)})}))})}function bo(e){return go(ho({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}function xo(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function So(e){return xo({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function Co(e){return new W(`model`,`rejected`,e)}function wo(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 To(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 Eo(e,t,n){let r=rr(),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)we(t,r);return r}function Do(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 Oo(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`&&!Do(e,a+1,n,i)&&r.push(a)}return r}function ko(e,t,n,r){let i=Oo(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=_a(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function Ao(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 jo(e,t,n,r){let i=ko(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...Ao(e,t,i)}}function Mo(e,t){if(e.at(-1)?.kind===`compaction`)return;let n,r=-1,i=0;for(let t=e.length-1;t>=0;--t){let a=e[t];if(a?.kind===`compaction`){n=Ie(a.model),r=t;let o=e.findIndex(e=>e.id===a.head);i=o>=0?o:t+1;break}}let a=e.flatMap((e,t)=>e.kind===`message`&&t>=i?[e]:[]),o=ya(To(e)).tokens,s=jo(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=Eo(u,e,r);for(let e of d)we(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 No={enabled:!0,maxRetries:3,baseDelayMs:2e3};function Po(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??wa()};return Wt(()=>Promise.resolve((r??Mr)(e,Si(t),i)).then(e=>e.result()),No,i.signal)}function Fo(e){return{systemPrompt:Me,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function Io(e,t,n){let r=e.previousSummary??``,i=t?Vt:It,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${ft(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function Lo(e){return`# Conversation\n${ft(e.turnPrefixMessages)}\n\n# Instructions\n${ui}`}async function Ro(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await Po(e,Fo(r),o,a),c=He(s,i);if(c!==void 0)throw Error(c);return s}function zo(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):Ro(t,n,r,Io(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function Bo(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):Ro(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,Lo(e),`Turn prefix summarization`,r)}function Vo(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.`:wi(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${wi(n.content)}`,i=t===void 0?n.usage:wo(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=wi(t.content),i=t.usage}let a=bt(e.fileOps);return{summary:r+$n(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function Ho(e,t,n,r,i){return Vo(e,await zo(e,t,Math.min(Math.floor(.8*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,r,i),e.isSplitTurn&&e.turnPrefixMessages.length>0?await Bo(e,t,n,i):void 0)}function Uo(e,t,n,r){return _e({try:i=>Ho(e,t,i,r,n),catch:e=>Co(e instanceof Error?e.message:String(e))})}function Wo(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var Go=new WeakMap;function Ko(e){return Go.has(e)}function qo(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return jr(t,M(()=>{Yo(e,r)})).pipe(_(l(i,t)),o(t=>(r.fiber=t,Go.set(e,r),r)))}function Jo(e){let t=e.summary;return e.summary=void 0,t}function Yo(e,t){t.fiber=void 0,t.summary=void 0,Go.get(e)===t&&Go.delete(e)}function Xo(e){return new W(`runtime`,`rejected`,e)}var Zo={handoff:`The compaction handoff failed; the conversation context is unchanged`,handoffResult:`The compaction handoff failed: it returned an invalid result; the conversation context is unchanged`,conflict:`The Session changed during compaction; the conversation context is unchanged`},Qo=class extends W{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,Zo[e]),this.phase=e,this.usage=t}get diagnostic(){return Zo[this.phase]}};function $o(e,t){let n=Un(e,t),r=fr(e),i=[];for(let t of e){let e=Vr(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:Jn(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:xr(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 es(e,t,n){return I({try:()=>wr(e,{sessionId:t,workId:n}),catch:()=>Xo(`Woodstock selected lineage is unavailable`)})}function ts(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return nn([...e,i],r).reduce((e,t)=>e+_a(t),0)}function ns(e,t,n){return C(()=>(kt(e.store,e.sessionId,n.trigger),rs(e,t,n).pipe(ue(M(()=>{yi(e.store,e.sessionId)})))))}function rs(e,t,n){return D(function*(){let r=Mo($o(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*Uo(r,e.model,e.stream,n.instructions),o=yield*os(e,r,a,i.id);return yield*ls(e,t,a,n,i.id,o)})}var is=kn([V({type:Nr(`accepted`),receipt:gr}),V({type:Nr(`discarded_by_policy`)})]),as=R(is);function os(e,t,n,r){return e.handoff===void 0?S(void 0):e.handoff.consume(Wo(t,n,e.sessionId,r)).pipe(p(()=>new Qo(`handoff`,n.usage)),F(e=>{let t=as(e);return t._tag===`Failure`?w(new Qo(`handoffResult`,n.usage)):S(t.success.type===`accepted`?t.success.receipt:void 0)}))}function ss(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=ts(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[Be(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 cs(e,t,n){let r=[...t,n];return{path:r,messages:nn(r,e.workId)}}function ls(e,t,n,r,i,a){let s=ss(e,t,n,r,i,a);return s===void 0?S(void 0):I({try:()=>On(e.store,s),catch:e=>e instanceof W?e.cause===`conflict`?new Qo(`conflict`):e:Xo(`Woodstock compaction append failed`)}).pipe(o(n=>cs(e,t,n)))}function us(e){return e instanceof Qo?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function ds(e,t){return I({try:()=>{Xr(e.store,t)},catch:e=>e instanceof W?e:Xo(`Compaction notice could not be recorded`)})}function fs(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return ds(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:us(n),usage:n instanceof Qo?n.usage:void 0})}function ps(e,t,n){return oe(ns(e,t,n)).pipe(F(t=>t._tag===`Success`?S(t.success):fs(e,n.trigger,t.failure).pipe(N(void 0))))}var ms={trigger:`threshold`,resumesRun:!1};function hs(e,t,n,r){return t.stopped||Ko(e.store)||!Ct(n,e.model.contextWindow,e.settings)?m:r.pipe(F(n=>gs(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function gs(e,t,n){let r=n.at(-1),i=Mo($o(n,e.workId),e.settings);return r===void 0||i===void 0?S(void 0):qo(e.store,t,t=>_s(e,i,r.id,t))}function _s(e,t,n,r){return C(()=>(kt(e.store,e.sessionId,`threshold`),Uo(t,e.model,e.stream).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),ue(M(()=>{yi(e.store,e.sessionId)})))))}function vs(e,t,n,r){return C(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?S(void 0):(t.slot=void 0,oe(L(a).pipe(F(()=>bs(e,i)),F(t=>t===void 0?S(void 0):xs(e,t,n)))).pipe(F(n=>n._tag===`Success`&&n.success!==void 0?S(n.success):(t.stopped=!0,n._tag===`Success`?S(void 0):fs(e,`threshold`,n.failure).pipe(N(void 0)))),ue(M(()=>{Yo(e.store,i)}))))})}function ys(e,t,n){return ds(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(N(void 0))}function bs(e,t){let n=Jo(t);if(n===void 0)return S(void 0);let{result:r,selectionTail:i}=n;return I({try:()=>ln(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof W?e:Xo(`Woodstock compaction head is unavailable`)}).pipe(F(t=>t===`stale`?ys(e,r,`stale`):os(e,n.preparation,r,i).pipe(o(e=>({result:r,selectionTail:i,receipt:e})))),ue(M(()=>{Yo(e.store,t)})))}function xs(e,t,n){return es(e.store,e.sessionId,e.workId).pipe(F(r=>{let i=ss(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?S(void 0):ht(i.tokensAfter,e.model.contextWindow,e.settings)?ys(e,t.result,`insufficient`):I({try:()=>Cn(e.store,i),catch:e=>e instanceof W?e.cause===`conflict`?new Qo(`conflict`):e:Xo(`Woodstock compaction append failed`)}).pipe(F(n=>n===`stale`?ys(e,t.result,`stale`):S(cs(e,r,n))))}))}function Ss(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return S(n);let r=ya(e.messages).tokens;return ht(r,e.model.contextWindow,e.settings)?ps(e,e.path,ms).pipe(o(e=>e??n)):hs(e,t,r,S(e.path)).pipe(N(n))}function Cs(e,t){let n=At(e.message,t.contextWindow),r=rt(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function ws(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function Ts(e,t,n,r){if(!e.settings.enabled)return S(void 0);let i=ht(ya([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?es(e.store,e.sessionId,e.workId):S(void 0)}function Es(e,t,n){return(r,i)=>D(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=ya(r).tokens,s=ht(o,e.model.contextWindow,e.settings),c=yield*vs(e,n,ms,s);if(c!==void 0)return a(c);let l=es(e.store,e.sessionId,e.workId);if(!s){yield*hs(e,n,o,l);return}let u=yield*ps(e,yield*l,ms);return u===void 0?void 0:a(u)})}function Ds(e,t,n){return D(function*(){let r=t,i=t.path.some(({entry:t})=>t.kind===`compaction`&&t.workId===e.workId&&t.data.resumesRun);for(;;){let t={path:r.path,messages:r.messages,newMessageCount:0},a=yield*e.run(t.messages,Es(e,t,n)),o=Cs(a,e.model),s=o.retry&&!i,c=yield*vs(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:ws(c.messages)},i=!0;continue}let l=yield*Ts(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*ps(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:ws(u.messages)},i=!0}})}function Os(e){return D(function*(){let t={scope:yield*P,slot:void 0,stopped:!1};return yield*Ds(e,e.settings.enabled?yield*Ss(e,t):e,t)})}function ks(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?S(`compacted`):ns(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(ce(t=>fs(e,`manual`,t)),F(t=>t===void 0?fs(e,`manual`,void 0).pipe(N(`nothing_to_compact`)):S(`compacted`)))}var As=tn.pipe(H(en(0)),H(Tt(2**53-1))),js=V({reserveTokens:B(As),keepRecentTokens:B(As),backgroundTokens:B(As)}),Ms=V({enabled:B(Xt),reserveTokens:B(As),keepRecentTokens:B(As),backgroundTokens:B(As),modelOverrides:B(hr(Ir,js))}),Ns=R(Ms,{onExcessProperty:`error`});function Ps(e){let t=Ns(e??{});if(t._tag===`Failure`)throw new W(`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??mi.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??mi.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??mi.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??mi.backgroundTokens}}}var Fs={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},Is=class extends W{phase;constructor(e){super(`runtime`,`rejected`,Fs[e]),this.phase=e}get diagnostic(){return Fs[this.phase]}},Ls={model:`model-failed`,tool:`tool-failed`,control:`control-failed`,listener:`listener-failed`},Rs=class extends W{reason;constructor(e,t){super(`runtime`,`rejected`,`Mule rejected the durable command run`,void 0,t),this.reason=e}get diagnostic(){return Ls[this.reason]}};function zs(e){return new Rs(e.phase,e)}function Bs(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+xo({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function Vs(e,t,n,r,i,a,o){let s=e.tools,c=i.modules??[],l=[...c,...a];return s===void 0?c.length>0||o.length>0?w(new Is(`missing`)):S([]):D(function*(){let i={sessionId:t,commandId:n};r!==void 0&&(i={...i,meta:r});let a={sources:s.sources,session:i,sandbox:s.sandbox,onSandboxFailure:r=>pt(e.store,{sessionId:t,commandId:n},r).pipe(te),modules:[...s.modules,...l],tools:o,access:{...s.access,sessionGrants:()=>Tn(e.store,t)?.grants??{}}},c=yield*(yield*st(s.execution===void 0?a:{...a,execution:s.execution}).pipe(p(()=>new Is(`runtime`)))).acquire().pipe(p(()=>new Is(`lease`)));return[c.executeTool,...c.tools]})}function Hs(e,t,n,r,i,a,s){return x(D(function*(){let l=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),u=l.release;u!==void 0&&(yield*me(()=>M(u)));let d=yield*Di(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),h=yield*Vs(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,l,r,i),ee=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),te=yield*hi(e.store,ee,n),ne=t=>Ye(e.store,{sessionId:ee.sessionId,workId:ee.commandId,delivery:t}).pipe(o(e=>e.map(({message:e})=>e)),p(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof W?e.message:`Session control delivery failed`}))),g=t.resume,re=Ps(e.compaction)(d.model),_,v=0;return{run:yield*Os({store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:d.model,stream:d.stream,handoff:a,settings:re,path:t.path,messages:t.messages,resuming:g!==void 0,run:(t,n)=>{v=0;let r=g;g=void 0;let i,a=e=>{if(e.type===`run_end`&&e.outcome===`failed`)return i=e,m;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=d.providerError?.(e.value);if(t!==void 0)return te({...e,value:{...e.value,providerError:t}})}return te(e)},u={model:d.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??Ee,retryAfterMs:d.retryAfterMs,retryable:d.retryable,systemPrompt:l.text,prepareSystemPrompt:()=>(s===void 0?S([]):s()).pipe(o(e=>l.text+e.map(({name:e,text:t})=>`\n\n[extension:${e}]\n${t}`).join(``)),p(e=>({_tag:`MuleError`,phase:`model`,message:`Extension prompt is unavailable`,cause:e}))),messages:t,resume:r,tools:h,getSteeringMessages:()=>ne(`steer`),prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(p(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>(t.type===`retry_finished`&&!t.success&&(v=t.attempt+1),Qn(e.store,ee,Bs(t,d.model),t.turn))};return bi.run(d.stream===void 0?u:{...u,stream:d.stream},a).pipe(c(e=>{if(i===void 0)return m;if(Yn(e)){let t=e.value.modelLimitReason??d.failureReason?.(e.value.message)??So(e.value);return _=(v>1&&e.value.modelLimitReason===void 0&&d.rejection?.(e.value.message)?.code!==`usage-limit-reached`?`The model failed ${String(v)} times on this conversation: ${t}`:t).slice(0,200),te(i,_)}let t=jn(e.cause);return te(i,f(t)?xo({runId:i.run.value,provider:d.model.provider,model:d.model.id}):t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):`runtime:rejected: ${zs(t.value).diagnostic}`)}),p(e=>e.phase===`model`?new W(`model`,`rejected`,e.message,void 0,e):zs(e)))}}),failureReason:_}}))}function Us(e,t,n){return x(D(function*(){let r=yield*Di(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),i=t.command.entry;return yield*ks({store:e.store,sessionId:t.command.sessionId,workId:i.workId,model:r.model,stream:r.stream,handoff:n,settings:Ps(e.compaction)(r.model),path:t.path,instructions:yn(i)?i.instructions:void 0})}))}var Ws=Object.freeze({maxRecoveries:2});function Gs(e){return new W(`runtime`,`rejected`,e)}function Ks(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof Is||e instanceof Rs||e instanceof Qo||e instanceof Ue?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function qs(e,t){return u(`shiitake_run_failed`,$t(t)).pipe(fe({workId:e,reason:`${t.boundary}:${t.cause}`}))}function Js(e,t,n,r){return D(function*(){nr(e.store,n.queue);let i=yield*I({try:()=>Gn(n),catch:()=>Gs(`Agent work payload is invalid`)}),a=yield*ni(e.store,i.work);if(a.abnormalTerminal!==void 0)return{kind:a.abnormalTerminal};let s=r?.incompatibleMigrations()[0];if(s!==void 0)return yield*u(`shiitake_run_contract_changed`).pipe(fe({workId:n.jobId,terminal:`contract_changed: ${s}`})),yield*w(Gs(`contract_changed: ${s}`));let c=new Set(r?.runParticipants().map(([e])=>e)??[]);if(yn(a.command.entry))return yield*Us(e,a,r?.compactionHandoff(c)),yield*xt(e.store,{sessionId:a.command.sessionId,commandFactId:i.work.commandFactId,workId:a.command.entry.workId,outcome:`completed`}),{kind:`completed`};let l=yield*I({try:()=>ke(e.store,i.work.sessionId,i.work.commandFactId,a.command.entry.workId),catch:()=>Gs(`Accepted run origin is unavailable`)}),d={sessionId:a.command.sessionId,workId:a.command.entry.workId,origin:l===null?null:{extensionId:Ae(qn)(l.extensionId),correlation:l.correlation}},f=r===void 0?[]:yield*r.filesForRun(d,c),p=r===void 0?[]:yield*ve([...c],t=>r.modulesForRun(d,new Set([t])).pipe(F(n=>I({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>St.grantAs(e,r))},catch:()=>Gs(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),m=r?.compactionHandoff(c),{run:h,failureReason:ee}=yield*Hs(e,a,{core:f.length===0?t:yield*bo(f.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},p,f,m,r===void 0?void 0:()=>r.promptSections(d,c));switch(h.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:ee??So(h)}}}).pipe(ie(e=>qs(n.jobId,e).pipe(N(Ks(e)))))}var Ys=R(Qt,{onExcessProperty:`error`}),Xs=R(Qr(Xt)),Zs=R(ar,{onExcessProperty:`error`});function Qs(e){if(e.reply===void 0)return;let t=Cr(Zs(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 W(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function $s(e,t){let n=t.mail;return n?.from.kind===`agent`&&n.replyTo.length>0?{agentId:n.from.agentId,sessionId:n.from.sessionId,name:jt(t.meta)?.name??n.from.agentId}:t.continuesWorkId===void 0?void 0:ii(e,t.sessionId,t.continuesWorkId)}function ec(e){let t=t=>({sessionId:U(t.sessionId),requireExistingSession:Cr(Xs(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:Cr(Et(t.command),`Session command is invalid`),origin:Cr(Ys(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:Qs(t),onAccepted:t.onAccepted,continuesWorkId:t.continuesWorkId,meta:t.meta===void 0?void 0:dt(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(on(e.owner,r,a.requestId),t.requireExistingSession&&!be(e.owner,r))throw new W(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&Sn(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&Sn(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested?o.jobId:void 0,c=Ar(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=$s(e.owner,t);n!==void 0&&_i(e.owner,r,c.accepted.commandId,n)}return An(e.owner,r,t.mail),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)=>C(()=>{let i=new Map,a=I({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof W?e:new W(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(k(()=>M(()=>{for(let[t,n]of i)n&&nr(e.owner,t)})),k(()=>i.size>0?e.requestWake:m))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>I({try:()=>({sessionId:U(t),requestId:_r({requestId:n})}),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(F(t=>r(()=>kr(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>I({try:()=>t(e),catch:e=>e instanceof W?e:new W(`contract`,`invalid`,`Session command is invalid`)}).pipe(F(e=>r(t=>t(e),n??`request`)))})}var tc=`core`,nc=`core-report`,rc=256,ic=1048576,ac=512,oc=64,sc=new TextEncoder,cc=R(K(V({name:Ir.pipe(H(Zr(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:Ir.pipe(H(br(1)),H(Er(e=>sc.encode(e).byteLength<=8192)))})).pipe(H(mr(16)))),lc=class extends Error{};function X(e){return e.length<=ac?e:`${e.slice(0,511)}…`}var uc=ri(tr(mt));function dc(e){return e instanceof Oi?e.reason:`${e._tag}: ${e.message}`}function fc(e){return e instanceof Oi||e instanceof ki||e instanceof Ni||e instanceof Ai}function pc(e,t){let r=jn(t);if(ae(r)){let t=r.value;return t instanceof Oi?X(t.reason):X(fc(t)?`${e}: ${dc(t)}`:`${e} failed`)}let i=n(ei(t));return ae(i)?i.value instanceof Error?X(i.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${i.value.message}`):X(`${e} defect`):X(`${e} was interrupted`)}function mc(e){let t=jn(e);return f(t)||t.value instanceof Oi}function Z(e,t){return new ki({reason:e,message:t})}function hc(e,t){return e.length>=1&&e.length<=rc?S(e):w(Z(`bound`,`${t} must be 1..256 characters`))}function gc(e){let t=X(e.message);if(e instanceof Ai)switch(e.reason){case`invalid`:return new W(`contract`,`invalid`,t);case`conflict`:return new W(`store`,`conflict`,t);case`not_found`:return new W(`store`,`rejected`,t);case`rejected`:return new W(`extensions`,`rejected`,t)}if(e instanceof Ni)switch(e.reason){case`invalid`:return new W(`contract`,`invalid`,t);case`conflict`:return new W(`contract`,`conflict`,t);case`closed`:return new W(`runtime`,`closed`,t)}return e.reason===`bound`?new W(`contract`,`invalid`,t):new W(`store`,`unavailable`,t)}function _c(e){let{owner:t}=e,n=new WeakMap,r=new Map,a=new Set,c,l=new Set,p=new Set,h,g=e=>Object.freeze({extensionId:e}),v=e=>F(Mi,t=>t.extensionId===e?m:j(Error(`Extension read used another extension's context`))),y=e=>F(ji,t=>{let r=n.get(t);return r?.extensionId===e?S(r):j(Error(`Extension write used outside its own core transaction`))}),b=e=>I({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),x=(e,t)=>e.admitted.grants.has(t)?m:w(Z(`unavailable`,`Extension is not granted ${t}`));function oe(e,n,r){let i=e.admitted.id,a=mn(tr(r.schema)),s=ci(r.schema),l=e=>{let t=a(e);return t._tag===`Failure`?w(Z(`decode`,`Stored ${n} record is invalid`)):S(t.success)};return Object.freeze({peek:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);let o=at(t,i,n,r);if(o===void 0)return E();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return A(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>oc)throw Z(`bound`,`Page limit must be 1..64`);return Pr(t,i,n,r).map(e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success})},get:r=>v(i).pipe(_(x(e,`state`)),_(b(()=>at(t,i,n,r))),F(e=>e===void 0?S(E()):l(e).pipe(o(A)))),page:r=>v(i).pipe(_(x(e,`state`)),_(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=oc?m:w(Z(`bound`,`Page limit must be 1..64`))),_(b(()=>Pr(t,i,n,r))),F(e=>ve(e,l))),put:a=>y(i).pipe(_(x(e,`state`)),_(C(()=>{let e=s(a);if(e._tag===`Failure`)return w(Z(`encode`,`The ${n} record does not match its schema`));let o=JSON.stringify(e.success);if(sc.encode(o).byteLength>ic)return w(Z(`bound`,`The ${n} record exceeds 1 MiB`));let c=r.index?.(a)??null;return le([hc(r.key(a),`A record key`),c===null?S(null):hc(c,`A record index`)]).pipe(F(([e,r])=>b(()=>{Ot(t,i,n,e,r,o)})))}))),remove:r=>y(i).pipe(_(x(e,`state`)),_(b(()=>{Oe(t,i,n,r)})))})}function se(e,n,r){let i=e.admitted.id,a=mn(tr(r.schema)),o=ci(r.schema),s=()=>{if(!l.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>rc)throw Z(`bound`,`A record key must be 1..256 characters`);return e},u=e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success};return Object.freeze({get:e=>{s();let r=at(t,i,n,c(e));return r===void 0?E():A(u(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>oc)throw Z(`bound`,`Page limit must be 1..64`);return Pr(t,i,n,e).map(u)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${n} record does not match its schema`);let l=JSON.stringify(a.success);if(sc.encode(l).byteLength>ic)throw Z(`bound`,`The ${n} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),Ot(t,i,n,c(r.key(e)),u,l)},remove:e=>{s(),Oe(t,i,n,c(e))}})}function ce(e){let n=e.admitted.id;return Object.freeze({set:(r,i)=>y(n).pipe(k(()=>x(e,`timers`)),k(()=>hc(r,`A timer key`)),k(()=>Number.isSafeInteger(i)&&i>=0?m:w(Z(`bound`,`A timer instant is invalid`))),F(e=>b(()=>{Kr(t,n,r,i),e.timersChanged=!0}))),cancel:r=>y(n).pipe(k(()=>x(e,`timers`)),F(e=>b(()=>{Zt(t,n,r),e.timersChanged=!0}))),read:r=>v(n).pipe(_(x(e,`timers`)),_(b(()=>an(t,n,r))),o(ne))})}function ue(n){let r=n.admitted.id,i=(i,a)=>y(r).pipe(k(()=>x(n,`attention`)),F(n=>I({try:()=>{U(i),a(),gn(t,i,e.readQueueHead(i)),n.observed.add(i)},catch:e=>e instanceof ki&&e.reason===`session_absent`?e:e instanceof W&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,n)=>{let a=R(Mn,{onExcessProperty:`error`})(n.waitingOn===void 0?n:{...n,inbox:!1});return a._tag===`Failure`?w(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!be(t,e))throw Z(`session_absent`,`Attention Session is absent`);li(t,e,r,a.success)})},awaitsPerson:e=>v(r).pipe(k(()=>x(n,`attention`)),_(b(()=>pi(t,e)))),clear:(e,n)=>hc(n,`An attention id`).pipe(_(i(e,()=>{wn(t,e,r,n)})))}}function O(e){let t=e.admitted.id;return n=>y(t).pipe(F(r=>e.admitted.grants.has(`send`)?I({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 Ni({reason:e instanceof W?e.cause===`conflict`?`conflict`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof W?e.message:`Session command is invalid`})}):w(new Ni({reason:`closed`,message:`Extension is not granted send`}))))}function de(r,i,a){return C(()=>{let s,c,l=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let t=g(r.admitted.id);c={extensionId:r.admitted.id,admit:e,observed:new Set,timersChanged:!1},n.set(t,c),p.add(r.admitted.id);let a=h;h=c;try{s=pe(i.pipe(d(ji,t),d(Mi,t)))}finally{h=a,n.delete(t),p.delete(r.admitted.id)}if(Lr(s))throw l;return s.value},a).pipe(o(()=>{if(s===void 0)throw Error(`Extension transaction returned no exit`);return s}),ie(e=>s!==void 0&&Lr(s)?S(s):w(e)),k(n=>Yn(n)&&c!==void 0?D(function*(){for(let e of c?.observed??[])nr(t,e);a===`request`&&c?.timersChanged===!0&&(yield*e.requestWake)}):m))})}function me(n){let r=``;for(let i=0;i<dr;i+=oc){let i=Pt(t,n,r);for(let n of i)gn(t,n,e.readQueueHead(n)),queueMicrotask(()=>{nr(t,n)});let a=i.at(-1);if(i.length<oc||a===void 0)return;r=a}}function P(e,n,r,i){let a=Date.now();e.status=`stopped`,e.reason=n,e.stoppedAt=a;let o=I({try:()=>{let r=()=>{Pn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:a,revision:e.admitted.revision}),me(e.admitted.id)};i===`own-transaction`?t.transactionSync(r):r()},catch:t=>new W(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)});return D(function*(){let t=yield*T(o);return yield*u(`shiitake_extension_stopped`).pipe(fe({extensionId:e.admitted.id,reason:n,cause:r===void 0?null:$t(r),durable:Yn(t)})),yield*t})}function ge(e,n,r){e.status=`stopped`,e.reason=n,e.stoppedAt=Date.now();let i=()=>{Pn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:e.stoppedAt,revision:e.admitted.revision}),me(e.admitted.id)};try{r===`own-transaction`?t.transactionSync(i):i()}catch(t){throw new W(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)}}function _e(e,n,r){let i=t=>{if(h?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return U(t),h},a=a=>{i(a);let o=Ur(t,a,e.admitted.id,n)??no(r,r.initial);if(sc.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=R(tr(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));Kn(t,o,e.admitted.id,n,no(r,l)),c.observed.add(o)}})}function ye(e){let n=new Set;return Object.freeze({collection:(t,n)=>oe(e,t,n),updateCollection:(t,n)=>se(e,t,n),document:(t,n)=>_e(e,t,n),update:r=>{let i=e.admitted.id;if(e.status!==`running`||!e.admitted.grants.has(`state`)||l.has(i)||p.has(i)||c===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let e=t.transactionSync(()=>{l.add(i);try{return Fr(r,void 0)}finally{l.delete(i)}});for(let e of n)nr(t,e);return e}catch(t){if(!(t instanceof Wr))throw t;let n=t.message;throw ge(e,n,`own-transaction`),new Oi({reason:n})}finally{n.clear()}},observeUpdate:t=>{if(!l.has(e.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);n.add(U(t))},context:Object.freeze({manifest:e.admitted.manifest,revision:e.admitted.revision,grants:Object.freeze([...e.admitted.grants]),send:O(e),timers:ce(e),attention:ue(e),isObserved:n=>e.status===`running`&&zt(t,n),sessionPosition:n=>v(e.admitted.id).pipe(_(x(e,`state`)),_(b(()=>{let e=U(n);if(!be(t,e))throw Z(`unavailable`,`Session timeline is unavailable`);return Dn(t,{sessionId:e})?.newestSequence??0}))),hasPendingSteer:n=>v(e.admitted.id).pipe(_(x(e,`run_tools`)),_(b(()=>wt(t,U(n.sessionId),n.workId)))),workSender:n=>v(e.admitted.id).pipe(_(x(e,`run_tools`)),_(b(()=>ii(t,U(n.sessionId),n.workId)??null))),hasSuccessfulToolResult:(n,r)=>v(e.admitted.id).pipe(_(x(e,`run_tools`)),_(b(()=>In(t,U(n.sessionId),n.workId,r)))),observe:t=>y(e.admitted.id).pipe(o(e=>{e.observed.add(t)})),transact:t=>(e.status===`running`?de(e,t,`request`).pipe(te):w(new Oi({reason:e.reason??`Extension is stopped`}))).pipe(F(t=>{if(Yn(t))return S(t.value);if(!mc(t.cause))return re(t.cause);let n=pc(`transact`,t.cause);return P(e,n,t.cause,`own-transaction`).pipe(F(()=>w(new Oi({reason:n}))))}))})})}function Se(e){let{id:n,definition:r,revision:i}=e.admitted,a=r.state.version,o=tt(t,n);if(o!==void 0&&o.version>a)throw new W(`extensions`,`conflict`,`Stored ${n} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=Kt(t,n).map(e=>({collection:e.collection,key:e.key,value:uc(e.valueJson)}));for(let t=o.version;t<a;t+=1){let i=r.state.migrations[t];if(i===void 0)throw new W(`extensions`,`state_reset_required`,`State reset required for ${n}: stored version ${String(o.version)}, declared version ${String(a)}. An operator must authorize the reset; stored records have not been changed.`);try{e=e.flatMap(e=>i(e))}catch(e){throw new lc(`Failed ${n} state migration from ${String(t)}`,{cause:e})}}Mt(t,n);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new lc(`Migrated ${n} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new lc(`Migrated ${n} ${i.collection} record is invalid`);Ot(t,n,i.collection,i.key,a.success,JSON.stringify(i.value))}}xe(t,n,a,i)}function Ce(e,t,n=!1){let r=ye(e);return D(function*(){let i=yield*sn(t);e.scope=i;let a=yield*C(()=>e.admitted.definition.activate(r)).pipe(d(nt,i),T);if(Yn(a)){e.hooks=a.value;return}if(yield*$e(i,a),n)return yield*w(new W(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${Or(a.cause)}`));yield*P(e,pc(`activation`,a.cause),a.cause,`own-transaction`)})}let L=e=>[...r.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function we(e){return Object.freeze({id:e.admitted.id,version:e.admitted.manifest.version,revision:e.admitted.revision,status:e.status,reason:e.reason,stoppedAt:e.stoppedAt})}function Te(e){return e.status===`running`&&e.hooks!==void 0&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))}function Ee(e,t,n){return T(n.pipe(d(Mi,g(e.admitted.id)))).pipe(F(n=>Yn(n)?S(A(n.value)):P(e,pc(t,n.cause),n.cause,`own-transaction`).pipe(N(E()))))}let De=(e,t,n)=>Lr(n)?P(e,pc(t,n.cause),n.cause,`own-transaction`):m;function ke(e){return I({try:()=>{t.transactionSync(()=>{Se(e);for(let[n,r]of Object.entries(e.admitted.documents))Ze(t,{extensionId:e.admitted.id,name:n,initialJson:no(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(k(()=>M(()=>{delete e.stateResetRequired})),N(!0),ie(t=>t instanceof W?t.cause===`state_reset_required`?(e.stateResetRequired=t,P(e,X(t.message),or(t),`own-transaction`).pipe(N(!1))):w(t):(t instanceof lc&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&a.add(e.admitted.id),P(e,X(t instanceof Error?`migration: ${t.message}`:`migration failed`),Hr(t),`own-transaction`).pipe(N(!1)))))}return D(function*(){let n=yield*rn();function l(e,r){return D(function*(){let i=cn(t,e.id),a=i?.status===`stopped`&&i.revision===e.revision,o={admitted:e,hooks:void 0,status:a?`stopped`:`running`,reason:a?i.reason:null,stoppedAt:a?i.stoppedAt:null};return yield*I({try:()=>{e.grants.has(`settled`)&&t.transactionSync(()=>{z(t,e.id)===void 0&<(t,e.id,z(t,`core`)??0)})},catch:()=>new W(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*ke(o))||a?r?yield*w(new W(`extensions`,`rejected`,`Extension ${e.id} cannot start: ${o.reason??`stopped`}`)):o:(yield*I({try:()=>{t.transactionSync(()=>{Pn(t,e.id,{status:`running`,reason:null,stoppedAt:null,revision:e.revision}),me(e.id)})},catch:()=>new W(`store`,`unavailable`,`Extension status is unavailable`)}),yield*Ce(o,n,r),o)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(i(()=>$e(n,Sr)));r.set(t.id,e)}yield*I({try:()=>{t.transactionSync(()=>{let n=je(t,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of n)me(e)})},catch:()=>new W(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:e=>D(function*(){let n=e.filter(e=>{let t=r.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(n.length>0)return yield*w(new W(`extensions`,`rejected`,`Extensions ${n.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,s=C(()=>ve([...o.values()].reverse(),e=>T(e.scope===void 0?m:$e(e.scope,Sr)),{concurrency:1}).pipe(k(()=>M(()=>{for(let t of e)r.has(t.id)||a.delete(t.id)})),F(qr)));yield*D(function*(){for(let t of e)r.has(t.id)||o.set(t.id,yield*l(t,!0))}).pipe(i(()=>s));let c=new Set(e.map(({id:e})=>e)),u=!1;return{discard:C(()=>u?m:(u=!0,s)),apply:D(function*(){if(u)return yield*w(new W(`extensions`,`rejected`,`Roster transition already settled`));yield*I({try:()=>{t.transactionSync(()=>{for(let[e,n]of r)c.has(n.admitted.id)||xi(t,e);let n=je(t,e.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of n)me(e)})},catch:()=>new W(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of r)c.has(t.admitted.id)||(t.scope!==void 0&&(yield*$e(t.scope,Sr)),r.delete(e),a.delete(t.admitted.id));for(let[e,t]of o)r.set(e,t);u=!0})}}),runParticipants:()=>[...r.values()].filter(Te).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...a],modulesForRun:(e,t)=>ve(L(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?S(E()):Ee(n,`moduleForRun`,C(()=>r(e))).pipe(o(s))}).pipe(o(e=>e.flatMap(he))),filesForRun:(e,t)=>D(function*(){let n=L(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*P(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*w(new W(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*Ee(n,`filesForRun`,C(()=>r(e)));return f(i)?yield*w(new W(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...ee(i.value,()=>[])])}),promptSections:(e,t)=>D(function*(){let n=[],r=0;for(let i of L(`prompt`)){if(!t.has(i.admitted.id))continue;let a=i.hooks?.prompt;if(a===void 0)return yield*P(i,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*w(new W(`extensions`,`rejected`,`Extension prompt is unavailable`));let o=yield*T(pr(()=>a(e)).pipe(d(Mi,g(i.admitted.id))));if(Lr(o))return yield*P(i,pc(`prompt`,o.cause),o.cause,`own-transaction`),yield*w(new W(`extensions`,`rejected`,`Extension prompt failed`));let s=cc(o.value),c=s._tag===`Success`?s.success:[];if(r+=c.reduce((e,t)=>e+sc.encode(t.text).byteLength,0),s._tag===`Failure`||new Set(c.map(({name:e})=>e)).size!==c.length||r>65536)return yield*P(i,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*w(new W(`extensions`,`rejected`,`Extension prompt is invalid`));n.push(...[...c].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${i.admitted.id}.${e.name}`,text:e.text})))}return n}),compactionHandoff:e=>L(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>L(`settled`).map(e=>({id:e.admitted.id,cursor:z(t,e.admitted.id)??0})),deliverSettled:(e,n)=>ve(L(`settled`),r=>C(()=>{let i=z(t,r.admitted.id)??0;if(n<=i)return m;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return de(r,(o===void 0||a.length===0?m:o(a)).pipe(_(M(()=>{lt(t,r.admitted.id,n)}))),`reconcile`).pipe(F(e=>De(r,`onSettled`,e)))}),{discard:!0}),fireDueTimers:e=>D(function*(){let n=L(`timers`).map(({admitted:e})=>e.id),i=Ge(t,n,e,oc);for(let n of i){let i=r.get(n.extensionId);if(i?.status!==`running`)continue;let a=i.hooks?.onTimer,o=yield*de(i,C(()=>an(t,n.extensionId,n.key)===n.dueAt?(Zt(t,n.extensionId,n.key),a===void 0?m:a({key:n.key,dueAt:n.dueAt,firedAt:e})):m),`reconcile`);yield*De(i,`onTimer`,o)}return i.length===oc}),timerWake:e=>dn(t,L(`timers`).map(({admitted:e})=>e.id),e),project:e=>{let t={};for(let n of r.values()){let r=n.admitted.grants.has(`projection`),i=n.admitted.grants.has(`commands`)?n.admitted.definition.catalog:void 0;if(!r&&i===void 0)continue;let a=n.admitted.revision,o=n.admitted.definition.contract.projection,s=n.hooks?.project;if(n.status===`running`&&n.hooks!==void 0){let l=!r||s===void 0||o===null?A(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=Fr(()=>s(e),void 0);if(ae(r)){let e=ci(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=R(mt)(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=Ae(mt)(Fr(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?A(t):(ge(n,X(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),E())})();if(ae(l)){t[n.admitted.id]=Object.freeze(i===void 0?{status:`running`,revision:a,value:l.value}:{status:`running`,revision:a,value:l.value,catalog:i});continue}}t[n.admitted.id]=Object.freeze({status:`stopped`,revision:a,reason:n.reason??`Extension did not activate`})}return Object.freeze(t)},call:(e,t,n,i,a)=>D(function*(){let o=r.get(t);if(o?.admitted.grants.has(`commands`)!==!0)return yield*w(new W(`extensions`,`unavailable`,`Extension is unavailable`));if(o.status!==`running`||o.hooks===void 0)return yield*w(o.stateResetRequired??new W(`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*w(new W(`contract`,`invalid`,`Extension command is unknown`));let l=e.scope===`session`?yield*I({try:()=>U(e.sessionId),catch:()=>new W(`contract`,`invalid`,`Session id is invalid`)}):null,u=o.hooks.commands.get(n);if(u===void 0)return R(c.input,{onExcessProperty:`error`})(i)._tag===`Failure`?yield*w(new W(`contract`,`invalid`,`Extension command input is invalid`)):(yield*P(o,`command ${n} has no handler`,void 0,`own-transaction`),yield*w(new W(`extensions`,`unavailable`,`Extension is stopped`)));let d=u(a===void 0?{sessionId:l,input:i}:{sessionId:l,input:i,caller:a});if(d._tag===`Failure`)return yield*w(new W(`contract`,`invalid`,`Extension command input is invalid`));let f=yield*de(o,d.success(),`request`);if(Yn(f))return f.value;let p=jn(f.cause);if(ae(p)&&!mc(f.cause))return yield*w(gc(p.value));let m=pc(`command ${n}`,f.cause);return yield*P(o,m,f.cause,`own-transaction`),yield*w(new W(`extensions`,`unavailable`,`Extension ${t} is stopped: ${m}`))}),list:()=>[...r.values()].map(we),resume:i=>D(function*(){let a=r.get(i);return a===void 0?yield*w(new W(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*I({try:()=>{t.transactionSync(()=>{Pn(t,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),me(a.admitted.id)})},catch:()=>new W(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*ke(a))&&(yield*Ce(a,n)),yield*e.requestWake),we(a))}),close:$e(n,Sr)};return Object.freeze(u)})}var vc=64;function Q(e){return new W(`runtime`,`rejected`,e)}function yc(e,t,n){return D(function*(){let r=yield*bc(t),i=t.outcome===`cancelled`?``:yield*gt(e,r.work),a=yield*Se(e,r.work,t.outcome),o=t.outcome===`completed`||t.outcome===`cancelled`?void 0:yield*er(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 bc(e){return I({try:()=>Gn(e),catch:()=>Q(`Agent work payload is invalid`)})}function xc(e,t){return e.fanOut(t).pipe(p(()=>Q(`Agent reply fan-out is unavailable`)))}function Sc(e,t,n){return t===void 0?m:D(function*(){let r=yield*bc(n);(r.mail?.replyTo.length??0)!==0&&(yield*xc(t,yield*yc(e,n,I({try:()=>hn(e,r.work.sessionId,r.work.commandFactId),catch:()=>Q(`Session attention is unavailable`)}))))})}function Cc(e,t,n,r){return n===void 0?m:D(function*(){let i=yield*bc(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*I({try:()=>$r(e,i.work.sessionId),catch:()=>Q(`Session delegator is unavailable`)});if(o===void 0)return;let s=a?.reply===void 0?a?.from:void 0;s!==void 0&&!(s.kind===`agent`&&o.replyTo.some(({agentId:e})=>e===s.agentId))||(yield*xc(n,{...yield*yc(e,r,I({try:()=>Hn(e,i.work.sessionId,o.replyTo),catch:()=>Q(`Session attention is unavailable`)})),delegator:o}))})}function wc(e,t,n,r){return ve(r,(i,a)=>D(function*(){!r.slice(a+1).some(({job:e})=>e.queue===i.job.queue)&&!(yield*Oc(e,i.job))&&(yield*Cc(e,t,n,i.job)),yield*I({try:()=>{lt(e,nc,i.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function Tc(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?m:D(function*(){let r=yield*I({try:()=>Gn(t),catch:()=>Q(`Agent work payload is invalid`)});yield*xt(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function Ec(e,t,n){return D(function*(){let r=yield*I({try:()=>Gn(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*Ve(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(Dr({work:{...e,recovery:Ws}}))}})})}function Dc(e){return e===void 0?m:e.drainOutbox().pipe(p(()=>Q(`Agent reply delivery is unavailable`)))}function Oc(e,t){return D(function*(){let n=yield*I({try:()=>Gn(t),catch:()=>Q(`Agent work payload is invalid`)}),i=yield*I({try:()=>ti(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return i&&(yield*r(`shiitake_settlement_session_refused`).pipe(fe({workId:t.jobId}))),i})}function kc(e,t){let n=Gn(t.job),r=ti(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:ke(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):Ne(e,n.work.sessionId,n.work.commandFactId,t.job.jobId);return Object.freeze({sequence:t.sequence,sessionId:n.work.sessionId,workId:t.job.jobId,outcome:t.job.outcome,terminal:r.terminal,toolCalls:r.toolCalls,origin:r.origin===null?null:Object.freeze({extensionId:Ae(qn)(r.origin.extensionId),correlation:r.origin.correlation})})}function Ac(e,t,n,r){return ve(r,r=>D(function*(){nr(e,r.job.queue),(yield*Oc(e,r.job))||(yield*Tc(e,r.job),yield*Ec(e,t,r.job),yield*Sc(e,n,r.job)),yield*I({try:()=>{lt(e,tc,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function jc(e){return D(function*(){if((yield*e.watchdog.tick()).status===`busy`)return yield*w(Q(`Runtime reconciliation is already active`));let t=yield*I({try:()=>z(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),n=yield*I({try:()=>z(e.store,`core-report`)??t,catch:()=>Q(`Settled cursor is unavailable`)}),r=e.extensions.settledConsumers(),i=Math.min(t,n,...r.map(({cursor:e})=>e)),a=yield*e.watchdog.readSettled(vc,i),o=yield*T(Ac(e.store,e.watchdog,e.mailRoom,a.filter(({sequence:e})=>e>t))),s=yield*I({try:()=>z(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),c=yield*I({try:()=>a.filter(({sequence:e})=>e<=s).map(t=>kc(e.store,t)),catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(c,s);let l=yield*T(wc(e.store,e.watchdog,e.mailRoom,a.filter(({sequence:e})=>e>n&&e<=s))),u=yield*e.extensions.fireDueTimers(Date.now());if((a.length===vc||u)&&(yield*e.requestWake),yield*Dc(e.mailRoom),Lr(o))return yield*re(o.cause);if(Lr(l))return yield*re(l.cause)}).pipe(p(e=>e instanceof W?e:Q(`Runtime reconciliation failed`)))}function $(e){return new W(`runtime`,`rejected`,e)}function Mc(e,n,r,a){return D(function*(){if(e.hostJobs?.lane==="default")return yield*w($(`Host lane conflicts with Agent work`));let s=`open`,c,l,d=Fe(!1),f=e=>M(()=>{s===`open`&&(c??=e)}),ee=C(()=>s===`open`?(s=`closing`,l=c,d.open):m).pipe(y),ne={},g={current:void 0},v=e,b,x=!1,ae=C(()=>ne.requestWake??w($(`Runtime host is unavailable`))),oe={current:void 0},se=new Set,T=new Map,E={owner:e.store,isAlive:()=>S(!1),executor:{execute:t=>de(M(()=>{let n=t.lane===e.hostJobs?.lane?{kind:`host`,lane:t.lane,jobId:t.jobId}:{kind:`session`,sessionId:t.queue,commandId:t.jobId};T.set(n.kind===`host`?`host`:`serial`,n),n.kind===`session`&&se.add(t.queue),yt(e.store)}),()=>t.lane===e.hostJobs?.lane?oe.current?.execute(t)??w(new Ei(`execution_failed`)):D(function*(){let r=b;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;v={...n,...r.configuration},b=void 0}return yield*Js(v,n,t,g.current)}).pipe(ce(e=>u(`configuration_apply_failed`,e)),p(()=>new Ei(`execution_failed`))),()=>M(()=>{t.lane!==e.hostJobs?.lane&&se.delete(t.queue),T.delete(t.lane===e.hostJobs?.lane?`host`:`serial`),yt(e.store)}))},wake:{recompute:()=>ae.pipe(p(()=>new Ei(`wake_unavailable`)))},project:t=>{oi(e.store,t,Date.now())}},O=yield*(e.hostJobs===void 0?Ti(E):Ti({...E,concurrentLane:e.hostJobs.lane}).pipe(k(t=>M(()=>{oe.current=e.hostJobs?.open(t)})))).pipe(p(()=>$(`Watchdog is unavailable`))),fe=()=>({core:n,extensions:[...g.current?.runParticipants()??[]]});yield*I({try:()=>Ps(e.compaction),catch:e=>e instanceof W?e:$(`Compaction settings are unavailable`)});let A=yield*I({try:()=>ot(e.storagePressure),catch:e=>e instanceof W?e:$(`Storage budget is unavailable`)}),pe=ec({owner:e.store,admitNew:A.admitNew,hostMeta:e.meta,contract:fe,enqueue:(e,t)=>{let n={work:{...e,recovery:Ws}};O.transactional.enqueueAcceptedJob(Dr(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>O.transactional.readQueueHead(e),commit:e=>C(()=>ne.commit===void 0?w($(`Runtime host is unavailable`)):ne.commit(e)),requestWake:ae});yield*I({try:()=>{Je(e.store),z(e.store,`core`)===void 0&&e.store.transactionSync(()=>{lt(e.store,tc,0)}),z(e.store,`core-report`)===void 0&&e.store.transactionSync(()=>{lt(e.store,nc,z(e.store,`core`)??0)})},catch:()=>new W(`store`,`unavailable`,`Extension store is unavailable`)});let j=yield*_c({owner:e.store,readQueueHead:e=>O.transactional.readQueueHead(e),door:pe,admitted:r,requestWake:ae});g.current=j;let me=jc({watchdog:O,store:e.store,extensions:j,requestWake:ae,mailRoom:a}).pipe(ce(f)),N=D(function*(){let t=yield*O.hasPendingWork,n=Date.now(),r=yield*I({try:()=>[z(e.store,`core`)??0,z(e.store,`core-report`)??0,...j.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*O.readSettled(1,Math.min(...r))).length>0,o=yield*I({try:()=>j.timerWake(n),catch:()=>$(`Extension timers are unavailable`)}),s=a===void 0?void 0:yield*a.nextWakeAt().pipe(p(()=>$(`Reply retry wake is unavailable`))),c=o.nextWakeAt===null?s??null:s===void 0?o.nextWakeAt:Math.min(o.nextWakeAt,s);return{pending:t||i||o.due||s!==void 0&&s<=n,nextWakeAt:c}}),he=yield*e.runtime.bind({reconcile:me,pendingWork:N.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(i(()=>j.close.pipe(te))),P=C(()=>s===`open`?t(he.requestWake.pipe(ie(f)),d.await):m);return ne.requestWake=P,ne.commit=he.commit,yield*he.requestWake.pipe(i(()=>le([he.close,j.close]).pipe(te))),Object.freeze({prepareConfiguration:e=>D(function*(){if(s!==`open`||x||b!==void 0)return yield*w($(`A configuration change is already pending, or the Agent is closing`));x=!0;let t=yield*yo(e.extensions).pipe(F(e=>j.stage(e)),i(()=>M(()=>{x=!1}))),n=!1;return{commit:I({try:()=>{if(n||s!==`open`)throw $(`Configuration preparation is no longer available`);b={configuration:e,apply:t.apply},n=!0,x=!1},catch:e=>e instanceof W?e:$(`Configuration commit failed`)}),discard:C(()=>n?m:(n=!0,x=!1,t.discard))}}),activeSessions:M(()=>[...se]),runningWork:t=>O.read(t).pipe(o(t=>t.status===`found`?T.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`)??null:null),p(e=>new W(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:j,commit:he.commit,assertOpen:C(()=>s===`open`?m:w(new W(`runtime`,`closed`,`Shiitake is closed`))),beginClose:ee,door:pe,createSessionWithinTransaction:t=>Wn(e.store,t,A.admitNew),stageSessionGrantsWithinTransaction:(t,n)=>{vi(e.store,t,n)},storage:A,recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>O.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(O.transactional.readQueueHead(e).state!==`idle`)throw new W(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof W?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>O.cancel({jobId:e,cancellationId:t}).pipe(F(e=>e.status===`recorded`||e.status===`replayed`?m:w($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>O.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>O.transactional.readQueueHead(e),requestWake:P,close:ee.pipe(_(h(he.close,{onFailure:e=>j.close.pipe(_(l===void 0?re(e):w(l))),onSuccess:()=>j.close.pipe(_(l===void 0?m:w(l)))})),ue(M(()=>{s=`closed`})))})})}var Nc=e({openRuntimeCore:()=>Pc});function Pc(e,t){return D(function*(){let n=yield*yo(e.extensions),r=yield*bo([]);yield*di(e.store);let i=yield*Mc(e,r,n,t),a=Qa(e,i),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:Da(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(_(Nt(e.store,t,n))),activeSessions:i.activeSessions,acceptMail:(e,n,r,a,o)=>eo(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);v(t.postMail(e))}),o)})})}export{wa as n,Pc as openRuntimeCore,ya as r,Nc as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./rolldown-runtime-hePW80VL.js";import{$ as t,Bn as n,F as r,G as i,Gr as a,I as o,Jn as s,K as c,O as l,P as u,Q as d,Qn as f,R as p,St as m,V as h,Xn as ee,Y as te,Yn as g,Zn as ne,_ as re,a as _,at as v,bt as ie,c as y,ct as b,d as ae,dt as x,er as S,et as oe,ft as C,g as w,gt as se,h as T,ht as ce,i as le,ir as E,j as D,m as ue,mi as O,mt as k,n as de,o as fe,or as A,ot as pe,p as j,pt as M,r as me,s as N,sr as he,st as P,t as ge,vt as _e,w as ve,xt as ye,y as F,yt as I}from"./Effect-BY0T-p9d.js";import{$ as be,$a as xe,$i as Se,$n as L,$r as R,$t as Ce,A as we,Aa as Te,Ai as Ee,An as De,Ar as z,At as Oe,B as ke,Br as Ae,Bt as je,C as Me,Ct as Ne,D as Pe,Dt as Fe,E as Ie,En as Le,Er as Re,Et as ze,F as Be,Fa as Ve,Fn as He,Fr as Ue,Ft as We,G as Ge,Gi as Ke,Gr as qe,Gt as Je,H as Ye,Ht as Xe,I as Ze,Ia as Qe,Ir as $e,It as et,J as tt,Ja as nt,Jn as rt,Jr as it,Jt as at,Ka as ot,Kn as st,Kr as ct,Kt as lt,L as ut,La as dt,Lr as ft,Lt as pt,M as mt,Ma as ht,Mn as gt,Mr as _t,Mt as vt,N as yt,Na as bt,Ni as xt,Nr as St,Nt as Ct,O as wt,Or as B,Ot as Tt,P as Et,Pr as Dt,Pt as Ot,Q as kt,Qa as At,Qn as jt,Qt as Mt,R as Nt,Ra as Pt,Rn as Ft,Rt as It,S as Lt,Sn as Rt,St as zt,T as Bt,Tn as Vt,Tt as Ht,U as Ut,Ut as Wt,V as Gt,Vi as Kt,Vr as qt,Vt as Jt,W as Yt,Wa as Xt,Wn as Zt,Wr as Qt,Wt as V,X as $t,Xa as en,Xn as tn,Xr as nn,Xt as rn,Y as an,Ya as on,Yi as sn,Yn as H,Yt as cn,Z as ln,Zn as un,Zt as dn,_ as fn,_a as pn,_i as mn,_n as hn,_t as gn,a as _n,an as vn,ar as yn,at as bn,b as xn,bn as Sn,bt as Cn,c as wn,ca as Tn,ct as En,d as Dn,di as U,dn as On,dt as kn,ei as An,en as jn,eo as Mn,et as Nn,f as Pn,fi as Fn,ft as In,g as Ln,gn as Rn,gr as zn,gt as Bn,h as Vn,hi as Hn,hn as Un,ht as Wn,i as Gn,ia as W,in as Kn,it as qn,j as Jn,ja as Yn,jn as Xn,jt as Zn,k as Qn,kn as $n,kr as er,kt as tr,l as nr,ln as rr,lr as ir,lt as ar,m as or,mi as sr,mn as cr,mt as lr,n as ur,na as dr,nn as fr,no as pr,nt as mr,o as hr,oa as gr,oi as _r,on as vr,ot as yr,p as br,pi as xr,pn as Sr,pr as Cr,pt as wr,q as Tr,qa as Er,qn as Dr,qr as G,qt as Or,r as kr,ra as Ar,ri as K,rr as jr,rt as Mr,s as Nr,sa as q,si as Pr,sn as Fr,st as Ir,t as Lr,ti as Rr,tn as zr,tr as Br,tt as Vr,u as Hr,ua as Ur,un as Wr,ut as Gr,v as Kr,vi as qr,vn as Jr,vr as Yr,vt as Xr,w as Zr,wn as Qr,wt as $r,x as ei,xn as ti,xr as ni,xt as ri,y as ii,yn as ai,yt as oi,z as si,za as ci,zn as li,zt as ui}from"./extension-hook-CBuX_bUG.js";import{l as di,m as fi,p as pi}from"./preload-helper-DY31Aviq.js";import{d as mi,f as hi,u as gi}from"./index-HgPChePI.js";import{a as _i,i as vi,n as yi,o as bi,r as xi,t as Si}from"./extensions-DEfvRHbZ.js";var Ci=gr(()=>Ji),wi=B(Ci),Ti=G({id:qt,payload:Dt}),Ei=G({...Ti.fields,schemas:Ar(wi)});function Di(e){let t={};for(let[n,r]of Object.entries(e))pn(r)&&a(t,n,r);return Object.keys(t).length===0?E():A(t)}var Oi=Ar(qe(ct,Rr)).pipe(Hn(W(Ue),{decode:Te(),encode:ht(e=>f(e)||e.value===void 0?E():Di(e.value))})),ki=gr(()=>Mi),Ai=B(ki),ji={annotations:Oi,checks:Ai},Mi=An([G({_tag:q(`Filter`),representation:Ei,annotations:Oi,aborted:z}),G({_tag:q(`FilterGroup`),representation:Ar(Ei),annotations:Oi,checks:Ae(ki)})]);function J(e){return G({_tag:q(e),...ji})}var Ni=G({_tag:q(`Declaration`),representation:Ti,annotations:Oi,typeParameters:wi,checks:Ai}),Pi=G({_tag:q(`Suspend`),annotations:Oi,checks:nn([]),thunk:Ci});function Fi(e,t){return t.pipe(Hn(G({type:q(e),value:t}),{decode:Yn(e=>e.value),encode:Yn(t=>({type:e,value:t}))}))}var Ii=Fi(`string`,ct),Li=Fi(`number`,Qt),Ri=G({_tag:q(`Literal`),...ji,literal:An([Ii,Fi(`number`,_t),Fi(`bigint`,er),Fi(`boolean`,z)])}),zi=G({_tag:q(`UniqueSymbol`),...ji,symbol:it}),Bi=G({_tag:q(`Enum`),...ji,enums:B(nn([ct,An([Ii,Li])]))}),Vi=G({_tag:q(`TemplateLiteral`),...ji,parts:wi}),Hi=G({isOptional:z,type:Ci,annotations:Oi}),Ui=G({_tag:q(`Arrays`),...ji,elements:B(Hi),rest:wi}),Wi=G({name:An([Ii,Li,Fi(`symbol`,it)]),type:Ci,isOptional:z,isMutable:z,annotations:Oi}),Gi=G({parameter:Ci,type:Ci}),Ki=G({_tag:q(`Objects`),...ji,propertySignatures:B(Wi),indexSignatures:B(Gi)}),qi=G({_tag:q(`Union`),...ji,types:wi,options:W(G({mode:W(ft([`anyOf`,`oneOf`]))}))}),Ji=An([Ni,G({_tag:q(`Reference`),$ref:qt}),Pi,J(`Null`),J(`Undefined`),J(`Void`),J(`Never`),J(`Unknown`),J(`Any`),J(`String`),J(`Number`),J(`Boolean`),J(`BigInt`),J(`Symbol`),J(`ObjectKeyword`),Ri,zi,Bi,Vi,Ui,Ki,qi]),Yi=sr(Tn(G({representation:Ci,references:qe(ct,Ci)})));function Xi(e){return Yi(e)}var Zi=Symbol.for(`@fungi.computer/shiitake/extension-definition-reader`);function Qi(e){return e[Zi]?.()}var $i=3.5,ea=4800;function ta(e){return e.totalTokens||e.input+e.output+e.cacheRead+e.cacheWrite}function na(e){try{return JSON.stringify(e)??`undefined`}catch{return`[unserializable]`}}function ra(e){if(typeof e==`string`)return e.length;let t=0;for(let n of e)t+=n.type===`text`?n.text.length:ea;return t}function ia(e){return Math.ceil(e.length/$i)}function aa(e){return Math.ceil(ra(e)/$i)}function oa(e){let t=0;if(e.role===`system`)return ia(fi(e))+la(e.toolsAdded)+la(e.toolsRemoved);if(e.role===`user`||e.role===`toolResult`)return aa(e.content);for(let n of e.content)n.type===`text`?t+=n.text.length:n.type===`thinking`?t+=n.thinking.length:t+=n.name.length+na(n.arguments).length;return Math.ceil(t/$i)}function sa(e){let t=-1/0,n;for(let r=0;r<e.length;r++){let i=e[r];if(i.role===`assistant`){let e=i;e.timestamp>=t&&e.stopReason!==`aborted`&&e.stopReason!==`error`&&ta(e.usage)>0&&(n={usage:e.usage,index:r})}t=Math.max(t,i.timestamp)}return n}function ca(e){let t=`messages`in e?e.messages:e,n=sa(t);if(n){let e=ta(n.usage),r=0;for(let e=n.index+1;e<t.length;e++)r+=oa(t[e]);return{tokens:e+r,usageTokens:e,trailingTokens:r,lastUsageIndex:n.index}}let r=0;for(let e of t)r+=oa(e);return{tokens:r,usageTokens:0,trailingTokens:r,lastUsageIndex:null}}function la(e){return!e||e.length===0?0:ia(na(e))}var ua=0xffffffffffff,da=(1n<<41n)-1n,fa=-1,Y;function pa(e){let t=e??Date.now();if(!Number.isInteger(t)||t<0||t>ua)throw RangeError(`UUIDv7 timestamp must be an integer between 0 and ${ua}`);let n=e===void 0?Math.max(t,fa):e;e===void 0&&(fa=n);let r=new Uint8Array(16);if(globalThis.crypto.getRandomValues(r),Y===void 0)Y=BigInt(r[1])<<32n|BigInt(r[2])<<24n|BigInt(r[3])<<16n|BigInt(r[4])<<8n|BigInt(r[5]);else{if(Y===da)throw RangeError(`UUIDv7 generator sequence exhausted`);Y++}let i=BigInt(n);for(let e=5;e>=0;e--)r[e]=Number(i>>BigInt((5-e)*8))&255;r[6]=112|Number(Y>>37n&15n),r[7]=Number(Y>>29n&255n),r[8]=128|Number(Y>>23n&63n),r[9]=Number(Y>>15n&255n),r[10]=Number(Y>>7n&255n),r[11]=Number((Y&127n)<<1n)|r[11]&1;let a=Array.from(r,e=>e.toString(16).padStart(2,`0`));return`${a.slice(0,4).join(``)}-${a.slice(4,6).join(``)}-${a.slice(6,8).join(``)}-${a.slice(8,10).join(``)}-${a.slice(10).join(``)}`}function ma(e){return nt(e,{onFailure:re,onSuccess:()=>m})}function ha(e,t){return h(e,{onFailure:e=>T(t).pipe(_(re(e))),onSuccess:()=>t})}function ga(e,t){let n={_tag:`open`},r=r=>ha(e,t).pipe(T,F(e=>M(()=>{r.result=e,n={_tag:`closed`}}).pipe(_(r.settled.open),_(ma(e)))),ie);return C(()=>{if(n._tag===`closed`)return m;if(n._tag!==`open`){let e=n;return e.settled.await.pipe(_(C(()=>{let t=e.result;return t===void 0?j(Error(`Agent close settlement was not recorded`)):ma(t)})))}let e={_tag:`running`,settled:Yr(!1)};return n=e,r(e)})}function _a(e,t,n,r){let i=Mr(e,t);if(n.state===`idle`)return{facts:{queue:{state:`idle`},cancellationRequested:!1,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};if(n.state===`queued`)return{facts:{queue:{state:`queued`,commandId:n.jobId,runningWork:r},cancellationRequested:n.cancellationRequested,retry:null,activeTool:null,lastModelChoiceSequence:i,compaction:null},progress:null,toolOutput:[]};let a=qn(e,t,n.jobId),o=a?.event.type===`auto_retry_start`?{attempt:a.event.attempt,maxAttempts:a.event.maxAttempts,delayMs:a.event.delayMs,errorMessage:a.event.errorMessage,scheduledAt:a.timestamp}:null;return{facts:{queue:{state:`running`,commandId:n.jobId},cancellationRequested:n.cancellationRequested,retry:o,activeTool:Vr(e,t,n.jobId)??null,lastModelChoiceSequence:i,compaction:ke(e,t)},progress:Gt(e,t,n.jobId),toolOutput:Ye(e,t,n.jobId)}}var va=new WeakMap;function ya(e,t){let n=yr(e,{sessionId:t}),r=$t(n);return r.length===0?null:ca(r).tokens}function ba(e,t,n,r=!0){return D(function*(){let i=yield*oe(I({try:()=>ar(e.store,t),catch:e=>e}));if(i._tag===`Failure`){Rt(`session-context.preference`,i.failure);return}let a=i.success,s=JSON.stringify(a),c=va.get(e)??new Map;va.set(e,c);let l=r?c.get(t):void 0,u=e.model.describe;if(l?.cursor===n&&l.preference===s){if(l.value===void 0||u===void 0)return l.value;let e=l.value;return yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:i})=>{if(e.window===i)return e;let a=Object.freeze({tokens:e.tokens,window:i});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:a}),a}),ae(t=>M(()=>(Rt(`session-context.describe`,t),e))))}let d=yield*oe(I({try:()=>ya(e.store,t),catch:e=>e}));if(d._tag===`Failure`){Rt(`session-context.figure`,d.failure);return}let f=d.success;if(f===null){r&&c.set(t,{cursor:n,preference:s,value:void 0});return}if(u===void 0){let e=Object.freeze({tokens:f,window:null});return r&&c.set(t,{cursor:n,preference:s,value:e}),e}r&&c.set(t,{cursor:n,preference:s,value:Object.freeze({tokens:f,window:null})});let p=yield*u({sessionId:t,preference:a}).pipe(o(({contextWindow:e})=>e),ae(e=>M(()=>(Rt(`session-context.describe`,e),null)))),m=Object.freeze({tokens:f,window:p});return r&&c.get(t)?.cursor===n&&c.set(t,{cursor:n,preference:s,value:m}),m})}function xa(e){return Object.freeze({list:e.assertOpen.pipe(o(()=>e.extensions.list())),resume:t=>e.assertOpen.pipe(_(e.extensions.resume(t))),call:(t,n,r)=>e.assertOpen.pipe(_(e.extensions.call({scope:`agent`},t,n,r)))})}function Sa(e,t,n){return t.readQueueHead(n).pipe(F(r=>(r.state===`queued`?t.runningWork(r.jobId):x(null)).pipe(o(t=>_a(e.store,n,r,t)))))}function Ca(e,t){return t===void 0?e:Object.freeze({...e,context:t})}function wa(e,t,n,r){return Sa(e,t,n).pipe(F(i=>Zr(e.store,n,i,r,()=>t.extensions.project(n))),F(t=>ba(e,n,t.cursor,r?.before===void 0).pipe(o(e=>Ca(t,e)))))}function Ta(e,t,n){return e.assertOpen.pipe(_(I({try:()=>n(H(t)),catch:e=>e instanceof L?e:new L(`store`,`rejected`,`Session owner operation failed`)})))}function Ea(e,t){return I({try:()=>{let n=Dr(t);if(n._tag===`Failure`)throw new L(`contract`,`invalid`,`Session command is invalid`);return Object.freeze({sessionId:H(e),command:n.success})},catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Session command is invalid`)})}function Da(e,t){return I({try:()=>Object.freeze({sessionId:H(e),options:un(t)}),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Subscribe options are invalid`)})}function Oa(e,t,n,r=!1){return t.assertOpen.pipe(_(wa(e,t,n,{includeSandboxFailures:r})),o(e=>Object.freeze({kind:`reset`,reason:`history_unavailable`,cursor:e.cursor,baseline:e})))}function ka(e){return[[e],A({after:e.cursor??void 0,delivery:e.baseline.hasMore?`replay`:`live`,awaitSignal:!e.baseline.hasMore})]}function Aa(e,t,n,r,i,a,s=!1){return Cr({after:i,delivery:a,awaitSignal:!1},i=>(i.awaitSignal?n.awaitSignal.pipe(F(e=>n.pollSignal.pipe(o(t=>t===void 0?e:Jr(e,t))))):n.pollSignal).pipe(F(a=>a===`closed`?x([[],E()]):a===`reset`?Oa(e,t,r,s).pipe(o(ka)):t.assertOpen.pipe(_(Sa(e,t,r)),F(c=>(n.setQueued(c.facts.queue.state===`queued`),a===`activity`&&i.delivery===`live`?x([[{kind:`activity`,activity:c.facts}],A({...i,awaitSignal:!0})]):a===`progress`&&i.delivery===`live`?x([[...c.progress===null?[]:[{kind:`progress`,progress:c.progress,activity:c.facts}],{kind:`tool_output`,toolOutput:c.toolOutput,activity:c.facts}],A({...i,awaitSignal:!0})]):Ie(e.store,r,i.after,i.delivery,c,()=>t.extensions.project(r),s).pipe(F(n=>{if(n.kind===`reset`)return Oa(e,t,r,s).pipe(o(ka));let a=n.frames.flatMap(e=>e.kind===`progress`||e.kind===`activity`||e.kind===`tool_output`?[]:[e.cursor]).at(-1),c={after:a??i.after,delivery:n.hasMore?i.delivery:`live`,awaitSignal:!n.hasMore};return(n.frames.some(e=>e.kind===`update`&&e.cursor!==i.after)&&!n.hasMore?ba(e,r,a??null):x(void 0)).pipe(o(e=>[e===void 0?n.frames:n.frames.map(t=>t.kind===`update`&&t.cursor===a?Object.freeze({...t,context:e}):t),A(c)]))}))))))))}function ja(e,t,n,r,i){return zn(t.assertOpen.pipe(_(Da(r,i)),F(r=>ge(n.register(r.sessionId),e=>M(e.close)).pipe(o(n=>Aa(e,t,n,r.sessionId,r.options.after,`replay`,r.options.includeSandboxFailures===!0))))))}function Ma(e,t){return I({try:()=>Object.freeze({sessionId:H(e),options:st(t)}),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Watch options are invalid`)})}function Na(e,t,n,r,a){return t.assertOpen.pipe(_(Ma(r,a)),F(r=>ye(a=>D(function*(){let s=yield*n.register(r.sessionId);return yield*a(t.assertOpen.pipe(_(wa(e,t,r.sessionId,r.options)),o(n=>(s.setQueued(n.activity.queue.state===`queued`),Object.freeze({snapshot:n,changes:Aa(e,t,s,r.sessionId,n.cursor??void 0,`live`,r.options.includeSandboxFailures===!0).pipe(ir(M(s.close))),close:M(s.close)}))))).pipe(i(()=>M(s.close)))}))))}function Pa(e,t,n,r,i,a){let o={sessionId:t,command:n,when:`now`,origin:{kind:`user`}};return r!==void 0&&(o={...o,meta:r}),i!==void 0&&(o={...o,mail:i}),a!==void 0&&(o={...o,reply:a}),e.assertOpen.pipe(_(e.door.admit(o)),F(e=>e.status===`accepted`?x({status:`accepted`,commandId:e.commandId}):w(new L(`runtime`,`unavailable`,`Session command was not admitted`))))}function Fa(e,t,n,r,i){return t.assertOpen.pipe(_(Ta(t,n,t=>{e.meta?.identityPath!==void 0&&i!==void 0&&tt(e.store,t,r.commandId,mr(e.store,e.meta.identityPath,i))})),_(br(e.store,n,r.commandId,r.onlyIfPending,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,i)),F(e=>e===void 0?x({status:`too_late`,commandId:r.commandId}):(e.active?t.signalCancellation(e.accepted.commandId,e.accepted.entryId):t.requestWake).pipe(N({status:`accepted`,commandId:e.accepted.commandId}))))}function Ia(e,t,n,r){return t.assertOpen.pipe(_(t.commit(nr(e.store,n,()=>t.readQueueHeadTransactional(n),t.recordAcceptedCancellation,r))),F(e=>e===void 0?t.requestWake:t.signalCancellation(e.commandId,e.entryId)))}function La(e,t,n,r){return t.assertOpen.pipe(_(Pn(e.store,{sessionId:n,type:`branch`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})),N(void 0))}function Ra(e,t,n,r){return t.assertOpen.pipe(_(fn(e.store,{sessionId:n,type:`fork`,entryId:r.entryId,assertIdleSession:t.assertIdleSession})))}function za(e,t,n,r,i){return t.assertOpen.pipe(_(Ea(n,i)),F(t=>Ba(e,r).pipe(o(e=>({...t,checked:e})))),F(({sessionId:n,command:r,checked:i})=>{switch(r.type){case`prompt`:case`compact`:return Pa(t,n,r,i);case`abort`:return Ia(e,t,n,i).pipe(N(void 0));case`cancel`:return Fa(e,t,n,r,i);case`branch`:return La(e,t,n,r);case`fork`:return Ra(e,t,n,r);case`operator`:return t.assertOpen.pipe(_(mt(e.store,{sessionId:n,requestId:r.requestId,author:r.author,meta:i,text:r.text,assertIdleSession:t.assertIdleSession})),N(void 0));case`title`:return t.commit(Ta(t,n,t=>{In(e.store,t,r.title)})).pipe(N(void 0))}}))}function Ba(e,t){return I({try:()=>t===void 0?void 0:Qr(e.meta,t),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Host metadata is invalid`)})}function Va(e,t){let n=ai(e.store),r=(r,i)=>{function a(n){return za(e,t,r,i,n)}return Object.freeze({command:a,withdraw:e=>t.assertOpen.pipe(_(t.door.withdraw(r,e))),abort:a({type:`abort`}),send:(e,t)=>M(()=>t?.requestId??Re()).pipe(F(n=>{let r={type:`prompt`,delivery:t?.delivery??`steer`,requestId:n,text:e};return a(t?.images===void 0?r:{...r,images:t.images}).pipe(p(e=>e.requestId===n?e:new L(e.boundary,e.cause,e.message,n)))})),cancel:e=>a({type:`cancel`,...e}),latestPending:Ta(t,r,t=>Ut(e.store,t,e.meta?.identityPath===void 0||i===void 0?void 0:mr(e.store,e.meta.identityPath,i))),modelPreference:Object.freeze({read:Ta(t,r,t=>ar(e.store,t)),set:n=>I({try:()=>Br(n),catch:()=>new L(`contract`,`invalid`,`Model preference is invalid`)}).pipe(F(n=>t.commit(Ta(t,r,t=>(kn(e.store,t,n),t))).pipe(k(t=>M(()=>{ti(e.store,t)})),y)))}),extension:e=>Object.freeze({call:(n,i)=>t.assertOpen.pipe(_(t.extensions.call({scope:`session`,sessionId:r},e,n,i)))}),read:n=>t.assertOpen.pipe(_(wa(e,t,r,n))),readSettlement:(i,a=0)=>b(D(function*(){yield*t.assertOpen;let s=yield*I({try:()=>({sessionId:H(r),...jt(tn({commandId:i,timeoutMs:a}),`Settlement request is invalid`)}),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Settlement request is invalid`)}),c=yield*ge(n.register(s.sessionId,`settlement`),e=>M(e.close)),l=Lt(e.store,s.sessionId,s.commandId),u=yield*l;return u!==void 0||s.timeoutMs===0?u:yield*D(function*(){for(;;){if((yield*c.awaitSignal)===`closed`)return yield*w(new L(`runtime`,`closed`,`Shiitake is closed`));let e=yield*l;if(e!==void 0)return e}}).pipe(se(s.timeoutMs),o(ne))})),subscribe:i=>ja(e,t,n,r,i),watch:i=>Na(e,t,n,r,i)})},i=Object.freeze({createSession:n=>t.assertOpen.pipe(_(or(e.store,n,t.storage.admitNew))),deleteSession:n=>t.assertOpen.pipe(_(Ln(e.store,{sessionId:n,assertIdleSession:t.assertIdleSession}))),listSessions:n=>t.assertOpen.pipe(_(Bt(e.store,n))),extensions:xa(t),session:e=>r(e,void 0),close:t.beginClose.pipe(_(n.close))});return Object.freeze({...i,prepareConfiguration:t.prepareConfiguration,grants:Object.freeze({deliver:(n,r)=>Ta(t,n,t=>e.store.transactionSync(()=>oi(e.store,t,r))),read:n=>Ta(t,n,t=>Cn(e.store,t))}),withMeta:e=>Object.freeze({...i,session:t=>r(t,e)})})}function Ha(e,t,n,r,i,a){if(t.to.sessionId===void 0){if(r!==void 0||t.replyTo.length===0)throw Error(`Only delegated work can create a recipient Session`);return e.door.transact(r=>{let o=e.createSessionWithinTransaction(t.key),s=a?.(o);s!==void 0&&e.stageSessionGrantsWithinTransaction(o,s);let c={...t,to:{...t.to,sessionId:o}},l={sessionId:o,requireExistingSession:!0,command:{requestId:t.key,delivery:`followUp`,type:`prompt`,text:t.content},when:`now`,origin:{kind:`user`},mail:c,onAccepted:(e,n)=>{if(i===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);i(Wr(t,o,n,Date.now()))}},u=r(n===void 0?l:{...l,meta:n});if(u.status!==`accepted`)throw Error(`Sessionless addressed mail was not admitted`);return{status:`accepted`,commandId:u.commandId,sessionId:o}})}return Pa(e,t.to.sessionId,{requestId:t.key,delivery:r===void 0?`followUp`:`steer`,type:`prompt`,text:t.content},n,t,r)}var Ua=G({fork:ft([`inherit-at-fork-point`,`current`,`fresh`]),maxBytes:St.pipe(K(Ee(0)),K(Kt(2**53-1)))});function Wa(e,t){let n=mn(e.schema)(t);if(n._tag===`Failure`)throw new vi({reason:`encode`,message:`Session document does not match its schema`});let r=U(Vt)(n.success);if(r._tag===`Failure`)throw new vi({reason:`encode`,message:`Session document must encode finite JSON`});let i=JSON.stringify(r.success);if(new TextEncoder().encode(i).byteLength>e.maxBytes)throw new vi({reason:`bound`,message:`Session document exceeds maxBytes`});return i}function Ga(e){return{...Fn(Ua)(e),schema:Xi(Ur(e.schema)),initial:Wa(e,e.initial)}}var Ka=64,qa=ft([`state`,`attention`,`settled`,`send`,`timers`,`commands`,`projection`,`run_tools`,`files`,`prompt`,`compaction_handoff`]),Ja=B(qa).pipe(K(Ke(10))),Ya=G({protocol:$e(`shiitake.extension/v0`),id:hr,version:wn,requests:Ja}),Xa=B(G({id:hr,capabilities:Ja,grantKey:W(hr)})).pipe(K(Ke(Ka))),Za=ct.pipe(K(Se(/^[a-z][A-Za-z0-9_]{0,63}$/u))),Qa=U(Ya,{onExcessProperty:`error`}),$a=U(Xa,{onExcessProperty:`error`}),eo=U(Za);function X(e){return new L(`extensions`,`invalid`,e)}function to(e){return new Set(e).size!==e.length}function no(e){return JSON.stringify(e,(e,t)=>O(t)?Object.fromEntries(Object.entries(t).sort(([e],[t])=>e<t?-1:+(e>t))):t)}function ro(e){return _e({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 L(`extensions`,`rejected`,`Extension digest failed`)})}function io(e,t){let{manifest:n,contract:r,state:i,config:a,catalog:o}=e,s={manifest:{protocol:n.protocol,id:n.id,version:n.version,requests:[...n.requests].sort()},commands:Object.fromEntries(Object.entries(r.commands).map(([e,t])=>[e,{scope:t.scope,input:Xi(Ur(t.input)),output:Xi(Ur(t.output))}])),projection:r.projection===null?null:Xi(Ur(r.projection.schema)),state:{version:i.version,collections:Object.fromEntries(Object.entries(i.collections).map(([e,t])=>[e,Xi(Ur(t.schema))]))},config:a},c=Object.keys(t).length===0?s:{...s,documents:Object.fromEntries(Object.entries(t).map(([e,t])=>[e,Ga(t)]))};return o===void 0?c:{...c,catalog:o}}function ao(e){if(Qa(e.manifest)._tag===`Failure`)throw X(`Extension manifest is invalid`);let t=e.manifest;if(to(t.requests))throw X(`Extension capability requests are invalid`);if(e.contract.id!==t.id)throw X(`Extension contract identity does not match its manifest`);if(!Number.isSafeInteger(e.state.version)||e.state.version<1)throw X(`Extension state version is invalid`);for(let t of Object.keys(e.state.collections))if(t===`update`||t===`read`||t===`observe`||eo(t)._tag===`Failure`)throw X(`Extension collection name is invalid`);if(e.catalog!==void 0&&!t.requests.includes(`commands`))throw X(`An extension catalog requires the commands capability`);return t}function oo(e){return D(function*(){let t=e?.roster??[],n=e?.grants??[],r=yield*I({try:()=>{if(t.length>Ka)throw X(`Extension roster is invalid`);let e=t.map(e=>{let t=Qi(e);if(t===void 0)throw X(`Extension roster entry was not defined`);let n=t.documents??{};for(let[e,t]of Object.entries(n)){if(eo(e)._tag===`Failure`)throw X(`Session document name is invalid`);Ga(t)}let r=ao(t);if(Object.keys(n).length>0&&!r.requests.includes(`state`))throw X(`Session documents require the state capability`);return{definition:t,documents:n,manifest:r}});if(to(e.map(({manifest:e})=>e.id)))throw new L(`extensions`,`conflict`,`Extension identities conflict`);let r=$a(n);if(r._tag===`Failure`)throw X(`Extension grants are invalid`);if(to(r.success.map(({id:e})=>e)))throw X(`Extension grant identities are invalid`);let i=new Map;for(let t of r.success){let n=e.find(({manifest:e})=>e.id===t.id);if(n===void 0||to(t.capabilities)||t.capabilities.some(e=>!n.manifest.requests.includes(e)))throw X(`Extension grant is invalid`);i.set(t.id,t.capabilities)}if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`compaction_handoff`)).length>1)throw new L(`extensions`,`conflict`,`Compaction handoff slot is already owned`);if(e.filter(({manifest:e})=>i.get(e.id)?.includes(`files`)).length>1)throw new L(`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 L?e:X(`Extension roster is invalid`)});return yield*ve(r,e=>D(function*(){let t=`sha256:${yield*ro(yield*I({try:()=>no(io(e.definition,e.documents)),catch:()=>X(`Extension schemas cannot be described`)}))}`,n=[...e.grants].sort(),r=`sha256:${yield*ro(no([t,n]))}`;return Object.freeze({id:e.manifest.id,manifest:e.manifest,definition:e.definition,documents:e.documents,grants:new Set(n),revision:Fn(Nr)(t),fingerprint:Fn(_n)(r)})}))})}function so(e){return ro(no({protocol:`shiitake.extension/v0`,runContract:1,fileTools:[...e].sort()}))}function co(e){let t={kind:`reason_unavailable`,...e,provider:e.provider===``?null:e.provider,model:e.model===``?null:e.model};return`${t.kind}: run=${t.runId}; provider=${t.provider??`unknown`}; model=${t.model??`unknown`}`.slice(0,200)}function lo(e){return co({runId:e.run.value,provider:e.message.provider,model:e.message.model})}function uo(e){return new L(`model`,`rejected`,e)}function fo(e,t){let n={input:e.input+t.input,output:e.output+t.output,cacheRead:e.cacheRead+t.cacheRead,cacheWrite:e.cacheWrite+t.cacheWrite,totalTokens:e.totalTokens+t.totalTokens,cost:{input:e.cost.input+t.cost.input,output:e.cost.output+t.cost.output,cacheRead:e.cost.cacheRead+t.cost.cacheRead,cacheWrite:e.cost.cacheWrite+t.cost.cacheWrite,total:e.cost.total+t.cost.total}};return(e.cacheWrite1h!==void 0||t.cacheWrite1h!==void 0)&&(n.cacheWrite1h=(e.cacheWrite1h??0)+(t.cacheWrite1h??0)),(e.reasoning!==void 0||t.reasoning!==void 0)&&(n.reasoning=(e.reasoning??0)+(t.reasoning??0)),n}function po(e){let t;for(let n of e)n.kind===`compaction`&&(t=n);let n=t,r=n===void 0?0:Math.max(0,e.findIndex(({id:e})=>e===n.head)),i=e.flatMap((e,t)=>e.kind===`message`&&t>=r?[e.message]:[]);return n===void 0?i:[n.model,...i]}function mo(e,t,n){let r=tr(),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)Oe(t,r);return r}function ho(e,t,n,r){for(let i=t;i<n;i+=1){let t=e[i];if(t?.kind===`message`){if(t.message.role===`assistant`)return!1;if(t.message.role===`toolResult`&&r.has(t.message.toolCallId))return!0}}return!1}function go(e,t,n){let r=[],i=new Set;for(let a=t;a<n;a+=1){let t=e[a];if(t?.kind!==`message`)continue;let o=t.message;o.role===`assistant`?(r.push(a),i=new Set(o.content.flatMap(e=>e.type===`toolCall`?[e.id]:[]))):o.role===`user`&&!ho(e,a+1,n,i)&&r.push(a)}return r}function _o(e,t,n,r){let i=go(e,t,n),a=0;for(let o=n-1;o>=t;--o){let t=e[o];if(t?.kind===`message`&&(a+=oa(t.message),a>=r))return i.find(e=>e>=o)??i.at(-1)}}function vo(e,t,n){let r=e[n],i=r?.kind===`message`&&r.message.role===`user`,a=-1;if(!i)for(let r=n;r>=t;--r){let t=e[r];if(t?.kind===`message`&&t.message.role===`user`){a=r;break}}return{isSplitTurn:!i&&a>=0,turnStartIndex:a}}function yo(e,t,n,r){let i=_o(e,t,n,r);return i===void 0?{firstKeptEntryIndex:t,isSplitTurn:!1,turnStartIndex:-1}:{firstKeptEntryIndex:i,...vo(e,t,i)}}function bo(e,t){if(e.at(-1)?.kind===`compaction`)return;let n,r=-1,i=0;for(let t=e.length-1;t>=0;--t){let a=e[t];if(a?.kind===`compaction`){n=Fe(a.model),r=t;let o=e.findIndex(e=>e.id===a.head);i=o>=0?o:t+1;break}}let a=e.flatMap((e,t)=>e.kind===`message`&&t>=i?[e]:[]),o=ca(po(e)).tokens,s=yo(a,0,a.length,t.keepRecentTokens),c=a[s.firstKeptEntryIndex];if(c?.kind!==`message`)return;let l=s.isSplitTurn?s.turnStartIndex:s.firstKeptEntryIndex,u=Object.freeze(a.slice(0,l).map(({message:e})=>e)),d=Object.freeze(s.isSplitTurn?a.slice(s.turnStartIndex,s.firstKeptEntryIndex).map(({message:e})=>e):[]);if(u.length===0&&d.length===0)return;let f=mo(u,e,r);for(let e of d)Oe(e,f);let p={firstKeptEntryId:c.id,messagesToSummarize:u,turnPrefixMessages:d,isSplitTurn:s.isSplitTurn,tokensBefore:o,fileOps:f,settings:t};return n===void 0?p:{...p,previousSummary:n}}var xo={enabled:!0,maxRetries:3,baseDelayMs:2e3};function So(e,t,n,r){let i={...n,cacheRetention:`none`,sessionId:n.sessionId??pa()};return He(()=>Promise.resolve((r??li)(e,di(t),i)).then(e=>e.result()),xo,i.signal)}function Co(e){return{systemPrompt:Ne,messages:[{role:`user`,content:[{type:`text`,text:e}],timestamp:Date.now()}]}}function wo(e,t,n){let r=e.previousSummary??``,i=t?Ht:zt,a=n===void 0?i:`${i}\n\nAdditional focus: ${n}`;return`<conversation>\n${vt(e.messagesToSummarize)}\n</conversation>\n\n${t?`<previous-summary>\n${r}\n</previous-summary>\n\n`:``}${a}`}function To(e){return`# Conversation\n${vt(e.turnPrefixMessages)}\n\n# Instructions\n${$r}`}async function Eo(e,t,n,r,i,a){let o=n===void 0?{maxTokens:t}:{maxTokens:t,signal:n},s=await So(e,Co(r),o,a),c=We(s,i);if(c!==void 0)throw Error(c);return s}function Do(e,t,n,r,i,a){return e.messagesToSummarize.length===0?Promise.resolve(void 0):Eo(t,n,r,wo(e,e.previousSummary!==void 0&&e.previousSummary.length>0,i),`Summarization`,a)}function Oo(e,t,n,r){return!e.isSplitTurn||e.turnPrefixMessages.length===0?Promise.resolve(void 0):Eo(t,Math.min(Math.floor(.5*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,To(e),`Turn prefix summarization`,r)}function ko(e,t,n){let r,i;if(e.isSplitTurn){if(n===void 0)throw Error(`Split-turn compaction did not produce a prefix summary`);r=`${t===void 0?e.previousSummary??`No prior history.`:pi(t.content)}\n\n---\n\n**Turn Context (split turn):**\n\n${pi(n.content)}`,i=t===void 0?n.usage:fo(t.usage,n.usage)}else{if(t===void 0)throw Error(`Compaction did not produce a history summary`);r=pi(t.content),i=t.usage}let a=Tt(e.fileOps);return{summary:r+Zn(a.readFiles,a.modifiedFiles),firstKeptEntryId:e.firstKeptEntryId,tokensBefore:e.tokensBefore,usage:i,details:a}}async function Ao(e,t,n,r,i){return ko(e,await Do(e,t,Math.min(Math.floor(.8*e.settings.reserveTokens),t.maxTokens>0?t.maxTokens:1/0),n,r,i),e.isSplitTurn&&e.turnPrefixMessages.length>0?await Oo(e,t,n,i):void 0)}function jo(e,t,n,r){return _e({try:i=>Ao(e,t,i,r,n),catch:e=>uo(e instanceof Error?e.message:String(e))})}function Mo(e,t,n,r){return{sessionId:n,messagesToSummarize:e.messagesToSummarize,turnPrefixMessages:e.turnPrefixMessages,result:t,contextRevision:r}}var No=new WeakMap;function Po(e){return No.has(e)}function Fo(e,t,n){let r={fiber:void 0,summary:void 0},i=n(e=>{r.summary=e});return Qe(t,M(()=>{Lo(e,r)})).pipe(_(l(i,t)),o(t=>(r.fiber=t,No.set(e,r),r)))}function Io(e){let t=e.summary;return e.summary=void 0,t}function Lo(e,t){t.fiber=void 0,t.summary=void 0,No.get(e)===t&&No.delete(e)}function Ro(e){return new L(`runtime`,`rejected`,e)}var zo={handoff:`The compaction handoff failed; the conversation context is unchanged`,handoffResult:`The compaction handoff failed: it returned an invalid result; the conversation context is unchanged`,conflict:`The Session changed during compaction; the conversation context is unchanged`},Bo=class extends L{phase;usage;constructor(e,t){super(e===`conflict`?`store`:`runtime`,e===`conflict`?`conflict`:`rejected`,zo[e]),this.phase=e,this.usage=t}get diagnostic(){return zo[this.phase]}};function Vo(e,t){let n=Bn(e,t),r=lr(e),i=[];for(let t of e){let e=Fr(t.entry);if(e!==void 0&&!r.has(e.workId)){i.push({id:t.id,kind:`message`,message:Kn(e)});continue}if(t.entry.kind===`operator`){i.push({id:t.id,kind:`message`,message:vr(t.entry)});continue}if(t.entry.kind===`message`){n.has(t.id)&&i.push({id:t.id,kind:`message`,message:t.entry.value});continue}if(t.entry.kind===`compaction`){let e={id:t.id,kind:`compaction`,head:t.entry.head,model:t.entry.model[0],usage:t.entry.data.usage};i.push(t.entry.data.details===void 0?e:{...e,details:t.entry.data.details})}}return i}function Ho(e,t,n){return I({try:()=>yr(e,{sessionId:t,workId:n}),catch:()=>Ro(`Woodstock selected lineage is unavailable`)})}function Uo(e,t,n,r){let i={...t,id:`${t.id}:compaction`,parentId:t.id,sequence:t.sequence+1,timestamp:Date.now(),entry:n};return $t([...e,i],r).reduce((e,t)=>e+oa(t),0)}function Wo(e,t,n){return C(()=>(Nt(e.store,e.sessionId,n.trigger),Go(e,t,n).pipe(ue(M(()=>{si(e.store,e.sessionId)})))))}function Go(e,t,n){return D(function*(){let r=bo(Vo(t,e.workId),e.settings);if(r===void 0)return;let i=t.at(-1);if(i===void 0)return;let a=yield*jo(r,e.model,e.stream,n.instructions),o=yield*Jo(e,r,a,i.id);return yield*Zo(e,t,a,n,i.id,o)})}var Ko=An([G({type:$e(`accepted`),receipt:fr}),G({type:$e(`discarded_by_policy`)})]),qo=U(Ko);function Jo(e,t,n,r){return e.handoff===void 0?x(void 0):e.handoff.consume(Mo(t,n,e.sessionId,r)).pipe(p(()=>new Bo(`handoff`,n.usage)),F(e=>{let t=qo(e);return t._tag===`Failure`?w(new Bo(`handoffResult`,n.usage)):x(t.success.type===`accepted`?t.success.receipt:void 0)}))}function Yo(e,t,n,r,i,a){let o=t.at(-1);if(o===void 0)return;let s=Uo(t,o,{kind:`compaction`,workId:e.workId,head:n.firstKeptEntryId,model:[ze(n.summary,Date.now())],data:{reason:r.trigger,resumesRun:r.resumesRun,tokensBefore:n.tokensBefore,tokensAfter:0,usage:n.usage,contextRevision:i}},e.workId),c={sessionId:e.sessionId,resumesRun:r.resumesRun,trigger:r.trigger,tokensAfter:s,expectedLeafId:o.id,workId:e.workId,head:n.firstKeptEntryId,summary:n.summary,tokensBefore:n.tokensBefore,usage:n.usage,contextRevision:i,details:n.details};return a===void 0?c:{...c,receipt:a}}function Xo(e,t,n){let r=[...t,n];return{path:r,messages:$t(r,e.workId)}}function Zo(e,t,n,r,i,a){let s=Yo(e,t,n,r,i,a);return s===void 0?x(void 0):I({try:()=>Dn(e.store,s),catch:e=>e instanceof L?e.cause===`conflict`?new Bo(`conflict`):e:Ro(`Woodstock compaction append failed`)}).pipe(o(n=>Xo(e,t,n)))}function Qo(e){return e instanceof Bo?e.diagnostic:e.boundary===`model`?e.message:`Compaction failed (${e.boundary}: ${e.cause})`}function $o(e,t){return I({try:()=>{Hr(e.store,t)},catch:e=>e instanceof L?e:Ro(`Compaction notice could not be recorded`)})}function es(e,t,n){let r={sessionId:e.sessionId,workId:e.workId,trigger:t};return $o(e,n===void 0?{...r,result:`nothing_to_compact`}:{...r,result:`failed`,diagnostic:Qo(n),usage:n instanceof Bo?n.usage:void 0})}function ts(e,t,n){return oe(Wo(e,t,n)).pipe(F(t=>t._tag===`Success`?x(t.success):es(e,n.trigger,t.failure).pipe(N(void 0))))}var ns={trigger:`threshold`,resumesRun:!1};function rs(e,t,n,r){return t.stopped||Po(e.store)||!Ot(n,e.model.contextWindow,e.settings)?m:r.pipe(F(n=>is(e,t.scope,n)),o(e=>{e===void 0?t.stopped=!0:t.slot=e}))}function is(e,t,n){let r=n.at(-1),i=bo(Vo(n,e.workId),e.settings);return r===void 0||i===void 0?x(void 0):Fo(e.store,t,t=>as(e,i,r.id,t))}function as(e,t,n,r){return C(()=>(Nt(e.store,e.sessionId,`threshold`),jo(t,e.model,e.stream).pipe(o(e=>{r({preparation:t,result:e,selectionTail:n})}),ue(M(()=>{si(e.store,e.sessionId)})))))}function os(e,t,n,r){return C(()=>{let i=t.slot,a=i?.fiber;return i===void 0||a===void 0||!r&&a.pollUnsafe()===void 0?x(void 0):(t.slot=void 0,oe(ni(a).pipe(F(()=>cs(e,i)),F(t=>t===void 0?x(void 0):ls(e,t,n)))).pipe(F(n=>n._tag===`Success`&&n.success!==void 0?x(n.success):(t.stopped=!0,n._tag===`Success`?x(void 0):es(e,`threshold`,n.failure).pipe(N(void 0)))),ue(M(()=>{Lo(e.store,i)}))))})}function ss(e,t,n){return $o(e,{sessionId:e.sessionId,workId:e.workId,trigger:`threshold`,result:n,usage:t.usage}).pipe(N(void 0))}function cs(e,t){let n=Io(t);if(n===void 0)return x(void 0);let{result:r,selectionTail:i}=n;return I({try:()=>ln(e.store,{sessionId:e.sessionId,head:r.firstKeptEntryId}),catch:e=>e instanceof L?e:Ro(`Woodstock compaction head is unavailable`)}).pipe(F(t=>t===`stale`?ss(e,r,`stale`):Jo(e,n.preparation,r,i).pipe(o(e=>({result:r,selectionTail:i,receipt:e})))),ue(M(()=>{Lo(e.store,t)})))}function ls(e,t,n){return Ho(e.store,e.sessionId,e.workId).pipe(F(r=>{let i=Yo(e,r,t.result,n,t.selectionTail,t.receipt);return i===void 0?x(void 0):Ct(i.tokensAfter,e.model.contextWindow,e.settings)?ss(e,t.result,`insufficient`):I({try:()=>xn(e.store,i),catch:e=>e instanceof L?e.cause===`conflict`?new Bo(`conflict`):e:Ro(`Woodstock compaction append failed`)}).pipe(F(n=>n===`stale`?ss(e,t.result,`stale`):x(Xo(e,r,n))))}))}function us(e,t){let n={path:e.path,messages:e.messages};if(e.resuming===!0)return x(n);let r=ca(e.messages).tokens;return Ct(r,e.model.contextWindow,e.settings)?ts(e,e.path,ns).pipe(o(e=>e??n)):rs(e,t,r,x(e.path)).pipe(N(n))}function ds(e,t){let n=De(e.message,t.contextWindow),r=Ft(e.message,t.maxTokens);return{triggered:n||r,overflow:n,retry:(n||r)&&e.message.stopReason!==`stop`}}function fs(e){let t=e.at(-1);return t?.role===`assistant`&&(t.stopReason===`error`||t.stopReason===`length`)?e.slice(0,-1):e}function ps(e,t,n,r){if(!e.settings.enabled)return x(void 0);let i=Ct(ca([...t.messages,...n.messages.slice(t.newMessageCount)]).tokens,e.model.contextWindow,e.settings);return r.triggered||i?Ho(e.store,e.sessionId,e.workId):x(void 0)}function ms(e,t,n){return(r,i)=>D(function*(){let a=e=>(t.path=e.path,t.messages=e.messages,t.newMessageCount=i,e.messages),o=ca(r).tokens,s=Ct(o,e.model.contextWindow,e.settings),c=yield*os(e,n,ns,s);if(c!==void 0)return a(c);let l=Ho(e.store,e.sessionId,e.workId);if(!s){yield*rs(e,n,o,l);return}let u=yield*ts(e,yield*l,ns);return u===void 0?void 0:a(u)})}function hs(e,t,n){return D(function*(){let r=t,i=t.path.some(({entry:t})=>t.kind===`compaction`&&t.workId===e.workId&&t.data.resumesRun);for(;;){let t={path:r.path,messages:r.messages,newMessageCount:0},a=yield*e.run(t.messages,ms(e,t,n)),o=ds(a,e.model),s=o.retry&&!i,c=yield*os(e,n,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:s},!0);if(c!==void 0){if(!s)return a;r={path:c.path,messages:fs(c.messages)},i=!0;continue}let l=yield*ps(e,t,a,o);if(l===void 0||o.retry&&i)return a;let u=yield*ts(e,l,{trigger:o.overflow?`overflow`:`threshold`,resumesRun:o.retry});if(u===void 0||!o.retry)return a;r={path:u.path,messages:fs(u.messages)},i=!0}})}function gs(e){return D(function*(){let t={scope:yield*P,slot:void 0,stopped:!1};return yield*hs(e,e.settings.enabled?yield*us(e,t):e,t)})}function _s(e){return e.path.some(({entry:t})=>(t.kind===`compaction`||t.kind===`compaction_notice`)&&t.workId===e.workId)?x(`compacted`):Wo(e,e.path,{trigger:`manual`,resumesRun:!1,instructions:e.instructions}).pipe(ce(t=>es(e,`manual`,t)),F(t=>t===void 0?es(e,`manual`,void 0).pipe(N(`nothing_to_compact`)):x(`compacted`)))}var vs=St.pipe(K(xt(0)),K(Kt(2**53-1))),ys=G({reserveTokens:W(vs),keepRecentTokens:W(vs),backgroundTokens:W(vs)}),bs=G({enabled:W(z),reserveTokens:W(vs),keepRecentTokens:W(vs),backgroundTokens:W(vs),modelOverrides:W(qe(ct,ys))}),xs=U(bs,{onExcessProperty:`error`});function Ss(e){let t=xs(e??{});if(t._tag===`Failure`)throw new L(`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??ri.enabled,reserveTokens:t?.reserveTokens??n.reserveTokens??ri.reserveTokens,keepRecentTokens:t?.keepRecentTokens??n.keepRecentTokens??ri.keepRecentTokens,backgroundTokens:t?.backgroundTokens??n.backgroundTokens??ri.backgroundTokens}}}function Cs(e){return new L(`runtime`,`rejected`,e)}var ws={missing:`Instruction capabilities have no tool runtime`,runtime:`Tool runtime failed`,lease:`Tool lease failed`},Ts=class extends L{phase;constructor(e){super(`runtime`,`rejected`,ws[e]),this.phase=e}get diagnostic(){return ws[this.phase]}};function Es(e,t){if(e.type===`retry_attempt_started`)return{type:`auto_retry_attempt`,run:e.run,attempt:e.attempt};let n=(`Model request failed. Retry the request. `+co({runId:e.run.value,provider:t.provider,model:t.id})).slice(0,200);return e.type===`retry_scheduled`?{type:`auto_retry_start`,run:e.run,attempt:e.attempt,maxAttempts:e.maxAttempts,delayMs:e.delayMs,errorMessage:n}:e.finalError===void 0?{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success}:{type:`auto_retry_end`,run:e.run,attempt:e.attempt,success:e.success,finalError:n}}function Ds(e,t,n,r,i,a,o){let s=e.tools,c=i.modules??[],l=[...c,...a];return s===void 0?c.length>0||o.length>0?w(new Ts(`missing`)):x([]):D(function*(){let i={sessionId:t,commandId:n};r!==void 0&&(i={...i,meta:r});let a={sources:s.sources,session:i,sandbox:s.sandbox,onSandboxFailure:r=>yt(e.store,{sessionId:t,commandId:n},r).pipe(te),modules:[...s.modules,...l],tools:o,access:{...s.access,sessionGrants:()=>Cn(e.store,t)?.grants??{}}},c=yield*(yield*$n(s.execution===void 0?a:{...a,execution:s.execution}).pipe(p(()=>new Ts(`runtime`)))).acquire().pipe(p(()=>new Ts(`lease`)));return[c.executeTool,...c.tools]})}function Os(e,t,n,r,i,a,s){return b(D(function*(){let l=yield*e.instructions.load({sessionId:t.command.sessionId,commandId:t.command.entry.workId}),u=l.release;u!==void 0&&(yield*me(()=>M(u)));let d=yield*gi(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),f=yield*Ds(e,t.command.sessionId,t.command.entry.workId,t.command.entry.meta,l,r,i),h=Object.freeze({sessionId:t.command.sessionId,requestId:t.command.entry.requestId,commandId:t.command.entry.workId}),ee=yield*ii(e.store,h,n),te=t=>Ze(e.store,{sessionId:h.sessionId,workId:h.commandId,delivery:t}).pipe(o(e=>e.map(({message:e})=>e)),p(e=>({_tag:`MuleError`,phase:`control`,message:e instanceof L?e.message:`Session control delivery failed`}))),g=t.resume,ne=Ss(e.compaction)(d.model),re,_=0;return{run:yield*gs({store:e.store,sessionId:t.command.sessionId,workId:t.command.entry.workId,model:d.model,stream:d.stream,handoff:a,settings:ne,path:t.path,messages:t.messages,resuming:g!==void 0,run:(t,n)=>{_=0;let r=g;g=void 0;let i,a=e=>{if(e.type===`run_end`&&e.outcome===`failed`)return i=e,m;if(e.type===`message_end`&&e.value.role===`assistant`&&e.value.stopReason===`error`){let t=d.providerError?.(e.value);if(t!==void 0)return ee({...e,value:{...e.value,providerError:t}})}return ee(e)},u={model:d.model,modelStreamIdleTimeoutMs:e.modelStreamIdleTimeoutMs,retry:e.retry??gt,retryAfterMs:d.retryAfterMs,retryable:d.retryable,systemPrompt:l.text,prepareSystemPrompt:()=>(s===void 0?x([]):s()).pipe(o(e=>l.text+e.map(({name:e,text:t})=>`\n\n[extension:${e}]\n${t}`).join(``)),p(e=>({_tag:`MuleError`,phase:`model`,message:`Extension prompt is unavailable`,cause:e}))),messages:t,resume:r,tools:f,getSteeringMessages:()=>te(`steer`),prepareNextTurn:e=>n(e.context,e.newMessages.length).pipe(p(e=>({_tag:`MuleError`,phase:`control`,message:e.message}))),onRetry:t=>(t.type===`retry_finished`&&!t.success&&(_=t.attempt+1),Jn(e.store,h,Es(t,d.model),t.turn))};return Xn.run(d.stream===void 0?u:{...u,stream:d.stream},a).pipe(c(e=>{if(i===void 0)return m;if(Er(e)){let t=e.value.modelLimitReason??d.failureReason?.(e.value.message)??lo(e.value);return re=(_>1&&e.value.modelLimitReason===void 0?`The model failed ${String(_)} times on this conversation: ${t}`:t).slice(0,200),ee(i,re)}let t=Mn(e.cause);return ee(i,S(t)&&t.value.phase===`model`?`model:rejected: ${t.value.message}`.slice(0,200):co({runId:i.run.value,provider:d.model.provider,model:d.model.id}))}),p(e=>e.phase===`model`?new L(`model`,`rejected`,e.message,void 0,e):Cs(`Mule rejected the durable command run`)))}}),failureReason:re}}))}function ks(e,t,n){return b(D(function*(){let r=yield*gi(e.model.acquire({sessionId:t.command.sessionId,preference:t.modelPreference})),i=t.command.entry;return yield*_s({store:e.store,sessionId:t.command.sessionId,workId:i.workId,model:r.model,stream:r.stream,handoff:n,settings:Ss(e.compaction)(r.model),path:t.path,instructions:vn(i)?i.instructions:void 0})}))}var As=Object.freeze({maxRecoveries:2});function js(e){return new L(`runtime`,`rejected`,e)}function Ms(e){let t=`${e.boundary}:${e.cause}`,n=e instanceof Ts||e instanceof Bo||e instanceof Ge?e.diagnostic:e.boundary===`model`?e.message:void 0;return{kind:`failed`,reason:n===void 0?t:`${t}: ${n}`.slice(0,200)}}function Ns(e,t){return u(`shiitake_run_failed`,bt(t)).pipe(fe({workId:e,reason:`${t.boundary}:${t.cause}`}))}function Ps(e,t,n,r){return D(function*(){ti(e.store,n.queue);let i=yield*I({try:()=>Sr(n),catch:()=>js(`Agent work payload is invalid`)}),a=yield*Kr(e.store,i.work);if(a.abnormalTerminal!==void 0)return{kind:a.abnormalTerminal};let s=r?.incompatibleMigrations()[0];if(s!==void 0)return yield*u(`shiitake_run_contract_changed`).pipe(fe({workId:n.jobId,terminal:`contract_changed: ${s}`})),yield*w(js(`contract_changed: ${s}`));let c=new Set(r?.runParticipants().map(([e])=>e)??[]);if(vn(a.command.entry))return yield*ks(e,a,r?.compactionHandoff(c)),yield*Et(e.store,{sessionId:a.command.sessionId,commandFactId:i.work.commandFactId,workId:a.command.entry.workId,outcome:`completed`}),{kind:`completed`};let l=yield*I({try:()=>Me(e.store,i.work.sessionId,i.work.commandFactId,a.command.entry.workId),catch:()=>js(`Accepted run origin is unavailable`)}),d={sessionId:a.command.sessionId,workId:a.command.entry.workId,origin:l===null?null:{extensionId:Fn(Gn)(l.extensionId),correlation:l.correlation}},f=r===void 0?[]:yield*r.filesForRun(d,c),p=r===void 0?[]:yield*ve([...c],t=>r.modulesForRun(d,new Set([t])).pipe(F(n=>I({try:()=>{let r=e.extensions.grants.find(e=>e.id===t)?.grantKey??t;return n.map(e=>Le.grantAs(e,r))},catch:()=>js(`Extension tools are invalid`)})))).pipe(o(e=>e.flat())),m=r?.compactionHandoff(c),{run:h,failureReason:ee}=yield*Os(e,a,{core:f.length===0?t:yield*so(f.map(e=>e.descriptor.name)),extensions:r?.runParticipants()??[]},p,f,m,r===void 0?void 0:()=>r.promptSections(d,c));switch(h.status){case`completed`:return{kind:`completed`};case`cancelled`:return{kind:`cancelled`};case`failed`:return{kind:`failed`,reason:ee??lo(h)}}}).pipe(ae(e=>Ns(n.jobId,e).pipe(N(Ms(e)))))}var Fs=U(Yt,{onExcessProperty:`error`}),Is=U(R(z)),Ls=U(rr,{onExcessProperty:`error`});function Rs(e){if(e.reply===void 0)return;let t=jt(Ls(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 L(`contract`,`invalid`,`Verified Agent reply does not match its mail`);return t}function zs(e){let t=t=>({sessionId:H(t.sessionId),requireExistingSession:jt(Is(t.requireExistingSession),`Session admission condition is invalid`)??!1,command:jt(Zt(t.command),`Session command is invalid`),origin:jt(Fs(t.origin),`Session command origin is invalid`),when:t.when,mail:t.mail,reply:Rs(t),onAccepted:t.onAccepted,meta:t.meta===void 0?void 0:Qr(e.hostMeta,t.meta)}),n=(t,n)=>{let{sessionId:r,origin:i}=t,a=t.command;if(an(e.owner,r,a.requestId),t.requireExistingSession&&!be(e.owner,r))throw new L(`contract`,`closed`,`Session target is unavailable`);let o=e.readQueueHead(r);if(t.when===`idle`&&o.state!==`idle`&&bn(e.owner,r,a.requestId)===void 0)return Object.freeze({status:`not_ready`});a.type===`prompt`&&bn(e.owner,r,a.requestId)===void 0&&e.admitNew();let s=a.type===`prompt`&&a.delivery===`steer`&&o.state===`running`&&!o.cancellationRequested?o.jobId:void 0,c=Tr(e.owner,r,a,t.meta,i,e.contract(),s===void 0?n=>{e.enqueue(n,t.mail)}:void 0,s,t.reply);return t.onAccepted?.(r,c.accepted.commandId),n.set(r,(n.get(r)??!1)||c.delivery===`new`),Object.freeze({status:`accepted`,commandId:c.accepted.commandId,delivery:c.delivery})},r=(t,r)=>C(()=>{let i=new Map,a=I({try:()=>(i.clear(),e.owner.transactionSync(()=>t(e=>n(e,i)))),catch:e=>e instanceof L?e:new L(`store`,`unavailable`,`Session command admission is unavailable`)});return(r===`request`?e.commit(a):a).pipe(k(()=>M(()=>{for(let[t,n]of i)n&&ti(e.owner,t)})),k(()=>i.size>0?e.requestWake:m))});return Object.freeze({transact:(e,n=`request`)=>r(n=>e(e=>n(t(e))),n),withdraw:(t,n)=>I({try:()=>({sessionId:H(t),requestId:rt({requestId:n})}),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Withdrawal request is invalid`)}).pipe(F(t=>r(()=>wr(e.owner,t.sessionId,t.requestId),`request`))),admit:(e,n)=>I({try:()=>t(e),catch:e=>e instanceof L?e:new L(`contract`,`invalid`,`Session command is invalid`)}).pipe(F(e=>r(t=>t(e),n??`request`)))})}var Bs=`core`,Vs=256,Hs=1048576,Us=512,Ws=64,Gs=new TextEncoder,Ks=U(B(G({name:ct.pipe(K(Se(/^[a-z][A-Za-z0-9_-]{0,63}$/u))),text:ct.pipe(K(sn(1)),K(dr(e=>Gs.encode(e).byteLength<=8192)))})).pipe(K(Ke(16)))),qs=class extends Error{};function Js(e){return e.length<=Us?e:`${e.slice(0,511)}…`}var Ys=Pr(qr(Vt));function Xs(e){return e instanceof _i?e.reason:`${e._tag}: ${e.message}`}function Zs(e){return e instanceof _i||e instanceof vi||e instanceof Si||e instanceof yi}function Qs(e,t){let r=Mn(t);if(S(r)){let t=r.value;return t instanceof _i?Js(t.reason):Js(Zs(t)?`${e}: ${Xs(t)}`:`${e} failed`)}let i=n(xe(t));return S(i)?i.value instanceof Error?Js(i.value.name===`AsyncFiberError`?`${e} crossed an asynchronous boundary inside a core transaction`:`${e} defect: ${i.value.message}`):Js(`${e} defect`):Js(`${e} was interrupted`)}function $s(e){let t=Mn(e);return f(t)||t.value instanceof _i}function Z(e,t){return new vi({reason:e,message:t})}function ec(e,t){return e.length>=1&&e.length<=Vs?x(e):w(Z(`bound`,`${t} must be 1..256 characters`))}function tc(e){let t=Js(e.message);if(e instanceof yi)switch(e.reason){case`invalid`:return new L(`contract`,`invalid`,t);case`conflict`:return new L(`store`,`conflict`,t);case`not_found`:return new L(`store`,`rejected`,t);case`rejected`:return new L(`extensions`,`rejected`,t)}if(e instanceof Si)switch(e.reason){case`invalid`:return new L(`contract`,`invalid`,t);case`conflict`:return new L(`contract`,`conflict`,t);case`closed`:return new L(`runtime`,`closed`,t)}return e.reason===`bound`?new L(`contract`,`invalid`,t):new L(`store`,`unavailable`,t)}function nc(e){let{owner:t}=e,n=new WeakMap,r=new Map,a=new Set,c,l=new Set,p=new Set,h,ne=e=>Object.freeze({extensionId:e}),v=e=>F(xi,t=>t.extensionId===e?m:j(Error(`Extension read used another extension's context`))),ie=e=>F(bi,t=>{let r=n.get(t);return r?.extensionId===e?x(r):j(Error(`Extension write used outside its own core transaction`))}),y=e=>I({try:e,catch:()=>Z(`unavailable`,`Extension state is unavailable`)}),b=(e,t)=>e.admitted.grants.has(t)?m:w(Z(`unavailable`,`Extension is not granted ${t}`));function oe(e,n,r){let i=e.admitted.id,a=_r(qr(r.schema)),s=xr(r.schema),l=e=>{let t=a(e);return t._tag===`Failure`?w(Z(`decode`,`Stored ${n} record is invalid`)):x(t.success)};return Object.freeze({peek:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);let o=lt(t,i,n,r);if(o===void 0)return E();let s=a(o);if(s._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return A(s.success)},peekPage:r=>{if(c!==i||!e.admitted.grants.has(`state`))throw Error(`Extension read used outside its own projection`);if(!Number.isSafeInteger(r.limit)||r.limit<1||r.limit>Ws)throw Z(`bound`,`Page limit must be 1..64`);return Or(t,i,n,r).map(e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success})},get:r=>v(i).pipe(_(b(e,`state`)),_(y(()=>lt(t,i,n,r))),F(e=>e===void 0?x(E()):l(e).pipe(o(A)))),page:r=>v(i).pipe(_(b(e,`state`)),_(Number.isSafeInteger(r.limit)&&r.limit>=1&&r.limit<=Ws?m:w(Z(`bound`,`Page limit must be 1..64`))),_(y(()=>Or(t,i,n,r))),F(e=>ve(e,l))),put:a=>ie(i).pipe(_(b(e,`state`)),_(C(()=>{let e=s(a);if(e._tag===`Failure`)return w(Z(`encode`,`The ${n} record does not match its schema`));let o=JSON.stringify(e.success);if(Gs.encode(o).byteLength>Hs)return w(Z(`bound`,`The ${n} record exceeds 1 MiB`));let c=r.index?.(a)??null;return le([ec(r.key(a),`A record key`),c===null?x(null):ec(c,`A record index`)]).pipe(F(([e,r])=>y(()=>{Mt(t,i,n,e,r,o)})))}))),remove:r=>ie(i).pipe(_(b(e,`state`)),_(y(()=>{je(t,i,n,r)})))})}function se(e,n,r){let i=e.admitted.id,a=_r(qr(r.schema)),o=xr(r.schema),s=()=>{if(!l.has(i)||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Extension state update is unavailable`)},c=e=>{if(e.length<1||e.length>Vs)throw Z(`bound`,`A record key must be 1..256 characters`);return e},u=e=>{let t=a(e);if(t._tag===`Failure`)throw Z(`decode`,`Stored ${n} record is invalid`);return t.success};return Object.freeze({get:e=>{s();let r=lt(t,i,n,c(e));return r===void 0?E():A(u(r))},page:e=>{if(s(),!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>Ws)throw Z(`bound`,`Page limit must be 1..64`);return Or(t,i,n,e).map(u)},put:e=>{s();let a=o(e);if(a._tag===`Failure`)throw Z(`encode`,`The ${n} record does not match its schema`);let l=JSON.stringify(a.success);if(Gs.encode(l).byteLength>Hs)throw Z(`bound`,`The ${n} record exceeds 1 MiB`);let u=r.index?.(e)??null;u!==null&&c(u),Mt(t,i,n,c(r.key(e)),u,l)},remove:e=>{s(),je(t,i,n,c(e))}})}function ce(e){let n=e.admitted.id;return Object.freeze({set:(r,i)=>ie(n).pipe(k(()=>b(e,`timers`)),k(()=>ec(r,`A timer key`)),k(()=>Number.isSafeInteger(i)&&i>=0?m:w(Z(`bound`,`A timer instant is invalid`))),F(e=>y(()=>{zr(t,n,r,i),e.timersChanged=!0}))),cancel:r=>ie(n).pipe(k(()=>b(e,`timers`)),F(e=>y(()=>{Jt(t,n,r),e.timersChanged=!0}))),read:r=>v(n).pipe(_(b(e,`timers`)),_(y(()=>rn(t,n,r))),o(g))})}function ue(n){let r=n.admitted.id,i=(i,a)=>ie(r).pipe(k(()=>b(n,`attention`)),F(n=>I({try:()=>{H(i),a(),gn(t,i,e.readQueueHead(i)),n.observed.add(i)},catch:e=>e instanceof vi&&e.reason===`session_absent`?e:e instanceof L&&e.cause===`invalid`?Z(`bound`,e.message):Z(`unavailable`,`Attention update is unavailable`)})));return{set:(e,n)=>{let a=U(jr,{onExcessProperty:`error`})(n);return a._tag===`Failure`?w(Z(`bound`,`Attention item is invalid`)):i(e,()=>{if(!be(t,e))throw Z(`session_absent`,`Attention Session is absent`);hn(t,e,r,a.success)})},clear:(e,n)=>ec(n,`An attention id`).pipe(_(i(e,()=>{cr(t,e,r,n)})))}}function O(e){let t=e.admitted.id;return n=>ie(t).pipe(F(r=>e.admitted.grants.has(`send`)?I({try:()=>{let{requireExistingSession:e=!1}=n,i=r.admit({sessionId:n.sessionId,requireExistingSession:e,command:{type:`prompt`,requestId:n.prompt.requestId,delivery:n.prompt.delivery,text:n.prompt.text},when:n.when,origin:{kind:`extension`,extensionId:t,correlation:n.correlation??null}});return i.status===`accepted`?{_tag:`Accepted`,commandId:i.commandId,delivery:i.delivery}:{_tag:`NotReady`}},catch:e=>new Si({reason:e instanceof L?e.cause===`conflict`?`conflict`:e.cause===`closed`?`closed`:`invalid`:`invalid`,message:e instanceof L?e.message:`Session command is invalid`})}):w(new Si({reason:`closed`,message:`Extension is not granted send`}))))}function de(r,i,a){return C(()=>{let s,c,l=Error(`Extension transaction rolled back`);return e.door.transact(e=>{let t=ne(r.admitted.id);c={extensionId:r.admitted.id,admit:e,observed:new Set,timersChanged:!1},n.set(t,c),p.add(r.admitted.id);let a=h;h=c;try{s=pe(i.pipe(d(bi,t),d(xi,t)))}finally{h=a,n.delete(t),p.delete(r.admitted.id)}if(ot(s))throw l;return s.value},a).pipe(o(()=>{if(s===void 0)throw Error(`Extension transaction returned no exit`);return s}),ae(e=>s!==void 0&&ot(s)?x(s):w(e)),k(n=>Er(n)&&c!==void 0?D(function*(){for(let e of c?.observed??[])ti(t,e);a===`request`&&c?.timersChanged===!0&&(yield*e.requestWake)}):m))})}function me(n){let r=``;for(let i=0;i<yn;i+=Ws){let i=Un(t,n,r);for(let n of i)gn(t,n,e.readQueueHead(n)),queueMicrotask(()=>{ti(t,n)});let a=i.at(-1);if(i.length<Ws||a===void 0)return;r=a}}function P(e,n,r,i){let a=Date.now();e.status=`stopped`,e.reason=n,e.stoppedAt=a;let o=I({try:()=>{let r=()=>{jn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:a,revision:e.admitted.revision}),me(e.admitted.id)};i===`own-transaction`?t.transactionSync(r):r()},catch:t=>new L(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)});return D(function*(){let t=yield*T(o);return yield*u(`shiitake_extension_stopped`).pipe(fe({extensionId:e.admitted.id,reason:n,cause:r===void 0?null:bt(r),durable:Er(t)})),yield*t})}function ge(e,n,r){e.status=`stopped`,e.reason=n,e.stoppedAt=Date.now();let i=()=>{jn(t,e.admitted.id,{status:`stopped`,reason:n,stoppedAt:e.stoppedAt,revision:e.admitted.revision}),me(e.admitted.id)};try{r===`own-transaction`?t.transactionSync(i):i()}catch(t){throw new L(`store`,`unavailable`,`Extension ${e.admitted.id} stop status is unavailable`,void 0,t)}}function _e(e,n,r){let i=t=>{if(h?.extensionId!==e.admitted.id||!e.admitted.grants.has(`state`))throw Z(`unavailable`,`Session documents require the extension's state transaction`);return H(t),h},a=a=>{i(a);let o=Ir(t,a,e.admitted.id,n)??Wa(r,r.initial);if(Gs.encode(o).byteLength>r.maxBytes)throw Z(`bound`,`Session document exceeds maxBytes`);let s=U(qr(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));Wn(t,o,e.admitted.id,n,Wa(r,l)),c.observed.add(o)}})}function ye(e){let n=new Set;return Object.freeze({collection:(t,n)=>oe(e,t,n),updateCollection:(t,n)=>se(e,t,n),document:(t,n)=>_e(e,t,n),update:r=>{let i=e.admitted.id;if(e.status!==`running`||!e.admitted.grants.has(`state`)||l.has(i)||p.has(i)||c===i)throw Z(`unavailable`,`Extension state update is unavailable`);try{let e=t.transactionSync(()=>{l.add(i);try{return kr(r,void 0)}finally{l.delete(i)}});for(let e of n)ti(t,e);return e}catch(t){if(!(t instanceof Lr))throw t;let n=t.message;throw ge(e,n,`own-transaction`),new _i({reason:n})}finally{n.clear()}},observeUpdate:t=>{if(!l.has(e.admitted.id))throw Z(`unavailable`,`Extension observation is unavailable`);n.add(H(t))},context:Object.freeze({manifest:e.admitted.manifest,revision:e.admitted.revision,grants:Object.freeze([...e.admitted.grants]),send:O(e),timers:ce(e),attention:ue(e),sessionPosition:n=>v(e.admitted.id).pipe(_(b(e,`state`)),_(y(()=>{let e=H(n);if(!be(t,e))throw Z(`unavailable`,`Session timeline is unavailable`);return En(t,{sessionId:e})?.newestSequence??0}))),hasPendingSteer:n=>v(e.admitted.id).pipe(_(b(e,`run_tools`)),_(y(()=>kt(t,H(n.sessionId),n.workId)))),hasSuccessfulToolResult:(n,r)=>v(e.admitted.id).pipe(_(b(e,`run_tools`)),_(y(()=>Nn(t,H(n.sessionId),n.workId,r)))),observe:t=>ie(e.admitted.id).pipe(o(e=>{e.observed.add(t)})),transact:t=>(e.status===`running`?de(e,t,`request`).pipe(te):w(new _i({reason:e.reason??`Extension is stopped`}))).pipe(F(t=>{if(Er(t))return x(t.value);if(!$s(t.cause))return re(t.cause);let n=Qs(`transact`,t.cause);return P(e,n,t.cause,`own-transaction`).pipe(F(()=>w(new _i({reason:n}))))}))})})}function xe(e){let{id:n,definition:r,revision:i}=e.admitted,a=r.state.version,o=at(t,n);if(o!==void 0&&o.version>a)throw new L(`extensions`,`conflict`,`Stored ${n} state version ${String(o.version)} is newer than ${String(a)}`);if(o!==void 0&&o.version<a){let e=Wt(t,n).map(e=>({collection:e.collection,key:e.key,value:Ys(e.valueJson)}));for(let t=o.version;t<a;t+=1){let i=r.state.migrations[t];if(i===void 0)throw new L(`extensions`,`state_reset_required`,`State reset required for ${n}: stored version ${String(o.version)}, declared version ${String(a)}. An operator must authorize the reset; stored records have not been changed.`);try{e=e.flatMap(e=>i(e))}catch(e){throw new qs(`Failed ${n} state migration from ${String(t)}`,{cause:e})}}It(t,n);for(let i of e){let e=r.state.collections[i.collection];if(e===void 0)throw new qs(`Migrated ${n} record names an undeclared collection`);let a=e.indexFromEncoded(i.value);if(a._tag===`Failure`)throw new qs(`Migrated ${n} ${i.collection} record is invalid`);Mt(t,n,i.collection,i.key,a.success,JSON.stringify(i.value))}}Ce(t,n,a,i)}function Se(e,t,n=!1){let r=ye(e);return D(function*(){let i=yield*Pt(t);e.scope=i;let a=yield*C(()=>e.admitted.definition.activate(r)).pipe(d(Ve,i),T);if(Er(a)){e.hooks=a.value;return}if(yield*dt(i,a),n)return yield*w(new L(`extensions`,`rejected`,`Extension ${e.admitted.id} failed to start: ${pr(a.cause)}`));yield*P(e,Qs(`activation`,a.cause),a.cause,`own-transaction`)})}let R=e=>[...r.values()].filter(t=>t.status===`running`&&t.hooks!==void 0&&t.admitted.grants.has(e));function we(e){return Object.freeze({id:e.admitted.id,version:e.admitted.manifest.version,revision:e.admitted.revision,status:e.status,reason:e.reason,stoppedAt:e.stoppedAt})}function Te(e){return e.status===`running`&&e.hooks!==void 0&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))}function Ee(e,t,n){return T(n.pipe(d(xi,ne(e.admitted.id)))).pipe(F(n=>Er(n)?x(A(n.value)):P(e,Qs(t,n.cause),n.cause,`own-transaction`).pipe(N(E()))))}let De=(e,t,n)=>ot(n)?P(e,Qs(t,n.cause),n.cause,`own-transaction`):m;function z(e){return I({try:()=>{t.transactionSync(()=>{xe(e);for(let[n,r]of Object.entries(e.admitted.documents))et(t,{extensionId:e.admitted.id,name:n,initialJson:Wa(r,r.initial),fork:r.fork,maxBytes:r.maxBytes})})},catch:e=>e}).pipe(k(()=>M(()=>{delete e.stateResetRequired})),N(!0),ae(t=>t instanceof L?t.cause===`state_reset_required`?(e.stateResetRequired=t,P(e,Js(t.message),At(t),`own-transaction`).pipe(N(!1))):w(t):(t instanceof qs&&(e.admitted.grants.has(`run_tools`)||e.admitted.grants.has(`files`)||e.admitted.grants.has(`prompt`)||e.admitted.grants.has(`compaction_handoff`))&&a.add(e.admitted.id),P(e,Js(t instanceof Error?`migration: ${t.message}`:`migration failed`),en(t),`own-transaction`).pipe(N(!1)))))}return D(function*(){let n=yield*ci();function l(e,r){return D(function*(){let i=cn(t,e.id),a=i?.status===`stopped`&&i.revision===e.revision,o={admitted:e,hooks:void 0,status:a?`stopped`:`running`,reason:a?i.reason:null,stoppedAt:a?i.stoppedAt:null};return yield*I({try:()=>{e.grants.has(`settled`)&&t.transactionSync(()=>{V(t,e.id)===void 0&&pt(t,e.id,V(t,`core`)??0)})},catch:()=>new L(`store`,`unavailable`,`Settled cursor is unavailable`)}),!(yield*z(o))||a?r?yield*w(new L(`extensions`,`rejected`,`Extension ${e.id} cannot start: ${o.reason??`stopped`}`)):o:(yield*I({try:()=>{t.transactionSync(()=>{jn(t,e.id,{status:`running`,reason:null,stoppedAt:null,revision:e.revision}),me(e.id)})},catch:()=>new L(`store`,`unavailable`,`Extension status is unavailable`)}),yield*Se(o,n,r),o)})}for(let t of e.admitted){let e=yield*l(t,!1).pipe(i(()=>dt(n,on)));r.set(t.id,e)}yield*I({try:()=>{t.transactionSync(()=>{let n=Rn(t,e.admitted.filter(e=>e.grants.has(`attention`)).map(e=>e.id));for(let e of n)me(e)})},catch:()=>new L(`store`,`unavailable`,`Attention grants are unavailable`)});let u={stage:e=>D(function*(){let n=e.filter(e=>{let t=r.get(e.id);return t!==void 0&&t.admitted.fingerprint!==e.fingerprint});if(n.length>0)return yield*w(new L(`extensions`,`rejected`,`Extensions ${n.map(({id:e})=>e).join(`, `)}: this change needs a restart: run fungi stop, then reopen fungi`));let o=new Map,s=C(()=>ve([...o.values()].reverse(),e=>T(e.scope===void 0?m:dt(e.scope,on)),{concurrency:1}).pipe(k(()=>M(()=>{for(let t of e)r.has(t.id)||a.delete(t.id)})),F(Xt)));yield*D(function*(){for(let t of e)r.has(t.id)||o.set(t.id,yield*l(t,!0))}).pipe(i(()=>s));let c=new Set(e.map(({id:e})=>e)),u=!1;return{discard:C(()=>u?m:(u=!0,s)),apply:D(function*(){if(u)return yield*w(new L(`extensions`,`rejected`,`Roster transition already settled`));yield*I({try:()=>{t.transactionSync(()=>{for(let[e,n]of r)c.has(n.admitted.id)||ui(t,e);let n=Rn(t,e.filter(e=>e.grants.has(`attention`)).map(({id:e})=>e));for(let e of n)me(e)})},catch:()=>new L(`store`,`unavailable`,`Roster publication storage is unavailable`)});for(let[e,t]of r)c.has(t.admitted.id)||(t.scope!==void 0&&(yield*dt(t.scope,on)),r.delete(e),a.delete(t.admitted.id));for(let[e,t]of o)r.set(e,t);u=!0})}}),runParticipants:()=>[...r.values()].filter(Te).map(e=>[e.admitted.id,e.admitted.fingerprint]),incompatibleMigrations:()=>[...a],modulesForRun:(e,t)=>ve(R(`run_tools`),n=>{let r=n.hooks?.moduleForRun;return!t.has(n.admitted.id)||r===void 0?x(E()):Ee(n,`moduleForRun`,C(()=>r(e))).pipe(o(s))}).pipe(o(e=>e.flatMap(he))),filesForRun:(e,t)=>D(function*(){let n=R(`files`).find(e=>t.has(e.admitted.id));if(n===void 0)return[];let r=n.hooks?.filesForRun;if(r===void 0)return yield*P(n,`files: granted capability has no handler`,void 0,`own-transaction`),yield*w(new L(`extensions`,`rejected`,`Extension Files are unavailable`));let i=yield*Ee(n,`filesForRun`,C(()=>r(e)));return f(i)?yield*w(new L(`extensions`,`rejected`,`Extension Files capture failed`)):Object.freeze([...ee(i.value,()=>[])])}),promptSections:(e,t)=>D(function*(){let n=[],r=0;for(let i of R(`prompt`)){if(!t.has(i.admitted.id))continue;let a=i.hooks?.prompt;if(a===void 0)return yield*P(i,`prompt: granted capability has no handler`,void 0,`own-transaction`),yield*w(new L(`extensions`,`rejected`,`Extension prompt is unavailable`));let o=yield*T(ur(()=>a(e)).pipe(d(xi,ne(i.admitted.id))));if(ot(o))return yield*P(i,Qs(`prompt`,o.cause),o.cause,`own-transaction`),yield*w(new L(`extensions`,`rejected`,`Extension prompt failed`));let s=Ks(o.value),c=s._tag===`Success`?s.success:[];if(r+=c.reduce((e,t)=>e+Gs.encode(t.text).byteLength,0),s._tag===`Failure`||new Set(c.map(({name:e})=>e)).size!==c.length||r>65536)return yield*P(i,`prompt: section is invalid or exceeds its bound`,void 0,`own-transaction`),yield*w(new L(`extensions`,`rejected`,`Extension prompt is invalid`));n.push(...[...c].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name)).map(e=>({name:`${i.admitted.id}.${e.name}`,text:e.text})))}return n}),compactionHandoff:e=>R(`compaction_handoff`).find(({admitted:t})=>e.has(t.id))?.hooks?.compactionHandoff,settledConsumers:()=>R(`settled`).map(e=>({id:e.admitted.id,cursor:V(t,e.admitted.id)??0})),deliverSettled:(e,n)=>ve(R(`settled`),r=>C(()=>{let i=V(t,r.admitted.id)??0;if(n<=i)return m;let a=e.filter(({sequence:e})=>e>i),o=r.hooks?.onSettled;return de(r,(o===void 0||a.length===0?m:o(a)).pipe(_(M(()=>{pt(t,r.admitted.id,n)}))),`reconcile`).pipe(F(e=>De(r,`onSettled`,e)))}),{discard:!0}),fireDueTimers:e=>D(function*(){let n=R(`timers`).map(({admitted:e})=>e.id),i=Je(t,n,e,Ws);for(let n of i){let i=r.get(n.extensionId);if(i?.status!==`running`)continue;let a=i.hooks?.onTimer,o=yield*de(i,C(()=>rn(t,n.extensionId,n.key)===n.dueAt?(Jt(t,n.extensionId,n.key),a===void 0?m:a({key:n.key,dueAt:n.dueAt,firedAt:e})):m),`reconcile`);yield*De(i,`onTimer`,o)}return i.length===Ws}),timerWake:e=>dn(t,R(`timers`).map(({admitted:e})=>e.id),e),project:e=>{let t={};for(let n of r.values()){let r=n.admitted.grants.has(`projection`),i=n.admitted.grants.has(`commands`)?n.admitted.definition.catalog:void 0;if(!r&&i===void 0)continue;let a=n.admitted.revision,o=n.admitted.definition.contract.projection,s=n.hooks?.project;if(n.status===`running`&&n.hooks!==void 0){let l=!r||s===void 0||o===null?A(null):(()=>{let t=null,r;c=n.admitted.id;try{let r=kr(()=>s(e),void 0);if(S(r)){let e=xr(o.schema)(r.value);if(e._tag===`Failure`)throw Error(`Extension projection is invalid`);let a=U(Vt)(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=Fn(Vt)(kr(()=>s(a.success),void 0)))}}catch(e){r=e}finally{c=void 0}return r===void 0?A(t):(ge(n,Js(r instanceof Error?`project defect: ${r.message}`:`project defect`),`enclosing-transaction`),E())})();if(S(l)){t[n.admitted.id]=Object.freeze(i===void 0?{status:`running`,revision:a,value:l.value}:{status:`running`,revision:a,value:l.value,catalog:i});continue}}t[n.admitted.id]=Object.freeze({status:`stopped`,revision:a,reason:n.reason??`Extension did not activate`})}return Object.freeze(t)},call:(e,t,n,i)=>D(function*(){let a=r.get(t);if(a?.admitted.grants.has(`commands`)!==!0)return yield*w(new L(`extensions`,`unavailable`,`Extension is unavailable`));if(a.status!==`running`||a.hooks===void 0)return yield*w(a.stateResetRequired??new L(`extensions`,`unavailable`,`Extension ${t} is stopped: ${a.reason??`not activated`}`));let o=a.admitted.definition.contract.commands,s=Object.hasOwn(o,n)?o[n]:void 0;if(s?.scope!==e.scope)return yield*w(new L(`contract`,`invalid`,`Extension command is unknown`));let c=e.scope===`session`?yield*I({try:()=>H(e.sessionId),catch:()=>new L(`contract`,`invalid`,`Session id is invalid`)}):null,l=a.hooks.commands.get(n);if(l===void 0)return U(s.input,{onExcessProperty:`error`})(i)._tag===`Failure`?yield*w(new L(`contract`,`invalid`,`Extension command input is invalid`)):(yield*P(a,`command ${n} has no handler`,void 0,`own-transaction`),yield*w(new L(`extensions`,`unavailable`,`Extension is stopped`)));let u=l({sessionId:c,input:i});if(u._tag===`Failure`)return yield*w(new L(`contract`,`invalid`,`Extension command input is invalid`));let d=yield*de(a,u.success(),`request`);if(Er(d))return d.value;let f=Mn(d.cause);if(S(f)&&!$s(d.cause))return yield*w(tc(f.value));let p=Qs(`command ${n}`,d.cause);return yield*P(a,p,d.cause,`own-transaction`),yield*w(new L(`extensions`,`unavailable`,`Extension ${t} is stopped: ${p}`))}),list:()=>[...r.values()].map(we),resume:i=>D(function*(){let a=r.get(i);return a===void 0?yield*w(new L(`extensions`,`unavailable`,`Extension is unavailable`)):(a.status===`stopped`&&(yield*I({try:()=>{t.transactionSync(()=>{jn(t,a.admitted.id,{status:`running`,reason:null,stoppedAt:null,revision:a.admitted.revision}),me(a.admitted.id)})},catch:()=>new L(`store`,`unavailable`,`Extension status is unavailable`)}),a.status=`running`,a.reason=null,a.stoppedAt=null,a.hooks===void 0&&(yield*z(a))&&(yield*Se(a,n)),yield*e.requestWake),we(a))}),close:dt(n,on)};return Object.freeze(u)})}var rc=64;function Q(e){return new L(`runtime`,`rejected`,e)}function ic(e,t,n){return t===void 0?m:D(function*(){let r=yield*I({try:()=>Sr(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`cancelled`?``:yield*wt(e,r.work),a=yield*we(e,r.work,n.outcome),o=n.outcome===`completed`||n.outcome===`cancelled`?void 0:yield*Qn(e,r.work),s=o===void 0?{job:n,content:i}:{job:n,content:i,diagnostic:o};yield*t.fanOut(a===void 0?s:{...s,meta:a}).pipe(p(()=>Q(`Agent reply fan-out is unavailable`)))})}function ac(e,t){let n=t.outcome;return n!==`interrupted`&&n!==`cancelled`&&n!==`failed`?m:D(function*(){let r=yield*I({try:()=>Sr(t),catch:()=>Q(`Agent work payload is invalid`)});yield*Et(e,{sessionId:r.work.sessionId,commandFactId:r.work.commandFactId,workId:t.jobId,outcome:n,diagnostic:t.failureReason})})}function oc(e,t,n){return D(function*(){let r=yield*I({try:()=>Sr(n),catch:()=>Q(`Agent work payload is invalid`)}),i=n.outcome===`outcome_unknown`?`interrupted`:n.outcome;yield*Be(e,{sessionId:r.work.sessionId,parentWorkId:n.jobId,outcome:i,diagnostic:n.failureReason,enqueue:e=>{t.transactional.enqueueAcceptedJob(On({work:{...e,recovery:As}}))}})})}function sc(e){return e===void 0?m:e.drainOutbox().pipe(p(()=>Q(`Agent reply delivery is unavailable`)))}function cc(e,t){return D(function*(){let n=yield*I({try:()=>Sr(t),catch:()=>Q(`Agent work payload is invalid`)}),i=yield*I({try:()=>Gr(e,n.work.sessionId),catch:()=>Q(`Session lineage state is unavailable`)});return i&&(yield*r(`shiitake_settlement_session_refused`).pipe(fe({workId:t.jobId}))),i})}function lc(e,t){let n=Sr(t.job),r=Gr(e,n.work.sessionId)?Object.freeze({terminal:`missing`,toolCalls:0,origin:Me(e,n.work.sessionId,n.work.commandFactId,t.job.jobId)}):Pe(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:Fn(Gn)(r.origin.extensionId),correlation:r.origin.correlation})})}function uc(e,t,n,r){return ve(r,r=>D(function*(){ti(e,r.job.queue),(yield*cc(e,r.job))||(yield*ac(e,r.job),yield*oc(e,t,r.job),yield*ic(e,n,r.job)),yield*I({try:()=>{pt(e,Bs,r.sequence)},catch:()=>Q(`Settled cursor is unavailable`)})}),{discard:!0})}function dc(e){return D(function*(){if((yield*e.watchdog.tick()).status===`busy`)return yield*w(Q(`Runtime reconciliation is already active`));let t=yield*I({try:()=>V(e.store,`core`)??0,catch:()=>Q(`Settled cursor is unavailable`)}),n=e.extensions.settledConsumers(),r=Math.min(t,...n.map(({cursor:e})=>e)),i=yield*e.watchdog.readSettled(rc,r),a=yield*T(uc(e.store,e.watchdog,e.mailRoom,i.filter(({sequence:e})=>e>t))),o=yield*I({try:()=>{let t=V(e.store,`core`)??0;return i.filter(({sequence:e})=>e<=t).map(t=>lc(e.store,t))},catch:()=>Q(`Settled run facts are unavailable`)});yield*e.extensions.deliverSettled(o,V(e.store,`core`)??0);let s=yield*e.extensions.fireDueTimers(Date.now());if((i.length===rc||s)&&(yield*e.requestWake),yield*sc(e.mailRoom),ot(a))return yield*re(a.cause)}).pipe(p(e=>e instanceof L?e:Q(`Runtime reconciliation failed`)))}function $(e){return new L(`runtime`,`rejected`,e)}function fc(e,n,r,a){return D(function*(){if(e.hostJobs?.lane==="default")return yield*w($(`Host lane conflicts with Agent work`));let s=`open`,c,l,d=Yr(!1),f=e=>M(()=>{s===`open`&&(c??=e)}),ee=C(()=>s===`open`?(s=`closing`,l=c,d.open):m).pipe(ie),g={},ne={current:void 0},v=e,y,b=!1,S=C(()=>g.requestWake??w($(`Runtime host is unavailable`))),oe={current:void 0},se=new Set,T=new Map,E={owner:e.store,isAlive:()=>x(!1),executor:{execute:t=>de(M(()=>{let n=t.lane===e.hostJobs?.lane?{kind:`host`,lane:t.lane,jobId:t.jobId}:{kind:`session`,sessionId:t.queue,commandId:t.jobId};T.set(n.kind===`host`?`host`:`serial`,n),n.kind===`session`&&se.add(t.queue),Sn(e.store)}),()=>t.lane===e.hostJobs?.lane?oe.current?.execute(t)??w(new hi(`execution_failed`)):D(function*(){let r=y;if(r!==void 0){yield*r.apply;let{tools:t,...n}=e;v={...n,...r.configuration},y=void 0}return yield*Ps(v,n,t,ne.current)}).pipe(ce(e=>u(`configuration_apply_failed`,e)),p(()=>new hi(`execution_failed`))),()=>M(()=>{t.lane!==e.hostJobs?.lane&&se.delete(t.queue),T.delete(t.lane===e.hostJobs?.lane?`host`:`serial`),Sn(e.store)}))},wake:{recompute:()=>S.pipe(p(()=>new hi(`wake_unavailable`)))},project:t=>{Xr(e.store,t,Date.now())}},O=yield*(e.hostJobs===void 0?mi(E):mi({...E,concurrentLane:e.hostJobs.lane}).pipe(k(t=>M(()=>{oe.current=e.hostJobs?.open(t)})))).pipe(p(()=>$(`Watchdog is unavailable`))),fe=()=>({core:n,extensions:[...ne.current?.runParticipants()??[]]});yield*I({try:()=>Ss(e.compaction),catch:e=>e instanceof L?e:$(`Compaction settings are unavailable`)});let A=yield*I({try:()=>ut(e.storagePressure),catch:e=>e instanceof L?e:$(`Storage budget is unavailable`)}),pe=zs({owner:e.store,admitNew:A.admitNew,hostMeta:e.meta,contract:fe,enqueue:(e,t)=>{let n={work:{...e,recovery:As}};O.transactional.enqueueAcceptedJob(On(t===void 0?n:{...n,mail:t}))},readQueueHead:e=>O.transactional.readQueueHead(e),commit:e=>C(()=>g.commit===void 0?w($(`Runtime host is unavailable`)):g.commit(e)),requestWake:S});yield*I({try:()=>{Xe(e.store),V(e.store,`core`)===void 0&&e.store.transactionSync(()=>{pt(e.store,Bs,0)})},catch:()=>new L(`store`,`unavailable`,`Extension store is unavailable`)});let j=yield*nc({owner:e.store,readQueueHead:e=>O.transactional.readQueueHead(e),door:pe,admitted:r,requestWake:S});ne.current=j;let me=dc({watchdog:O,store:e.store,extensions:j,requestWake:S,mailRoom:a}).pipe(ce(f)),N=D(function*(){let t=yield*O.hasPendingWork,n=Date.now(),r=yield*I({try:()=>[V(e.store,`core`)??0,...j.settledConsumers().map(({cursor:e})=>e)],catch:()=>$(`Settled cursor is unavailable`)}),i=(yield*O.readSettled(1,Math.min(...r))).length>0,o=yield*I({try:()=>j.timerWake(n),catch:()=>$(`Extension timers are unavailable`)}),s=a===void 0?void 0:yield*a.nextWakeAt().pipe(p(()=>$(`Reply retry wake is unavailable`))),c=o.nextWakeAt===null?s??null:s===void 0?o.nextWakeAt:Math.min(o.nextWakeAt,s);return{pending:t||i||o.due||s!==void 0&&s<=n,nextWakeAt:c}}),he=yield*e.runtime.bind({reconcile:me,pendingWork:N.pipe(p(()=>$(`Pending work is unavailable`)))}).pipe(i(()=>j.close.pipe(te))),P=C(()=>s===`open`?t(he.requestWake.pipe(ae(f)),d.await):m);return g.requestWake=P,g.commit=he.commit,yield*he.requestWake.pipe(i(()=>le([he.close,j.close]).pipe(te))),Object.freeze({prepareConfiguration:e=>D(function*(){if(s!==`open`||b||y!==void 0)return yield*w($(`A configuration change is already pending, or the Agent is closing`));b=!0;let t=yield*oo(e.extensions).pipe(F(e=>j.stage(e)),i(()=>M(()=>{b=!1}))),n=!1;return{commit:I({try:()=>{if(n||s!==`open`)throw $(`Configuration preparation is no longer available`);y={configuration:e,apply:t.apply},n=!0,b=!1},catch:e=>e instanceof L?e:$(`Configuration commit failed`)}),discard:C(()=>n?m:(n=!0,b=!1,t.discard))}}),activeSessions:M(()=>[...se]),runningWork:t=>O.read(t).pipe(o(t=>t.status===`found`?T.get(t.job.lane===e.hostJobs?.lane?`host`:`serial`)??null:null),p(e=>new L(`runtime`,`rejected`,`Running work is unavailable`,void 0,e))),extensions:j,commit:he.commit,assertOpen:C(()=>s===`open`?m:w(new L(`runtime`,`closed`,`Shiitake is closed`))),beginClose:ee,door:pe,createSessionWithinTransaction:t=>Vn(e.store,t,A.admitNew),stageSessionGrantsWithinTransaction:(t,n)=>{oi(e.store,t,n)},storage:A,recordAcceptedCancellation:({jobId:e,cancellationId:t,onlyIfPending:n})=>O.transactional.recordCancellationIntent({jobId:e,cancellationId:t,onlyIfQueued:n}),assertIdleSession:e=>{try{if(O.transactional.readQueueHead(e).state!==`idle`)throw new L(`runtime`,`conflict`,`Session branch or fork requires an idle Session`)}catch(e){throw e instanceof L?e:$(`Session status is unavailable`)}},signalCancellation:(e,t)=>O.cancel({jobId:e,cancellationId:t}).pipe(F(e=>e.status===`recorded`||e.status===`replayed`?m:w($(`Cancellation is unavailable`))),p(()=>$(`Cancellation is unavailable`))),readQueueHead:e=>O.readQueueHead(e).pipe(p(()=>$(`Session status is unavailable`))),readQueueHeadTransactional:e=>O.transactional.readQueueHead(e),requestWake:P,close:ee.pipe(_(h(he.close,{onFailure:e=>j.close.pipe(_(l===void 0?re(e):w(l))),onSuccess:()=>j.close.pipe(_(l===void 0?m:w(l)))})),ue(M(()=>{s=`closed`})))})})}var pc=e({openRuntimeCore:()=>mc});function mc(e,t){return D(function*(){let n=yield*oo(e.extensions),r=yield*so([]);yield*ei(e.store);let i=yield*fc(e,r,n,t),a=Va(e,i),o=Object.freeze({session:a.session,createSession:a.createSession,deleteSession:a.deleteSession,listSessions:a.listSessions,extensions:a.extensions,close:ga(a.close,i.close)}),s=Object.freeze({...o,prepareConfiguration:i.prepareConfiguration,grants:a.grants,withMeta:e=>Object.freeze({...o,session:a.withMeta(e).session})});return Object.freeze({agent:s,readSettlement:(t,n)=>i.assertOpen.pipe(_(Lt(e.store,t,n))),activeSessions:i.activeSessions,acceptMail:(e,n,r,a,o)=>Ha(i,e,n,r,a??(e=>{if(t?.postMail===void 0)throw Error(`Recipient Agent mail outbox is unavailable`);v(t.postMail(e))}),o)})})}export{pa as n,mc as openRuntimeCore,ca as r,pc as t};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{n as e}from"./models-BM_0GHMS.js";import{r as t}from"./runtime-core-DOL1texL.js";function n(){return typeof process>`u`||!(process.versions?.node||process.versions?.bun)?null:process.getBuiltinModule?.(`node:os`)??null}var r=n();function i(){return r?`pi (${r.platform()} ${r.release()}; ${r.arch()})`:`pi (browser)`}var a=class extends Error{},o=[`$ref`,`$defs`,`definitions`,`allOf`,`oneOf`,`patternProperties`,`dependentSchemas`,`dependencies`,`unevaluatedProperties`,`propertyNames`,`contains`,`prefixItems`,`not`,`if`,`then`,`else`];function s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function c(e){if(!s(e))return!1;let t=typeof e.type==`string`?[e.type]:Array.isArray(e.type)?e.type:[];return t.includes(`object`)||t.includes(`array`)||e.properties!==void 0||e.items!==void 0}function l(e){return s(e)?e.type===`null`||Array.isArray(e.type)&&e.type.includes(`null`)||e.const===null||Array.isArray(e.enum)&&e.enum.includes(null)?!0:Array.isArray(e.anyOf)&&e.anyOf.some(e=>l(e)):!1}function u(e,t){if(!s(e))throw new a(`boolean schemas are unsupported`);for(let t of o)if(e[t]!==void 0)throw new a(`${t} schemas are unsupported`);if(t){for(let[n,r]of Object.entries(e))if(t(n,r))throw new a(`${n}: ${JSON.stringify(r)} is unsupported`)}if(e.anyOf!==void 0){if(!Array.isArray(e.anyOf)||e.anyOf.length===0)throw new a(`anyOf must contain at least one schema`);for(let n of e.anyOf){if(c(n))throw new a(`object and array unions are unsupported`);u(n,t)}}if(e.items!==void 0){if(Array.isArray(e.items))throw new a(`tuple schemas are unsupported`);u(e.items,t)}let n=e.type===`object`;if(e.properties!==void 0&&!n)throw new a(`properties require type object`);if(!n)return;if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new a(`schema-valued or true additionalProperties is unsupported`);if(e.properties!==void 0&&!s(e.properties))throw new a(`object properties must be a schema map`);if(e.required!==void 0&&(!Array.isArray(e.required)||e.required.some(e=>typeof e!=`string`)))throw new a(`object required must be a string array`);let r=e.properties??{},i=Object.keys(r),d=new Set(Array.isArray(e.required)?e.required:[]);if([...d].some(e=>!i.includes(e)))throw new a(`required contains an unknown property`);for(let[e,n]of Object.entries(r))u(n,t),!d.has(e)&&!l(n)&&(r[e]={anyOf:[n,{type:`null`}]});e.required=i,e.additionalProperties=!1}function d(e,t){let n=structuredClone(e);if(!s(n)||(u(n,t),n.type!==`object`))throw new a(`root schema must have type object`);return n}function f(e,t){return t===!0?d(e.parameters):e.parameters}function p(e,t,n){let r=t[n];if(typeof r!=`string`)throw Error(`Grammar tool call "${e}" requires argument "${n}" to be a string.`);return r}function m(e,t,n,r){if(e.closed){if(r&&n===e.input)return;throw Error(`grammar tool input for property "${t}" changed after it was closed`)}if(!n.startsWith(e.input))throw Error(`grammar tool input for property "${t}" changed non-monotonically`);let i=n.slice(e.input.length);if(!r&&i.length===0)return;let a=``;return e.started||=(a+=`{${JSON.stringify(t)}:"`,!0),a+=JSON.stringify(i).slice(1,-1),e.input=n,r&&(a+=`"}`,e.closed=!0),a}function h(e){let t=e.parameters;if(t.type!==`object`)throw Error(`grammar constrained sampling requires an object parameter schema`);if(!Array.isArray(t.required)||t.required.length!==1||typeof t.required[0]!=`string`)throw Error(`grammar constrained sampling requires exactly one required string property`);let n=t.required[0];if(!t.properties?.[n])throw Error(`grammar constrained sampling requires a properties entry for ${n}`);if(t.properties[n]?.type!==`string`)throw Error(`grammar constrained sampling property ${n} must have type string`);return n}function g(e,t,n){let r=e.constrainedSampling;if(!(!r||r.type!==`json_schema`)){if(t)try{return d(e.parameters,n),!0}catch(t){if(!(t instanceof a))throw t;if(r.strict!==`require`)return;throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but ${t.message}.`)}if(r.strict===`require`)throw Error(`Tool "${e.name}" requires JSON-schema constrained sampling, but strict tools are unsupported.`)}}function _(e,t){let n=e.constrainedSampling;if(!n||n.type!==`grammar`||!t)return;let r=n.variants.openai_lark,i=n.variants.openai_regex,a=typeof r==`string`&&r.trim().length>0,o=typeof i==`string`&&i.trim().length>0;if(!a&&!o)throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: no supported grammar variant was provided.`);try{return{format:a?`lark`:`regex`,definition:a?r:i,inputProperty:h(e)}}catch(t){let n=t instanceof Error?t.message:String(t);throw Error(`Tool "${e.name}" cannot use grammar constrained sampling: ${n}.`)}}function v(e,t){let n=new Map;for(let r of e??[]){let e=_(r,t);e&&n.set(r.name,e.inputProperty)}return n}var y=4096,b=1;function x(e,n,r){if(e.contextWindow<=0)return Math.max(b,r);let i=e.contextWindow-t(n).tokens-y;return Math.min(r,Math.max(b,i))}function S(t,n,r){let i=e(t,n),a=t.samplingParamsByThinkingLevel?.[i];return t.samplingParams||a||r?{...t.samplingParams,...a,...r}:void 0}function C(e,t,n,r){let i=S(e,n?.reasoning??`off`,n?.samplingParams);return{temperature:n?.temperature,samplingParams:i,maxTokens:x(e,t,n?.maxTokens??e.maxTokens),signal:n?.signal,telemetryContext:n?.telemetryContext,apiKey:r||n?.apiKey,fetch:n?.fetch,transport:n?.transport,cacheRetention:n?.cacheRetention,sessionId:n?.sessionId,headers:n?.headers,onPayload:n?.onPayload,onResponse:n?.onResponse,onProviderStreamEvent:n?.onProviderStreamEvent,timeoutMs:n?.timeoutMs,websocketConnectTimeoutMs:n?.websocketConnectTimeoutMs,maxRetries:n?.maxRetries,maxRetryDelayMs:n?.maxRetryDelayMs,metadata:n?.metadata,env:n?.env}}var w=1024,T={minimal:1024,low:2048,medium:8192,high:16384};function E(e){return e===`xhigh`||e===`max`?`high`:e}function D(e,t){return{...T,...t}[E(e)]}function O(e,t){return Math.min(e,Math.max(0,t-w))}function k(e,t,n,r){let i=D(n,r),a=e===void 0?t:Math.min(e+i,t);return a<=i&&(i=O(i,a)),{maxTokens:a,thinkingBudget:i}}var A=`(image omitted: model does not support images)`,j=`(tool image omitted: model does not support images)`,M=`(image attached after the tool results)`;function N(e){if(!e.isError)return;let t=e.content.filter(e=>e.type===`image`);if(t.length!==0)return{content:P(e.content,M),caption:`Images from the error result of tool call ${e.toolCallId} (${e.toolName}):`,images:t}}function P(e,t){let n=[],r=!1;for(let i of e){if(i.type===`image`){r||n.push({type:`text`,text:t}),r=!0;continue}n.push(i),r=i.text===t}return n}function F(e,t){return t.input.includes(`image`)?e:e.map(e=>e.role===`user`&&Array.isArray(e.content)?{...e,content:P(e.content,A)}:e.role===`toolResult`?{...e,content:P(e.content,j)}:e)}function I(e,t,n){let r=new Map,i=F(e.map(e=>e.content==null?{...e,content:[]}:e),t).map(e=>{if(e.role===`system`||e.role===`user`)return e;if(e.role===`toolResult`){let t=r.get(e.toolCallId);return t&&t!==e.toolCallId?{...e,toolCallId:t}:e}if(e.role===`assistant`){let i=e,a=i.provider===t.provider&&i.api===t.api&&i.model===t.id,o=i.content.flatMap(e=>{if(e.type===`thinking`)return a?e.redacted||e.thinkingSignature?e:!e.thinking||e.thinking.trim()===``?[]:e:[];if(e.type===`text`)return a?e:{type:`text`,text:e.text};if(e.type===`toolCall`){let o=e,s=o;if(!a&&o.thoughtSignature&&(s={...o},delete s.thoughtSignature),!a&&n){let e=n(o.id,t,i);e!==o.id&&(r.set(o.id,e),s={...s,id:e})}return s}return e});return{...i,content:o}}return e}),a=[],o=[],s=new Set,c=[],l=()=>{if(o.length>0){for(let e of o)s.has(e.id)||a.push({role:`toolResult`,toolCallId:e.id,toolName:e.name,content:[{type:`text`,text:`No result provided`}],isError:!0,timestamp:Date.now()});o=[],s=new Set}a.push(...c),c.length=0};for(let e=0;e<i.length;e++){let t=i[e];if(t.role===`assistant`){l();let e=t;if(e.stopReason===`error`||e.stopReason===`aborted`)continue;let n=e.content.filter(e=>e.type===`toolCall`);n.length>0&&(o=n,s=new Set),a.push(t)}else t.role===`toolResult`?(s.add(t.toolCallId),a.push(t)):t.role===`system`?o.length>0?c.push(t):a.push(t):(t.role===`user`&&l(),a.push(t))}return l(),a}export{x as a,D as c,p as d,f,i as h,C as i,m as l,g as m,I as n,O as o,_ as p,k as r,S as s,N as t,v as u};
|