@fungi.computer/grove 0.4.0 → 0.5.0

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