alchemylab-opencode 2.0.3 → 2.0.4

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 (39) hide show
  1. package/dist/{anthropic-ND6UHXWL.js → anthropic-FVULF7C3.js} +1 -1
  2. package/dist/{app-runtime-ZWWQ4JTM.js → app-runtime-LDQWNGWP.js} +1 -1
  3. package/dist/{chunk-IQSFXWDQ.js → chunk-2JE3QYG6.js} +1 -1
  4. package/dist/{chunk-6MAPFAXY.js → chunk-4GJE6OMN.js} +1 -1
  5. package/dist/{chunk-AUB2TEYJ.js → chunk-5BLZCAU6.js} +1 -1
  6. package/dist/{chunk-XSKT4AXR.js → chunk-B74WSFN4.js} +3 -3
  7. package/dist/{chunk-2XWBNI3L.js → chunk-DADVNQTM.js} +80 -80
  8. package/dist/{chunk-RIA6SDOY.js → chunk-DWEYXIQI.js} +3 -3
  9. package/dist/{chunk-L3CE2Y3L.js → chunk-FOHYZ7MJ.js} +1 -1
  10. package/dist/{chunk-WL33KE3H.js → chunk-G7PFO5HG.js} +3 -3
  11. package/dist/{chunk-DGJQZN2Q.js → chunk-NGT6LCW6.js} +1 -1
  12. package/dist/{chunk-DZ6G4VSD.js → chunk-OT2YNR56.js} +1 -1
  13. package/dist/{chunk-WZ4237YY.js → chunk-OUVSKG2H.js} +1 -1
  14. package/dist/{chunk-F5PY52BY.js → chunk-UPEPL4I2.js} +1 -1
  15. package/dist/{code-mode-H3HRSD24.js → code-mode-YYOGD36U.js} +1 -1
  16. package/dist/{dist-KGNO5AP7.js → dist-KM5HCPZX.js} +1 -1
  17. package/dist/{dist-WZJ3LNRG.js → dist-YUH4RKR5.js} +1 -1
  18. package/dist/{dist-es-RZ25XEH6.js → dist-es-6PLFRCS4.js} +1 -1
  19. package/dist/{dist-es-EVVG3KDV.js → dist-es-G5UIJOU7.js} +2 -2
  20. package/dist/{dist-es-DHCTZZ2E.js → dist-es-HYIIGUNX.js} +1 -1
  21. package/dist/{dist-es-CH2YKBKX.js → dist-es-LSR2QCFZ.js} +1 -1
  22. package/dist/{dist-es-HRCONNGK.js → dist-es-W5GYOX6F.js} +1 -1
  23. package/dist/run.js +1 -1
  24. package/dist/serve.js +1 -1
  25. package/dist/{server-XRUYBM7W.js → server-LVIHYOCY.js} +3 -3
  26. package/dist/{session-4BXV4JJH.js → session-6OPJNJMK.js} +1 -1
  27. package/dist/{src-QJHT5SCV.js → src-3NCXEROI.js} +1 -1
  28. package/dist/{worktree-B2LROS2B.js → worktree-32M5MTFE.js} +1 -1
  29. package/package.json +1 -1
  30. /package/dist/{dist-LOXU6IEM.js → dist-CYBRID2F.js} +0 -0
  31. /package/dist/{lib-7VH6D2QJ.js → lib-ZP7Q6A3E.js} +0 -0
  32. /package/dist/{mime-types-GSWEOYZ5.js → mime-types-46EO4HOZ.js} +0 -0
  33. /package/dist/{signin-DKBWDEYP.js → signin-OCIW23YM.js} +0 -0
  34. /package/dist/{src-JODD73WX.js → src-LXWGIUZH.js} +0 -0
  35. /package/dist/{src-SMM4U63G.js → src-YAAFIGTW.js} +0 -0
  36. /package/dist/{sso-oidc-S3P64MCY.js → sso-oidc-OMMKINFE.js} +0 -0
  37. /package/dist/{sts-RG44NMOQ.js → sts-MWK22JIX.js} +0 -0
  38. /package/dist/{token-2V62AM3G.js → token-QPO3OAGS.js} +0 -0
  39. /package/dist/{token-util-VXONHEUD.js → token-util-YGPCEEPO.js} +0 -0
@@ -15,11 +15,11 @@ import { dirname as __alchemyDirname } from 'node:path';
15
15
  const __alchemy_filename = __alchemyFileURLToPath(import.meta.url);
16
16
  const __alchemy_dirname = __alchemyDirname(__alchemy_filename);
17
17
 
18
- import{A as Ge,B as Rt,C as ns,E as Qu,F as pt,G as yt,H as Ft,b as _n,h as ai,l as ci,m as Mu,n as _u,o as Ou,p as Ha,q as ju,r as Uu,s as Fu,u as Gu,w as Xe,x as Yu,y as Ju,z as wo}from"./chunk-WL33KE3H.js";import{b as yi,c as Zo,d as Ku,e as Xu,g as er}from"./chunk-6MAPFAXY.js";import{L as zt,N as Ke,P as Xn,R as hi,U as Hu,V as gi,X as cn,i as ku}from"./chunk-XSKT4AXR.js";import{R as me,a as ts,b as Lu,c as Nu,d as Dn,e as Za,f as Wu,g as bo,h as mi,i as nc,j as Pt,k as at,l as Fe,m as oc,n as Vu,o as zu,p as Ze,q as an}from"./chunk-L3CE2Y3L.js";import{$a as yn,C as hu,Da as G,E as gu,F as yu,Fa as ut,G as bu,Ga as pi,H as wu,I as vu,J as xu,Ja as be,K as xt,Ka as Xa,L as Su,La as st,M as si,Ma as gn,N as Xo,Na as Kn,O as Wa,Oa as Qa,P as Iu,Pa as it,Q as Va,R as yo,S as Jn,T as On,U as za,_a as Oe,ab as fi,c as Yn,cb as $u,f as qa,fa as Eu,ga as Tu,gb as qu,h as ho,ha as Ut,ia as li,ib as ec,jb as Qo,k as kn,kb as De,la as Ya,lb as tc,ma as Ja,mb as Be,pa as Ka,r as dt,ra as di,s as Vt,u as ri,v as Tt,va as Xt,wa as Bu,xa as ui,y as go}from"./chunk-RIA6SDOY.js";import{G as Ga}from"./chunk-V6FDDNGV.js";import{a as ii}from"./chunk-QCRIXKIC.js";import{a as Ru,b as Cu,c as Au}from"./chunk-LIXP4TPL.js";import{a as Pu}from"./chunk-M6E6KNLV.js";import{d as kg}from"./chunk-NDI67DRG.js";import{a as oi}from"./chunk-K5LKDIVU.js";import{c as se,d as Hn,f as mo}from"./chunk-R2GWBJEP.js";import{$a as Zs,$b as Ce,Aa as Et,Ab as Zd,Bb as ei,Cb as Ba,Fa as Cn,Fb as $a,Gb as eu,Ib as tu,Jb as nu,Kb as ou,La as sn,Lb as ru,Ma as uo,Nb as su,Pa as St,Qb as iu,Rb as Mn,Sb as rt,Tb as gt,Wb as es,Xb as Gn,Ya as Ua,Zc as du,ac as Yo,b as Wd,bc as au,bd as uu,c as Vn,cd as pu,db as Kr,dc as ti,de as fu,eb as Kd,fa as zd,g as ja,gc as Jo,ge as mu,ha as ke,hc as cu,ia as Xs,ic as Sn,jc as fo,lb as Xr,m as Jr,ma as mn,mb as Se,mc as In,nb as Qr,nc as lu,oa as Gd,ob as Zr,pa as hn,pc as Ae,q as Ve,qa as Hd,qb as Qe,r as zn,rb as po,rc as ni,sa as Yd,sb as An,tb as Xd,ub as Fa,uc as Ko,vb as Wt,wb as Qd,x as fn,xb as lt,ya as Qs,za as Jd}from"./chunk-7XX6TY62.js";import{g as Du}from"./chunk-UCLPBO4I.js";import{h as Ks,k as Ho,t as Rn}from"./chunk-VWLJXTZ5.js";import{Ah as Hs,Bc as Dt,Bf as r,Bh as Ys,Dh as Ud,Fg as Yr,Fi as Vd,Ig as Ad,Ih as Fd,Ma as Ed,Nh as Bd,Tc as Te,Th as $d,Wh as Js,Yh as Na,Z as Dd,Zh as qd,aa as xn,bb as Re,bi as vt,dc as ht,hh as Oa,ja as Ma,jd as tt,lc as bt,mh as La,nb as Td,pa as _a,pd as Pd,pj as c,qh as Md,rg as Vs,rh as _d,tg as Cd,th as Od,uh as zs,vh as Gs,wa as Go,wh as Ld,xh as Nd,zd as Rd,zh as jd}from"./chunk-ELPXQ32J.js";import{a as i,b as Hr,d as kt,e as fe,g as kd}from"./chunk-2MRHL4B2.js";var vr=kt(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.stringArray=Lt.array=Lt.func=Lt.error=Lt.number=Lt.string=Lt.boolean=void 0;function Kv(e){return e===!0||e===!1}i(Kv,"boolean");Lt.boolean=Kv;function qf(e){return typeof e=="string"||e instanceof String}i(qf,"string");Lt.string=qf;function Xv(e){return typeof e=="number"||e instanceof Number}i(Xv,"number");Lt.number=Xv;function Qv(e){return e instanceof Error}i(Qv,"error");Lt.error=Qv;function Zv(e){return typeof e=="function"}i(Zv,"func");Lt.func=Zv;function Wf(e){return Array.isArray(e)}i(Wf,"array");Lt.array=Wf;function ex(e){return Wf(e)&&e.every(t=>qf(t))}i(ex,"stringArray");Lt.stringArray=ex});var nl=kt(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Message=ye.NotificationType9=ye.NotificationType8=ye.NotificationType7=ye.NotificationType6=ye.NotificationType5=ye.NotificationType4=ye.NotificationType3=ye.NotificationType2=ye.NotificationType1=ye.NotificationType0=ye.NotificationType=ye.RequestType9=ye.RequestType8=ye.RequestType7=ye.RequestType6=ye.RequestType5=ye.RequestType4=ye.RequestType3=ye.RequestType2=ye.RequestType1=ye.RequestType=ye.RequestType0=ye.AbstractMessageSignature=ye.ParameterStructures=ye.ResponseError=ye.ErrorCodes=void 0;var Eo=vr(),Mc;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(Mc||(ye.ErrorCodes=Mc={}));var _c=class e extends Error{static{i(this,"ResponseError")}constructor(t,n,o){super(n),this.code=Eo.number(t)?t:Mc.UnknownErrorCode,this.data=o,Object.setPrototypeOf(this,e.prototype)}toJson(){let t={code:this.code,message:this.message};return this.data!==void 0&&(t.data=this.data),t}};ye.ResponseError=_c;var Yt=class e{static{i(this,"ParameterStructures")}constructor(t){this.kind=t}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};ye.ParameterStructures=Yt;Yt.auto=new Yt("auto");Yt.byPosition=new Yt("byPosition");Yt.byName=new Yt("byName");var ct=class{static{i(this,"AbstractMessageSignature")}constructor(t,n){this.method=t,this.numberOfParams=n}get parameterStructures(){return Yt.auto}};ye.AbstractMessageSignature=ct;var Oc=class extends ct{static{i(this,"RequestType0")}constructor(t){super(t,0)}};ye.RequestType0=Oc;var Lc=class extends ct{static{i(this,"RequestType")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.RequestType=Lc;var Nc=class extends ct{static{i(this,"RequestType1")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.RequestType1=Nc;var jc=class extends ct{static{i(this,"RequestType2")}constructor(t){super(t,2)}};ye.RequestType2=jc;var Uc=class extends ct{static{i(this,"RequestType3")}constructor(t){super(t,3)}};ye.RequestType3=Uc;var Fc=class extends ct{static{i(this,"RequestType4")}constructor(t){super(t,4)}};ye.RequestType4=Fc;var Bc=class extends ct{static{i(this,"RequestType5")}constructor(t){super(t,5)}};ye.RequestType5=Bc;var $c=class extends ct{static{i(this,"RequestType6")}constructor(t){super(t,6)}};ye.RequestType6=$c;var qc=class extends ct{static{i(this,"RequestType7")}constructor(t){super(t,7)}};ye.RequestType7=qc;var Wc=class extends ct{static{i(this,"RequestType8")}constructor(t){super(t,8)}};ye.RequestType8=Wc;var Vc=class extends ct{static{i(this,"RequestType9")}constructor(t){super(t,9)}};ye.RequestType9=Vc;var zc=class extends ct{static{i(this,"NotificationType")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.NotificationType=zc;var Gc=class extends ct{static{i(this,"NotificationType0")}constructor(t){super(t,0)}};ye.NotificationType0=Gc;var Hc=class extends ct{static{i(this,"NotificationType1")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.NotificationType1=Hc;var Yc=class extends ct{static{i(this,"NotificationType2")}constructor(t){super(t,2)}};ye.NotificationType2=Yc;var Jc=class extends ct{static{i(this,"NotificationType3")}constructor(t){super(t,3)}};ye.NotificationType3=Jc;var Kc=class extends ct{static{i(this,"NotificationType4")}constructor(t){super(t,4)}};ye.NotificationType4=Kc;var Xc=class extends ct{static{i(this,"NotificationType5")}constructor(t){super(t,5)}};ye.NotificationType5=Xc;var Qc=class extends ct{static{i(this,"NotificationType6")}constructor(t){super(t,6)}};ye.NotificationType6=Qc;var Zc=class extends ct{static{i(this,"NotificationType7")}constructor(t){super(t,7)}};ye.NotificationType7=Zc;var el=class extends ct{static{i(this,"NotificationType8")}constructor(t){super(t,8)}};ye.NotificationType8=el;var tl=class extends ct{static{i(this,"NotificationType9")}constructor(t){super(t,9)}};ye.NotificationType9=tl;var Vf;(function(e){function t(s){let a=s;return a&&Eo.string(a.method)&&(Eo.string(a.id)||Eo.number(a.id))}i(t,"isRequest"),e.isRequest=t;function n(s){let a=s;return a&&Eo.string(a.method)&&s.id===void 0}i(n,"isNotification"),e.isNotification=n;function o(s){let a=s;return a&&(a.result!==void 0||!!a.error)&&(Eo.string(a.id)||Eo.number(a.id)||a.id===null)}i(o,"isResponse"),e.isResponse=o})(Vf||(ye.Message=Vf={}))});var rl=kt(to=>{"use strict";var zf;Object.defineProperty(to,"__esModule",{value:!0});to.LRUCache=to.LinkedMap=to.Touch=void 0;var Nt;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(Nt||(to.Touch=Nt={}));var qi=class{static{i(this,"LinkedMap")}constructor(){this[zf]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(t){return this._map.has(t)}get(t,n=Nt.None){let o=this._map.get(t);if(o)return n!==Nt.None&&this.touch(o,n),o.value}set(t,n,o=Nt.None){let s=this._map.get(t);if(s)s.value=n,o!==Nt.None&&this.touch(s,o);else{switch(s={key:t,value:n,next:void 0,previous:void 0},o){case Nt.None:this.addItemLast(s);break;case Nt.First:this.addItemFirst(s);break;case Nt.Last:this.addItemLast(s);break;default:this.addItemLast(s);break}this._map.set(t,s),this._size++}return this}delete(t){return!!this.remove(t)}remove(t){let n=this._map.get(t);if(n)return this._map.delete(t),this.removeItem(n),this._size--,n.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let t=this._head;return this._map.delete(t.key),this.removeItem(t),this._size--,t.value}forEach(t,n){let o=this._state,s=this._head;for(;s;){if(n?t.bind(n)(s.value,s.key,this):t(s.value,s.key,this),this._state!==o)throw new Error("LinkedMap got modified during iteration.");s=s.next}}keys(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:n.key,done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}values(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:n.value,done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}entries(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:[n.key,n.value],done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}[(zf=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(t){if(t>=this.size)return;if(t===0){this.clear();return}let n=this._head,o=this.size;for(;n&&o>t;)this._map.delete(n.key),n=n.next,o--;this._head=n,this._size=o,n&&(n.previous=void 0),this._state++}addItemFirst(t){if(!this._head&&!this._tail)this._tail=t;else if(this._head)t.next=this._head,this._head.previous=t;else throw new Error("Invalid list");this._head=t,this._state++}addItemLast(t){if(!this._head&&!this._tail)this._head=t;else if(this._tail)t.previous=this._tail,this._tail.next=t;else throw new Error("Invalid list");this._tail=t,this._state++}removeItem(t){if(t===this._head&&t===this._tail)this._head=void 0,this._tail=void 0;else if(t===this._head){if(!t.next)throw new Error("Invalid list");t.next.previous=void 0,this._head=t.next}else if(t===this._tail){if(!t.previous)throw new Error("Invalid list");t.previous.next=void 0,this._tail=t.previous}else{let n=t.next,o=t.previous;if(!n||!o)throw new Error("Invalid list");n.previous=o,o.next=n}t.next=void 0,t.previous=void 0,this._state++}touch(t,n){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(n!==Nt.First&&n!==Nt.Last)){if(n===Nt.First){if(t===this._head)return;let o=t.next,s=t.previous;t===this._tail?(s.next=void 0,this._tail=s):(o.previous=s,s.next=o),t.previous=void 0,t.next=this._head,this._head.previous=t,this._head=t,this._state++}else if(n===Nt.Last){if(t===this._tail)return;let o=t.next,s=t.previous;t===this._head?(o.previous=void 0,this._head=o):(o.previous=s,s.next=o),t.next=void 0,t.previous=this._tail,this._tail.next=t,this._tail=t,this._state++}}}toJSON(){let t=[];return this.forEach((n,o)=>{t.push([o,n])}),t}fromJSON(t){this.clear();for(let[n,o]of t)this.set(n,o)}};to.LinkedMap=qi;var ol=class extends qi{static{i(this,"LRUCache")}constructor(t,n=1){super(),this._limit=t,this._ratio=Math.min(Math.max(0,n),1)}get limit(){return this._limit}set limit(t){this._limit=t,this.checkTrim()}get ratio(){return this._ratio}set ratio(t){this._ratio=Math.min(Math.max(0,t),1),this.checkTrim()}get(t,n=Nt.AsNew){return super.get(t,n)}peek(t){return super.get(t,Nt.None)}set(t,n){return super.set(t,n,Nt.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};to.LRUCache=ol});var Hf=kt(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.Disposable=void 0;var Gf;(function(e){function t(n){return{dispose:n}}i(t,"create"),e.create=t})(Gf||(Wi.Disposable=Gf={}))});var no=kt(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var sl;function il(){if(sl===void 0)throw new Error("No runtime abstraction layer installed");return sl}i(il,"RAL");(function(e){function t(n){if(n===void 0)throw new Error("No runtime abstraction layer provided");sl=n}i(t,"install"),e.install=t})(il||(il={}));al.default=il});var Sr=kt(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.Emitter=xr.Event=void 0;var tx=no(),Yf;(function(e){let t={dispose(){}};e.None=function(){return t}})(Yf||(xr.Event=Yf={}));var cl=class{static{i(this,"CallbackList")}add(t,n=null,o){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(t),this._contexts.push(n),Array.isArray(o)&&o.push({dispose:i(()=>this.remove(t,n),"dispose")})}remove(t,n=null){if(!this._callbacks)return;let o=!1;for(let s=0,a=this._callbacks.length;s<a;s++)if(this._callbacks[s]===t)if(this._contexts[s]===n){this._callbacks.splice(s,1),this._contexts.splice(s,1);return}else o=!0;if(o)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...t){if(!this._callbacks)return[];let n=[],o=this._callbacks.slice(0),s=this._contexts.slice(0);for(let a=0,l=o.length;a<l;a++)try{n.push(o[a].apply(s[a],t))}catch(d){(0,tx.default)().console.error(d)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},Vi=class e{static{i(this,"Emitter")}constructor(t){this._options=t}get event(){return this._event||(this._event=(t,n,o)=>{this._callbacks||(this._callbacks=new cl),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let s={dispose:i(()=>{this._callbacks&&(this._callbacks.remove(t,n),s.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))},"dispose")};return Array.isArray(o)&&o.push(s),s}),this._event}fire(t){this._callbacks&&this._callbacks.invoke.call(this._callbacks,t)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};xr.Emitter=Vi;Vi._noop=function(){}});var Hi=kt(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.CancellationTokenSource=Ir.CancellationToken=void 0;var nx=no(),ox=vr(),ll=Sr(),zi;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ll.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ll.Event.None});function t(n){let o=n;return o&&(o===e.None||o===e.Cancelled||ox.boolean(o.isCancellationRequested)&&!!o.onCancellationRequested)}i(t,"is"),e.is=t})(zi||(Ir.CancellationToken=zi={}));var rx=Object.freeze(function(e,t){let n=(0,nx.default)().timer.setTimeout(e.bind(t),0);return{dispose(){n.dispose()}}}),Gi=class{static{i(this,"MutableToken")}constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?rx:(this._emitter||(this._emitter=new ll.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},dl=class{static{i(this,"CancellationTokenSource")}get token(){return this._token||(this._token=new Gi),this._token}cancel(){this._token?this._token.cancel():this._token=zi.Cancelled}dispose(){this._token?this._token instanceof Gi&&this._token.dispose():this._token=zi.None}};Ir.CancellationTokenSource=dl});var Jf=kt(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.SharedArrayReceiverStrategy=kr.SharedArraySenderStrategy=void 0;var sx=Hi(),bs;(function(e){e.Continue=0,e.Cancelled=1})(bs||(bs={}));var ul=class{static{i(this,"SharedArraySenderStrategy")}constructor(){this.buffers=new Map}enableCancellation(t){if(t.id===null)return;let n=new SharedArrayBuffer(4),o=new Int32Array(n,0,1);o[0]=bs.Continue,this.buffers.set(t.id,n),t.$cancellationData=n}async sendCancellation(t,n){let o=this.buffers.get(n);if(o===void 0)return;let s=new Int32Array(o,0,1);Atomics.store(s,0,bs.Cancelled)}cleanup(t){this.buffers.delete(t)}dispose(){this.buffers.clear()}};kr.SharedArraySenderStrategy=ul;var pl=class{static{i(this,"SharedArrayBufferCancellationToken")}constructor(t){this.data=new Int32Array(t,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===bs.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},fl=class{static{i(this,"SharedArrayBufferCancellationTokenSource")}constructor(t){this.token=new pl(t)}cancel(){}dispose(){}},ml=class{static{i(this,"SharedArrayReceiverStrategy")}constructor(){this.kind="request"}createCancellationTokenSource(t){let n=t.$cancellationData;return n===void 0?new sx.CancellationTokenSource:new fl(n)}};kr.SharedArrayReceiverStrategy=ml});var gl=kt(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Semaphore=void 0;var ix=no(),hl=class{static{i(this,"Semaphore")}constructor(t=1){if(t<=0)throw new Error("Capacity must be greater than 0");this._capacity=t,this._active=0,this._waiting=[]}lock(t){return new Promise((n,o)=>{this._waiting.push({thunk:t,resolve:n,reject:o}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,ix.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let t=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let n=t.thunk();n instanceof Promise?n.then(o=>{this._active--,t.resolve(o),this.runNext()},o=>{this._active--,t.reject(o),this.runNext()}):(this._active--,t.resolve(n),this.runNext())}catch(n){this._active--,t.reject(n),this.runNext()}}};Yi.Semaphore=hl});var Xf=kt(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.ReadableStreamMessageReader=oo.AbstractMessageReader=oo.MessageReader=void 0;var bl=no(),Dr=vr(),yl=Sr(),ax=gl(),Kf;(function(e){function t(n){let o=n;return o&&Dr.func(o.listen)&&Dr.func(o.dispose)&&Dr.func(o.onError)&&Dr.func(o.onClose)&&Dr.func(o.onPartialMessage)}i(t,"is"),e.is=t})(Kf||(oo.MessageReader=Kf={}));var Ji=class{static{i(this,"AbstractMessageReader")}constructor(){this.errorEmitter=new yl.Emitter,this.closeEmitter=new yl.Emitter,this.partialMessageEmitter=new yl.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(t){this.errorEmitter.fire(this.asError(t))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(t){this.partialMessageEmitter.fire(t)}asError(t){return t instanceof Error?t:new Error(`Reader received error. Reason: ${Dr.string(t.message)?t.message:"unknown"}`)}};oo.AbstractMessageReader=Ji;var wl;(function(e){function t(n){let o,s,a,l=new Map,d,p=new Map;if(n===void 0||typeof n=="string")o=n??"utf-8";else{if(o=n.charset??"utf-8",n.contentDecoder!==void 0&&(a=n.contentDecoder,l.set(a.name,a)),n.contentDecoders!==void 0)for(let f of n.contentDecoders)l.set(f.name,f);if(n.contentTypeDecoder!==void 0&&(d=n.contentTypeDecoder,p.set(d.name,d)),n.contentTypeDecoders!==void 0)for(let f of n.contentTypeDecoders)p.set(f.name,f)}return d===void 0&&(d=(0,bl.default)().applicationJson.decoder,p.set(d.name,d)),{charset:o,contentDecoder:a,contentDecoders:l,contentTypeDecoder:d,contentTypeDecoders:p}}i(t,"fromOptions"),e.fromOptions=t})(wl||(wl={}));var vl=class extends Ji{static{i(this,"ReadableStreamMessageReader")}constructor(t,n){super(),this.readable=t,this.options=wl.fromOptions(n),this.buffer=(0,bl.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new ax.Semaphore(1)}set partialMessageTimeout(t){this._partialMessageTimeout=t}get partialMessageTimeout(){return this._partialMessageTimeout}listen(t){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=t;let n=this.readable.onData(o=>{this.onData(o)});return this.readable.onError(o=>this.fireError(o)),this.readable.onClose(()=>this.fireClose()),n}onData(t){try{for(this.buffer.append(t);;){if(this.nextMessageLength===-1){let o=this.buffer.tryReadHeaders(!0);if(!o)return;let s=o.get("content-length");if(!s){this.fireError(new Error(`Header must provide a Content-Length property.
19
- ${JSON.stringify(Object.fromEntries(o))}`));return}let a=parseInt(s);if(isNaN(a)){this.fireError(new Error(`Content-Length value must be a number. Got ${s}`));return}this.nextMessageLength=a}let n=this.buffer.tryReadBody(this.nextMessageLength);if(n===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let o=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(n):n,s=await this.options.contentTypeDecoder.decode(o,this.options);this.callback(s)}).catch(o=>{this.fireError(o)})}}catch(n){this.fireError(n)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,bl.default)().timer.setTimeout((t,n)=>{this.partialMessageTimer=void 0,t===this.messageToken&&(this.firePartialMessage({messageToken:t,waitingTime:n}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};oo.ReadableStreamMessageReader=vl});var nm=kt(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.WriteableStreamMessageWriter=ro.AbstractMessageWriter=ro.MessageWriter=void 0;var Qf=no(),ws=vr(),cx=gl(),Zf=Sr(),lx="Content-Length: ",em=`\r
20
- `,tm;(function(e){function t(n){let o=n;return o&&ws.func(o.dispose)&&ws.func(o.onClose)&&ws.func(o.onError)&&ws.func(o.write)}i(t,"is"),e.is=t})(tm||(ro.MessageWriter=tm={}));var Ki=class{static{i(this,"AbstractMessageWriter")}constructor(){this.errorEmitter=new Zf.Emitter,this.closeEmitter=new Zf.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(t,n,o){this.errorEmitter.fire([this.asError(t),n,o])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(t){return t instanceof Error?t:new Error(`Writer received error. Reason: ${ws.string(t.message)?t.message:"unknown"}`)}};ro.AbstractMessageWriter=Ki;var xl;(function(e){function t(n){return n===void 0||typeof n=="string"?{charset:n??"utf-8",contentTypeEncoder:(0,Qf.default)().applicationJson.encoder}:{charset:n.charset??"utf-8",contentEncoder:n.contentEncoder,contentTypeEncoder:n.contentTypeEncoder??(0,Qf.default)().applicationJson.encoder}}i(t,"fromOptions"),e.fromOptions=t})(xl||(xl={}));var Sl=class extends Ki{static{i(this,"WriteableStreamMessageWriter")}constructor(t,n){super(),this.writable=t,this.options=xl.fromOptions(n),this.errorCount=0,this.writeSemaphore=new cx.Semaphore(1),this.writable.onError(o=>this.fireError(o)),this.writable.onClose(()=>this.fireClose())}async write(t){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(t,this.options).then(o=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(o):o).then(o=>{let s=[];return s.push(lx,o.byteLength.toString(),em),s.push(em),this.doWrite(t,s,o)},o=>{throw this.fireError(o),o}))}async doWrite(t,n,o){try{return await this.writable.write(n.join(""),"ascii"),this.writable.write(o)}catch(s){return this.handleError(s,t),Promise.reject(s)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){this.writable.end()}};ro.WriteableStreamMessageWriter=Sl});var om=kt(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AbstractMessageBuffer=void 0;var dx=13,ux=10,px=`\r
21
- `,Il=class{static{i(this,"AbstractMessageBuffer")}constructor(t="utf-8"){this._encoding=t,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(t){let n=typeof t=="string"?this.fromString(t,this._encoding):t;this._chunks.push(n),this._totalLength+=n.byteLength}tryReadHeaders(t=!1){if(this._chunks.length===0)return;let n=0,o=0,s=0,a=0;e:for(;o<this._chunks.length;){let f=this._chunks[o];for(s=0;s<f.length;){switch(f[s]){case dx:switch(n){case 0:n=1;break;case 2:n=3;break;default:n=0}break;case ux:switch(n){case 1:n=2;break;case 3:n=4,s++;break e;default:n=0}break;default:n=0}s++}a+=f.byteLength,o++}if(n!==4)return;let l=this._read(a+s),d=new Map,p=this.toString(l,"ascii").split(px);if(p.length<2)return d;for(let f=0;f<p.length-2;f++){let u=p[f],g=u.indexOf(":");if(g===-1)throw new Error(`Message header must separate key and value using ':'
22
- ${u}`);let y=u.substr(0,g),b=u.substr(g+1).trim();d.set(t?y.toLowerCase():y,b)}return d}tryReadBody(t){if(!(this._totalLength<t))return this._read(t)}get numberOfBytes(){return this._totalLength}_read(t){if(t===0)return this.emptyBuffer();if(t>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===t){let a=this._chunks[0];return this._chunks.shift(),this._totalLength-=t,this.asNative(a)}if(this._chunks[0].byteLength>t){let a=this._chunks[0],l=this.asNative(a,t);return this._chunks[0]=a.slice(t),this._totalLength-=t,l}let n=this.allocNative(t),o=0,s=0;for(;t>0;){let a=this._chunks[s];if(a.byteLength>t){let l=a.slice(0,t);n.set(l,o),o+=t,this._chunks[s]=a.slice(t),this._totalLength-=t,t-=t}else n.set(a,o),o+=a.byteLength,this._chunks.shift(),this._totalLength-=a.byteLength,t-=a.byteLength}return n}};Xi.AbstractMessageBuffer=Il});var cm=kt(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.createMessageConnection=Me.ConnectionOptions=Me.MessageStrategy=Me.CancellationStrategy=Me.CancellationSenderStrategy=Me.CancellationReceiverStrategy=Me.RequestCancellationReceiverStrategy=Me.IdCancellationReceiverStrategy=Me.ConnectionStrategy=Me.ConnectionError=Me.ConnectionErrors=Me.LogTraceNotification=Me.SetTraceNotification=Me.TraceFormat=Me.TraceValues=Me.Trace=Me.NullLogger=Me.ProgressType=Me.ProgressToken=void 0;var rm=no(),mt=vr(),Ie=nl(),sm=rl(),vs=Sr(),kl=Hi(),Is;(function(e){e.type=new Ie.NotificationType("$/cancelRequest")})(Is||(Is={}));var Dl;(function(e){function t(n){return typeof n=="string"||typeof n=="number"}i(t,"is"),e.is=t})(Dl||(Me.ProgressToken=Dl={}));var xs;(function(e){e.type=new Ie.NotificationType("$/progress")})(xs||(xs={}));var El=class{static{i(this,"ProgressType")}constructor(){}};Me.ProgressType=El;var Tl;(function(e){function t(n){return mt.func(n)}i(t,"is"),e.is=t})(Tl||(Tl={}));Me.NullLogger=Object.freeze({error:i(()=>{},"error"),warn:i(()=>{},"warn"),info:i(()=>{},"info"),log:i(()=>{},"log")});var ze;(function(e){e[e.Off=0]="Off",e[e.Messages=1]="Messages",e[e.Compact=2]="Compact",e[e.Verbose=3]="Verbose"})(ze||(Me.Trace=ze={}));var im;(function(e){e.Off="off",e.Messages="messages",e.Compact="compact",e.Verbose="verbose"})(im||(Me.TraceValues=im={}));(function(e){function t(o){if(!mt.string(o))return e.Off;switch(o=o.toLowerCase(),o){case"off":return e.Off;case"messages":return e.Messages;case"compact":return e.Compact;case"verbose":return e.Verbose;default:return e.Off}}i(t,"fromString"),e.fromString=t;function n(o){switch(o){case e.Off:return"off";case e.Messages:return"messages";case e.Compact:return"compact";case e.Verbose:return"verbose";default:return"off"}}i(n,"toString"),e.toString=n})(ze||(Me.Trace=ze={}));var tn;(function(e){e.Text="text",e.JSON="json"})(tn||(Me.TraceFormat=tn={}));(function(e){function t(n){return mt.string(n)?(n=n.toLowerCase(),n==="json"?e.JSON:e.Text):e.Text}i(t,"fromString"),e.fromString=t})(tn||(Me.TraceFormat=tn={}));var Pl;(function(e){e.type=new Ie.NotificationType("$/setTrace")})(Pl||(Me.SetTraceNotification=Pl={}));var Qi;(function(e){e.type=new Ie.NotificationType("$/logTrace")})(Qi||(Me.LogTraceNotification=Qi={}));var Ss;(function(e){e[e.Closed=1]="Closed",e[e.Disposed=2]="Disposed",e[e.AlreadyListening=3]="AlreadyListening"})(Ss||(Me.ConnectionErrors=Ss={}));var Er=class e extends Error{static{i(this,"ConnectionError")}constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,e.prototype)}};Me.ConnectionError=Er;var Rl;(function(e){function t(n){let o=n;return o&&mt.func(o.cancelUndispatched)}i(t,"is"),e.is=t})(Rl||(Me.ConnectionStrategy=Rl={}));var Zi;(function(e){function t(n){let o=n;return o&&(o.kind===void 0||o.kind==="id")&&mt.func(o.createCancellationTokenSource)&&(o.dispose===void 0||mt.func(o.dispose))}i(t,"is"),e.is=t})(Zi||(Me.IdCancellationReceiverStrategy=Zi={}));var Cl;(function(e){function t(n){let o=n;return o&&o.kind==="request"&&mt.func(o.createCancellationTokenSource)&&(o.dispose===void 0||mt.func(o.dispose))}i(t,"is"),e.is=t})(Cl||(Me.RequestCancellationReceiverStrategy=Cl={}));var ea;(function(e){e.Message=Object.freeze({createCancellationTokenSource(n){return new kl.CancellationTokenSource}});function t(n){return Zi.is(n)||Cl.is(n)}i(t,"is"),e.is=t})(ea||(Me.CancellationReceiverStrategy=ea={}));var ta;(function(e){e.Message=Object.freeze({sendCancellation(n,o){return n.sendNotification(Is.type,{id:o})},cleanup(n){}});function t(n){let o=n;return o&&mt.func(o.sendCancellation)&&mt.func(o.cleanup)}i(t,"is"),e.is=t})(ta||(Me.CancellationSenderStrategy=ta={}));var na;(function(e){e.Message=Object.freeze({receiver:ea.Message,sender:ta.Message});function t(n){let o=n;return o&&ea.is(o.receiver)&&ta.is(o.sender)}i(t,"is"),e.is=t})(na||(Me.CancellationStrategy=na={}));var oa;(function(e){function t(n){let o=n;return o&&mt.func(o.handleMessage)}i(t,"is"),e.is=t})(oa||(Me.MessageStrategy=oa={}));var am;(function(e){function t(n){let o=n;return o&&(na.is(o.cancellationStrategy)||Rl.is(o.connectionStrategy)||oa.is(o.messageStrategy))}i(t,"is"),e.is=t})(am||(Me.ConnectionOptions=am={}));var wn;(function(e){e[e.New=1]="New",e[e.Listening=2]="Listening",e[e.Closed=3]="Closed",e[e.Disposed=4]="Disposed"})(wn||(wn={}));function fx(e,t,n,o){let s=n!==void 0?n:Me.NullLogger,a=0,l=0,d=0,p="2.0",f,u=new Map,g,y=new Map,b=new Map,S,T=new sm.LinkedMap,m=new Map,h=new Set,k=new Map,w=ze.Off,I=tn.Text,P,x=wn.New,A=new vs.Emitter,C=new vs.Emitter,$=new vs.Emitter,j=new vs.Emitter,z=new vs.Emitter,ie=o&&o.cancellationStrategy?o.cancellationStrategy:na.Message;function L(v){if(v===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+v.toString()}i(L,"createRequestQueueKey");function V(v){return v===null?"res-unknown-"+(++d).toString():"res-"+v.toString()}i(V,"createResponseQueueKey");function D(){return"not-"+(++l).toString()}i(D,"createNotificationQueueKey");function M(v,O){Ie.Message.isRequest(O)?v.set(L(O.id),O):Ie.Message.isResponse(O)?v.set(V(O.id),O):v.set(D(),O)}i(M,"addMessageToQueue");function _(v){}i(_,"cancelUndispatched");function N(){return x===wn.Listening}i(N,"isListening");function W(){return x===wn.Closed}i(W,"isClosed");function U(){return x===wn.Disposed}i(U,"isDisposed");function we(){(x===wn.New||x===wn.Listening)&&(x=wn.Closed,C.fire(void 0))}i(we,"closeHandler");function pe(v){A.fire([v,void 0,void 0])}i(pe,"readErrorHandler");function ce(v){A.fire(v)}i(ce,"writeErrorHandler"),e.onClose(we),e.onError(pe),t.onClose(we),t.onError(ce);function re(){S||T.size===0||(S=(0,rm.default)().timer.setImmediate(()=>{S=void 0,q()}))}i(re,"triggerMessageQueue");function R(v){Ie.Message.isRequest(v)?ne(v):Ie.Message.isNotification(v)?ot(v):Ie.Message.isResponse(v)?Ue(v):Mt(v)}i(R,"handleMessage");function q(){if(T.size===0)return;let v=T.shift();try{let O=o?.messageStrategy;oa.is(O)?O.handleMessage(v,R):R(v)}finally{re()}}i(q,"processMessageQueue");let H=i(v=>{try{if(Ie.Message.isNotification(v)&&v.method===Is.type.method){let O=v.params.id,F=L(O),Z=T.get(F);if(Ie.Message.isRequest(Z)){let le=o?.connectionStrategy,ue=le&&le.cancelUndispatched?le.cancelUndispatched(Z,_):void 0;if(ue&&(ue.error!==void 0||ue.result!==void 0)){T.delete(F),k.delete(O),ue.id=Z.id,Y(ue,v.method,Date.now()),t.write(ue).catch(()=>s.error("Sending response for canceled message failed."));return}}let _e=k.get(O);if(_e!==void 0){_e.cancel(),de(v);return}else h.add(O)}M(T,v)}finally{re()}},"callback");function ne(v){if(U())return;function O(X,he,ge){let Pe={jsonrpc:p,id:v.id};X instanceof Ie.ResponseError?Pe.error=X.toJson():Pe.result=X===void 0?null:X,Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(O,"reply");function F(X,he,ge){let Pe={jsonrpc:p,id:v.id,error:X.toJson()};Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(F,"replyError");function Z(X,he,ge){X===void 0&&(X=null);let Pe={jsonrpc:p,id:v.id,result:X};Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(Z,"replySuccess"),ve(v);let _e=u.get(v.method),le,ue;_e&&(le=_e.type,ue=_e.handler);let K=Date.now();if(ue||f){let X=v.id??String(Date.now()),he=Zi.is(ie.receiver)?ie.receiver.createCancellationTokenSource(X):ie.receiver.createCancellationTokenSource(v);v.id!==null&&h.has(v.id)&&he.cancel(),v.id!==null&&k.set(X,he);try{let ge;if(ue)if(v.params===void 0){if(le!==void 0&&le.numberOfParams!==0){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines ${le.numberOfParams} params but received none.`),v.method,K);return}ge=ue(he.token)}else if(Array.isArray(v.params)){if(le!==void 0&&le.parameterStructures===Ie.ParameterStructures.byName){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines parameters by name but received parameters by position`),v.method,K);return}ge=ue(...v.params,he.token)}else{if(le!==void 0&&le.parameterStructures===Ie.ParameterStructures.byPosition){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines parameters by position but received parameters by name`),v.method,K);return}ge=ue(v.params,he.token)}else f&&(ge=f(v.method,v.params,he.token));let Pe=ge;ge?Pe.then?Pe.then(Ye=>{k.delete(X),O(Ye,v.method,K)},Ye=>{k.delete(X),Ye instanceof Ie.ResponseError?F(Ye,v.method,K):Ye&&mt.string(Ye.message)?F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed with message: ${Ye.message}`),v.method,K):F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed unexpectedly without providing any details.`),v.method,K)}):(k.delete(X),O(ge,v.method,K)):(k.delete(X),Z(ge,v.method,K))}catch(ge){k.delete(X),ge instanceof Ie.ResponseError?O(ge,v.method,K):ge&&mt.string(ge.message)?F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed with message: ${ge.message}`),v.method,K):F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed unexpectedly without providing any details.`),v.method,K)}}else F(new Ie.ResponseError(Ie.ErrorCodes.MethodNotFound,`Unhandled method ${v.method}`),v.method,K)}i(ne,"handleRequest");function Ue(v){if(!U())if(v.id===null)v.error?s.error(`Received response message without id: Error is:
18
+ import{A as Ge,B as Rt,C as ns,E as Qu,F as pt,G as yt,H as Ft,b as _n,h as ai,l as ci,m as Mu,n as _u,o as Ou,p as Ha,q as ju,r as Uu,s as Fu,u as Gu,w as Xe,x as Yu,y as Ju,z as wo}from"./chunk-G7PFO5HG.js";import{b as yi,c as Zo,d as Ku,e as Xu,g as er}from"./chunk-4GJE6OMN.js";import{L as zt,N as Ke,P as Xn,R as hi,U as Hu,V as gi,X as cn,i as ku}from"./chunk-B74WSFN4.js";import{R as me,a as ts,b as Lu,c as Nu,d as Dn,e as Za,f as Wu,g as bo,h as mi,i as nc,j as Pt,k as at,l as Fe,m as oc,n as Vu,o as zu,p as Ze,q as an}from"./chunk-FOHYZ7MJ.js";import{$a as yn,C as hu,Da as G,E as gu,F as yu,Fa as ut,G as bu,Ga as pi,H as wu,I as vu,J as xu,Ja as be,K as xt,Ka as Xa,L as Su,La as st,M as si,Ma as gn,N as Xo,Na as Kn,O as Wa,Oa as Qa,P as Iu,Pa as it,Q as Va,R as yo,S as Jn,T as On,U as za,_a as Oe,ab as fi,c as Yn,cb as $u,f as qa,fa as Eu,ga as Tu,gb as qu,h as ho,ha as Ut,ia as li,ib as ec,jb as Qo,k as kn,kb as De,la as Ya,lb as tc,ma as Ja,mb as Be,pa as Ka,r as dt,ra as di,s as Vt,u as ri,v as Tt,va as Xt,wa as Bu,xa as ui,y as go}from"./chunk-DWEYXIQI.js";import{G as Ga}from"./chunk-V6FDDNGV.js";import{a as ii}from"./chunk-QCRIXKIC.js";import{a as Ru,b as Cu,c as Au}from"./chunk-LIXP4TPL.js";import{a as Pu}from"./chunk-M6E6KNLV.js";import{d as kg}from"./chunk-NDI67DRG.js";import{a as oi}from"./chunk-K5LKDIVU.js";import{c as se,d as Hn,f as mo}from"./chunk-R2GWBJEP.js";import{$a as Zs,$b as Ce,Aa as Et,Ab as Zd,Bb as ei,Cb as Ba,Fa as Cn,Fb as $a,Gb as eu,Ib as tu,Jb as nu,Kb as ou,La as sn,Lb as ru,Ma as uo,Nb as su,Pa as St,Qb as iu,Rb as Mn,Sb as rt,Tb as gt,Wb as es,Xb as Gn,Ya as Ua,Zc as du,ac as Yo,b as Wd,bc as au,bd as uu,c as Vn,cd as pu,db as Kr,dc as ti,de as fu,eb as Kd,fa as zd,g as ja,gc as Jo,ge as mu,ha as ke,hc as cu,ia as Xs,ic as Sn,jc as fo,lb as Xr,m as Jr,ma as mn,mb as Se,mc as In,nb as Qr,nc as lu,oa as Gd,ob as Zr,pa as hn,pc as Ae,q as Ve,qa as Hd,qb as Qe,r as zn,rb as po,rc as ni,sa as Yd,sb as An,tb as Xd,ub as Fa,uc as Ko,vb as Wt,wb as Qd,x as fn,xb as lt,ya as Qs,za as Jd}from"./chunk-7XX6TY62.js";import{g as Du}from"./chunk-UCLPBO4I.js";import{h as Ks,k as Ho,t as Rn}from"./chunk-VWLJXTZ5.js";import{Ah as Hs,Bc as Dt,Bf as r,Bh as Ys,Dh as Ud,Fg as Yr,Fi as Vd,Ig as Ad,Ih as Fd,Ma as Ed,Nh as Bd,Tc as Te,Th as $d,Wh as Js,Yh as Na,Z as Dd,Zh as qd,aa as xn,bb as Re,bi as vt,dc as ht,hh as Oa,ja as Ma,jd as tt,lc as bt,mh as La,nb as Td,pa as _a,pd as Pd,pj as c,qh as Md,rg as Vs,rh as _d,tg as Cd,th as Od,uh as zs,vh as Gs,wa as Go,wh as Ld,xh as Nd,zd as Rd,zh as jd}from"./chunk-ELPXQ32J.js";import{a as i,b as Hr,d as kt,e as fe,g as kd}from"./chunk-2MRHL4B2.js";var vr=kt(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.stringArray=Lt.array=Lt.func=Lt.error=Lt.number=Lt.string=Lt.boolean=void 0;function ex(e){return e===!0||e===!1}i(ex,"boolean");Lt.boolean=ex;function qf(e){return typeof e=="string"||e instanceof String}i(qf,"string");Lt.string=qf;function tx(e){return typeof e=="number"||e instanceof Number}i(tx,"number");Lt.number=tx;function nx(e){return e instanceof Error}i(nx,"error");Lt.error=nx;function ox(e){return typeof e=="function"}i(ox,"func");Lt.func=ox;function Wf(e){return Array.isArray(e)}i(Wf,"array");Lt.array=Wf;function rx(e){return Wf(e)&&e.every(t=>qf(t))}i(rx,"stringArray");Lt.stringArray=rx});var nl=kt(ye=>{"use strict";Object.defineProperty(ye,"__esModule",{value:!0});ye.Message=ye.NotificationType9=ye.NotificationType8=ye.NotificationType7=ye.NotificationType6=ye.NotificationType5=ye.NotificationType4=ye.NotificationType3=ye.NotificationType2=ye.NotificationType1=ye.NotificationType0=ye.NotificationType=ye.RequestType9=ye.RequestType8=ye.RequestType7=ye.RequestType6=ye.RequestType5=ye.RequestType4=ye.RequestType3=ye.RequestType2=ye.RequestType1=ye.RequestType=ye.RequestType0=ye.AbstractMessageSignature=ye.ParameterStructures=ye.ResponseError=ye.ErrorCodes=void 0;var Eo=vr(),Mc;(function(e){e.ParseError=-32700,e.InvalidRequest=-32600,e.MethodNotFound=-32601,e.InvalidParams=-32602,e.InternalError=-32603,e.jsonrpcReservedErrorRangeStart=-32099,e.serverErrorStart=-32099,e.MessageWriteError=-32099,e.MessageReadError=-32098,e.PendingResponseRejected=-32097,e.ConnectionInactive=-32096,e.ServerNotInitialized=-32002,e.UnknownErrorCode=-32001,e.jsonrpcReservedErrorRangeEnd=-32e3,e.serverErrorEnd=-32e3})(Mc||(ye.ErrorCodes=Mc={}));var _c=class e extends Error{static{i(this,"ResponseError")}constructor(t,n,o){super(n),this.code=Eo.number(t)?t:Mc.UnknownErrorCode,this.data=o,Object.setPrototypeOf(this,e.prototype)}toJson(){let t={code:this.code,message:this.message};return this.data!==void 0&&(t.data=this.data),t}};ye.ResponseError=_c;var Yt=class e{static{i(this,"ParameterStructures")}constructor(t){this.kind=t}static is(t){return t===e.auto||t===e.byName||t===e.byPosition}toString(){return this.kind}};ye.ParameterStructures=Yt;Yt.auto=new Yt("auto");Yt.byPosition=new Yt("byPosition");Yt.byName=new Yt("byName");var ct=class{static{i(this,"AbstractMessageSignature")}constructor(t,n){this.method=t,this.numberOfParams=n}get parameterStructures(){return Yt.auto}};ye.AbstractMessageSignature=ct;var Oc=class extends ct{static{i(this,"RequestType0")}constructor(t){super(t,0)}};ye.RequestType0=Oc;var Lc=class extends ct{static{i(this,"RequestType")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.RequestType=Lc;var Nc=class extends ct{static{i(this,"RequestType1")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.RequestType1=Nc;var jc=class extends ct{static{i(this,"RequestType2")}constructor(t){super(t,2)}};ye.RequestType2=jc;var Uc=class extends ct{static{i(this,"RequestType3")}constructor(t){super(t,3)}};ye.RequestType3=Uc;var Fc=class extends ct{static{i(this,"RequestType4")}constructor(t){super(t,4)}};ye.RequestType4=Fc;var Bc=class extends ct{static{i(this,"RequestType5")}constructor(t){super(t,5)}};ye.RequestType5=Bc;var $c=class extends ct{static{i(this,"RequestType6")}constructor(t){super(t,6)}};ye.RequestType6=$c;var qc=class extends ct{static{i(this,"RequestType7")}constructor(t){super(t,7)}};ye.RequestType7=qc;var Wc=class extends ct{static{i(this,"RequestType8")}constructor(t){super(t,8)}};ye.RequestType8=Wc;var Vc=class extends ct{static{i(this,"RequestType9")}constructor(t){super(t,9)}};ye.RequestType9=Vc;var zc=class extends ct{static{i(this,"NotificationType")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.NotificationType=zc;var Gc=class extends ct{static{i(this,"NotificationType0")}constructor(t){super(t,0)}};ye.NotificationType0=Gc;var Hc=class extends ct{static{i(this,"NotificationType1")}constructor(t,n=Yt.auto){super(t,1),this._parameterStructures=n}get parameterStructures(){return this._parameterStructures}};ye.NotificationType1=Hc;var Yc=class extends ct{static{i(this,"NotificationType2")}constructor(t){super(t,2)}};ye.NotificationType2=Yc;var Jc=class extends ct{static{i(this,"NotificationType3")}constructor(t){super(t,3)}};ye.NotificationType3=Jc;var Kc=class extends ct{static{i(this,"NotificationType4")}constructor(t){super(t,4)}};ye.NotificationType4=Kc;var Xc=class extends ct{static{i(this,"NotificationType5")}constructor(t){super(t,5)}};ye.NotificationType5=Xc;var Qc=class extends ct{static{i(this,"NotificationType6")}constructor(t){super(t,6)}};ye.NotificationType6=Qc;var Zc=class extends ct{static{i(this,"NotificationType7")}constructor(t){super(t,7)}};ye.NotificationType7=Zc;var el=class extends ct{static{i(this,"NotificationType8")}constructor(t){super(t,8)}};ye.NotificationType8=el;var tl=class extends ct{static{i(this,"NotificationType9")}constructor(t){super(t,9)}};ye.NotificationType9=tl;var Vf;(function(e){function t(s){let a=s;return a&&Eo.string(a.method)&&(Eo.string(a.id)||Eo.number(a.id))}i(t,"isRequest"),e.isRequest=t;function n(s){let a=s;return a&&Eo.string(a.method)&&s.id===void 0}i(n,"isNotification"),e.isNotification=n;function o(s){let a=s;return a&&(a.result!==void 0||!!a.error)&&(Eo.string(a.id)||Eo.number(a.id)||a.id===null)}i(o,"isResponse"),e.isResponse=o})(Vf||(ye.Message=Vf={}))});var rl=kt(to=>{"use strict";var zf;Object.defineProperty(to,"__esModule",{value:!0});to.LRUCache=to.LinkedMap=to.Touch=void 0;var Nt;(function(e){e.None=0,e.First=1,e.AsOld=e.First,e.Last=2,e.AsNew=e.Last})(Nt||(to.Touch=Nt={}));var qi=class{static{i(this,"LinkedMap")}constructor(){this[zf]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){return this._head?.value}get last(){return this._tail?.value}has(t){return this._map.has(t)}get(t,n=Nt.None){let o=this._map.get(t);if(o)return n!==Nt.None&&this.touch(o,n),o.value}set(t,n,o=Nt.None){let s=this._map.get(t);if(s)s.value=n,o!==Nt.None&&this.touch(s,o);else{switch(s={key:t,value:n,next:void 0,previous:void 0},o){case Nt.None:this.addItemLast(s);break;case Nt.First:this.addItemFirst(s);break;case Nt.Last:this.addItemLast(s);break;default:this.addItemLast(s);break}this._map.set(t,s),this._size++}return this}delete(t){return!!this.remove(t)}remove(t){let n=this._map.get(t);if(n)return this._map.delete(t),this.removeItem(n),this._size--,n.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");let t=this._head;return this._map.delete(t.key),this.removeItem(t),this._size--,t.value}forEach(t,n){let o=this._state,s=this._head;for(;s;){if(n?t.bind(n)(s.value,s.key,this):t(s.value,s.key,this),this._state!==o)throw new Error("LinkedMap got modified during iteration.");s=s.next}}keys(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:n.key,done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}values(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:n.value,done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}entries(){let t=this._state,n=this._head,o={[Symbol.iterator]:()=>o,next:i(()=>{if(this._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){let s={value:[n.key,n.value],done:!1};return n=n.next,s}else return{value:void 0,done:!0}},"next")};return o}[(zf=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(t){if(t>=this.size)return;if(t===0){this.clear();return}let n=this._head,o=this.size;for(;n&&o>t;)this._map.delete(n.key),n=n.next,o--;this._head=n,this._size=o,n&&(n.previous=void 0),this._state++}addItemFirst(t){if(!this._head&&!this._tail)this._tail=t;else if(this._head)t.next=this._head,this._head.previous=t;else throw new Error("Invalid list");this._head=t,this._state++}addItemLast(t){if(!this._head&&!this._tail)this._head=t;else if(this._tail)t.previous=this._tail,this._tail.next=t;else throw new Error("Invalid list");this._tail=t,this._state++}removeItem(t){if(t===this._head&&t===this._tail)this._head=void 0,this._tail=void 0;else if(t===this._head){if(!t.next)throw new Error("Invalid list");t.next.previous=void 0,this._head=t.next}else if(t===this._tail){if(!t.previous)throw new Error("Invalid list");t.previous.next=void 0,this._tail=t.previous}else{let n=t.next,o=t.previous;if(!n||!o)throw new Error("Invalid list");n.previous=o,o.next=n}t.next=void 0,t.previous=void 0,this._state++}touch(t,n){if(!this._head||!this._tail)throw new Error("Invalid list");if(!(n!==Nt.First&&n!==Nt.Last)){if(n===Nt.First){if(t===this._head)return;let o=t.next,s=t.previous;t===this._tail?(s.next=void 0,this._tail=s):(o.previous=s,s.next=o),t.previous=void 0,t.next=this._head,this._head.previous=t,this._head=t,this._state++}else if(n===Nt.Last){if(t===this._tail)return;let o=t.next,s=t.previous;t===this._head?(o.previous=void 0,this._head=o):(o.previous=s,s.next=o),t.next=void 0,t.previous=this._tail,this._tail.next=t,this._tail=t,this._state++}}}toJSON(){let t=[];return this.forEach((n,o)=>{t.push([o,n])}),t}fromJSON(t){this.clear();for(let[n,o]of t)this.set(n,o)}};to.LinkedMap=qi;var ol=class extends qi{static{i(this,"LRUCache")}constructor(t,n=1){super(),this._limit=t,this._ratio=Math.min(Math.max(0,n),1)}get limit(){return this._limit}set limit(t){this._limit=t,this.checkTrim()}get ratio(){return this._ratio}set ratio(t){this._ratio=Math.min(Math.max(0,t),1),this.checkTrim()}get(t,n=Nt.AsNew){return super.get(t,n)}peek(t){return super.get(t,Nt.None)}set(t,n){return super.set(t,n,Nt.Last),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}};to.LRUCache=ol});var Hf=kt(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.Disposable=void 0;var Gf;(function(e){function t(n){return{dispose:n}}i(t,"create"),e.create=t})(Gf||(Wi.Disposable=Gf={}))});var no=kt(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});var sl;function il(){if(sl===void 0)throw new Error("No runtime abstraction layer installed");return sl}i(il,"RAL");(function(e){function t(n){if(n===void 0)throw new Error("No runtime abstraction layer provided");sl=n}i(t,"install"),e.install=t})(il||(il={}));al.default=il});var Sr=kt(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.Emitter=xr.Event=void 0;var sx=no(),Yf;(function(e){let t={dispose(){}};e.None=function(){return t}})(Yf||(xr.Event=Yf={}));var cl=class{static{i(this,"CallbackList")}add(t,n=null,o){this._callbacks||(this._callbacks=[],this._contexts=[]),this._callbacks.push(t),this._contexts.push(n),Array.isArray(o)&&o.push({dispose:i(()=>this.remove(t,n),"dispose")})}remove(t,n=null){if(!this._callbacks)return;let o=!1;for(let s=0,a=this._callbacks.length;s<a;s++)if(this._callbacks[s]===t)if(this._contexts[s]===n){this._callbacks.splice(s,1),this._contexts.splice(s,1);return}else o=!0;if(o)throw new Error("When adding a listener with a context, you should remove it with the same context")}invoke(...t){if(!this._callbacks)return[];let n=[],o=this._callbacks.slice(0),s=this._contexts.slice(0);for(let a=0,l=o.length;a<l;a++)try{n.push(o[a].apply(s[a],t))}catch(d){(0,sx.default)().console.error(d)}return n}isEmpty(){return!this._callbacks||this._callbacks.length===0}dispose(){this._callbacks=void 0,this._contexts=void 0}},Vi=class e{static{i(this,"Emitter")}constructor(t){this._options=t}get event(){return this._event||(this._event=(t,n,o)=>{this._callbacks||(this._callbacks=new cl),this._options&&this._options.onFirstListenerAdd&&this._callbacks.isEmpty()&&this._options.onFirstListenerAdd(this),this._callbacks.add(t,n);let s={dispose:i(()=>{this._callbacks&&(this._callbacks.remove(t,n),s.dispose=e._noop,this._options&&this._options.onLastListenerRemove&&this._callbacks.isEmpty()&&this._options.onLastListenerRemove(this))},"dispose")};return Array.isArray(o)&&o.push(s),s}),this._event}fire(t){this._callbacks&&this._callbacks.invoke.call(this._callbacks,t)}dispose(){this._callbacks&&(this._callbacks.dispose(),this._callbacks=void 0)}};xr.Emitter=Vi;Vi._noop=function(){}});var Hi=kt(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.CancellationTokenSource=Ir.CancellationToken=void 0;var ix=no(),ax=vr(),ll=Sr(),zi;(function(e){e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:ll.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ll.Event.None});function t(n){let o=n;return o&&(o===e.None||o===e.Cancelled||ax.boolean(o.isCancellationRequested)&&!!o.onCancellationRequested)}i(t,"is"),e.is=t})(zi||(Ir.CancellationToken=zi={}));var cx=Object.freeze(function(e,t){let n=(0,ix.default)().timer.setTimeout(e.bind(t),0);return{dispose(){n.dispose()}}}),Gi=class{static{i(this,"MutableToken")}constructor(){this._isCancelled=!1}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?cx:(this._emitter||(this._emitter=new ll.Emitter),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=void 0)}},dl=class{static{i(this,"CancellationTokenSource")}get token(){return this._token||(this._token=new Gi),this._token}cancel(){this._token?this._token.cancel():this._token=zi.Cancelled}dispose(){this._token?this._token instanceof Gi&&this._token.dispose():this._token=zi.None}};Ir.CancellationTokenSource=dl});var Jf=kt(kr=>{"use strict";Object.defineProperty(kr,"__esModule",{value:!0});kr.SharedArrayReceiverStrategy=kr.SharedArraySenderStrategy=void 0;var lx=Hi(),bs;(function(e){e.Continue=0,e.Cancelled=1})(bs||(bs={}));var ul=class{static{i(this,"SharedArraySenderStrategy")}constructor(){this.buffers=new Map}enableCancellation(t){if(t.id===null)return;let n=new SharedArrayBuffer(4),o=new Int32Array(n,0,1);o[0]=bs.Continue,this.buffers.set(t.id,n),t.$cancellationData=n}async sendCancellation(t,n){let o=this.buffers.get(n);if(o===void 0)return;let s=new Int32Array(o,0,1);Atomics.store(s,0,bs.Cancelled)}cleanup(t){this.buffers.delete(t)}dispose(){this.buffers.clear()}};kr.SharedArraySenderStrategy=ul;var pl=class{static{i(this,"SharedArrayBufferCancellationToken")}constructor(t){this.data=new Int32Array(t,0,1)}get isCancellationRequested(){return Atomics.load(this.data,0)===bs.Cancelled}get onCancellationRequested(){throw new Error("Cancellation over SharedArrayBuffer doesn't support cancellation events")}},fl=class{static{i(this,"SharedArrayBufferCancellationTokenSource")}constructor(t){this.token=new pl(t)}cancel(){}dispose(){}},ml=class{static{i(this,"SharedArrayReceiverStrategy")}constructor(){this.kind="request"}createCancellationTokenSource(t){let n=t.$cancellationData;return n===void 0?new lx.CancellationTokenSource:new fl(n)}};kr.SharedArrayReceiverStrategy=ml});var gl=kt(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.Semaphore=void 0;var dx=no(),hl=class{static{i(this,"Semaphore")}constructor(t=1){if(t<=0)throw new Error("Capacity must be greater than 0");this._capacity=t,this._active=0,this._waiting=[]}lock(t){return new Promise((n,o)=>{this._waiting.push({thunk:t,resolve:n,reject:o}),this.runNext()})}get active(){return this._active}runNext(){this._waiting.length===0||this._active===this._capacity||(0,dx.default)().timer.setImmediate(()=>this.doRunNext())}doRunNext(){if(this._waiting.length===0||this._active===this._capacity)return;let t=this._waiting.shift();if(this._active++,this._active>this._capacity)throw new Error("To many thunks active");try{let n=t.thunk();n instanceof Promise?n.then(o=>{this._active--,t.resolve(o),this.runNext()},o=>{this._active--,t.reject(o),this.runNext()}):(this._active--,t.resolve(n),this.runNext())}catch(n){this._active--,t.reject(n),this.runNext()}}};Yi.Semaphore=hl});var Xf=kt(oo=>{"use strict";Object.defineProperty(oo,"__esModule",{value:!0});oo.ReadableStreamMessageReader=oo.AbstractMessageReader=oo.MessageReader=void 0;var bl=no(),Dr=vr(),yl=Sr(),ux=gl(),Kf;(function(e){function t(n){let o=n;return o&&Dr.func(o.listen)&&Dr.func(o.dispose)&&Dr.func(o.onError)&&Dr.func(o.onClose)&&Dr.func(o.onPartialMessage)}i(t,"is"),e.is=t})(Kf||(oo.MessageReader=Kf={}));var Ji=class{static{i(this,"AbstractMessageReader")}constructor(){this.errorEmitter=new yl.Emitter,this.closeEmitter=new yl.Emitter,this.partialMessageEmitter=new yl.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(t){this.errorEmitter.fire(this.asError(t))}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}get onPartialMessage(){return this.partialMessageEmitter.event}firePartialMessage(t){this.partialMessageEmitter.fire(t)}asError(t){return t instanceof Error?t:new Error(`Reader received error. Reason: ${Dr.string(t.message)?t.message:"unknown"}`)}};oo.AbstractMessageReader=Ji;var wl;(function(e){function t(n){let o,s,a,l=new Map,d,p=new Map;if(n===void 0||typeof n=="string")o=n??"utf-8";else{if(o=n.charset??"utf-8",n.contentDecoder!==void 0&&(a=n.contentDecoder,l.set(a.name,a)),n.contentDecoders!==void 0)for(let f of n.contentDecoders)l.set(f.name,f);if(n.contentTypeDecoder!==void 0&&(d=n.contentTypeDecoder,p.set(d.name,d)),n.contentTypeDecoders!==void 0)for(let f of n.contentTypeDecoders)p.set(f.name,f)}return d===void 0&&(d=(0,bl.default)().applicationJson.decoder,p.set(d.name,d)),{charset:o,contentDecoder:a,contentDecoders:l,contentTypeDecoder:d,contentTypeDecoders:p}}i(t,"fromOptions"),e.fromOptions=t})(wl||(wl={}));var vl=class extends Ji{static{i(this,"ReadableStreamMessageReader")}constructor(t,n){super(),this.readable=t,this.options=wl.fromOptions(n),this.buffer=(0,bl.default)().messageBuffer.create(this.options.charset),this._partialMessageTimeout=1e4,this.nextMessageLength=-1,this.messageToken=0,this.readSemaphore=new ux.Semaphore(1)}set partialMessageTimeout(t){this._partialMessageTimeout=t}get partialMessageTimeout(){return this._partialMessageTimeout}listen(t){this.nextMessageLength=-1,this.messageToken=0,this.partialMessageTimer=void 0,this.callback=t;let n=this.readable.onData(o=>{this.onData(o)});return this.readable.onError(o=>this.fireError(o)),this.readable.onClose(()=>this.fireClose()),n}onData(t){try{for(this.buffer.append(t);;){if(this.nextMessageLength===-1){let o=this.buffer.tryReadHeaders(!0);if(!o)return;let s=o.get("content-length");if(!s){this.fireError(new Error(`Header must provide a Content-Length property.
19
+ ${JSON.stringify(Object.fromEntries(o))}`));return}let a=parseInt(s);if(isNaN(a)){this.fireError(new Error(`Content-Length value must be a number. Got ${s}`));return}this.nextMessageLength=a}let n=this.buffer.tryReadBody(this.nextMessageLength);if(n===void 0){this.setPartialMessageTimer();return}this.clearPartialMessageTimer(),this.nextMessageLength=-1,this.readSemaphore.lock(async()=>{let o=this.options.contentDecoder!==void 0?await this.options.contentDecoder.decode(n):n,s=await this.options.contentTypeDecoder.decode(o,this.options);this.callback(s)}).catch(o=>{this.fireError(o)})}}catch(n){this.fireError(n)}}clearPartialMessageTimer(){this.partialMessageTimer&&(this.partialMessageTimer.dispose(),this.partialMessageTimer=void 0)}setPartialMessageTimer(){this.clearPartialMessageTimer(),!(this._partialMessageTimeout<=0)&&(this.partialMessageTimer=(0,bl.default)().timer.setTimeout((t,n)=>{this.partialMessageTimer=void 0,t===this.messageToken&&(this.firePartialMessage({messageToken:t,waitingTime:n}),this.setPartialMessageTimer())},this._partialMessageTimeout,this.messageToken,this._partialMessageTimeout))}};oo.ReadableStreamMessageReader=vl});var nm=kt(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.WriteableStreamMessageWriter=ro.AbstractMessageWriter=ro.MessageWriter=void 0;var Qf=no(),ws=vr(),px=gl(),Zf=Sr(),fx="Content-Length: ",em=`\r
20
+ `,tm;(function(e){function t(n){let o=n;return o&&ws.func(o.dispose)&&ws.func(o.onClose)&&ws.func(o.onError)&&ws.func(o.write)}i(t,"is"),e.is=t})(tm||(ro.MessageWriter=tm={}));var Ki=class{static{i(this,"AbstractMessageWriter")}constructor(){this.errorEmitter=new Zf.Emitter,this.closeEmitter=new Zf.Emitter}dispose(){this.errorEmitter.dispose(),this.closeEmitter.dispose()}get onError(){return this.errorEmitter.event}fireError(t,n,o){this.errorEmitter.fire([this.asError(t),n,o])}get onClose(){return this.closeEmitter.event}fireClose(){this.closeEmitter.fire(void 0)}asError(t){return t instanceof Error?t:new Error(`Writer received error. Reason: ${ws.string(t.message)?t.message:"unknown"}`)}};ro.AbstractMessageWriter=Ki;var xl;(function(e){function t(n){return n===void 0||typeof n=="string"?{charset:n??"utf-8",contentTypeEncoder:(0,Qf.default)().applicationJson.encoder}:{charset:n.charset??"utf-8",contentEncoder:n.contentEncoder,contentTypeEncoder:n.contentTypeEncoder??(0,Qf.default)().applicationJson.encoder}}i(t,"fromOptions"),e.fromOptions=t})(xl||(xl={}));var Sl=class extends Ki{static{i(this,"WriteableStreamMessageWriter")}constructor(t,n){super(),this.writable=t,this.options=xl.fromOptions(n),this.errorCount=0,this.writeSemaphore=new px.Semaphore(1),this.writable.onError(o=>this.fireError(o)),this.writable.onClose(()=>this.fireClose())}async write(t){return this.writeSemaphore.lock(async()=>this.options.contentTypeEncoder.encode(t,this.options).then(o=>this.options.contentEncoder!==void 0?this.options.contentEncoder.encode(o):o).then(o=>{let s=[];return s.push(fx,o.byteLength.toString(),em),s.push(em),this.doWrite(t,s,o)},o=>{throw this.fireError(o),o}))}async doWrite(t,n,o){try{return await this.writable.write(n.join(""),"ascii"),this.writable.write(o)}catch(s){return this.handleError(s,t),Promise.reject(s)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){this.writable.end()}};ro.WriteableStreamMessageWriter=Sl});var om=kt(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.AbstractMessageBuffer=void 0;var mx=13,hx=10,gx=`\r
21
+ `,Il=class{static{i(this,"AbstractMessageBuffer")}constructor(t="utf-8"){this._encoding=t,this._chunks=[],this._totalLength=0}get encoding(){return this._encoding}append(t){let n=typeof t=="string"?this.fromString(t,this._encoding):t;this._chunks.push(n),this._totalLength+=n.byteLength}tryReadHeaders(t=!1){if(this._chunks.length===0)return;let n=0,o=0,s=0,a=0;e:for(;o<this._chunks.length;){let f=this._chunks[o];for(s=0;s<f.length;){switch(f[s]){case mx:switch(n){case 0:n=1;break;case 2:n=3;break;default:n=0}break;case hx:switch(n){case 1:n=2;break;case 3:n=4,s++;break e;default:n=0}break;default:n=0}s++}a+=f.byteLength,o++}if(n!==4)return;let l=this._read(a+s),d=new Map,p=this.toString(l,"ascii").split(gx);if(p.length<2)return d;for(let f=0;f<p.length-2;f++){let u=p[f],g=u.indexOf(":");if(g===-1)throw new Error(`Message header must separate key and value using ':'
22
+ ${u}`);let y=u.substr(0,g),b=u.substr(g+1).trim();d.set(t?y.toLowerCase():y,b)}return d}tryReadBody(t){if(!(this._totalLength<t))return this._read(t)}get numberOfBytes(){return this._totalLength}_read(t){if(t===0)return this.emptyBuffer();if(t>this._totalLength)throw new Error("Cannot read so many bytes!");if(this._chunks[0].byteLength===t){let a=this._chunks[0];return this._chunks.shift(),this._totalLength-=t,this.asNative(a)}if(this._chunks[0].byteLength>t){let a=this._chunks[0],l=this.asNative(a,t);return this._chunks[0]=a.slice(t),this._totalLength-=t,l}let n=this.allocNative(t),o=0,s=0;for(;t>0;){let a=this._chunks[s];if(a.byteLength>t){let l=a.slice(0,t);n.set(l,o),o+=t,this._chunks[s]=a.slice(t),this._totalLength-=t,t-=t}else n.set(a,o),o+=a.byteLength,this._chunks.shift(),this._totalLength-=a.byteLength,t-=a.byteLength}return n}};Xi.AbstractMessageBuffer=Il});var cm=kt(Me=>{"use strict";Object.defineProperty(Me,"__esModule",{value:!0});Me.createMessageConnection=Me.ConnectionOptions=Me.MessageStrategy=Me.CancellationStrategy=Me.CancellationSenderStrategy=Me.CancellationReceiverStrategy=Me.RequestCancellationReceiverStrategy=Me.IdCancellationReceiverStrategy=Me.ConnectionStrategy=Me.ConnectionError=Me.ConnectionErrors=Me.LogTraceNotification=Me.SetTraceNotification=Me.TraceFormat=Me.TraceValues=Me.Trace=Me.NullLogger=Me.ProgressType=Me.ProgressToken=void 0;var rm=no(),mt=vr(),Ie=nl(),sm=rl(),vs=Sr(),kl=Hi(),Is;(function(e){e.type=new Ie.NotificationType("$/cancelRequest")})(Is||(Is={}));var Dl;(function(e){function t(n){return typeof n=="string"||typeof n=="number"}i(t,"is"),e.is=t})(Dl||(Me.ProgressToken=Dl={}));var xs;(function(e){e.type=new Ie.NotificationType("$/progress")})(xs||(xs={}));var El=class{static{i(this,"ProgressType")}constructor(){}};Me.ProgressType=El;var Tl;(function(e){function t(n){return mt.func(n)}i(t,"is"),e.is=t})(Tl||(Tl={}));Me.NullLogger=Object.freeze({error:i(()=>{},"error"),warn:i(()=>{},"warn"),info:i(()=>{},"info"),log:i(()=>{},"log")});var ze;(function(e){e[e.Off=0]="Off",e[e.Messages=1]="Messages",e[e.Compact=2]="Compact",e[e.Verbose=3]="Verbose"})(ze||(Me.Trace=ze={}));var im;(function(e){e.Off="off",e.Messages="messages",e.Compact="compact",e.Verbose="verbose"})(im||(Me.TraceValues=im={}));(function(e){function t(o){if(!mt.string(o))return e.Off;switch(o=o.toLowerCase(),o){case"off":return e.Off;case"messages":return e.Messages;case"compact":return e.Compact;case"verbose":return e.Verbose;default:return e.Off}}i(t,"fromString"),e.fromString=t;function n(o){switch(o){case e.Off:return"off";case e.Messages:return"messages";case e.Compact:return"compact";case e.Verbose:return"verbose";default:return"off"}}i(n,"toString"),e.toString=n})(ze||(Me.Trace=ze={}));var tn;(function(e){e.Text="text",e.JSON="json"})(tn||(Me.TraceFormat=tn={}));(function(e){function t(n){return mt.string(n)?(n=n.toLowerCase(),n==="json"?e.JSON:e.Text):e.Text}i(t,"fromString"),e.fromString=t})(tn||(Me.TraceFormat=tn={}));var Pl;(function(e){e.type=new Ie.NotificationType("$/setTrace")})(Pl||(Me.SetTraceNotification=Pl={}));var Qi;(function(e){e.type=new Ie.NotificationType("$/logTrace")})(Qi||(Me.LogTraceNotification=Qi={}));var Ss;(function(e){e[e.Closed=1]="Closed",e[e.Disposed=2]="Disposed",e[e.AlreadyListening=3]="AlreadyListening"})(Ss||(Me.ConnectionErrors=Ss={}));var Er=class e extends Error{static{i(this,"ConnectionError")}constructor(t,n){super(n),this.code=t,Object.setPrototypeOf(this,e.prototype)}};Me.ConnectionError=Er;var Rl;(function(e){function t(n){let o=n;return o&&mt.func(o.cancelUndispatched)}i(t,"is"),e.is=t})(Rl||(Me.ConnectionStrategy=Rl={}));var Zi;(function(e){function t(n){let o=n;return o&&(o.kind===void 0||o.kind==="id")&&mt.func(o.createCancellationTokenSource)&&(o.dispose===void 0||mt.func(o.dispose))}i(t,"is"),e.is=t})(Zi||(Me.IdCancellationReceiverStrategy=Zi={}));var Cl;(function(e){function t(n){let o=n;return o&&o.kind==="request"&&mt.func(o.createCancellationTokenSource)&&(o.dispose===void 0||mt.func(o.dispose))}i(t,"is"),e.is=t})(Cl||(Me.RequestCancellationReceiverStrategy=Cl={}));var ea;(function(e){e.Message=Object.freeze({createCancellationTokenSource(n){return new kl.CancellationTokenSource}});function t(n){return Zi.is(n)||Cl.is(n)}i(t,"is"),e.is=t})(ea||(Me.CancellationReceiverStrategy=ea={}));var ta;(function(e){e.Message=Object.freeze({sendCancellation(n,o){return n.sendNotification(Is.type,{id:o})},cleanup(n){}});function t(n){let o=n;return o&&mt.func(o.sendCancellation)&&mt.func(o.cleanup)}i(t,"is"),e.is=t})(ta||(Me.CancellationSenderStrategy=ta={}));var na;(function(e){e.Message=Object.freeze({receiver:ea.Message,sender:ta.Message});function t(n){let o=n;return o&&ea.is(o.receiver)&&ta.is(o.sender)}i(t,"is"),e.is=t})(na||(Me.CancellationStrategy=na={}));var oa;(function(e){function t(n){let o=n;return o&&mt.func(o.handleMessage)}i(t,"is"),e.is=t})(oa||(Me.MessageStrategy=oa={}));var am;(function(e){function t(n){let o=n;return o&&(na.is(o.cancellationStrategy)||Rl.is(o.connectionStrategy)||oa.is(o.messageStrategy))}i(t,"is"),e.is=t})(am||(Me.ConnectionOptions=am={}));var wn;(function(e){e[e.New=1]="New",e[e.Listening=2]="Listening",e[e.Closed=3]="Closed",e[e.Disposed=4]="Disposed"})(wn||(wn={}));function yx(e,t,n,o){let s=n!==void 0?n:Me.NullLogger,a=0,l=0,d=0,p="2.0",f,u=new Map,g,y=new Map,b=new Map,S,T=new sm.LinkedMap,m=new Map,h=new Set,k=new Map,w=ze.Off,I=tn.Text,P,x=wn.New,A=new vs.Emitter,C=new vs.Emitter,$=new vs.Emitter,j=new vs.Emitter,z=new vs.Emitter,ie=o&&o.cancellationStrategy?o.cancellationStrategy:na.Message;function L(v){if(v===null)throw new Error("Can't send requests with id null since the response can't be correlated.");return"req-"+v.toString()}i(L,"createRequestQueueKey");function V(v){return v===null?"res-unknown-"+(++d).toString():"res-"+v.toString()}i(V,"createResponseQueueKey");function D(){return"not-"+(++l).toString()}i(D,"createNotificationQueueKey");function M(v,O){Ie.Message.isRequest(O)?v.set(L(O.id),O):Ie.Message.isResponse(O)?v.set(V(O.id),O):v.set(D(),O)}i(M,"addMessageToQueue");function _(v){}i(_,"cancelUndispatched");function N(){return x===wn.Listening}i(N,"isListening");function W(){return x===wn.Closed}i(W,"isClosed");function U(){return x===wn.Disposed}i(U,"isDisposed");function we(){(x===wn.New||x===wn.Listening)&&(x=wn.Closed,C.fire(void 0))}i(we,"closeHandler");function pe(v){A.fire([v,void 0,void 0])}i(pe,"readErrorHandler");function ce(v){A.fire(v)}i(ce,"writeErrorHandler"),e.onClose(we),e.onError(pe),t.onClose(we),t.onError(ce);function re(){S||T.size===0||(S=(0,rm.default)().timer.setImmediate(()=>{S=void 0,q()}))}i(re,"triggerMessageQueue");function R(v){Ie.Message.isRequest(v)?ne(v):Ie.Message.isNotification(v)?ot(v):Ie.Message.isResponse(v)?Ue(v):Mt(v)}i(R,"handleMessage");function q(){if(T.size===0)return;let v=T.shift();try{let O=o?.messageStrategy;oa.is(O)?O.handleMessage(v,R):R(v)}finally{re()}}i(q,"processMessageQueue");let H=i(v=>{try{if(Ie.Message.isNotification(v)&&v.method===Is.type.method){let O=v.params.id,F=L(O),Z=T.get(F);if(Ie.Message.isRequest(Z)){let le=o?.connectionStrategy,ue=le&&le.cancelUndispatched?le.cancelUndispatched(Z,_):void 0;if(ue&&(ue.error!==void 0||ue.result!==void 0)){T.delete(F),k.delete(O),ue.id=Z.id,Y(ue,v.method,Date.now()),t.write(ue).catch(()=>s.error("Sending response for canceled message failed."));return}}let _e=k.get(O);if(_e!==void 0){_e.cancel(),de(v);return}else h.add(O)}M(T,v)}finally{re()}},"callback");function ne(v){if(U())return;function O(X,he,ge){let Pe={jsonrpc:p,id:v.id};X instanceof Ie.ResponseError?Pe.error=X.toJson():Pe.result=X===void 0?null:X,Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(O,"reply");function F(X,he,ge){let Pe={jsonrpc:p,id:v.id,error:X.toJson()};Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(F,"replyError");function Z(X,he,ge){X===void 0&&(X=null);let Pe={jsonrpc:p,id:v.id,result:X};Y(Pe,he,ge),t.write(Pe).catch(()=>s.error("Sending response failed."))}i(Z,"replySuccess"),ve(v);let _e=u.get(v.method),le,ue;_e&&(le=_e.type,ue=_e.handler);let K=Date.now();if(ue||f){let X=v.id??String(Date.now()),he=Zi.is(ie.receiver)?ie.receiver.createCancellationTokenSource(X):ie.receiver.createCancellationTokenSource(v);v.id!==null&&h.has(v.id)&&he.cancel(),v.id!==null&&k.set(X,he);try{let ge;if(ue)if(v.params===void 0){if(le!==void 0&&le.numberOfParams!==0){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines ${le.numberOfParams} params but received none.`),v.method,K);return}ge=ue(he.token)}else if(Array.isArray(v.params)){if(le!==void 0&&le.parameterStructures===Ie.ParameterStructures.byName){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines parameters by name but received parameters by position`),v.method,K);return}ge=ue(...v.params,he.token)}else{if(le!==void 0&&le.parameterStructures===Ie.ParameterStructures.byPosition){F(new Ie.ResponseError(Ie.ErrorCodes.InvalidParams,`Request ${v.method} defines parameters by position but received parameters by name`),v.method,K);return}ge=ue(v.params,he.token)}else f&&(ge=f(v.method,v.params,he.token));let Pe=ge;ge?Pe.then?Pe.then(Ye=>{k.delete(X),O(Ye,v.method,K)},Ye=>{k.delete(X),Ye instanceof Ie.ResponseError?F(Ye,v.method,K):Ye&&mt.string(Ye.message)?F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed with message: ${Ye.message}`),v.method,K):F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed unexpectedly without providing any details.`),v.method,K)}):(k.delete(X),O(ge,v.method,K)):(k.delete(X),Z(ge,v.method,K))}catch(ge){k.delete(X),ge instanceof Ie.ResponseError?O(ge,v.method,K):ge&&mt.string(ge.message)?F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed with message: ${ge.message}`),v.method,K):F(new Ie.ResponseError(Ie.ErrorCodes.InternalError,`Request ${v.method} failed unexpectedly without providing any details.`),v.method,K)}}else F(new Ie.ResponseError(Ie.ErrorCodes.MethodNotFound,`Unhandled method ${v.method}`),v.method,K)}i(ne,"handleRequest");function Ue(v){if(!U())if(v.id===null)v.error?s.error(`Received response message without id: Error is:
23
23
  ${JSON.stringify(v.error,void 0,4)}`):s.error("Received response message without id. No further error information provided.");else{let O=v.id,F=m.get(O);if(te(v,F),F!==void 0){m.delete(O);try{if(v.error){let Z=v.error;F.reject(new Ie.ResponseError(Z.code,Z.message,Z.data))}else if(v.result!==void 0)F.resolve(v.result);else throw new Error("Should never happen.")}catch(Z){Z.message?s.error(`Response handler '${F.method}' failed with message: ${Z.message}`):s.error(`Response handler '${F.method}' failed unexpectedly.`)}}}}i(Ue,"handleResponse");function ot(v){if(U())return;let O,F;if(v.method===Is.type.method){let Z=v.params.id;h.delete(Z),de(v);return}else{let Z=y.get(v.method);Z&&(F=Z.handler,O=Z.type)}if(F||g)try{if(de(v),F)if(v.params===void 0)O!==void 0&&O.numberOfParams!==0&&O.parameterStructures!==Ie.ParameterStructures.byName&&s.error(`Notification ${v.method} defines ${O.numberOfParams} params but received none.`),F();else if(Array.isArray(v.params)){let Z=v.params;v.method===xs.type.method&&Z.length===2&&Dl.is(Z[0])?F({token:Z[0],value:Z[1]}):(O!==void 0&&(O.parameterStructures===Ie.ParameterStructures.byName&&s.error(`Notification ${v.method} defines parameters by name but received parameters by position`),O.numberOfParams!==v.params.length&&s.error(`Notification ${v.method} defines ${O.numberOfParams} params but received ${Z.length} arguments`)),F(...Z))}else O!==void 0&&O.parameterStructures===Ie.ParameterStructures.byPosition&&s.error(`Notification ${v.method} defines parameters by position but received parameters by name`),F(v.params);else g&&g(v.method,v.params)}catch(Z){Z.message?s.error(`Notification handler '${v.method}' failed with message: ${Z.message}`):s.error(`Notification handler '${v.method}' failed unexpectedly.`)}else $.fire(v)}i(ot,"handleNotification");function Mt(v){if(!v){s.error("Received empty message.");return}s.error(`Received message which is neither a response nor a notification message:
24
24
  ${JSON.stringify(v,null,4)}`);let O=v;if(mt.string(O.id)||mt.number(O.id)){let F=O.id,Z=m.get(F);Z&&Z.reject(new Error("The received response has neither a result nor an error property."))}}i(Mt,"handleInvalidMessage");function et(v){if(v!=null)switch(w){case ze.Verbose:return JSON.stringify(v,null,4);case ze.Compact:return JSON.stringify(v);default:return}}i(et,"stringifyTrace");function Pn(v){if(!(w===ze.Off||!P))if(I===tn.Text){let O;(w===ze.Verbose||w===ze.Compact)&&v.params&&(O=`Params: ${et(v.params)}
25
25
 
@@ -45,8 +45,8 @@ ${JSON.stringify(v,null,4)}`);let O=v;if(mt.string(O.id)||mt.number(O.id)){let F
45
45
 
46
46
  `:v.error===void 0&&(F=`No result returned.
47
47
 
48
- `)),O){let Z=v.error?` Request failed: ${v.error.message} (${v.error.code}).`:"";P.log(`Received response '${O.method} - (${v.id})' in ${Date.now()-O.timerStart}ms.${Z}`,F)}else P.log(`Received response ${v.id} without active response promise.`,F)}else oe("receive-response",v)}i(te,"traceReceivedResponse");function oe(v,O){if(!P||w===ze.Off)return;let F={isLSPMessage:!0,type:v,message:O,timestamp:Date.now()};P.log(F)}i(oe,"logLSPMessage");function ae(){if(W())throw new Er(Ss.Closed,"Connection is closed.");if(U())throw new Er(Ss.Disposed,"Connection is disposed.")}i(ae,"throwIfClosedOrDisposed");function Q(){if(N())throw new Er(Ss.AlreadyListening,"Connection is already listening")}i(Q,"throwIfListening");function je(){if(!N())throw new Error("Call listen() first.")}i(je,"throwIfNotListening");function Je(v){return v===void 0?null:v}i(Je,"undefinedToNull");function Ne(v){if(v!==null)return v}i(Ne,"nullToUndefined");function He(v){return v!=null&&!Array.isArray(v)&&typeof v=="object"}i(He,"isNamedParam");function xe(v,O){switch(v){case Ie.ParameterStructures.auto:return He(O)?Ne(O):[Je(O)];case Ie.ParameterStructures.byName:if(!He(O))throw new Error("Received parameters by name but param is not an object literal.");return Ne(O);case Ie.ParameterStructures.byPosition:return[Je(O)];default:throw new Error(`Unknown parameter structure ${v.toString()}`)}}i(xe,"computeSingleParam");function We(v,O){let F,Z=v.numberOfParams;switch(Z){case 0:F=void 0;break;case 1:F=xe(v.parameterStructures,O[0]);break;default:F=[];for(let _e=0;_e<O.length&&_e<Z;_e++)F.push(Je(O[_e]));if(O.length<Z)for(let _e=O.length;_e<Z;_e++)F.push(null);break}return F}i(We,"computeMessageParams");let J={sendNotification:i((v,...O)=>{ae();let F,Z;if(mt.string(v)){F=v;let le=O[0],ue=0,K=Ie.ParameterStructures.auto;Ie.ParameterStructures.is(le)&&(ue=1,K=le);let X=O.length,he=X-ue;switch(he){case 0:Z=void 0;break;case 1:Z=xe(K,O[ue]);break;default:if(K===Ie.ParameterStructures.byName)throw new Error(`Received ${he} parameters for 'by Name' notification parameter structure.`);Z=O.slice(ue,X).map(ge=>Je(ge));break}}else{let le=O;F=v.method,Z=We(v,le)}let _e={jsonrpc:p,method:F,params:Z};return E(_e),t.write(_e).catch(le=>{throw s.error("Sending notification failed."),le})},"sendNotification"),onNotification:i((v,O)=>{ae();let F;return mt.func(v)?g=v:O&&(mt.string(v)?(F=v,y.set(v,{type:void 0,handler:O})):(F=v.method,y.set(v.method,{type:v,handler:O}))),{dispose:i(()=>{F!==void 0?y.delete(F):g=void 0},"dispose")}},"onNotification"),onProgress:i((v,O,F)=>{if(b.has(O))throw new Error(`Progress handler for token ${O} already registered`);return b.set(O,F),{dispose:i(()=>{b.delete(O)},"dispose")}},"onProgress"),sendProgress:i((v,O,F)=>J.sendNotification(xs.type,{token:O,value:F}),"sendProgress"),onUnhandledProgress:j.event,sendRequest:i((v,...O)=>{ae(),je();let F,Z,_e;if(mt.string(v)){F=v;let X=O[0],he=O[O.length-1],ge=0,Pe=Ie.ParameterStructures.auto;Ie.ParameterStructures.is(X)&&(ge=1,Pe=X);let Ye=O.length;kl.CancellationToken.is(he)&&(Ye=Ye-1,_e=he);let wt=Ye-ge;switch(wt){case 0:Z=void 0;break;case 1:Z=xe(Pe,O[ge]);break;default:if(Pe===Ie.ParameterStructures.byName)throw new Error(`Received ${wt} parameters for 'by Name' request parameter structure.`);Z=O.slice(ge,Ye).map(zo=>Je(zo));break}}else{let X=O;F=v.method,Z=We(v,X);let he=v.numberOfParams;_e=kl.CancellationToken.is(X[he])?X[he]:void 0}let le=a++,ue;_e&&(ue=_e.onCancellationRequested(()=>{let X=ie.sender.sendCancellation(J,le);return X===void 0?(s.log(`Received no promise from cancellation strategy when cancelling id ${le}`),Promise.resolve()):X.catch(()=>{s.log(`Sending cancellation messages for id ${le} failed`)})}));let K={jsonrpc:p,id:le,method:F,params:Z};return Pn(K),typeof ie.sender.enableCancellation=="function"&&ie.sender.enableCancellation(K),new Promise(async(X,he)=>{let ge=i(wt=>{X(wt),ie.sender.cleanup(le),ue?.dispose()},"resolveWithCleanup"),Pe=i(wt=>{he(wt),ie.sender.cleanup(le),ue?.dispose()},"rejectWithCleanup"),Ye={method:F,timerStart:Date.now(),resolve:ge,reject:Pe};try{m.set(le,Ye),await t.write(K)}catch(wt){throw m.delete(le),Ye.reject(new Ie.ResponseError(Ie.ErrorCodes.MessageWriteError,wt.message?wt.message:"Unknown reason")),s.error("Sending request failed."),wt}})},"sendRequest"),onRequest:i((v,O)=>{ae();let F=null;return Tl.is(v)?(F=void 0,f=v):mt.string(v)?(F=null,O!==void 0&&(F=v,u.set(v,{handler:O,type:void 0}))):O!==void 0&&(F=v.method,u.set(v.method,{type:v,handler:O})),{dispose:i(()=>{F!==null&&(F!==void 0?u.delete(F):f=void 0)},"dispose")}},"onRequest"),hasPendingResponse:i(()=>m.size>0,"hasPendingResponse"),trace:i(async(v,O,F)=>{let Z=!1,_e=tn.Text;F!==void 0&&(mt.boolean(F)?Z=F:(Z=F.sendNotification||!1,_e=F.traceFormat||tn.Text)),w=v,I=_e,w===ze.Off?P=void 0:P=O,Z&&!W()&&!U()&&await J.sendNotification(Pl.type,{value:ze.toString(v)})},"trace"),onError:A.event,onClose:C.event,onUnhandledNotification:$.event,onDispose:z.event,end:i(()=>{t.end()},"end"),dispose:i(()=>{if(U())return;x=wn.Disposed,z.fire(void 0);let v=new Ie.ResponseError(Ie.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let O of m.values())O.reject(v);m=new Map,k=new Map,h=new Set,T=new sm.LinkedMap,mt.func(t.dispose)&&t.dispose(),mt.func(e.dispose)&&e.dispose()},"dispose"),listen:i(()=>{ae(),Q(),x=wn.Listening,e.listen(H)},"listen"),inspect:i(()=>{(0,rm.default)().console.log("inspect")},"inspect")};return J.onNotification(Qi.type,v=>{if(w===ze.Off||!P)return;let O=w===ze.Verbose||w===ze.Compact;P.log(v.message,O?v.verbose:void 0)}),J.onNotification(xs.type,v=>{let O=b.get(v.token);O?O(v.value):j.fire(v)}),J}i(fx,"createMessageConnection");Me.createMessageConnection=fx});var ra=kt(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.ProgressType=B.ProgressToken=B.createMessageConnection=B.NullLogger=B.ConnectionOptions=B.ConnectionStrategy=B.AbstractMessageBuffer=B.WriteableStreamMessageWriter=B.AbstractMessageWriter=B.MessageWriter=B.ReadableStreamMessageReader=B.AbstractMessageReader=B.MessageReader=B.SharedArrayReceiverStrategy=B.SharedArraySenderStrategy=B.CancellationToken=B.CancellationTokenSource=B.Emitter=B.Event=B.Disposable=B.LRUCache=B.Touch=B.LinkedMap=B.ParameterStructures=B.NotificationType9=B.NotificationType8=B.NotificationType7=B.NotificationType6=B.NotificationType5=B.NotificationType4=B.NotificationType3=B.NotificationType2=B.NotificationType1=B.NotificationType0=B.NotificationType=B.ErrorCodes=B.ResponseError=B.RequestType9=B.RequestType8=B.RequestType7=B.RequestType6=B.RequestType5=B.RequestType4=B.RequestType3=B.RequestType2=B.RequestType1=B.RequestType0=B.RequestType=B.Message=B.RAL=void 0;B.MessageStrategy=B.CancellationStrategy=B.CancellationSenderStrategy=B.CancellationReceiverStrategy=B.ConnectionError=B.ConnectionErrors=B.LogTraceNotification=B.SetTraceNotification=B.TraceFormat=B.TraceValues=B.Trace=void 0;var nt=nl();Object.defineProperty(B,"Message",{enumerable:!0,get:i(function(){return nt.Message},"get")});Object.defineProperty(B,"RequestType",{enumerable:!0,get:i(function(){return nt.RequestType},"get")});Object.defineProperty(B,"RequestType0",{enumerable:!0,get:i(function(){return nt.RequestType0},"get")});Object.defineProperty(B,"RequestType1",{enumerable:!0,get:i(function(){return nt.RequestType1},"get")});Object.defineProperty(B,"RequestType2",{enumerable:!0,get:i(function(){return nt.RequestType2},"get")});Object.defineProperty(B,"RequestType3",{enumerable:!0,get:i(function(){return nt.RequestType3},"get")});Object.defineProperty(B,"RequestType4",{enumerable:!0,get:i(function(){return nt.RequestType4},"get")});Object.defineProperty(B,"RequestType5",{enumerable:!0,get:i(function(){return nt.RequestType5},"get")});Object.defineProperty(B,"RequestType6",{enumerable:!0,get:i(function(){return nt.RequestType6},"get")});Object.defineProperty(B,"RequestType7",{enumerable:!0,get:i(function(){return nt.RequestType7},"get")});Object.defineProperty(B,"RequestType8",{enumerable:!0,get:i(function(){return nt.RequestType8},"get")});Object.defineProperty(B,"RequestType9",{enumerable:!0,get:i(function(){return nt.RequestType9},"get")});Object.defineProperty(B,"ResponseError",{enumerable:!0,get:i(function(){return nt.ResponseError},"get")});Object.defineProperty(B,"ErrorCodes",{enumerable:!0,get:i(function(){return nt.ErrorCodes},"get")});Object.defineProperty(B,"NotificationType",{enumerable:!0,get:i(function(){return nt.NotificationType},"get")});Object.defineProperty(B,"NotificationType0",{enumerable:!0,get:i(function(){return nt.NotificationType0},"get")});Object.defineProperty(B,"NotificationType1",{enumerable:!0,get:i(function(){return nt.NotificationType1},"get")});Object.defineProperty(B,"NotificationType2",{enumerable:!0,get:i(function(){return nt.NotificationType2},"get")});Object.defineProperty(B,"NotificationType3",{enumerable:!0,get:i(function(){return nt.NotificationType3},"get")});Object.defineProperty(B,"NotificationType4",{enumerable:!0,get:i(function(){return nt.NotificationType4},"get")});Object.defineProperty(B,"NotificationType5",{enumerable:!0,get:i(function(){return nt.NotificationType5},"get")});Object.defineProperty(B,"NotificationType6",{enumerable:!0,get:i(function(){return nt.NotificationType6},"get")});Object.defineProperty(B,"NotificationType7",{enumerable:!0,get:i(function(){return nt.NotificationType7},"get")});Object.defineProperty(B,"NotificationType8",{enumerable:!0,get:i(function(){return nt.NotificationType8},"get")});Object.defineProperty(B,"NotificationType9",{enumerable:!0,get:i(function(){return nt.NotificationType9},"get")});Object.defineProperty(B,"ParameterStructures",{enumerable:!0,get:i(function(){return nt.ParameterStructures},"get")});var Al=rl();Object.defineProperty(B,"LinkedMap",{enumerable:!0,get:i(function(){return Al.LinkedMap},"get")});Object.defineProperty(B,"LRUCache",{enumerable:!0,get:i(function(){return Al.LRUCache},"get")});Object.defineProperty(B,"Touch",{enumerable:!0,get:i(function(){return Al.Touch},"get")});var mx=Hf();Object.defineProperty(B,"Disposable",{enumerable:!0,get:i(function(){return mx.Disposable},"get")});var lm=Sr();Object.defineProperty(B,"Event",{enumerable:!0,get:i(function(){return lm.Event},"get")});Object.defineProperty(B,"Emitter",{enumerable:!0,get:i(function(){return lm.Emitter},"get")});var dm=Hi();Object.defineProperty(B,"CancellationTokenSource",{enumerable:!0,get:i(function(){return dm.CancellationTokenSource},"get")});Object.defineProperty(B,"CancellationToken",{enumerable:!0,get:i(function(){return dm.CancellationToken},"get")});var um=Jf();Object.defineProperty(B,"SharedArraySenderStrategy",{enumerable:!0,get:i(function(){return um.SharedArraySenderStrategy},"get")});Object.defineProperty(B,"SharedArrayReceiverStrategy",{enumerable:!0,get:i(function(){return um.SharedArrayReceiverStrategy},"get")});var Ml=Xf();Object.defineProperty(B,"MessageReader",{enumerable:!0,get:i(function(){return Ml.MessageReader},"get")});Object.defineProperty(B,"AbstractMessageReader",{enumerable:!0,get:i(function(){return Ml.AbstractMessageReader},"get")});Object.defineProperty(B,"ReadableStreamMessageReader",{enumerable:!0,get:i(function(){return Ml.ReadableStreamMessageReader},"get")});var _l=nm();Object.defineProperty(B,"MessageWriter",{enumerable:!0,get:i(function(){return _l.MessageWriter},"get")});Object.defineProperty(B,"AbstractMessageWriter",{enumerable:!0,get:i(function(){return _l.AbstractMessageWriter},"get")});Object.defineProperty(B,"WriteableStreamMessageWriter",{enumerable:!0,get:i(function(){return _l.WriteableStreamMessageWriter},"get")});var hx=om();Object.defineProperty(B,"AbstractMessageBuffer",{enumerable:!0,get:i(function(){return hx.AbstractMessageBuffer},"get")});var At=cm();Object.defineProperty(B,"ConnectionStrategy",{enumerable:!0,get:i(function(){return At.ConnectionStrategy},"get")});Object.defineProperty(B,"ConnectionOptions",{enumerable:!0,get:i(function(){return At.ConnectionOptions},"get")});Object.defineProperty(B,"NullLogger",{enumerable:!0,get:i(function(){return At.NullLogger},"get")});Object.defineProperty(B,"createMessageConnection",{enumerable:!0,get:i(function(){return At.createMessageConnection},"get")});Object.defineProperty(B,"ProgressToken",{enumerable:!0,get:i(function(){return At.ProgressToken},"get")});Object.defineProperty(B,"ProgressType",{enumerable:!0,get:i(function(){return At.ProgressType},"get")});Object.defineProperty(B,"Trace",{enumerable:!0,get:i(function(){return At.Trace},"get")});Object.defineProperty(B,"TraceValues",{enumerable:!0,get:i(function(){return At.TraceValues},"get")});Object.defineProperty(B,"TraceFormat",{enumerable:!0,get:i(function(){return At.TraceFormat},"get")});Object.defineProperty(B,"SetTraceNotification",{enumerable:!0,get:i(function(){return At.SetTraceNotification},"get")});Object.defineProperty(B,"LogTraceNotification",{enumerable:!0,get:i(function(){return At.LogTraceNotification},"get")});Object.defineProperty(B,"ConnectionErrors",{enumerable:!0,get:i(function(){return At.ConnectionErrors},"get")});Object.defineProperty(B,"ConnectionError",{enumerable:!0,get:i(function(){return At.ConnectionError},"get")});Object.defineProperty(B,"CancellationReceiverStrategy",{enumerable:!0,get:i(function(){return At.CancellationReceiverStrategy},"get")});Object.defineProperty(B,"CancellationSenderStrategy",{enumerable:!0,get:i(function(){return At.CancellationSenderStrategy},"get")});Object.defineProperty(B,"CancellationStrategy",{enumerable:!0,get:i(function(){return At.CancellationStrategy},"get")});Object.defineProperty(B,"MessageStrategy",{enumerable:!0,get:i(function(){return At.MessageStrategy},"get")});var gx=no();B.RAL=gx.default});var mm=kt(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var pm=Hr("util"),Un=ra(),sa=class e extends Un.AbstractMessageBuffer{static{i(this,"MessageBuffer")}constructor(t="utf-8"){super(t)}emptyBuffer(){return e.emptyBuffer}fromString(t,n){return Buffer.from(t,n)}toString(t,n){return t instanceof Buffer?t.toString(n):new pm.TextDecoder(n).decode(t)}asNative(t,n){return n===void 0?t instanceof Buffer?t:Buffer.from(t):t instanceof Buffer?t.slice(0,n):Buffer.from(t,0,n)}allocNative(t){return Buffer.allocUnsafe(t)}};sa.emptyBuffer=Buffer.allocUnsafe(0);var Ol=class{static{i(this,"ReadableStreamWrapper")}constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),Un.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),Un.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),Un.Disposable.create(()=>this.stream.off("end",t))}onData(t){return this.stream.on("data",t),Un.Disposable.create(()=>this.stream.off("data",t))}},Ll=class{static{i(this,"WritableStreamWrapper")}constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),Un.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),Un.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),Un.Disposable.create(()=>this.stream.off("end",t))}write(t,n){return new Promise((o,s)=>{let a=i(l=>{l==null?o():s(l)},"callback");typeof t=="string"?this.stream.write(t,n,a):this.stream.write(t,a)})}end(){this.stream.end()}},fm=Object.freeze({messageBuffer:Object.freeze({create:i(e=>new sa(e),"create")}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:i((e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(n){return Promise.reject(n)}},"encode")}),decoder:Object.freeze({name:"application/json",decode:i((e,t)=>{try{return e instanceof Buffer?Promise.resolve(JSON.parse(e.toString(t.charset))):Promise.resolve(JSON.parse(new pm.TextDecoder(t.charset).decode(e)))}catch(n){return Promise.reject(n)}},"decode")})}),stream:Object.freeze({asReadableStream:i(e=>new Ol(e),"asReadableStream"),asWritableStream:i(e=>new Ll(e),"asWritableStream")}),console,timer:Object.freeze({setTimeout(e,t,...n){let o=setTimeout(e,t,...n);return{dispose:i(()=>clearTimeout(o),"dispose")}},setImmediate(e,...t){let n=setImmediate(e,...t);return{dispose:i(()=>clearImmediate(n),"dispose")}},setInterval(e,t,...n){let o=setInterval(e,t,...n);return{dispose:i(()=>clearInterval(o),"dispose")}}})});function Nl(){return fm}i(Nl,"RIL");(function(e){function t(){Un.RAL.install(fm)}i(t,"install"),e.install=t})(Nl||(Nl={}));jl.default=Nl});var ym=kt($e=>{"use strict";var yx=$e&&$e.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:i(function(){return t[n]},"get")}),Object.defineProperty(e,o,s)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),bx=$e&&$e.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&yx(t,e,n)};Object.defineProperty($e,"__esModule",{value:!0});$e.createMessageConnection=$e.createServerSocketTransport=$e.createClientSocketTransport=$e.createServerPipeTransport=$e.createClientPipeTransport=$e.generateRandomPipeName=$e.StreamMessageWriter=$e.StreamMessageReader=$e.SocketMessageWriter=$e.SocketMessageReader=$e.PortMessageWriter=$e.PortMessageReader=$e.IPCMessageWriter=$e.IPCMessageReader=void 0;var Tr=mm();Tr.default.install();var hm=Hr("path"),wx=Hr("os"),vx=Hr("crypto"),ca=Hr("net"),nn=ra();bx(ra(),$e);var Ul=class extends nn.AbstractMessageReader{static{i(this,"IPCMessageReader")}constructor(t){super(),this.process=t;let n=this.process;n.on("error",o=>this.fireError(o)),n.on("close",()=>this.fireClose())}listen(t){return this.process.on("message",t),nn.Disposable.create(()=>this.process.off("message",t))}};$e.IPCMessageReader=Ul;var Fl=class extends nn.AbstractMessageWriter{static{i(this,"IPCMessageWriter")}constructor(t){super(),this.process=t,this.errorCount=0;let n=this.process;n.on("error",o=>this.fireError(o)),n.on("close",()=>this.fireClose)}write(t){try{return typeof this.process.send=="function"&&this.process.send(t,void 0,void 0,n=>{n?(this.errorCount++,this.handleError(n,t)):this.errorCount=0}),Promise.resolve()}catch(n){return this.handleError(n,t),Promise.reject(n)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){}};$e.IPCMessageWriter=Fl;var Bl=class extends nn.AbstractMessageReader{static{i(this,"PortMessageReader")}constructor(t){super(),this.onData=new nn.Emitter,t.on("close",()=>this.fireClose),t.on("error",n=>this.fireError(n)),t.on("message",n=>{this.onData.fire(n)})}listen(t){return this.onData.event(t)}};$e.PortMessageReader=Bl;var $l=class extends nn.AbstractMessageWriter{static{i(this,"PortMessageWriter")}constructor(t){super(),this.port=t,this.errorCount=0,t.on("close",()=>this.fireClose()),t.on("error",n=>this.fireError(n))}write(t){try{return this.port.postMessage(t),Promise.resolve()}catch(n){return this.handleError(n,t),Promise.reject(n)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){}};$e.PortMessageWriter=$l;var To=class extends nn.ReadableStreamMessageReader{static{i(this,"SocketMessageReader")}constructor(t,n="utf-8"){super((0,Tr.default)().stream.asReadableStream(t),n)}};$e.SocketMessageReader=To;var Po=class extends nn.WriteableStreamMessageWriter{static{i(this,"SocketMessageWriter")}constructor(t,n){super((0,Tr.default)().stream.asWritableStream(t),n),this.socket=t}dispose(){super.dispose(),this.socket.destroy()}};$e.SocketMessageWriter=Po;var ia=class extends nn.ReadableStreamMessageReader{static{i(this,"StreamMessageReader")}constructor(t,n){super((0,Tr.default)().stream.asReadableStream(t),n)}};$e.StreamMessageReader=ia;var aa=class extends nn.WriteableStreamMessageWriter{static{i(this,"StreamMessageWriter")}constructor(t,n){super((0,Tr.default)().stream.asWritableStream(t),n)}};$e.StreamMessageWriter=aa;var gm=process.env.XDG_RUNTIME_DIR,xx=new Map([["linux",107],["darwin",103]]);function Sx(){let e=(0,vx.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${e}-sock`;let t;gm?t=hm.join(gm,`vscode-ipc-${e}.sock`):t=hm.join(wx.tmpdir(),`vscode-${e}.sock`);let n=xx.get(process.platform);return n!==void 0&&t.length>n&&(0,Tr.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${n} characters.`),t}i(Sx,"generateRandomPipeName");$e.generateRandomPipeName=Sx;function Ix(e,t="utf-8"){let n,o=new Promise((s,a)=>{n=s});return new Promise((s,a)=>{let l=(0,ca.createServer)(d=>{l.close(),n([new To(d,t),new Po(d,t)])});l.on("error",a),l.listen(e,()=>{l.removeListener("error",a),s({onConnected:i(()=>o,"onConnected")})})})}i(Ix,"createClientPipeTransport");$e.createClientPipeTransport=Ix;function kx(e,t="utf-8"){let n=(0,ca.createConnection)(e);return[new To(n,t),new Po(n,t)]}i(kx,"createServerPipeTransport");$e.createServerPipeTransport=kx;function Dx(e,t="utf-8"){let n,o=new Promise((s,a)=>{n=s});return new Promise((s,a)=>{let l=(0,ca.createServer)(d=>{l.close(),n([new To(d,t),new Po(d,t)])});l.on("error",a),l.listen(e,"127.0.0.1",()=>{l.removeListener("error",a),s({onConnected:i(()=>o,"onConnected")})})})}i(Dx,"createClientSocketTransport");$e.createClientSocketTransport=Dx;function Ex(e,t="utf-8"){let n=(0,ca.createConnection)(e,"127.0.0.1");return[new To(n,t),new Po(n,t)]}i(Ex,"createServerSocketTransport");$e.createServerSocketTransport=Ex;function Tx(e){let t=e;return t.read!==void 0&&t.addListener!==void 0}i(Tx,"isReadableStream");function Px(e){let t=e;return t.write!==void 0&&t.addListener!==void 0}i(Px,"isWritableStream");function Rx(e,t,n,o){n||(n=nn.NullLogger);let s=Tx(e)?new ia(e):e,a=Px(t)?new aa(t):t;return nn.ConnectionStrategy.is(o)&&(o={connectionStrategy:o}),(0,nn.createMessageConnection)(s,a,n,o)}i(Rx,"createMessageConnection");$e.createMessageConnection=Rx});var wm=kt((MO,bm)=>{"use strict";bm.exports=ym()});var vo={};fe(vo,{AppNodeBuilder:()=>vo,build:()=>Dg});function Dg(e,t=[]){let n=t;if(ke.hasUnbound(e,Yn.node)&&!Eg(t,Yn.node)){let o=Uu(t),s=Xs({service:Yn.Service,layer:o,deps:[]});n=t.concat([[Yn.node,s]])}return ke.compile(e,n)}i(Dg,"build");function Eg(e,t){return e.some(([n])=>n.name===t.name)}i(Eg,"hasReplacement");var sc={};fe(sc,{Authorization:()=>rc,AuthorizeInput:()=>Ag,CallbackInput:()=>Mg,Method:()=>bi,Methods:()=>ep,OauthCallbackFailed:()=>xi,OauthCodeMissing:()=>vi,OauthMissing:()=>wi,ProviderAuth:()=>sc,Service:()=>xo,ValidationFailed:()=>os,node:()=>Lg,use:()=>_g});var Zu=c.Struct({key:c.String,op:c.Literals(["eq","neq"]),value:c.String}),Tg=c.Struct({type:c.Literal("text"),key:c.String,message:c.String,placeholder:hn(c.String),when:hn(Zu)}),Pg=c.Struct({label:c.String,value:c.String,hint:hn(c.String)}),Rg=c.Struct({type:c.Literal("select"),key:c.String,message:c.String,options:c.Array(Pg),when:hn(Zu)}),Cg=c.Union([Tg,Rg]),bi=class extends c.Class("ProviderAuthMethod")({type:c.Literals(["oauth","api"]),label:c.String,prompts:hn(c.Array(Cg))}){static{i(this,"Method")}},ep=c.Record(c.String,c.Array(bi)),rc=class extends c.Class("ProviderAuthAuthorization")({url:c.String,method:c.Literals(["auto","code"]),instructions:c.String}){static{i(this,"Authorization")}},Ag=c.Struct({method:c.Finite.annotate({description:"Auth method index"}),inputs:c.optional(c.Record(c.String,c.String)).annotate({description:"Prompt inputs"})}),Mg=c.Struct({method:c.Finite.annotate({description:"Auth method index"}),code:c.optional(c.String).annotate({description:"OAuth authorization code"})}),wi=class extends c.TaggedErrorClass()("ProviderAuthOauthMissing",{providerID:sn.ID}){static{i(this,"OauthMissing")}},vi=class extends c.TaggedErrorClass()("ProviderAuthOauthCodeMissing",{providerID:sn.ID}){static{i(this,"OauthCodeMissing")}},xi=class extends c.TaggedErrorClass()("ProviderAuthOauthCallbackFailed",{}){static{i(this,"OauthCallbackFailed")}},os=class extends c.TaggedErrorClass()("ProviderAuthValidationFailed",{field:c.String,message:c.String}){static{i(this,"ValidationFailed")}},xo=class extends Re.Service()("@opencode/ProviderAuth"){static{i(this,"Service")}},_g=Wt(xo),Og=Te.effect(xo,r.gen(function*(){let e=yield*Xt.Service,t=yield*pt.Service,n=yield*G.make(r.fn("ProviderAuth.state")(function*(){let d=yield*t.list();return{hooks:Go.fromEntries(Ed.filterMap(d,p=>p.auth?.provider!==void 0?Ma.succeed([sn.ID.make(p.auth.provider),p.auth]):Ma.failVoid)),pending:new Map}})),o=c.decodeUnknownSync(ep),s=r.fn("ProviderAuth.methods")(function*(){let d=(yield*G.get(n)).hooks;return o(Go.map(d,p=>p.methods.map(f=>({type:f.type,label:f.label,...f.prompts&&{prompts:f.prompts.map(u=>u.type==="select"?{type:"select",key:u.key,message:u.message,options:u.options,...u.when&&{when:u.when}}:{type:"text",key:u.key,message:u.message,...u.placeholder&&{placeholder:u.placeholder},...u.when&&{when:u.when}})}}))))}),a=r.fn("ProviderAuth.authorize")(function*(d){let{hooks:p,pending:f}=yield*G.get(n),u=p[d.providerID].methods[d.method];if(u.type!=="oauth")return;if(u.prompts&&d.inputs){for(let y of u.prompts)if(y.type==="text"&&y.validate&&d.inputs[y.key]!==void 0){let b=y.validate(d.inputs[y.key]);if(b)return yield*new os({field:y.key,message:b})}}let g=yield*r.tryPromise({try:i(()=>u.authorize(d.inputs),"try"),catch:i(y=>new os({field:"authorize",message:y instanceof Error?y.message:String(y)}),"catch")});return f.set(d.providerID,g),{url:g.url,method:g.method,instructions:g.instructions}}),l=r.fn("ProviderAuth.callback")(function*(d){let f=(yield*G.get(n)).pending.get(d.providerID);if(!f)return yield*new wi({providerID:d.providerID});if(f.method==="code"&&!d.code)return yield*new vi({providerID:d.providerID});let u=yield*r.promise(()=>f.method==="code"?f.callback(d.code):f.callback());if(!u||u.type!=="success")return yield*new xi({});if("key"in u&&(yield*e.set(d.providerID,{type:"api",key:u.key,...u.metadata?{metadata:u.metadata}:{}})),"refresh"in u){let{type:g,provider:y,refresh:b,access:S,expires:T,...m}=u;yield*e.set(d.providerID,{type:"oauth",access:S,refresh:b,expires:T,...m})}});return xo.of({methods:s,authorize:a,callback:l})})),Lg=ke.make({service:xo,layer:Og,deps:[Xt.node,pt.node]});var Qt={};fe(Qt,{Answer:()=>Vg,Event:()=>Ii,Info:()=>Bg,NotFoundError:()=>ss,Option:()=>Fg,Prompt:()=>$g,Question:()=>Qt,Rejected:()=>Hg,RejectedError:()=>rs,Replied:()=>Gg,Reply:()=>zg,Request:()=>Wg,Service:()=>tr,Tool:()=>qg,node:()=>Jg});var Ot={};fe(Ot,{Answer:()=>ic,Event:()=>Ug,ID:()=>Si,Info:()=>ip,Option:()=>rp,Prompt:()=>Ng,QuestionV1:()=>Ot,Rejected:()=>dp,Replied:()=>lp,Reply:()=>jg,Request:()=>cp,Tool:()=>ap});var Si=c.String.check(c.isStartsWith("que")).pipe(c.brand("QuestionID"),Hd(e=>({ascending:i(t=>e.make(t??"que_"+Yd()),"ascending")}))),rp=c.Struct({label:c.String.annotate({description:"Display text (1-5 words, concise)"}),description:c.String.annotate({description:"Explanation of choice"})}).annotate({identifier:"QuestionOption"}),sp={question:c.String.annotate({description:"Complete question"}),header:c.String.annotate({description:"Very short label (max 30 chars)"}),options:c.Array(rp).annotate({description:"Available choices"}),multiple:c.optional(c.Boolean).annotate({description:"Allow selecting multiple choices"})},ip=c.Struct({...sp,custom:c.optional(c.Boolean).annotate({description:"Allow typing a custom answer (default: true)"})}).annotate({identifier:"QuestionInfo"}),Ng=c.Struct(sp).annotate({identifier:"QuestionPrompt"}),ap=c.Struct({messageID:fu.MessageID,callID:c.String}).annotate({identifier:"QuestionTool"}),cp=c.Struct({id:Si,sessionID:Cn,questions:c.Array(ip).annotate({description:"Questions to ask"}),tool:c.optional(ap)}).annotate({identifier:"QuestionRequest"}),ic=c.Array(c.String).annotate({identifier:"QuestionAnswer"}),jg=c.Struct({answers:c.Array(ic).annotate({description:"User answers in order of questions (each answer is an array of selected labels)"})}).annotate({identifier:"QuestionReply"}),lp=c.Struct({sessionID:Cn,requestID:Si,answers:c.Array(ic)}).annotate({identifier:"QuestionReplied"}),dp=c.Struct({sessionID:Cn,requestID:Si}).annotate({identifier:"QuestionRejected"}),tp=Qs({type:"question.asked",schema:cp.fields}),np=Qs({type:"question.replied",schema:lp.fields}),op=Qs({type:"question.rejected",schema:dp.fields}),Ug={Asked:tp,Replied:np,Rejected:op,Definitions:Jd(tp,np,op)};var ac=Ot.ID;var Fg=Ot.Option,Bg=Ot.Info,$g=Ot.Prompt,qg=Ot.Tool,Wg=Ot.Request,Vg=Ot.Answer,zg=Ot.Reply,Gg=Ot.Replied,Hg=Ot.Rejected,Ii=Ot.Event,rs=class extends c.TaggedErrorClass()("QuestionRejectedError",{}){static{i(this,"RejectedError")}get message(){return"The user dismissed this question"}},ss=class extends c.TaggedErrorClass()("Question.NotFoundError",{requestID:ac}){static{i(this,"NotFoundError")}},tr=class extends Re.Service()("@opencode/Question"){static{i(this,"Service")}},Yg=Te.effect(tr,r.gen(function*(){let e=yield*De.Service,t=yield*G.make(r.fn("Question.state")(function*(){let l={pending:new Map};return yield*r.addFinalizer(()=>r.gen(function*(){for(let d of l.pending.values())yield*ht.fail(d.deferred,new rs);l.pending.clear()})),l})),n=r.fn("Question.ask")(function*(l){let d=(yield*G.get(t)).pending,p=ac.ascending();yield*r.logInfo("asking",{id:p,questions:l.questions.length});let f=yield*ht.make(),u={id:p,sessionID:l.sessionID,questions:l.questions,tool:l.tool};return d.set(p,{info:u,deferred:f}),yield*e.publish(Ii.Asked,u),yield*r.ensuring(ht.await(f),r.sync(()=>{d.delete(p)}))}),o=r.fn("Question.reply")(function*(l){let d=(yield*G.get(t)).pending,p=d.get(l.requestID);if(!p)return yield*r.logWarning("reply for unknown request",{requestID:l.requestID}),yield*new ss({requestID:l.requestID});d.delete(l.requestID),yield*r.logInfo("replied",{requestID:l.requestID,answers:l.answers}),yield*e.publish(Ii.Replied,{sessionID:p.info.sessionID,requestID:p.info.id,answers:l.answers.map(f=>[...f])}),yield*ht.succeed(p.deferred,l.answers)}),s=r.fn("Question.reject")(function*(l){let d=(yield*G.get(t)).pending,p=d.get(l);if(!p)return yield*r.logWarning("reject for unknown request",{requestID:l}),yield*new ss({requestID:l});d.delete(l),yield*r.logInfo("rejected",{requestID:l}),yield*e.publish(Ii.Rejected,{sessionID:p.info.sessionID,requestID:p.info.id}),yield*ht.fail(p.deferred,new rs)}),a=r.fn("Question.list")(function*(){let l=(yield*G.get(t)).pending;return Array.from(l.values(),d=>d.info)});return tr.of({ask:n,reply:o,reject:s,list:a})})),Jg=ke.make({service:tr,layer:Yg,deps:[De.node]});var Qn={};fe(Qn,{Event:()=>up,Info:()=>Kg,Service:()=>nr,Todo:()=>Qn,node:()=>Qg});var Kg=Ha.Info,up=Ha.Event,nr=class extends Re.Service()("@opencode/SessionTodo"){static{i(this,"Service")}},Xg=Te.effect(nr,r.gen(function*(){let e=yield*De.Service,{db:t}=yield*Qe.Service,n=r.fn("Todo.update")(function*(s){yield*t.transaction(a=>r.gen(function*(){yield*a.delete(go).where(St(go.session_id,s.sessionID)).run(),s.todos.length!==0&&(yield*a.insert(go).values(s.todos.map((l,d)=>({session_id:s.sessionID,content:l.content,status:l.status,priority:l.priority,position:d}))).run())})).pipe(r.orDie),yield*e.publish(up.Updated,s)}),o=r.fn("Todo.get")(function*(s){return(yield*t.select().from(go).where(St(go.session_id,s)).orderBy(Zs(go.position)).all().pipe(r.orDie)).map(l=>({content:l.content,status:l.status,priority:l.priority}))});return nr.of({update:n,get:o})})),Qg=ke.make({service:nr,layer:Xg,deps:[De.node,Qe.node]});var ln={};fe(ln,{Event:()=>cc,Info:()=>ey,Service:()=>rr,SessionStatus:()=>ln,node:()=>ny});var or={};fe(or,{Definitions:()=>Zg,Idle:()=>mp,Info:()=>pp,SessionStatusEvent:()=>or,Status:()=>fp});var pp=c.Union([c.Struct({type:c.Literal("idle")}),c.Struct({type:c.Literal("retry"),attempt:mn,message:c.String,action:hn(c.Struct({reason:c.String,provider:c.String,title:c.String,message:c.String,label:c.String,link:hn(c.String)})),next:mn}),c.Struct({type:c.Literal("busy")})]).annotate({identifier:"SessionStatus"}),fp=Et.define({type:"session.status",schema:{sessionID:Cn,status:pp}}),mp=Et.define({type:"session.idle",schema:{sessionID:Cn}}),Zg=Et.inventory(fp,mp);var ey=or.Info,cc=or,rr=class extends Re.Service()("@opencode/SessionStatus"){static{i(this,"Service")}},ty=Te.effect(rr,r.gen(function*(){let e=yield*De.Service,t=yield*G.make(r.fn("SessionStatus.state")(()=>r.succeed(new Map))),n=r.fn("SessionStatus.get")(function*(a){return(yield*G.get(t)).get(a)??{type:"idle"}}),o=r.fn("SessionStatus.list")(function*(){return new Map(yield*G.get(t))}),s=r.fn("SessionStatus.set")(function*(a,l){let d=yield*G.get(t);if(yield*e.publish(cc.Status,{sessionID:a,status:l}),l.type==="idle"){yield*e.publish(cc.Idle,{sessionID:a}),d.delete(a);return}d.set(a,l)});return rr.of({get:n,list:o,set:s})})),ny=ke.make({service:rr,layer:ty,deps:[De.node]});var Ln={};fe(Ln,{Service:()=>sr,SessionRunState:()=>Ln,node:()=>iy});var is={};fe(is,{Busy:()=>ki,Cancelled:()=>So,Runner:()=>is,make:()=>oy});var So=class extends c.TaggedErrorClass()("RunnerCancelled",{}){static{i(this,"Cancelled")}},ki=class extends c.TaggedErrorClass()("RunnerBusy",{}){static{i(this,"Busy")}},oy=i((e,t)=>{let n=Rn.makeUnsafe({_tag:"Idle"}),o=t?.onIdle??r.void,s=t?.onBusy??r.void,a=t?.onInterrupt,l=0,d=i(()=>Rn.getUnsafe(n),"state"),p=i(()=>(l+=1,l),"next"),f=i((w,I)=>bt.isFailure(I)&&tt.hasInterruptsOnly(I.cause)?ht.fail(w,new So).pipe(r.asVoid):ht.done(w,I).pipe(r.asVoid),"complete"),u=i(w=>ht.await(w).pipe(r.catchTag("RunnerCancelled",I=>a??r.die(I))),"awaitDone"),g=i(()=>Rn.modify(n,w=>[w._tag==="Idle"?o:r.void,w]).pipe(r.flatten),"idleIfCurrent"),y=i((w,I,P)=>Rn.modify(n,x=>[r.gen(function*(){x._tag==="Running"&&x.run.id===w&&(yield*o),yield*f(I,P)}),x._tag==="Running"&&x.run.id===w?{_tag:"Idle"}:x]).pipe(r.flatten),"finishRun"),b=i((w,I)=>r.gen(function*(){let P=p(),x=yield*w.pipe(r.onExit(A=>y(P,I,A)),r.forkIn(e));return{id:P,done:I,fiber:x}}),"startRun"),S=i(w=>Rn.modifyEffect(n,r.fnUntraced(function*(I){if(I._tag==="Shell"&&I.shell.id===w)return[o,{_tag:"Idle"}];if(I._tag==="ShellThenRun"&&I.shell.id===w){let P=yield*b(I.run.work,I.run.done);return[r.void,{_tag:"Running",run:P}]}return[r.void,I]})).pipe(r.flatten),"finishShell"),T=i(w=>r.gen(function*(){w.ready&&(yield*w.ready.await.pipe(r.exit,r.asVoid)),yield*ht.succeed(w.cancelled,void 0).pipe(r.asVoid),yield*Vs.interrupt(w.fiber)}),"stopShell"),m=i(w=>Rn.modifyEffect(n,r.fnUntraced(function*(I){switch(I._tag){case"Running":case"ShellThenRun":return[u(I.run.done),I];case"Shell":{let P={id:p(),done:yield*ht.make(),work:w};return[u(P.done),{_tag:"ShellThenRun",shell:I.shell,run:P}]}case"Idle":{let P=yield*ht.make(),x=yield*b(w,P);return[u(P),{_tag:"Running",run:x}]}}})).pipe(r.flatten),"ensureRunning"),h=i((w,I)=>Rn.modifyEffect(n,r.fnUntraced(function*(P){if(P._tag!=="Idle")return[r.fail(new ki),P];yield*s;let x=p(),A=yield*ht.make(),C=yield*w.pipe(r.ensuring(S(x)),r.forkChild),$={id:x,cancelled:A,ready:I,fiber:C};return[r.gen(function*(){let j=yield*Vs.await(C);return bt.isSuccess(j)?j.value:tt.hasInterruptsOnly(j.cause)||(yield*ht.isDone(A))&&tt.hasInterrupts(j.cause)&&!tt.hasDies(j.cause)?a?yield*a:yield*r.die(new So):yield*r.failCause(j.cause)}),{_tag:"Shell",shell:$}]})).pipe(r.flatten),"startShell"),k=Rn.modify(n,w=>{switch(w._tag){case"Idle":return[r.void,w];case"Running":return[r.gen(function*(){yield*Vs.interrupt(w.run.fiber),yield*ht.fail(w.run.done,new So).pipe(r.asVoid),yield*g()}),{_tag:"Idle"}];case"Shell":return[r.gen(function*(){yield*T(w.shell),yield*g()}),{_tag:"Idle"}];case"ShellThenRun":return[r.gen(function*(){yield*T(w.shell),yield*ht.fail(w.run.done,new So).pipe(r.asVoid),yield*g()}),{_tag:"Idle"}]}}).pipe(r.flatten);return{get state(){return d()},get busy(){return d()._tag!=="Idle"},ensureRunning:m,startShell:h,cancel:k}},"make");var sr=class extends Re.Service()("@opencode/SessionRunState"){static{i(this,"Service")}},ry=Te.effect(sr,r.gen(function*(){let e=yield*bo.Service,t=yield*ln.Service,n=yield*G.make(r.fn("SessionRunState.state")(function*(){let f=yield*Dt.Scope,u=new Map;return yield*r.addFinalizer(r.fnUntraced(function*(){u.size>0&&(yield*r.logWarning("instance closing: its running turns are cancelled",{sessions:[...u.keys()].join(",")})),yield*r.forEach(u.values(),g=>g.cancel,{concurrency:"unbounded",discard:!0}),u.clear()})),{runners:u,scope:f}})),o=r.fn("SessionRunState.runner")(function*(f,u){let g=yield*G.get(n),y=g.runners.get(f);if(y)return y;let b=is.make(g.scope,{onIdle:r.gen(function*(){g.runners.delete(f),yield*t.set(f,{type:"idle"})}),onBusy:t.set(f,{type:"busy"}),onInterrupt:u});return g.runners.set(f,b),b}),s=r.fn("SessionRunState.assertNotBusy")(function*(f){(yield*G.get(n)).runners.get(f)?.busy&&(yield*hp(f))}),a=r.fn("SessionRunState.cancel")(function*(f){yield*r.logWarning("session cancel requested",{sessionID:f}),yield*sy(e,f);let g=(yield*G.get(n)).runners.get(f);if(!g){yield*t.set(f,{type:"idle"});return}yield*g.cancel}),l=r.fn("SessionRunState.busy")(function*(){return[...(yield*G.get(n)).runners.entries()].filter(([,u])=>u.busy).map(([u])=>u)}),d=r.fn("SessionRunState.ensureRunning")(function*(f,u,g){return yield*(yield*o(f,u)).ensureRunning(g)}),p=r.fn("SessionRunState.startShell")(function*(f,u,g,y){return yield*(yield*o(f,u)).startShell(g,y).pipe(r.catchTag("RunnerBusy",()=>r.fail(hp(f))))});return sr.of({assertNotBusy:s,cancel:a,busy:l,ensureRunning:d,startShell:p})})),sy=r.fn("SessionRunState.cancelBackgroundJobs")(function*(e,t){let n=yield*e.list(),o=new Set([t]),s=new Set,a=i(d=>d.status!=="running"||s.has(d.id)?!1:o.has(d.id)||typeof d.metadata?.sessionId=="string"&&o.has(d.metadata.sessionId)?!0:typeof d.metadata?.parentSessionId=="string"&&o.has(d.metadata.parentSessionId),"matches"),l=n.filter(a);for(;l.length>0;)yield*r.forEach(l,d=>e.cancel(d.id).pipe(r.tap(()=>r.sync(()=>{s.add(d.id),o.add(d.id),typeof d.metadata?.sessionId=="string"&&o.add(d.metadata.sessionId)}))),{concurrency:"unbounded",discard:!0}),l=n.filter(a)});function hp(e){return new me.BusyError({sessionID:e})}i(hp,"busyError");var iy=ke.make({service:sr,layer:ry,deps:[bo.node,ln.node]});var dn={};fe(dn,{LLM:()=>dn,OUTPUT_TOKEN_MAX:()=>ev,Service:()=>ko,hasToolCalls:()=>ov,node:()=>rv,use:()=>tv});var as={};fe(as,{Wildcard:()=>as,all:()=>ay,allStructured:()=>cy,match:()=>Di});function Di(e,t){e&&(e=e.replaceAll("\\","/")),t&&(t=t.replaceAll("\\","/"));let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");n.endsWith(" .*")&&(n=n.slice(0,-3)+"( .*)?");let o=process.platform==="win32"?"si":"s";return new RegExp("^"+n+"$",o).test(e)}i(Di,"match");function ay(e,t){let n=Ja(t,Object.entries,Ka([([s])=>s.length,"asc"],[([s])=>s,"asc"])),o;for(let[s,a]of n)if(Di(e,s)){o=a;continue}return o}i(ay,"all");function cy(e,t){let n=Ja(t,Object.entries,Ka([([s])=>s.length,"asc"],[([s])=>s,"asc"])),o;for(let[s,a]of n){let l=s.split(/\s+/);if(Di(e.head,l[0])&&(l.length===1||lc(e.tail,l.slice(1)))){o=a;continue}}return o}i(cy,"allStructured");function lc(e,t){if(t.length===0)return!0;let[n,...o]=t;if(n==="*")return lc(e,o);for(let s=0;s<e.length;s++)if(Di(e[s],n)&&lc(e.slice(s+1),o))return!0;return!1}i(lc,"matchSequence");var ir={};fe(ir,{LLMAISDK:()=>ir,adapterState:()=>bp,toLLMEvents:()=>dy});function bp(){return{step:0,text:0,reasoning:0,currentTextID:void 0,currentReasoningID:void 0,toolNames:{},copilotTotalNanoAiu:void 0}}i(bp,"adapterState");function gp(e){return c.is(Zd)(e)?e:"unknown"}i(gp,"finishReason");function Zt(e){if(e!=null)return c.is(Qd)(e)?e:void 0}i(Zt,"providerMetadata");function ly(e){if(!e||typeof e!="object")return;let t=e,n=t.response&&typeof t.response=="object"?t.response:void 0,o=t.copilot_usage??n?.copilot_usage;if(!o||typeof o!="object")return;let s=o.total_nano_aiu;if(!(typeof s!="number"||!Number.isFinite(s)||s<0))return s}i(ly,"copilotTotalNanoAiu");function yp(e){if(!e||typeof e!="object")return;let t=e,n=Object.entries({inputTokens:t.inputTokens,outputTokens:t.outputTokens,totalTokens:t.totalTokens,reasoningTokens:t.outputTokenDetails?.reasoningTokens??t.reasoningTokens,cacheReadInputTokens:t.inputTokenDetails?.cacheReadTokens??t.cachedInputTokens,cacheWriteInputTokens:t.inputTokenDetails?.cacheWriteTokens}).filter(o=>o[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}i(yp,"usage");function dc(e,t){return e.currentTextID=t??e.currentTextID??`text-${e.text++}`,e.currentTextID}i(dc,"currentTextID");function uc(e,t){return e.currentReasoningID=t??e.currentReasoningID??`reasoning-${e.reasoning++}`,e.currentReasoningID}i(uc,"currentReasoningID");function dy(e,t){switch(t.type){case"start":return r.succeed([]);case"start-step":return r.succeed([rt.stepStart({index:e.step})]);case"finish-step":return t.rawFinishReason==="network_error"?r.fail(new Wu.ResponseStreamError("Provider finish_reason: network_error")):r.sync(()=>{let n=Zt(t.providerMetadata),o=e.copilotTotalNanoAiu===void 0?n:{...n,copilot:{...n?.copilot,totalNanoAiu:e.copilotTotalNanoAiu}};return e.copilotTotalNanoAiu=void 0,[rt.stepFinish({index:e.step++,reason:gp(t.finishReason),usage:yp(t.usage),providerMetadata:o,...typeof t.response?.modelId=="string"?{responseModelID:t.response.modelId}:{}})]});case"finish":return r.sync(()=>{let n=[rt.finish({reason:gp(t.finishReason),usage:yp(t.totalUsage),providerMetadata:"providerMetadata"in t?Zt(t.providerMetadata):void 0})];return Object.assign(e,bp()),n});case"text-start":return r.sync(()=>(e.currentTextID=dc(e,t.id),[rt.textStart({id:e.currentTextID,providerMetadata:Zt(t.providerMetadata)})]));case"text-delta":return r.succeed([rt.textDelta({id:dc(e,t.id),text:t.text,providerMetadata:Zt(t.providerMetadata)})]);case"text-end":return r.sync(()=>{let n=dc(e,t.id);return e.currentTextID=void 0,[rt.textEnd({id:n,providerMetadata:Zt(t.providerMetadata)})]});case"reasoning-start":return r.sync(()=>(e.currentReasoningID=uc(e,t.id),[rt.reasoningStart({id:e.currentReasoningID,providerMetadata:Zt(t.providerMetadata)})]));case"reasoning-delta":return r.succeed([rt.reasoningDelta({id:uc(e,t.id),text:t.text,providerMetadata:Zt(t.providerMetadata)})]);case"reasoning-end":return r.sync(()=>{let n=uc(e,t.id);return e.currentReasoningID=void 0,[rt.reasoningEnd({id:n,providerMetadata:Zt(t.providerMetadata)})]});case"tool-input-start":return r.sync(()=>(e.toolNames[t.id]=t.toolName,[rt.toolInputStart({id:t.id,name:t.toolName,providerMetadata:Zt(t.providerMetadata)})]));case"tool-input-delta":return r.succeed([rt.toolInputDelta({id:t.id,name:e.toolNames[t.id]??"unknown",text:t.delta??""})]);case"tool-input-end":return r.succeed([rt.toolInputEnd({id:t.id,name:e.toolNames[t.id]??"unknown",providerMetadata:Zt(t.providerMetadata)})]);case"tool-call":return r.sync(()=>(e.toolNames[t.toolCallId]=t.toolName,[rt.toolCall({id:t.toolCallId,name:t.toolName,input:t.input,providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:Zt(t.providerMetadata)})]));case"tool-result":return r.sync(()=>{let n=e.toolNames[t.toolCallId]??"unknown";return delete e.toolNames[t.toolCallId],[rt.toolResult({id:t.toolCallId,name:n,result:eu.make(t.output),providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:Zt(t.providerMetadata)})]});case"tool-error":return r.sync(()=>{let n=e.toolNames[t.toolCallId]??("toolName"in t?t.toolName:"unknown");return delete e.toolNames[t.toolCallId],[rt.toolError({id:t.toolCallId,name:n,message:gn(t.error),error:t.error,providerMetadata:Zt(t.providerMetadata)})]});case"error":return r.fail(t.error);case"abort":case"source":case"file":case"tool-output-denied":case"tool-approval-request":return r.succeed([]);case"raw":return r.sync(()=>(e.copilotTotalNanoAiu=ly(t.rawValue)??e.copilotTotalNanoAiu,[]));default:{let n=t;return r.succeed([])}}}i(dy,"toLLMEvents");var hs={};fe(hs,{LLMNativeRuntime:()=>hs,nativeTools:()=>of,status:()=>Ww,stream:()=>Vw});var ms={};fe(ms,{LLMNative:()=>ms,model:()=>ef,request:()=>qw});var Ei={};fe(Ei,{configure:()=>pc,id:()=>wp,model:()=>my,provider:()=>vp,routes:()=>uy});var wp=lt.make("anthropic"),uy=[Wa],py=i(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("ANTHROPIC_API_KEY")).pipe(gt.header("x-api-key")),"auth"),fy=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return Wa.with({...s,endpoint:{baseURL:o},auth:py(e)})},"configuredRoute"),pc=i((e={})=>{let t=fy(e);return{id:wp,model:i(n=>t.model({id:n}),"model"),configure:pc}},"configure"),vp=pc(),my=vp.model;var Pi={};fe(Pi,{configure:()=>gc,id:()=>hc,model:()=>fb,provider:()=>Rp,routes:()=>db});var cs={};fe(cs,{BedrockEventStream:()=>cs,framing:()=>vy});var hy=new Ru(Au,Cu),gy=new TextDecoder,yy={buffer:new Uint8Array(0),offset:0},by=i((e,t)=>{let n=e.buffer.length-e.offset,o=new Uint8Array(n+t.length);return o.set(e.buffer.subarray(e.offset),0),o.set(t,n),{buffer:o,offset:0}},"appendChunk"),wy=i(e=>(t,n)=>r.gen(function*(){let o=by(t,n),s=[];for(;o.buffer.length-o.offset>=4;){let a=o.buffer.subarray(o.offset),l=new DataView(a.buffer,a.byteOffset,a.byteLength).getUint32(0,!1);if(a.length<l)break;let d=yield*r.try({try:i(()=>hy.decode(a.subarray(0,l)),"try"),catch:i(g=>Ce.eventError(e,`Failed to decode Bedrock Converse event-stream frame: ${g instanceof Error?g.message:String(g)}`),"catch")});if(o={buffer:o.buffer,offset:o.offset+l},d.headers[":message-type"]?.value!=="event")continue;let p=d.headers[":event-type"]?.value;if(typeof p!="string")continue;let f=gy.decode(d.body);if(!f)continue;let u=yield*Ce.parseJson(e,f,"Failed to parse Bedrock Converse event-stream payload");delete u.p,s.push({[p]:u})}return[o,s]}),"consumeFrames"),vy=i(e=>({id:"aws-event-stream",frame:i(t=>t.pipe(vt.mapAccumEffect(()=>yy,wy(e))),"frame")}),"framing");var ar={};fe(ar,{BedrockAuth:()=>ar,auth:()=>Sy,sigV4:()=>xp});var xy=i(e=>r.tryPromise({try:i(async()=>{let t=await new Pu({url:e.url,method:"POST",headers:Object.entries(e.headers),body:e.body,region:e.credentials.region,accessKeyId:e.credentials.accessKeyId,secretAccessKey:e.credentials.secretAccessKey,sessionToken:e.credentials.sessionToken,service:"bedrock"}).sign();return Object.fromEntries(t.headers.entries())},"try"),catch:i(t=>Ce.invalidRequest(`Bedrock Converse SigV4 signing failed: ${t instanceof Error?t.message:String(t)}`),"catch")}),"signRequest"),xp=i(e=>gt.custom(t=>r.gen(function*(){if(!e)return yield*Ce.invalidRequest("Bedrock Converse requires either route bearer auth or AWS credentials configured on the route");let n=ja.set(t.headers,"content-type","application/json"),o=yield*xy({url:t.url,body:t.body,headers:n,credentials:e});return ja.setAll(n,o)})),"sigV4"),Sy=xp(void 0);var en={};fe(en,{BEDROCK_BREAKPOINT_CAP:()=>Sp,BedrockCache:()=>en,CachePointBlock:()=>Iy,block:()=>Ty,breakpoints:()=>ky});var Iy=c.Struct({cachePoint:c.Struct({type:c.tag("default"),ttl:c.optional(c.Literals(["5m","1h"]))})}),Sp=4,ky=i(()=>vu(Sp),"breakpoints"),Dy={cachePoint:{type:"default"}},Ey={cachePoint:{type:"default",ttl:"1h"}},Ty=i((e,t)=>{if(!(t?.type!=="ephemeral"&&t?.type!=="persistent")){if(e.remaining<=0){e.dropped+=1;return}return e.remaining-=1,xu(t.ttlSeconds)==="1h"?Ey:Dy}},"block");var Nn={};fe(Nn,{BedrockMedia:()=>Nn,DocumentBlock:()=>Ry,DocumentFormat:()=>Ep,ImageBlock:()=>Py,ImageFormat:()=>Dp,lower:()=>Ay});var Dp=c.Literals(["png","jpeg","gif","webp"]),Py=c.Struct({image:c.Struct({format:Dp,source:c.Struct({bytes:c.String})})}),Ep=c.Literals(["pdf","csv","doc","docx","xls","xlsx","html","txt","md"]),Ry=c.Struct({document:c.Struct({format:Ep,name:c.String,source:c.Struct({bytes:c.String})})}),Ip={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},kp={"application/pdf":"pdf","text/csv":"csv","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/html":"html","text/plain":"txt","text/markdown":"md"},Cy=i((e,t,n)=>({document:{format:t,name:e.filename??`document.${t}`,source:{bytes:n}}}),"documentBlock"),Ay=r.fn("BedrockMedia.lower")(function*(e){let t=e.mediaType.toLowerCase(),n=Ip[t];if(n){let s=yield*Ce.validateMedia("Bedrock Converse",e,new Set(Object.keys(Ip)));return{image:{format:n,source:{bytes:s.base64}}}}if(t.startsWith("image/"))return yield*Ce.invalidRequest(`Bedrock Converse does not support image media type ${e.mediaType}`);let o=kp[t];if(o){let s=yield*Ce.validateMedia("Bedrock Converse",e,new Set(Object.keys(kp)));return Cy(e,o,s.base64)}return yield*Ce.invalidRequest(`Bedrock Converse does not support media type ${e.mediaType}`)});var ls="bedrock-converse",fc=c.Struct({text:c.String}),My=c.Struct({toolUse:c.Struct({toolUseId:c.String,name:c.String,input:c.Unknown})}),_y=c.Union([c.Struct({text:c.String}),c.Struct({json:c.Unknown}),Nn.ImageBlock]),Oy=c.Struct({toolResult:c.Struct({toolUseId:c.String,content:c.Array(_y),status:c.optional(c.Literals(["success","error"]))})}),Ly=c.Struct({reasoningContent:c.Struct({reasoningText:c.optional(c.Struct({text:c.String,signature:c.optional(c.String)}))})}),Ny=c.Union([fc,Nn.ImageBlock,Nn.DocumentBlock,Oy,en.CachePointBlock]),jy=c.Union([fc,Ly,My,en.CachePointBlock]),Uy=c.Union([c.Struct({role:c.Literal("user"),content:c.Array(Ny)}),c.Struct({role:c.Literal("assistant"),content:c.Array(jy)})]).pipe(c.toTaggedUnion("role")),Fy=c.Union([fc,en.CachePointBlock]),By=c.Struct({toolSpec:c.Struct({name:c.String,description:c.String,inputSchema:c.Struct({json:es})})}),$y=c.Union([By,en.CachePointBlock]),qy=c.Union([c.Struct({auto:c.Struct({})}),c.Struct({any:c.Struct({})}),c.Struct({tool:c.Struct({name:c.String})})]),Wy={modelId:c.String,messages:c.Array(Uy),system:Gn(Fy),inferenceConfig:c.optional(c.Struct({maxTokens:c.optional(c.Number),temperature:c.optional(c.Number),topP:c.optional(c.Number),stopSequences:Gn(c.String)})),toolConfig:c.optional(c.Struct({tools:c.Array($y),toolChoice:c.optional(qy)})),additionalModelRequestFields:c.optional(es)},Vy=c.Struct(Wy),zy=c.Struct({inputTokens:c.optional(c.Number),outputTokens:c.optional(c.Number),totalTokens:c.optional(c.Number),cacheReadInputTokens:c.optional(c.Number),cacheWriteInputTokens:c.optional(c.Number)}),Gy=c.Struct({messageStart:c.optional(c.Struct({role:c.String})),contentBlockStart:c.optional(c.Struct({contentBlockIndex:c.Number,start:c.optional(c.Struct({toolUse:c.optional(c.Struct({toolUseId:c.String,name:c.String}))}))})),contentBlockDelta:c.optional(c.Struct({contentBlockIndex:c.Number,delta:c.optional(c.Struct({text:c.optional(c.String),toolUse:c.optional(c.Struct({input:c.String})),reasoningContent:c.optional(c.Struct({text:c.optional(c.String),signature:c.optional(c.String)}))}))})),contentBlockStop:c.optional(c.Struct({contentBlockIndex:c.Number})),messageStop:c.optional(c.Struct({stopReason:c.String,additionalModelResponseFields:c.optional(c.Unknown)})),metadata:c.optional(c.Struct({usage:c.optional(zy),metrics:c.optional(c.Unknown)})),internalServerException:c.optional(c.Struct({message:c.String})),modelStreamErrorException:c.optional(c.Struct({message:c.String})),validationException:c.optional(c.Struct({message:c.String})),throttlingException:c.optional(c.Struct({message:c.String})),serviceUnavailableException:c.optional(c.Struct({message:c.String}))}),Hy=i((e,t)=>({toolSpec:{name:e.name,description:e.description,inputSchema:{json:t}}}),"lowerToolSpec"),Yy=i((e,t,n)=>{let o=[];for(let s of n){o.push(Hy(s,si.modelCompatibility(s.inputSchema,e)));let a=en.block(t,s.cache);a&&o.push(a)}return o},"lowerTools"),Ti=i((e,t,n)=>{let o=en.block(e,n);return o?[{text:t},o]:[{text:t}]},"textWithCache"),Jy=i(e=>Ce.matchToolChoice("Bedrock Converse",e,{auto:i(()=>({auto:{}}),"auto"),none:i(()=>{},"none"),required:i(()=>({any:{}}),"required"),tool:i(t=>({tool:{name:t}}),"tool")}),"lowerToolChoice"),Ky=i(e=>({bedrock:e}),"bedrockMetadata"),Xy=i(e=>{let t=e.providerMetadata?.bedrock;return e.encrypted??(Ce.isRecord(t)&&typeof t.signature=="string"?t.signature:void 0)},"reasoningSignature"),Qy=i(e=>({toolUse:{toolUseId:e.id,name:e.name,input:e.input}}),"lowerToolCall"),Zy=r.fn("BedrockConverse.lowerToolResultContent")(function*(e){if(e.result.type==="text"||e.result.type==="error")return[{text:Ce.toolResultText(e)}];if(e.result.type==="json")return[{json:e.result.value}];let t=[];for(let n of e.result.value){if(n.type==="text"){t.push({text:n.text});continue}let o=yield*Nn.lower({type:"media",mediaType:n.mime,data:n.uri,filename:n.name});if(!("image"in o))return yield*Ce.invalidRequest("Bedrock Converse only supports image media in tool results");t.push(o)}return t}),eb=r.fn("BedrockConverse.lowerToolResult")(function*(e){return{toolResult:{toolUseId:e.id,content:yield*Zy(e),status:e.result.type==="error"?"error":"success"}}}),tb=r.fn("BedrockConverse.lowerMessages")(function*(e,t){let n=[];for(let o of e.messages){if(o.role==="system"){let a=yield*Ce.wrappedSystemUpdate("Bedrock Converse",o),l=Ti(t,a.text,a.cache),d=n.at(-1);d?.role==="user"?n[n.length-1]={role:"user",content:[...d.content,...l]}:n.push({role:"user",content:l});continue}if(o.role==="user"){let a=[];for(let l of o.content){if(!Ce.supportsContent(l,["text","media"]))return yield*Ce.unsupportedContent("Bedrock Converse","user",["text","media"]);if(l.type==="text"){a.push(...Ti(t,l.text,l.cache));continue}if(l.type==="media"){a.push(yield*Nn.lower(l));continue}}n.push({role:"user",content:a});continue}if(o.role==="assistant"){let a=[];for(let l of o.content){if(!Ce.supportsContent(l,["text","reasoning","tool-call"]))return yield*Ce.unsupportedContent("Bedrock Converse","assistant",["text","reasoning","tool-call"]);if(l.type==="text"){a.push(...Ti(t,l.text,l.cache));continue}if(l.type==="reasoning"){a.push({reasoningContent:{reasoningText:{text:l.text,signature:Xy(l)}}});continue}if(l.type==="tool-call"){a.push(Qy(l));continue}}n.push({role:"assistant",content:a});continue}let s=[];for(let a of o.content){if(!Ce.supportsContent(a,["tool-result"]))return yield*Ce.unsupportedContent("Bedrock Converse","tool",["tool-result"]);s.push(yield*eb(a));let l=en.block(t,a.cache);l&&s.push(l)}n.push({role:"user",content:s})}return n}),nb=i((e,t)=>t.flatMap(n=>Ti(e,n.text,n.cache)),"lowerSystem"),ob=r.fn("BedrockConverse.fromRequest")(function*(e){let t=e.toolChoice?yield*Jy(e.toolChoice):void 0,n=e.generation,o=en.breakpoints(),s=e.tools.length>0&&e.toolChoice?.type!=="none"?{tools:Yy(e.model.compatibility?.toolSchema,o,e.tools),toolChoice:t}:void 0,a=e.system.length===0?void 0:nb(o,e.system),l=yield*tb(e,o);return o.dropped>0&&(yield*r.logWarning(`Bedrock Converse: dropped ${o.dropped} cache breakpoint(s); the API allows at most ${en.BEDROCK_BREAKPOINT_CAP} per request.`)),{modelId:e.model.id,messages:l,system:a,inferenceConfig:n?.maxTokens===void 0&&n?.temperature===void 0&&n?.topP===void 0&&(n?.stop===void 0||n.stop.length===0)?void 0:{maxTokens:n?.maxTokens,temperature:n?.temperature,topP:n?.topP,stopSequences:n?.stop},toolConfig:s,additionalModelRequestFields:n?.topK===void 0?void 0:{top_k:n.topK}}}),rb=i(e=>e==="end_turn"||e==="stop_sequence"?"stop":e==="max_tokens"?"length":e==="tool_use"?"tool-calls":e==="content_filtered"||e==="guardrail_intervened"?"content-filter":"unknown","mapFinishReason"),sb=i(e=>{if(!e)return;let t=(e.cacheReadInputTokens??0)+(e.cacheWriteInputTokens??0),n=Ce.subtractTokens(e.inputTokens,t);return new Mn({inputTokens:e.inputTokens,outputTokens:e.outputTokens,nonCachedInputTokens:n,cacheReadInputTokens:e.cacheReadInputTokens,cacheWriteInputTokens:e.cacheWriteInputTokens,totalTokens:Ce.totalTokens(e.inputTokens,e.outputTokens,e.totalTokens),providerMetadata:{bedrock:e}})},"mapUsage"),ib=i((e,t)=>r.gen(function*(){if(t.contentBlockStart?.start?.toolUse){let n=t.contentBlockStart.contentBlockIndex,o=[],s=xt.stepStart(e.lifecycle,o);return[{...e,lifecycle:s,tools:Xo.start(e.tools,n,{id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})},[...o,rt.toolInputStart({id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})]]}if(t.contentBlockDelta?.delta?.text){let n=[];return[{...e,lifecycle:xt.textDelta(e.lifecycle,n,`text-${t.contentBlockDelta.contentBlockIndex}`,t.contentBlockDelta.delta.text)},n]}if(t.contentBlockDelta?.delta?.reasoningContent){let n=t.contentBlockDelta.contentBlockIndex,o=t.contentBlockDelta.delta.reasoningContent,s=[];return[{...e,lifecycle:o.text?xt.reasoningDelta(e.lifecycle,s,`reasoning-${n}`,o.text):e.lifecycle,reasoningSignatures:o.signature?{...e.reasoningSignatures,[n]:o.signature}:e.reasoningSignatures},s]}if(t.contentBlockDelta?.delta?.toolUse){let n=t.contentBlockDelta.contentBlockIndex,o=Xo.appendExisting(ls,e.tools,n,t.contentBlockDelta.delta.toolUse.input,"Bedrock Converse tool delta is missing its tool call");if(Xo.isError(o))return yield*o;let s=[],a=o.events.length?xt.stepStart(e.lifecycle,s):e.lifecycle;return s.push(...o.events),[{...e,lifecycle:a,tools:o.tools},s]}if(t.contentBlockStop){let n=t.contentBlockStop.contentBlockIndex,o=yield*Xo.finish(ls,e.tools,n),s=[],a=o.events??[],l=a.length?xt.stepStart(e.lifecycle,s):xt.reasoningEnd(xt.textEnd(e.lifecycle,s,`text-${n}`),s,`reasoning-${n}`,e.reasoningSignatures[n]?Ky({signature:e.reasoningSignatures[n]}):void 0);return s.push(...a),[{...e,hasToolCalls:a.some(rt.is.toolCall)?!0:e.hasToolCalls,lifecycle:l,tools:o.tools,reasoningSignatures:Object.fromEntries(Object.entries(e.reasoningSignatures).filter(([d])=>d!==String(n)))},s]}if(t.messageStop)return[{...e,pendingFinish:{reason:rb(t.messageStop.stopReason),usage:e.pendingFinish?.usage}},[]];if(t.metadata){let n=sb(t.metadata.usage);return[{...e,pendingFinish:{reason:e.pendingFinish?.reason??"stop",usage:n}},[]]}if(t.internalServerException||t.modelStreamErrorException||t.serviceUnavailableException){let n=t.internalServerException?.message??t.modelStreamErrorException?.message??t.serviceUnavailableException?.message??"Bedrock Converse stream error";return[e,[rt.providerError({message:n,retryable:!0})]]}if(t.validationException||t.throttlingException){let n=t.validationException?.message??t.throttlingException?.message??"Bedrock Converse error";return[e,[rt.providerError({message:n,classification:t.validationException&&au(n)?"context-overflow":void 0,retryable:t.throttlingException!==void 0})]]}return[e,[]]}),"step"),ab=cs.framing(ls),cb=i(e=>e.pendingFinish?(()=>{let t=[];return xt.finish(e.lifecycle,t,{reason:e.pendingFinish.reason==="stop"&&e.hasToolCalls?"tool-calls":e.pendingFinish.reason,usage:e.pendingFinish.usage}),t})():[],"onHalt"),lb=fo.make({id:ls,body:{schema:Vy,from:ob},stream:{event:Gy,initial:i(()=>({tools:Xo.empty(),pendingFinish:void 0,hasToolCalls:!1,lifecycle:xt.initial(),reasoningSignatures:{}}),"initial"),step:ib,onHalt:cb}}),mc=Jo.make({id:ls,provider:"bedrock",protocol:lb,endpoint:Yo.path(({body:e})=>`/model/${encodeURIComponent(e.modelId)}/converse-stream`),auth:ar.auth,framing:ab}),Tp=ar.sigV4;var hc=lt.make("amazon-bedrock"),db=[mc],ub=i(e=>`https://bedrock-runtime.${e}.amazonaws.com`,"bedrockBaseURL"),pb=i(e=>{let{apiKey:t,credentials:n,region:o,baseURL:s,...a}=e,l=o??n?.region??"us-east-1";return mc.with({...a,provider:hc,endpoint:{baseURL:s??ub(l)},auth:t===void 0?Tp(n):gt.bearer(t)})},"configuredRoute"),gc=i((e={})=>{let t=pb(e);return{id:hc,model:i(n=>t.model({id:n}),"model"),configure:gc}},"configure"),Rp=gc(),fb=Rp.model;var Ri={};fe(Ri,{configure:()=>wc,id:()=>ds,provider:()=>Sb,routes:()=>wb});var mb=i(e=>Object.entries(e).filter(t=>t[1]!==void 0),"definedEntries"),Cp=i(e=>{let t=Object.fromEntries(mb({store:e?.store,promptCacheKey:e?.promptCacheKey,reasoningEffort:e?.reasoningEffort,reasoningSummary:e?.reasoningSummary,include:e?.include,textVerbosity:e?.textVerbosity,serviceTier:e?.serviceTier}));if(Object.keys(t).length!==0)return{openai:t}},"openAIProviderOptions"),hb=i((e,t={})=>{let n=e.toLowerCase();if(!(!n.includes("gpt-5")||n.includes("gpt-5-chat")||n.includes("gpt-5-pro")))return Cp({reasoningEffort:"medium",reasoningSummary:"auto",include:["reasoning.encrypted_content"],textVerbosity:t.textVerbosity===!0&&n.includes("gpt-5.")&&!n.includes("codex")&&!n.includes("-chat")?"low":void 0})},"gpt5DefaultOptions"),gb=i((e,t={})=>Ba(Cp({store:!1}),hb(e,t)),"openAIDefaultOptions"),Zn=i((e,t,n={})=>({...t,providerOptions:Ba(gb(e,n),t.providerOptions)}),"withOpenAIOptions");var ds=lt.make("azure"),Mp=gt.remove("authorization"),bb=i(e=>`https://${e.trim()}.openai.azure.com/openai/v1`,"resourceBaseURL"),_p=On.with({id:"azure-openai-responses",provider:ds,auth:Mp,endpoint:{query:{"api-version":"v1"}}}),Op=yo.with({id:"azure-openai-chat",provider:ds,auth:Mp,endpoint:{query:{"api-version":"v1"}}}),wb=[_p,Op],vb=i(e=>{let{apiKey:t,apiVersion:n,resourceName:o,useCompletionUrls:s,baseURL:a,queryParams:l,...d}=e;if("auth"in d){let{auth:p,...f}=d;return f}return d},"defaults"),xb=i(e=>"auth"in e&&e.auth?e.auth:gt.remove("authorization").andThen(gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("AZURE_OPENAI_API_KEY")).pipe(gt.header("api-key"))),"auth"),Ap=i((e,t)=>e.with({auth:xb(t),endpoint:{baseURL:t.baseURL??bb(t.resourceName),query:{...t.apiVersion?{"api-version":t.apiVersion}:{},...t.queryParams}}}),"configuredRoute"),wc=i(e=>{let t=Ap(_p,e),n=Ap(Op,e),o=vb(e),s=i(l=>t.with(Zn(l,o)).model({id:l}),"responses"),a=i(l=>n.with(Zn(l,o)).model({id:l}),"chat");return{id:ds,model:i(l=>e.useCompletionUrls===!0?a(l):s(l),"model"),responses:s,chat:a,configure:wc}},"configure"),Sb={id:ds,configure:wc};var Ib=lt.make("cloudflare-ai-gateway"),kb=lt.make("cloudflare-workers-ai");var oR=Jn.with({id:"cloudflare-ai-gateway",provider:Ib}),rR=Jn.with({id:"cloudflare-workers-ai",provider:kb});var Np=lt.make("github-copilot");var lR=yo.with({provider:Np}),dR=On.with({provider:Np});var Ci={};fe(Ci,{configure:()=>xc,id:()=>qp,model:()=>iw,provider:()=>Wp,routes:()=>ow});var jp="gemini",Up=new Set(Ce.MEDIA_MIMES),Tb="https://generativelanguage.googleapis.com/v1beta",Pb=c.Struct({text:c.String,thought:c.optional(c.Boolean),thoughtSignature:c.optional(c.String)}),Rb=c.Struct({inlineData:c.Struct({mimeType:c.String,data:c.String})}),Cb=c.Struct({functionCall:c.Struct({name:c.String,args:c.Unknown}),thoughtSignature:c.optional(c.String)}),Ab=c.Struct({functionResponse:c.Struct({name:c.String,response:c.Unknown})}),Mb=c.Union([Pb,Rb,Cb,Ab]),Fp=c.Struct({role:c.Literals(["user","model"]),parts:c.Array(Mb)}),_b=c.Struct({parts:c.Array(c.Struct({text:c.String}))}),Ob=c.Struct({name:c.String,description:c.String,parameters:c.optional(es)}),Lb=c.Struct({functionDeclarations:c.Array(Ob)}),Nb=c.Struct({functionCallingConfig:c.Struct({mode:c.Literals(["AUTO","NONE","ANY"]),allowedFunctionNames:Gn(c.String)})}),jb=c.Struct({thinkingBudget:c.optional(c.Number),includeThoughts:c.optional(c.Boolean)}),Ub=c.Struct({maxOutputTokens:c.optional(c.Number),temperature:c.optional(c.Number),topP:c.optional(c.Number),topK:c.optional(c.Number),stopSequences:Gn(c.String),thinkingConfig:c.optional(jb)}),Fb={contents:c.Array(Fp),systemInstruction:c.optional(_b),tools:Gn(Lb),toolConfig:c.optional(Nb),generationConfig:c.optional(Ub)},Bb=c.Struct(Fb),$b=c.Struct({cachedContentTokenCount:c.optional(c.Number),thoughtsTokenCount:c.optional(c.Number),promptTokenCount:c.optional(c.Number),candidatesTokenCount:c.optional(c.Number),totalTokenCount:c.optional(c.Number)}),qb=c.Struct({content:c.optional(Fp),finishReason:c.optional(c.String)}),Wb=c.Struct({candidates:Gn(qb),usageMetadata:c.optional($b)}),Vb=i((e,t)=>({name:e.name,description:e.description,parameters:Su.convert(t)}),"lowerTool"),zb=i(e=>Ce.matchToolChoice("Gemini",e,{auto:i(()=>({functionCallingConfig:{mode:"AUTO"}}),"auto"),none:i(()=>({functionCallingConfig:{mode:"NONE"}}),"none"),required:i(()=>({functionCallingConfig:{mode:"ANY"}}),"required"),tool:i(t=>({functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t]}}),"tool")}),"lowerToolConfig"),Gb=r.fn("Gemini.lowerUserPart")(function*(e){if(e.type==="text")return{text:e.text};let t=yield*Ce.validateMedia("Gemini",e,Up);return{inlineData:{mimeType:t.mime,data:t.base64}}}),us=i(e=>({google:e}),"googleMetadata"),Bp=i(e=>{let t=e?.google;return Ce.isRecord(t)&&typeof t.thoughtSignature=="string"?t.thoughtSignature:void 0},"thoughtSignature"),Hb=i(e=>({functionCall:{name:e.name,args:e.input},thoughtSignature:Bp(e.providerMetadata)}),"lowerToolCall"),Yb=r.fn("Gemini.lowerMessages")(function*(e){let t=[];for(let n of e.messages){if(n.role==="system"){let s=yield*Ce.wrappedSystemUpdate("Gemini",n),a=t.at(-1);a?.role==="user"?t[t.length-1]={role:"user",parts:[...a.parts,{text:s.text}]}:t.push({role:"user",parts:[{text:s.text}]});continue}if(n.role==="user"){let s=[];for(let a of n.content){if(!Ce.supportsContent(a,["text","media"]))return yield*Ce.unsupportedContent("Gemini","user",["text","media"]);s.push(yield*Gb(a))}t.push({role:"user",parts:s});continue}if(n.role==="assistant"){let s=[];for(let a of n.content){if(!Ce.supportsContent(a,["text","reasoning","tool-call"]))return yield*Ce.unsupportedContent("Gemini","assistant",["text","reasoning","tool-call"]);if(a.type==="text"){s.push({text:a.text});continue}if(a.type==="reasoning"){s.push({text:a.text,thought:!0,thoughtSignature:Bp(a.providerMetadata)});continue}if(a.type==="tool-call"){s.push(Hb(a));continue}}t.push({role:"model",parts:s});continue}let o=[];for(let s of n.content){if(!Ce.supportsContent(s,["tool-result"]))return yield*Ce.unsupportedContent("Gemini","tool",["tool-result"]);if(s.result.type!=="content"){o.push({functionResponse:{name:s.name,response:{name:s.name,content:Ce.toolResultText(s)}}});continue}let a=s.result.value,l=a.filter(d=>d.type==="text").map(d=>d.text);o.push({functionResponse:{name:s.name,response:{name:s.name,content:l.join(`
49
- `)}}});for(let d of a){if(d.type==="text")continue;let p=yield*Ce.validateToolFile("Gemini",d,Up);o.push({inlineData:{mimeType:p.mime,data:p.base64}})}}t.push({role:"user",parts:o})}return t}),Jb=i(e=>e.providerOptions?.gemini,"geminiOptions"),Kb=i(e=>{let t=Jb(e)?.thinkingConfig;if(!Ce.isRecord(t))return;let n={thinkingBudget:typeof t.thinkingBudget=="number"?t.thinkingBudget:void 0,includeThoughts:typeof t.includeThoughts=="boolean"?t.includeThoughts:void 0};return Object.values(n).some(o=>o!==void 0)?n:void 0},"thinkingConfig"),Xb=r.fn("Gemini.fromRequest")(function*(e){let t=e.tools.length>0&&e.toolChoice?.type!=="none",n=e.generation,o=e.model.compatibility?.toolSchema,s={maxOutputTokens:n?.maxTokens,temperature:n?.temperature,topP:n?.topP,topK:n?.topK,stopSequences:n?.stop,thinkingConfig:Kb(e)};return{contents:yield*Yb(e),systemInstruction:e.system.length===0?void 0:{parts:[{text:Ce.joinText(e.system)}]},tools:t?[{functionDeclarations:e.tools.map(a=>Vb(a,si.modelCompatibility(a.inputSchema,o)))}]:void 0,toolConfig:t&&e.toolChoice?yield*zb(e.toolChoice):void 0,generationConfig:Object.values(s).some(a=>a!==void 0)?s:void 0}}),Qb=i(e=>{if(!e)return;let t=e.cachedContentTokenCount,n=Ce.subtractTokens(e.promptTokenCount,t),o=e.candidatesTokenCount!==void 0?e.candidatesTokenCount+(e.thoughtsTokenCount??0):void 0;return new Mn({inputTokens:e.promptTokenCount,outputTokens:o,nonCachedInputTokens:n,cacheReadInputTokens:t,reasoningTokens:e.thoughtsTokenCount,totalTokens:Ce.totalTokens(e.promptTokenCount,o,e.totalTokenCount),providerMetadata:{google:e}})},"mapUsage"),Zb=i((e,t)=>e==="STOP"?t?"tool-calls":"stop":e==="MAX_TOKENS"?"length":e==="IMAGE_SAFETY"||e==="RECITATION"||e==="SAFETY"||e==="BLOCKLIST"||e==="PROHIBITED_CONTENT"||e==="SPII"?"content-filter":e==="MALFORMED_FUNCTION_CALL"?"error":"unknown","mapFinishReason"),ew=i(e=>e.finishReason||e.usage?(()=>{let t=[],n=e.reasoningSignature?xt.reasoningEnd(e.lifecycle,t,"reasoning-0",us({thoughtSignature:e.reasoningSignature})):e.lifecycle;return xt.finish(n,t,{reason:Zb(e.finishReason,e.hasToolCalls),usage:e.usage}),t})():[],"finish"),tw=i((e,t)=>{let n={...e,usage:t.usageMetadata?Qb(t.usageMetadata)??e.usage:e.usage},o=t.candidates?.[0];if(!o?.content)return r.succeed([{...n,finishReason:o?.finishReason??n.finishReason},[]]);let s=[],a=n.hasToolCalls,l=n.lifecycle,d=n.nextToolCallId,p=n.reasoningSignature;for(let f of o.content.parts){if("thoughtSignature"in f&&f.thoughtSignature&&"thought"in f&&f.thought&&(p=f.thoughtSignature),"text"in f&&f.text.length>0){if(f.thought){l=xt.reasoningDelta(l,s,"reasoning-0",f.text,f.thoughtSignature?us({thoughtSignature:f.thoughtSignature}):void 0);continue}l=xt.reasoningEnd(l,s,"reasoning-0",p?us({thoughtSignature:p}):void 0),l=xt.textDelta(l,s,"text-0",f.text);continue}if("functionCall"in f){let u=f.functionCall.args,g=`tool_${d++}`;l=xt.reasoningEnd(l,s,"reasoning-0",p?us({thoughtSignature:p}):void 0),l=xt.stepStart(l,s),s.push(rt.toolCall({id:g,name:f.functionCall.name,input:u,providerMetadata:f.thoughtSignature?us({thoughtSignature:f.thoughtSignature}):void 0})),a=!0}}return r.succeed([{...n,hasToolCalls:a,lifecycle:l,nextToolCallId:d,reasoningSignature:p,finishReason:o.finishReason??n.finishReason},s])},"step"),nw=fo.make({id:jp,body:{schema:Bb,from:Xb},stream:{event:fo.jsonEvent(Wb),initial:i(()=>({hasToolCalls:!1,nextToolCallId:0,lifecycle:xt.initial()}),"initial"),step:tw,onHalt:ew}}),vc=Jo.make({id:jp,provider:"google",protocol:nw,endpoint:Yo.path(({request:e})=>`/models/${e.model.id}:streamGenerateContent?alt=sse`,{baseURL:Tb}),auth:gt.none,framing:ti.sse});var qp=lt.make("google"),ow=[vc],rw=i(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("GOOGLE_GENERATIVE_AI_API_KEY")).pipe(gt.header("x-goog-api-key")),"auth"),sw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return vc.with({...s,endpoint:{baseURL:o},auth:rw(e)})},"configuredRoute"),xc=i((e={})=>{let t=sw(e);return{id:qp,model:i(n=>t.model({id:n}),"model"),configure:xc}},"configure"),Wp=xc(),iw=Wp.model;var Ai={};fe(Ai,{chat:()=>fw,configure:()=>Ic,id:()=>Vp,model:()=>dw,provider:()=>ps,responses:()=>uw,responsesWebSocket:()=>pw,routes:()=>aw});var Vp=lt.make("openai"),aw=[On,za,yo],cw=i(e=>Sn.bearer(e,"OPENAI_API_KEY"),"auth"),lw=i(e=>{let{apiKey:t,auth:n,baseURL:o,queryParams:s,...a}=e;return a},"defaults"),Sc=i((e,t)=>e.with({auth:cw(t),endpoint:{baseURL:t.baseURL,query:t.queryParams}}),"configuredRoute"),Ic=i((e={})=>{let t=Sc(On,e),n=Sc(za,e),o=Sc(yo,e),s=lw(e),a=i(p=>t.with(Zn(p,s,{textVerbosity:!0})).model({id:p}),"responses");return{id:Vp,model:a,responses:a,responsesWebSocket:i(p=>n.with(Zn(p,s,{textVerbosity:!0})).model({id:p}),"responsesWebSocket"),chat:i(p=>o.with(Zn(p,s)).model({id:p}),"chat"),configure:Ic}},"configure"),ps=Ic(),dw=ps.model,uw=ps.responses,pw=ps.responsesWebSocket,fw=ps.chat;var _i={};fe(_i,{baseten:()=>gw,cerebras:()=>yw,configure:()=>Mi,deepinfra:()=>bw,deepseek:()=>ww,fireworks:()=>vw,groq:()=>xw,id:()=>Gp,provider:()=>hw,routes:()=>mw,togetherai:()=>Sw});var Gt={baseten:{provider:"baseten",baseURL:"https://inference.baseten.co/v1"},cerebras:{provider:"cerebras",baseURL:"https://api.cerebras.ai/v1"},deepinfra:{provider:"deepinfra",baseURL:"https://api.deepinfra.com/v1/openai"},deepseek:{provider:"deepseek",baseURL:"https://api.deepseek.com/v1"},fireworks:{provider:"fireworks",baseURL:"https://api.fireworks.ai/inference/v1"},groq:{provider:"groq",baseURL:"https://api.groq.com/openai/v1"},openrouter:{provider:"openrouter",baseURL:"https://openrouter.ai/api/v1"},togetherai:{provider:"togetherai",baseURL:"https://api.together.xyz/v1"},xai:{provider:"xai",baseURL:"https://api.x.ai/v1"}},AR=Object.fromEntries(Object.values(Gt).map(e=>[e.provider,e]));var Gp=lt.make("openai-compatible"),mw=[Jn],Mi=i(e=>{let t=e.provider??"openai-compatible",{provider:n,baseURL:o,apiKey:s,auth:a,...l}=e,d=Jn.with({...l,provider:t,endpoint:{baseURL:o},auth:Sn.bearer(e,[])});return{id:lt.make(t),model:i(p=>d.model({id:p,provider:lt.make(t)}),"model"),configure:Mi}},"configure"),Io=i(e=>{let t=i((n={})=>{let o=Mi({...n,baseURL:n.baseURL??e.baseURL,provider:e.provider});return{id:lt.make(e.provider),model:o.model,configure:t}},"configureProfile");return t()},"define"),hw={id:Gp,configure:Mi},gw=Io(Gt.baseten),yw=Io(Gt.cerebras),bw=Io(Gt.deepinfra),ww=Io(Gt.deepseek),vw=Io(Gt.fireworks),xw=Io(Gt.groq),Sw=Io(Gt.togetherai);var Oi={};fe(Oi,{configure:()=>Dc,id:()=>Hp,model:()=>Pw,profile:()=>fs,protocol:()=>Yp,provider:()=>Jp,route:()=>kc,routes:()=>Ew});var fs=Gt.openrouter,Hp=lt.make(fs.provider),Iw="openrouter",kw=c.StructWithRest(c.Struct(Iu),[c.Record(c.String,c.Any)]),Yp=fo.make({id:"openrouter-chat",body:{schema:kw,from:i(e=>Va.body.from(e).pipe(r.map(t=>({...t,...Dw(e.providerOptions?.openrouter)}))),"from")},stream:Va.stream}),Dw=i(e=>{let t=ei(e)?e:{};return{...t.usage===!0?{usage:{include:!0}}:ei(t.usage)?{usage:t.usage}:{},...ei(t.reasoning)?{reasoning:t.reasoning}:{},...typeof t.promptCacheKey=="string"?{prompt_cache_key:t.promptCacheKey}:{}}},"bodyOptions"),kc=Jo.make({id:Iw,provider:fs.provider,protocol:Yp,endpoint:Yo.path("/chat/completions",{baseURL:fs.baseURL}),framing:ti.sse}),Ew=[kc],Tw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return kc.with({...s,endpoint:{baseURL:o??fs.baseURL},auth:Sn.bearer(e,"OPENROUTER_API_KEY")})},"configuredRoute"),Dc=i((e={})=>{let t=Tw(e);return{id:Hp,model:i(n=>t.model({id:n}),"model"),configure:Dc}},"configure"),Jp=Dc(),Pw=Jp.model;var Ec=lt.make("xai");var Kp=i(e=>Sn.bearer(e,"XAI_API_KEY"),"auth"),Rw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return On.with({...s,provider:Ec,endpoint:{baseURL:o??Gt.xai.baseURL},auth:Kp(e)})},"configuredResponsesRoute"),Cw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return Jn.with({...s,provider:Ec,endpoint:{baseURL:o??Gt.xai.baseURL},auth:Kp(e)})},"configuredChatRoute"),Xp=i((e={})=>{let t=Rw(e),n=Cw(e),o=i(a=>t.model({id:a}),"responses");return{id:Ec,model:o,responses:o,chat:i(a=>n.model({id:a}),"chat"),configure:Xp}},"configure"),Tc=Xp(),HR=Tc.model,YR=Tc.responses,JR=Tc.chat;var Qp=i(e=>{if(!ut(e))return;let t=Object.fromEntries(Object.entries(e).filter(n=>ut(n[1])));return Object.keys(t).length===0?void 0:t},"providerMetadata"),Li=i(e=>Qp(e.providerMetadata)??Qp(e.providerOptions),"partProviderMetadata"),Mw=i(e=>({type:"text",text:typeof e.text=="string"?e.text:"",providerMetadata:Li(e)}),"textPart"),_w=i(e=>{if(typeof e.data!="string"&&!(e.data instanceof Uint8Array))throw new Error("Native LLM request adapter only supports file parts with string or Uint8Array data");return{type:"media",mediaType:typeof e.mediaType=="string"?e.mediaType:"application/octet-stream",data:e.data,filename:typeof e.filename=="string"?e.filename:void 0}},"mediaPart"),Ow=i(e=>{let t=ut(e.output)?e.output:{type:"json",value:e.output},n=t.type==="text"?"text":t.type==="error-text"?"error":"json";return nu.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",result:"value"in t?t.value:t,resultType:n,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:Li(e)})},"toolResult"),Lw=i(e=>{if(!ut(e))throw new Error("Native LLM request adapter only supports object content parts");if(e.type==="text")return Mw(e);if(e.type==="file")return _w(e);if(e.type==="reasoning")return{type:"reasoning",text:typeof e.text=="string"?e.text:"",providerMetadata:Li(e)};if(e.type==="tool-call")return tu.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",input:e.input,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:Li(e)});if(e.type==="tool-result")return Ow(e);throw new Error(`Native LLM request adapter does not support ${String(e.type)} content parts`)},"contentPart"),Nw=i(e=>typeof e=="string"?[{type:"text",text:e}]:e.map(Lw),"content"),jw=i(e=>{let t=e.flatMap(o=>o.role==="system"?[$a.make(o.content)]:[]),n=e.flatMap(o=>o.role==="system"?[]:[ou.make({role:o.role,content:Nw(o.content),native:ut(o.providerOptions)?{providerOptions:o.providerOptions}:void 0})]);return{system:t,messages:n}},"messages"),Uw=i(e=>ut(e)?ut(e.jsonSchema)?e.jsonSchema:e:{type:"object",properties:{}},"schema"),Fw=i(e=>Object.entries(e??{}).map(([t,n])=>ru.make({name:t,description:n.description??"",inputSchema:Uw(n.inputSchema)})),"tools"),Bw=i(e=>{let t={temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxOutputTokens};return Object.values(t).some(n=>n!==void 0)?t:void 0},"generation"),$w=i(e=>"model"in e?e.baseURL??(e.model.api.url||void 0):e.api.url||void 0,"baseURL"),Zp=i((e,t)=>{if(t)return t;throw new Error(`Native LLM request adapter requires a base URL for ${e.providerID}/${e.id}`)},"requireBaseURL"),ef=i((e,t)=>{let n="model"in e?e.model:e,o=$w(e),s={..."model"in e&&e.apiKey?{apiKey:e.apiKey}:{},...o?{baseURL:o}:{},headers:Object.keys({...n.headers,...t}).length===0?void 0:{...n.headers,...t},limits:{context:n.limit.context,output:n.limit.output}};if(n.api.npm==="@ai-sdk/openai")return Ai.configure(s).responses(n.api.id);if(n.api.npm==="@ai-sdk/azure")return Ri.configure({...s,baseURL:Zp(n,o)}).responses(n.api.id);if(n.api.npm==="@ai-sdk/anthropic")return Ei.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/google")return Ci.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/amazon-bedrock")return Pi.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/openai-compatible")return _i.configure({...s,provider:String(n.providerID),baseURL:Zp(n,o)}).model(n.api.id);if(n.api.npm==="@openrouter/ai-sdk-provider")return Oi.configure(s).model(n.api.id);throw new Error(`Native LLM request adapter does not support provider package ${n.api.npm}`)},"model"),qw=i(e=>{let t=jw(e.messages);return wu.request({model:ef(e,e.headers),system:[...(e.system??[]).map($a.make),...t.system],messages:t.messages,tools:Fw(e.tools),toolChoice:e.toolChoice,generation:Bw(e),providerOptions:e.providerOptions})},"request");function Ww(e){return tf(e,nf(e))}i(Ww,"status");function tf(e,t){let n=e.model.providerID;if(n!=="openai"&&n!=="anthropic"&&!n.startsWith("opencode"))return{type:"unsupported",reason:"provider is not openai, opencode, or anthropic"};let o=e.model.api.npm;if(o!=="@ai-sdk/openai"&&o!=="@ai-sdk/openai-compatible"&&o!=="@ai-sdk/anthropic")return{type:"unsupported",reason:"provider package is not OpenAI, OpenAI-compatible, or Anthropic"};if(e.auth?.type==="oauth"&&!(e.provider.id==="openai"&&t))return{type:"unsupported",reason:"OAuth auth requires a provider fetch override"};let s=typeof e.provider.options.apiKey=="string"?e.provider.options.apiKey:e.provider.key;return s?{type:"supported",apiKey:s,baseURL:typeof e.provider.options.baseURL=="string"?e.provider.options.baseURL:void 0}:{type:"unsupported",reason:"API key is not configured"}}i(tf,"statusWithFetch");function Vw(e){let t=nf(e),n=tf(e,t);if(n.type==="unsupported")return n;let o=of(e.tools,e),s=ms.request({model:e.model,apiKey:n.apiKey,baseURL:n.baseURL,messages:Xe.message(e.messages,e.model,e.providerOptions??{}),toolChoice:e.toolChoice,temperature:e.temperature,topP:e.topP,topK:e.topK,maxOutputTokens:e.maxOutputTokens,providerOptions:Xe.providerOptions(e.model,e.providerOptions??{}),headers:{...zw(e.provider.options.headers),...e.headers}}),a=Gs(zs(r.gen(function*(){let l=yield*Ks.make(),d=yield*Yr.unbounded();return e.llmClient.stream(su.update(s,{tools:[...s.tools,...gu(o)]})).pipe(Hs(f=>f.type!=="tool-call"||f.providerExecuted?La(f):La(f).pipe(Ys(Oa(bu.dispatch(o,f).pipe(r.flatMap(u=>Yr.offerAll(d,u.events)),r.catchCause(u=>Yr.failCause(d,u)),r.asVoid,Ks.run(l,{startImmediately:!0})))))),Ys(Oa(Ks.awaitEmpty(l).pipe(r.andThen(Yr.end(d)),r.asVoid)))).pipe(Ys(_d(d)))})));return{...n,stream:t?a.pipe($d(zd.Fetch,t)):a}}i(Vw,"stream");function nf(e){if(e.provider.id!=="openai"||e.auth?.type!=="oauth")return;let t=e.provider.options.fetch;if(typeof t=="function")return t}i(nf,"providerFetch");function zw(e){if(ut(e))return Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}i(zw,"providerHeaders");function Gw(e){return!e||typeof e!="object"?{type:"object",properties:{}}:"jsonSchema"in e&&e.jsonSchema&&typeof e.jsonSchema=="object"?e.jsonSchema:fi(e).jsonSchema}i(Gw,"nativeSchema");function of(e,t){return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,yu.make({description:o.description??"",jsonSchema:Gw(o.inputSchema),execute:i((s,a)=>r.tryPromise({try:i(()=>{if(!o.execute)throw new Error(`Tool has no execute handler: ${n}`);return o.execute(s,{toolCallId:a?.id??n,messages:t.messages,abortSignal:t.abort})},"try"),catch:i(l=>new iu({message:gn(l),error:l}),"catch")}),"execute")})]))}i(of,"nativeTools");var lr={};fe(lr,{LLMRequestPrep:()=>lr,hasToolCalls:()=>yf,prepare:()=>Xw});var eo={};fe(eo,{Service:()=>cr,SystemPrompt:()=>eo,node:()=>Kw,provider:()=>Hw});var rf=`You are OpenCode, the best coding agent on the planet.
48
+ `)),O){let Z=v.error?` Request failed: ${v.error.message} (${v.error.code}).`:"";P.log(`Received response '${O.method} - (${v.id})' in ${Date.now()-O.timerStart}ms.${Z}`,F)}else P.log(`Received response ${v.id} without active response promise.`,F)}else oe("receive-response",v)}i(te,"traceReceivedResponse");function oe(v,O){if(!P||w===ze.Off)return;let F={isLSPMessage:!0,type:v,message:O,timestamp:Date.now()};P.log(F)}i(oe,"logLSPMessage");function ae(){if(W())throw new Er(Ss.Closed,"Connection is closed.");if(U())throw new Er(Ss.Disposed,"Connection is disposed.")}i(ae,"throwIfClosedOrDisposed");function Q(){if(N())throw new Er(Ss.AlreadyListening,"Connection is already listening")}i(Q,"throwIfListening");function je(){if(!N())throw new Error("Call listen() first.")}i(je,"throwIfNotListening");function Je(v){return v===void 0?null:v}i(Je,"undefinedToNull");function Ne(v){if(v!==null)return v}i(Ne,"nullToUndefined");function He(v){return v!=null&&!Array.isArray(v)&&typeof v=="object"}i(He,"isNamedParam");function xe(v,O){switch(v){case Ie.ParameterStructures.auto:return He(O)?Ne(O):[Je(O)];case Ie.ParameterStructures.byName:if(!He(O))throw new Error("Received parameters by name but param is not an object literal.");return Ne(O);case Ie.ParameterStructures.byPosition:return[Je(O)];default:throw new Error(`Unknown parameter structure ${v.toString()}`)}}i(xe,"computeSingleParam");function We(v,O){let F,Z=v.numberOfParams;switch(Z){case 0:F=void 0;break;case 1:F=xe(v.parameterStructures,O[0]);break;default:F=[];for(let _e=0;_e<O.length&&_e<Z;_e++)F.push(Je(O[_e]));if(O.length<Z)for(let _e=O.length;_e<Z;_e++)F.push(null);break}return F}i(We,"computeMessageParams");let J={sendNotification:i((v,...O)=>{ae();let F,Z;if(mt.string(v)){F=v;let le=O[0],ue=0,K=Ie.ParameterStructures.auto;Ie.ParameterStructures.is(le)&&(ue=1,K=le);let X=O.length,he=X-ue;switch(he){case 0:Z=void 0;break;case 1:Z=xe(K,O[ue]);break;default:if(K===Ie.ParameterStructures.byName)throw new Error(`Received ${he} parameters for 'by Name' notification parameter structure.`);Z=O.slice(ue,X).map(ge=>Je(ge));break}}else{let le=O;F=v.method,Z=We(v,le)}let _e={jsonrpc:p,method:F,params:Z};return E(_e),t.write(_e).catch(le=>{throw s.error("Sending notification failed."),le})},"sendNotification"),onNotification:i((v,O)=>{ae();let F;return mt.func(v)?g=v:O&&(mt.string(v)?(F=v,y.set(v,{type:void 0,handler:O})):(F=v.method,y.set(v.method,{type:v,handler:O}))),{dispose:i(()=>{F!==void 0?y.delete(F):g=void 0},"dispose")}},"onNotification"),onProgress:i((v,O,F)=>{if(b.has(O))throw new Error(`Progress handler for token ${O} already registered`);return b.set(O,F),{dispose:i(()=>{b.delete(O)},"dispose")}},"onProgress"),sendProgress:i((v,O,F)=>J.sendNotification(xs.type,{token:O,value:F}),"sendProgress"),onUnhandledProgress:j.event,sendRequest:i((v,...O)=>{ae(),je();let F,Z,_e;if(mt.string(v)){F=v;let X=O[0],he=O[O.length-1],ge=0,Pe=Ie.ParameterStructures.auto;Ie.ParameterStructures.is(X)&&(ge=1,Pe=X);let Ye=O.length;kl.CancellationToken.is(he)&&(Ye=Ye-1,_e=he);let wt=Ye-ge;switch(wt){case 0:Z=void 0;break;case 1:Z=xe(Pe,O[ge]);break;default:if(Pe===Ie.ParameterStructures.byName)throw new Error(`Received ${wt} parameters for 'by Name' request parameter structure.`);Z=O.slice(ge,Ye).map(zo=>Je(zo));break}}else{let X=O;F=v.method,Z=We(v,X);let he=v.numberOfParams;_e=kl.CancellationToken.is(X[he])?X[he]:void 0}let le=a++,ue;_e&&(ue=_e.onCancellationRequested(()=>{let X=ie.sender.sendCancellation(J,le);return X===void 0?(s.log(`Received no promise from cancellation strategy when cancelling id ${le}`),Promise.resolve()):X.catch(()=>{s.log(`Sending cancellation messages for id ${le} failed`)})}));let K={jsonrpc:p,id:le,method:F,params:Z};return Pn(K),typeof ie.sender.enableCancellation=="function"&&ie.sender.enableCancellation(K),new Promise(async(X,he)=>{let ge=i(wt=>{X(wt),ie.sender.cleanup(le),ue?.dispose()},"resolveWithCleanup"),Pe=i(wt=>{he(wt),ie.sender.cleanup(le),ue?.dispose()},"rejectWithCleanup"),Ye={method:F,timerStart:Date.now(),resolve:ge,reject:Pe};try{m.set(le,Ye),await t.write(K)}catch(wt){throw m.delete(le),Ye.reject(new Ie.ResponseError(Ie.ErrorCodes.MessageWriteError,wt.message?wt.message:"Unknown reason")),s.error("Sending request failed."),wt}})},"sendRequest"),onRequest:i((v,O)=>{ae();let F=null;return Tl.is(v)?(F=void 0,f=v):mt.string(v)?(F=null,O!==void 0&&(F=v,u.set(v,{handler:O,type:void 0}))):O!==void 0&&(F=v.method,u.set(v.method,{type:v,handler:O})),{dispose:i(()=>{F!==null&&(F!==void 0?u.delete(F):f=void 0)},"dispose")}},"onRequest"),hasPendingResponse:i(()=>m.size>0,"hasPendingResponse"),trace:i(async(v,O,F)=>{let Z=!1,_e=tn.Text;F!==void 0&&(mt.boolean(F)?Z=F:(Z=F.sendNotification||!1,_e=F.traceFormat||tn.Text)),w=v,I=_e,w===ze.Off?P=void 0:P=O,Z&&!W()&&!U()&&await J.sendNotification(Pl.type,{value:ze.toString(v)})},"trace"),onError:A.event,onClose:C.event,onUnhandledNotification:$.event,onDispose:z.event,end:i(()=>{t.end()},"end"),dispose:i(()=>{if(U())return;x=wn.Disposed,z.fire(void 0);let v=new Ie.ResponseError(Ie.ErrorCodes.PendingResponseRejected,"Pending response rejected since connection got disposed");for(let O of m.values())O.reject(v);m=new Map,k=new Map,h=new Set,T=new sm.LinkedMap,mt.func(t.dispose)&&t.dispose(),mt.func(e.dispose)&&e.dispose()},"dispose"),listen:i(()=>{ae(),Q(),x=wn.Listening,e.listen(H)},"listen"),inspect:i(()=>{(0,rm.default)().console.log("inspect")},"inspect")};return J.onNotification(Qi.type,v=>{if(w===ze.Off||!P)return;let O=w===ze.Verbose||w===ze.Compact;P.log(v.message,O?v.verbose:void 0)}),J.onNotification(xs.type,v=>{let O=b.get(v.token);O?O(v.value):j.fire(v)}),J}i(yx,"createMessageConnection");Me.createMessageConnection=yx});var ra=kt(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.ProgressType=B.ProgressToken=B.createMessageConnection=B.NullLogger=B.ConnectionOptions=B.ConnectionStrategy=B.AbstractMessageBuffer=B.WriteableStreamMessageWriter=B.AbstractMessageWriter=B.MessageWriter=B.ReadableStreamMessageReader=B.AbstractMessageReader=B.MessageReader=B.SharedArrayReceiverStrategy=B.SharedArraySenderStrategy=B.CancellationToken=B.CancellationTokenSource=B.Emitter=B.Event=B.Disposable=B.LRUCache=B.Touch=B.LinkedMap=B.ParameterStructures=B.NotificationType9=B.NotificationType8=B.NotificationType7=B.NotificationType6=B.NotificationType5=B.NotificationType4=B.NotificationType3=B.NotificationType2=B.NotificationType1=B.NotificationType0=B.NotificationType=B.ErrorCodes=B.ResponseError=B.RequestType9=B.RequestType8=B.RequestType7=B.RequestType6=B.RequestType5=B.RequestType4=B.RequestType3=B.RequestType2=B.RequestType1=B.RequestType0=B.RequestType=B.Message=B.RAL=void 0;B.MessageStrategy=B.CancellationStrategy=B.CancellationSenderStrategy=B.CancellationReceiverStrategy=B.ConnectionError=B.ConnectionErrors=B.LogTraceNotification=B.SetTraceNotification=B.TraceFormat=B.TraceValues=B.Trace=void 0;var nt=nl();Object.defineProperty(B,"Message",{enumerable:!0,get:i(function(){return nt.Message},"get")});Object.defineProperty(B,"RequestType",{enumerable:!0,get:i(function(){return nt.RequestType},"get")});Object.defineProperty(B,"RequestType0",{enumerable:!0,get:i(function(){return nt.RequestType0},"get")});Object.defineProperty(B,"RequestType1",{enumerable:!0,get:i(function(){return nt.RequestType1},"get")});Object.defineProperty(B,"RequestType2",{enumerable:!0,get:i(function(){return nt.RequestType2},"get")});Object.defineProperty(B,"RequestType3",{enumerable:!0,get:i(function(){return nt.RequestType3},"get")});Object.defineProperty(B,"RequestType4",{enumerable:!0,get:i(function(){return nt.RequestType4},"get")});Object.defineProperty(B,"RequestType5",{enumerable:!0,get:i(function(){return nt.RequestType5},"get")});Object.defineProperty(B,"RequestType6",{enumerable:!0,get:i(function(){return nt.RequestType6},"get")});Object.defineProperty(B,"RequestType7",{enumerable:!0,get:i(function(){return nt.RequestType7},"get")});Object.defineProperty(B,"RequestType8",{enumerable:!0,get:i(function(){return nt.RequestType8},"get")});Object.defineProperty(B,"RequestType9",{enumerable:!0,get:i(function(){return nt.RequestType9},"get")});Object.defineProperty(B,"ResponseError",{enumerable:!0,get:i(function(){return nt.ResponseError},"get")});Object.defineProperty(B,"ErrorCodes",{enumerable:!0,get:i(function(){return nt.ErrorCodes},"get")});Object.defineProperty(B,"NotificationType",{enumerable:!0,get:i(function(){return nt.NotificationType},"get")});Object.defineProperty(B,"NotificationType0",{enumerable:!0,get:i(function(){return nt.NotificationType0},"get")});Object.defineProperty(B,"NotificationType1",{enumerable:!0,get:i(function(){return nt.NotificationType1},"get")});Object.defineProperty(B,"NotificationType2",{enumerable:!0,get:i(function(){return nt.NotificationType2},"get")});Object.defineProperty(B,"NotificationType3",{enumerable:!0,get:i(function(){return nt.NotificationType3},"get")});Object.defineProperty(B,"NotificationType4",{enumerable:!0,get:i(function(){return nt.NotificationType4},"get")});Object.defineProperty(B,"NotificationType5",{enumerable:!0,get:i(function(){return nt.NotificationType5},"get")});Object.defineProperty(B,"NotificationType6",{enumerable:!0,get:i(function(){return nt.NotificationType6},"get")});Object.defineProperty(B,"NotificationType7",{enumerable:!0,get:i(function(){return nt.NotificationType7},"get")});Object.defineProperty(B,"NotificationType8",{enumerable:!0,get:i(function(){return nt.NotificationType8},"get")});Object.defineProperty(B,"NotificationType9",{enumerable:!0,get:i(function(){return nt.NotificationType9},"get")});Object.defineProperty(B,"ParameterStructures",{enumerable:!0,get:i(function(){return nt.ParameterStructures},"get")});var Al=rl();Object.defineProperty(B,"LinkedMap",{enumerable:!0,get:i(function(){return Al.LinkedMap},"get")});Object.defineProperty(B,"LRUCache",{enumerable:!0,get:i(function(){return Al.LRUCache},"get")});Object.defineProperty(B,"Touch",{enumerable:!0,get:i(function(){return Al.Touch},"get")});var bx=Hf();Object.defineProperty(B,"Disposable",{enumerable:!0,get:i(function(){return bx.Disposable},"get")});var lm=Sr();Object.defineProperty(B,"Event",{enumerable:!0,get:i(function(){return lm.Event},"get")});Object.defineProperty(B,"Emitter",{enumerable:!0,get:i(function(){return lm.Emitter},"get")});var dm=Hi();Object.defineProperty(B,"CancellationTokenSource",{enumerable:!0,get:i(function(){return dm.CancellationTokenSource},"get")});Object.defineProperty(B,"CancellationToken",{enumerable:!0,get:i(function(){return dm.CancellationToken},"get")});var um=Jf();Object.defineProperty(B,"SharedArraySenderStrategy",{enumerable:!0,get:i(function(){return um.SharedArraySenderStrategy},"get")});Object.defineProperty(B,"SharedArrayReceiverStrategy",{enumerable:!0,get:i(function(){return um.SharedArrayReceiverStrategy},"get")});var Ml=Xf();Object.defineProperty(B,"MessageReader",{enumerable:!0,get:i(function(){return Ml.MessageReader},"get")});Object.defineProperty(B,"AbstractMessageReader",{enumerable:!0,get:i(function(){return Ml.AbstractMessageReader},"get")});Object.defineProperty(B,"ReadableStreamMessageReader",{enumerable:!0,get:i(function(){return Ml.ReadableStreamMessageReader},"get")});var _l=nm();Object.defineProperty(B,"MessageWriter",{enumerable:!0,get:i(function(){return _l.MessageWriter},"get")});Object.defineProperty(B,"AbstractMessageWriter",{enumerable:!0,get:i(function(){return _l.AbstractMessageWriter},"get")});Object.defineProperty(B,"WriteableStreamMessageWriter",{enumerable:!0,get:i(function(){return _l.WriteableStreamMessageWriter},"get")});var wx=om();Object.defineProperty(B,"AbstractMessageBuffer",{enumerable:!0,get:i(function(){return wx.AbstractMessageBuffer},"get")});var At=cm();Object.defineProperty(B,"ConnectionStrategy",{enumerable:!0,get:i(function(){return At.ConnectionStrategy},"get")});Object.defineProperty(B,"ConnectionOptions",{enumerable:!0,get:i(function(){return At.ConnectionOptions},"get")});Object.defineProperty(B,"NullLogger",{enumerable:!0,get:i(function(){return At.NullLogger},"get")});Object.defineProperty(B,"createMessageConnection",{enumerable:!0,get:i(function(){return At.createMessageConnection},"get")});Object.defineProperty(B,"ProgressToken",{enumerable:!0,get:i(function(){return At.ProgressToken},"get")});Object.defineProperty(B,"ProgressType",{enumerable:!0,get:i(function(){return At.ProgressType},"get")});Object.defineProperty(B,"Trace",{enumerable:!0,get:i(function(){return At.Trace},"get")});Object.defineProperty(B,"TraceValues",{enumerable:!0,get:i(function(){return At.TraceValues},"get")});Object.defineProperty(B,"TraceFormat",{enumerable:!0,get:i(function(){return At.TraceFormat},"get")});Object.defineProperty(B,"SetTraceNotification",{enumerable:!0,get:i(function(){return At.SetTraceNotification},"get")});Object.defineProperty(B,"LogTraceNotification",{enumerable:!0,get:i(function(){return At.LogTraceNotification},"get")});Object.defineProperty(B,"ConnectionErrors",{enumerable:!0,get:i(function(){return At.ConnectionErrors},"get")});Object.defineProperty(B,"ConnectionError",{enumerable:!0,get:i(function(){return At.ConnectionError},"get")});Object.defineProperty(B,"CancellationReceiverStrategy",{enumerable:!0,get:i(function(){return At.CancellationReceiverStrategy},"get")});Object.defineProperty(B,"CancellationSenderStrategy",{enumerable:!0,get:i(function(){return At.CancellationSenderStrategy},"get")});Object.defineProperty(B,"CancellationStrategy",{enumerable:!0,get:i(function(){return At.CancellationStrategy},"get")});Object.defineProperty(B,"MessageStrategy",{enumerable:!0,get:i(function(){return At.MessageStrategy},"get")});var vx=no();B.RAL=vx.default});var mm=kt(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var pm=Hr("util"),Un=ra(),sa=class e extends Un.AbstractMessageBuffer{static{i(this,"MessageBuffer")}constructor(t="utf-8"){super(t)}emptyBuffer(){return e.emptyBuffer}fromString(t,n){return Buffer.from(t,n)}toString(t,n){return t instanceof Buffer?t.toString(n):new pm.TextDecoder(n).decode(t)}asNative(t,n){return n===void 0?t instanceof Buffer?t:Buffer.from(t):t instanceof Buffer?t.slice(0,n):Buffer.from(t,0,n)}allocNative(t){return Buffer.allocUnsafe(t)}};sa.emptyBuffer=Buffer.allocUnsafe(0);var Ol=class{static{i(this,"ReadableStreamWrapper")}constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),Un.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),Un.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),Un.Disposable.create(()=>this.stream.off("end",t))}onData(t){return this.stream.on("data",t),Un.Disposable.create(()=>this.stream.off("data",t))}},Ll=class{static{i(this,"WritableStreamWrapper")}constructor(t){this.stream=t}onClose(t){return this.stream.on("close",t),Un.Disposable.create(()=>this.stream.off("close",t))}onError(t){return this.stream.on("error",t),Un.Disposable.create(()=>this.stream.off("error",t))}onEnd(t){return this.stream.on("end",t),Un.Disposable.create(()=>this.stream.off("end",t))}write(t,n){return new Promise((o,s)=>{let a=i(l=>{l==null?o():s(l)},"callback");typeof t=="string"?this.stream.write(t,n,a):this.stream.write(t,a)})}end(){this.stream.end()}},fm=Object.freeze({messageBuffer:Object.freeze({create:i(e=>new sa(e),"create")}),applicationJson:Object.freeze({encoder:Object.freeze({name:"application/json",encode:i((e,t)=>{try{return Promise.resolve(Buffer.from(JSON.stringify(e,void 0,0),t.charset))}catch(n){return Promise.reject(n)}},"encode")}),decoder:Object.freeze({name:"application/json",decode:i((e,t)=>{try{return e instanceof Buffer?Promise.resolve(JSON.parse(e.toString(t.charset))):Promise.resolve(JSON.parse(new pm.TextDecoder(t.charset).decode(e)))}catch(n){return Promise.reject(n)}},"decode")})}),stream:Object.freeze({asReadableStream:i(e=>new Ol(e),"asReadableStream"),asWritableStream:i(e=>new Ll(e),"asWritableStream")}),console,timer:Object.freeze({setTimeout(e,t,...n){let o=setTimeout(e,t,...n);return{dispose:i(()=>clearTimeout(o),"dispose")}},setImmediate(e,...t){let n=setImmediate(e,...t);return{dispose:i(()=>clearImmediate(n),"dispose")}},setInterval(e,t,...n){let o=setInterval(e,t,...n);return{dispose:i(()=>clearInterval(o),"dispose")}}})});function Nl(){return fm}i(Nl,"RIL");(function(e){function t(){Un.RAL.install(fm)}i(t,"install"),e.install=t})(Nl||(Nl={}));jl.default=Nl});var ym=kt($e=>{"use strict";var xx=$e&&$e.__createBinding||(Object.create?(function(e,t,n,o){o===void 0&&(o=n);var s=Object.getOwnPropertyDescriptor(t,n);(!s||("get"in s?!t.__esModule:s.writable||s.configurable))&&(s={enumerable:!0,get:i(function(){return t[n]},"get")}),Object.defineProperty(e,o,s)}):(function(e,t,n,o){o===void 0&&(o=n),e[o]=t[n]})),Sx=$e&&$e.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&xx(t,e,n)};Object.defineProperty($e,"__esModule",{value:!0});$e.createMessageConnection=$e.createServerSocketTransport=$e.createClientSocketTransport=$e.createServerPipeTransport=$e.createClientPipeTransport=$e.generateRandomPipeName=$e.StreamMessageWriter=$e.StreamMessageReader=$e.SocketMessageWriter=$e.SocketMessageReader=$e.PortMessageWriter=$e.PortMessageReader=$e.IPCMessageWriter=$e.IPCMessageReader=void 0;var Tr=mm();Tr.default.install();var hm=Hr("path"),Ix=Hr("os"),kx=Hr("crypto"),ca=Hr("net"),nn=ra();Sx(ra(),$e);var Ul=class extends nn.AbstractMessageReader{static{i(this,"IPCMessageReader")}constructor(t){super(),this.process=t;let n=this.process;n.on("error",o=>this.fireError(o)),n.on("close",()=>this.fireClose())}listen(t){return this.process.on("message",t),nn.Disposable.create(()=>this.process.off("message",t))}};$e.IPCMessageReader=Ul;var Fl=class extends nn.AbstractMessageWriter{static{i(this,"IPCMessageWriter")}constructor(t){super(),this.process=t,this.errorCount=0;let n=this.process;n.on("error",o=>this.fireError(o)),n.on("close",()=>this.fireClose)}write(t){try{return typeof this.process.send=="function"&&this.process.send(t,void 0,void 0,n=>{n?(this.errorCount++,this.handleError(n,t)):this.errorCount=0}),Promise.resolve()}catch(n){return this.handleError(n,t),Promise.reject(n)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){}};$e.IPCMessageWriter=Fl;var Bl=class extends nn.AbstractMessageReader{static{i(this,"PortMessageReader")}constructor(t){super(),this.onData=new nn.Emitter,t.on("close",()=>this.fireClose),t.on("error",n=>this.fireError(n)),t.on("message",n=>{this.onData.fire(n)})}listen(t){return this.onData.event(t)}};$e.PortMessageReader=Bl;var $l=class extends nn.AbstractMessageWriter{static{i(this,"PortMessageWriter")}constructor(t){super(),this.port=t,this.errorCount=0,t.on("close",()=>this.fireClose()),t.on("error",n=>this.fireError(n))}write(t){try{return this.port.postMessage(t),Promise.resolve()}catch(n){return this.handleError(n,t),Promise.reject(n)}}handleError(t,n){this.errorCount++,this.fireError(t,n,this.errorCount)}end(){}};$e.PortMessageWriter=$l;var To=class extends nn.ReadableStreamMessageReader{static{i(this,"SocketMessageReader")}constructor(t,n="utf-8"){super((0,Tr.default)().stream.asReadableStream(t),n)}};$e.SocketMessageReader=To;var Po=class extends nn.WriteableStreamMessageWriter{static{i(this,"SocketMessageWriter")}constructor(t,n){super((0,Tr.default)().stream.asWritableStream(t),n),this.socket=t}dispose(){super.dispose(),this.socket.destroy()}};$e.SocketMessageWriter=Po;var ia=class extends nn.ReadableStreamMessageReader{static{i(this,"StreamMessageReader")}constructor(t,n){super((0,Tr.default)().stream.asReadableStream(t),n)}};$e.StreamMessageReader=ia;var aa=class extends nn.WriteableStreamMessageWriter{static{i(this,"StreamMessageWriter")}constructor(t,n){super((0,Tr.default)().stream.asWritableStream(t),n)}};$e.StreamMessageWriter=aa;var gm=process.env.XDG_RUNTIME_DIR,Dx=new Map([["linux",107],["darwin",103]]);function Ex(){let e=(0,kx.randomBytes)(21).toString("hex");if(process.platform==="win32")return`\\\\.\\pipe\\vscode-jsonrpc-${e}-sock`;let t;gm?t=hm.join(gm,`vscode-ipc-${e}.sock`):t=hm.join(Ix.tmpdir(),`vscode-${e}.sock`);let n=Dx.get(process.platform);return n!==void 0&&t.length>n&&(0,Tr.default)().console.warn(`WARNING: IPC handle "${t}" is longer than ${n} characters.`),t}i(Ex,"generateRandomPipeName");$e.generateRandomPipeName=Ex;function Tx(e,t="utf-8"){let n,o=new Promise((s,a)=>{n=s});return new Promise((s,a)=>{let l=(0,ca.createServer)(d=>{l.close(),n([new To(d,t),new Po(d,t)])});l.on("error",a),l.listen(e,()=>{l.removeListener("error",a),s({onConnected:i(()=>o,"onConnected")})})})}i(Tx,"createClientPipeTransport");$e.createClientPipeTransport=Tx;function Px(e,t="utf-8"){let n=(0,ca.createConnection)(e);return[new To(n,t),new Po(n,t)]}i(Px,"createServerPipeTransport");$e.createServerPipeTransport=Px;function Rx(e,t="utf-8"){let n,o=new Promise((s,a)=>{n=s});return new Promise((s,a)=>{let l=(0,ca.createServer)(d=>{l.close(),n([new To(d,t),new Po(d,t)])});l.on("error",a),l.listen(e,"127.0.0.1",()=>{l.removeListener("error",a),s({onConnected:i(()=>o,"onConnected")})})})}i(Rx,"createClientSocketTransport");$e.createClientSocketTransport=Rx;function Cx(e,t="utf-8"){let n=(0,ca.createConnection)(e,"127.0.0.1");return[new To(n,t),new Po(n,t)]}i(Cx,"createServerSocketTransport");$e.createServerSocketTransport=Cx;function Ax(e){let t=e;return t.read!==void 0&&t.addListener!==void 0}i(Ax,"isReadableStream");function Mx(e){let t=e;return t.write!==void 0&&t.addListener!==void 0}i(Mx,"isWritableStream");function _x(e,t,n,o){n||(n=nn.NullLogger);let s=Ax(e)?new ia(e):e,a=Mx(t)?new aa(t):t;return nn.ConnectionStrategy.is(o)&&(o={connectionStrategy:o}),(0,nn.createMessageConnection)(s,a,n,o)}i(_x,"createMessageConnection");$e.createMessageConnection=_x});var wm=kt((NO,bm)=>{"use strict";bm.exports=ym()});var vo={};fe(vo,{AppNodeBuilder:()=>vo,build:()=>Dg});function Dg(e,t=[]){let n=t;if(ke.hasUnbound(e,Yn.node)&&!Eg(t,Yn.node)){let o=Uu(t),s=Xs({service:Yn.Service,layer:o,deps:[]});n=t.concat([[Yn.node,s]])}return ke.compile(e,n)}i(Dg,"build");function Eg(e,t){return e.some(([n])=>n.name===t.name)}i(Eg,"hasReplacement");var sc={};fe(sc,{Authorization:()=>rc,AuthorizeInput:()=>Ag,CallbackInput:()=>Mg,Method:()=>bi,Methods:()=>ep,OauthCallbackFailed:()=>xi,OauthCodeMissing:()=>vi,OauthMissing:()=>wi,ProviderAuth:()=>sc,Service:()=>xo,ValidationFailed:()=>os,node:()=>Lg,use:()=>_g});var Zu=c.Struct({key:c.String,op:c.Literals(["eq","neq"]),value:c.String}),Tg=c.Struct({type:c.Literal("text"),key:c.String,message:c.String,placeholder:hn(c.String),when:hn(Zu)}),Pg=c.Struct({label:c.String,value:c.String,hint:hn(c.String)}),Rg=c.Struct({type:c.Literal("select"),key:c.String,message:c.String,options:c.Array(Pg),when:hn(Zu)}),Cg=c.Union([Tg,Rg]),bi=class extends c.Class("ProviderAuthMethod")({type:c.Literals(["oauth","api"]),label:c.String,prompts:hn(c.Array(Cg))}){static{i(this,"Method")}},ep=c.Record(c.String,c.Array(bi)),rc=class extends c.Class("ProviderAuthAuthorization")({url:c.String,method:c.Literals(["auto","code"]),instructions:c.String}){static{i(this,"Authorization")}},Ag=c.Struct({method:c.Finite.annotate({description:"Auth method index"}),inputs:c.optional(c.Record(c.String,c.String)).annotate({description:"Prompt inputs"})}),Mg=c.Struct({method:c.Finite.annotate({description:"Auth method index"}),code:c.optional(c.String).annotate({description:"OAuth authorization code"})}),wi=class extends c.TaggedErrorClass()("ProviderAuthOauthMissing",{providerID:sn.ID}){static{i(this,"OauthMissing")}},vi=class extends c.TaggedErrorClass()("ProviderAuthOauthCodeMissing",{providerID:sn.ID}){static{i(this,"OauthCodeMissing")}},xi=class extends c.TaggedErrorClass()("ProviderAuthOauthCallbackFailed",{}){static{i(this,"OauthCallbackFailed")}},os=class extends c.TaggedErrorClass()("ProviderAuthValidationFailed",{field:c.String,message:c.String}){static{i(this,"ValidationFailed")}},xo=class extends Re.Service()("@opencode/ProviderAuth"){static{i(this,"Service")}},_g=Wt(xo),Og=Te.effect(xo,r.gen(function*(){let e=yield*Xt.Service,t=yield*pt.Service,n=yield*G.make(r.fn("ProviderAuth.state")(function*(){let d=yield*t.list();return{hooks:Go.fromEntries(Ed.filterMap(d,p=>p.auth?.provider!==void 0?Ma.succeed([sn.ID.make(p.auth.provider),p.auth]):Ma.failVoid)),pending:new Map}})),o=c.decodeUnknownSync(ep),s=r.fn("ProviderAuth.methods")(function*(){let d=(yield*G.get(n)).hooks;return o(Go.map(d,p=>p.methods.map(f=>({type:f.type,label:f.label,...f.prompts&&{prompts:f.prompts.map(u=>u.type==="select"?{type:"select",key:u.key,message:u.message,options:u.options,...u.when&&{when:u.when}}:{type:"text",key:u.key,message:u.message,...u.placeholder&&{placeholder:u.placeholder},...u.when&&{when:u.when}})}}))))}),a=r.fn("ProviderAuth.authorize")(function*(d){let{hooks:p,pending:f}=yield*G.get(n),u=p[d.providerID].methods[d.method];if(u.type!=="oauth")return;if(u.prompts&&d.inputs){for(let y of u.prompts)if(y.type==="text"&&y.validate&&d.inputs[y.key]!==void 0){let b=y.validate(d.inputs[y.key]);if(b)return yield*new os({field:y.key,message:b})}}let g=yield*r.tryPromise({try:i(()=>u.authorize(d.inputs),"try"),catch:i(y=>new os({field:"authorize",message:y instanceof Error?y.message:String(y)}),"catch")});return f.set(d.providerID,g),{url:g.url,method:g.method,instructions:g.instructions}}),l=r.fn("ProviderAuth.callback")(function*(d){let f=(yield*G.get(n)).pending.get(d.providerID);if(!f)return yield*new wi({providerID:d.providerID});if(f.method==="code"&&!d.code)return yield*new vi({providerID:d.providerID});let u=yield*r.promise(()=>f.method==="code"?f.callback(d.code):f.callback());if(!u||u.type!=="success")return yield*new xi({});if("key"in u&&(yield*e.set(d.providerID,{type:"api",key:u.key,...u.metadata?{metadata:u.metadata}:{}})),"refresh"in u){let{type:g,provider:y,refresh:b,access:S,expires:T,...m}=u;yield*e.set(d.providerID,{type:"oauth",access:S,refresh:b,expires:T,...m})}});return xo.of({methods:s,authorize:a,callback:l})})),Lg=ke.make({service:xo,layer:Og,deps:[Xt.node,pt.node]});var Qt={};fe(Qt,{Answer:()=>Vg,Event:()=>Ii,Info:()=>Bg,NotFoundError:()=>ss,Option:()=>Fg,Prompt:()=>$g,Question:()=>Qt,Rejected:()=>Hg,RejectedError:()=>rs,Replied:()=>Gg,Reply:()=>zg,Request:()=>Wg,Service:()=>tr,Tool:()=>qg,node:()=>Jg});var Ot={};fe(Ot,{Answer:()=>ic,Event:()=>Ug,ID:()=>Si,Info:()=>ip,Option:()=>rp,Prompt:()=>Ng,QuestionV1:()=>Ot,Rejected:()=>dp,Replied:()=>lp,Reply:()=>jg,Request:()=>cp,Tool:()=>ap});var Si=c.String.check(c.isStartsWith("que")).pipe(c.brand("QuestionID"),Hd(e=>({ascending:i(t=>e.make(t??"que_"+Yd()),"ascending")}))),rp=c.Struct({label:c.String.annotate({description:"Display text (1-5 words, concise)"}),description:c.String.annotate({description:"Explanation of choice"})}).annotate({identifier:"QuestionOption"}),sp={question:c.String.annotate({description:"Complete question"}),header:c.String.annotate({description:"Very short label (max 30 chars)"}),options:c.Array(rp).annotate({description:"Available choices"}),multiple:c.optional(c.Boolean).annotate({description:"Allow selecting multiple choices"})},ip=c.Struct({...sp,custom:c.optional(c.Boolean).annotate({description:"Allow typing a custom answer (default: true)"})}).annotate({identifier:"QuestionInfo"}),Ng=c.Struct(sp).annotate({identifier:"QuestionPrompt"}),ap=c.Struct({messageID:fu.MessageID,callID:c.String}).annotate({identifier:"QuestionTool"}),cp=c.Struct({id:Si,sessionID:Cn,questions:c.Array(ip).annotate({description:"Questions to ask"}),tool:c.optional(ap)}).annotate({identifier:"QuestionRequest"}),ic=c.Array(c.String).annotate({identifier:"QuestionAnswer"}),jg=c.Struct({answers:c.Array(ic).annotate({description:"User answers in order of questions (each answer is an array of selected labels)"})}).annotate({identifier:"QuestionReply"}),lp=c.Struct({sessionID:Cn,requestID:Si,answers:c.Array(ic)}).annotate({identifier:"QuestionReplied"}),dp=c.Struct({sessionID:Cn,requestID:Si}).annotate({identifier:"QuestionRejected"}),tp=Qs({type:"question.asked",schema:cp.fields}),np=Qs({type:"question.replied",schema:lp.fields}),op=Qs({type:"question.rejected",schema:dp.fields}),Ug={Asked:tp,Replied:np,Rejected:op,Definitions:Jd(tp,np,op)};var ac=Ot.ID;var Fg=Ot.Option,Bg=Ot.Info,$g=Ot.Prompt,qg=Ot.Tool,Wg=Ot.Request,Vg=Ot.Answer,zg=Ot.Reply,Gg=Ot.Replied,Hg=Ot.Rejected,Ii=Ot.Event,rs=class extends c.TaggedErrorClass()("QuestionRejectedError",{}){static{i(this,"RejectedError")}get message(){return"The user dismissed this question"}},ss=class extends c.TaggedErrorClass()("Question.NotFoundError",{requestID:ac}){static{i(this,"NotFoundError")}},tr=class extends Re.Service()("@opencode/Question"){static{i(this,"Service")}},Yg=Te.effect(tr,r.gen(function*(){let e=yield*De.Service,t=yield*G.make(r.fn("Question.state")(function*(){let l={pending:new Map};return yield*r.addFinalizer(()=>r.gen(function*(){for(let d of l.pending.values())yield*ht.fail(d.deferred,new rs);l.pending.clear()})),l})),n=r.fn("Question.ask")(function*(l){let d=(yield*G.get(t)).pending,p=ac.ascending();yield*r.logInfo("asking",{id:p,questions:l.questions.length});let f=yield*ht.make(),u={id:p,sessionID:l.sessionID,questions:l.questions,tool:l.tool};return d.set(p,{info:u,deferred:f}),yield*e.publish(Ii.Asked,u),yield*r.ensuring(ht.await(f),r.sync(()=>{d.delete(p)}))}),o=r.fn("Question.reply")(function*(l){let d=(yield*G.get(t)).pending,p=d.get(l.requestID);if(!p)return yield*r.logWarning("reply for unknown request",{requestID:l.requestID}),yield*new ss({requestID:l.requestID});d.delete(l.requestID),yield*r.logInfo("replied",{requestID:l.requestID,answers:l.answers}),yield*e.publish(Ii.Replied,{sessionID:p.info.sessionID,requestID:p.info.id,answers:l.answers.map(f=>[...f])}),yield*ht.succeed(p.deferred,l.answers)}),s=r.fn("Question.reject")(function*(l){let d=(yield*G.get(t)).pending,p=d.get(l);if(!p)return yield*r.logWarning("reject for unknown request",{requestID:l}),yield*new ss({requestID:l});d.delete(l),yield*r.logInfo("rejected",{requestID:l}),yield*e.publish(Ii.Rejected,{sessionID:p.info.sessionID,requestID:p.info.id}),yield*ht.fail(p.deferred,new rs)}),a=r.fn("Question.list")(function*(){let l=(yield*G.get(t)).pending;return Array.from(l.values(),d=>d.info)});return tr.of({ask:n,reply:o,reject:s,list:a})})),Jg=ke.make({service:tr,layer:Yg,deps:[De.node]});var Qn={};fe(Qn,{Event:()=>up,Info:()=>Kg,Service:()=>nr,Todo:()=>Qn,node:()=>Qg});var Kg=Ha.Info,up=Ha.Event,nr=class extends Re.Service()("@opencode/SessionTodo"){static{i(this,"Service")}},Xg=Te.effect(nr,r.gen(function*(){let e=yield*De.Service,{db:t}=yield*Qe.Service,n=r.fn("Todo.update")(function*(s){yield*t.transaction(a=>r.gen(function*(){yield*a.delete(go).where(St(go.session_id,s.sessionID)).run(),s.todos.length!==0&&(yield*a.insert(go).values(s.todos.map((l,d)=>({session_id:s.sessionID,content:l.content,status:l.status,priority:l.priority,position:d}))).run())})).pipe(r.orDie),yield*e.publish(up.Updated,s)}),o=r.fn("Todo.get")(function*(s){return(yield*t.select().from(go).where(St(go.session_id,s)).orderBy(Zs(go.position)).all().pipe(r.orDie)).map(l=>({content:l.content,status:l.status,priority:l.priority}))});return nr.of({update:n,get:o})})),Qg=ke.make({service:nr,layer:Xg,deps:[De.node,Qe.node]});var ln={};fe(ln,{Event:()=>cc,Info:()=>ey,Service:()=>rr,SessionStatus:()=>ln,node:()=>ny});var or={};fe(or,{Definitions:()=>Zg,Idle:()=>mp,Info:()=>pp,SessionStatusEvent:()=>or,Status:()=>fp});var pp=c.Union([c.Struct({type:c.Literal("idle")}),c.Struct({type:c.Literal("retry"),attempt:mn,message:c.String,action:hn(c.Struct({reason:c.String,provider:c.String,title:c.String,message:c.String,label:c.String,link:hn(c.String)})),next:mn}),c.Struct({type:c.Literal("busy")})]).annotate({identifier:"SessionStatus"}),fp=Et.define({type:"session.status",schema:{sessionID:Cn,status:pp}}),mp=Et.define({type:"session.idle",schema:{sessionID:Cn}}),Zg=Et.inventory(fp,mp);var ey=or.Info,cc=or,rr=class extends Re.Service()("@opencode/SessionStatus"){static{i(this,"Service")}},ty=Te.effect(rr,r.gen(function*(){let e=yield*De.Service,t=yield*G.make(r.fn("SessionStatus.state")(()=>r.succeed(new Map))),n=r.fn("SessionStatus.get")(function*(a){return(yield*G.get(t)).get(a)??{type:"idle"}}),o=r.fn("SessionStatus.list")(function*(){return new Map(yield*G.get(t))}),s=r.fn("SessionStatus.set")(function*(a,l){let d=yield*G.get(t);if(yield*e.publish(cc.Status,{sessionID:a,status:l}),l.type==="idle"){yield*e.publish(cc.Idle,{sessionID:a}),d.delete(a);return}d.set(a,l)});return rr.of({get:n,list:o,set:s})})),ny=ke.make({service:rr,layer:ty,deps:[De.node]});var Ln={};fe(Ln,{Service:()=>sr,SessionRunState:()=>Ln,node:()=>iy});var is={};fe(is,{Busy:()=>ki,Cancelled:()=>So,Runner:()=>is,make:()=>oy});var So=class extends c.TaggedErrorClass()("RunnerCancelled",{}){static{i(this,"Cancelled")}},ki=class extends c.TaggedErrorClass()("RunnerBusy",{}){static{i(this,"Busy")}},oy=i((e,t)=>{let n=Rn.makeUnsafe({_tag:"Idle"}),o=t?.onIdle??r.void,s=t?.onBusy??r.void,a=t?.onInterrupt,l=0,d=i(()=>Rn.getUnsafe(n),"state"),p=i(()=>(l+=1,l),"next"),f=i((w,I)=>bt.isFailure(I)&&tt.hasInterruptsOnly(I.cause)?ht.fail(w,new So).pipe(r.asVoid):ht.done(w,I).pipe(r.asVoid),"complete"),u=i(w=>ht.await(w).pipe(r.catchTag("RunnerCancelled",I=>a??r.die(I))),"awaitDone"),g=i(()=>Rn.modify(n,w=>[w._tag==="Idle"?o:r.void,w]).pipe(r.flatten),"idleIfCurrent"),y=i((w,I,P)=>Rn.modify(n,x=>[r.gen(function*(){x._tag==="Running"&&x.run.id===w&&(yield*o),yield*f(I,P)}),x._tag==="Running"&&x.run.id===w?{_tag:"Idle"}:x]).pipe(r.flatten),"finishRun"),b=i((w,I)=>r.gen(function*(){let P=p(),x=yield*w.pipe(r.onExit(A=>y(P,I,A)),r.forkIn(e));return{id:P,done:I,fiber:x}}),"startRun"),S=i(w=>Rn.modifyEffect(n,r.fnUntraced(function*(I){if(I._tag==="Shell"&&I.shell.id===w)return[o,{_tag:"Idle"}];if(I._tag==="ShellThenRun"&&I.shell.id===w){let P=yield*b(I.run.work,I.run.done);return[r.void,{_tag:"Running",run:P}]}return[r.void,I]})).pipe(r.flatten),"finishShell"),T=i(w=>r.gen(function*(){w.ready&&(yield*w.ready.await.pipe(r.exit,r.asVoid)),yield*ht.succeed(w.cancelled,void 0).pipe(r.asVoid),yield*Vs.interrupt(w.fiber)}),"stopShell"),m=i(w=>Rn.modifyEffect(n,r.fnUntraced(function*(I){switch(I._tag){case"Running":case"ShellThenRun":return[u(I.run.done),I];case"Shell":{let P={id:p(),done:yield*ht.make(),work:w};return[u(P.done),{_tag:"ShellThenRun",shell:I.shell,run:P}]}case"Idle":{let P=yield*ht.make(),x=yield*b(w,P);return[u(P),{_tag:"Running",run:x}]}}})).pipe(r.flatten),"ensureRunning"),h=i((w,I)=>Rn.modifyEffect(n,r.fnUntraced(function*(P){if(P._tag!=="Idle")return[r.fail(new ki),P];yield*s;let x=p(),A=yield*ht.make(),C=yield*w.pipe(r.ensuring(S(x)),r.forkChild),$={id:x,cancelled:A,ready:I,fiber:C};return[r.gen(function*(){let j=yield*Vs.await(C);return bt.isSuccess(j)?j.value:tt.hasInterruptsOnly(j.cause)||(yield*ht.isDone(A))&&tt.hasInterrupts(j.cause)&&!tt.hasDies(j.cause)?a?yield*a:yield*r.die(new So):yield*r.failCause(j.cause)}),{_tag:"Shell",shell:$}]})).pipe(r.flatten),"startShell"),k=Rn.modify(n,w=>{switch(w._tag){case"Idle":return[r.void,w];case"Running":return[r.gen(function*(){yield*Vs.interrupt(w.run.fiber),yield*ht.fail(w.run.done,new So).pipe(r.asVoid),yield*g()}),{_tag:"Idle"}];case"Shell":return[r.gen(function*(){yield*T(w.shell),yield*g()}),{_tag:"Idle"}];case"ShellThenRun":return[r.gen(function*(){yield*T(w.shell),yield*ht.fail(w.run.done,new So).pipe(r.asVoid),yield*g()}),{_tag:"Idle"}]}}).pipe(r.flatten);return{get state(){return d()},get busy(){return d()._tag!=="Idle"},ensureRunning:m,startShell:h,cancel:k}},"make");var sr=class extends Re.Service()("@opencode/SessionRunState"){static{i(this,"Service")}},ry=Te.effect(sr,r.gen(function*(){let e=yield*bo.Service,t=yield*ln.Service,n=yield*G.make(r.fn("SessionRunState.state")(function*(){let f=yield*Dt.Scope,u=new Map;return yield*r.addFinalizer(r.fnUntraced(function*(){u.size>0&&(yield*r.logWarning("instance closing: its running turns are cancelled",{sessions:[...u.keys()].join(",")})),yield*r.forEach(u.values(),g=>g.cancel,{concurrency:"unbounded",discard:!0}),u.clear()})),{runners:u,scope:f}})),o=r.fn("SessionRunState.runner")(function*(f,u){let g=yield*G.get(n),y=g.runners.get(f);if(y)return y;let b=is.make(g.scope,{onIdle:r.gen(function*(){g.runners.delete(f),yield*t.set(f,{type:"idle"})}),onBusy:t.set(f,{type:"busy"}),onInterrupt:u});return g.runners.set(f,b),b}),s=r.fn("SessionRunState.assertNotBusy")(function*(f){(yield*G.get(n)).runners.get(f)?.busy&&(yield*hp(f))}),a=r.fn("SessionRunState.cancel")(function*(f){yield*r.logWarning("session cancel requested",{sessionID:f}),yield*sy(e,f);let g=(yield*G.get(n)).runners.get(f);if(!g){yield*t.set(f,{type:"idle"});return}yield*g.cancel}),l=r.fn("SessionRunState.busy")(function*(){return[...(yield*G.get(n)).runners.entries()].filter(([,u])=>u.busy).map(([u])=>u)}),d=r.fn("SessionRunState.ensureRunning")(function*(f,u,g){return yield*(yield*o(f,u)).ensureRunning(g)}),p=r.fn("SessionRunState.startShell")(function*(f,u,g,y){return yield*(yield*o(f,u)).startShell(g,y).pipe(r.catchTag("RunnerBusy",()=>r.fail(hp(f))))});return sr.of({assertNotBusy:s,cancel:a,busy:l,ensureRunning:d,startShell:p})})),sy=r.fn("SessionRunState.cancelBackgroundJobs")(function*(e,t){let n=yield*e.list(),o=new Set([t]),s=new Set,a=i(d=>d.status!=="running"||s.has(d.id)?!1:o.has(d.id)||typeof d.metadata?.sessionId=="string"&&o.has(d.metadata.sessionId)?!0:typeof d.metadata?.parentSessionId=="string"&&o.has(d.metadata.parentSessionId),"matches"),l=n.filter(a);for(;l.length>0;)yield*r.forEach(l,d=>e.cancel(d.id).pipe(r.tap(()=>r.sync(()=>{s.add(d.id),o.add(d.id),typeof d.metadata?.sessionId=="string"&&o.add(d.metadata.sessionId)}))),{concurrency:"unbounded",discard:!0}),l=n.filter(a)});function hp(e){return new me.BusyError({sessionID:e})}i(hp,"busyError");var iy=ke.make({service:sr,layer:ry,deps:[bo.node,ln.node]});var dn={};fe(dn,{LLM:()=>dn,OUTPUT_TOKEN_MAX:()=>ev,Service:()=>ko,hasToolCalls:()=>ov,node:()=>rv,use:()=>tv});var as={};fe(as,{Wildcard:()=>as,all:()=>ay,allStructured:()=>cy,match:()=>Di});function Di(e,t){e&&(e=e.replaceAll("\\","/")),t&&(t=t.replaceAll("\\","/"));let n=t.replace(/[.+^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*").replace(/\?/g,".");n.endsWith(" .*")&&(n=n.slice(0,-3)+"( .*)?");let o=process.platform==="win32"?"si":"s";return new RegExp("^"+n+"$",o).test(e)}i(Di,"match");function ay(e,t){let n=Ja(t,Object.entries,Ka([([s])=>s.length,"asc"],[([s])=>s,"asc"])),o;for(let[s,a]of n)if(Di(e,s)){o=a;continue}return o}i(ay,"all");function cy(e,t){let n=Ja(t,Object.entries,Ka([([s])=>s.length,"asc"],[([s])=>s,"asc"])),o;for(let[s,a]of n){let l=s.split(/\s+/);if(Di(e.head,l[0])&&(l.length===1||lc(e.tail,l.slice(1)))){o=a;continue}}return o}i(cy,"allStructured");function lc(e,t){if(t.length===0)return!0;let[n,...o]=t;if(n==="*")return lc(e,o);for(let s=0;s<e.length;s++)if(Di(e[s],n)&&lc(e.slice(s+1),o))return!0;return!1}i(lc,"matchSequence");var ir={};fe(ir,{LLMAISDK:()=>ir,adapterState:()=>bp,toLLMEvents:()=>dy});function bp(){return{step:0,text:0,reasoning:0,currentTextID:void 0,currentReasoningID:void 0,toolNames:{},copilotTotalNanoAiu:void 0}}i(bp,"adapterState");function gp(e){return c.is(Zd)(e)?e:"unknown"}i(gp,"finishReason");function Zt(e){if(e!=null)return c.is(Qd)(e)?e:void 0}i(Zt,"providerMetadata");function ly(e){if(!e||typeof e!="object")return;let t=e,n=t.response&&typeof t.response=="object"?t.response:void 0,o=t.copilot_usage??n?.copilot_usage;if(!o||typeof o!="object")return;let s=o.total_nano_aiu;if(!(typeof s!="number"||!Number.isFinite(s)||s<0))return s}i(ly,"copilotTotalNanoAiu");function yp(e){if(!e||typeof e!="object")return;let t=e,n=Object.entries({inputTokens:t.inputTokens,outputTokens:t.outputTokens,totalTokens:t.totalTokens,reasoningTokens:t.outputTokenDetails?.reasoningTokens??t.reasoningTokens,cacheReadInputTokens:t.inputTokenDetails?.cacheReadTokens??t.cachedInputTokens,cacheWriteInputTokens:t.inputTokenDetails?.cacheWriteTokens}).filter(o=>o[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}i(yp,"usage");function dc(e,t){return e.currentTextID=t??e.currentTextID??`text-${e.text++}`,e.currentTextID}i(dc,"currentTextID");function uc(e,t){return e.currentReasoningID=t??e.currentReasoningID??`reasoning-${e.reasoning++}`,e.currentReasoningID}i(uc,"currentReasoningID");function dy(e,t){switch(t.type){case"start":return r.succeed([]);case"start-step":return r.succeed([rt.stepStart({index:e.step})]);case"finish-step":return t.rawFinishReason==="network_error"?r.fail(new Wu.ResponseStreamError("Provider finish_reason: network_error")):r.sync(()=>{let n=Zt(t.providerMetadata),o=e.copilotTotalNanoAiu===void 0?n:{...n,copilot:{...n?.copilot,totalNanoAiu:e.copilotTotalNanoAiu}};return e.copilotTotalNanoAiu=void 0,[rt.stepFinish({index:e.step++,reason:gp(t.finishReason),usage:yp(t.usage),providerMetadata:o,...typeof t.response?.modelId=="string"?{responseModelID:t.response.modelId}:{}})]});case"finish":return r.sync(()=>{let n=[rt.finish({reason:gp(t.finishReason),usage:yp(t.totalUsage),providerMetadata:"providerMetadata"in t?Zt(t.providerMetadata):void 0})];return Object.assign(e,bp()),n});case"text-start":return r.sync(()=>(e.currentTextID=dc(e,t.id),[rt.textStart({id:e.currentTextID,providerMetadata:Zt(t.providerMetadata)})]));case"text-delta":return r.succeed([rt.textDelta({id:dc(e,t.id),text:t.text,providerMetadata:Zt(t.providerMetadata)})]);case"text-end":return r.sync(()=>{let n=dc(e,t.id);return e.currentTextID=void 0,[rt.textEnd({id:n,providerMetadata:Zt(t.providerMetadata)})]});case"reasoning-start":return r.sync(()=>(e.currentReasoningID=uc(e,t.id),[rt.reasoningStart({id:e.currentReasoningID,providerMetadata:Zt(t.providerMetadata)})]));case"reasoning-delta":return r.succeed([rt.reasoningDelta({id:uc(e,t.id),text:t.text,providerMetadata:Zt(t.providerMetadata)})]);case"reasoning-end":return r.sync(()=>{let n=uc(e,t.id);return e.currentReasoningID=void 0,[rt.reasoningEnd({id:n,providerMetadata:Zt(t.providerMetadata)})]});case"tool-input-start":return r.sync(()=>(e.toolNames[t.id]=t.toolName,[rt.toolInputStart({id:t.id,name:t.toolName,providerMetadata:Zt(t.providerMetadata)})]));case"tool-input-delta":return r.succeed([rt.toolInputDelta({id:t.id,name:e.toolNames[t.id]??"unknown",text:t.delta??""})]);case"tool-input-end":return r.succeed([rt.toolInputEnd({id:t.id,name:e.toolNames[t.id]??"unknown",providerMetadata:Zt(t.providerMetadata)})]);case"tool-call":return r.sync(()=>(e.toolNames[t.toolCallId]=t.toolName,[rt.toolCall({id:t.toolCallId,name:t.toolName,input:t.input,providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:Zt(t.providerMetadata)})]));case"tool-result":return r.sync(()=>{let n=e.toolNames[t.toolCallId]??"unknown";return delete e.toolNames[t.toolCallId],[rt.toolResult({id:t.toolCallId,name:n,result:eu.make(t.output),providerExecuted:"providerExecuted"in t?t.providerExecuted:void 0,providerMetadata:Zt(t.providerMetadata)})]});case"tool-error":return r.sync(()=>{let n=e.toolNames[t.toolCallId]??("toolName"in t?t.toolName:"unknown");return delete e.toolNames[t.toolCallId],[rt.toolError({id:t.toolCallId,name:n,message:gn(t.error),error:t.error,providerMetadata:Zt(t.providerMetadata)})]});case"error":return r.fail(t.error);case"abort":case"source":case"file":case"tool-output-denied":case"tool-approval-request":return r.succeed([]);case"raw":return r.sync(()=>(e.copilotTotalNanoAiu=ly(t.rawValue)??e.copilotTotalNanoAiu,[]));default:{let n=t;return r.succeed([])}}}i(dy,"toLLMEvents");var hs={};fe(hs,{LLMNativeRuntime:()=>hs,nativeTools:()=>of,status:()=>Ww,stream:()=>Vw});var ms={};fe(ms,{LLMNative:()=>ms,model:()=>ef,request:()=>qw});var Ei={};fe(Ei,{configure:()=>pc,id:()=>wp,model:()=>my,provider:()=>vp,routes:()=>uy});var wp=lt.make("anthropic"),uy=[Wa],py=i(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("ANTHROPIC_API_KEY")).pipe(gt.header("x-api-key")),"auth"),fy=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return Wa.with({...s,endpoint:{baseURL:o},auth:py(e)})},"configuredRoute"),pc=i((e={})=>{let t=fy(e);return{id:wp,model:i(n=>t.model({id:n}),"model"),configure:pc}},"configure"),vp=pc(),my=vp.model;var Pi={};fe(Pi,{configure:()=>gc,id:()=>hc,model:()=>fb,provider:()=>Rp,routes:()=>db});var cs={};fe(cs,{BedrockEventStream:()=>cs,framing:()=>vy});var hy=new Ru(Au,Cu),gy=new TextDecoder,yy={buffer:new Uint8Array(0),offset:0},by=i((e,t)=>{let n=e.buffer.length-e.offset,o=new Uint8Array(n+t.length);return o.set(e.buffer.subarray(e.offset),0),o.set(t,n),{buffer:o,offset:0}},"appendChunk"),wy=i(e=>(t,n)=>r.gen(function*(){let o=by(t,n),s=[];for(;o.buffer.length-o.offset>=4;){let a=o.buffer.subarray(o.offset),l=new DataView(a.buffer,a.byteOffset,a.byteLength).getUint32(0,!1);if(a.length<l)break;let d=yield*r.try({try:i(()=>hy.decode(a.subarray(0,l)),"try"),catch:i(g=>Ce.eventError(e,`Failed to decode Bedrock Converse event-stream frame: ${g instanceof Error?g.message:String(g)}`),"catch")});if(o={buffer:o.buffer,offset:o.offset+l},d.headers[":message-type"]?.value!=="event")continue;let p=d.headers[":event-type"]?.value;if(typeof p!="string")continue;let f=gy.decode(d.body);if(!f)continue;let u=yield*Ce.parseJson(e,f,"Failed to parse Bedrock Converse event-stream payload");delete u.p,s.push({[p]:u})}return[o,s]}),"consumeFrames"),vy=i(e=>({id:"aws-event-stream",frame:i(t=>t.pipe(vt.mapAccumEffect(()=>yy,wy(e))),"frame")}),"framing");var ar={};fe(ar,{BedrockAuth:()=>ar,auth:()=>Sy,sigV4:()=>xp});var xy=i(e=>r.tryPromise({try:i(async()=>{let t=await new Pu({url:e.url,method:"POST",headers:Object.entries(e.headers),body:e.body,region:e.credentials.region,accessKeyId:e.credentials.accessKeyId,secretAccessKey:e.credentials.secretAccessKey,sessionToken:e.credentials.sessionToken,service:"bedrock"}).sign();return Object.fromEntries(t.headers.entries())},"try"),catch:i(t=>Ce.invalidRequest(`Bedrock Converse SigV4 signing failed: ${t instanceof Error?t.message:String(t)}`),"catch")}),"signRequest"),xp=i(e=>gt.custom(t=>r.gen(function*(){if(!e)return yield*Ce.invalidRequest("Bedrock Converse requires either route bearer auth or AWS credentials configured on the route");let n=ja.set(t.headers,"content-type","application/json"),o=yield*xy({url:t.url,body:t.body,headers:n,credentials:e});return ja.setAll(n,o)})),"sigV4"),Sy=xp(void 0);var en={};fe(en,{BEDROCK_BREAKPOINT_CAP:()=>Sp,BedrockCache:()=>en,CachePointBlock:()=>Iy,block:()=>Ty,breakpoints:()=>ky});var Iy=c.Struct({cachePoint:c.Struct({type:c.tag("default"),ttl:c.optional(c.Literals(["5m","1h"]))})}),Sp=4,ky=i(()=>vu(Sp),"breakpoints"),Dy={cachePoint:{type:"default"}},Ey={cachePoint:{type:"default",ttl:"1h"}},Ty=i((e,t)=>{if(!(t?.type!=="ephemeral"&&t?.type!=="persistent")){if(e.remaining<=0){e.dropped+=1;return}return e.remaining-=1,xu(t.ttlSeconds)==="1h"?Ey:Dy}},"block");var Nn={};fe(Nn,{BedrockMedia:()=>Nn,DocumentBlock:()=>Ry,DocumentFormat:()=>Ep,ImageBlock:()=>Py,ImageFormat:()=>Dp,lower:()=>Ay});var Dp=c.Literals(["png","jpeg","gif","webp"]),Py=c.Struct({image:c.Struct({format:Dp,source:c.Struct({bytes:c.String})})}),Ep=c.Literals(["pdf","csv","doc","docx","xls","xlsx","html","txt","md"]),Ry=c.Struct({document:c.Struct({format:Ep,name:c.String,source:c.Struct({bytes:c.String})})}),Ip={"image/png":"png","image/jpeg":"jpeg","image/jpg":"jpeg","image/gif":"gif","image/webp":"webp"},kp={"application/pdf":"pdf","text/csv":"csv","application/msword":"doc","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"docx","application/vnd.ms-excel":"xls","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"xlsx","text/html":"html","text/plain":"txt","text/markdown":"md"},Cy=i((e,t,n)=>({document:{format:t,name:e.filename??`document.${t}`,source:{bytes:n}}}),"documentBlock"),Ay=r.fn("BedrockMedia.lower")(function*(e){let t=e.mediaType.toLowerCase(),n=Ip[t];if(n){let s=yield*Ce.validateMedia("Bedrock Converse",e,new Set(Object.keys(Ip)));return{image:{format:n,source:{bytes:s.base64}}}}if(t.startsWith("image/"))return yield*Ce.invalidRequest(`Bedrock Converse does not support image media type ${e.mediaType}`);let o=kp[t];if(o){let s=yield*Ce.validateMedia("Bedrock Converse",e,new Set(Object.keys(kp)));return Cy(e,o,s.base64)}return yield*Ce.invalidRequest(`Bedrock Converse does not support media type ${e.mediaType}`)});var ls="bedrock-converse",fc=c.Struct({text:c.String}),My=c.Struct({toolUse:c.Struct({toolUseId:c.String,name:c.String,input:c.Unknown})}),_y=c.Union([c.Struct({text:c.String}),c.Struct({json:c.Unknown}),Nn.ImageBlock]),Oy=c.Struct({toolResult:c.Struct({toolUseId:c.String,content:c.Array(_y),status:c.optional(c.Literals(["success","error"]))})}),Ly=c.Struct({reasoningContent:c.Struct({reasoningText:c.optional(c.Struct({text:c.String,signature:c.optional(c.String)}))})}),Ny=c.Union([fc,Nn.ImageBlock,Nn.DocumentBlock,Oy,en.CachePointBlock]),jy=c.Union([fc,Ly,My,en.CachePointBlock]),Uy=c.Union([c.Struct({role:c.Literal("user"),content:c.Array(Ny)}),c.Struct({role:c.Literal("assistant"),content:c.Array(jy)})]).pipe(c.toTaggedUnion("role")),Fy=c.Union([fc,en.CachePointBlock]),By=c.Struct({toolSpec:c.Struct({name:c.String,description:c.String,inputSchema:c.Struct({json:es})})}),$y=c.Union([By,en.CachePointBlock]),qy=c.Union([c.Struct({auto:c.Struct({})}),c.Struct({any:c.Struct({})}),c.Struct({tool:c.Struct({name:c.String})})]),Wy={modelId:c.String,messages:c.Array(Uy),system:Gn(Fy),inferenceConfig:c.optional(c.Struct({maxTokens:c.optional(c.Number),temperature:c.optional(c.Number),topP:c.optional(c.Number),stopSequences:Gn(c.String)})),toolConfig:c.optional(c.Struct({tools:c.Array($y),toolChoice:c.optional(qy)})),additionalModelRequestFields:c.optional(es)},Vy=c.Struct(Wy),zy=c.Struct({inputTokens:c.optional(c.Number),outputTokens:c.optional(c.Number),totalTokens:c.optional(c.Number),cacheReadInputTokens:c.optional(c.Number),cacheWriteInputTokens:c.optional(c.Number)}),Gy=c.Struct({messageStart:c.optional(c.Struct({role:c.String})),contentBlockStart:c.optional(c.Struct({contentBlockIndex:c.Number,start:c.optional(c.Struct({toolUse:c.optional(c.Struct({toolUseId:c.String,name:c.String}))}))})),contentBlockDelta:c.optional(c.Struct({contentBlockIndex:c.Number,delta:c.optional(c.Struct({text:c.optional(c.String),toolUse:c.optional(c.Struct({input:c.String})),reasoningContent:c.optional(c.Struct({text:c.optional(c.String),signature:c.optional(c.String)}))}))})),contentBlockStop:c.optional(c.Struct({contentBlockIndex:c.Number})),messageStop:c.optional(c.Struct({stopReason:c.String,additionalModelResponseFields:c.optional(c.Unknown)})),metadata:c.optional(c.Struct({usage:c.optional(zy),metrics:c.optional(c.Unknown)})),internalServerException:c.optional(c.Struct({message:c.String})),modelStreamErrorException:c.optional(c.Struct({message:c.String})),validationException:c.optional(c.Struct({message:c.String})),throttlingException:c.optional(c.Struct({message:c.String})),serviceUnavailableException:c.optional(c.Struct({message:c.String}))}),Hy=i((e,t)=>({toolSpec:{name:e.name,description:e.description,inputSchema:{json:t}}}),"lowerToolSpec"),Yy=i((e,t,n)=>{let o=[];for(let s of n){o.push(Hy(s,si.modelCompatibility(s.inputSchema,e)));let a=en.block(t,s.cache);a&&o.push(a)}return o},"lowerTools"),Ti=i((e,t,n)=>{let o=en.block(e,n);return o?[{text:t},o]:[{text:t}]},"textWithCache"),Jy=i(e=>Ce.matchToolChoice("Bedrock Converse",e,{auto:i(()=>({auto:{}}),"auto"),none:i(()=>{},"none"),required:i(()=>({any:{}}),"required"),tool:i(t=>({tool:{name:t}}),"tool")}),"lowerToolChoice"),Ky=i(e=>({bedrock:e}),"bedrockMetadata"),Xy=i(e=>{let t=e.providerMetadata?.bedrock;return e.encrypted??(Ce.isRecord(t)&&typeof t.signature=="string"?t.signature:void 0)},"reasoningSignature"),Qy=i(e=>({toolUse:{toolUseId:e.id,name:e.name,input:e.input}}),"lowerToolCall"),Zy=r.fn("BedrockConverse.lowerToolResultContent")(function*(e){if(e.result.type==="text"||e.result.type==="error")return[{text:Ce.toolResultText(e)}];if(e.result.type==="json")return[{json:e.result.value}];let t=[];for(let n of e.result.value){if(n.type==="text"){t.push({text:n.text});continue}let o=yield*Nn.lower({type:"media",mediaType:n.mime,data:n.uri,filename:n.name});if(!("image"in o))return yield*Ce.invalidRequest("Bedrock Converse only supports image media in tool results");t.push(o)}return t}),eb=r.fn("BedrockConverse.lowerToolResult")(function*(e){return{toolResult:{toolUseId:e.id,content:yield*Zy(e),status:e.result.type==="error"?"error":"success"}}}),tb=r.fn("BedrockConverse.lowerMessages")(function*(e,t){let n=[];for(let o of e.messages){if(o.role==="system"){let a=yield*Ce.wrappedSystemUpdate("Bedrock Converse",o),l=Ti(t,a.text,a.cache),d=n.at(-1);d?.role==="user"?n[n.length-1]={role:"user",content:[...d.content,...l]}:n.push({role:"user",content:l});continue}if(o.role==="user"){let a=[];for(let l of o.content){if(!Ce.supportsContent(l,["text","media"]))return yield*Ce.unsupportedContent("Bedrock Converse","user",["text","media"]);if(l.type==="text"){a.push(...Ti(t,l.text,l.cache));continue}if(l.type==="media"){a.push(yield*Nn.lower(l));continue}}n.push({role:"user",content:a});continue}if(o.role==="assistant"){let a=[];for(let l of o.content){if(!Ce.supportsContent(l,["text","reasoning","tool-call"]))return yield*Ce.unsupportedContent("Bedrock Converse","assistant",["text","reasoning","tool-call"]);if(l.type==="text"){a.push(...Ti(t,l.text,l.cache));continue}if(l.type==="reasoning"){a.push({reasoningContent:{reasoningText:{text:l.text,signature:Xy(l)}}});continue}if(l.type==="tool-call"){a.push(Qy(l));continue}}n.push({role:"assistant",content:a});continue}let s=[];for(let a of o.content){if(!Ce.supportsContent(a,["tool-result"]))return yield*Ce.unsupportedContent("Bedrock Converse","tool",["tool-result"]);s.push(yield*eb(a));let l=en.block(t,a.cache);l&&s.push(l)}n.push({role:"user",content:s})}return n}),nb=i((e,t)=>t.flatMap(n=>Ti(e,n.text,n.cache)),"lowerSystem"),ob=r.fn("BedrockConverse.fromRequest")(function*(e){let t=e.toolChoice?yield*Jy(e.toolChoice):void 0,n=e.generation,o=en.breakpoints(),s=e.tools.length>0&&e.toolChoice?.type!=="none"?{tools:Yy(e.model.compatibility?.toolSchema,o,e.tools),toolChoice:t}:void 0,a=e.system.length===0?void 0:nb(o,e.system),l=yield*tb(e,o);return o.dropped>0&&(yield*r.logWarning(`Bedrock Converse: dropped ${o.dropped} cache breakpoint(s); the API allows at most ${en.BEDROCK_BREAKPOINT_CAP} per request.`)),{modelId:e.model.id,messages:l,system:a,inferenceConfig:n?.maxTokens===void 0&&n?.temperature===void 0&&n?.topP===void 0&&(n?.stop===void 0||n.stop.length===0)?void 0:{maxTokens:n?.maxTokens,temperature:n?.temperature,topP:n?.topP,stopSequences:n?.stop},toolConfig:s,additionalModelRequestFields:n?.topK===void 0?void 0:{top_k:n.topK}}}),rb=i(e=>e==="end_turn"||e==="stop_sequence"?"stop":e==="max_tokens"?"length":e==="tool_use"?"tool-calls":e==="content_filtered"||e==="guardrail_intervened"?"content-filter":"unknown","mapFinishReason"),sb=i(e=>{if(!e)return;let t=(e.cacheReadInputTokens??0)+(e.cacheWriteInputTokens??0),n=Ce.subtractTokens(e.inputTokens,t);return new Mn({inputTokens:e.inputTokens,outputTokens:e.outputTokens,nonCachedInputTokens:n,cacheReadInputTokens:e.cacheReadInputTokens,cacheWriteInputTokens:e.cacheWriteInputTokens,totalTokens:Ce.totalTokens(e.inputTokens,e.outputTokens,e.totalTokens),providerMetadata:{bedrock:e}})},"mapUsage"),ib=i((e,t)=>r.gen(function*(){if(t.contentBlockStart?.start?.toolUse){let n=t.contentBlockStart.contentBlockIndex,o=[],s=xt.stepStart(e.lifecycle,o);return[{...e,lifecycle:s,tools:Xo.start(e.tools,n,{id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})},[...o,rt.toolInputStart({id:t.contentBlockStart.start.toolUse.toolUseId,name:t.contentBlockStart.start.toolUse.name})]]}if(t.contentBlockDelta?.delta?.text){let n=[];return[{...e,lifecycle:xt.textDelta(e.lifecycle,n,`text-${t.contentBlockDelta.contentBlockIndex}`,t.contentBlockDelta.delta.text)},n]}if(t.contentBlockDelta?.delta?.reasoningContent){let n=t.contentBlockDelta.contentBlockIndex,o=t.contentBlockDelta.delta.reasoningContent,s=[];return[{...e,lifecycle:o.text?xt.reasoningDelta(e.lifecycle,s,`reasoning-${n}`,o.text):e.lifecycle,reasoningSignatures:o.signature?{...e.reasoningSignatures,[n]:o.signature}:e.reasoningSignatures},s]}if(t.contentBlockDelta?.delta?.toolUse){let n=t.contentBlockDelta.contentBlockIndex,o=Xo.appendExisting(ls,e.tools,n,t.contentBlockDelta.delta.toolUse.input,"Bedrock Converse tool delta is missing its tool call");if(Xo.isError(o))return yield*o;let s=[],a=o.events.length?xt.stepStart(e.lifecycle,s):e.lifecycle;return s.push(...o.events),[{...e,lifecycle:a,tools:o.tools},s]}if(t.contentBlockStop){let n=t.contentBlockStop.contentBlockIndex,o=yield*Xo.finish(ls,e.tools,n),s=[],a=o.events??[],l=a.length?xt.stepStart(e.lifecycle,s):xt.reasoningEnd(xt.textEnd(e.lifecycle,s,`text-${n}`),s,`reasoning-${n}`,e.reasoningSignatures[n]?Ky({signature:e.reasoningSignatures[n]}):void 0);return s.push(...a),[{...e,hasToolCalls:a.some(rt.is.toolCall)?!0:e.hasToolCalls,lifecycle:l,tools:o.tools,reasoningSignatures:Object.fromEntries(Object.entries(e.reasoningSignatures).filter(([d])=>d!==String(n)))},s]}if(t.messageStop)return[{...e,pendingFinish:{reason:rb(t.messageStop.stopReason),usage:e.pendingFinish?.usage}},[]];if(t.metadata){let n=sb(t.metadata.usage);return[{...e,pendingFinish:{reason:e.pendingFinish?.reason??"stop",usage:n}},[]]}if(t.internalServerException||t.modelStreamErrorException||t.serviceUnavailableException){let n=t.internalServerException?.message??t.modelStreamErrorException?.message??t.serviceUnavailableException?.message??"Bedrock Converse stream error";return[e,[rt.providerError({message:n,retryable:!0})]]}if(t.validationException||t.throttlingException){let n=t.validationException?.message??t.throttlingException?.message??"Bedrock Converse error";return[e,[rt.providerError({message:n,classification:t.validationException&&au(n)?"context-overflow":void 0,retryable:t.throttlingException!==void 0})]]}return[e,[]]}),"step"),ab=cs.framing(ls),cb=i(e=>e.pendingFinish?(()=>{let t=[];return xt.finish(e.lifecycle,t,{reason:e.pendingFinish.reason==="stop"&&e.hasToolCalls?"tool-calls":e.pendingFinish.reason,usage:e.pendingFinish.usage}),t})():[],"onHalt"),lb=fo.make({id:ls,body:{schema:Vy,from:ob},stream:{event:Gy,initial:i(()=>({tools:Xo.empty(),pendingFinish:void 0,hasToolCalls:!1,lifecycle:xt.initial(),reasoningSignatures:{}}),"initial"),step:ib,onHalt:cb}}),mc=Jo.make({id:ls,provider:"bedrock",protocol:lb,endpoint:Yo.path(({body:e})=>`/model/${encodeURIComponent(e.modelId)}/converse-stream`),auth:ar.auth,framing:ab}),Tp=ar.sigV4;var hc=lt.make("amazon-bedrock"),db=[mc],ub=i(e=>`https://bedrock-runtime.${e}.amazonaws.com`,"bedrockBaseURL"),pb=i(e=>{let{apiKey:t,credentials:n,region:o,baseURL:s,...a}=e,l=o??n?.region??"us-east-1";return mc.with({...a,provider:hc,endpoint:{baseURL:s??ub(l)},auth:t===void 0?Tp(n):gt.bearer(t)})},"configuredRoute"),gc=i((e={})=>{let t=pb(e);return{id:hc,model:i(n=>t.model({id:n}),"model"),configure:gc}},"configure"),Rp=gc(),fb=Rp.model;var Ri={};fe(Ri,{configure:()=>wc,id:()=>ds,provider:()=>Sb,routes:()=>wb});var mb=i(e=>Object.entries(e).filter(t=>t[1]!==void 0),"definedEntries"),Cp=i(e=>{let t=Object.fromEntries(mb({store:e?.store,promptCacheKey:e?.promptCacheKey,reasoningEffort:e?.reasoningEffort,reasoningSummary:e?.reasoningSummary,include:e?.include,textVerbosity:e?.textVerbosity,serviceTier:e?.serviceTier}));if(Object.keys(t).length!==0)return{openai:t}},"openAIProviderOptions"),hb=i((e,t={})=>{let n=e.toLowerCase();if(!(!n.includes("gpt-5")||n.includes("gpt-5-chat")||n.includes("gpt-5-pro")))return Cp({reasoningEffort:"medium",reasoningSummary:"auto",include:["reasoning.encrypted_content"],textVerbosity:t.textVerbosity===!0&&n.includes("gpt-5.")&&!n.includes("codex")&&!n.includes("-chat")?"low":void 0})},"gpt5DefaultOptions"),gb=i((e,t={})=>Ba(Cp({store:!1}),hb(e,t)),"openAIDefaultOptions"),Zn=i((e,t,n={})=>({...t,providerOptions:Ba(gb(e,n),t.providerOptions)}),"withOpenAIOptions");var ds=lt.make("azure"),Mp=gt.remove("authorization"),bb=i(e=>`https://${e.trim()}.openai.azure.com/openai/v1`,"resourceBaseURL"),_p=On.with({id:"azure-openai-responses",provider:ds,auth:Mp,endpoint:{query:{"api-version":"v1"}}}),Op=yo.with({id:"azure-openai-chat",provider:ds,auth:Mp,endpoint:{query:{"api-version":"v1"}}}),wb=[_p,Op],vb=i(e=>{let{apiKey:t,apiVersion:n,resourceName:o,useCompletionUrls:s,baseURL:a,queryParams:l,...d}=e;if("auth"in d){let{auth:p,...f}=d;return f}return d},"defaults"),xb=i(e=>"auth"in e&&e.auth?e.auth:gt.remove("authorization").andThen(gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("AZURE_OPENAI_API_KEY")).pipe(gt.header("api-key"))),"auth"),Ap=i((e,t)=>e.with({auth:xb(t),endpoint:{baseURL:t.baseURL??bb(t.resourceName),query:{...t.apiVersion?{"api-version":t.apiVersion}:{},...t.queryParams}}}),"configuredRoute"),wc=i(e=>{let t=Ap(_p,e),n=Ap(Op,e),o=vb(e),s=i(l=>t.with(Zn(l,o)).model({id:l}),"responses"),a=i(l=>n.with(Zn(l,o)).model({id:l}),"chat");return{id:ds,model:i(l=>e.useCompletionUrls===!0?a(l):s(l),"model"),responses:s,chat:a,configure:wc}},"configure"),Sb={id:ds,configure:wc};var Ib=lt.make("cloudflare-ai-gateway"),kb=lt.make("cloudflare-workers-ai");var aR=Jn.with({id:"cloudflare-ai-gateway",provider:Ib}),cR=Jn.with({id:"cloudflare-workers-ai",provider:kb});var Np=lt.make("github-copilot");var fR=yo.with({provider:Np}),mR=On.with({provider:Np});var Ci={};fe(Ci,{configure:()=>xc,id:()=>qp,model:()=>iw,provider:()=>Wp,routes:()=>ow});var jp="gemini",Up=new Set(Ce.MEDIA_MIMES),Tb="https://generativelanguage.googleapis.com/v1beta",Pb=c.Struct({text:c.String,thought:c.optional(c.Boolean),thoughtSignature:c.optional(c.String)}),Rb=c.Struct({inlineData:c.Struct({mimeType:c.String,data:c.String})}),Cb=c.Struct({functionCall:c.Struct({name:c.String,args:c.Unknown}),thoughtSignature:c.optional(c.String)}),Ab=c.Struct({functionResponse:c.Struct({name:c.String,response:c.Unknown})}),Mb=c.Union([Pb,Rb,Cb,Ab]),Fp=c.Struct({role:c.Literals(["user","model"]),parts:c.Array(Mb)}),_b=c.Struct({parts:c.Array(c.Struct({text:c.String}))}),Ob=c.Struct({name:c.String,description:c.String,parameters:c.optional(es)}),Lb=c.Struct({functionDeclarations:c.Array(Ob)}),Nb=c.Struct({functionCallingConfig:c.Struct({mode:c.Literals(["AUTO","NONE","ANY"]),allowedFunctionNames:Gn(c.String)})}),jb=c.Struct({thinkingBudget:c.optional(c.Number),includeThoughts:c.optional(c.Boolean)}),Ub=c.Struct({maxOutputTokens:c.optional(c.Number),temperature:c.optional(c.Number),topP:c.optional(c.Number),topK:c.optional(c.Number),stopSequences:Gn(c.String),thinkingConfig:c.optional(jb)}),Fb={contents:c.Array(Fp),systemInstruction:c.optional(_b),tools:Gn(Lb),toolConfig:c.optional(Nb),generationConfig:c.optional(Ub)},Bb=c.Struct(Fb),$b=c.Struct({cachedContentTokenCount:c.optional(c.Number),thoughtsTokenCount:c.optional(c.Number),promptTokenCount:c.optional(c.Number),candidatesTokenCount:c.optional(c.Number),totalTokenCount:c.optional(c.Number)}),qb=c.Struct({content:c.optional(Fp),finishReason:c.optional(c.String)}),Wb=c.Struct({candidates:Gn(qb),usageMetadata:c.optional($b)}),Vb=i((e,t)=>({name:e.name,description:e.description,parameters:Su.convert(t)}),"lowerTool"),zb=i(e=>Ce.matchToolChoice("Gemini",e,{auto:i(()=>({functionCallingConfig:{mode:"AUTO"}}),"auto"),none:i(()=>({functionCallingConfig:{mode:"NONE"}}),"none"),required:i(()=>({functionCallingConfig:{mode:"ANY"}}),"required"),tool:i(t=>({functionCallingConfig:{mode:"ANY",allowedFunctionNames:[t]}}),"tool")}),"lowerToolConfig"),Gb=r.fn("Gemini.lowerUserPart")(function*(e){if(e.type==="text")return{text:e.text};let t=yield*Ce.validateMedia("Gemini",e,Up);return{inlineData:{mimeType:t.mime,data:t.base64}}}),us=i(e=>({google:e}),"googleMetadata"),Bp=i(e=>{let t=e?.google;return Ce.isRecord(t)&&typeof t.thoughtSignature=="string"?t.thoughtSignature:void 0},"thoughtSignature"),Hb=i(e=>({functionCall:{name:e.name,args:e.input},thoughtSignature:Bp(e.providerMetadata)}),"lowerToolCall"),Yb=r.fn("Gemini.lowerMessages")(function*(e){let t=[];for(let n of e.messages){if(n.role==="system"){let s=yield*Ce.wrappedSystemUpdate("Gemini",n),a=t.at(-1);a?.role==="user"?t[t.length-1]={role:"user",parts:[...a.parts,{text:s.text}]}:t.push({role:"user",parts:[{text:s.text}]});continue}if(n.role==="user"){let s=[];for(let a of n.content){if(!Ce.supportsContent(a,["text","media"]))return yield*Ce.unsupportedContent("Gemini","user",["text","media"]);s.push(yield*Gb(a))}t.push({role:"user",parts:s});continue}if(n.role==="assistant"){let s=[];for(let a of n.content){if(!Ce.supportsContent(a,["text","reasoning","tool-call"]))return yield*Ce.unsupportedContent("Gemini","assistant",["text","reasoning","tool-call"]);if(a.type==="text"){s.push({text:a.text});continue}if(a.type==="reasoning"){s.push({text:a.text,thought:!0,thoughtSignature:Bp(a.providerMetadata)});continue}if(a.type==="tool-call"){s.push(Hb(a));continue}}t.push({role:"model",parts:s});continue}let o=[];for(let s of n.content){if(!Ce.supportsContent(s,["tool-result"]))return yield*Ce.unsupportedContent("Gemini","tool",["tool-result"]);if(s.result.type!=="content"){o.push({functionResponse:{name:s.name,response:{name:s.name,content:Ce.toolResultText(s)}}});continue}let a=s.result.value,l=a.filter(d=>d.type==="text").map(d=>d.text);o.push({functionResponse:{name:s.name,response:{name:s.name,content:l.join(`
49
+ `)}}});for(let d of a){if(d.type==="text")continue;let p=yield*Ce.validateToolFile("Gemini",d,Up);o.push({inlineData:{mimeType:p.mime,data:p.base64}})}}t.push({role:"user",parts:o})}return t}),Jb=i(e=>e.providerOptions?.gemini,"geminiOptions"),Kb=i(e=>{let t=Jb(e)?.thinkingConfig;if(!Ce.isRecord(t))return;let n={thinkingBudget:typeof t.thinkingBudget=="number"?t.thinkingBudget:void 0,includeThoughts:typeof t.includeThoughts=="boolean"?t.includeThoughts:void 0};return Object.values(n).some(o=>o!==void 0)?n:void 0},"thinkingConfig"),Xb=r.fn("Gemini.fromRequest")(function*(e){let t=e.tools.length>0&&e.toolChoice?.type!=="none",n=e.generation,o=e.model.compatibility?.toolSchema,s={maxOutputTokens:n?.maxTokens,temperature:n?.temperature,topP:n?.topP,topK:n?.topK,stopSequences:n?.stop,thinkingConfig:Kb(e)};return{contents:yield*Yb(e),systemInstruction:e.system.length===0?void 0:{parts:[{text:Ce.joinText(e.system)}]},tools:t?[{functionDeclarations:e.tools.map(a=>Vb(a,si.modelCompatibility(a.inputSchema,o)))}]:void 0,toolConfig:t&&e.toolChoice?yield*zb(e.toolChoice):void 0,generationConfig:Object.values(s).some(a=>a!==void 0)?s:void 0}}),Qb=i(e=>{if(!e)return;let t=e.cachedContentTokenCount,n=Ce.subtractTokens(e.promptTokenCount,t),o=e.candidatesTokenCount!==void 0?e.candidatesTokenCount+(e.thoughtsTokenCount??0):void 0;return new Mn({inputTokens:e.promptTokenCount,outputTokens:o,nonCachedInputTokens:n,cacheReadInputTokens:t,reasoningTokens:e.thoughtsTokenCount,totalTokens:Ce.totalTokens(e.promptTokenCount,o,e.totalTokenCount),providerMetadata:{google:e}})},"mapUsage"),Zb=i((e,t)=>e==="STOP"?t?"tool-calls":"stop":e==="MAX_TOKENS"?"length":e==="IMAGE_SAFETY"||e==="RECITATION"||e==="SAFETY"||e==="BLOCKLIST"||e==="PROHIBITED_CONTENT"||e==="SPII"?"content-filter":e==="MALFORMED_FUNCTION_CALL"?"error":"unknown","mapFinishReason"),ew=i(e=>e.finishReason||e.usage?(()=>{let t=[],n=e.reasoningSignature?xt.reasoningEnd(e.lifecycle,t,"reasoning-0",us({thoughtSignature:e.reasoningSignature})):e.lifecycle;return xt.finish(n,t,{reason:Zb(e.finishReason,e.hasToolCalls),usage:e.usage}),t})():[],"finish"),tw=i((e,t)=>{let n={...e,usage:t.usageMetadata?Qb(t.usageMetadata)??e.usage:e.usage},o=t.candidates?.[0];if(!o?.content)return r.succeed([{...n,finishReason:o?.finishReason??n.finishReason},[]]);let s=[],a=n.hasToolCalls,l=n.lifecycle,d=n.nextToolCallId,p=n.reasoningSignature;for(let f of o.content.parts){if("thoughtSignature"in f&&f.thoughtSignature&&"thought"in f&&f.thought&&(p=f.thoughtSignature),"text"in f&&f.text.length>0){if(f.thought){l=xt.reasoningDelta(l,s,"reasoning-0",f.text,f.thoughtSignature?us({thoughtSignature:f.thoughtSignature}):void 0);continue}l=xt.reasoningEnd(l,s,"reasoning-0",p?us({thoughtSignature:p}):void 0),l=xt.textDelta(l,s,"text-0",f.text);continue}if("functionCall"in f){let u=f.functionCall.args,g=`tool_${d++}`;l=xt.reasoningEnd(l,s,"reasoning-0",p?us({thoughtSignature:p}):void 0),l=xt.stepStart(l,s),s.push(rt.toolCall({id:g,name:f.functionCall.name,input:u,providerMetadata:f.thoughtSignature?us({thoughtSignature:f.thoughtSignature}):void 0})),a=!0}}return r.succeed([{...n,hasToolCalls:a,lifecycle:l,nextToolCallId:d,reasoningSignature:p,finishReason:o.finishReason??n.finishReason},s])},"step"),nw=fo.make({id:jp,body:{schema:Bb,from:Xb},stream:{event:fo.jsonEvent(Wb),initial:i(()=>({hasToolCalls:!1,nextToolCallId:0,lifecycle:xt.initial()}),"initial"),step:tw,onHalt:ew}}),vc=Jo.make({id:jp,provider:"google",protocol:nw,endpoint:Yo.path(({request:e})=>`/models/${e.model.id}:streamGenerateContent?alt=sse`,{baseURL:Tb}),auth:gt.none,framing:ti.sse});var qp=lt.make("google"),ow=[vc],rw=i(e=>"auth"in e&&e.auth?e.auth:gt.optional("apiKey"in e?e.apiKey:void 0,"apiKey").orElse(gt.config("GOOGLE_GENERATIVE_AI_API_KEY")).pipe(gt.header("x-goog-api-key")),"auth"),sw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return vc.with({...s,endpoint:{baseURL:o},auth:rw(e)})},"configuredRoute"),xc=i((e={})=>{let t=sw(e);return{id:qp,model:i(n=>t.model({id:n}),"model"),configure:xc}},"configure"),Wp=xc(),iw=Wp.model;var Ai={};fe(Ai,{chat:()=>fw,configure:()=>Ic,id:()=>Vp,model:()=>dw,provider:()=>ps,responses:()=>uw,responsesWebSocket:()=>pw,routes:()=>aw});var Vp=lt.make("openai"),aw=[On,za,yo],cw=i(e=>Sn.bearer(e,"OPENAI_API_KEY"),"auth"),lw=i(e=>{let{apiKey:t,auth:n,baseURL:o,queryParams:s,...a}=e;return a},"defaults"),Sc=i((e,t)=>e.with({auth:cw(t),endpoint:{baseURL:t.baseURL,query:t.queryParams}}),"configuredRoute"),Ic=i((e={})=>{let t=Sc(On,e),n=Sc(za,e),o=Sc(yo,e),s=lw(e),a=i(p=>t.with(Zn(p,s,{textVerbosity:!0})).model({id:p}),"responses");return{id:Vp,model:a,responses:a,responsesWebSocket:i(p=>n.with(Zn(p,s,{textVerbosity:!0})).model({id:p}),"responsesWebSocket"),chat:i(p=>o.with(Zn(p,s)).model({id:p}),"chat"),configure:Ic}},"configure"),ps=Ic(),dw=ps.model,uw=ps.responses,pw=ps.responsesWebSocket,fw=ps.chat;var _i={};fe(_i,{baseten:()=>gw,cerebras:()=>yw,configure:()=>Mi,deepinfra:()=>bw,deepseek:()=>ww,fireworks:()=>vw,groq:()=>xw,id:()=>Gp,provider:()=>hw,routes:()=>mw,togetherai:()=>Sw});var Gt={baseten:{provider:"baseten",baseURL:"https://inference.baseten.co/v1"},cerebras:{provider:"cerebras",baseURL:"https://api.cerebras.ai/v1"},deepinfra:{provider:"deepinfra",baseURL:"https://api.deepinfra.com/v1/openai"},deepseek:{provider:"deepseek",baseURL:"https://api.deepseek.com/v1"},fireworks:{provider:"fireworks",baseURL:"https://api.fireworks.ai/inference/v1"},groq:{provider:"groq",baseURL:"https://api.groq.com/openai/v1"},openrouter:{provider:"openrouter",baseURL:"https://openrouter.ai/api/v1"},togetherai:{provider:"togetherai",baseURL:"https://api.together.xyz/v1"},xai:{provider:"xai",baseURL:"https://api.x.ai/v1"}},LR=Object.fromEntries(Object.values(Gt).map(e=>[e.provider,e]));var Gp=lt.make("openai-compatible"),mw=[Jn],Mi=i(e=>{let t=e.provider??"openai-compatible",{provider:n,baseURL:o,apiKey:s,auth:a,...l}=e,d=Jn.with({...l,provider:t,endpoint:{baseURL:o},auth:Sn.bearer(e,[])});return{id:lt.make(t),model:i(p=>d.model({id:p,provider:lt.make(t)}),"model"),configure:Mi}},"configure"),Io=i(e=>{let t=i((n={})=>{let o=Mi({...n,baseURL:n.baseURL??e.baseURL,provider:e.provider});return{id:lt.make(e.provider),model:o.model,configure:t}},"configureProfile");return t()},"define"),hw={id:Gp,configure:Mi},gw=Io(Gt.baseten),yw=Io(Gt.cerebras),bw=Io(Gt.deepinfra),ww=Io(Gt.deepseek),vw=Io(Gt.fireworks),xw=Io(Gt.groq),Sw=Io(Gt.togetherai);var Oi={};fe(Oi,{configure:()=>Dc,id:()=>Hp,model:()=>Pw,profile:()=>fs,protocol:()=>Yp,provider:()=>Jp,route:()=>kc,routes:()=>Ew});var fs=Gt.openrouter,Hp=lt.make(fs.provider),Iw="openrouter",kw=c.StructWithRest(c.Struct(Iu),[c.Record(c.String,c.Any)]),Yp=fo.make({id:"openrouter-chat",body:{schema:kw,from:i(e=>Va.body.from(e).pipe(r.map(t=>({...t,...Dw(e.providerOptions?.openrouter)}))),"from")},stream:Va.stream}),Dw=i(e=>{let t=ei(e)?e:{};return{...t.usage===!0?{usage:{include:!0}}:ei(t.usage)?{usage:t.usage}:{},...ei(t.reasoning)?{reasoning:t.reasoning}:{},...typeof t.promptCacheKey=="string"?{prompt_cache_key:t.promptCacheKey}:{}}},"bodyOptions"),kc=Jo.make({id:Iw,provider:fs.provider,protocol:Yp,endpoint:Yo.path("/chat/completions",{baseURL:fs.baseURL}),framing:ti.sse}),Ew=[kc],Tw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return kc.with({...s,endpoint:{baseURL:o??fs.baseURL},auth:Sn.bearer(e,"OPENROUTER_API_KEY")})},"configuredRoute"),Dc=i((e={})=>{let t=Tw(e);return{id:Hp,model:i(n=>t.model({id:n}),"model"),configure:Dc}},"configure"),Jp=Dc(),Pw=Jp.model;var Ec=lt.make("xai");var Kp=i(e=>Sn.bearer(e,"XAI_API_KEY"),"auth"),Rw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return On.with({...s,provider:Ec,endpoint:{baseURL:o??Gt.xai.baseURL},auth:Kp(e)})},"configuredResponsesRoute"),Cw=i(e=>{let{apiKey:t,auth:n,baseURL:o,...s}=e;return Jn.with({...s,provider:Ec,endpoint:{baseURL:o??Gt.xai.baseURL},auth:Kp(e)})},"configuredChatRoute"),Xp=i((e={})=>{let t=Rw(e),n=Cw(e),o=i(a=>t.model({id:a}),"responses");return{id:Ec,model:o,responses:o,chat:i(a=>n.model({id:a}),"chat"),configure:Xp}},"configure"),Tc=Xp(),XR=Tc.model,QR=Tc.responses,ZR=Tc.chat;var Qp=i(e=>{if(!ut(e))return;let t=Object.fromEntries(Object.entries(e).filter(n=>ut(n[1])));return Object.keys(t).length===0?void 0:t},"providerMetadata"),Li=i(e=>Qp(e.providerMetadata)??Qp(e.providerOptions),"partProviderMetadata"),Mw=i(e=>({type:"text",text:typeof e.text=="string"?e.text:"",providerMetadata:Li(e)}),"textPart"),_w=i(e=>{if(typeof e.data!="string"&&!(e.data instanceof Uint8Array))throw new Error("Native LLM request adapter only supports file parts with string or Uint8Array data");return{type:"media",mediaType:typeof e.mediaType=="string"?e.mediaType:"application/octet-stream",data:e.data,filename:typeof e.filename=="string"?e.filename:void 0}},"mediaPart"),Ow=i(e=>{let t=ut(e.output)?e.output:{type:"json",value:e.output},n=t.type==="text"?"text":t.type==="error-text"?"error":"json";return nu.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",result:"value"in t?t.value:t,resultType:n,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:Li(e)})},"toolResult"),Lw=i(e=>{if(!ut(e))throw new Error("Native LLM request adapter only supports object content parts");if(e.type==="text")return Mw(e);if(e.type==="file")return _w(e);if(e.type==="reasoning")return{type:"reasoning",text:typeof e.text=="string"?e.text:"",providerMetadata:Li(e)};if(e.type==="tool-call")return tu.make({id:typeof e.toolCallId=="string"?e.toolCallId:"",name:typeof e.toolName=="string"?e.toolName:"",input:e.input,providerExecuted:typeof e.providerExecuted=="boolean"?e.providerExecuted:void 0,providerMetadata:Li(e)});if(e.type==="tool-result")return Ow(e);throw new Error(`Native LLM request adapter does not support ${String(e.type)} content parts`)},"contentPart"),Nw=i(e=>typeof e=="string"?[{type:"text",text:e}]:e.map(Lw),"content"),jw=i(e=>{let t=e.flatMap(o=>o.role==="system"?[$a.make(o.content)]:[]),n=e.flatMap(o=>o.role==="system"?[]:[ou.make({role:o.role,content:Nw(o.content),native:ut(o.providerOptions)?{providerOptions:o.providerOptions}:void 0})]);return{system:t,messages:n}},"messages"),Uw=i(e=>ut(e)?ut(e.jsonSchema)?e.jsonSchema:e:{type:"object",properties:{}},"schema"),Fw=i(e=>Object.entries(e??{}).map(([t,n])=>ru.make({name:t,description:n.description??"",inputSchema:Uw(n.inputSchema)})),"tools"),Bw=i(e=>{let t={temperature:e.temperature,topP:e.topP,topK:e.topK,maxTokens:e.maxOutputTokens};return Object.values(t).some(n=>n!==void 0)?t:void 0},"generation"),$w=i(e=>"model"in e?e.baseURL??(e.model.api.url||void 0):e.api.url||void 0,"baseURL"),Zp=i((e,t)=>{if(t)return t;throw new Error(`Native LLM request adapter requires a base URL for ${e.providerID}/${e.id}`)},"requireBaseURL"),ef=i((e,t)=>{let n="model"in e?e.model:e,o=$w(e),s={..."model"in e&&e.apiKey?{apiKey:e.apiKey}:{},...o?{baseURL:o}:{},headers:Object.keys({...n.headers,...t}).length===0?void 0:{...n.headers,...t},limits:{context:n.limit.context,output:n.limit.output}};if(n.api.npm==="@ai-sdk/openai")return Ai.configure(s).responses(n.api.id);if(n.api.npm==="@ai-sdk/azure")return Ri.configure({...s,baseURL:Zp(n,o)}).responses(n.api.id);if(n.api.npm==="@ai-sdk/anthropic")return Ei.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/google")return Ci.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/amazon-bedrock")return Pi.configure(s).model(n.api.id);if(n.api.npm==="@ai-sdk/openai-compatible")return _i.configure({...s,provider:String(n.providerID),baseURL:Zp(n,o)}).model(n.api.id);if(n.api.npm==="@openrouter/ai-sdk-provider")return Oi.configure(s).model(n.api.id);throw new Error(`Native LLM request adapter does not support provider package ${n.api.npm}`)},"model"),qw=i(e=>{let t=jw(e.messages);return wu.request({model:ef(e,e.headers),system:[...(e.system??[]).map($a.make),...t.system],messages:t.messages,tools:Fw(e.tools),toolChoice:e.toolChoice,generation:Bw(e),providerOptions:e.providerOptions})},"request");function Ww(e){return tf(e,nf(e))}i(Ww,"status");function tf(e,t){let n=e.model.providerID;if(n!=="openai"&&n!=="anthropic"&&!n.startsWith("opencode"))return{type:"unsupported",reason:"provider is not openai, opencode, or anthropic"};let o=e.model.api.npm;if(o!=="@ai-sdk/openai"&&o!=="@ai-sdk/openai-compatible"&&o!=="@ai-sdk/anthropic")return{type:"unsupported",reason:"provider package is not OpenAI, OpenAI-compatible, or Anthropic"};if(e.auth?.type==="oauth"&&!(e.provider.id==="openai"&&t))return{type:"unsupported",reason:"OAuth auth requires a provider fetch override"};let s=typeof e.provider.options.apiKey=="string"?e.provider.options.apiKey:e.provider.key;return s?{type:"supported",apiKey:s,baseURL:typeof e.provider.options.baseURL=="string"?e.provider.options.baseURL:void 0}:{type:"unsupported",reason:"API key is not configured"}}i(tf,"statusWithFetch");function Vw(e){let t=nf(e),n=tf(e,t);if(n.type==="unsupported")return n;let o=of(e.tools,e),s=ms.request({model:e.model,apiKey:n.apiKey,baseURL:n.baseURL,messages:Xe.message(e.messages,e.model,e.providerOptions??{}),toolChoice:e.toolChoice,temperature:e.temperature,topP:e.topP,topK:e.topK,maxOutputTokens:e.maxOutputTokens,providerOptions:Xe.providerOptions(e.model,e.providerOptions??{}),headers:{...zw(e.provider.options.headers),...e.headers}}),a=Gs(zs(r.gen(function*(){let l=yield*Ks.make(),d=yield*Yr.unbounded();return e.llmClient.stream(su.update(s,{tools:[...s.tools,...gu(o)]})).pipe(Hs(f=>f.type!=="tool-call"||f.providerExecuted?La(f):La(f).pipe(Ys(Oa(bu.dispatch(o,f).pipe(r.flatMap(u=>Yr.offerAll(d,u.events)),r.catchCause(u=>Yr.failCause(d,u)),r.asVoid,Ks.run(l,{startImmediately:!0})))))),Ys(Oa(Ks.awaitEmpty(l).pipe(r.andThen(Yr.end(d)),r.asVoid)))).pipe(Ys(_d(d)))})));return{...n,stream:t?a.pipe($d(zd.Fetch,t)):a}}i(Vw,"stream");function nf(e){if(e.provider.id!=="openai"||e.auth?.type!=="oauth")return;let t=e.provider.options.fetch;if(typeof t=="function")return t}i(nf,"providerFetch");function zw(e){if(ut(e))return Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}i(zw,"providerHeaders");function Gw(e){return!e||typeof e!="object"?{type:"object",properties:{}}:"jsonSchema"in e&&e.jsonSchema&&typeof e.jsonSchema=="object"?e.jsonSchema:fi(e).jsonSchema}i(Gw,"nativeSchema");function of(e,t){return Object.fromEntries(Object.entries(e).map(([n,o])=>[n,yu.make({description:o.description??"",jsonSchema:Gw(o.inputSchema),execute:i((s,a)=>r.tryPromise({try:i(()=>{if(!o.execute)throw new Error(`Tool has no execute handler: ${n}`);return o.execute(s,{toolCallId:a?.id??n,messages:t.messages,abortSignal:t.abort})},"try"),catch:i(l=>new iu({message:gn(l),error:l}),"catch")}),"execute")})]))}i(of,"nativeTools");var lr={};fe(lr,{LLMRequestPrep:()=>lr,hasToolCalls:()=>yf,prepare:()=>Xw});var eo={};fe(eo,{Service:()=>cr,SystemPrompt:()=>eo,node:()=>Kw,provider:()=>Hw});var rf=`You are OpenCode, the best coding agent on the planet.
50
50
 
51
51
  You are an interactive CLI tool that helps users with software engineering tasks. Use the instructions below and the tools available to you to assist the user.
52
52
 
@@ -983,10 +983,10 @@ assistant: Clients are marked as failed in the \`connectToServer\` function in s
983
983
  `))}let l=!e.small&&e.model.variants&&e.user.model.variant?e.model.variants[e.user.model.variant]:{},d=e.small?Xe.smallOptions(e.model):Xe.options({model:e.model,sessionID:e.sessionID,providerOptions:e.provider.options}),{cacheTtl:p,toolScopes:f,...u}=e.agent.options??{},g=Pc(Pc(Pc(d,e.model.options),u),l);e.model.api.npm==="@ai-sdk/azure"&&(e.provider.options.useCompletionUrls||e.model.options.useCompletionUrls||g.useCompletionUrls)&&(delete g.reasoningSummary,delete g.include),t&&(g.instructions=s.join(`
984
984
  `));let y=t||e.isWorkflow?e.messages:[...s.map(h=>({role:"system",content:h})),...e.messages],b=yield*e.plugin.trigger("chat.params",{sessionID:e.sessionID,agent:e.agent.name,model:e.model,provider:e.provider,message:e.user},{temperature:e.model.capabilities.temperature?e.agent.temperature??Xe.temperature(e.model):void 0,topP:e.agent.topP??Xe.topP(e.model),topK:Xe.topK(e.model),maxOutputTokens:Xe.maxOutputTokens(e.model,e.flags.outputTokenMax),options:g}),{headers:S}=yield*e.plugin.trigger("chat.headers",{sessionID:e.sessionID,agent:e.agent.name,model:e.model,provider:e.provider,message:e.user},{headers:{}}),T=Qw(e);if(e.model.api.npm==="@ai-sdk/openai"||e.model.api.npm==="@ai-sdk/azure"||e.model.api.npm==="@ai-sdk/amazon-bedrock/mantle")for(let h of Object.keys(T))T[h]={...T[h],strict:!1};e.model.providerID.includes("github-copilot")&&Object.keys(T).length===0&&yf(e.messages)&&(T._noop={description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:yn({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:i(async()=>({output:"",title:"",metadata:{}}),"execute")});let m=e.model.providerID.startsWith("opencode")?(yield*G.context).project.id:void 0;return{system:s,messages:y,tools:Object.fromEntries(Object.entries(T).toSorted(([h],[k])=>h.localeCompare(k))),params:b,messageTransformOptions:g,messageCacheTtl:p==="5m"?"5m":void 0,headers:{"x-opencode-session-id":e.sessionID,...e.parentSessionID?{"x-opencode-parent-session-id":e.parentSessionID}:{},...e.model.providerID.startsWith("opencode")?{...m?{"x-opencode-project":m}:{},"x-opencode-session":e.sessionID,"x-opencode-request":e.user.id,"x-opencode-client":e.flags.client,"User-Agent":hf}:{"x-session-affinity":e.sessionID,"X-Session-Id":e.sessionID,"User-Agent":hf},...e.parentSessionID?{"x-parent-session-id":e.parentSessionID}:{},...e.model.headers,...S}}});function Qw(e){let t=Ke.disabled(Object.keys(e.tools),Ke.merge(e.agent.permission,e.permission??[])),n=Go.filter(e.tools,(s,a)=>e.user.tools?.[a]!==!1&&!t.has(a)),o=e.agent.options?.toolScopes;return o?Go.map(n,(s,a)=>Zw(s,o[a],e.model)):n}i(Qw,"resolveTools");function Zw(e,t,n){let o=e;if(!t||!o.fieldTags||!o.jsonInputSchema)return e;let{description:s,schema:a}=Hu(e.description??"",o.jsonInputSchema,o.fieldTags,t);return{...e,description:s,inputSchema:yn(Xe.schema(n,a))}}i(Zw,"narrow");function yf(e){for(let t of e)if(Array.isArray(t.content)){for(let n of t.content)if(n.type==="tool-call"||n.type==="tool-result")return!0}return!1}i(yf,"hasToolCalls");var ev=Xe.OUTPUT_TOKEN_MAX,ko=class extends Re.Service()("@opencode/LLM"){static{i(this,"Service")}},tv=Wt(ko),nv=Te.effect(ko,r.gen(function*(){let e=yield*Xt.Service,t=yield*Oe.Service,n=yield*yt.Service,o=yield*pt.Service,s=yield*Ke.Service,a=yield*De.Service,l=yield*cu.Service,d=yield*Be.Service,p=r.fn("LLM.run")(function*(u){yield*r.logInfo("stream",{providerID:u.model.providerID,modelID:u.model.id,"session.id":u.sessionID,small:(u.small??!1).toString(),agent:u.agent.name,mode:u.agent.mode});let[g,y,b,S]=yield*r.all([n.getLanguage(u.model),t.get(),n.getProvider(u.model.providerID),e.get(u.model.providerID)],{concurrency:"unbounded"}),T=g instanceof Ga,m=yield*lr.prepare({...u,provider:b,auth:S,plugin:o,flags:d,isWorkflow:T});if(st.on()&&st.supports(u.model)&&u.model.providerID==="anthropic"&&S?.type==="oauth"){let I=st.relocate({system:m.system,messages:u.messages,append:!u.headers?.[st.HEADER]});I&&(I.added&&u.storeSystem&&(yield*u.storeSystem(I.added)),I.added&&st.log("system message",{"session.id":u.sessionID,chars:I.added.length,stored:!!u.storeSystem}),m={...m,system:I.system,messages:[...I.system.map(P=>({role:"system",content:P})),...I.messages]})}let h=yield*zt.make();if(g instanceof Ga){let I=g;I.sessionID=u.sessionID,I.systemPrompt=m.system.join(`
985
985
  `),I.toolExecutor=async(A,C,$)=>{let j=m.tools[A];if(!j||!j.execute)return{result:"",error:`Unknown tool: ${A}`};try{let z=await j.execute(JSON.parse(C),{toolCallId:$,messages:u.messages,abortSignal:u.abort});return{result:typeof z=="string"?z:z?.output??JSON.stringify(z),metadata:typeof z=="object"?z?.metadata:void 0,title:typeof z=="object"?z?.title:void 0}}catch(z){return{result:"",error:z.message??String(z)}}};let P=Ke.merge(u.agent.permission??[],u.permission??[]);I.sessionPreapprovedTools=Object.keys(m.tools).filter(A=>{let C=P.findLast($=>as.match(A,$.permission));return!C||C.action!=="ask"});let x=new Set;I.approvalHandler=h.bind(async A=>{let C=[...new Set(A.map(z=>z.name))];if(C.every(z=>x.has(z)))return{approved:!0};let $=ri.ID.ascending(),j;try{j=await h.promise(a.listen(L=>{if(L.type!==Ke.Event.Replied.type)return r.void;let V=L.data;return V.requestID!==$?r.void:(V.reply,r.void)}));let z=A.map(L=>{try{let V=JSON.parse(L.args),D=V?.title??V?.name??"";return D?`${L.name}: ${D}`:L.name}catch{return L.name}}),ie=[...new Set(z)];await h.promise(s.ask({id:$,sessionID:Pt.make(u.sessionID),permission:"workflow_tool_approval",patterns:ie,metadata:{tools:A},always:ie,ruleset:[]}));for(let L of C)x.add(L);return I.sessionPreapprovedTools=[...I.sessionPreapprovedTools??[],...C],{approved:!0}}catch{return{approved:!1}}finally{j&&await h.promise(j)}})}let k=y.experimental?.openTelemetry?Dd(yield*r.serviceOption(Du)):void 0,w=k?new Proxy(k,{get(I,P,x){return P!=="startSpan"?Reflect.get(I,P,x):(...A)=>{let C=I.startSpan(...A);return C.setAttribute("session.id",u.sessionID),C}}}):void 0;if(d.experimentalNativeLlm){let I=hs.stream({model:u.model,provider:b,auth:S,llmClient:l,messages:m.messages,tools:m.tools,toolChoice:u.toolChoice,temperature:m.params.temperature,topP:m.params.topP,topK:m.params.topK,maxOutputTokens:m.params.maxOutputTokens,providerOptions:m.params.options,headers:m.headers,abort:u.abort});if(I.type==="supported")return yield*r.logInfo("llm runtime selected",{"llm.runtime":"native","llm.provider":u.model.providerID,"llm.model":u.model.id}),{type:"native",stream:I.stream};yield*r.logInfo("llm runtime selected",{"llm.runtime":"ai-sdk","llm.provider":u.model.providerID,"llm.model":u.model.id,"llm.native_unsupported_reason":I.reason}),yield*r.logInfo("native runtime unavailable; falling back to ai-sdk",{providerID:u.model.providerID,modelID:u.model.id,"session.id":u.sessionID,small:(u.small??!1).toString(),agent:u.agent.name,mode:u.agent.mode,reason:I.reason})}return yield*r.logInfo("llm runtime selected",{"llm.runtime":"ai-sdk","llm.provider":u.model.providerID,"llm.model":u.model.id}),{type:"ai-sdk",result:$u({onError(I){h.fork(r.logError("stream error",{providerID:u.model.providerID,modelID:u.model.id,"session.id":u.sessionID,small:(u.small??!1).toString(),agent:u.agent.name,mode:u.agent.mode,error:I}))},includeRawChunks:u.model.providerID.includes("github-copilot"),async experimental_repairToolCall(I){let P=I.toolCall.toolName.toLowerCase();if(!m.tools[I.toolCall.toolName]&&!m.tools[P]){let x=P.replace(/^(?:mcp_|alchemy_)+/,""),A=Object.keys(m.tools).filter(C=>C===x||C.endsWith(`_${x}`));if(x&&A.length===1)return{...I.toolCall,toolName:A[0]}}return P!==I.toolCall.toolName&&m.tools[P]?{...I.toolCall,toolName:P}:{...I.toolCall,input:JSON.stringify({tool:I.toolCall.toolName,error:I.error.message}),toolName:"invalid"}},temperature:m.params.temperature,topP:m.params.topP,topK:m.params.topK,providerOptions:Xe.providerOptions(u.model,m.params.options),activeTools:Object.keys(m.tools).filter(I=>I!=="invalid"),tools:m.tools,toolChoice:u.toolChoice,maxOutputTokens:m.params.maxOutputTokens,abortSignal:u.abort,headers:u.headers?{...m.headers,...u.headers}:m.headers,maxRetries:u.retries??0,messages:m.messages,model:qu({model:g,middleware:[{specificationVersion:"v3",async transformParams(I){return I.type==="stream"&&(I.params.prompt=Xe.message(I.params.prompt,u.model,m.messageTransformOptions,{messageCacheTtl:m.messageCacheTtl,points:u.cachePoints})),I.params}}]}),experimental_telemetry:{isEnabled:y.experimental?.openTelemetry,functionId:"session.llm",tracer:w,metadata:{userId:y.username??"unknown",sessionId:u.sessionID}}})}}),f=i(u=>Gs(zs(r.gen(function*(){let g=yield*r.acquireRelease(r.sync(()=>new AbortController),S=>r.sync(()=>S.abort()));yield*r.logInfo("llm stream start",{providerID:u.model.providerID,modelID:u.model.id});let y=yield*p({...u,abort:g.signal});if(y.type==="native")return y.stream;let b=ir.adapterState();return Od(y.result.fullStream,S=>S instanceof Error?S:new Error(String(S))).pipe(Nd(S=>ir.toLLMEvents(b,S)),Hs(S=>Md(S)))}))),"stream");return ko.of({stream:f})})),ov=lr.hasToolCalls,rv=ke.make({service:ko,layer:nv,deps:[Xt.node,Oe.node,yt.node,pt.node,Ke.node,De.node,lu,Be.node]});var un={};fe(un,{DiffInput:()=>av,Service:()=>dr,SessionSummary:()=>un,node:()=>cv});function sv(e){if(!e.startsWith('"')||!e.endsWith('"'))return e;let t=e.slice(1,-1),n=[];for(let o=0;o<t.length;o++){let s=t[o];if(s!=="\\"){n.push(s.charCodeAt(0));continue}let a=t[o+1];if(!a){n.push(92);continue}if(a>="0"&&a<="7"){let p=t.slice(o+1,o+4).match(/^[0-7]{1,3}/);if(!p){n.push(a.charCodeAt(0)),o++;continue}n.push(parseInt(p[0],8)),o+=p[0].length;continue}let l=a==="n"?`
986
- `:a==="r"?"\r":a==="t"?" ":a==="b"?"\b":a==="f"?"\f":a==="v"?"\v":a==="\\"||a==='"'?a:void 0;n.push((l??a).charCodeAt(0)),o++}return Buffer.from(n).toString()}i(sv,"unquoteGitPath");var dr=class extends Re.Service()("@opencode/SessionSummary"){static{i(this,"Service")}},iv=Te.effect(dr,r.gen(function*(){let e=yield*me.Service,t=yield*an.Service,n=yield*De.Service,o=yield*Oe.Service,s=r.fn("SessionSummary.computeDiff")(function*(d){let p,f;for(let u of d.messages){if(!p){for(let g of u.parts)if(g.type==="step-start"&&g.snapshot){p=g.snapshot;break}}for(let g of u.parts)g.type==="step-finish"&&g.snapshot&&(f=g.snapshot)}return p&&f?yield*t.diffFull(p,f):[]}),a=r.fn("SessionSummary.summarize")(function*(d){if(yield*e.setSummary({sessionID:d.sessionID,summary:{additions:0,deletions:0,files:0}}),yield*n.publish(me.Event.Diff,{sessionID:d.sessionID,diff:[]}),(yield*o.get()).snapshot===!1)return;let p=yield*e.messages({sessionID:d.sessionID}).pipe(r.orDie);if(!p.length)return;let f=p.filter(y=>y.info.id===d.messageID||y.info.role==="assistant"&&y.info.parentID===d.messageID),u=f.find(y=>y.info.id===d.messageID);if(!u||u.info.role!=="user")return;let g=yield*s({messages:f});u.info.summary={...u.info.summary,diffs:g},yield*e.updateMessage(u.info)}),l=r.fn("SessionSummary.diff")(function*(d){if(!d.messageID)return[];let p=(yield*e.messages({sessionID:d.sessionID}).pipe(r.orDie)).find(u=>u.info.id===d.messageID);return!p||p.info.role!=="user"?[]:(p.info.summary?.diffs??[]).map(u=>{if(u.file===void 0)return u;let g=sv(u.file);return g===u.file?u:{...u,file:g}})});return dr.of({summarize:a,diff:l,computeDiff:s})})),av=c.Struct({sessionID:Pt,messageID:c.optional(at)}),cv=ke.make({service:dr,layer:iv,deps:[me.node,an.node,De.node,Oe.node]});var jn={};fe(jn,{Service:()=>hr,SessionProcessor:()=>jn,node:()=>Ev});var bn={};fe(bn,{DecodeError:()=>Ui,Image:()=>bn,InvalidDataUrlError:()=>ji,ResizerUnavailableError:()=>Ni,Service:()=>ur,SizeError:()=>gs,node:()=>yv});import lv from"node:path";import{fileURLToPath as dv}from"node:url";var uv=5*1024*1024,pv=2e3,fv=2e3,mv=!0,hv=[80,85,70,55,40],Ni=class extends c.TaggedErrorClass()("ImageResizerUnavailableError",{}){static{i(this,"ResizerUnavailableError")}get message(){return"Image resizer is unavailable"}},ji=class extends c.TaggedErrorClass()("ImageInvalidDataUrlError",{url:c.String}){static{i(this,"InvalidDataUrlError")}get message(){return"Image URL must be a base64 data URL"}},Ui=class extends c.TaggedErrorClass()("ImageDecodeError",{}){static{i(this,"DecodeError")}get message(){return"Image could not be decoded"}},gs=class extends c.TaggedErrorClass()("ImageSizeError",{bytes:c.Number,max:c.Number,width:c.Number,height:c.Number,max_width:c.Number,max_height:c.Number}){static{i(this,"SizeError")}get message(){return`Image ${this.width}x${this.height} with base64 size ${this.bytes} exceeds configured limits and could not be resized below ${this.max_width}x${this.max_height}/${this.max} bytes`}},ur=class extends Re.Service()("@opencode/Image"){static{i(this,"Service")}},gv=Te.effect(ur,r.gen(function*(){let e=yield*Oe.Service,t=yield*r.cached(r.sync(()=>{globalThis.__OPENCODE_PHOTON_WASM_PATH=lv.isAbsolute(oi)?oi:dv(new URL(oi,import.meta.url))}).pipe(r.andThen(()=>r.tryPromise(()=>import("@silvia-odwyer/photon-node"))),r.tapError(o=>r.logWarning("failed to load photon",{error:o})),r.mapError(()=>new Ni))),n=r.fn("Image.normalize")(function*(o){let s=(yield*e.get()).attachment?.image,a={autoResize:s?.auto_resize??mv,maxWidth:s?.max_width??pv,maxHeight:s?.max_height??fv,maxBase64Bytes:s?.max_base64_bytes??uv};if(!o.url.startsWith("data:")||!o.url.includes(";base64,"))return yield*new ji({url:o.url});let l=o.url.slice(o.url.indexOf(";base64,")+8),d=Buffer.byteLength(l,"utf8"),p=yield*t,f=yield*r.try({try:i(()=>p.PhotonImage.new_from_byteslice(Buffer.from(l,"base64")),"try"),catch:i(()=>new Ui,"catch")}).pipe(r.tapError(u=>r.logWarning("failed to decode image",{error:u})));try{let u=f.get_width(),g=f.get_height();if(u<=a.maxWidth&&g<=a.maxHeight&&d<=a.maxBase64Bytes)return o;if(!a.autoResize)return yield*new gs({bytes:d,max:a.maxBase64Bytes,width:u,height:g,max_width:a.maxWidth,max_height:a.maxHeight});let y=Math.min(1,a.maxWidth/u,a.maxHeight/g);for(let b of Array.from({length:32}).reduce(S=>{let T=S.at(-1)??{width:Math.max(1,Math.round(u*y)),height:Math.max(1,Math.round(g*y))},m=S.length===0?T:{width:T.width===1?1:Math.max(1,Math.floor(T.width*.75)),height:T.height===1?1:Math.max(1,Math.floor(T.height*.75))};return S.some(h=>h.width===m.width&&h.height===m.height)?S:[...S,m]},[])){let S=p.resize(f,b.width,b.height,p.SamplingFilter.Lanczos3),T=[{data:Buffer.from(S.get_bytes()).toString("base64"),mime:"image/png"},...hv.map(m=>({data:Buffer.from(S.get_bytes_jpeg(m)).toString("base64"),mime:"image/jpeg"}))].map(m=>({...m,bytes:Buffer.byteLength(m.data,"utf8")})).find(m=>m.bytes<=a.maxBase64Bytes);if(S.free(),T)return yield*r.logInfo("using resized image",{from_mime:o.mime,to_mime:T.mime,from:`${u}x${g}`,to:`${b.width}x${b.height}`}),{...o,mime:T.mime,url:`data:${T.mime};base64,${T.data}`}}return yield*new gs({bytes:d,max:a.maxBase64Bytes,width:u,height:g,max_width:a.maxWidth,max_height:a.maxHeight})}finally{f.free()}});return ur.of({normalize:n})})),yv=ke.make({service:ur,layer:gv,deps:[Oe.node]});var bv=2e4,wv=.05;function Fi(e){let t=e.model.limit.context;if(t===0)return 0;let n=e.cfg.compaction?.reserved??(String(e.model.providerID)==="openai"&&e.model.limit.input?Math.round(e.model.limit.input*wv):Math.min(bv,Xe.maxOutputTokens(e.model,e.outputTokenMax)));return e.model.limit.input?Math.max(0,e.model.limit.input-n):Math.max(0,t-Xe.maxOutputTokens(e.model,e.outputTokenMax))}i(Fi,"usable");function Bi(e){return e.cfg.compaction?.auto===!1||e.model.limit.context===0?!1:(e.tokens.total||e.tokens.input+e.tokens.output+e.tokens.cache.read+e.tokens.cache.write)>=Fi(e)}i(Bi,"isOverflow");var fr={};fe(fr,{GO_UPSELL_MESSAGE:()=>wf,GO_UPSELL_URL:()=>vf,RETRY_AFTER_MAX:()=>Df,RETRY_BACKOFF_FACTOR:()=>Sf,RETRY_INITIAL_DELAY:()=>xf,RETRY_JITTER_FACTOR:()=>If,RETRY_MAX_BACKOFF:()=>kf,RETRY_MAX_RETRIES:()=>Ef,SessionRetry:()=>fr,delay:()=>Tf,policy:()=>kv,retryable:()=>Pf});var wf="Free usage exceeded, subscribe to Go",vf="https://opencode.ai/go",xf=500,Sf=2,If=.25,kf=32e3,Df=6e5,Ef=10,vv=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function xv(e){let t=e?.data.responseHeaders;if(!t)return;let n=Number.parseFloat(t["retry-after-ms"]??"");if(!Number.isNaN(n)&&n>=0)return n;let o=t["retry-after"];if(!o)return;let s=Number.parseFloat(o);if(!Number.isNaN(s)&&s>=0)return Math.ceil(s*1e3);let a=Date.parse(o)-Date.now();if(!Number.isNaN(a)&&a>0)return Math.ceil(a)}i(xv,"retryAfter");function Tf(e,t,n=Math.random()){let o=xv(t);if(o!==void 0)return Math.min(o,Df);let s=Math.min(xf*Math.pow(Sf,e-1),kf);return Math.round(s*(1+If*n))}i(Tf,"delay");function Sv(e){return dt.APIError.isInstance(e)&&!!e.data.responseBody?.includes("FreeUsageLimitError")}i(Sv,"uncapped");function Pf(e,t){if(dt.ProviderQuotaError.isInstance(e)||dt.APIError.isInstance(e)&&e.data.metadata?.alchemyStop||dt.ContextOverflowError.isInstance(e))return;if(dt.APIError.isInstance(e)){let a=e.data.statusCode;if(!e.data.isRetryable&&!(a!==void 0&&a>=500)&&!Rc(e.data.message)&&!Rc(e.data.responseBody))return;if(e.data.responseBody?.includes("FreeUsageLimitError"))return{message:wf,action:{reason:"free_tier_limit",provider:t,title:"Free limit reached",message:"Subscribe to OpenCode Go for reliable access to the best open-source models for $10/month.",label:"subscribe",link:vf}};if(e.data.responseBody?.includes("GoUsageLimitError")){let l=bf(e.data.responseBody),d=pr(l?.metadata?.workspace),p=pr(l?.metadata?.limitName),f=Iv(e.data.responseHeaders?.["retry-after"]),u=Za(()=>{if(f===void 0)return"";let b=Math.max(0,Math.ceil(f)),S=Math.floor(b/86400),T=Math.floor(b%86400/3600),m=Math.ceil(b%3600/60),h=i((k,w)=>`${k} ${w}${k===1?"":"s"}`,"unit");return S>0?T>0?`${h(S,"day")} ${h(T,"hour")}`:h(S,"day"):T>0?m>0?`${h(T,"hour")} ${h(m,"minute")}`:h(T,"hour"):m>0?h(m,"minute"):"less than a minute"}),g=`${p?`${p} usage limit`:"Usage limit"} reached. It will reset in ${u}. To continue using this model now, enable usage from your available balance`,y=`https://opencode.ai/workspace/${d}/go`;return{message:`${g} - ${y}`,action:{reason:"account_rate_limit",provider:t,title:"Go limit reached",message:g,label:"open settings",link:y}}}return{message:e.data.message.includes("Overloaded")?"Provider is overloaded":e.data.message}}let n=ut(e.data)?e.data.message:void 0;if(typeof n!="string")return;let o=n.toLowerCase();if(o.includes("too_many_requests"))return{message:"Too Many Requests"};let s=bf(n);if(ut(s)){let a=ut(s.error)?s.error:{},l=pr(s.type),d=pr(a.code),p=pr(a.type);if(l==="api_error")return{message:"Provider server error"};if(l.includes("overloaded")||d.includes("exhausted")||d.includes("unavailable")||d.includes("overloaded")||p.includes("unavailable")||p.includes("overloaded")||d==="slow_down")return{message:"Provider is overloaded"}}if(o.includes("exhausted")||o.includes("unavailable"))return{message:"Provider is overloaded"};if(Rc(n))return{message:n}}i(Pf,"retryable");function Rc(e){return typeof e=="string"&&vv.some(t=>t.test(e))}i(Rc,"matchesRetryableMessage");function pr(e){return e==null?"":String(e)}i(pr,"str");function Iv(e){let t=Number.parseFloat(pr(e));if(!Number.isNaN(t))return t}i(Iv,"num");function bf(e){return Za(()=>{try{return typeof e!="string"?void 0:JSON.parse(e)}catch{return}})}i(bf,"parseJSON");function kv(e){return Rd.fromStepWithMetadata(r.succeed(t=>{let n=e.parse(t.input),o=Pf(n,e.provider);return o?t.attempt>Ef&&!Sv(n)?tt.done(t.attempt):r.gen(function*(){let s=Tf(t.attempt,dt.APIError.isInstance(n)?n:void 0),a=yield*Pd.currentTimeMillis;return yield*e.set({attempt:t.attempt,message:o.message,action:o.action,next:a+s}),[t.attempt,Td.millis(s)]}):tt.done(t.attempt)}))}i(kv,"policy");function Cf(e,t){if(Rf(t)!=="final_answer")return;let n=t.text.trim();if(n)return e.find(o=>o.type==="text"&&o.id!==t.id&&Rf(o)==="commentary"&&o.text.trim()===n)}i(Cf,"repeatedPreamble");function Rf(e){for(let t of Object.values(e.metadata??{}))if(t&&typeof t=="object"&&typeof t.phase=="string")return t.phase}i(Rf,"phaseOf");function Cc(e){let t=e instanceof Error?e.message:String(e),n=typeof import.meta.dirname=="string"?import.meta.dirname:void 0;return n&&t.includes("Cannot find module")&&t.includes(n)?"AlchemyLab's files were updated or rebuilt while it was running, so this tool can no longer load. Restart alchemylab to get the tools back.":t}i(Cc,"toolErrorText");var Ht;(f=>{let e=new Map;function t(u,g){let y={executing:0,ended:!1,end:g};return e.set(u,y),y}f.open=t,i(t,"open");function n(u,g){e.get(u)===g&&e.delete(u)}f.close=n,i(n,"close");function o(u){let g=e.get(u);return!g||g.ended||g.executing>0?!1:(g.ended=!0,g.end(),!0)}f.endForPerson=o,i(o,"endForPerson");function s(u){if(u){if(u.ended)return new Error("Not run: the user's message ended this step before this tool started.");u.executing++}}f.enter=s,i(s,"enter");function a(u){u&&u.executing>0&&u.executing--}f.leave=a,i(a,"leave");function l(u,g){let y=s(u);return y?Promise.reject(y):g()}f.run=l,i(l,"run");function d(u){a(e.get(u))}f.recorded=d,i(d,"recorded");function p(u){let g=new Set;for(let b of u)(b.type==="text"||b.type==="reasoning")&&!b.time?.end&&g.add(b.id),b.type==="tool"&&b.state.status==="pending"&&g.add(b.id);let y=i(b=>!g.has(b.id)&&(b.type==="text"||b.type==="tool"),"kept");for(let b=0;b<u.length;b++){let S=u[b];S.type!=="reasoning"||g.has(S.id)||u.slice(b+1).some(y)||g.add(S.id)}if(!u.some(y))for(let b of u)b.type==="step-start"&&g.add(b.id);return[...g]}f.toDrop=p,i(p,"toDrop")})(Ht||={});var mr;(a=>{a.LIMIT=12;let t=new Map;function n(l,d,p,f){if(!p)return t.delete(l),0;let u=`${d}\0${f.slice(0,300)}`,g=t.get(l),y=g&&g.sig===u?g.count+1:1;return t.set(l,{sig:u,count:y}),y}a.note=n,i(n,"note");function o(l){t.delete(l)}a.forget=o,i(o,"forget");function s(l,d,p){let f=p.replace(/\s+/g," ").trim().slice(0,160);return`It made the same failing call ${d} times in a row (${l}: "${f}"), so it was stopped.`}a.line=s,i(s,"line")})(mr||={});function Af(e,t,n,o){let s=mr.note(e,t,n,o);if(!(s<mr.LIMIT))throw mr.forget(e),new dt.APIError({message:mr.line(t,s,o),isRetryable:!1,metadata:{alchemyStop:"repeated-tool-failure",tool:t,count:String(s)}})}i(Af,"breakRepeat");var Mf=3,hr=class extends Re.Service()("@opencode/SessionProcessor"){static{i(this,"Service")}},Dv=Te.effect(hr,r.gen(function*(){let e=yield*me.Service,t=yield*Oe.Service,n=yield*an.Service,o=yield*Ft.Service,s=yield*dn.Service,a=yield*Ke.Service,l=yield*pt.Service,d=yield*un.Service,p=yield*Dt.Scope,f=yield*ln.Service,u=yield*bn.Service,g=yield*De.Service,y=yield*Qe.Service,b=r.fn("SessionProcessor.create")(function*(S){let T=yield*n.track(),m={assistantMessage:S.assistantMessage,sessionID:S.sessionID,model:S.model,toolcalls:{},shouldBreak:!1,snapshot:T,blocked:!1,needsCompaction:!1,currentText:void 0,reasoningMap:{}},h=!1,k={},w={},I=i(R=>{let q=Ze.fromError(R,{providerID:S.model.providerID,aborted:h});if(q?.name==="MessageAbortedError"&&!h){let H=R,ne=H?.cause;globalThis.process.stderr.write(`level=WARN service=session.processor message="stream aborted without an interrupt" ${JSON.stringify({sessionID:S.sessionID,name:String(H?.name??""),message:String(H?.message??""),stack:String(H?.stack??"").slice(0,1500),cause:ne?`${String(ne.name??"")}: ${String(ne.message??"")} ${String(ne.stack??"").slice(0,800)}`:""})}
986
+ `:a==="r"?"\r":a==="t"?" ":a==="b"?"\b":a==="f"?"\f":a==="v"?"\v":a==="\\"||a==='"'?a:void 0;n.push((l??a).charCodeAt(0)),o++}return Buffer.from(n).toString()}i(sv,"unquoteGitPath");var dr=class extends Re.Service()("@opencode/SessionSummary"){static{i(this,"Service")}},iv=Te.effect(dr,r.gen(function*(){let e=yield*me.Service,t=yield*an.Service,n=yield*De.Service,o=yield*Oe.Service,s=r.fn("SessionSummary.computeDiff")(function*(d){let p,f;for(let u of d.messages){if(!p){for(let g of u.parts)if(g.type==="step-start"&&g.snapshot){p=g.snapshot;break}}for(let g of u.parts)g.type==="step-finish"&&g.snapshot&&(f=g.snapshot)}return p&&f?yield*t.diffFull(p,f):[]}),a=r.fn("SessionSummary.summarize")(function*(d){if(yield*e.setSummary({sessionID:d.sessionID,summary:{additions:0,deletions:0,files:0}}),yield*n.publish(me.Event.Diff,{sessionID:d.sessionID,diff:[]}),(yield*o.get()).snapshot===!1)return;let p=yield*e.messages({sessionID:d.sessionID}).pipe(r.orDie);if(!p.length)return;let f=p.filter(y=>y.info.id===d.messageID||y.info.role==="assistant"&&y.info.parentID===d.messageID),u=f.find(y=>y.info.id===d.messageID);if(!u||u.info.role!=="user")return;let g=yield*s({messages:f});u.info.summary={...u.info.summary,diffs:g},yield*e.updateMessage(u.info)}),l=r.fn("SessionSummary.diff")(function*(d){if(!d.messageID)return[];let p=(yield*e.messages({sessionID:d.sessionID}).pipe(r.orDie)).find(u=>u.info.id===d.messageID);return!p||p.info.role!=="user"?[]:(p.info.summary?.diffs??[]).map(u=>{if(u.file===void 0)return u;let g=sv(u.file);return g===u.file?u:{...u,file:g}})});return dr.of({summarize:a,diff:l,computeDiff:s})})),av=c.Struct({sessionID:Pt,messageID:c.optional(at)}),cv=ke.make({service:dr,layer:iv,deps:[me.node,an.node,De.node,Oe.node]});var jn={};fe(jn,{Service:()=>hr,SessionProcessor:()=>jn,node:()=>Cv});var bn={};fe(bn,{DecodeError:()=>Ui,Image:()=>bn,InvalidDataUrlError:()=>ji,ResizerUnavailableError:()=>Ni,Service:()=>ur,SizeError:()=>gs,node:()=>xv});import lv from"node:path";import{fileURLToPath as dv}from"node:url";var uv=5*1024*1024,pv=2e3,fv=2e3,mv=!0,hv=[80,85,70,55,40],gv=256*1024,yv=85,bv=.5,Ni=class extends c.TaggedErrorClass()("ImageResizerUnavailableError",{}){static{i(this,"ResizerUnavailableError")}get message(){return"Image resizer is unavailable"}},ji=class extends c.TaggedErrorClass()("ImageInvalidDataUrlError",{url:c.String}){static{i(this,"InvalidDataUrlError")}get message(){return"Image URL must be a base64 data URL"}},Ui=class extends c.TaggedErrorClass()("ImageDecodeError",{}){static{i(this,"DecodeError")}get message(){return"Image could not be decoded"}},gs=class extends c.TaggedErrorClass()("ImageSizeError",{bytes:c.Number,max:c.Number,width:c.Number,height:c.Number,max_width:c.Number,max_height:c.Number}){static{i(this,"SizeError")}get message(){return`Image ${this.width}x${this.height} with base64 size ${this.bytes} exceeds configured limits and could not be resized below ${this.max_width}x${this.max_height}/${this.max} bytes`}};function wv(e){let t=e.get_raw_pixels();for(let n=3;n<t.length;n+=4)if(t[n]!==255)return!1;return!0}i(wv,"opaque");var ur=class extends Re.Service()("@opencode/Image"){static{i(this,"Service")}},vv=Te.effect(ur,r.gen(function*(){let e=yield*Oe.Service,t=yield*r.cached(r.sync(()=>{globalThis.__OPENCODE_PHOTON_WASM_PATH=lv.isAbsolute(oi)?oi:dv(new URL(oi,import.meta.url))}).pipe(r.andThen(()=>r.tryPromise(()=>import("@silvia-odwyer/photon-node"))),r.tapError(o=>r.logWarning("failed to load photon",{error:o})),r.mapError(()=>new Ni))),n=r.fn("Image.normalize")(function*(o){let s=(yield*e.get()).attachment?.image,a={autoResize:s?.auto_resize??mv,maxWidth:s?.max_width??pv,maxHeight:s?.max_height??fv,maxBase64Bytes:s?.max_base64_bytes??uv};if(!o.url.startsWith("data:")||!o.url.includes(";base64,"))return yield*new ji({url:o.url});let l=o.url.slice(o.url.indexOf(";base64,")+8),d=Buffer.byteLength(l,"utf8"),p=yield*t,f=yield*r.try({try:i(()=>p.PhotonImage.new_from_byteslice(Buffer.from(l,"base64")),"try"),catch:i(()=>new Ui,"catch")}).pipe(r.tapError(u=>r.logWarning("failed to decode image",{error:u})));try{let u=f.get_width(),g=f.get_height();if(u<=a.maxWidth&&g<=a.maxHeight&&d<=a.maxBase64Bytes){if(o.mime!=="image/png"||d<gv||!wv(f))return o;let b=Buffer.from(f.get_bytes_jpeg(yv)).toString("base64");return Buffer.byteLength(b,"utf8")>d*bv?o:(yield*r.logInfo("using lighter image",{from:d,to:Buffer.byteLength(b,"utf8"),size:`${u}x${g}`}),{...o,mime:"image/jpeg",url:`data:image/jpeg;base64,${b}`})}if(!a.autoResize)return yield*new gs({bytes:d,max:a.maxBase64Bytes,width:u,height:g,max_width:a.maxWidth,max_height:a.maxHeight});let y=Math.min(1,a.maxWidth/u,a.maxHeight/g);for(let b of Array.from({length:32}).reduce(S=>{let T=S.at(-1)??{width:Math.max(1,Math.round(u*y)),height:Math.max(1,Math.round(g*y))},m=S.length===0?T:{width:T.width===1?1:Math.max(1,Math.floor(T.width*.75)),height:T.height===1?1:Math.max(1,Math.floor(T.height*.75))};return S.some(h=>h.width===m.width&&h.height===m.height)?S:[...S,m]},[])){let S=p.resize(f,b.width,b.height,p.SamplingFilter.Lanczos3),T=[{data:Buffer.from(S.get_bytes()).toString("base64"),mime:"image/png"},...hv.map(m=>({data:Buffer.from(S.get_bytes_jpeg(m)).toString("base64"),mime:"image/jpeg"}))].map(m=>({...m,bytes:Buffer.byteLength(m.data,"utf8")})).find(m=>m.bytes<=a.maxBase64Bytes);if(S.free(),T)return yield*r.logInfo("using resized image",{from_mime:o.mime,to_mime:T.mime,from:`${u}x${g}`,to:`${b.width}x${b.height}`}),{...o,mime:T.mime,url:`data:${T.mime};base64,${T.data}`}}return yield*new gs({bytes:d,max:a.maxBase64Bytes,width:u,height:g,max_width:a.maxWidth,max_height:a.maxHeight})}finally{f.free()}});return ur.of({normalize:n})})),xv=ke.make({service:ur,layer:vv,deps:[Oe.node]});var Sv=2e4,Iv=.05;function Fi(e){let t=e.model.limit.context;if(t===0)return 0;let n=e.cfg.compaction?.reserved??(String(e.model.providerID)==="openai"&&e.model.limit.input?Math.round(e.model.limit.input*Iv):Math.min(Sv,Xe.maxOutputTokens(e.model,e.outputTokenMax)));return e.model.limit.input?Math.max(0,e.model.limit.input-n):Math.max(0,t-Xe.maxOutputTokens(e.model,e.outputTokenMax))}i(Fi,"usable");function Bi(e){return e.cfg.compaction?.auto===!1||e.model.limit.context===0?!1:(e.tokens.total||e.tokens.input+e.tokens.output+e.tokens.cache.read+e.tokens.cache.write)>=Fi(e)}i(Bi,"isOverflow");var fr={};fe(fr,{GO_UPSELL_MESSAGE:()=>wf,GO_UPSELL_URL:()=>vf,RETRY_AFTER_MAX:()=>Df,RETRY_BACKOFF_FACTOR:()=>Sf,RETRY_INITIAL_DELAY:()=>xf,RETRY_JITTER_FACTOR:()=>If,RETRY_MAX_BACKOFF:()=>kf,RETRY_MAX_RETRIES:()=>Ef,SessionRetry:()=>fr,delay:()=>Tf,policy:()=>Pv,retryable:()=>Pf});var wf="Free usage exceeded, subscribe to Go",vf="https://opencode.ai/go",xf=500,Sf=2,If=.25,kf=32e3,Df=6e5,Ef=10,kv=[/429|500|502|503|504|524/i,/rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,/overloaded|service unavailable|service_unavailable|service-unavailable|internal error|internal_error|internal server error|server error|server_error|server-error|provider returned error|provider_returned_error|provider-returned-error/i,/terminated|fetch failed|failed to fetch|network[-_\s]error|upstream connect|connection error|connection refused|connection lost|socket connection was closed|socket hang up|reset before headers|getaddrinfo|enotfound|eai_again|econnrefused|econnreset|etimedout/i,/^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,/try your request again|retry your request|resource exhausted|resource_exhausted/i,/\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i];function Dv(e){let t=e?.data.responseHeaders;if(!t)return;let n=Number.parseFloat(t["retry-after-ms"]??"");if(!Number.isNaN(n)&&n>=0)return n;let o=t["retry-after"];if(!o)return;let s=Number.parseFloat(o);if(!Number.isNaN(s)&&s>=0)return Math.ceil(s*1e3);let a=Date.parse(o)-Date.now();if(!Number.isNaN(a)&&a>0)return Math.ceil(a)}i(Dv,"retryAfter");function Tf(e,t,n=Math.random()){let o=Dv(t);if(o!==void 0)return Math.min(o,Df);let s=Math.min(xf*Math.pow(Sf,e-1),kf);return Math.round(s*(1+If*n))}i(Tf,"delay");function Ev(e){return dt.APIError.isInstance(e)&&!!e.data.responseBody?.includes("FreeUsageLimitError")}i(Ev,"uncapped");function Pf(e,t){if(dt.ProviderQuotaError.isInstance(e)||dt.APIError.isInstance(e)&&e.data.metadata?.alchemyStop||dt.ContextOverflowError.isInstance(e))return;if(dt.APIError.isInstance(e)){let a=e.data.statusCode;if(!e.data.isRetryable&&!(a!==void 0&&a>=500)&&!Rc(e.data.message)&&!Rc(e.data.responseBody))return;if(e.data.responseBody?.includes("FreeUsageLimitError"))return{message:wf,action:{reason:"free_tier_limit",provider:t,title:"Free limit reached",message:"Subscribe to OpenCode Go for reliable access to the best open-source models for $10/month.",label:"subscribe",link:vf}};if(e.data.responseBody?.includes("GoUsageLimitError")){let l=bf(e.data.responseBody),d=pr(l?.metadata?.workspace),p=pr(l?.metadata?.limitName),f=Tv(e.data.responseHeaders?.["retry-after"]),u=Za(()=>{if(f===void 0)return"";let b=Math.max(0,Math.ceil(f)),S=Math.floor(b/86400),T=Math.floor(b%86400/3600),m=Math.ceil(b%3600/60),h=i((k,w)=>`${k} ${w}${k===1?"":"s"}`,"unit");return S>0?T>0?`${h(S,"day")} ${h(T,"hour")}`:h(S,"day"):T>0?m>0?`${h(T,"hour")} ${h(m,"minute")}`:h(T,"hour"):m>0?h(m,"minute"):"less than a minute"}),g=`${p?`${p} usage limit`:"Usage limit"} reached. It will reset in ${u}. To continue using this model now, enable usage from your available balance`,y=`https://opencode.ai/workspace/${d}/go`;return{message:`${g} - ${y}`,action:{reason:"account_rate_limit",provider:t,title:"Go limit reached",message:g,label:"open settings",link:y}}}return{message:e.data.message.includes("Overloaded")?"Provider is overloaded":e.data.message}}let n=ut(e.data)?e.data.message:void 0;if(typeof n!="string")return;let o=n.toLowerCase();if(o.includes("too_many_requests"))return{message:"Too Many Requests"};let s=bf(n);if(ut(s)){let a=ut(s.error)?s.error:{},l=pr(s.type),d=pr(a.code),p=pr(a.type);if(l==="api_error")return{message:"Provider server error"};if(l.includes("overloaded")||d.includes("exhausted")||d.includes("unavailable")||d.includes("overloaded")||p.includes("unavailable")||p.includes("overloaded")||d==="slow_down")return{message:"Provider is overloaded"}}if(o.includes("exhausted")||o.includes("unavailable"))return{message:"Provider is overloaded"};if(Rc(n))return{message:n}}i(Pf,"retryable");function Rc(e){return typeof e=="string"&&kv.some(t=>t.test(e))}i(Rc,"matchesRetryableMessage");function pr(e){return e==null?"":String(e)}i(pr,"str");function Tv(e){let t=Number.parseFloat(pr(e));if(!Number.isNaN(t))return t}i(Tv,"num");function bf(e){return Za(()=>{try{return typeof e!="string"?void 0:JSON.parse(e)}catch{return}})}i(bf,"parseJSON");function Pv(e){return Rd.fromStepWithMetadata(r.succeed(t=>{let n=e.parse(t.input),o=Pf(n,e.provider);return o?t.attempt>Ef&&!Ev(n)?tt.done(t.attempt):r.gen(function*(){let s=Tf(t.attempt,dt.APIError.isInstance(n)?n:void 0),a=yield*Pd.currentTimeMillis;return yield*e.set({attempt:t.attempt,message:o.message,action:o.action,next:a+s}),[t.attempt,Td.millis(s)]}):tt.done(t.attempt)}))}i(Pv,"policy");function Cf(e,t){if(Rf(t)!=="final_answer")return;let n=t.text.trim();if(n)return e.find(o=>o.type==="text"&&o.id!==t.id&&Rf(o)==="commentary"&&o.text.trim()===n)}i(Cf,"repeatedPreamble");function Rf(e){for(let t of Object.values(e.metadata??{}))if(t&&typeof t=="object"&&typeof t.phase=="string")return t.phase}i(Rf,"phaseOf");function Cc(e){let t=e instanceof Error?e.message:String(e),n=typeof import.meta.dirname=="string"?import.meta.dirname:void 0;return n&&t.includes("Cannot find module")&&t.includes(n)?"AlchemyLab's files were updated or rebuilt while it was running, so this tool can no longer load. Restart alchemylab to get the tools back.":t}i(Cc,"toolErrorText");var Ht;(f=>{let e=new Map;function t(u,g){let y={executing:0,ended:!1,end:g};return e.set(u,y),y}f.open=t,i(t,"open");function n(u,g){e.get(u)===g&&e.delete(u)}f.close=n,i(n,"close");function o(u){let g=e.get(u);return!g||g.ended||g.executing>0?!1:(g.ended=!0,g.end(),!0)}f.endForPerson=o,i(o,"endForPerson");function s(u){if(u){if(u.ended)return new Error("Not run: the user's message ended this step before this tool started.");u.executing++}}f.enter=s,i(s,"enter");function a(u){u&&u.executing>0&&u.executing--}f.leave=a,i(a,"leave");function l(u,g){let y=s(u);return y?Promise.reject(y):g()}f.run=l,i(l,"run");function d(u){a(e.get(u))}f.recorded=d,i(d,"recorded");function p(u){let g=new Set;for(let b of u)(b.type==="text"||b.type==="reasoning")&&!b.time?.end&&g.add(b.id),b.type==="tool"&&b.state.status==="pending"&&g.add(b.id);let y=i(b=>!g.has(b.id)&&(b.type==="text"||b.type==="tool"),"kept");for(let b=0;b<u.length;b++){let S=u[b];S.type!=="reasoning"||g.has(S.id)||u.slice(b+1).some(y)||g.add(S.id)}if(!u.some(y))for(let b of u)b.type==="step-start"&&g.add(b.id);return[...g]}f.toDrop=p,i(p,"toDrop")})(Ht||={});var mr;(a=>{a.LIMIT=12;let t=new Map;function n(l,d,p,f){if(!p)return t.delete(l),0;let u=`${d}\0${f.slice(0,300)}`,g=t.get(l),y=g&&g.sig===u?g.count+1:1;return t.set(l,{sig:u,count:y}),y}a.note=n,i(n,"note");function o(l){t.delete(l)}a.forget=o,i(o,"forget");function s(l,d,p){let f=p.replace(/\s+/g," ").trim().slice(0,160);return`It made the same failing call ${d} times in a row (${l}: "${f}"), so it was stopped.`}a.line=s,i(s,"line")})(mr||={});function Af(e,t,n,o){let s=mr.note(e,t,n,o);if(!(s<mr.LIMIT))throw mr.forget(e),new dt.APIError({message:mr.line(t,s,o),isRetryable:!1,metadata:{alchemyStop:"repeated-tool-failure",tool:t,count:String(s)}})}i(Af,"breakRepeat");var Mf=3,hr=class extends Re.Service()("@opencode/SessionProcessor"){static{i(this,"Service")}},Rv=Te.effect(hr,r.gen(function*(){let e=yield*me.Service,t=yield*Oe.Service,n=yield*an.Service,o=yield*Ft.Service,s=yield*dn.Service,a=yield*Ke.Service,l=yield*pt.Service,d=yield*un.Service,p=yield*Dt.Scope,f=yield*ln.Service,u=yield*bn.Service,g=yield*De.Service,y=yield*Qe.Service,b=r.fn("SessionProcessor.create")(function*(S){let T=yield*n.track(),m={assistantMessage:S.assistantMessage,sessionID:S.sessionID,model:S.model,toolcalls:{},shouldBreak:!1,snapshot:T,blocked:!1,needsCompaction:!1,currentText:void 0,reasoningMap:{}},h=!1,k={},w={},I=i(R=>{let q=Ze.fromError(R,{providerID:S.model.providerID,aborted:h});if(q?.name==="MessageAbortedError"&&!h){let H=R,ne=H?.cause;globalThis.process.stderr.write(`level=WARN service=session.processor message="stream aborted without an interrupt" ${JSON.stringify({sessionID:S.sessionID,name:String(H?.name??""),message:String(H?.message??""),stack:String(H?.stack??"").slice(0,1500),cause:ne?`${String(ne.name??"")}: ${String(ne.message??"")} ${String(ne.stack??"").slice(0,800)}`:""})}
987
987
  `)}return q},"parse"),P=r.fn("SessionProcessor.settleToolCall")(function*(R){let q=m.toolcalls[R]?.done;delete m.toolcalls[R],q&&(yield*ht.succeed(q,void 0).pipe(r.ignore))}),x=r.fn("SessionProcessor.readToolCall")(function*(R){let q=m.toolcalls[R];if(!q)return;let H=yield*e.getPart({partID:q.partID,messageID:q.messageID,sessionID:q.sessionID});if(!H||H.type!=="tool"){delete m.toolcalls[R];return}return{call:q,part:H}}),A=r.fn("SessionProcessor.updateToolCall")(function*(R,q){let H=yield*x(R);if(!H)return;let ne=yield*e.updatePart(q(H.part));return m.toolcalls[R]={...H.call,partID:ne.id,messageID:ne.messageID,sessionID:ne.sessionID},ne}),C=r.fn("SessionProcessor.completeToolCall")(function*(R,q){let H=yield*x(R);if(!H||H.part.state.status!=="running")return Ht.recorded(m.sessionID);yield*e.updatePart({...H.part,state:{status:"completed",input:H.part.state.input,output:q.output,metadata:q.metadata,title:q.title,time:{start:H.part.state.time.start,end:Date.now()},attachments:q.attachments}}),yield*P(R),Ht.recorded(m.sessionID),Af(m.sessionID,H.part.tool,q.metadata?.isError===!0,String(q.output??""))}),$=r.fn("SessionProcessor.failToolCall")(function*(R,q){let H=yield*x(R);return!H||H.part.state.status!=="running"?(Ht.recorded(m.sessionID),!1):(yield*e.updatePart({...H.part,state:{status:"error",input:H.part.state.input,error:Cc(q),metadata:H.part.state.metadata,time:{start:H.part.state.time.start,end:Date.now()}}}),(q instanceof ri.RejectedError||q instanceof Qt.RejectedError)&&(m.blocked=m.shouldBreak),yield*P(R),Ht.recorded(m.sessionID),Af(m.sessionID,H.part.tool,!0,Cc(q)),!0)}),j=r.fn("SessionProcessor.finishReasoning")(function*(R){R in m.reasoningMap&&(m.reasoningMap[R].text=m.reasoningMap[R].text,m.reasoningMap[R].time={...m.reasoningMap[R].time,end:Date.now()},yield*e.updatePart(m.reasoningMap[R]),delete m.reasoningMap[R])}),z=r.fn("SessionProcessor.ensureToolCall")(function*(R){let q=yield*x(R.id);if(q){if(!R.providerExecuted||q.part.metadata?.providerExecuted)return q;let ne=yield*e.updatePart({...q.part,metadata:{...q.part.metadata,providerExecuted:!0}});return m.toolcalls[R.id]={...q.call,partID:ne.id,messageID:ne.messageID,sessionID:ne.sessionID},{call:m.toolcalls[R.id],part:ne}}let H=yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"tool",tool:R.name,callID:R.id,state:{status:"pending",input:{},raw:""},metadata:R.providerExecuted?{providerExecuted:!0}:void 0});return m.toolcalls[R.id]={done:yield*ht.make(),partID:H.id,messageID:H.messageID,sessionID:H.sessionID},{call:m.toolcalls[R.id],part:H}}),ie=i(R=>c.is(dt.FilePart)(R),"isFilePart"),L=i(R=>ut(R.result.value)&&typeof R.result.value.output=="string"?{title:typeof R.result.value.title=="string"?R.result.value.title:R.name,metadata:ut(R.result.value.metadata)?R.result.value.metadata:{},output:R.result.value.output,attachments:Array.isArray(R.result.value.attachments)?R.result.value.attachments.filter(ie):void 0}:{title:R.name,metadata:R.result.type==="json"&&ut(R.result.value)?R.result.value:{},output:typeof R.result.value=="string"?R.result.value:JSON.stringify(R.result.value)??""},"toolResultOutput"),V=r.fnUntraced(function*(R){switch(R.type){case"reasoning-start":if(R.id in m.reasoningMap)return;m.reasoningMap[R.id]={id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"reasoning",text:"",time:{start:Date.now()},metadata:R.providerMetadata},yield*e.updatePart(m.reasoningMap[R.id]);return;case"reasoning-delta":if(!(R.id in m.reasoningMap))return;m.reasoningMap[R.id].text+=R.text,R.providerMetadata&&(m.reasoningMap[R.id].metadata=R.providerMetadata),yield*e.updatePartDelta({sessionID:m.reasoningMap[R.id].sessionID,messageID:m.reasoningMap[R.id].messageID,partID:m.reasoningMap[R.id].id,field:"text",delta:R.text});return;case"reasoning-end":R.providerMetadata&&R.id in m.reasoningMap&&(m.reasoningMap[R.id].metadata=R.providerMetadata),yield*j(R.id);return;case"tool-input-start":if(m.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${R.name}`);yield*z(R);return;case"tool-input-delta":{let q=yield*z(R);if(q.part.state.status!=="pending")return;let H=(w[R.id]??q.part.state.raw??"")+R.text,ne=Date.now();if(ne-(k[R.id]??0)<2e3){w[R.id]=H;return}k[R.id]=ne,delete w[R.id],yield*A(R.id,Ue=>Ue.state.status==="pending"?{...Ue,state:{...Ue.state,raw:H}}:Ue),yield*e.touch(m.sessionID);return}case"tool-input-end":{yield*z(R);return}case"tool-call":{if(m.assistantMessage.summary)throw new Error(`Tool call not allowed while generating summary: ${R.name}`);yield*z(R);let q=ut(R.input)?R.input:{value:R.input};yield*A(R.id,ot=>({...ot,tool:R.name,state:ot.state.status==="running"?{...ot.state,input:q}:{status:"running",input:q,time:{start:Date.now()}},metadata:ot.metadata?.providerExecuted?{...R.providerMetadata,providerExecuted:!0}:R.providerMetadata}));let ne=(yield*Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y))).slice(-Mf);if(ne.length!==Mf||!ne.every(ot=>ot.type==="tool"&&ot.tool===R.name&&ot.state.status!=="pending"&&JSON.stringify(ot.state.input)===JSON.stringify(q)))return;let Ue=yield*o.get(m.assistantMessage.agent);yield*a.ask({permission:"doom_loop",patterns:[R.name],sessionID:m.assistantMessage.sessionID,metadata:{tool:R.name,input:q},always:[R.name],ruleset:Ue.permission});return}case"tool-result":{if(!(yield*x(R.id))&&R.result.type==="error")return;if(R.result.type==="error"){yield*$(R.id,R.result.value);return}let H=L(R),ne=yield*r.forEach(H.attachments??[],et=>et.mime.startsWith("image/")?u.normalize(et).pipe(r.catchIf(Pn=>Pn instanceof bn.ResizerUnavailableError,()=>r.succeed(et)),r.exit):r.succeed(bt.succeed(et))),Ue=ne.filter(bt.isFailure).length,ot=ne.filter(bt.isSuccess).map(et=>et.value),Mt={...H,output:Ue===0?H.output:`${H.output}
988
988
 
989
- [${Ue} image${Ue===1?"":"s"} omitted: could not be resized below the image size limit.]`,attachments:ot.length?ot:void 0};yield*C(R.id,Mt);return}case"tool-error":{yield*$(R.id,R.error??new Error(R.message));return}case"provider-error":throw new Error(R.message);case"step-start":m.snapshot||(m.snapshot=yield*n.track()),yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,snapshot:m.snapshot,type:"step-start"});return;case"step-finish":{let q=yield*n.track();yield*r.forEach(Object.keys(m.reasoningMap),j);let H=ut(R.providerMetadata?.anthropic)?R.providerMetadata.anthropic.inputTransformations:void 0;m.model.api.npm==="@ai-sdk/anthropic"&&st.log("thinking check",{"session.id":m.sessionID,step:m.assistantMessage.id,dropped:Array.isArray(H)?H.length:0,entries:Array.isArray(H)?H.map(Ue=>({path:Ue?.path,reason:Ue?.reason,type:Ue?.type})):[]}),Array.isArray(H)&&H.length>0&&(yield*r.logWarning("thinking blocks dropped by provider",{sessionID:m.sessionID,messageID:m.assistantMessage.id,model:m.model.id,transformations:JSON.stringify(H)}));let ne=me.getUsage({model:m.model,usage:R.usage??new Mn({}),metadata:R.providerMetadata});if(m.assistantMessage.finish=R.reason,m.assistantMessage.cost+=ne.cost,m.assistantMessage.tokens=ne.tokens,R.responseModelID&&(m.assistantMessage.servedModelID=R.responseModelID),yield*e.updatePart({id:Fe.ascending(),reason:R.reason,snapshot:q,messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"step-finish",tokens:ne.tokens,cost:ne.cost}),yield*e.updateMessage(m.assistantMessage),m.snapshot){let Ue=yield*n.patch(m.snapshot);Ue.files.length&&(yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,type:"patch",hash:Ue.hash,files:Ue.files})),m.snapshot=void 0}yield*d.summarize({sessionID:m.sessionID,messageID:m.assistantMessage.parentID}).pipe(r.ignore,r.forkIn(p)),!m.assistantMessage.summary&&Bi({cfg:yield*t.get(),tokens:ne.tokens,model:m.model})&&(m.needsCompaction=!0);return}case"text-start":m.currentText={id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"text",text:"",time:{start:Date.now()},metadata:R.providerMetadata},yield*e.updatePart(m.currentText);return;case"text-delta":if(!m.currentText)return;m.currentText.text+=R.text,R.providerMetadata&&(m.currentText.metadata=R.providerMetadata),yield*e.updatePartDelta({sessionID:m.currentText.sessionID,messageID:m.currentText.messageID,partID:m.currentText.id,field:"text",delta:R.text});return;case"text-end":if(!m.currentText)return;m.currentText.text=m.currentText.text,m.currentText.text=(yield*l.trigger("experimental.text.complete",{sessionID:m.sessionID,messageID:m.assistantMessage.id,partID:m.currentText.id},{text:m.currentText.text})).text;{let q=Date.now();m.currentText.time={start:m.currentText.time?.start??q,end:q}}R.providerMetadata&&(m.currentText.metadata=R.providerMetadata),yield*e.updatePart(m.currentText);{let q=yield*Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y)),H=Cf(q,m.currentText);H&&(yield*e.removePart({sessionID:H.sessionID,messageID:H.messageID,partID:H.id}))}m.currentText=void 0;return;case"finish":return}}),D=r.fn("SessionProcessor.cleanup")(function*(){if(m.snapshot){let R=yield*n.patch(m.snapshot);R.files.length&&(yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,type:"patch",hash:R.hash,files:R.files})),m.snapshot=void 0}if(m.currentText){let R=Date.now();m.currentText.time={start:m.currentText.time?.start??R,end:R},yield*e.updatePart(m.currentText),m.currentText=void 0}for(let R of Object.values(m.reasoningMap)){let q=Date.now();yield*e.updatePart({...R,time:{start:R.time.start??q,end:q}})}m.reasoningMap={},yield*r.forEach(Object.values(m.toolcalls),R=>ht.await(R.done).pipe(r.timeout("250 millis"),r.ignore),{concurrency:"unbounded"});for(let R of Object.keys(m.toolcalls)){let q=yield*x(R);if(!q)continue;let H=q.part,ne=Date.now(),Ue="metadata"in H.state&&ut(H.state.metadata)?H.state.metadata:{};yield*e.updatePart({...H,state:{...H.state,status:"error",error:"Tool execution aborted",metadata:{...Ue,interrupted:!0},time:{start:"time"in H.state?H.state.time.start:ne,end:ne}}})}m.toolcalls={},m.assistantMessage.time.completed=Date.now(),yield*e.updateMessage(m.assistantMessage)}),M=r.fn("SessionProcessor.halt")(function*(R){yield*r.logError("process",{"session.id":S.sessionID,messageID:S.assistantMessage.id,error:gn(R),stack:R instanceof Error?R.stack:void 0});let q=I(R);if(dt.ContextOverflowError.isInstance(q)){if((yield*t.get()).compaction?.auto===!1&&!m.assistantMessage.summary){m.assistantMessage.error=q,m.assistantMessage.finish="error",yield*g.publish(me.Event.Error,{sessionID:m.sessionID,error:q}),yield*f.set(m.sessionID,{type:"idle"});return}m.needsCompaction=!0,yield*g.publish(me.Event.Error,{sessionID:m.sessionID,error:q});return}m.assistantMessage.error=q,yield*g.publish(me.Event.Error,{sessionID:m.assistantMessage.sessionID,error:m.assistantMessage.error}),yield*f.set(m.sessionID,{type:"idle"})}),_=new Set,N=i(()=>Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y),r.map(R=>R.filter(q=>!_.has(q.id)))),"attemptParts"),W=i(R=>(R.type==="text"||R.type==="reasoning")&&!R.time?.end,"unfinished"),U=r.fn("SessionProcessor.dropAttempt")(function*(){m.currentText=void 0,m.reasoningMap={};for(let R of yield*N())R.type!=="text"&&R.type!=="reasoning"&&R.type!=="step-start"||(yield*e.removePart({sessionID:R.sessionID,messageID:R.messageID,partID:R.id}))}),we=r.fn("SessionProcessor.keepFinished")(function*(R){if(!fr.retryable(I(R),S.model.providerID))return yield*r.fail(R);let q=yield*N();if(!q.some(ne=>ne.type==="tool"&&(ne.state.status==="completed"||ne.state.status==="error")))return yield*r.fail(R);yield*r.logInfo("step failed after a tool finished; continuing from its finished items",{error:gn(R)}),m.currentText=void 0,m.reasoningMap={};for(let ne of q)W(ne)&&(yield*e.removePart({sessionID:ne.sessionID,messageID:ne.messageID,partID:ne.id}));m.assistantMessage.finish="tool-calls"}),pe=!1,ce=r.fn("SessionProcessor.endForPerson")(function*(){m.currentText=void 0,m.reasoningMap={};let R=yield*N(),q=new Set(Ht.toDrop(R));for(let H of R)q.has(H.id)&&(H.type==="tool"&&delete m.toolcalls[H.callID],yield*e.removePart({sessionID:H.sessionID,messageID:H.messageID,partID:H.id}));m.assistantMessage.finish="tool-calls",yield*r.logInfo("step ended for a person's message",{sessionID:m.sessionID,messageID:m.assistantMessage.id,dropped:q.size})}),re=r.fn("SessionProcessor.process")(function*(R){yield*r.logInfo("process",{"session.id":S.sessionID,messageID:S.assistantMessage.id}),m.needsCompaction=!1,m.shouldBreak=(yield*t.get()).experimental?.continue_loop_on_deny!==!0;let q=0,H=S.preempt?.pipe(r.andThen(r.sync(()=>{pe=!0})));return yield*r.gen(function*(){return yield*r.gen(function*(){if(pe)return;q++>0&&(yield*U()),_=new Set((yield*Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y))).map(Ue=>Ue.id)),m.currentText=void 0,m.reasoningMap={},yield*f.set(m.sessionID,{type:"busy"});let ne=s.stream(R).pipe(jd(Ue=>V(Ue)),Fd(()=>m.needsCompaction));yield*H?r.raceFirst(ne.pipe(Na),H):ne.pipe(Na),pe&&(yield*ce())}).pipe(r.onInterrupt(ne=>r.gen(function*(){yield*r.logWarning("turn interrupted",{sessionID:m.sessionID,interruptors:[...ne].map(Ue=>String(Ue)).join(","),attempt:q}),h=!0,m.assistantMessage.error||(yield*M(new DOMException("Aborted","AbortError")))})),r.catchCauseIf(ne=>!tt.hasInterruptsOnly(ne),ne=>r.fail(tt.squash(ne))),r.catch(we),r.retry(fr.policy({provider:S.model.providerID,parse:I,set:i(ne=>f.set(m.sessionID,{type:"retry",attempt:ne.attempt,message:ne.message,action:ne.action,next:ne.next}),"set")})),r.catch(M),r.ensuring(D())),m.needsCompaction?"compact":m.blocked||m.assistantMessage.error?"stop":"continue"})});return{get message(){return m.assistantMessage},updateToolCall:A,completeToolCall:C,process:re}});return hr.of({create:b})})),Ev=ke.make({service:hr,layer:Dv,deps:[me.node,Oe.node,an.node,Ft.node,dn.node,Ke.node,pt.node,un.node,ln.node,bn.node,De.node,Qe.node]});var gr={};fe(gr,{Event:()=>Uf,PRUNE_MINIMUM:()=>Ff,PRUNE_PROTECT:()=>Bf,Service:()=>Do,SessionCompaction:()=>gr,lastStep:()=>Ac,node:()=>Wv,summaryOnPrefix:()=>jf,use:()=>$v});var ys={};fe(ys,{Compacted:()=>_f,Definitions:()=>Tv,SessionCompactionEvent:()=>ys});var _f=Et.define({type:"session.compacted",schema:{sessionID:Cn}}),Tv=Et.inventory(_f);import Pv from"path";import{readFile as Rv}from"fs/promises";var $i="The messages before this compaction, word for word (newest last):";function Of(e){let t=[];for(let s of e)if(!(s.info.role!=="user"||s.parts.some(a=>a.type==="compaction"))){for(let a of s.parts)if(!(a.type!=="text"||!a.text?.trim())){if(!a.synthetic)t.push(a.text.trim());else if(a.text.includes($i)){let l=a.text.slice(a.text.indexOf($i)+$i.length).split(`
989
+ [${Ue} image${Ue===1?"":"s"} omitted: could not be resized below the image size limit.]`,attachments:ot.length?ot:void 0};yield*C(R.id,Mt);return}case"tool-error":{yield*$(R.id,R.error??new Error(R.message));return}case"provider-error":throw new Error(R.message);case"step-start":m.snapshot||(m.snapshot=yield*n.track()),yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,snapshot:m.snapshot,type:"step-start"});return;case"step-finish":{let q=yield*n.track();yield*r.forEach(Object.keys(m.reasoningMap),j);let H=ut(R.providerMetadata?.anthropic)?R.providerMetadata.anthropic.inputTransformations:void 0;m.model.api.npm==="@ai-sdk/anthropic"&&st.log("thinking check",{"session.id":m.sessionID,step:m.assistantMessage.id,dropped:Array.isArray(H)?H.length:0,entries:Array.isArray(H)?H.map(Ue=>({path:Ue?.path,reason:Ue?.reason,type:Ue?.type})):[]}),Array.isArray(H)&&H.length>0&&(yield*r.logWarning("thinking blocks dropped by provider",{sessionID:m.sessionID,messageID:m.assistantMessage.id,model:m.model.id,transformations:JSON.stringify(H)}));let ne=me.getUsage({model:m.model,usage:R.usage??new Mn({}),metadata:R.providerMetadata});if(m.assistantMessage.finish=R.reason,m.assistantMessage.cost+=ne.cost,m.assistantMessage.tokens=ne.tokens,R.responseModelID&&(m.assistantMessage.servedModelID=R.responseModelID),yield*e.updatePart({id:Fe.ascending(),reason:R.reason,snapshot:q,messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"step-finish",tokens:ne.tokens,cost:ne.cost}),yield*e.updateMessage(m.assistantMessage),m.snapshot){let Ue=yield*n.patch(m.snapshot);Ue.files.length&&(yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,type:"patch",hash:Ue.hash,files:Ue.files})),m.snapshot=void 0}yield*d.summarize({sessionID:m.sessionID,messageID:m.assistantMessage.parentID}).pipe(r.ignore,r.forkIn(p)),!m.assistantMessage.summary&&Bi({cfg:yield*t.get(),tokens:ne.tokens,model:m.model})&&(m.needsCompaction=!0);return}case"text-start":m.currentText={id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.assistantMessage.sessionID,type:"text",text:"",time:{start:Date.now()},metadata:R.providerMetadata},yield*e.updatePart(m.currentText);return;case"text-delta":if(!m.currentText)return;m.currentText.text+=R.text,R.providerMetadata&&(m.currentText.metadata=R.providerMetadata),yield*e.updatePartDelta({sessionID:m.currentText.sessionID,messageID:m.currentText.messageID,partID:m.currentText.id,field:"text",delta:R.text});return;case"text-end":if(!m.currentText)return;m.currentText.text=m.currentText.text,m.currentText.text=(yield*l.trigger("experimental.text.complete",{sessionID:m.sessionID,messageID:m.assistantMessage.id,partID:m.currentText.id},{text:m.currentText.text})).text;{let q=Date.now();m.currentText.time={start:m.currentText.time?.start??q,end:q}}R.providerMetadata&&(m.currentText.metadata=R.providerMetadata),yield*e.updatePart(m.currentText);{let q=yield*Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y)),H=Cf(q,m.currentText);H&&(yield*e.removePart({sessionID:H.sessionID,messageID:H.messageID,partID:H.id}))}m.currentText=void 0;return;case"finish":return}}),D=r.fn("SessionProcessor.cleanup")(function*(){if(m.snapshot){let R=yield*n.patch(m.snapshot);R.files.length&&(yield*e.updatePart({id:Fe.ascending(),messageID:m.assistantMessage.id,sessionID:m.sessionID,type:"patch",hash:R.hash,files:R.files})),m.snapshot=void 0}if(m.currentText){let R=Date.now();m.currentText.time={start:m.currentText.time?.start??R,end:R},yield*e.updatePart(m.currentText),m.currentText=void 0}for(let R of Object.values(m.reasoningMap)){let q=Date.now();yield*e.updatePart({...R,time:{start:R.time.start??q,end:q}})}m.reasoningMap={},yield*r.forEach(Object.values(m.toolcalls),R=>ht.await(R.done).pipe(r.timeout("250 millis"),r.ignore),{concurrency:"unbounded"});for(let R of Object.keys(m.toolcalls)){let q=yield*x(R);if(!q)continue;let H=q.part,ne=Date.now(),Ue="metadata"in H.state&&ut(H.state.metadata)?H.state.metadata:{};yield*e.updatePart({...H,state:{...H.state,status:"error",error:"Tool execution aborted",metadata:{...Ue,interrupted:!0},time:{start:"time"in H.state?H.state.time.start:ne,end:ne}}})}m.toolcalls={},m.assistantMessage.time.completed=Date.now(),yield*e.updateMessage(m.assistantMessage)}),M=r.fn("SessionProcessor.halt")(function*(R){yield*r.logError("process",{"session.id":S.sessionID,messageID:S.assistantMessage.id,error:gn(R),stack:R instanceof Error?R.stack:void 0});let q=I(R);if(dt.ContextOverflowError.isInstance(q)){if((yield*t.get()).compaction?.auto===!1&&!m.assistantMessage.summary){m.assistantMessage.error=q,m.assistantMessage.finish="error",yield*g.publish(me.Event.Error,{sessionID:m.sessionID,error:q}),yield*f.set(m.sessionID,{type:"idle"});return}m.needsCompaction=!0,yield*g.publish(me.Event.Error,{sessionID:m.sessionID,error:q});return}m.assistantMessage.error=q,yield*g.publish(me.Event.Error,{sessionID:m.assistantMessage.sessionID,error:m.assistantMessage.error}),yield*f.set(m.sessionID,{type:"idle"})}),_=new Set,N=i(()=>Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y),r.map(R=>R.filter(q=>!_.has(q.id)))),"attemptParts"),W=i(R=>(R.type==="text"||R.type==="reasoning")&&!R.time?.end,"unfinished"),U=r.fn("SessionProcessor.dropAttempt")(function*(){m.currentText=void 0,m.reasoningMap={};for(let R of yield*N())R.type!=="text"&&R.type!=="reasoning"&&R.type!=="step-start"||(yield*e.removePart({sessionID:R.sessionID,messageID:R.messageID,partID:R.id}))}),we=r.fn("SessionProcessor.keepFinished")(function*(R){if(!fr.retryable(I(R),S.model.providerID))return yield*r.fail(R);let q=yield*N();if(!q.some(ne=>ne.type==="tool"&&(ne.state.status==="completed"||ne.state.status==="error")))return yield*r.fail(R);yield*r.logInfo("step failed after a tool finished; continuing from its finished items",{error:gn(R)}),m.currentText=void 0,m.reasoningMap={};for(let ne of q)W(ne)&&(yield*e.removePart({sessionID:ne.sessionID,messageID:ne.messageID,partID:ne.id}));m.assistantMessage.finish="tool-calls"}),pe=!1,ce=r.fn("SessionProcessor.endForPerson")(function*(){m.currentText=void 0,m.reasoningMap={};let R=yield*N(),q=new Set(Ht.toDrop(R));for(let H of R)q.has(H.id)&&(H.type==="tool"&&delete m.toolcalls[H.callID],yield*e.removePart({sessionID:H.sessionID,messageID:H.messageID,partID:H.id}));m.assistantMessage.finish="tool-calls",yield*r.logInfo("step ended for a person's message",{sessionID:m.sessionID,messageID:m.assistantMessage.id,dropped:q.size})}),re=r.fn("SessionProcessor.process")(function*(R){yield*r.logInfo("process",{"session.id":S.sessionID,messageID:S.assistantMessage.id}),m.needsCompaction=!1,m.shouldBreak=(yield*t.get()).experimental?.continue_loop_on_deny!==!0;let q=0,H=S.preempt?.pipe(r.andThen(r.sync(()=>{pe=!0})));return yield*r.gen(function*(){return yield*r.gen(function*(){if(pe)return;q++>0&&(yield*U()),_=new Set((yield*Ze.parts(m.assistantMessage.id).pipe(r.provideService(Qe.Service,y))).map(Ue=>Ue.id)),m.currentText=void 0,m.reasoningMap={},yield*f.set(m.sessionID,{type:"busy"});let ne=s.stream(R).pipe(jd(Ue=>V(Ue)),Fd(()=>m.needsCompaction));yield*H?r.raceFirst(ne.pipe(Na),H):ne.pipe(Na),pe&&(yield*ce())}).pipe(r.onInterrupt(ne=>r.gen(function*(){yield*r.logWarning("turn interrupted",{sessionID:m.sessionID,interruptors:[...ne].map(Ue=>String(Ue)).join(","),attempt:q}),h=!0,m.assistantMessage.error||(yield*M(new DOMException("Aborted","AbortError")))})),r.catchCauseIf(ne=>!tt.hasInterruptsOnly(ne),ne=>r.fail(tt.squash(ne))),r.catch(we),r.retry(fr.policy({provider:S.model.providerID,parse:I,set:i(ne=>f.set(m.sessionID,{type:"retry",attempt:ne.attempt,message:ne.message,action:ne.action,next:ne.next}),"set")})),r.catch(M),r.ensuring(D())),m.needsCompaction?"compact":m.blocked||m.assistantMessage.error?"stop":"continue"})});return{get message(){return m.assistantMessage},updateToolCall:A,completeToolCall:C,process:re}});return hr.of({create:b})})),Cv=ke.make({service:hr,layer:Rv,deps:[me.node,Oe.node,an.node,Ft.node,dn.node,Ke.node,pt.node,un.node,ln.node,bn.node,De.node,Qe.node]});var gr={};fe(gr,{Event:()=>Uf,PRUNE_MINIMUM:()=>Ff,PRUNE_PROTECT:()=>Bf,Service:()=>Do,SessionCompaction:()=>gr,lastStep:()=>Ac,node:()=>Hv,summaryOnPrefix:()=>jf,use:()=>zv});var ys={};fe(ys,{Compacted:()=>_f,Definitions:()=>Av,SessionCompactionEvent:()=>ys});var _f=Et.define({type:"session.compacted",schema:{sessionID:Cn}}),Av=Et.inventory(_f);import Mv from"path";import{readFile as _v}from"fs/promises";var $i="The messages before this compaction, word for word (newest last):";function Of(e){let t=[];for(let s of e)if(!(s.info.role!=="user"||s.parts.some(a=>a.type==="compaction"))){for(let a of s.parts)if(!(a.type!=="text"||!a.text?.trim())){if(!a.synthetic)t.push(a.text.trim());else if(a.text.includes($i)){let l=a.text.slice(a.text.indexOf($i)+$i.length).split(`
990
990
 
991
991
  <<<END>>>`)[0];t.push(...l.split(`
992
992
 
@@ -1000,20 +1000,20 @@ ${n.join(`
1000
1000
 
1001
1001
  `)}
1002
1002
 
1003
- <<<END>>>`}i(Of,"wordsToCarry");async function Cv(e,t){if(!Xr.ALCHEMYLAB)return"";try{let n=JSON.parse(await Rv(Pv.join(e,".alchemy_lab","action-server.json"),"utf8"));if(!n?.port)return"";let o=await fetch(`http://127.0.0.1:${n.port}/api/sessions/${encodeURIComponent(t)}/after-compaction`,{signal:AbortSignal.timeout(8e3),headers:typeof n.secret=="string"?{"x-alchemy-local":n.secret}:{}});if(!o.ok)return"";let s=await o.json();return String(s?.data?.text??"").trim()}catch{return""}}i(Cv,"recordsAfterCompaction");function Ac(e){let t;for(let n of e){let o=n.info;o.role!=="assistant"||o.summary||o.aside||!o.finish||o.error||(!t||o.time.created>t.time.created||o.time.created===t.time.created&&o.id>t.id)&&(t=o)}return t}i(Ac,"lastStep");function jf(e){let t=e.step;if(!t||t.providerID!==e.model.providerID||t.modelID!==e.model.id||t.tokens.cache.read+t.tokens.cache.write<=0)return!1;let n=Xe.cacheWarmForMs(e.model,e.cacheTtl==="5m"?"5m":void 0);return n===void 0?!1:e.now-t.time.created<n}i(jf,"summaryOnPrefix");var Uf=ys,Ff=2e4,Bf=4e4,Lf=2e3,Av=["skill"],Mv=2e3,_v=15e3,Ov=4e3,Lv=i(e=>e.length<=Lf?e:`${e.slice(0,Lf)}
1004
- [truncated]`,"truncate"),Nv=i(e=>{if(e.info.role==="user"){let t=e.parts.filter(o=>o.type==="text"&&!o.ignored).map(o=>o.text).filter(Boolean).join(`
1003
+ <<<END>>>`}i(Of,"wordsToCarry");async function Ov(e,t){if(!Xr.ALCHEMYLAB)return"";try{let n=JSON.parse(await _v(Mv.join(e,".alchemy_lab","action-server.json"),"utf8"));if(!n?.port)return"";let o=await fetch(`http://127.0.0.1:${n.port}/api/sessions/${encodeURIComponent(t)}/after-compaction`,{signal:AbortSignal.timeout(8e3),headers:typeof n.secret=="string"?{"x-alchemy-local":n.secret}:{}});if(!o.ok)return"";let s=await o.json();return String(s?.data?.text??"").trim()}catch{return""}}i(Ov,"recordsAfterCompaction");function Ac(e){let t;for(let n of e){let o=n.info;o.role!=="assistant"||o.summary||o.aside||!o.finish||o.error||(!t||o.time.created>t.time.created||o.time.created===t.time.created&&o.id>t.id)&&(t=o)}return t}i(Ac,"lastStep");function jf(e){let t=e.step;if(!t||t.providerID!==e.model.providerID||t.modelID!==e.model.id||t.tokens.cache.read+t.tokens.cache.write<=0)return!1;let n=Xe.cacheWarmForMs(e.model,e.cacheTtl==="5m"?"5m":void 0);return n===void 0?!1:e.now-t.time.created<n}i(jf,"summaryOnPrefix");var Uf=ys,Ff=2e4,Bf=4e4,Lf=2e3,Lv=["skill"],Nv=2e3,jv=15e3,Uv=4e3,Fv=i(e=>e.length<=Lf?e:`${e.slice(0,Lf)}
1004
+ [truncated]`,"truncate"),Bv=i(e=>{if(e.info.role==="user"){let t=e.parts.filter(o=>o.type==="text"&&!o.ignored).map(o=>o.text).filter(Boolean).join(`
1005
1005
  `),n=e.parts.flatMap(o=>o.type==="file"?[`[Attached ${o.mime}: ${o.filename??"file"}]`]:[]);return[...t?[`[User]: ${t}`]:[],...n].join(`
1006
- `)}return e.parts.flatMap(t=>{if(t.type==="text")return t.text?[`[Assistant]: ${t.text}`]:[];if(t.type==="reasoning")return t.text?[`[Assistant reasoning]: ${t.text}`]:[];if(t.type!=="tool")return[];let n=`[Assistant tool call]: ${t.tool}(${JSON.stringify(t.state.input)})`;if(t.state.status==="completed"){let o=(t.state.attachments??[]).map(a=>`[Attached ${a.mime}: ${a.filename??"file"}]`),s=t.state.time.compacted?"[Old tool result content cleared]":Lv([t.state.output,...o].join(`
1006
+ `)}return e.parts.flatMap(t=>{if(t.type==="text")return t.text?[`[Assistant]: ${t.text}`]:[];if(t.type==="reasoning")return t.text?[`[Assistant reasoning]: ${t.text}`]:[];if(t.type!=="tool")return[];let n=`[Assistant tool call]: ${t.tool}(${JSON.stringify(t.state.input)})`;if(t.state.status==="completed"){let o=(t.state.attachments??[]).map(a=>`[Attached ${a.mime}: ${a.filename??"file"}]`),s=t.state.time.compacted?"[Old tool result content cleared]":Fv([t.state.output,...o].join(`
1007
1007
  `));return[n,`[Tool result]: ${s}`]}return t.state.status==="error"?[n,`[Tool error]: ${t.state.error}`]:[n]}).join(`
1008
- `)},"serialize");function jv(e){return e.parts.filter(n=>n.type==="text").map(n=>n.text.trim()).filter(Boolean).join(`
1008
+ `)},"serialize");function $v(e){return e.parts.filter(n=>n.type==="text").map(n=>n.text.trim()).filter(Boolean).join(`
1009
1009
 
1010
- `).trim()||void 0}i(jv,"summaryText");function Uv(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];o.info.role==="user"&&o.parts.some(s=>s.type==="compaction")&&t.set(o.info.id,n)}return e.flatMap((n,o)=>{if(n.info.role!=="assistant")return[];if(!n.info.summary||!n.info.finish||n.info.error)return[];let s=t.get(n.info.parentID);return s===void 0?[]:[{userIndex:s,assistantIndex:o,summary:jv(n)}]})}i(Uv,"completedCompactions");function Nf(e){return e.cfg.compaction?.preserve_recent_tokens??Math.min(_v,Math.max(Mv,Math.floor(Fi(e)*.25)))}i(Nf,"preserveRecentBudget");function Fv(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n];o.info.role==="user"&&(o.parts.some(s=>s.type==="compaction")||t.push({start:n,end:e.length,id:o.info.id}))}for(let n=0;n<t.length-1;n++)t[n].end=t[n+1].start;return t}i(Fv,"turns");function Bv(e){return r.gen(function*(){if(!(e.budget<=0)&&!(e.turn.end-e.turn.start<=1)){for(let t=e.turn.start+1;t<e.turn.end;t++)if(!((yield*e.estimate({messages:e.messages.slice(t,e.turn.end),model:e.model}))>e.budget))return{start:t,id:e.messages[t].info.id}}})}i(Bv,"splitTurn");var Do=class extends Re.Service()("@opencode/SessionCompaction"){static{i(this,"Service")}},$v=Wt(Do),qv=Te.effect(Do,r.gen(function*(){let e=yield*Oe.Service,t=yield*me.Service,n=yield*Ft.Service,o=yield*pt.Service,s=yield*jn.Service,a=yield*yt.Service,l=yield*De.Service,d=yield*Be.Service,p=yield*dn.Service,f=r.fn("SessionCompaction.isOverflow")(function*(h){return Bi({cfg:yield*e.get(),tokens:h.tokens,model:h.model,outputTokenMax:d.outputTokenMax})}),u=r.fn("SessionCompaction.estimate")(function*(h){let k=yield*Ze.toModelMessagesEffect(h.messages,h.model);return ci.estimate(JSON.stringify(k))}),g=r.fn("SessionCompaction.select")(function*(h){let k=h.cfg.compaction?.tail_turns;if(k!==void 0&&k<=0)return{head:h.messages,tail_start_id:void 0};let w=Nf({cfg:h.cfg,model:h.model}),I=Fv(h.messages);if(!I.length)return{head:h.messages,tail_start_id:void 0};let P=k===void 0?I:I.slice(-k),x=0,A;for(let C=P.length-1;C>=0;C--){let $=P[C],j=yield*u({messages:h.messages.slice($.start,$.end),model:h.model});if(x+j<=w){x+=j,A={start:$.start,id:$.id};continue}let z=w-x,ie=yield*Bv({messages:h.messages,turn:$,model:h.model,budget:z,estimate:u});ie?A=ie:A||(yield*r.logInfo("tail fallback",{budget:w,size:j,total:x}));break}return!A||A.start===0?{head:h.messages,tail_start_id:void 0}:{head:h.messages.slice(0,A.start),tail_start_id:A.id}}),y=r.fn("SessionCompaction.prune")(function*(h){if(!(yield*e.get()).compaction?.prune)return;yield*r.logInfo("pruning");let w=yield*t.messages({sessionID:h.sessionID}).pipe(r.catchIf(mi.isInstance,()=>r.succeed(void 0)));if(!w)return;let I=0,P=0,x=[],A=0;e:for(let C=w.length-1;C>=0;C--){let $=w[C];if($.info.role==="user"&&A++,!(A<2)){if($.info.role==="assistant"&&$.info.summary)break e;for(let j=$.parts.length-1;j>=0;j--){let z=$.parts[j];if(z.type!=="tool"||z.state.status!=="completed"||Av.includes(z.tool))continue;if(z.state.time.compacted)break e;let ie=ci.estimate(z.state.output);I+=ie,!(I<=Bf)&&(P+=ie,x.push(z))}}}if(yield*r.logInfo("found",{pruned:P,total:I}),P>Ff){for(let C of x)C.state.status==="completed"&&(C.state.time.compacted=Date.now(),yield*t.updatePart(C));yield*r.logInfo("pruned",{count:x.length})}}),b=r.fn("SessionCompaction.serverSummary")(function*(h){let k=i((ce,re)=>r.sync(()=>(st.log("fallback to today's compaction",{"session.id":h.sessionID,reason:ce,...re}),{fallback:ce})),"fallback"),w=h.step,I=yield*h.prefix(w);if(!I)return yield*k("the session's prefix could not be rebuilt");let P=yield*r.forEach(h.history,ce=>u({messages:[ce],model:h.model})),x=w.tokens.input+w.tokens.cache.read+w.tokens.cache.write+w.tokens.output,A=P.reduce((ce,re)=>ce+re,0),C=Math.floor(Fi({cfg:h.cfg,model:h.model,outputTokenMax:d.outputTokenMax})*.75)-Math.max(0,x-A)-Ov,$=Math.min(Nf({cfg:h.cfg,model:h.model}),Math.max(0,C)),j=st.cut(h.history,P,$),z=structuredClone(j?h.history.slice(0,j.index):h.history);yield*o.trigger("experimental.chat.messages.transform",{},{messages:z});let ie=yield*Ze.toModelMessagesEffect(z,h.model),L=crypto.randomUUID();st.log("compacting",{"session.id":h.sessionID,head:z.length,kept:j?h.history.length-j.index:0,keptFrom:j?.id,keptTokens:j?.tokens??0,budget:$,room:C,context:x});let V,D=yield*p.stream({user:I.user,agent:I.agent,permission:I.permission,sessionID:h.sessionID,parentSessionID:I.parentSessionID,system:I.system,tools:I.tools,messages:ie,model:h.model,cachePoints:"all",headers:{[st.HEADER]:L}}).pipe(Js(ce=>r.sync(()=>{ce.type==="step-finish"&&(V={usage:ce.usage,providerMetadata:ce.providerMetadata})})),r.as("ok"),r.catchCause(ce=>tt.hasInterruptsOnly(ce)?r.interrupt:r.succeed(String(tt.squash(ce)).slice(0,500)))),M=st.take(L);if(D!=="ok")return yield*k("the compaction request failed",{error:D,status:M?.status,body:M?.error});if(!M?.block)return yield*k("the reply carried no compaction block",{status:M?.status,stop:M?.stopReason,body:M?.error});let _=(M.usage?.iterations??[]).find(ce=>ce?.type==="compaction"),N=_?new Mn({inputTokens:(_.input_tokens??0)+(_.cache_read_input_tokens??0)+(_.cache_creation_input_tokens??0),outputTokens:_.output_tokens??0,totalTokens:(_.input_tokens??0)+(_.cache_read_input_tokens??0)+(_.cache_creation_input_tokens??0)+(_.output_tokens??0),cacheReadInputTokens:_.cache_read_input_tokens??0,cacheWriteInputTokens:_.cache_creation_input_tokens??0}):V?.usage??new Mn({}),W=me.getUsage({model:h.model,usage:N,metadata:V?.providerMetadata}),U=yield*G.context,we=Date.now(),pe={id:at.ascending(),role:"assistant",parentID:h.parentID,sessionID:h.sessionID,mode:"compaction",agent:"compaction",variant:h.userMessage.model.variant,summary:!0,path:{cwd:U.directory,root:U.worktree},cost:W.cost,tokens:W.tokens,modelID:h.model.id,providerID:h.model.providerID,finish:"stop",time:{created:we,completed:we}};return yield*t.updateMessage(pe),st.remember(M.block),yield*t.updatePart({id:Fe.ascending(),messageID:pe.id,sessionID:h.sessionID,type:"text",text:M.block.content,time:{start:we,end:we},metadata:{[st.METADATA_KEY]:{block:M.block,system:[]}}}),st.log("block stored",{"session.id":h.sessionID,message:pe.id,chars:M.block.content.length,signature:typeof M.block.signature=="string"?M.block.signature.length:0,keptFrom:j?.id,usage:M.usage,inputTransformations:M.inputTransformations??[]}),{message:pe,tailStartID:j?.id}}),S=i(h=>r.sync(()=>{let k=Ac(h.history),w=h.tailStartID?h.history.findIndex(A=>A.info.id===h.tailStartID):-1,I=w<0?[]:h.history.slice(w).filter(A=>A.info.role==="assistant"&&!A.info.summary&&!A.info.aside),P=I.filter(A=>A.parts.some(C=>C.type==="reasoning"&&typeof C.metadata?.anthropic?.signature=="string")),x=h.message.tokens;st.log("compaction done",{"session.id":h.sessionID,agent:h.agent,model:`${h.model.providerID}/${h.model.id}`,path:h.path,...h.then?{then:h.then}:{},result:h.result,contextBefore:k?k.tokens.input+k.tokens.cache.read+k.tokens.cache.write+k.tokens.output:0,usage:{input:x.input,cacheRead:x.cache.read,cacheWrite:x.cache.write,output:x.output+x.reasoning},cost:h.message.cost,keptSteps:I.length,keptWithThinking:P.length})}),"logDone"),T=r.fn("SessionCompaction.process")(function*(h){let k=h.messages.findLast(re=>re.info.id===h.parentID);if(!k||k.info.role!=="user")throw new Error(`Compaction parent must be a user message: ${h.parentID}`);let w=k.info,I=k.parts.find(re=>re.type==="compaction"),P=h.messages,x;if(h.overflow){let re=h.messages.findIndex(q=>q.info.id===h.parentID);for(let q=re-1;q>=0;q--){let H=h.messages[q];if(H.info.role==="user"&&!H.parts.some(ne=>ne.type==="compaction")){x={info:H.info,parts:H.parts},P=h.messages.slice(0,q);break}}x&&P.some(q=>q.info.role==="user"&&!q.parts.some(H=>H.type==="compaction"))||(x=void 0,P=h.messages)}let A=yield*n.get("compaction"),C=A.model?yield*a.getModel(A.model.providerID,A.model.modelID).pipe(r.orDie):yield*a.getModel(w.model.providerID,w.model.modelID).pipe(r.orDie),$=yield*e.get(),j=I&&P.at(-1)?.info.id===h.parentID?P.slice(0,-1):P,z=Uv(j),ie=new Set(z.flatMap(re=>[re.userIndex,re.assistantIndex])),L=z.at(-1)?.summary,V=yield*G.context,D=h.prefix&&!h.overflow&&!A.model?Ac(j):void 0,M=D?yield*n.get(D.agent):void 0,_=!!D&&!!M&&jf({step:D,model:C,cacheTtl:M.options?.cacheTtl,now:Date.now()}),N=_&&D&&h.prefix&&st.on()&&st.supports(C)?yield*b({sessionID:h.sessionID,parentID:h.parentID,history:j,model:C,userMessage:w,step:D,prefix:h.prefix,cfg:$}):void 0,W=N&&"message"in N?N:void 0;W&&I&&I.tail_start_id!==W.tailStartID&&(yield*t.updatePart({...I,tail_start_id:W.tailStartID}));let U=!W&&_&&D&&h.prefix?yield*h.prefix(D):void 0,we=r.gen(function*(){let re=yield*o.trigger("experimental.session.compacting",{sessionID:h.sessionID},{context:[],prompt:void 0}),R=U?void 0:yield*g({messages:j.filter((et,Pn)=>!ie.has(Pn)),cfg:$,model:C}),q=structuredClone(R?R.head:j);yield*o.trigger("experimental.chat.messages.transform",{},{messages:q});let H=U?"":q.map(Nv).filter(Boolean).join(`
1010
+ `).trim()||void 0}i($v,"summaryText");function qv(e){let t=new Map;for(let n=0;n<e.length;n++){let o=e[n];o.info.role==="user"&&o.parts.some(s=>s.type==="compaction")&&t.set(o.info.id,n)}return e.flatMap((n,o)=>{if(n.info.role!=="assistant")return[];if(!n.info.summary||!n.info.finish||n.info.error)return[];let s=t.get(n.info.parentID);return s===void 0?[]:[{userIndex:s,assistantIndex:o,summary:$v(n)}]})}i(qv,"completedCompactions");function Nf(e){return e.cfg.compaction?.preserve_recent_tokens??Math.min(jv,Math.max(Nv,Math.floor(Fi(e)*.25)))}i(Nf,"preserveRecentBudget");function Wv(e){let t=[];for(let n=0;n<e.length;n++){let o=e[n];o.info.role==="user"&&(o.parts.some(s=>s.type==="compaction")||t.push({start:n,end:e.length,id:o.info.id}))}for(let n=0;n<t.length-1;n++)t[n].end=t[n+1].start;return t}i(Wv,"turns");function Vv(e){return r.gen(function*(){if(!(e.budget<=0)&&!(e.turn.end-e.turn.start<=1)){for(let t=e.turn.start+1;t<e.turn.end;t++)if(!((yield*e.estimate({messages:e.messages.slice(t,e.turn.end),model:e.model}))>e.budget))return{start:t,id:e.messages[t].info.id}}})}i(Vv,"splitTurn");var Do=class extends Re.Service()("@opencode/SessionCompaction"){static{i(this,"Service")}},zv=Wt(Do),Gv=Te.effect(Do,r.gen(function*(){let e=yield*Oe.Service,t=yield*me.Service,n=yield*Ft.Service,o=yield*pt.Service,s=yield*jn.Service,a=yield*yt.Service,l=yield*De.Service,d=yield*Be.Service,p=yield*dn.Service,f=r.fn("SessionCompaction.isOverflow")(function*(h){return Bi({cfg:yield*e.get(),tokens:h.tokens,model:h.model,outputTokenMax:d.outputTokenMax})}),u=r.fn("SessionCompaction.estimate")(function*(h){let k=yield*Ze.toModelMessagesEffect(h.messages,h.model);return ci.estimate(JSON.stringify(k))}),g=r.fn("SessionCompaction.select")(function*(h){let k=h.cfg.compaction?.tail_turns;if(k!==void 0&&k<=0)return{head:h.messages,tail_start_id:void 0};let w=Nf({cfg:h.cfg,model:h.model}),I=Wv(h.messages);if(!I.length)return{head:h.messages,tail_start_id:void 0};let P=k===void 0?I:I.slice(-k),x=0,A;for(let C=P.length-1;C>=0;C--){let $=P[C],j=yield*u({messages:h.messages.slice($.start,$.end),model:h.model});if(x+j<=w){x+=j,A={start:$.start,id:$.id};continue}let z=w-x,ie=yield*Vv({messages:h.messages,turn:$,model:h.model,budget:z,estimate:u});ie?A=ie:A||(yield*r.logInfo("tail fallback",{budget:w,size:j,total:x}));break}return!A||A.start===0?{head:h.messages,tail_start_id:void 0}:{head:h.messages.slice(0,A.start),tail_start_id:A.id}}),y=r.fn("SessionCompaction.prune")(function*(h){if(!(yield*e.get()).compaction?.prune)return;yield*r.logInfo("pruning");let w=yield*t.messages({sessionID:h.sessionID}).pipe(r.catchIf(mi.isInstance,()=>r.succeed(void 0)));if(!w)return;let I=0,P=0,x=[],A=0;e:for(let C=w.length-1;C>=0;C--){let $=w[C];if($.info.role==="user"&&A++,!(A<2)){if($.info.role==="assistant"&&$.info.summary)break e;for(let j=$.parts.length-1;j>=0;j--){let z=$.parts[j];if(z.type!=="tool"||z.state.status!=="completed"||Lv.includes(z.tool))continue;if(z.state.time.compacted)break e;let ie=ci.estimate(z.state.output);I+=ie,!(I<=Bf)&&(P+=ie,x.push(z))}}}if(yield*r.logInfo("found",{pruned:P,total:I}),P>Ff){for(let C of x)C.state.status==="completed"&&(C.state.time.compacted=Date.now(),yield*t.updatePart(C));yield*r.logInfo("pruned",{count:x.length})}}),b=r.fn("SessionCompaction.serverSummary")(function*(h){let k=i((ce,re)=>r.sync(()=>(st.log("fallback to today's compaction",{"session.id":h.sessionID,reason:ce,...re}),{fallback:ce})),"fallback"),w=h.step,I=yield*h.prefix(w);if(!I)return yield*k("the session's prefix could not be rebuilt");let P=yield*r.forEach(h.history,ce=>u({messages:[ce],model:h.model})),x=w.tokens.input+w.tokens.cache.read+w.tokens.cache.write+w.tokens.output,A=P.reduce((ce,re)=>ce+re,0),C=Math.floor(Fi({cfg:h.cfg,model:h.model,outputTokenMax:d.outputTokenMax})*.75)-Math.max(0,x-A)-Uv,$=Math.min(Nf({cfg:h.cfg,model:h.model}),Math.max(0,C)),j=st.cut(h.history,P,$),z=structuredClone(j?h.history.slice(0,j.index):h.history);yield*o.trigger("experimental.chat.messages.transform",{},{messages:z});let ie=yield*Ze.toModelMessagesEffect(z,h.model),L=crypto.randomUUID();st.log("compacting",{"session.id":h.sessionID,head:z.length,kept:j?h.history.length-j.index:0,keptFrom:j?.id,keptTokens:j?.tokens??0,budget:$,room:C,context:x});let V,D=yield*p.stream({user:I.user,agent:I.agent,permission:I.permission,sessionID:h.sessionID,parentSessionID:I.parentSessionID,system:I.system,tools:I.tools,messages:ie,model:h.model,cachePoints:"all",headers:{[st.HEADER]:L}}).pipe(Js(ce=>r.sync(()=>{ce.type==="step-finish"&&(V={usage:ce.usage,providerMetadata:ce.providerMetadata})})),r.as("ok"),r.catchCause(ce=>tt.hasInterruptsOnly(ce)?r.interrupt:r.succeed(String(tt.squash(ce)).slice(0,500)))),M=st.take(L);if(D!=="ok")return yield*k("the compaction request failed",{error:D,status:M?.status,body:M?.error});if(!M?.block)return yield*k("the reply carried no compaction block",{status:M?.status,stop:M?.stopReason,body:M?.error});let _=(M.usage?.iterations??[]).find(ce=>ce?.type==="compaction"),N=_?new Mn({inputTokens:(_.input_tokens??0)+(_.cache_read_input_tokens??0)+(_.cache_creation_input_tokens??0),outputTokens:_.output_tokens??0,totalTokens:(_.input_tokens??0)+(_.cache_read_input_tokens??0)+(_.cache_creation_input_tokens??0)+(_.output_tokens??0),cacheReadInputTokens:_.cache_read_input_tokens??0,cacheWriteInputTokens:_.cache_creation_input_tokens??0}):V?.usage??new Mn({}),W=me.getUsage({model:h.model,usage:N,metadata:V?.providerMetadata}),U=yield*G.context,we=Date.now(),pe={id:at.ascending(),role:"assistant",parentID:h.parentID,sessionID:h.sessionID,mode:"compaction",agent:"compaction",variant:h.userMessage.model.variant,summary:!0,path:{cwd:U.directory,root:U.worktree},cost:W.cost,tokens:W.tokens,modelID:h.model.id,providerID:h.model.providerID,finish:"stop",time:{created:we,completed:we}};return yield*t.updateMessage(pe),st.remember(M.block),yield*t.updatePart({id:Fe.ascending(),messageID:pe.id,sessionID:h.sessionID,type:"text",text:M.block.content,time:{start:we,end:we},metadata:{[st.METADATA_KEY]:{block:M.block,system:[]}}}),st.log("block stored",{"session.id":h.sessionID,message:pe.id,chars:M.block.content.length,signature:typeof M.block.signature=="string"?M.block.signature.length:0,keptFrom:j?.id,usage:M.usage,inputTransformations:M.inputTransformations??[]}),{message:pe,tailStartID:j?.id}}),S=i(h=>r.sync(()=>{let k=Ac(h.history),w=h.tailStartID?h.history.findIndex(A=>A.info.id===h.tailStartID):-1,I=w<0?[]:h.history.slice(w).filter(A=>A.info.role==="assistant"&&!A.info.summary&&!A.info.aside),P=I.filter(A=>A.parts.some(C=>C.type==="reasoning"&&typeof C.metadata?.anthropic?.signature=="string")),x=h.message.tokens;st.log("compaction done",{"session.id":h.sessionID,agent:h.agent,model:`${h.model.providerID}/${h.model.id}`,path:h.path,...h.then?{then:h.then}:{},result:h.result,contextBefore:k?k.tokens.input+k.tokens.cache.read+k.tokens.cache.write+k.tokens.output:0,usage:{input:x.input,cacheRead:x.cache.read,cacheWrite:x.cache.write,output:x.output+x.reasoning},cost:h.message.cost,keptSteps:I.length,keptWithThinking:P.length})}),"logDone"),T=r.fn("SessionCompaction.process")(function*(h){let k=h.messages.findLast(re=>re.info.id===h.parentID);if(!k||k.info.role!=="user")throw new Error(`Compaction parent must be a user message: ${h.parentID}`);let w=k.info,I=k.parts.find(re=>re.type==="compaction"),P=h.messages,x;if(h.overflow){let re=h.messages.findIndex(q=>q.info.id===h.parentID);for(let q=re-1;q>=0;q--){let H=h.messages[q];if(H.info.role==="user"&&!H.parts.some(ne=>ne.type==="compaction")){x={info:H.info,parts:H.parts},P=h.messages.slice(0,q);break}}x&&P.some(q=>q.info.role==="user"&&!q.parts.some(H=>H.type==="compaction"))||(x=void 0,P=h.messages)}let A=yield*n.get("compaction"),C=A.model?yield*a.getModel(A.model.providerID,A.model.modelID).pipe(r.orDie):yield*a.getModel(w.model.providerID,w.model.modelID).pipe(r.orDie),$=yield*e.get(),j=I&&P.at(-1)?.info.id===h.parentID?P.slice(0,-1):P,z=qv(j),ie=new Set(z.flatMap(re=>[re.userIndex,re.assistantIndex])),L=z.at(-1)?.summary,V=yield*G.context,D=h.prefix&&!h.overflow&&!A.model?Ac(j):void 0,M=D?yield*n.get(D.agent):void 0,_=!!D&&!!M&&jf({step:D,model:C,cacheTtl:M.options?.cacheTtl,now:Date.now()}),N=_&&D&&h.prefix&&st.on()&&st.supports(C)?yield*b({sessionID:h.sessionID,parentID:h.parentID,history:j,model:C,userMessage:w,step:D,prefix:h.prefix,cfg:$}):void 0,W=N&&"message"in N?N:void 0;W&&I&&I.tail_start_id!==W.tailStartID&&(yield*t.updatePart({...I,tail_start_id:W.tailStartID}));let U=!W&&_&&D&&h.prefix?yield*h.prefix(D):void 0,we=r.gen(function*(){let re=yield*o.trigger("experimental.session.compacting",{sessionID:h.sessionID},{context:[],prompt:void 0}),R=U?void 0:yield*g({messages:j.filter((et,Pn)=>!ie.has(Pn)),cfg:$,model:C}),q=structuredClone(R?R.head:j);yield*o.trigger("experimental.chat.messages.transform",{},{messages:q});let H=U?"":q.map(Bv).filter(Boolean).join(`
1011
1011
 
1012
1012
  `),ne=re.prompt??[U?_u({previousSummary:z.length>0}):Mu({previousSummary:L,context:[H]}),...re.context].filter(Boolean).join(`
1013
1013
 
1014
1014
  `),Ue={id:at.ascending(),role:"assistant",parentID:h.parentID,sessionID:h.sessionID,mode:"compaction",agent:"compaction",variant:w.model.variant,summary:!0,path:{cwd:V.directory,root:V.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelID:C.id,providerID:C.providerID,time:{created:Date.now()}};yield*t.updateMessage(Ue);let ot=yield*s.create({assistantMessage:Ue,sessionID:h.sessionID,model:C});yield*r.logInfo(U?"compacting on the session's own prefix":"compacting a serialized history",{"session.id":h.sessionID,step:D?.id,overflow:!!h.overflow,ownModel:!!A.model});let Mt=yield*ot.process(U?{user:U.user,agent:U.agent,permission:U.permission,sessionID:h.sessionID,parentSessionID:U.parentSessionID,tools:U.tools,system:U.system,messages:[...yield*Ze.toModelMessagesEffect(q,C),{role:"user",content:[{type:"text",text:ne}]}],model:C,cachePoints:"history"}:{user:w,agent:A,sessionID:h.sessionID,tools:{},system:[],messages:[{role:"user",content:[{type:"text",text:[ne,...re.prompt?["The following is the conversation history:",H]:[]].filter(Boolean).join(`
1015
1015
 
1016
- `)}]}],model:C,cachePoints:"none"});return Mt==="compact"?(ot.message.error=new dt.ContextOverflowError({message:x?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),ot.message.finish="error",yield*t.updateMessage(ot.message),{result:"stop",message:ot.message,tailStartID:void 0,onPrefix:!!U}):(I&&R?.tail_start_id&&I.tail_start_id!==R.tail_start_id&&(yield*t.updatePart({...I,tail_start_id:R.tail_start_id})),{result:Mt,message:ot.message,tailStartID:R?.tail_start_id,onPrefix:!!U})}),pe=W?{result:"continue",message:W.message,tailStartID:W.tailStartID,onPrefix:!1}:yield*we;if(yield*S({sessionID:h.sessionID,agent:D?.agent??w.agent,model:C,path:W?"anthropic":N&&"fallback"in N?`fallback:${N.fallback}`:pe.onPrefix?"prefix":"condensed",then:N&&"fallback"in N?pe.onPrefix?"prefix":"condensed":void 0,history:j,message:pe.message,tailStartID:pe.tailStartID,result:pe.result}),pe.result==="stop"&&pe.message.error)return"stop";let ce=pe.result;if(ce==="continue"&&h.auto){if(x){let re=x.info,R=yield*t.updateMessage({id:at.ascending(),role:"user",sessionID:h.sessionID,time:{created:Date.now()},agent:re.agent,model:re.model,format:re.format,tools:re.tools,system:re.system});for(let q of x.parts){if(q.type==="compaction")continue;let H=q.type==="file"&&Ze.isMedia(q.mime)?{type:"text",text:`[Attached ${q.mime}: ${q.filename??"file"}]`}:q;yield*t.updatePart({...H,id:Fe.ascending(),messageID:R.id,sessionID:h.sessionID})}}if(!x){let re=yield*a.getProvider(w.model.providerID);if((yield*o.trigger("experimental.compaction.autocontinue",{sessionID:h.sessionID,agent:w.agent,model:yield*a.getModel(w.model.providerID,w.model.modelID).pipe(r.orDie),provider:{source:re.source,info:re,options:re.options},message:w,overflow:h.overflow===!0},{enabled:!0})).enabled){let R=yield*t.updateMessage({id:at.ascending(),role:"user",sessionID:h.sessionID,time:{created:Date.now()},agent:w.agent,model:w.model}),q=yield*r.promise(()=>Cv(V.directory,h.sessionID)),H=Of(h.messages),ne=(h.overflow?`The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context. If the user was asking about attached images or files, explain that the attachments were too large to process and suggest they try again with smaller or fewer files.
1016
+ `)}]}],model:C,cachePoints:"none"});return Mt==="compact"?(ot.message.error=new dt.ContextOverflowError({message:x?"Conversation history too large to compact - exceeds model context limit":"Session too large to compact - context exceeds model limit even after stripping media"}).toObject(),ot.message.finish="error",yield*t.updateMessage(ot.message),{result:"stop",message:ot.message,tailStartID:void 0,onPrefix:!!U}):(I&&R?.tail_start_id&&I.tail_start_id!==R.tail_start_id&&(yield*t.updatePart({...I,tail_start_id:R.tail_start_id})),{result:Mt,message:ot.message,tailStartID:R?.tail_start_id,onPrefix:!!U})}),pe=W?{result:"continue",message:W.message,tailStartID:W.tailStartID,onPrefix:!1}:yield*we;if(yield*S({sessionID:h.sessionID,agent:D?.agent??w.agent,model:C,path:W?"anthropic":N&&"fallback"in N?`fallback:${N.fallback}`:pe.onPrefix?"prefix":"condensed",then:N&&"fallback"in N?pe.onPrefix?"prefix":"condensed":void 0,history:j,message:pe.message,tailStartID:pe.tailStartID,result:pe.result}),pe.result==="stop"&&pe.message.error)return"stop";let ce=pe.result;if(ce==="continue"&&h.auto){if(x){let re=x.info,R=yield*t.updateMessage({id:at.ascending(),role:"user",sessionID:h.sessionID,time:{created:Date.now()},agent:re.agent,model:re.model,format:re.format,tools:re.tools,system:re.system});for(let q of x.parts){if(q.type==="compaction")continue;let H=q.type==="file"&&Ze.isMedia(q.mime)?{type:"text",text:`[Attached ${q.mime}: ${q.filename??"file"}]`}:q;yield*t.updatePart({...H,id:Fe.ascending(),messageID:R.id,sessionID:h.sessionID})}}if(!x){let re=yield*a.getProvider(w.model.providerID);if((yield*o.trigger("experimental.compaction.autocontinue",{sessionID:h.sessionID,agent:w.agent,model:yield*a.getModel(w.model.providerID,w.model.modelID).pipe(r.orDie),provider:{source:re.source,info:re,options:re.options},message:w,overflow:h.overflow===!0},{enabled:!0})).enabled){let R=yield*t.updateMessage({id:at.ascending(),role:"user",sessionID:h.sessionID,time:{created:Date.now()},agent:w.agent,model:w.model}),q=yield*r.promise(()=>Ov(V.directory,h.sessionID)),H=Of(h.messages),ne=(h.overflow?`The previous request exceeded the provider's size limit due to large media attachments. The conversation was compacted and media files were removed from context. If the user was asking about attached images or files, explain that the attachments were too large to process and suggest they try again with smaller or fewer files.
1017
1017
 
1018
1018
  `:"")+"This session was compacted automatically to free context: the summary above covers the earlier part of it, and nothing else has happened since. "+(H||q?`Below are the messages it received and the records as they stand now.
1019
1019
 
@@ -1023,15 +1023,15 @@ ${n.join(`
1023
1023
 
1024
1024
  `:"")+(q?`${q}
1025
1025
 
1026
- `:"")+"Resume directly with the next step: do not acknowledge the summary, do not recap, and do not stop to report. Pick up the last task as if the break never happened.";yield*t.updatePart({id:Fe.ascending(),messageID:R.id,sessionID:h.sessionID,type:"text",metadata:{compaction_continue:!0},synthetic:!0,text:ne,time:{start:Date.now(),end:Date.now()}})}}}return pe.message.error?"stop":(ce==="continue"&&(yield*l.publish(Uf.Compacted,{sessionID:h.sessionID})),ce)}),m=r.fn("SessionCompaction.create")(function*(h){let k=yield*t.updateMessage({id:at.ascending(),role:"user",model:h.model,sessionID:h.sessionID,agent:h.agent,time:{created:Date.now()}});yield*t.updatePart({id:Fe.ascending(),messageID:k.id,sessionID:k.sessionID,type:"compaction",auto:h.auto,overflow:h.overflow})});return Do.of({isOverflow:f,prune:y,process:T,create:m})})),Wv=ke.make({service:Do,layer:qv,deps:[Oe.node,me.node,Ft.node,pt.node,jn.node,yt.node,De.node,Be.node,dn.node]});var br={};fe(br,{RevertInput:()=>Vv,Service:()=>yr,SessionRevert:()=>br,node:()=>Gv});var Vv=c.Struct({sessionID:Pt,messageID:at,partID:c.optional(Fe)}),yr=class extends Re.Service()("@opencode/SessionRevert"){static{i(this,"Service")}},zv=Te.effect(yr,r.gen(function*(){let e=yield*me.Service,t=yield*an.Service,n=yield*nc.Service,o=yield*De.Service,s=yield*un.Service,a=yield*Ln.Service,l=r.fn("SessionRevert.revert")(function*(f){yield*a.assertNotBusy(f.sessionID);let u=yield*e.messages({sessionID:f.sessionID}).pipe(r.orDie),g,y=yield*e.get(f.sessionID).pipe(r.orDie),b,S=[];for(let k of u){k.info.role==="user"&&(g=k.info);let w=[];for(let I of k.parts){if(b){I.type==="patch"&&S.push(I);continue}if(!b){if(k.info.id===f.messageID&&!f.partID||I.id===f.partID){let P=w.some(x=>["text","tool"].includes(x.type))?f.partID:void 0;b={messageID:!P&&g?g.id:k.info.id,partID:P}}w.push(I)}}}if(!b)return y;b.snapshot=y.revert?.snapshot??(yield*t.track()),y.revert?.snapshot&&(yield*t.restore(y.revert.snapshot)),yield*t.revert(S),b.snapshot&&(b.diff=yield*t.diff(b.snapshot));let T=u.findIndex(k=>k.info.id===b.messageID),m=T<0?[]:u.slice(T),h=yield*s.computeDiff({messages:m});return yield*n.write(["session_diff",f.sessionID],h).pipe(r.ignore),yield*o.publish(me.Event.Diff,{sessionID:f.sessionID,diff:h}),yield*e.setRevert({sessionID:f.sessionID,revert:b,summary:{additions:h.reduce((k,w)=>k+w.additions,0),deletions:h.reduce((k,w)=>k+w.deletions,0),files:h.length}}),yield*e.get(f.sessionID).pipe(r.orDie)}),d=r.fn("SessionRevert.unrevert")(function*(f){yield*r.logInfo("unreverting",{sessionID:f.sessionID}),yield*a.assertNotBusy(f.sessionID);let u=yield*e.get(f.sessionID).pipe(r.orDie);return u.revert?(u.revert.snapshot&&(yield*t.restore(u.revert.snapshot)),yield*e.clearRevert(f.sessionID),yield*e.get(f.sessionID).pipe(r.orDie)):u}),p=r.fn("SessionRevert.cleanup")(function*(f){if(!f.revert)return;let u=f.id,g=yield*e.messages({sessionID:u}).pipe(r.orDie),y=f.revert.messageID,b=g.findIndex(m=>m.info.id===y),S=b<0?void 0:g[b],T=b<0?[]:g.slice(b+(f.revert.partID?1:0));for(let m of T)yield*e.removeMessage({sessionID:u,messageID:m.info.id});if(f.revert.partID&&S){let m=f.revert.partID,h=S.parts.findIndex(k=>k.id===m);if(h>=0){let k=S.parts.slice(h);S.parts=S.parts.slice(0,h);for(let w of k)yield*e.removePart({sessionID:u,messageID:S.info.id,partID:w.id})}}yield*e.clearRevert(u)});return yr.of({revert:l,unrevert:d,cleanup:p})})),Gv=ke.make({service:yr,layer:zv,deps:[me.node,an.node,nc.node,De.node,un.node,Ln.node]});var En={};fe(En,{Instruction:()=>En,Service:()=>wr,loaded:()=>Yv,node:()=>Jv});import Ct from"path";function $f(e){let t=new Set;for(let n of e)for(let o of n.parts)if(o.type==="tool"&&o.tool==="read"&&o.state.status==="completed"){if(o.state.time.compacted)continue;let s=o.state.metadata?.loaded;if(!s||!Array.isArray(s))continue;for(let a of s)typeof a=="string"&&t.add(a)}return t}i($f,"extract");var wr=class extends Re.Service()("@opencode/Instruction"){static{i(this,"Service")}},Hv=Te.effect(wr,r.gen(function*(){let e=yield*Oe.Service,t=yield*Ae.Service,n=yield*Se.Service,o=yield*Be.Service,s=fn.filterStatusOk(li(yield*fn.HttpClient)),a=[Ct.join(n.config,"AGENTS.md"),...o.disableClaudeCodePrompt?[]:[Ct.join(n.home,".claude","CLAUDE.md")]],l=["AGENTS.md",...o.disableClaudeCodePrompt?[]:["CLAUDE.md"],"CONTEXT.md"],d=yield*G.make(r.fn("Instruction.state")(()=>r.succeed({claims:new Map}))),p=r.fnUntraced(function*(m){let h=yield*G.context;return Xr.OPENCODE_DISABLE_PROJECT_CONFIG?yield*t.globUp(m,n.config,n.config).pipe(r.catch(()=>r.succeed([]))):yield*t.globUp(m,h.directory,h.worktree).pipe(r.catch(()=>r.succeed([])))}),f=r.fnUntraced(function*(m){return yield*t.readFileString(m).pipe(r.catch(()=>r.succeed("")))}),u=r.fnUntraced(function*(m){let h=yield*s.execute(Ve.get(m)).pipe(r.timeout(5e3),r.catch(()=>r.succeed(null)));if(!h)return"";let k=yield*h.arrayBuffer.pipe(r.catch(()=>r.succeed(new ArrayBuffer(0))));return new TextDecoder().decode(k)}),g=r.fn("Instruction.clear")(function*(m){(yield*G.get(d)).claims.delete(m)}),y=r.fn("Instruction.systemPaths")(function*(){let m=yield*e.get(),h=yield*G.context,k=new Set;for(let w of a)if(yield*t.existsSafe(w)){k.add(Ct.resolve(w));break}if(!Xr.OPENCODE_DISABLE_PROJECT_CONFIG)for(let w of l){let I=yield*t.findUp(w,h.directory,h.worktree).pipe(r.catch(()=>r.succeed([])));if(I.length>0){I.forEach(P=>k.add(Ct.resolve(P)));break}}if(m.instructions)for(let w of m.instructions){if(w.startsWith("https://")||w.startsWith("http://"))continue;let I=w.startsWith("~/")?Ct.join(n.home,w.slice(2)):w;(yield*(Ct.isAbsolute(I)?t.glob(Ct.basename(I),{cwd:Ct.dirname(I),absolute:!0,include:"file"}):p(I)).pipe(r.catch(()=>r.succeed([])))).forEach(x=>k.add(Ct.resolve(x)))}return k}),b=r.fn("Instruction.system")(function*(){let m=yield*e.get(),h=yield*y(),k=(m.instructions??[]).filter(P=>P.startsWith("https://")||P.startsWith("http://")),w=yield*r.forEach(Array.from(h),f,{concurrency:8}),I=yield*r.forEach(k,u,{concurrency:4});return[...Array.from(h).flatMap((P,x)=>w[x]?[`Instructions from: ${P}
1026
+ `:"")+"Resume directly with the next step: do not acknowledge the summary, do not recap, and do not stop to report. Pick up the last task as if the break never happened.";yield*t.updatePart({id:Fe.ascending(),messageID:R.id,sessionID:h.sessionID,type:"text",metadata:{compaction_continue:!0},synthetic:!0,text:ne,time:{start:Date.now(),end:Date.now()}})}}}return pe.message.error?"stop":(ce==="continue"&&(yield*l.publish(Uf.Compacted,{sessionID:h.sessionID})),ce)}),m=r.fn("SessionCompaction.create")(function*(h){let k=yield*t.updateMessage({id:at.ascending(),role:"user",model:h.model,sessionID:h.sessionID,agent:h.agent,time:{created:Date.now()}});yield*t.updatePart({id:Fe.ascending(),messageID:k.id,sessionID:k.sessionID,type:"compaction",auto:h.auto,overflow:h.overflow})});return Do.of({isOverflow:f,prune:y,process:T,create:m})})),Hv=ke.make({service:Do,layer:Gv,deps:[Oe.node,me.node,Ft.node,pt.node,jn.node,yt.node,De.node,Be.node,dn.node]});var br={};fe(br,{RevertInput:()=>Yv,Service:()=>yr,SessionRevert:()=>br,node:()=>Kv});var Yv=c.Struct({sessionID:Pt,messageID:at,partID:c.optional(Fe)}),yr=class extends Re.Service()("@opencode/SessionRevert"){static{i(this,"Service")}},Jv=Te.effect(yr,r.gen(function*(){let e=yield*me.Service,t=yield*an.Service,n=yield*nc.Service,o=yield*De.Service,s=yield*un.Service,a=yield*Ln.Service,l=r.fn("SessionRevert.revert")(function*(f){yield*a.assertNotBusy(f.sessionID);let u=yield*e.messages({sessionID:f.sessionID}).pipe(r.orDie),g,y=yield*e.get(f.sessionID).pipe(r.orDie),b,S=[];for(let k of u){k.info.role==="user"&&(g=k.info);let w=[];for(let I of k.parts){if(b){I.type==="patch"&&S.push(I);continue}if(!b){if(k.info.id===f.messageID&&!f.partID||I.id===f.partID){let P=w.some(x=>["text","tool"].includes(x.type))?f.partID:void 0;b={messageID:!P&&g?g.id:k.info.id,partID:P}}w.push(I)}}}if(!b)return y;b.snapshot=y.revert?.snapshot??(yield*t.track()),y.revert?.snapshot&&(yield*t.restore(y.revert.snapshot)),yield*t.revert(S),b.snapshot&&(b.diff=yield*t.diff(b.snapshot));let T=u.findIndex(k=>k.info.id===b.messageID),m=T<0?[]:u.slice(T),h=yield*s.computeDiff({messages:m});return yield*n.write(["session_diff",f.sessionID],h).pipe(r.ignore),yield*o.publish(me.Event.Diff,{sessionID:f.sessionID,diff:h}),yield*e.setRevert({sessionID:f.sessionID,revert:b,summary:{additions:h.reduce((k,w)=>k+w.additions,0),deletions:h.reduce((k,w)=>k+w.deletions,0),files:h.length}}),yield*e.get(f.sessionID).pipe(r.orDie)}),d=r.fn("SessionRevert.unrevert")(function*(f){yield*r.logInfo("unreverting",{sessionID:f.sessionID}),yield*a.assertNotBusy(f.sessionID);let u=yield*e.get(f.sessionID).pipe(r.orDie);return u.revert?(u.revert.snapshot&&(yield*t.restore(u.revert.snapshot)),yield*e.clearRevert(f.sessionID),yield*e.get(f.sessionID).pipe(r.orDie)):u}),p=r.fn("SessionRevert.cleanup")(function*(f){if(!f.revert)return;let u=f.id,g=yield*e.messages({sessionID:u}).pipe(r.orDie),y=f.revert.messageID,b=g.findIndex(m=>m.info.id===y),S=b<0?void 0:g[b],T=b<0?[]:g.slice(b+(f.revert.partID?1:0));for(let m of T)yield*e.removeMessage({sessionID:u,messageID:m.info.id});if(f.revert.partID&&S){let m=f.revert.partID,h=S.parts.findIndex(k=>k.id===m);if(h>=0){let k=S.parts.slice(h);S.parts=S.parts.slice(0,h);for(let w of k)yield*e.removePart({sessionID:u,messageID:S.info.id,partID:w.id})}}yield*e.clearRevert(u)});return yr.of({revert:l,unrevert:d,cleanup:p})})),Kv=ke.make({service:yr,layer:Jv,deps:[me.node,an.node,nc.node,De.node,un.node,Ln.node]});var En={};fe(En,{Instruction:()=>En,Service:()=>wr,loaded:()=>Qv,node:()=>Zv});import Ct from"path";function $f(e){let t=new Set;for(let n of e)for(let o of n.parts)if(o.type==="tool"&&o.tool==="read"&&o.state.status==="completed"){if(o.state.time.compacted)continue;let s=o.state.metadata?.loaded;if(!s||!Array.isArray(s))continue;for(let a of s)typeof a=="string"&&t.add(a)}return t}i($f,"extract");var wr=class extends Re.Service()("@opencode/Instruction"){static{i(this,"Service")}},Xv=Te.effect(wr,r.gen(function*(){let e=yield*Oe.Service,t=yield*Ae.Service,n=yield*Se.Service,o=yield*Be.Service,s=fn.filterStatusOk(li(yield*fn.HttpClient)),a=[Ct.join(n.config,"AGENTS.md"),...o.disableClaudeCodePrompt?[]:[Ct.join(n.home,".claude","CLAUDE.md")]],l=["AGENTS.md",...o.disableClaudeCodePrompt?[]:["CLAUDE.md"],"CONTEXT.md"],d=yield*G.make(r.fn("Instruction.state")(()=>r.succeed({claims:new Map}))),p=r.fnUntraced(function*(m){let h=yield*G.context;return Xr.OPENCODE_DISABLE_PROJECT_CONFIG?yield*t.globUp(m,n.config,n.config).pipe(r.catch(()=>r.succeed([]))):yield*t.globUp(m,h.directory,h.worktree).pipe(r.catch(()=>r.succeed([])))}),f=r.fnUntraced(function*(m){return yield*t.readFileString(m).pipe(r.catch(()=>r.succeed("")))}),u=r.fnUntraced(function*(m){let h=yield*s.execute(Ve.get(m)).pipe(r.timeout(5e3),r.catch(()=>r.succeed(null)));if(!h)return"";let k=yield*h.arrayBuffer.pipe(r.catch(()=>r.succeed(new ArrayBuffer(0))));return new TextDecoder().decode(k)}),g=r.fn("Instruction.clear")(function*(m){(yield*G.get(d)).claims.delete(m)}),y=r.fn("Instruction.systemPaths")(function*(){let m=yield*e.get(),h=yield*G.context,k=new Set;for(let w of a)if(yield*t.existsSafe(w)){k.add(Ct.resolve(w));break}if(!Xr.OPENCODE_DISABLE_PROJECT_CONFIG)for(let w of l){let I=yield*t.findUp(w,h.directory,h.worktree).pipe(r.catch(()=>r.succeed([])));if(I.length>0){I.forEach(P=>k.add(Ct.resolve(P)));break}}if(m.instructions)for(let w of m.instructions){if(w.startsWith("https://")||w.startsWith("http://"))continue;let I=w.startsWith("~/")?Ct.join(n.home,w.slice(2)):w;(yield*(Ct.isAbsolute(I)?t.glob(Ct.basename(I),{cwd:Ct.dirname(I),absolute:!0,include:"file"}):p(I)).pipe(r.catch(()=>r.succeed([])))).forEach(x=>k.add(Ct.resolve(x)))}return k}),b=r.fn("Instruction.system")(function*(){let m=yield*e.get(),h=yield*y(),k=(m.instructions??[]).filter(P=>P.startsWith("https://")||P.startsWith("http://")),w=yield*r.forEach(Array.from(h),f,{concurrency:8}),I=yield*r.forEach(k,u,{concurrency:4});return[...Array.from(h).flatMap((P,x)=>w[x]?[`Instructions from: ${P}
1027
1027
  ${w[x]}`]:[]),...k.flatMap((P,x)=>I[x]?[`Instructions from: ${P}
1028
1028
  ${I[x]}`]:[])]}),S=r.fn("Instruction.find")(function*(m){for(let h of l){let k=Ct.resolve(Ct.join(m,h));if(yield*t.existsSafe(k))return k}}),T=r.fn("Instruction.resolve")(function*(m,h,k){let w=yield*y(),I=$f(m),P=[],x=yield*G.get(d),A=Ct.resolve(yield*G.directory),C=Ct.resolve(h),$=Ct.dirname(C);for(;$.startsWith(A)&&$!==A;){let j=yield*S($);if(!j||j===C||w.has(j)||I.has(j)){$=Ct.dirname($);continue}let z=x.claims.get(k);if(z||(z=new Set,x.claims.set(k,z)),z.has(j)){$=Ct.dirname($);continue}z.add(j);let ie=yield*f(j);ie&&P.push({filepath:j,content:`Instructions from: ${j}
1029
- ${ie}`}),$=Ct.dirname($)}return P});return wr.of({clear:g,systemPaths:y,system:b,find:S,resolve:T})}));function Yv(e){return $f(e)}i(Yv,"loaded");var Jv=ke.make({service:wr,layer:Hv,deps:[Oe.node,Ae.node,Se.node,Be.node,In]});var ft={};fe(ft,{Diagnostic:()=>Es,DocumentSymbol:()=>NS,Event:()=>Mm,LSP:()=>ft,Range:()=>da,Service:()=>_r,Status:()=>jS,Symbol:()=>LS,node:()=>$S});var Pr=kd(wm(),1);import ks from"path";import{pathToFileURL as so,fileURLToPath as Cx}from"url";var vm={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".csx":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};var Ax=150,ql=5e3,Wl=1e4,xm=3e3,Mx=45e3,_x=1,Ox=2,Lx=2,zl=class extends c.TaggedErrorClass()("LSPInitializeError",{serverID:c.String,cause:c.optional(c.Defect())}){static{i(this,"InitializeError")}};function Vl(e){if(e.startsWith("file://"))return be.normalizePath(Cx(e))}i(Vl,"getFilePath");function Nx(e){if(!e)return;let t=e.textDocumentSync;return typeof t=="number"?t:t?.change}i(Nx,"getSyncKind");function jx(e){let t=e.split(/\r\n|\r|\n/);return{line:t.length-1,character:t.at(-1)?.length??0}}i(jx,"endPosition");function Sm(e){let t=new Set;return e.filter(n=>{let o=JSON.stringify({code:n.code,severity:n.severity,message:n.message,source:n.source,range:n.range});return t.has(o)?!1:(t.add(o),!0)})}i(Sm,"dedupeDiagnostics");function Ux(e,t){return t?t.split(".").reduce((o,s)=>{if(!(!o||typeof o!="object"||!(s in o)))return o[s]},e)??null:e??null}i(Ux,"configurationValue");function Fx(e){return e==="typescript"}i(Fx,"shouldSeedDiagnosticsOnFirstPush");async function Im(e){let t=e.instance,n=(0,Pr.createMessageConnection)(new Pr.StreamMessageReader(e.server.process.stdout),new Pr.StreamMessageWriter(e.server.process.stdin));e.server.process.stderr?.resume();let o=new Map,s=new Map,a=new Map,l=new Map,d=new Set,p=new Set,f=i(D=>Sm([...o.get(D)??[],...s.get(D)??[]]),"mergedDiagnostics"),u=i((D,M)=>{o.set(D,M);for(let _ of p)_({path:D,serverID:e.serverID})},"updatePushDiagnostics"),g=i((D,M)=>{s.set(D,M)},"updatePullDiagnostics"),y=i(()=>{for(let D of[...d])D()},"emitRegistrationChange");n.onNotification("textDocument/publishDiagnostics",D=>{let M=Vl(D.uri);if(M){if(a.set(M,{at:Date.now(),version:typeof D.version=="number"?D.version:void 0}),Fx(e.serverID)&&!o.has(M)){o.set(M,D.diagnostics);return}u(M,D.diagnostics)}}),n.onRequest("window/workDoneProgress/create",D=>null),n.onRequest("workspace/configuration",async D=>(D.items??[]).map(_=>Ux(e.server.initialization,_.section))),n.onRequest("client/registerCapability",async D=>{let M=D.registrations??[],_=!1;for(let N of M)N.method==="textDocument/diagnostic"&&(l.set(N.id,N),_=!0);_&&y()}),n.onRequest("client/unregisterCapability",async D=>{let M=D.unregisterations??[],_=!1;for(let N of M)N.method==="textDocument/diagnostic"&&(l.delete(N.id),_=!0);_&&y()}),n.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:so(e.root).href}]),n.onRequest("workspace/diagnostic/refresh",async()=>null),n.listen();let b=await hi(n.sendRequest("initialize",{rootUri:so(e.root).href,processId:e.server.process.pid,workspaceFolders:[{name:"workspace",uri:so(e.root).href}],initializationOptions:{...e.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0},diagnostics:{refreshSupport:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!0},publishDiagnostics:{versionSupport:!1}}}}),Mx).catch(D=>{throw new zl({serverID:e.serverID,cause:D})}),S=Nx(b.capabilities),T=!!b.capabilities?.diagnosticProvider;await n.sendNotification("initialized",{}),e.server.initialization&&await n.sendNotification("workspace/didChangeConfiguration",{settings:e.server.initialization});let m={},h=i((D,M)=>{let _=M.some(U=>U.handled),N=M.some(U=>U.matched);if(!_)return{handled:!1,matched:!1};let W=new Map;for(let U of M)for(let[we,pe]of U.byFile.entries()){let ce=W.get(we)??[];W.set(we,ce.concat(pe))}N&&!W.has(D)&&W.set(D,[]);for(let[U,we]of W.entries())g(U,Sm(we));return{handled:_,matched:N}},"mergeResults");async function k(D,M){let _=await hi(n.sendRequest("textDocument/diagnostic",{...M?{identifier:M}:{},textDocument:{uri:so(D).href}}),xm).catch(()=>null);if(!_)return{handled:!1,matched:!1,byFile:new Map};let N=new Map,W=i((pe,ce)=>{let re=N.get(pe)??[];N.set(pe,re.concat(ce))},"push"),U=!1,we=!1;Array.isArray(_.items)&&(W(D,_.items),U=!0,we=!0);for(let[pe,ce]of Object.entries(_.relatedDocuments??{})){let re=Vl(pe);!re||!Array.isArray(ce.items)||(W(re,ce.items),U=!0,we=we||re===D)}return{handled:U,matched:we,byFile:N}}i(k,"requestDiagnosticReport");async function w(D,M){let _=await hi(n.sendRequest("workspace/diagnostic",{...M?{identifier:M}:{},previousResultIds:[]}),xm).catch(()=>null);if(!_)return{handled:!1,matched:!1,byFile:new Map};let N=new Map,W=!1;for(let U of _.items??[]){let we=U.uri?Vl(U.uri):void 0;if(!we||!Array.isArray(U.items))continue;let pe=N.get(we)??[];N.set(we,pe.concat(U.items)),W=W||we===D}return{handled:!0,matched:W,byFile:N}}i(w,"requestWorkspaceDiagnosticReport");function I(){let D=[...l.values()].filter(M=>M.registerOptions?.workspaceDiagnostics!==!0);return{documentIdentifiers:[...new Set(D.flatMap(M=>M.registerOptions?.identifier??[]))],supported:T||D.length>0}}i(I,"documentPullState");function P(){let D=[...l.values()].filter(M=>M.registerOptions?.workspaceDiagnostics===!0);return{workspaceIdentifiers:[...new Set(D.flatMap(M=>M.registerOptions?.identifier??[]))],supported:D.length>0}}i(P,"workspacePullState");let x=i((D,M)=>M.some(_=>(_.byFile.get(D)?.length??0)>0),"hasCurrentFileDiagnostics");async function A(D,M,_){if(!M.length)return{handled:!1,matched:!1};let N=[];return new Promise(W=>{let U=M.length,we=!1,pe=i((ce,re=!1)=>{we||!re&&!_(N)||(we=!0,W(ce))},"finish");for(let ce of M)ce.then(re=>{N.push(re),U-=1;let R=h(D,N);pe(R),U===0&&pe(R,!0)})})}i(A,"requestDiagnostics");async function C(D){let M=I();return M.supported?A(D,[k(D),...M.documentIdentifiers.map(_=>k(D,_))],_=>x(D,_)):{handled:!1,matched:!1}}i(C,"requestDocumentDiagnostics");async function $(D){let M=I(),_=P();return!M.supported&&!_.supported?{handled:!1,matched:!1}:h(D,await Promise.all([...M.supported?[k(D)]:[],...M.documentIdentifiers.map(N=>k(D,N)),..._.supported?[w(D)]:[],..._.workspaceIdentifiers.map(N=>w(D,N))]))}i($,"requestFullDiagnostics");function j(D){return D<=0?Promise.resolve(!1):new Promise(M=>{let _=!1,N,W=i(we=>{_||(_=!0,N&&clearTimeout(N),d.delete(U),M(we))},"finish"),U=i(()=>W(!0),"listener");d.add(U),N=setTimeout(()=>W(!1),D)})}i(j,"waitForRegistrationChange");function z(D){return D.timeout<=0?Promise.resolve(!1):new Promise(M=>{let _=!1,N,W,U,we=i(re=>{_||(_=!0,N&&clearTimeout(N),W&&clearTimeout(W),U?.(),M(re))},"finish"),pe=i(()=>{let re=a.get(D.path);re&&(typeof re.version=="number"&&re.version!==D.version||re.at<D.after&&re.version!==D.version||(N&&clearTimeout(N),N=setTimeout(()=>we(!0),Math.max(0,Ax-(Date.now()-re.at)))))},"schedule");W=setTimeout(()=>we(!1),D.timeout);let ce=i(re=>{re.path!==D.path||re.serverID!==e.serverID||pe()},"listener");p.add(ce),U=i(()=>p.delete(ce),"unsub"),pe()})}i(z,"waitForFreshPush");async function ie(D){let M=D.after??Date.now(),_=z({path:D.path,version:D.version,after:M,timeout:ql});for(;Date.now()-M<ql;){if((await C(D.path)).matched)return;let W=ql-(Date.now()-M);if(W<=0||await Promise.race([_.then(we=>we?"push":"timeout"),j(W).then(we=>we?"registration":"timeout")])!=="registration")return}}i(ie,"waitForDocumentDiagnostics");async function L(D){let M=D.after??Date.now(),_=z({path:D.path,version:D.version,after:M,timeout:Wl});for(;Date.now()-M<Wl;){let N=await $(D.path);if(N.handled||N.matched)return;let W=Wl-(Date.now()-M);if(W<=0||await Promise.race([_.then(we=>we?"push":"timeout"),j(W).then(we=>we?"registration":"timeout")])!=="registration")return}}return i(L,"waitForFullDiagnostics"),{root:e.root,get serverID(){return e.serverID},get connection(){return n},notify:{async open(D){D.path=be.normalizePath(ks.isAbsolute(D.path)?D.path:ks.resolve(e.directory,D.path));let M=await be.readText(D.path),_=ks.extname(D.path),N=vm[_]??"plaintext",W=m[D.path];if(W!==void 0){await n.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:so(D.path).href,type:Ox}]});let U=W.version+1;return m[D.path]={version:U,text:M},await n.sendNotification("textDocument/didChange",{textDocument:{uri:so(D.path).href,version:U},contentChanges:S===Lx?[{range:{start:{line:0,character:0},end:jx(W.text)},text:M}]:[{text:M}]}),U}return await n.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:so(D.path).href,type:_x}]}),o.delete(D.path),s.delete(D.path),await n.sendNotification("textDocument/didOpen",{textDocument:{uri:so(D.path).href,languageId:N,version:0,text:M}}),m[D.path]={version:0,text:M},0}},get diagnostics(){let D=new Map;for(let M of new Set([...o.keys(),...s.keys()]))D.set(M,f(M));return D},async waitForDiagnostics(D){let M=be.normalizePath(ks.isAbsolute(D.path)?D.path:ks.resolve(e.directory,D.path));if(D.mode==="document"){await ie({path:M,version:D.version,after:D.after});return}await L({path:M,version:D.version,after:D.after})},async shutdown(){n.end(),n.dispose(),await it.stop(e.server.process)}}}i(Im,"create");import Yl from"path";import{pathToFileURL as Mr,fileURLToPath as OS}from"url";var Hl={};fe(Hl,{Astro:()=>pS,BashLS:()=>SS,Biome:()=>Kx,CSharp:()=>oS,Clangd:()=>dS,Clojure:()=>TS,Dart:()=>vS,Deno:()=>zx,DockerfileLS:()=>DS,ESLint:()=>Yx,ElixirLS:()=>tS,FSharp:()=>aS,Gleam:()=>ES,Gopls:()=>Xx,HLS:()=>CS,JDTLS:()=>mS,JuliaLS:()=>AS,KotlinLS:()=>hS,LuaLS:()=>yS,Nixd:()=>PS,Ocaml:()=>xS,Oxlint:()=>Jx,PHPIntelephense:()=>bS,Prisma:()=>wS,Pyright:()=>eS,Razor:()=>rS,Rubocop:()=>Qx,RustAnalyzer:()=>lS,SourceKit:()=>cS,Svelte:()=>uS,TerraformLS:()=>IS,TexLab:()=>kS,Tinymist:()=>RS,Ty:()=>Zx,Typescript:()=>Gx,Vue:()=>Hx,YamlLS:()=>gS,Zls:()=>nS});import ee from"path";import Cr from"os";import{text as Wx}from"node:stream/consumers";import qe from"fs/promises";var on={};fe(on,{Archive:()=>on,extractZip:()=>Bx});import Dm from"path";async function Bx(e,t){if(process.platform==="win32"){let n=Dm.resolve(e),o=Dm.resolve(t),s=`$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${n}' -DestinationPath '${o}' -Force`;await Qa(["powershell","-NoProfile","-NonInteractive","-Command",s]);return}await Qa(["unzip","-o","-q",e,"-d",t])}i(Bx,"extractZip");import{createRequire as $x}from"node:module";import qx from"node:path";var Rr;(t=>{function e(n,o){try{return $x(qx.join(o,"package.json")).resolve(n)}catch{}}t.resolve=e,i(e,"resolve")})(Rr||={});function Ee(e,t,n){let o=Array.isArray(t)?[...t]:[],s=Array.isArray(t)?n:t,a=it.spawn([e,...o],{...s,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!a.stdin||!a.stdout||!a.stderr)throw new Error("Process output not available");return a}i(Ee,"spawn");var Ar=i(async e=>qe.stat(e).then(()=>!0).catch(()=>!1),"pathExists"),Ro=i((e,t={})=>it.run(e,{...t,nothrow:!0}),"run"),Vx=i((e,t={})=>it.text(e,{...t,nothrow:!0}),"output"),Le=i((e,t)=>async(n,o)=>{if(t){let l=be.up({targets:t,start:ee.dirname(n),stop:o.directory}),d=await l.next();if(await l.return(),d.value)return}let s=be.up({targets:e,start:ee.dirname(n),stop:o.directory}),a=await s.next();return await s.return(),a.value?ee.dirname(a.value):o.directory},"NearestRoot"),la=i((e,t)=>async(n,o)=>{if(t){let l=be.up({targets:t,start:ee.dirname(n),stop:o.directory}),d=await l.next();if(await l.return(),d.value)return}let s=be.up({targets:e,start:ee.dirname(n),stop:o.directory}),a=await s.next();if(await s.return(),!!a.value)return ee.dirname(a.value)},"StrictNearestRoot"),zx={id:"deno",root:i(async(e,t)=>{let n=be.up({targets:["deno.json","deno.jsonc"],start:ee.dirname(e),stop:t.directory}),o=await n.next();if(await n.return(),!!o.value)return ee.dirname(o.value)},"root"),extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(e){let t=se("deno");if(t)return{process:Ee(t,["lsp"],{cwd:e})}}},Gx={id:"typescript",root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn(e,t){let n=Rr.resolve("typescript/lib/tsserver.js",t.directory);if(!n)return;let o=await Ut.which("typescript-language-server");return o?{process:Ee(o,["--stdio"],{cwd:e,env:{...process.env}}),initialization:{tsserver:{path:n}}}:void 0}},Hx={id:"vue",extensions:[".vue"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("vue-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("@vue/language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{}}}},Yx={id:"eslint",root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn(e,t,n){if(!Rr.resolve("eslint",t.directory))return;let s=ee.join(Se.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await be.exists(s)){if(n.disableLspDownload)return;let l=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!l.ok)return;let d=ee.join(Se.Path.bin,"vscode-eslint.zip");if(l.body&&await be.writeStream(d,l.body),!await on.extractZip(d,Se.Path.bin).then(()=>!0).catch(b=>!1))return;await qe.rm(d,{force:!0});let f=ee.join(Se.Path.bin,"vscode-eslint-main"),u=ee.join(Se.Path.bin,"vscode-eslint");await qe.stat(u).catch(()=>{})&&await qe.rm(u,{force:!0,recursive:!0}),await qe.rename(f,u);let y=process.platform==="win32"?"npm.cmd":"npm";await it.run([y,"install"],{cwd:u}),await it.run([y,"run","compile"],{cwd:u})}return{process:Ee("node",[s,"--stdio"],{cwd:e,env:{...process.env}})}}},Jx={id:"oxlint",root:Le([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn(e,t){let n=process.platform==="win32"?".cmd":"",o=ee.join("node_modules",".bin","oxc_language_server"+n),s=ee.join("node_modules",".bin","oxlint"+n),a=i(async p=>{let f=ee.join(e,p);if(await be.exists(f))return f;let u=be.up({targets:[p],start:e,stop:t.worktree}),g=await u.next();if(await u.return(),g.value)return g.value},"resolveBin"),l=await a(s);if(!l){let p=se("oxlint");p&&(l=p)}if(l){let p=Ee(l,["--help"]);if(await p.exited,p.stdout&&(await Wx(p.stdout)).includes("--lsp"))return{process:Ee(l,["--lsp"],{cwd:e})}}let d=await a(o);if(!d){let p=se("oxc_language_server");p&&(d=p)}if(d)return{process:Ee(d,[],{cwd:e})}}},Kx={id:"biome",root:Le(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn(e){let t=ee.join(e,"node_modules",".bin","biome"),n;if(await be.exists(t)&&(n=t),!n){let a=se("biome");a&&(n=a)}let o=["lsp-proxy","--stdio"];if(!n){if(!Rr.resolve("biome",e)||(n=await Ut.which("biome"),!n))return;o=["lsp-proxy","--stdio"]}return{process:Ee(n,o,{cwd:e,env:{...process.env}})}}},Xx={id:"gopls",root:i(async(e,t)=>{let n=await Le(["go.work"])(e,t);return n||Le(["go.mod","go.sum"])(e,t)},"root"),extensions:[".go"],async spawn(e,t,n){let o=se("gopls");if(!o){if(!se("go")||n.disableLspDownload||await it.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{...process.env,GOBIN:Se.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"gopls"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,{cwd:e})}}},Qx={id:"ruby-lsp",root:Le(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(e,t,n){let o=se("rubocop");if(!o){let s=se("ruby"),a=se("gem");if(!s||!a||n.disableLspDownload||await it.spawn(["gem","install","rubocop","--bindir",Se.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"rubocop"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,["--lsp"],{cwd:e})}}},Zx={id:"ty",extensions:[".py",".pyi"],root:Le(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,n){if(!n.experimentalLspTy)return;let o=se("ty"),s={},a=[process.env.VIRTUAL_ENV,ee.join(e,".venv"),ee.join(e,"venv")].filter(d=>d!==void 0);for(let d of a){let f=process.platform==="win32"?ee.join(d,"Scripts","python.exe"):ee.join(d,"bin","python");if(await be.exists(f)){s.pythonPath=f;break}}if(!o)for(let d of a){let f=process.platform==="win32"?ee.join(d,"Scripts","ty.exe"):ee.join(d,"bin","ty");if(await be.exists(f)){o=f;break}}return o?{process:Ee(o,["server"],{cwd:e}),initialization:s}:void 0}},eS={id:"pyright",extensions:[".py",".pyi"],root:Le(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,n){let o=se("pyright-langserver"),s=[];if(!o){if(n.disableLspDownload)return;let p=await Ut.which("pyright","pyright-langserver");if(!p)return;o=p}s.push("--stdio");let a={},l=[process.env.VIRTUAL_ENV,ee.join(e,".venv"),ee.join(e,"venv")].filter(p=>p!==void 0);for(let p of l){let u=process.platform==="win32"?ee.join(p,"Scripts","python.exe"):ee.join(p,"bin","python");if(await be.exists(u)){a.pythonPath=u;break}}return{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:a}}},tS={id:"elixir-ls",extensions:[".ex",".exs"],root:Le(["mix.exs","mix.lock"]),async spawn(e,t,n){let o=se("elixir-ls");if(!o){let s=ee.join(Se.Path.bin,"elixir-ls");if(o=ee.join(Se.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await be.exists(o)){if(!se("elixir")||n.disableLspDownload)return;let l=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!l.ok)return;let d=ee.join(Se.Path.bin,"elixir-ls.zip");if(l.body&&await be.writeStream(d,l.body),!await on.extractZip(d,Se.Path.bin).then(()=>!0).catch(g=>!1))return;await qe.rm(d,{force:!0,recursive:!0});let f=ee.join(Se.Path.bin,"elixir-ls-master"),u={MIX_ENV:"prod",...process.env};await it.run(["mix","deps.get"],{cwd:f,env:u}),await it.run(["mix","compile"],{cwd:f,env:u}),await it.run(["mix","elixir_ls.release2","-o","release"],{cwd:f,env:u})}}return{process:Ee(o,{cwd:e})}}},nS={id:"zls",extensions:[".zig",".zon"],root:Le(["build.zig"]),async spawn(e,t,n){let o=se("zls");if(!o){if(!se("zig")||n.disableLspDownload)return;let a=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!a.ok)return;let l=await a.json(),d=process.platform,p=process.arch,f="",u=p;p==="arm64"?u="aarch64":p==="x64"?u="x86_64":p==="ia32"&&(u="x86");let g=d;d==="darwin"?g="macos":d==="win32"&&(g="windows");let y=d==="win32"?"zip":"tar.xz";if(f=`zls-${u}-${g}.${y}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(f))return;let S=l.assets?.find(k=>k.name===f);if(!S?.browser_download_url)return;let T=S.browser_download_url,m=await fetch(T);if(!m.ok)return;let h=ee.join(Se.Path.bin,f);if(m.body&&await be.writeStream(h,m.body),y==="zip"){if(!await on.extractZip(h,Se.Path.bin).then(()=>!0).catch(w=>!1))return}else await Ro(["tar","-xf",h],{cwd:Se.Path.bin});if(await qe.rm(h,{force:!0}),o=ee.join(Se.Path.bin,"zls"+(d==="win32"?".exe":"")),!await be.exists(o))return;d!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},oS={id:"csharp",root:Le([".slnx",".sln",".csproj","global.json"]),extensions:[".cs",".csx"],async spawn(e,t,n){let o=await Em(n.disableLspDownload);if(o)return{process:Ee(o,["--stdio","--autoLoadProjects"],{cwd:e})}}},rS={id:"razor",root:Le([".slnx",".sln",".csproj","global.json"]),extensions:[".razor",".cshtml"],async spawn(e,t,n){let o=await Em(n.disableLspDownload);if(!o)return;let s=await iS();if(s)return{process:Ee(o,["--stdio","--autoLoadProjects",`--razorSourceGenerator=${s.compiler}`,`--razorDesignTimePath=${s.targets}`,"--extension",s.extension],{cwd:e})}}},Gl;async function Em(e){let t=se("roslyn-language-server");if(t)return t;let n=await Tm();return n||(Gl||=sS(e).finally(()=>{Gl=void 0}),Gl)}i(Em,"getRoslynLanguageServer");async function sS(e){if(!se("dotnet")||e||await it.spawn(["dotnet","tool","install","--global","roslyn-language-server","--prerelease"],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;let o=se("roslyn-language-server");if(o)return o;let s=await Tm();if(s)return s}i(sS,"installRoslynLanguageServer");async function Tm(){let e=ee.join(process.env.DOTNET_CLI_HOME??Cr.homedir(),".dotnet","tools","roslyn-language-server"+(process.platform==="win32"?".cmd":""));return await Ar(e)?e:void 0}i(Tm,"roslynLanguageServerGlobalPath");async function iS(){let e=[process.env.VSCODE_EXTENSIONS,ee.join(Cr.homedir(),".vscode","extensions"),ee.join(Cr.homedir(),".vscode-insiders","extensions"),ee.join(Cr.homedir(),".vscode-server","extensions"),ee.join(Cr.homedir(),".vscode-server-insiders","extensions")].filter(t=>t!==void 0);for(let t of[...new Set(e)]){let n=await qe.readdir(t,{withFileTypes:!0}).catch(()=>[]),o=await Promise.all(n.filter(s=>s.isDirectory()&&s.name.startsWith("ms-dotnettools.csharp-")).map(async s=>({path:ee.join(t,s.name,".razorExtension"),modified:(await qe.stat(ee.join(t,s.name)).catch(()=>{}))?.mtimeMs??0})));for(let s of o.sort((a,l)=>l.modified-a.modified).map(a=>a.path)){let a={compiler:ee.join(s,"Microsoft.CodeAnalysis.Razor.Compiler.dll"),targets:ee.join(s,"Targets","Microsoft.NET.Sdk.Razor.DesignTime.targets"),extension:ee.join(s,"Microsoft.VisualStudioCode.RazorExtension.dll")};if(await Ar(a.compiler)&&await Ar(a.targets)&&await Ar(a.extension))return a}}}i(iS,"findVscodeRazorExtension");var aS={id:"fsharp",root:Le([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(e,t,n){let o=se("fsautocomplete");if(!o){if(!se("dotnet")||n.disableLspDownload||await it.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",Se.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,{cwd:e})}}},cS={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:Le(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(e){let t=se("sourcekit-lsp");if(t)return{process:Ee(t,{cwd:e})};if(!se("xcrun"))return;let n=await Vx(["xcrun","--find","sourcekit-lsp"]);if(n.code!==0)return;let o=n.text.trim();return{process:Ee(o,{cwd:e})}}},lS={id:"rust",root:i(async(e,t)=>{let n=await Le(["Cargo.toml","Cargo.lock"])(e,t);if(n===void 0)return;let o=n;for(;o!==ee.dirname(o);){let s=ee.join(o,"Cargo.toml");try{if((await be.readText(s)).includes("[workspace]"))return o}catch{}let a=ee.dirname(o);if(a===o||(o=a,!o.startsWith(t.worktree)))break}return n},"root"),extensions:[".rs"],async spawn(e){let t=se("rust-analyzer");if(t)return{process:Ee(t,{cwd:e})}}},dS={id:"clangd",root:Le(["compile_commands.json","compile_flags.txt",".clangd"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(e,t,n){let o=["--background-index","--clang-tidy"],s=se("clangd");if(s)return{process:Ee(s,o,{cwd:e})};let a=process.platform==="win32"?".exe":"",l=ee.join(Se.Path.bin,"clangd"+a);if(await be.exists(l))return{process:Ee(l,o,{cwd:e})};let d=await qe.readdir(Se.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let C of d){if(!C.isDirectory()||!C.name.startsWith("clangd_"))continue;let $=ee.join(Se.Path.bin,C.name,"bin","clangd"+a);if(await be.exists($))return{process:Ee($,o,{cwd:e})}}if(n.disableLspDownload)return;let p=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!p.ok)return;let f=await p.json(),u=f.tag_name;if(!u)return;let g=process.platform,b={darwin:"mac",linux:"linux",win32:"windows"}[g];if(!b)return;let S=f.assets??[],T=i(C=>!C.name||!C.browser_download_url||!C.name.includes(b)?!1:C.name.includes(u),"valid"),m=S.find(C=>T(C)&&C.name?.endsWith(".zip"))??S.find(C=>T(C)&&C.name?.endsWith(".tar.xz"))??S.find(C=>T(C));if(!m?.name||!m.browser_download_url)return;let h=m.name,k=await fetch(m.browser_download_url);if(!k.ok)return;let w=ee.join(Se.Path.bin,h),I=await k.arrayBuffer();if(I.byteLength===0)return;await be.write(w,Buffer.from(I));let P=h.endsWith(".zip"),x=h.endsWith(".tar.xz");if(!P&&!x||P&&!await on.extractZip(w,Se.Path.bin).then(()=>!0).catch($=>!1))return;x&&await Ro(["tar","-xf",w],{cwd:Se.Path.bin}),await qe.rm(w,{force:!0});let A=ee.join(Se.Path.bin,"clangd_"+u,"bin","clangd"+a);if(await be.exists(A))return g!=="win32"&&await qe.chmod(A,493).catch(()=>{}),await qe.unlink(ee.join(Se.Path.bin,"clangd")).catch(()=>{}),await qe.symlink(A,ee.join(Se.Path.bin,"clangd")).catch(()=>{}),{process:Ee(A,o,{cwd:e})}}},uS={id:"svelte",extensions:[".svelte"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("svelteserver"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("svelte-language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{}}}},pS={id:"astro",extensions:[".astro"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=Rr.resolve("typescript/lib/tsserver.js",t.directory);if(!o)return;let s=ee.dirname(o),a=se("astro-ls"),l=[];if(!a){if(n.disableLspDownload)return;let p=await Ut.which("@astrojs/language-server");if(!p)return;a=p}return l.push("--stdio"),{process:Ee(a,l,{cwd:e,env:{...process.env}}),initialization:{typescript:{tsdk:s}}}}};function fS(e,t){let n=t.replace(/\\/g,"/").replace(/\/$/,"");if(!n)return!1;let o=e.match(/<modules>([\s\S]*?)<\/modules>/g)??[];for(let s of o){let a=s.replace(/<!--[\s\S]*?-->/g,"");for(let l of a.matchAll(/<module>\s*([^<]+?)\s*<\/module>/g))if(l[1].replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"")===n)return!0}return!1}i(fS,"isModuleOf");var mS={id:"jdtls",root:i(async(e,t)=>{let n=["settings.gradle","settings.gradle.kts"],o=["gradlew","gradlew.bat"],[s,a]=await Promise.all([la(o,n)(e,t),la(n)(e,t)]);if(s)return s;if(a)return a;let l=await la(["build.gradle","build.gradle.kts"])(e,t);if(l)return l;let d=await be.findUp("pom.xml",ee.dirname(e),t.directory);if(d.length>0){let f=ee.dirname(d[0]);for(let u=1;u<d.length;u++){let g=ee.dirname(d[u]),y=ee.relative(g,f),b=await qe.readFile(d[u],"utf-8").catch(()=>null);if(b&&fS(b,y))f=g;else break}return f}let p=await la([".project",".classpath"])(e,t);if(p)return p},"root"),extensions:[".java"],async spawn(e,t,n){let o=se("java");if(!o)return;let s=await Ro(["java","-version"]).then(y=>{let b=/"(\d+)\.\d+\.\d+"/.exec(y.stderr.toString());return b?parseInt(b[1]):void 0});if(s==null||s<21)return;let a=ee.join(Se.Path.bin,"jdtls"),l=ee.join(a,"plugins");if(!await Ar(l)){if(n.disableLspDownload)return;await qe.mkdir(a,{recursive:!0});let y="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",b="release.tar.gz",S=await fetch(y);if(!S.ok||!S.body||(await be.writeStream(ee.join(a,b),S.body),(await Ro(["tar","-xzf",b],{cwd:a})).code!==0))return;await qe.rm(ee.join(a,b),{force:!0})}let p=(await qe.readdir(l).catch(()=>[])).find(y=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(y))?.trim()??"",f=ee.join(l,p);if(!await Ar(f))return;let u=ee.join(a,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),g=await qe.mkdtemp(ee.join(Cr.tmpdir(),"opencode-jdtls-data"));return{process:Ee(o,["-jar",f,"-configuration",u,"-data",g,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:e})}}},hS={id:"kotlin-ls",extensions:[".kt",".kts"],root:i(async(e,t)=>{let n=await Le(["settings.gradle.kts","settings.gradle"])(e,t);if(n)return n;let o=await Le(["gradlew","gradlew.bat"])(e,t);if(o)return o;let s=await Le(["build.gradle.kts","build.gradle"])(e,t);return s||Le(["pom.xml"])(e,t)},"root"),async spawn(e,t,n){let o=ee.join(Se.Path.bin,"kotlin-ls"),s=process.platform==="win32"?ee.join(o,"kotlin-lsp.cmd"):ee.join(o,"kotlin-lsp.sh");if(!await be.exists(s)){if(n.disableLspDownload)return;let l=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!l.ok)return;let p=(await l.json()).name?.replace(/^v/,"");if(!p)return;let f=process.platform,u=process.arch,g=u;u==="arm64"?g="aarch64":u==="x64"&&(g="x64");let y=f;f==="darwin"?y="mac":f==="linux"?y="linux":f==="win32"&&(y="win");let b=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],S=`${y}-${g}`;if(!b.includes(S))return;let T=`kotlin-lsp-${p}-${y}-${g}.zip`,m=`https://download-cdn.jetbrains.com/kotlin-lsp/${p}/${T}`;await qe.mkdir(o,{recursive:!0});let h=ee.join(o,"kotlin-ls.zip"),k=await fetch(m);if(!k.ok||!k.body||(await be.writeStream(h,k.body),!await on.extractZip(h,o).then(()=>!0).catch(I=>!1)))return;await qe.rm(h,{force:!0}),process.platform!=="win32"&&await qe.chmod(s,493).catch(()=>{})}if(await be.exists(s))return{process:Ee(s,["--stdio"],{cwd:e})}}},gS={id:"yaml-ls",extensions:[".yaml",".yml"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("yaml-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("yaml-language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},yS={id:"lua-ls",root:Le([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(e,t,n){let o=se("lua-language-server");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,d=process.arch,p="",f=d;d==="arm64"?f="arm64":d==="x64"?f="x64":d==="ia32"&&(f="ia32");let u=l;l==="darwin"?u="darwin":l==="linux"?u="linux":l==="win32"&&(u="win32");let g=l==="win32"?"zip":"tar.gz";p=`lua-language-server-${a.tag_name}-${u}-${f}.${g}`;let y=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],b=`${u}-${f}.${g}`;if(!y.includes(b))return;let S=a.assets.find(I=>I.name===p);if(!S)return;let T=S.browser_download_url,m=await fetch(T);if(!m.ok)return;let h=ee.join(Se.Path.bin,p);m.body&&await be.writeStream(h,m.body);let k=ee.join(Se.Path.bin,`lua-language-server-${f}-${u}`);if(await qe.stat(k).catch(()=>{})&&await qe.rm(k,{force:!0,recursive:!0}),await qe.mkdir(k,{recursive:!0}),g==="zip"){if(!await on.extractZip(h,k).then(()=>!0).catch(P=>!1))return}else if(!await Ro(["tar","-xzf",h,"-C",k]).then(P=>P.code===0).catch(P=>!1))return;if(await qe.rm(h,{force:!0}),o=ee.join(k,"bin","lua-language-server"+(l==="win32"?".exe":"")),!await be.exists(o)||l!=="win32"&&!await qe.chmod(o,493).then(()=>!0).catch(P=>!1))return}return{process:Ee(o,{cwd:e})}}},bS={id:"php intelephense",extensions:[".php"],root:Le(["composer.json","composer.lock",".php-version"]),async spawn(e,t,n){let o=se("intelephense"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("intelephense");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{telemetry:{enabled:!1}}}}},wS={id:"prisma",extensions:[".prisma"],root:Le(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(e){let t=se("prisma");if(t)return{process:Ee(t,["language-server"],{cwd:e})}}},vS={id:"dart",extensions:[".dart"],root:Le(["pubspec.yaml","analysis_options.yaml"]),async spawn(e){let t=se("dart");if(t)return{process:Ee(t,["language-server","--lsp"],{cwd:e})}}},xS={id:"ocaml-lsp",extensions:[".ml",".mli"],root:Le(["dune-project","dune-workspace",".merlin","opam"]),async spawn(e){let t=se("ocamllsp");if(t)return{process:Ee(t,{cwd:e})}}},SS={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:i(async(e,t)=>t.directory,"root"),async spawn(e,t,n){let o=se("bash-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("bash-language-server");if(!l)return;o=l}return s.push("start"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},IS={id:"terraform",extensions:[".tf",".tfvars"],root:Le([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(e,t,n){let o=se("terraform-ls");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,p=process.arch==="arm64"?"arm64":"amd64",f=l==="win32"?"windows":l,g=(a.builds??[]).find(T=>T.arch===p&&T.os===f);if(!g?.url)return;let y=await fetch(g.url);if(!y.ok)return;let b=ee.join(Se.Path.bin,"terraform-ls.zip");if(y.body&&await be.writeStream(b,y.body),!await on.extractZip(b,Se.Path.bin).then(()=>!0).catch(T=>!1)||(await qe.rm(b,{force:!0}),o=ee.join(Se.Path.bin,"terraform-ls"+(l==="win32"?".exe":"")),!await be.exists(o)))return;l!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,["serve"],{cwd:e}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},kS={id:"texlab",extensions:[".tex",".bib"],root:Le([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(e,t,n){let o=se("texlab");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!s.ok)return;let a=await s.json();if(!a.tag_name?.replace("v",""))return;let d=process.platform,f=process.arch==="arm64"?"aarch64":"x86_64",u=d==="darwin"?"macos":d==="win32"?"windows":"linux",g=d==="win32"?"zip":"tar.gz",y=`texlab-${f}-${u}.${g}`,S=(a.assets??[]).find(h=>h.name===y);if(!S?.browser_download_url)return;let T=await fetch(S.browser_download_url);if(!T.ok)return;let m=ee.join(Se.Path.bin,y);if(T.body&&await be.writeStream(m,T.body),g==="zip"&&!await on.extractZip(m,Se.Path.bin).then(()=>!0).catch(k=>!1)||(g==="tar.gz"&&await Ro(["tar","-xzf",m],{cwd:Se.Path.bin}),await qe.rm(m,{force:!0}),o=ee.join(Se.Path.bin,"texlab"+(d==="win32"?".exe":"")),!await be.exists(o)))return;d!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},DS={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:i(async(e,t)=>t.directory,"root"),async spawn(e,t,n){let o=se("docker-langserver"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("dockerfile-language-server-nodejs");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},ES={id:"gleam",extensions:[".gleam"],root:Le(["gleam.toml"]),async spawn(e){let t=se("gleam");if(t)return{process:Ee(t,["lsp"],{cwd:e})}}},TS={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:Le(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(e){let t=se("clojure-lsp");if(!t&&process.platform==="win32"&&(t=se("clojure-lsp.exe")),!!t)return{process:Ee(t,["listen"],{cwd:e})}}},PS={id:"nixd",extensions:[".nix"],root:i(async(e,t)=>{let n=await Le(["flake.nix"])(e,t);return n&&n!==t.directory?n:t.worktree&&t.worktree!==t.directory?t.worktree:t.directory},"root"),async spawn(e){let t=se("nixd");if(t)return{process:Ee(t,[],{cwd:e,env:{...process.env}})}}},RS={id:"tinymist",extensions:[".typ",".typc"],root:Le(["typst.toml"]),async spawn(e,t,n){let o=se("tinymist");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,p=process.arch==="arm64"?"aarch64":"x86_64",f,u;l==="darwin"?(f="apple-darwin",u="tar.gz"):l==="win32"?(f="pc-windows-msvc",u="zip"):(f="unknown-linux-gnu",u="tar.gz");let g=`tinymist-${p}-${f}.${u}`,b=(a.assets??[]).find(m=>m.name===g);if(!b?.browser_download_url)return;let S=await fetch(b.browser_download_url);if(!S.ok)return;let T=ee.join(Se.Path.bin,g);if(S.body&&await be.writeStream(T,S.body),u==="zip"){if(!await on.extractZip(T,Se.Path.bin).then(()=>!0).catch(h=>!1))return}else await Ro(["tar","-xzf",T,"--strip-components=1"],{cwd:Se.Path.bin});if(await qe.rm(T,{force:!0}),o=ee.join(Se.Path.bin,"tinymist"+(l==="win32"?".exe":"")),!await be.exists(o))return;l!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},CS={id:"haskell-language-server",extensions:[".hs",".lhs"],root:Le(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(e){let t=se("haskell-language-server-wrapper");if(t)return{process:Ee(t,["--lsp"],{cwd:e})}}},AS={id:"julials",extensions:[".jl"],root:Le(["Project.toml","Manifest.toml","*.jl"]),async spawn(e){let t=se("julia");if(t)return{process:Ee(t,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:e})}}};var Ds={};fe(Ds,{Definitions:()=>MS,LspEvent:()=>Ds,Updated:()=>Pm});var Pm=Et.define({type:"lsp.updated",schema:{}}),MS=Et.inventory(Pm);var Es={};fe(Es,{Diagnostic:()=>Es,pretty:()=>Cm,report:()=>_S});var Rm=20;function Cm(e){let n={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[e.severity||1],o=e.range.start.line+1,s=e.range.start.character+1;return`${n} [${o}:${s}] ${e.message}`}i(Cm,"pretty");function _S(e,t){let n=t.filter(l=>l.severity===1);if(n.length===0)return"";let o=n.slice(0,Rm),s=n.length-Rm,a=s>0?`
1029
+ ${ie}`}),$=Ct.dirname($)}return P});return wr.of({clear:g,systemPaths:y,system:b,find:S,resolve:T})}));function Qv(e){return $f(e)}i(Qv,"loaded");var Zv=ke.make({service:wr,layer:Xv,deps:[Oe.node,Ae.node,Se.node,Be.node,In]});var ft={};fe(ft,{Diagnostic:()=>Es,DocumentSymbol:()=>BS,Event:()=>Mm,LSP:()=>ft,Range:()=>da,Service:()=>_r,Status:()=>$S,Symbol:()=>FS,node:()=>zS});var Pr=kd(wm(),1);import ks from"path";import{pathToFileURL as so,fileURLToPath as Ox}from"url";var vm={".abap":"abap",".bat":"bat",".bib":"bibtex",".bibtex":"bibtex",".clj":"clojure",".cljs":"clojure",".cljc":"clojure",".edn":"clojure",".coffee":"coffeescript",".c":"c",".cpp":"cpp",".cxx":"cpp",".cc":"cpp",".c++":"cpp",".cs":"csharp",".csx":"csharp",".css":"css",".d":"d",".pas":"pascal",".pascal":"pascal",".diff":"diff",".patch":"diff",".dart":"dart",".dockerfile":"dockerfile",".ex":"elixir",".exs":"elixir",".erl":"erlang",".ets":"typescript",".hrl":"erlang",".fs":"fsharp",".fsi":"fsharp",".fsx":"fsharp",".fsscript":"fsharp",".gitcommit":"git-commit",".gitrebase":"git-rebase",".go":"go",".groovy":"groovy",".gleam":"gleam",".hbs":"handlebars",".handlebars":"handlebars",".hs":"haskell",".lhs":"haskell",".html":"html",".htm":"html",".ini":"ini",".java":"java",".jl":"julia",".js":"javascript",".kt":"kotlin",".kts":"kotlin",".jsx":"javascriptreact",".json":"json",".tex":"latex",".latex":"latex",".less":"less",".lua":"lua",".makefile":"makefile",makefile:"makefile",".md":"markdown",".markdown":"markdown",".m":"objective-c",".mm":"objective-cpp",".pl":"perl",".pm":"perl",".pm6":"perl6",".php":"php",".ps1":"powershell",".psm1":"powershell",".pug":"jade",".jade":"jade",".py":"python",".r":"r",".cshtml":"razor",".razor":"razor",".rb":"ruby",".rake":"ruby",".gemspec":"ruby",".ru":"ruby",".erb":"erb",".html.erb":"erb",".js.erb":"erb",".css.erb":"erb",".json.erb":"erb",".rs":"rust",".scss":"scss",".sass":"sass",".scala":"scala",".shader":"shaderlab",".sh":"shellscript",".bash":"shellscript",".zsh":"shellscript",".ksh":"shellscript",".sql":"sql",".svelte":"svelte",".swift":"swift",".ts":"typescript",".tsx":"typescriptreact",".mts":"typescript",".cts":"typescript",".mtsx":"typescriptreact",".ctsx":"typescriptreact",".xml":"xml",".xsl":"xsl",".yaml":"yaml",".yml":"yaml",".mjs":"javascript",".cjs":"javascript",".vue":"vue",".zig":"zig",".zon":"zig",".astro":"astro",".ml":"ocaml",".mli":"ocaml",".tf":"terraform",".tfvars":"terraform-vars",".hcl":"hcl",".nix":"nix",".typ":"typst",".typc":"typst"};var Lx=150,ql=5e3,Wl=1e4,xm=3e3,Nx=45e3,jx=1,Ux=2,Fx=2,zl=class extends c.TaggedErrorClass()("LSPInitializeError",{serverID:c.String,cause:c.optional(c.Defect())}){static{i(this,"InitializeError")}};function Vl(e){if(e.startsWith("file://"))return be.normalizePath(Ox(e))}i(Vl,"getFilePath");function Bx(e){if(!e)return;let t=e.textDocumentSync;return typeof t=="number"?t:t?.change}i(Bx,"getSyncKind");function $x(e){let t=e.split(/\r\n|\r|\n/);return{line:t.length-1,character:t.at(-1)?.length??0}}i($x,"endPosition");function Sm(e){let t=new Set;return e.filter(n=>{let o=JSON.stringify({code:n.code,severity:n.severity,message:n.message,source:n.source,range:n.range});return t.has(o)?!1:(t.add(o),!0)})}i(Sm,"dedupeDiagnostics");function qx(e,t){return t?t.split(".").reduce((o,s)=>{if(!(!o||typeof o!="object"||!(s in o)))return o[s]},e)??null:e??null}i(qx,"configurationValue");function Wx(e){return e==="typescript"}i(Wx,"shouldSeedDiagnosticsOnFirstPush");async function Im(e){let t=e.instance,n=(0,Pr.createMessageConnection)(new Pr.StreamMessageReader(e.server.process.stdout),new Pr.StreamMessageWriter(e.server.process.stdin));e.server.process.stderr?.resume();let o=new Map,s=new Map,a=new Map,l=new Map,d=new Set,p=new Set,f=i(D=>Sm([...o.get(D)??[],...s.get(D)??[]]),"mergedDiagnostics"),u=i((D,M)=>{o.set(D,M);for(let _ of p)_({path:D,serverID:e.serverID})},"updatePushDiagnostics"),g=i((D,M)=>{s.set(D,M)},"updatePullDiagnostics"),y=i(()=>{for(let D of[...d])D()},"emitRegistrationChange");n.onNotification("textDocument/publishDiagnostics",D=>{let M=Vl(D.uri);if(M){if(a.set(M,{at:Date.now(),version:typeof D.version=="number"?D.version:void 0}),Wx(e.serverID)&&!o.has(M)){o.set(M,D.diagnostics);return}u(M,D.diagnostics)}}),n.onRequest("window/workDoneProgress/create",D=>null),n.onRequest("workspace/configuration",async D=>(D.items??[]).map(_=>qx(e.server.initialization,_.section))),n.onRequest("client/registerCapability",async D=>{let M=D.registrations??[],_=!1;for(let N of M)N.method==="textDocument/diagnostic"&&(l.set(N.id,N),_=!0);_&&y()}),n.onRequest("client/unregisterCapability",async D=>{let M=D.unregisterations??[],_=!1;for(let N of M)N.method==="textDocument/diagnostic"&&(l.delete(N.id),_=!0);_&&y()}),n.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:so(e.root).href}]),n.onRequest("workspace/diagnostic/refresh",async()=>null),n.listen();let b=await hi(n.sendRequest("initialize",{rootUri:so(e.root).href,processId:e.server.process.pid,workspaceFolders:[{name:"workspace",uri:so(e.root).href}],initializationOptions:{...e.server.initialization},capabilities:{window:{workDoneProgress:!0},workspace:{configuration:!0,didChangeWatchedFiles:{dynamicRegistration:!0},diagnostics:{refreshSupport:!1}},textDocument:{synchronization:{didOpen:!0,didChange:!0},diagnostic:{dynamicRegistration:!0,relatedDocumentSupport:!0},publishDiagnostics:{versionSupport:!1}}}}),Nx).catch(D=>{throw new zl({serverID:e.serverID,cause:D})}),S=Bx(b.capabilities),T=!!b.capabilities?.diagnosticProvider;await n.sendNotification("initialized",{}),e.server.initialization&&await n.sendNotification("workspace/didChangeConfiguration",{settings:e.server.initialization});let m={},h=i((D,M)=>{let _=M.some(U=>U.handled),N=M.some(U=>U.matched);if(!_)return{handled:!1,matched:!1};let W=new Map;for(let U of M)for(let[we,pe]of U.byFile.entries()){let ce=W.get(we)??[];W.set(we,ce.concat(pe))}N&&!W.has(D)&&W.set(D,[]);for(let[U,we]of W.entries())g(U,Sm(we));return{handled:_,matched:N}},"mergeResults");async function k(D,M){let _=await hi(n.sendRequest("textDocument/diagnostic",{...M?{identifier:M}:{},textDocument:{uri:so(D).href}}),xm).catch(()=>null);if(!_)return{handled:!1,matched:!1,byFile:new Map};let N=new Map,W=i((pe,ce)=>{let re=N.get(pe)??[];N.set(pe,re.concat(ce))},"push"),U=!1,we=!1;Array.isArray(_.items)&&(W(D,_.items),U=!0,we=!0);for(let[pe,ce]of Object.entries(_.relatedDocuments??{})){let re=Vl(pe);!re||!Array.isArray(ce.items)||(W(re,ce.items),U=!0,we=we||re===D)}return{handled:U,matched:we,byFile:N}}i(k,"requestDiagnosticReport");async function w(D,M){let _=await hi(n.sendRequest("workspace/diagnostic",{...M?{identifier:M}:{},previousResultIds:[]}),xm).catch(()=>null);if(!_)return{handled:!1,matched:!1,byFile:new Map};let N=new Map,W=!1;for(let U of _.items??[]){let we=U.uri?Vl(U.uri):void 0;if(!we||!Array.isArray(U.items))continue;let pe=N.get(we)??[];N.set(we,pe.concat(U.items)),W=W||we===D}return{handled:!0,matched:W,byFile:N}}i(w,"requestWorkspaceDiagnosticReport");function I(){let D=[...l.values()].filter(M=>M.registerOptions?.workspaceDiagnostics!==!0);return{documentIdentifiers:[...new Set(D.flatMap(M=>M.registerOptions?.identifier??[]))],supported:T||D.length>0}}i(I,"documentPullState");function P(){let D=[...l.values()].filter(M=>M.registerOptions?.workspaceDiagnostics===!0);return{workspaceIdentifiers:[...new Set(D.flatMap(M=>M.registerOptions?.identifier??[]))],supported:D.length>0}}i(P,"workspacePullState");let x=i((D,M)=>M.some(_=>(_.byFile.get(D)?.length??0)>0),"hasCurrentFileDiagnostics");async function A(D,M,_){if(!M.length)return{handled:!1,matched:!1};let N=[];return new Promise(W=>{let U=M.length,we=!1,pe=i((ce,re=!1)=>{we||!re&&!_(N)||(we=!0,W(ce))},"finish");for(let ce of M)ce.then(re=>{N.push(re),U-=1;let R=h(D,N);pe(R),U===0&&pe(R,!0)})})}i(A,"requestDiagnostics");async function C(D){let M=I();return M.supported?A(D,[k(D),...M.documentIdentifiers.map(_=>k(D,_))],_=>x(D,_)):{handled:!1,matched:!1}}i(C,"requestDocumentDiagnostics");async function $(D){let M=I(),_=P();return!M.supported&&!_.supported?{handled:!1,matched:!1}:h(D,await Promise.all([...M.supported?[k(D)]:[],...M.documentIdentifiers.map(N=>k(D,N)),..._.supported?[w(D)]:[],..._.workspaceIdentifiers.map(N=>w(D,N))]))}i($,"requestFullDiagnostics");function j(D){return D<=0?Promise.resolve(!1):new Promise(M=>{let _=!1,N,W=i(we=>{_||(_=!0,N&&clearTimeout(N),d.delete(U),M(we))},"finish"),U=i(()=>W(!0),"listener");d.add(U),N=setTimeout(()=>W(!1),D)})}i(j,"waitForRegistrationChange");function z(D){return D.timeout<=0?Promise.resolve(!1):new Promise(M=>{let _=!1,N,W,U,we=i(re=>{_||(_=!0,N&&clearTimeout(N),W&&clearTimeout(W),U?.(),M(re))},"finish"),pe=i(()=>{let re=a.get(D.path);re&&(typeof re.version=="number"&&re.version!==D.version||re.at<D.after&&re.version!==D.version||(N&&clearTimeout(N),N=setTimeout(()=>we(!0),Math.max(0,Lx-(Date.now()-re.at)))))},"schedule");W=setTimeout(()=>we(!1),D.timeout);let ce=i(re=>{re.path!==D.path||re.serverID!==e.serverID||pe()},"listener");p.add(ce),U=i(()=>p.delete(ce),"unsub"),pe()})}i(z,"waitForFreshPush");async function ie(D){let M=D.after??Date.now(),_=z({path:D.path,version:D.version,after:M,timeout:ql});for(;Date.now()-M<ql;){if((await C(D.path)).matched)return;let W=ql-(Date.now()-M);if(W<=0||await Promise.race([_.then(we=>we?"push":"timeout"),j(W).then(we=>we?"registration":"timeout")])!=="registration")return}}i(ie,"waitForDocumentDiagnostics");async function L(D){let M=D.after??Date.now(),_=z({path:D.path,version:D.version,after:M,timeout:Wl});for(;Date.now()-M<Wl;){let N=await $(D.path);if(N.handled||N.matched)return;let W=Wl-(Date.now()-M);if(W<=0||await Promise.race([_.then(we=>we?"push":"timeout"),j(W).then(we=>we?"registration":"timeout")])!=="registration")return}}return i(L,"waitForFullDiagnostics"),{root:e.root,get serverID(){return e.serverID},get connection(){return n},notify:{async open(D){D.path=be.normalizePath(ks.isAbsolute(D.path)?D.path:ks.resolve(e.directory,D.path));let M=await be.readText(D.path),_=ks.extname(D.path),N=vm[_]??"plaintext",W=m[D.path];if(W!==void 0){await n.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:so(D.path).href,type:Ux}]});let U=W.version+1;return m[D.path]={version:U,text:M},await n.sendNotification("textDocument/didChange",{textDocument:{uri:so(D.path).href,version:U},contentChanges:S===Fx?[{range:{start:{line:0,character:0},end:$x(W.text)},text:M}]:[{text:M}]}),U}return await n.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:so(D.path).href,type:jx}]}),o.delete(D.path),s.delete(D.path),await n.sendNotification("textDocument/didOpen",{textDocument:{uri:so(D.path).href,languageId:N,version:0,text:M}}),m[D.path]={version:0,text:M},0}},get diagnostics(){let D=new Map;for(let M of new Set([...o.keys(),...s.keys()]))D.set(M,f(M));return D},async waitForDiagnostics(D){let M=be.normalizePath(ks.isAbsolute(D.path)?D.path:ks.resolve(e.directory,D.path));if(D.mode==="document"){await ie({path:M,version:D.version,after:D.after});return}await L({path:M,version:D.version,after:D.after})},async shutdown(){n.end(),n.dispose(),await it.stop(e.server.process)}}}i(Im,"create");import Yl from"path";import{pathToFileURL as Mr,fileURLToPath as US}from"url";var Hl={};fe(Hl,{Astro:()=>gS,BashLS:()=>ES,Biome:()=>eS,CSharp:()=>aS,Clangd:()=>mS,Clojure:()=>AS,Dart:()=>kS,Deno:()=>Jx,DockerfileLS:()=>RS,ESLint:()=>Qx,ElixirLS:()=>sS,FSharp:()=>uS,Gleam:()=>CS,Gopls:()=>tS,HLS:()=>OS,JDTLS:()=>bS,JuliaLS:()=>LS,KotlinLS:()=>wS,LuaLS:()=>xS,Nixd:()=>MS,Ocaml:()=>DS,Oxlint:()=>Zx,PHPIntelephense:()=>SS,Prisma:()=>IS,Pyright:()=>rS,Razor:()=>cS,Rubocop:()=>nS,RustAnalyzer:()=>fS,SourceKit:()=>pS,Svelte:()=>hS,TerraformLS:()=>TS,TexLab:()=>PS,Tinymist:()=>_S,Ty:()=>oS,Typescript:()=>Kx,Vue:()=>Xx,YamlLS:()=>vS,Zls:()=>iS});import ee from"path";import Cr from"os";import{text as Hx}from"node:stream/consumers";import qe from"fs/promises";var on={};fe(on,{Archive:()=>on,extractZip:()=>Vx});import Dm from"path";async function Vx(e,t){if(process.platform==="win32"){let n=Dm.resolve(e),o=Dm.resolve(t),s=`$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${n}' -DestinationPath '${o}' -Force`;await Qa(["powershell","-NoProfile","-NonInteractive","-Command",s]);return}await Qa(["unzip","-o","-q",e,"-d",t])}i(Vx,"extractZip");import{createRequire as zx}from"node:module";import Gx from"node:path";var Rr;(t=>{function e(n,o){try{return zx(Gx.join(o,"package.json")).resolve(n)}catch{}}t.resolve=e,i(e,"resolve")})(Rr||={});function Ee(e,t,n){let o=Array.isArray(t)?[...t]:[],s=Array.isArray(t)?n:t,a=it.spawn([e,...o],{...s,stdin:"pipe",stdout:"pipe",stderr:"pipe"});if(!a.stdin||!a.stdout||!a.stderr)throw new Error("Process output not available");return a}i(Ee,"spawn");var Ar=i(async e=>qe.stat(e).then(()=>!0).catch(()=>!1),"pathExists"),Ro=i((e,t={})=>it.run(e,{...t,nothrow:!0}),"run"),Yx=i((e,t={})=>it.text(e,{...t,nothrow:!0}),"output"),Le=i((e,t)=>async(n,o)=>{if(t){let l=be.up({targets:t,start:ee.dirname(n),stop:o.directory}),d=await l.next();if(await l.return(),d.value)return}let s=be.up({targets:e,start:ee.dirname(n),stop:o.directory}),a=await s.next();return await s.return(),a.value?ee.dirname(a.value):o.directory},"NearestRoot"),la=i((e,t)=>async(n,o)=>{if(t){let l=be.up({targets:t,start:ee.dirname(n),stop:o.directory}),d=await l.next();if(await l.return(),d.value)return}let s=be.up({targets:e,start:ee.dirname(n),stop:o.directory}),a=await s.next();if(await s.return(),!!a.value)return ee.dirname(a.value)},"StrictNearestRoot"),Jx={id:"deno",root:i(async(e,t)=>{let n=be.up({targets:["deno.json","deno.jsonc"],start:ee.dirname(e),stop:t.directory}),o=await n.next();if(await n.return(),!!o.value)return ee.dirname(o.value)},"root"),extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(e){let t=se("deno");if(t)return{process:Ee(t,["lsp"],{cwd:e})}}},Kx={id:"typescript",root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"],["deno.json","deno.jsonc"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts"],async spawn(e,t){let n=Rr.resolve("typescript/lib/tsserver.js",t.directory);if(!n)return;let o=await Ut.which("typescript-language-server");return o?{process:Ee(o,["--stdio"],{cwd:e,env:{...process.env}}),initialization:{tsserver:{path:n}}}:void 0}},Xx={id:"vue",extensions:[".vue"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("vue-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("@vue/language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{}}}},Qx={id:"eslint",root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue"],async spawn(e,t,n){if(!Rr.resolve("eslint",t.directory))return;let s=ee.join(Se.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await be.exists(s)){if(n.disableLspDownload)return;let l=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!l.ok)return;let d=ee.join(Se.Path.bin,"vscode-eslint.zip");if(l.body&&await be.writeStream(d,l.body),!await on.extractZip(d,Se.Path.bin).then(()=>!0).catch(b=>!1))return;await qe.rm(d,{force:!0});let f=ee.join(Se.Path.bin,"vscode-eslint-main"),u=ee.join(Se.Path.bin,"vscode-eslint");await qe.stat(u).catch(()=>{})&&await qe.rm(u,{force:!0,recursive:!0}),await qe.rename(f,u);let y=process.platform==="win32"?"npm.cmd":"npm";await it.run([y,"install"],{cwd:u}),await it.run([y,"run","compile"],{cwd:u})}return{process:Ee("node",[s,"--stdio"],{cwd:e,env:{...process.env}})}}},Zx={id:"oxlint",root:Le([".oxlintrc.json","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock","package.json"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".vue",".astro",".svelte"],async spawn(e,t){let n=process.platform==="win32"?".cmd":"",o=ee.join("node_modules",".bin","oxc_language_server"+n),s=ee.join("node_modules",".bin","oxlint"+n),a=i(async p=>{let f=ee.join(e,p);if(await be.exists(f))return f;let u=be.up({targets:[p],start:e,stop:t.worktree}),g=await u.next();if(await u.return(),g.value)return g.value},"resolveBin"),l=await a(s);if(!l){let p=se("oxlint");p&&(l=p)}if(l){let p=Ee(l,["--help"]);if(await p.exited,p.stdout&&(await Hx(p.stdout)).includes("--lsp"))return{process:Ee(l,["--lsp"],{cwd:e})}}let d=await a(o);if(!d){let p=se("oxc_language_server");p&&(d=p)}if(d)return{process:Ee(d,[],{cwd:e})}}},eS={id:"biome",root:Le(["biome.json","biome.jsonc","package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),extensions:[".ts",".tsx",".js",".jsx",".mjs",".cjs",".mts",".cts",".json",".jsonc",".vue",".astro",".svelte",".css",".graphql",".gql",".html"],async spawn(e){let t=ee.join(e,"node_modules",".bin","biome"),n;if(await be.exists(t)&&(n=t),!n){let a=se("biome");a&&(n=a)}let o=["lsp-proxy","--stdio"];if(!n){if(!Rr.resolve("biome",e)||(n=await Ut.which("biome"),!n))return;o=["lsp-proxy","--stdio"]}return{process:Ee(n,o,{cwd:e,env:{...process.env}})}}},tS={id:"gopls",root:i(async(e,t)=>{let n=await Le(["go.work"])(e,t);return n||Le(["go.mod","go.sum"])(e,t)},"root"),extensions:[".go"],async spawn(e,t,n){let o=se("gopls");if(!o){if(!se("go")||n.disableLspDownload||await it.spawn(["go","install","golang.org/x/tools/gopls@latest"],{env:{...process.env,GOBIN:Se.Path.bin},stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"gopls"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,{cwd:e})}}},nS={id:"ruby-lsp",root:Le(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(e,t,n){let o=se("rubocop");if(!o){let s=se("ruby"),a=se("gem");if(!s||!a||n.disableLspDownload||await it.spawn(["gem","install","rubocop","--bindir",Se.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"rubocop"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,["--lsp"],{cwd:e})}}},oS={id:"ty",extensions:[".py",".pyi"],root:Le(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,n){if(!n.experimentalLspTy)return;let o=se("ty"),s={},a=[process.env.VIRTUAL_ENV,ee.join(e,".venv"),ee.join(e,"venv")].filter(d=>d!==void 0);for(let d of a){let f=process.platform==="win32"?ee.join(d,"Scripts","python.exe"):ee.join(d,"bin","python");if(await be.exists(f)){s.pythonPath=f;break}}if(!o)for(let d of a){let f=process.platform==="win32"?ee.join(d,"Scripts","ty.exe"):ee.join(d,"bin","ty");if(await be.exists(f)){o=f;break}}return o?{process:Ee(o,["server"],{cwd:e}),initialization:s}:void 0}},rS={id:"pyright",extensions:[".py",".pyi"],root:Le(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(e,t,n){let o=se("pyright-langserver"),s=[];if(!o){if(n.disableLspDownload)return;let p=await Ut.which("pyright","pyright-langserver");if(!p)return;o=p}s.push("--stdio");let a={},l=[process.env.VIRTUAL_ENV,ee.join(e,".venv"),ee.join(e,"venv")].filter(p=>p!==void 0);for(let p of l){let u=process.platform==="win32"?ee.join(p,"Scripts","python.exe"):ee.join(p,"bin","python");if(await be.exists(u)){a.pythonPath=u;break}}return{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:a}}},sS={id:"elixir-ls",extensions:[".ex",".exs"],root:Le(["mix.exs","mix.lock"]),async spawn(e,t,n){let o=se("elixir-ls");if(!o){let s=ee.join(Se.Path.bin,"elixir-ls");if(o=ee.join(Se.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await be.exists(o)){if(!se("elixir")||n.disableLspDownload)return;let l=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!l.ok)return;let d=ee.join(Se.Path.bin,"elixir-ls.zip");if(l.body&&await be.writeStream(d,l.body),!await on.extractZip(d,Se.Path.bin).then(()=>!0).catch(g=>!1))return;await qe.rm(d,{force:!0,recursive:!0});let f=ee.join(Se.Path.bin,"elixir-ls-master"),u={MIX_ENV:"prod",...process.env};await it.run(["mix","deps.get"],{cwd:f,env:u}),await it.run(["mix","compile"],{cwd:f,env:u}),await it.run(["mix","elixir_ls.release2","-o","release"],{cwd:f,env:u})}}return{process:Ee(o,{cwd:e})}}},iS={id:"zls",extensions:[".zig",".zon"],root:Le(["build.zig"]),async spawn(e,t,n){let o=se("zls");if(!o){if(!se("zig")||n.disableLspDownload)return;let a=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!a.ok)return;let l=await a.json(),d=process.platform,p=process.arch,f="",u=p;p==="arm64"?u="aarch64":p==="x64"?u="x86_64":p==="ia32"&&(u="x86");let g=d;d==="darwin"?g="macos":d==="win32"&&(g="windows");let y=d==="win32"?"zip":"tar.xz";if(f=`zls-${u}-${g}.${y}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(f))return;let S=l.assets?.find(k=>k.name===f);if(!S?.browser_download_url)return;let T=S.browser_download_url,m=await fetch(T);if(!m.ok)return;let h=ee.join(Se.Path.bin,f);if(m.body&&await be.writeStream(h,m.body),y==="zip"){if(!await on.extractZip(h,Se.Path.bin).then(()=>!0).catch(w=>!1))return}else await Ro(["tar","-xf",h],{cwd:Se.Path.bin});if(await qe.rm(h,{force:!0}),o=ee.join(Se.Path.bin,"zls"+(d==="win32"?".exe":"")),!await be.exists(o))return;d!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},aS={id:"csharp",root:Le([".slnx",".sln",".csproj","global.json"]),extensions:[".cs",".csx"],async spawn(e,t,n){let o=await Em(n.disableLspDownload);if(o)return{process:Ee(o,["--stdio","--autoLoadProjects"],{cwd:e})}}},cS={id:"razor",root:Le([".slnx",".sln",".csproj","global.json"]),extensions:[".razor",".cshtml"],async spawn(e,t,n){let o=await Em(n.disableLspDownload);if(!o)return;let s=await dS();if(s)return{process:Ee(o,["--stdio","--autoLoadProjects",`--razorSourceGenerator=${s.compiler}`,`--razorDesignTimePath=${s.targets}`,"--extension",s.extension],{cwd:e})}}},Gl;async function Em(e){let t=se("roslyn-language-server");if(t)return t;let n=await Tm();return n||(Gl||=lS(e).finally(()=>{Gl=void 0}),Gl)}i(Em,"getRoslynLanguageServer");async function lS(e){if(!se("dotnet")||e||await it.spawn(["dotnet","tool","install","--global","roslyn-language-server","--prerelease"],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;let o=se("roslyn-language-server");if(o)return o;let s=await Tm();if(s)return s}i(lS,"installRoslynLanguageServer");async function Tm(){let e=ee.join(process.env.DOTNET_CLI_HOME??Cr.homedir(),".dotnet","tools","roslyn-language-server"+(process.platform==="win32"?".cmd":""));return await Ar(e)?e:void 0}i(Tm,"roslynLanguageServerGlobalPath");async function dS(){let e=[process.env.VSCODE_EXTENSIONS,ee.join(Cr.homedir(),".vscode","extensions"),ee.join(Cr.homedir(),".vscode-insiders","extensions"),ee.join(Cr.homedir(),".vscode-server","extensions"),ee.join(Cr.homedir(),".vscode-server-insiders","extensions")].filter(t=>t!==void 0);for(let t of[...new Set(e)]){let n=await qe.readdir(t,{withFileTypes:!0}).catch(()=>[]),o=await Promise.all(n.filter(s=>s.isDirectory()&&s.name.startsWith("ms-dotnettools.csharp-")).map(async s=>({path:ee.join(t,s.name,".razorExtension"),modified:(await qe.stat(ee.join(t,s.name)).catch(()=>{}))?.mtimeMs??0})));for(let s of o.sort((a,l)=>l.modified-a.modified).map(a=>a.path)){let a={compiler:ee.join(s,"Microsoft.CodeAnalysis.Razor.Compiler.dll"),targets:ee.join(s,"Targets","Microsoft.NET.Sdk.Razor.DesignTime.targets"),extension:ee.join(s,"Microsoft.VisualStudioCode.RazorExtension.dll")};if(await Ar(a.compiler)&&await Ar(a.targets)&&await Ar(a.extension))return a}}}i(dS,"findVscodeRazorExtension");var uS={id:"fsharp",root:Le([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(e,t,n){let o=se("fsautocomplete");if(!o){if(!se("dotnet")||n.disableLspDownload||await it.spawn(["dotnet","tool","install","fsautocomplete","--tool-path",Se.Path.bin],{stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited!==0)return;o=ee.join(Se.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":""))}return{process:Ee(o,{cwd:e})}}},pS={id:"sourcekit-lsp",extensions:[".swift",".objc","objcpp"],root:Le(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(e){let t=se("sourcekit-lsp");if(t)return{process:Ee(t,{cwd:e})};if(!se("xcrun"))return;let n=await Yx(["xcrun","--find","sourcekit-lsp"]);if(n.code!==0)return;let o=n.text.trim();return{process:Ee(o,{cwd:e})}}},fS={id:"rust",root:i(async(e,t)=>{let n=await Le(["Cargo.toml","Cargo.lock"])(e,t);if(n===void 0)return;let o=n;for(;o!==ee.dirname(o);){let s=ee.join(o,"Cargo.toml");try{if((await be.readText(s)).includes("[workspace]"))return o}catch{}let a=ee.dirname(o);if(a===o||(o=a,!o.startsWith(t.worktree)))break}return n},"root"),extensions:[".rs"],async spawn(e){let t=se("rust-analyzer");if(t)return{process:Ee(t,{cwd:e})}}},mS={id:"clangd",root:Le(["compile_commands.json","compile_flags.txt",".clangd"]),extensions:[".c",".cpp",".cc",".cxx",".c++",".h",".hpp",".hh",".hxx",".h++"],async spawn(e,t,n){let o=["--background-index","--clang-tidy"],s=se("clangd");if(s)return{process:Ee(s,o,{cwd:e})};let a=process.platform==="win32"?".exe":"",l=ee.join(Se.Path.bin,"clangd"+a);if(await be.exists(l))return{process:Ee(l,o,{cwd:e})};let d=await qe.readdir(Se.Path.bin,{withFileTypes:!0}).catch(()=>[]);for(let C of d){if(!C.isDirectory()||!C.name.startsWith("clangd_"))continue;let $=ee.join(Se.Path.bin,C.name,"bin","clangd"+a);if(await be.exists($))return{process:Ee($,o,{cwd:e})}}if(n.disableLspDownload)return;let p=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!p.ok)return;let f=await p.json(),u=f.tag_name;if(!u)return;let g=process.platform,b={darwin:"mac",linux:"linux",win32:"windows"}[g];if(!b)return;let S=f.assets??[],T=i(C=>!C.name||!C.browser_download_url||!C.name.includes(b)?!1:C.name.includes(u),"valid"),m=S.find(C=>T(C)&&C.name?.endsWith(".zip"))??S.find(C=>T(C)&&C.name?.endsWith(".tar.xz"))??S.find(C=>T(C));if(!m?.name||!m.browser_download_url)return;let h=m.name,k=await fetch(m.browser_download_url);if(!k.ok)return;let w=ee.join(Se.Path.bin,h),I=await k.arrayBuffer();if(I.byteLength===0)return;await be.write(w,Buffer.from(I));let P=h.endsWith(".zip"),x=h.endsWith(".tar.xz");if(!P&&!x||P&&!await on.extractZip(w,Se.Path.bin).then(()=>!0).catch($=>!1))return;x&&await Ro(["tar","-xf",w],{cwd:Se.Path.bin}),await qe.rm(w,{force:!0});let A=ee.join(Se.Path.bin,"clangd_"+u,"bin","clangd"+a);if(await be.exists(A))return g!=="win32"&&await qe.chmod(A,493).catch(()=>{}),await qe.unlink(ee.join(Se.Path.bin,"clangd")).catch(()=>{}),await qe.symlink(A,ee.join(Se.Path.bin,"clangd")).catch(()=>{}),{process:Ee(A,o,{cwd:e})}}},hS={id:"svelte",extensions:[".svelte"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("svelteserver"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("svelte-language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{}}}},gS={id:"astro",extensions:[".astro"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=Rr.resolve("typescript/lib/tsserver.js",t.directory);if(!o)return;let s=ee.dirname(o),a=se("astro-ls"),l=[];if(!a){if(n.disableLspDownload)return;let p=await Ut.which("@astrojs/language-server");if(!p)return;a=p}return l.push("--stdio"),{process:Ee(a,l,{cwd:e,env:{...process.env}}),initialization:{typescript:{tsdk:s}}}}};function yS(e,t){let n=t.replace(/\\/g,"/").replace(/\/$/,"");if(!n)return!1;let o=e.match(/<modules>([\s\S]*?)<\/modules>/g)??[];for(let s of o){let a=s.replace(/<!--[\s\S]*?-->/g,"");for(let l of a.matchAll(/<module>\s*([^<]+?)\s*<\/module>/g))if(l[1].replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,"")===n)return!0}return!1}i(yS,"isModuleOf");var bS={id:"jdtls",root:i(async(e,t)=>{let n=["settings.gradle","settings.gradle.kts"],o=["gradlew","gradlew.bat"],[s,a]=await Promise.all([la(o,n)(e,t),la(n)(e,t)]);if(s)return s;if(a)return a;let l=await la(["build.gradle","build.gradle.kts"])(e,t);if(l)return l;let d=await be.findUp("pom.xml",ee.dirname(e),t.directory);if(d.length>0){let f=ee.dirname(d[0]);for(let u=1;u<d.length;u++){let g=ee.dirname(d[u]),y=ee.relative(g,f),b=await qe.readFile(d[u],"utf-8").catch(()=>null);if(b&&yS(b,y))f=g;else break}return f}let p=await la([".project",".classpath"])(e,t);if(p)return p},"root"),extensions:[".java"],async spawn(e,t,n){let o=se("java");if(!o)return;let s=await Ro(["java","-version"]).then(y=>{let b=/"(\d+)\.\d+\.\d+"/.exec(y.stderr.toString());return b?parseInt(b[1]):void 0});if(s==null||s<21)return;let a=ee.join(Se.Path.bin,"jdtls"),l=ee.join(a,"plugins");if(!await Ar(l)){if(n.disableLspDownload)return;await qe.mkdir(a,{recursive:!0});let y="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",b="release.tar.gz",S=await fetch(y);if(!S.ok||!S.body||(await be.writeStream(ee.join(a,b),S.body),(await Ro(["tar","-xzf",b],{cwd:a})).code!==0))return;await qe.rm(ee.join(a,b),{force:!0})}let p=(await qe.readdir(l).catch(()=>[])).find(y=>/^org\.eclipse\.equinox\.launcher_.*\.jar$/.test(y))?.trim()??"",f=ee.join(l,p);if(!await Ar(f))return;let u=ee.join(a,(()=>{switch(process.platform){case"darwin":return"config_mac";case"linux":return"config_linux";case"win32":return"config_win";default:return"config_linux"}})()),g=await qe.mkdtemp(ee.join(Cr.tmpdir(),"opencode-jdtls-data"));return{process:Ee(o,["-jar",f,"-configuration",u,"-data",g,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens java.base/java.util=ALL-UNNAMED","--add-opens java.base/java.lang=ALL-UNNAMED"],{cwd:e})}}},wS={id:"kotlin-ls",extensions:[".kt",".kts"],root:i(async(e,t)=>{let n=await Le(["settings.gradle.kts","settings.gradle"])(e,t);if(n)return n;let o=await Le(["gradlew","gradlew.bat"])(e,t);if(o)return o;let s=await Le(["build.gradle.kts","build.gradle"])(e,t);return s||Le(["pom.xml"])(e,t)},"root"),async spawn(e,t,n){let o=ee.join(Se.Path.bin,"kotlin-ls"),s=process.platform==="win32"?ee.join(o,"kotlin-lsp.cmd"):ee.join(o,"kotlin-lsp.sh");if(!await be.exists(s)){if(n.disableLspDownload)return;let l=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!l.ok)return;let p=(await l.json()).name?.replace(/^v/,"");if(!p)return;let f=process.platform,u=process.arch,g=u;u==="arm64"?g="aarch64":u==="x64"&&(g="x64");let y=f;f==="darwin"?y="mac":f==="linux"?y="linux":f==="win32"&&(y="win");let b=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],S=`${y}-${g}`;if(!b.includes(S))return;let T=`kotlin-lsp-${p}-${y}-${g}.zip`,m=`https://download-cdn.jetbrains.com/kotlin-lsp/${p}/${T}`;await qe.mkdir(o,{recursive:!0});let h=ee.join(o,"kotlin-ls.zip"),k=await fetch(m);if(!k.ok||!k.body||(await be.writeStream(h,k.body),!await on.extractZip(h,o).then(()=>!0).catch(I=>!1)))return;await qe.rm(h,{force:!0}),process.platform!=="win32"&&await qe.chmod(s,493).catch(()=>{})}if(await be.exists(s))return{process:Ee(s,["--stdio"],{cwd:e})}}},vS={id:"yaml-ls",extensions:[".yaml",".yml"],root:Le(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(e,t,n){let o=se("yaml-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("yaml-language-server");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},xS={id:"lua-ls",root:Le([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(e,t,n){let o=se("lua-language-server");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,d=process.arch,p="",f=d;d==="arm64"?f="arm64":d==="x64"?f="x64":d==="ia32"&&(f="ia32");let u=l;l==="darwin"?u="darwin":l==="linux"?u="linux":l==="win32"&&(u="win32");let g=l==="win32"?"zip":"tar.gz";p=`lua-language-server-${a.tag_name}-${u}-${f}.${g}`;let y=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],b=`${u}-${f}.${g}`;if(!y.includes(b))return;let S=a.assets.find(I=>I.name===p);if(!S)return;let T=S.browser_download_url,m=await fetch(T);if(!m.ok)return;let h=ee.join(Se.Path.bin,p);m.body&&await be.writeStream(h,m.body);let k=ee.join(Se.Path.bin,`lua-language-server-${f}-${u}`);if(await qe.stat(k).catch(()=>{})&&await qe.rm(k,{force:!0,recursive:!0}),await qe.mkdir(k,{recursive:!0}),g==="zip"){if(!await on.extractZip(h,k).then(()=>!0).catch(P=>!1))return}else if(!await Ro(["tar","-xzf",h,"-C",k]).then(P=>P.code===0).catch(P=>!1))return;if(await qe.rm(h,{force:!0}),o=ee.join(k,"bin","lua-language-server"+(l==="win32"?".exe":"")),!await be.exists(o)||l!=="win32"&&!await qe.chmod(o,493).then(()=>!0).catch(P=>!1))return}return{process:Ee(o,{cwd:e})}}},SS={id:"php intelephense",extensions:[".php"],root:Le(["composer.json","composer.lock",".php-version"]),async spawn(e,t,n){let o=se("intelephense"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("intelephense");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}}),initialization:{telemetry:{enabled:!1}}}}},IS={id:"prisma",extensions:[".prisma"],root:Le(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(e){let t=se("prisma");if(t)return{process:Ee(t,["language-server"],{cwd:e})}}},kS={id:"dart",extensions:[".dart"],root:Le(["pubspec.yaml","analysis_options.yaml"]),async spawn(e){let t=se("dart");if(t)return{process:Ee(t,["language-server","--lsp"],{cwd:e})}}},DS={id:"ocaml-lsp",extensions:[".ml",".mli"],root:Le(["dune-project","dune-workspace",".merlin","opam"]),async spawn(e){let t=se("ocamllsp");if(t)return{process:Ee(t,{cwd:e})}}},ES={id:"bash",extensions:[".sh",".bash",".zsh",".ksh"],root:i(async(e,t)=>t.directory,"root"),async spawn(e,t,n){let o=se("bash-language-server"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("bash-language-server");if(!l)return;o=l}return s.push("start"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},TS={id:"terraform",extensions:[".tf",".tfvars"],root:Le([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(e,t,n){let o=se("terraform-ls");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.releases.hashicorp.com/v1/releases/terraform-ls/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,p=process.arch==="arm64"?"arm64":"amd64",f=l==="win32"?"windows":l,g=(a.builds??[]).find(T=>T.arch===p&&T.os===f);if(!g?.url)return;let y=await fetch(g.url);if(!y.ok)return;let b=ee.join(Se.Path.bin,"terraform-ls.zip");if(y.body&&await be.writeStream(b,y.body),!await on.extractZip(b,Se.Path.bin).then(()=>!0).catch(T=>!1)||(await qe.rm(b,{force:!0}),o=ee.join(Se.Path.bin,"terraform-ls"+(l==="win32"?".exe":"")),!await be.exists(o)))return;l!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,["serve"],{cwd:e}),initialization:{experimentalFeatures:{prefillRequiredFields:!0,validateOnSave:!0}}}}},PS={id:"texlab",extensions:[".tex",".bib"],root:Le([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(e,t,n){let o=se("texlab");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!s.ok)return;let a=await s.json();if(!a.tag_name?.replace("v",""))return;let d=process.platform,f=process.arch==="arm64"?"aarch64":"x86_64",u=d==="darwin"?"macos":d==="win32"?"windows":"linux",g=d==="win32"?"zip":"tar.gz",y=`texlab-${f}-${u}.${g}`,S=(a.assets??[]).find(h=>h.name===y);if(!S?.browser_download_url)return;let T=await fetch(S.browser_download_url);if(!T.ok)return;let m=ee.join(Se.Path.bin,y);if(T.body&&await be.writeStream(m,T.body),g==="zip"&&!await on.extractZip(m,Se.Path.bin).then(()=>!0).catch(k=>!1)||(g==="tar.gz"&&await Ro(["tar","-xzf",m],{cwd:Se.Path.bin}),await qe.rm(m,{force:!0}),o=ee.join(Se.Path.bin,"texlab"+(d==="win32"?".exe":"")),!await be.exists(o)))return;d!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},RS={id:"dockerfile",extensions:[".dockerfile","Dockerfile"],root:i(async(e,t)=>t.directory,"root"),async spawn(e,t,n){let o=se("docker-langserver"),s=[];if(!o){if(n.disableLspDownload)return;let l=await Ut.which("dockerfile-language-server-nodejs");if(!l)return;o=l}return s.push("--stdio"),{process:Ee(o,s,{cwd:e,env:{...process.env}})}}},CS={id:"gleam",extensions:[".gleam"],root:Le(["gleam.toml"]),async spawn(e){let t=se("gleam");if(t)return{process:Ee(t,["lsp"],{cwd:e})}}},AS={id:"clojure-lsp",extensions:[".clj",".cljs",".cljc",".edn"],root:Le(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(e){let t=se("clojure-lsp");if(!t&&process.platform==="win32"&&(t=se("clojure-lsp.exe")),!!t)return{process:Ee(t,["listen"],{cwd:e})}}},MS={id:"nixd",extensions:[".nix"],root:i(async(e,t)=>{let n=await Le(["flake.nix"])(e,t);return n&&n!==t.directory?n:t.worktree&&t.worktree!==t.directory?t.worktree:t.directory},"root"),async spawn(e){let t=se("nixd");if(t)return{process:Ee(t,[],{cwd:e,env:{...process.env}})}}},_S={id:"tinymist",extensions:[".typ",".typc"],root:Le(["typst.toml"]),async spawn(e,t,n){let o=se("tinymist");if(!o){if(n.disableLspDownload)return;let s=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!s.ok)return;let a=await s.json(),l=process.platform,p=process.arch==="arm64"?"aarch64":"x86_64",f,u;l==="darwin"?(f="apple-darwin",u="tar.gz"):l==="win32"?(f="pc-windows-msvc",u="zip"):(f="unknown-linux-gnu",u="tar.gz");let g=`tinymist-${p}-${f}.${u}`,b=(a.assets??[]).find(m=>m.name===g);if(!b?.browser_download_url)return;let S=await fetch(b.browser_download_url);if(!S.ok)return;let T=ee.join(Se.Path.bin,g);if(S.body&&await be.writeStream(T,S.body),u==="zip"){if(!await on.extractZip(T,Se.Path.bin).then(()=>!0).catch(h=>!1))return}else await Ro(["tar","-xzf",T,"--strip-components=1"],{cwd:Se.Path.bin});if(await qe.rm(T,{force:!0}),o=ee.join(Se.Path.bin,"tinymist"+(l==="win32"?".exe":"")),!await be.exists(o))return;l!=="win32"&&await qe.chmod(o,493).catch(()=>{})}return{process:Ee(o,{cwd:e})}}},OS={id:"haskell-language-server",extensions:[".hs",".lhs"],root:Le(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(e){let t=se("haskell-language-server-wrapper");if(t)return{process:Ee(t,["--lsp"],{cwd:e})}}},LS={id:"julials",extensions:[".jl"],root:Le(["Project.toml","Manifest.toml","*.jl"]),async spawn(e){let t=se("julia");if(t)return{process:Ee(t,["--startup-file=no","--history-file=no","-e","using LanguageServer; runserver()"],{cwd:e})}}};var Ds={};fe(Ds,{Definitions:()=>NS,LspEvent:()=>Ds,Updated:()=>Pm});var Pm=Et.define({type:"lsp.updated",schema:{}}),NS=Et.inventory(Pm);var Es={};fe(Es,{Diagnostic:()=>Es,pretty:()=>Cm,report:()=>jS});var Rm=20;function Cm(e){let n={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[e.severity||1],o=e.range.start.line+1,s=e.range.start.character+1;return`${n} [${o}:${s}] ${e.message}`}i(Cm,"pretty");function jS(e,t){let n=t.filter(l=>l.severity===1);if(n.length===0)return"";let o=n.slice(0,Rm),s=n.length-Rm,a=s>0?`
1030
1030
  ... and ${s} more`:"";return`<diagnostics file="${e}">
1031
1031
  ${o.map(Cm).join(`
1032
1032
  `)}${a}
1033
- </diagnostics>`}i(_S,"report");var Mm=Ds,Am=c.Struct({line:mn,character:mn}),da=c.Struct({start:Am,end:Am}).annotate({identifier:"Range"}),LS=c.Struct({name:c.String,kind:mn,location:c.Struct({uri:c.String,range:da})}).annotate({identifier:"Symbol"}),NS=c.Struct({name:c.String,detail:c.optional(c.String),kind:mn,range:da,selectionRange:da}).annotate({identifier:"DocumentSymbol"}),jS=c.Struct({id:c.String,name:c.String,root:c.String,status:c.Literals(["connected","error"])}).annotate({identifier:"LSPStatus"});var US=[5,12,6,11,13,14,23,10],FS=i((e,t)=>{t.experimentalLspTy?e.pyright&&delete e.pyright:e.ty&&delete e.ty},"filterExperimentalServers"),_r=class extends Re.Service()("@opencode/LSP"){static{i(this,"Service")}},BS=Te.effect(_r,r.gen(function*(){let e=yield*Oe.Service,t=yield*Be.Service,n=yield*De.Service,o=yield*G.make(r.fn("LSP.state")(function*(x){let A=yield*e.get(),C={};if(!A.lsp)yield*r.logInfo("all LSPs are disabled");else{for(let j of Object.values(Hl))C[j.id]=j;if(FS(C,t),A.lsp!==!0)for(let[j,z]of Object.entries(A.lsp)){let ie=C[j];if(z.disabled){yield*r.logInfo(`LSP server ${j} is disabled`),delete C[j];continue}C[j]={...ie,id:j,root:ie?.root??(async(L,V)=>V.directory),extensions:z.extensions??ie?.extensions??[],spawn:i(async L=>({process:Ee(z.command[0],z.command.slice(1),{cwd:L,env:{...process.env,...z.env}}),initialization:z.initialization}),"spawn")}}yield*r.logInfo("enabled LSP servers",{serverIds:Object.values(C).map(j=>j.id).join(", ")})}let $={clients:[],servers:C,broken:new Set,spawning:new Map};return yield*r.addFinalizer(()=>r.promise(async()=>{await Promise.all($.clients.map(j=>j.shutdown()))})),$})),s=r.fnUntraced(function*(x){let A=yield*G.context;if(!pi(x,A))return[];let C=yield*G.get(o),$=yield*r.promise(async()=>{let j=Yl.parse(x).ext||x,z=[],ie=0;async function L(V,D,M){let _=await V.spawn(D,A,t).then(U=>(U||C.broken.add(M),U)).catch(()=>{C.broken.add(M)});if(!_)return;let N=await Im({serverID:V.id,server:_,root:D,directory:A.directory,instance:A}).catch(async()=>{C.broken.add(M),await it.stop(_.process)});if(!N)return;let W=C.clients.find(U=>U.root===D&&U.serverID===V.id);return W?(await it.stop(_.process),W):(C.clients.push(N),N)}i(L,"schedule");for(let V of Object.values(C.servers)){if(V.extensions.length&&!V.extensions.includes(j))continue;let D=await V.root(x,A);if(!D||C.broken.has(D+V.id))continue;let M=C.clients.find(U=>U.root===D&&U.serverID===V.id);if(M){z.push(M);continue}let _=C.spawning.get(D+V.id);if(_){let U=await _;if(!U)continue;z.push(U);continue}let N=L(V,D,D+V.id);C.spawning.set(D+V.id,N),N.finally(()=>{C.spawning.get(D+V.id)===N&&C.spawning.delete(D+V.id)});let W=await N;W&&(z.push(W),ie++)}return{result:z,updated:ie}});return yield*r.forEach(Array.from({length:$.updated}),()=>n.publish(Mm.Updated,{}),{discard:!0}),$.result}),a=r.fnUntraced(function*(x,A){let C=yield*s(x);return yield*r.promise(()=>Promise.all(C.map($=>A($))))}),l=r.fnUntraced(function*(x){let A=yield*G.get(o);return yield*r.promise(()=>Promise.all(A.clients.map(C=>x(C))))}),d=r.fn("LSP.init")(function*(){yield*G.get(o)}),p=r.fn("LSP.status")(function*(){let x=yield*G.context,A=yield*G.get(o),C=[];for(let $ of A.clients)C.push({id:$.serverID,name:A.servers[$.serverID].id,root:Yl.relative(x.directory,$.root),status:"connected"});return C}),f=r.fn("LSP.hasClients")(function*(x){let A=yield*G.context,C=yield*G.get(o);return yield*r.promise(async()=>{let $=Yl.parse(x).ext||x;for(let j of Object.values(C.servers)){if(j.extensions.length&&!j.extensions.includes($))continue;let z=await j.root(x,A);if(z&&!C.broken.has(z+j.id))return!0}return!1})}),u=r.fn("LSP.touchFile")(function*(x,A){yield*r.logInfo("touching file",{file:x});let C=yield*s(x);yield*r.promise(()=>Promise.all(C.map(async $=>{let j=Date.now(),z=await $.notify.open({path:x});if(A)return $.waitForDiagnostics({path:x,version:z,mode:A,after:j})})).catch(()=>{}))}),g=r.fn("LSP.diagnostics")(function*(){let x={},A=yield*l(async C=>C.diagnostics);for(let C of A)for(let[$,j]of C.entries()){let z=x[$]||[];z.push(...j),x[$]=z}return x}),y=r.fn("LSP.hover")(function*(x){return yield*a(x.file,A=>A.connection.sendRequest("textDocument/hover",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))}),b=r.fn("LSP.definition")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/definition",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))).flat().filter(Boolean)}),S=r.fn("LSP.references")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/references",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character},context:{includeDeclaration:!0}}).catch(()=>[]))).flat().filter(Boolean)}),T=r.fn("LSP.implementation")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/implementation",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))).flat().filter(Boolean)}),m=r.fn("LSP.documentSymbol")(function*(x){let A=OS(x);return(yield*a(A,$=>$.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:x}}).catch(()=>[]))).flat().filter(Boolean)}),h=r.fn("LSP.workspaceSymbol")(function*(x){return(yield*l(C=>C.connection.sendRequest("workspace/symbol",{query:x}).then($=>$.filter(j=>US.includes(j.kind)).slice(0,10)).catch(()=>[]))).flat()}),k=r.fn("LSP.prepareCallHierarchy")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>[]))).flat().filter(Boolean)}),w=r.fnUntraced(function*(x,A){return(yield*a(x.file,async $=>{let j=await $.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>[]);return j?.length?$.connection.sendRequest(A,{item:j[0]}).catch(()=>[]):[]})).flat().filter(Boolean)}),I=r.fn("LSP.incomingCalls")(function*(x){return yield*w(x,"callHierarchy/incomingCalls")}),P=r.fn("LSP.outgoingCalls")(function*(x){return yield*w(x,"callHierarchy/outgoingCalls")});return _r.of({init:d,status:p,hasClients:f,touchFile:u,diagnostics:g,hover:y,definition:b,references:S,implementation:T,documentSymbol:m,workspaceSymbol:h,prepareCallHierarchy:k,incomingCalls:I,outgoingCalls:P})})),$S=ke.make({service:_r,layer:BS,deps:[Oe.node,Be.node,Ae.node,De.node]});var Jt={};fe(Jt,{Format:()=>Jt,Service:()=>Co,Status:()=>mI,node:()=>yI,use:()=>hI});import fI from"path";var ua={};fe(ua,{biome:()=>GS,clang:()=>YS,cljfmt:()=>uI,dart:()=>tI,dfmt:()=>pI,gleam:()=>sI,gofmt:()=>qS,htmlbeautifier:()=>eI,ktlint:()=>JS,latexindent:()=>rI,mix:()=>WS,nixfmt:()=>aI,ocamlformat:()=>nI,ormolu:()=>dI,oxfmt:()=>zS,pint:()=>lI,prettier:()=>VS,rlang:()=>KS,rubocop:()=>QS,ruff:()=>_m,rustfmt:()=>cI,shfmt:()=>iI,standardrb:()=>ZS,terraform:()=>oI,uvformat:()=>XS,zig:()=>HS});var qS={name:"gofmt",extensions:[".go"],async enabled(){let e=se("gofmt");return e?[e,"-w","$FILE"]:!1}},WS={name:"mix",extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){let e=se("mix");return e?[e,"format","$FILE"]:!1}},VS={name:"prettier",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=await be.findUp("package.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.dependencies?.prettier||o.devDependencies?.prettier){let s=await Ut.which("prettier");if(s)return[s,"--write","$FILE"]}}return!1}},zS={name:"oxfmt",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],async enabled(e){if(!e.experimentalOxfmt)return!1;let t=await be.findUp("package.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.dependencies?.oxfmt||o.devDependencies?.oxfmt){let s=await Ut.which("oxfmt");if(s)return[s,"$FILE"]}}return!1}},GS={name:"biome",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=["biome.json","biome.jsonc"];for(let n of t)if((await be.findUp(n,e.directory,e.worktree)).length>0){let s=await Ut.which("@biomejs/biome");if(s)return[s,"format","--write","$FILE"]}return!1}},HS={name:"zig",extensions:[".zig",".zon"],async enabled(){let e=se("zig");return e?[e,"fmt","$FILE"]:!1}},YS={name:"clang-format",extensions:[".c",".cc",".cpp",".cxx",".c++",".h",".hh",".hpp",".hxx",".h++",".ino",".C",".H"],async enabled(e){if((await be.findUp(".clang-format",e.directory,e.worktree)).length>0){let n=se("clang-format");if(n)return[n,"-i","$FILE"]}return!1}},JS={name:"ktlint",extensions:[".kt",".kts"],async enabled(){let e=se("ktlint");return e?[e,"-F","$FILE"]:!1}},_m={name:"ruff",extensions:[".py",".pyi"],async enabled(e){if(!se("ruff"))return!1;let t=["pyproject.toml","ruff.toml",".ruff.toml"];for(let o of t){let s=await be.findUp(o,e.directory,e.worktree);if(s.length>0)if(o==="pyproject.toml"){if((await be.readText(s[0])).includes("[tool.ruff]"))return["ruff","format","$FILE"]}else return["ruff","format","$FILE"]}let n=["requirements.txt","pyproject.toml","Pipfile"];for(let o of n){let s=await be.findUp(o,e.directory,e.worktree);if(s.length>0&&(await be.readText(s[0])).includes("ruff"))return["ruff","format","$FILE"]}return!1}},KS={name:"air",extensions:[".R"],async enabled(){let e=se("air");if(e==null)return!1;let t=await it.text([e,"--help"],{nothrow:!0}),n=t.text.split(`
1034
- `)[0],o=n.includes("R language"),s=n.includes("formatter");return t.code===0&&o&&s?[e,"format","$FILE"]:!1}},XS={name:"uv",extensions:[".py",".pyi"],async enabled(e){if(await _m.enabled(e))return!1;let t=se("uv");return t==null?!1:(await it.run([t,"format","--help"],{nothrow:!0})).code===0?[t,"format","--","$FILE"]:!1}},QS={name:"rubocop",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=se("rubocop");return e?[e,"--autocorrect","$FILE"]:!1}},ZS={name:"standardrb",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=se("standardrb");return e?[e,"--fix","$FILE"]:!1}},eI={name:"htmlbeautifier",extensions:[".erb",".html.erb"],async enabled(){let e=se("htmlbeautifier");return e?[e,"$FILE"]:!1}},tI={name:"dart",extensions:[".dart"],async enabled(){let e=se("dart");return e?[e,"format","$FILE"]:!1}},nI={name:"ocamlformat",extensions:[".ml",".mli"],async enabled(e){return se("ocamlformat")&&(await be.findUp(".ocamlformat",e.directory,e.worktree)).length>0?["ocamlformat","-i","$FILE"]:!1}},oI={name:"terraform",extensions:[".tf",".tfvars"],async enabled(){let e=se("terraform");return e?[e,"fmt","$FILE"]:!1}},rI={name:"latexindent",extensions:[".tex"],async enabled(){let e=se("latexindent");return e?[e,"-w","-s","$FILE"]:!1}},sI={name:"gleam",extensions:[".gleam"],async enabled(){let e=se("gleam");return e?[e,"format","$FILE"]:!1}},iI={name:"shfmt",extensions:[".sh",".bash"],async enabled(){let e=se("shfmt");return e?[e,"-w","$FILE"]:!1}},aI={name:"nixfmt",extensions:[".nix"],async enabled(){let e=se("nixfmt");return e?[e,"$FILE"]:!1}},cI={name:"rustfmt",extensions:[".rs"],async enabled(){let e=se("rustfmt");return e?[e,"$FILE"]:!1}},lI={name:"pint",extensions:[".php"],async enabled(e){let t=await be.findUp("composer.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.require?.["laravel/pint"]||o["require-dev"]?.["laravel/pint"])return["./vendor/bin/pint","$FILE"]}return!1}},dI={name:"ormolu",extensions:[".hs"],async enabled(){let e=se("ormolu");return e?[e,"-i","$FILE"]:!1}},uI={name:"cljfmt",extensions:[".clj",".cljs",".cljc",".edn"],async enabled(){let e=se("cljfmt");return e?[e,"fix","--quiet","$FILE"]:!1}},pI={name:"dfmt",extensions:[".d"],async enabled(){let e=se("dfmt");return e?[e,"-i","$FILE"]:!1}};var mI=c.Struct({name:c.String,extensions:c.Array(c.String),enabled:c.Boolean}).annotate({identifier:"FormatterStatus"}),Co=class extends Re.Service()("@opencode/Format"){static{i(this,"Service")}},hI=Wt(Co),gI=Te.effect(Co,r.gen(function*(){let e=yield*Oe.Service,t=yield*Ko.Service,n=yield*Be.Service,o=yield*G.make(r.fn("Format.state")(function*(d){let p={},f={};async function u(T){let m=p[T.name];return(m===!1||m===void 0)&&(m=await T.enabled({...d,experimentalOxfmt:n.experimentalOxfmt}),p[T.name]=m),m}i(u,"getCommand");async function g(T){return await u(T)!==!1}i(g,"isEnabled");async function y(T){let m=Object.values(f).filter(k=>k.extensions.includes(T));return(await Promise.all(m.map(async k=>{let w=await u(k);return{item:k,cmd:w}}))).filter(k=>k.cmd!==!1).map(k=>({item:k.item,cmd:k.cmd}))}i(y,"getFormatter");function b(T){return r.gen(function*(){yield*r.logInfo("formatting",{file:T});let m=yield*r.promise(()=>y(fI.extname(T)));if(!m.length)return!1;for(let{item:h,cmd:k}of m){yield*r.logInfo("running",{command:k});let w=k.map(x=>x.replace("$FILE",T)),I=yield*G.directory,P=yield*t.run(Vn.make(w[0],w.slice(1),{cwd:I,env:h.environment,extendEnv:!0,stdin:"ignore",stdout:"ignore",stderr:"ignore"})).pipe(r.catch(x=>r.logError("failed to format file",{error:"spawn failed",command:k,...h.environment,file:T,cause:gn(x.cause??x)}).pipe(r.as(void 0))));P&&P.exitCode!==0&&(yield*r.logError("failed",{command:k,...h.environment}))}return!0})}i(b,"formatFile");let S=yield*e.get();if(!S.formatter)return yield*r.logInfo("all formatters are disabled"),yield*r.logInfo("init"),{formatters:f,isEnabled:g,formatFile:b};for(let T of Object.values(ua))f[T.name]=T;if(S.formatter!==!0)for(let[T,m]of Object.entries(S.formatter)){let h=ua[T];if(["ruff","uv"].includes(T)&&(S.formatter.ruff?.disabled||S.formatter.uv?.disabled)){delete f.ruff,delete f.uv;continue}if(m.disabled){delete f[T];continue}let k=di(h??{extensions:[]},m);f[T]={...k,name:T,extensions:k.extensions??[],enabled:h&&!k.command?h.enabled:async w=>k.command??!1}}return yield*r.logInfo("init"),{formatters:f,isEnabled:g,formatFile:b}})),s=r.fn("Format.init")(function*(){yield*G.get(o)}),a=r.fn("Format.status")(function*(){let{formatters:d,isEnabled:p}=yield*G.get(o),f=[];for(let u of Object.values(d)){let g=yield*r.promise(()=>p(u));f.push({name:u.name,extensions:u.extensions,enabled:g})}return f}),l=r.fn("Format.file")(function*(d){let{formatFile:p}=yield*G.get(o);return yield*p(d)});return Co.of({init:s,status:a,file:l})})),yI=ke.make({service:Co,layer:gI,deps:[Oe.node,Ko.node,Be.node]});var $n={};fe($n,{Service:()=>jr,ToolRegistry:()=>$n,node:()=>Jk,webSearchEnabled:()=>Lh});import bI from"path";var Om=`Use this tool when you have completed the planning phase and are ready to exit plan agent.
1033
+ </diagnostics>`}i(jS,"report");var Mm=Ds,Am=c.Struct({line:mn,character:mn}),da=c.Struct({start:Am,end:Am}).annotate({identifier:"Range"}),FS=c.Struct({name:c.String,kind:mn,location:c.Struct({uri:c.String,range:da})}).annotate({identifier:"Symbol"}),BS=c.Struct({name:c.String,detail:c.optional(c.String),kind:mn,range:da,selectionRange:da}).annotate({identifier:"DocumentSymbol"}),$S=c.Struct({id:c.String,name:c.String,root:c.String,status:c.Literals(["connected","error"])}).annotate({identifier:"LSPStatus"});var qS=[5,12,6,11,13,14,23,10],WS=i((e,t)=>{t.experimentalLspTy?e.pyright&&delete e.pyright:e.ty&&delete e.ty},"filterExperimentalServers"),_r=class extends Re.Service()("@opencode/LSP"){static{i(this,"Service")}},VS=Te.effect(_r,r.gen(function*(){let e=yield*Oe.Service,t=yield*Be.Service,n=yield*De.Service,o=yield*G.make(r.fn("LSP.state")(function*(x){let A=yield*e.get(),C={};if(!A.lsp)yield*r.logInfo("all LSPs are disabled");else{for(let j of Object.values(Hl))C[j.id]=j;if(WS(C,t),A.lsp!==!0)for(let[j,z]of Object.entries(A.lsp)){let ie=C[j];if(z.disabled){yield*r.logInfo(`LSP server ${j} is disabled`),delete C[j];continue}C[j]={...ie,id:j,root:ie?.root??(async(L,V)=>V.directory),extensions:z.extensions??ie?.extensions??[],spawn:i(async L=>({process:Ee(z.command[0],z.command.slice(1),{cwd:L,env:{...process.env,...z.env}}),initialization:z.initialization}),"spawn")}}yield*r.logInfo("enabled LSP servers",{serverIds:Object.values(C).map(j=>j.id).join(", ")})}let $={clients:[],servers:C,broken:new Set,spawning:new Map};return yield*r.addFinalizer(()=>r.promise(async()=>{await Promise.all($.clients.map(j=>j.shutdown()))})),$})),s=r.fnUntraced(function*(x){let A=yield*G.context;if(!pi(x,A))return[];let C=yield*G.get(o),$=yield*r.promise(async()=>{let j=Yl.parse(x).ext||x,z=[],ie=0;async function L(V,D,M){let _=await V.spawn(D,A,t).then(U=>(U||C.broken.add(M),U)).catch(()=>{C.broken.add(M)});if(!_)return;let N=await Im({serverID:V.id,server:_,root:D,directory:A.directory,instance:A}).catch(async()=>{C.broken.add(M),await it.stop(_.process)});if(!N)return;let W=C.clients.find(U=>U.root===D&&U.serverID===V.id);return W?(await it.stop(_.process),W):(C.clients.push(N),N)}i(L,"schedule");for(let V of Object.values(C.servers)){if(V.extensions.length&&!V.extensions.includes(j))continue;let D=await V.root(x,A);if(!D||C.broken.has(D+V.id))continue;let M=C.clients.find(U=>U.root===D&&U.serverID===V.id);if(M){z.push(M);continue}let _=C.spawning.get(D+V.id);if(_){let U=await _;if(!U)continue;z.push(U);continue}let N=L(V,D,D+V.id);C.spawning.set(D+V.id,N),N.finally(()=>{C.spawning.get(D+V.id)===N&&C.spawning.delete(D+V.id)});let W=await N;W&&(z.push(W),ie++)}return{result:z,updated:ie}});return yield*r.forEach(Array.from({length:$.updated}),()=>n.publish(Mm.Updated,{}),{discard:!0}),$.result}),a=r.fnUntraced(function*(x,A){let C=yield*s(x);return yield*r.promise(()=>Promise.all(C.map($=>A($))))}),l=r.fnUntraced(function*(x){let A=yield*G.get(o);return yield*r.promise(()=>Promise.all(A.clients.map(C=>x(C))))}),d=r.fn("LSP.init")(function*(){yield*G.get(o)}),p=r.fn("LSP.status")(function*(){let x=yield*G.context,A=yield*G.get(o),C=[];for(let $ of A.clients)C.push({id:$.serverID,name:A.servers[$.serverID].id,root:Yl.relative(x.directory,$.root),status:"connected"});return C}),f=r.fn("LSP.hasClients")(function*(x){let A=yield*G.context,C=yield*G.get(o);return yield*r.promise(async()=>{let $=Yl.parse(x).ext||x;for(let j of Object.values(C.servers)){if(j.extensions.length&&!j.extensions.includes($))continue;let z=await j.root(x,A);if(z&&!C.broken.has(z+j.id))return!0}return!1})}),u=r.fn("LSP.touchFile")(function*(x,A){yield*r.logInfo("touching file",{file:x});let C=yield*s(x);yield*r.promise(()=>Promise.all(C.map(async $=>{let j=Date.now(),z=await $.notify.open({path:x});if(A)return $.waitForDiagnostics({path:x,version:z,mode:A,after:j})})).catch(()=>{}))}),g=r.fn("LSP.diagnostics")(function*(){let x={},A=yield*l(async C=>C.diagnostics);for(let C of A)for(let[$,j]of C.entries()){let z=x[$]||[];z.push(...j),x[$]=z}return x}),y=r.fn("LSP.hover")(function*(x){return yield*a(x.file,A=>A.connection.sendRequest("textDocument/hover",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))}),b=r.fn("LSP.definition")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/definition",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))).flat().filter(Boolean)}),S=r.fn("LSP.references")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/references",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character},context:{includeDeclaration:!0}}).catch(()=>[]))).flat().filter(Boolean)}),T=r.fn("LSP.implementation")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/implementation",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))).flat().filter(Boolean)}),m=r.fn("LSP.documentSymbol")(function*(x){let A=US(x);return(yield*a(A,$=>$.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:x}}).catch(()=>[]))).flat().filter(Boolean)}),h=r.fn("LSP.workspaceSymbol")(function*(x){return(yield*l(C=>C.connection.sendRequest("workspace/symbol",{query:x}).then($=>$.filter(j=>qS.includes(j.kind)).slice(0,10)).catch(()=>[]))).flat()}),k=r.fn("LSP.prepareCallHierarchy")(function*(x){return(yield*a(x.file,C=>C.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>[]))).flat().filter(Boolean)}),w=r.fnUntraced(function*(x,A){return(yield*a(x.file,async $=>{let j=await $.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:Mr(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>[]);return j?.length?$.connection.sendRequest(A,{item:j[0]}).catch(()=>[]):[]})).flat().filter(Boolean)}),I=r.fn("LSP.incomingCalls")(function*(x){return yield*w(x,"callHierarchy/incomingCalls")}),P=r.fn("LSP.outgoingCalls")(function*(x){return yield*w(x,"callHierarchy/outgoingCalls")});return _r.of({init:d,status:p,hasClients:f,touchFile:u,diagnostics:g,hover:y,definition:b,references:S,implementation:T,documentSymbol:m,workspaceSymbol:h,prepareCallHierarchy:k,incomingCalls:I,outgoingCalls:P})})),zS=ke.make({service:_r,layer:VS,deps:[Oe.node,Be.node,Ae.node,De.node]});var Jt={};fe(Jt,{Format:()=>Jt,Service:()=>Co,Status:()=>bI,node:()=>xI,use:()=>wI});import yI from"path";var ua={};fe(ua,{biome:()=>KS,clang:()=>QS,cljfmt:()=>hI,dart:()=>sI,dfmt:()=>gI,gleam:()=>lI,gofmt:()=>GS,htmlbeautifier:()=>rI,ktlint:()=>ZS,latexindent:()=>cI,mix:()=>HS,nixfmt:()=>uI,ocamlformat:()=>iI,ormolu:()=>mI,oxfmt:()=>JS,pint:()=>fI,prettier:()=>YS,rlang:()=>eI,rubocop:()=>nI,ruff:()=>_m,rustfmt:()=>pI,shfmt:()=>dI,standardrb:()=>oI,terraform:()=>aI,uvformat:()=>tI,zig:()=>XS});var GS={name:"gofmt",extensions:[".go"],async enabled(){let e=se("gofmt");return e?[e,"-w","$FILE"]:!1}},HS={name:"mix",extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){let e=se("mix");return e?[e,"format","$FILE"]:!1}},YS={name:"prettier",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=await be.findUp("package.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.dependencies?.prettier||o.devDependencies?.prettier){let s=await Ut.which("prettier");if(s)return[s,"--write","$FILE"]}}return!1}},JS={name:"oxfmt",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts"],async enabled(e){if(!e.experimentalOxfmt)return!1;let t=await be.findUp("package.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.dependencies?.oxfmt||o.devDependencies?.oxfmt){let s=await Ut.which("oxfmt");if(s)return[s,"$FILE"]}}return!1}},KS={name:"biome",environment:{BUN_BE_BUN:"1"},extensions:[".js",".jsx",".mjs",".cjs",".ts",".tsx",".mts",".cts",".html",".htm",".css",".scss",".sass",".less",".vue",".svelte",".json",".jsonc",".yaml",".yml",".toml",".xml",".md",".mdx",".graphql",".gql"],async enabled(e){let t=["biome.json","biome.jsonc"];for(let n of t)if((await be.findUp(n,e.directory,e.worktree)).length>0){let s=await Ut.which("@biomejs/biome");if(s)return[s,"format","--write","$FILE"]}return!1}},XS={name:"zig",extensions:[".zig",".zon"],async enabled(){let e=se("zig");return e?[e,"fmt","$FILE"]:!1}},QS={name:"clang-format",extensions:[".c",".cc",".cpp",".cxx",".c++",".h",".hh",".hpp",".hxx",".h++",".ino",".C",".H"],async enabled(e){if((await be.findUp(".clang-format",e.directory,e.worktree)).length>0){let n=se("clang-format");if(n)return[n,"-i","$FILE"]}return!1}},ZS={name:"ktlint",extensions:[".kt",".kts"],async enabled(){let e=se("ktlint");return e?[e,"-F","$FILE"]:!1}},_m={name:"ruff",extensions:[".py",".pyi"],async enabled(e){if(!se("ruff"))return!1;let t=["pyproject.toml","ruff.toml",".ruff.toml"];for(let o of t){let s=await be.findUp(o,e.directory,e.worktree);if(s.length>0)if(o==="pyproject.toml"){if((await be.readText(s[0])).includes("[tool.ruff]"))return["ruff","format","$FILE"]}else return["ruff","format","$FILE"]}let n=["requirements.txt","pyproject.toml","Pipfile"];for(let o of n){let s=await be.findUp(o,e.directory,e.worktree);if(s.length>0&&(await be.readText(s[0])).includes("ruff"))return["ruff","format","$FILE"]}return!1}},eI={name:"air",extensions:[".R"],async enabled(){let e=se("air");if(e==null)return!1;let t=await it.text([e,"--help"],{nothrow:!0}),n=t.text.split(`
1034
+ `)[0],o=n.includes("R language"),s=n.includes("formatter");return t.code===0&&o&&s?[e,"format","$FILE"]:!1}},tI={name:"uv",extensions:[".py",".pyi"],async enabled(e){if(await _m.enabled(e))return!1;let t=se("uv");return t==null?!1:(await it.run([t,"format","--help"],{nothrow:!0})).code===0?[t,"format","--","$FILE"]:!1}},nI={name:"rubocop",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=se("rubocop");return e?[e,"--autocorrect","$FILE"]:!1}},oI={name:"standardrb",extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){let e=se("standardrb");return e?[e,"--fix","$FILE"]:!1}},rI={name:"htmlbeautifier",extensions:[".erb",".html.erb"],async enabled(){let e=se("htmlbeautifier");return e?[e,"$FILE"]:!1}},sI={name:"dart",extensions:[".dart"],async enabled(){let e=se("dart");return e?[e,"format","$FILE"]:!1}},iI={name:"ocamlformat",extensions:[".ml",".mli"],async enabled(e){return se("ocamlformat")&&(await be.findUp(".ocamlformat",e.directory,e.worktree)).length>0?["ocamlformat","-i","$FILE"]:!1}},aI={name:"terraform",extensions:[".tf",".tfvars"],async enabled(){let e=se("terraform");return e?[e,"fmt","$FILE"]:!1}},cI={name:"latexindent",extensions:[".tex"],async enabled(){let e=se("latexindent");return e?[e,"-w","-s","$FILE"]:!1}},lI={name:"gleam",extensions:[".gleam"],async enabled(){let e=se("gleam");return e?[e,"format","$FILE"]:!1}},dI={name:"shfmt",extensions:[".sh",".bash"],async enabled(){let e=se("shfmt");return e?[e,"-w","$FILE"]:!1}},uI={name:"nixfmt",extensions:[".nix"],async enabled(){let e=se("nixfmt");return e?[e,"$FILE"]:!1}},pI={name:"rustfmt",extensions:[".rs"],async enabled(){let e=se("rustfmt");return e?[e,"$FILE"]:!1}},fI={name:"pint",extensions:[".php"],async enabled(e){let t=await be.findUp("composer.json",e.directory,e.worktree);for(let n of t){let o=await be.readJson(n);if(o.require?.["laravel/pint"]||o["require-dev"]?.["laravel/pint"])return["./vendor/bin/pint","$FILE"]}return!1}},mI={name:"ormolu",extensions:[".hs"],async enabled(){let e=se("ormolu");return e?[e,"-i","$FILE"]:!1}},hI={name:"cljfmt",extensions:[".clj",".cljs",".cljc",".edn"],async enabled(){let e=se("cljfmt");return e?[e,"fix","--quiet","$FILE"]:!1}},gI={name:"dfmt",extensions:[".d"],async enabled(){let e=se("dfmt");return e?[e,"-i","$FILE"]:!1}};var bI=c.Struct({name:c.String,extensions:c.Array(c.String),enabled:c.Boolean}).annotate({identifier:"FormatterStatus"}),Co=class extends Re.Service()("@opencode/Format"){static{i(this,"Service")}},wI=Wt(Co),vI=Te.effect(Co,r.gen(function*(){let e=yield*Oe.Service,t=yield*Ko.Service,n=yield*Be.Service,o=yield*G.make(r.fn("Format.state")(function*(d){let p={},f={};async function u(T){let m=p[T.name];return(m===!1||m===void 0)&&(m=await T.enabled({...d,experimentalOxfmt:n.experimentalOxfmt}),p[T.name]=m),m}i(u,"getCommand");async function g(T){return await u(T)!==!1}i(g,"isEnabled");async function y(T){let m=Object.values(f).filter(k=>k.extensions.includes(T));return(await Promise.all(m.map(async k=>{let w=await u(k);return{item:k,cmd:w}}))).filter(k=>k.cmd!==!1).map(k=>({item:k.item,cmd:k.cmd}))}i(y,"getFormatter");function b(T){return r.gen(function*(){yield*r.logInfo("formatting",{file:T});let m=yield*r.promise(()=>y(yI.extname(T)));if(!m.length)return!1;for(let{item:h,cmd:k}of m){yield*r.logInfo("running",{command:k});let w=k.map(x=>x.replace("$FILE",T)),I=yield*G.directory,P=yield*t.run(Vn.make(w[0],w.slice(1),{cwd:I,env:h.environment,extendEnv:!0,stdin:"ignore",stdout:"ignore",stderr:"ignore"})).pipe(r.catch(x=>r.logError("failed to format file",{error:"spawn failed",command:k,...h.environment,file:T,cause:gn(x.cause??x)}).pipe(r.as(void 0))));P&&P.exitCode!==0&&(yield*r.logError("failed",{command:k,...h.environment}))}return!0})}i(b,"formatFile");let S=yield*e.get();if(!S.formatter)return yield*r.logInfo("all formatters are disabled"),yield*r.logInfo("init"),{formatters:f,isEnabled:g,formatFile:b};for(let T of Object.values(ua))f[T.name]=T;if(S.formatter!==!0)for(let[T,m]of Object.entries(S.formatter)){let h=ua[T];if(["ruff","uv"].includes(T)&&(S.formatter.ruff?.disabled||S.formatter.uv?.disabled)){delete f.ruff,delete f.uv;continue}if(m.disabled){delete f[T];continue}let k=di(h??{extensions:[]},m);f[T]={...k,name:T,extensions:k.extensions??[],enabled:h&&!k.command?h.enabled:async w=>k.command??!1}}return yield*r.logInfo("init"),{formatters:f,isEnabled:g,formatFile:b}})),s=r.fn("Format.init")(function*(){yield*G.get(o)}),a=r.fn("Format.status")(function*(){let{formatters:d,isEnabled:p}=yield*G.get(o),f=[];for(let u of Object.values(d)){let g=yield*r.promise(()=>p(u));f.push({name:u.name,extensions:u.extensions,enabled:g})}return f}),l=r.fn("Format.file")(function*(d){let{formatFile:p}=yield*G.get(o);return yield*p(d)});return Co.of({init:s,status:a,file:l})})),xI=ke.make({service:Co,layer:vI,deps:[Oe.node,Ko.node,Be.node]});var $n={};fe($n,{Service:()=>jr,ToolRegistry:()=>$n,node:()=>Zk,webSearchEnabled:()=>Lh});import SI from"path";var Om=`Use this tool when you have completed the planning phase and are ready to exit plan agent.
1035
1035
 
1036
1036
  This tool will ask the user if they want to switch to build agent to start implementing the plan.
1037
1037
 
@@ -1044,7 +1044,7 @@ Do NOT call this tool:
1044
1044
  - Before you have created or finalized the plan
1045
1045
  - If you still have unanswered questions about the implementation
1046
1046
  - If the user has indicated they want to continue planning
1047
- `;var wI=c.Struct({}),Lm=Ge("plan_exit",r.gen(function*(){let e=yield*me.Service,t=yield*Qt.Service,n=yield*yt.Service;return{description:Om,parameters:wI,execute:i((o,s)=>r.gen(function*(){let a=yield*G.context,l=yield*e.get(s.sessionID),d=bI.relative(a.worktree,me.plan(l,a));(yield*t.ask({sessionID:s.sessionID,questions:[{question:`Plan at ${d} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:!1,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:s.callID?{messageID:s.messageID,callID:s.callID}:void 0}))[0]?.[0]==="No"&&(yield*new Qt.RejectedError);let u=(yield*e.messages({sessionID:s.sessionID}).pipe(r.orDie)).findLast(b=>b.info.role==="user"&&b.info.model),g=u?.info.role==="user"&&u.info.model?u.info.model:yield*n.defaultModel(),y={id:at.ascending(),sessionID:s.sessionID,role:"user",time:{created:Date.now()},agent:"build",model:g};return yield*e.updateMessage(y),yield*e.updatePart({id:Fe.ascending(),messageID:y.id,sessionID:s.sessionID,type:"text",text:`The plan at ${d} has been approved, you can now edit files. Execute the plan`,synthetic:!0}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{}}}).pipe(r.orDie),"execute")}}));var Nm=`Use this tool when you need to ask the user questions during execution. This allows you to:
1047
+ `;var II=c.Struct({}),Lm=Ge("plan_exit",r.gen(function*(){let e=yield*me.Service,t=yield*Qt.Service,n=yield*yt.Service;return{description:Om,parameters:II,execute:i((o,s)=>r.gen(function*(){let a=yield*G.context,l=yield*e.get(s.sessionID),d=SI.relative(a.worktree,me.plan(l,a));(yield*t.ask({sessionID:s.sessionID,questions:[{question:`Plan at ${d} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:!1,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:s.callID?{messageID:s.messageID,callID:s.callID}:void 0}))[0]?.[0]==="No"&&(yield*new Qt.RejectedError);let u=(yield*e.messages({sessionID:s.sessionID}).pipe(r.orDie)).findLast(b=>b.info.role==="user"&&b.info.model),g=u?.info.role==="user"&&u.info.model?u.info.model:yield*n.defaultModel(),y={id:at.ascending(),sessionID:s.sessionID,role:"user",time:{created:Date.now()},agent:"build",model:g};return yield*e.updateMessage(y),yield*e.updatePart({id:Fe.ascending(),messageID:y.id,sessionID:s.sessionID,type:"text",text:`The plan at ${d} has been approved, you can now edit files. Execute the plan`,synthetic:!0}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{}}}).pipe(r.orDie),"execute")}}));var Nm=`Use this tool when you need to ask the user questions during execution. This allows you to:
1048
1048
  1. Gather user preferences or requirements
1049
1049
  2. Clarify ambiguous instructions
1050
1050
  3. Get decisions on implementation choices as you work
@@ -1054,53 +1054,53 @@ Usage notes:
1054
1054
  - When \`custom\` is enabled (default), a "Type your own answer" option is added automatically; don't include "Other" or catch-all options
1055
1055
  - Answers are returned as arrays of labels; set \`multiple: true\` to allow selecting more than one
1056
1056
  - If you recommend a specific option, make that the first option in the list and add "(Recommended)" at the end of the label
1057
- `;var vI=c.Struct({questions:c.mutable(c.Array(Qt.Prompt)).annotate({description:"Questions to ask"})}),jm=Ge("question",r.gen(function*(){let e=yield*Qt.Service;return{description:Nm,parameters:vI,execute:i((t,n)=>r.gen(function*(){let o=yield*e.ask({sessionID:n.sessionID,questions:t.questions,tool:n.callID?{messageID:n.messageID,callID:n.callID}:void 0}),s=t.questions.map((a,l)=>`"${a.question}"="${o[l]?.length?o[l].join(", "):"Unanswered"}"`).join(", ");return{title:`Asked ${t.questions.length} question${t.questions.length>1?"s":""}`,output:`User has answered your questions: ${s}. You can now continue with the user's answers in mind.`,metadata:{answers:o}}}).pipe(r.orDie),"execute")}}));import*as ao from"path";var Um='Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + colon + space (e.g., `1: `). Everything after that space is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `oldString` is not found in the file with an error "oldString not found in content".\n- The edit will FAIL if `oldString` is found multiple times in the file with an error "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match." Either provide a larger string with more surrounding context to make it unique or use `replaceAll` to change every instance of `oldString`. \n- Use `replaceAll` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n';import Jl from"path";var $t=r.fn("Tool.assertExternalDirectory")(function*(e,t,n){if(!t||n?.bypass)return!1;let o=yield*G.context,s=process.platform==="win32"?Ae.normalizePath(t):t;if(pi(s,o))return!1;let l=(n?.kind??"file")==="directory"?s:Jl.dirname(s),d=process.platform==="win32"?Ae.normalizePathPattern(Jl.join(l,"*")):Jl.join(l,"*").replaceAll("\\","/");return yield*e.ask({permission:"external_directory",patterns:[d],always:[d],metadata:{filepath:s,parentDir:l}}),!0});var Fm=65279,xI=String.fromCharCode(Fm);function pn(e){return e.charCodeAt(0)!==Fm?{bom:!1,text:e}:{bom:!0,text:e.slice(1)}}i(pn,"split");function Kt(e,t){let n=pn(e).text;return t?xI+n:n}i(Kt,"join");var io=r.fn("Bom.readFile")(function*(e,t){return pn(new TextDecoder("utf-8",{ignoreBOM:!0}).decode(yield*e.readFile(t)))}),Ao=r.fn("Bom.syncFile")(function*(e,t,n){let o=yield*io(e,t);return o.bom===n||(yield*e.writeWithDirs(t,Kt(o.text,n))),o.text});function Or(e){return e.replaceAll(`\r
1057
+ `;var kI=c.Struct({questions:c.mutable(c.Array(Qt.Prompt)).annotate({description:"Questions to ask"})}),jm=Ge("question",r.gen(function*(){let e=yield*Qt.Service;return{description:Nm,parameters:kI,execute:i((t,n)=>r.gen(function*(){let o=yield*e.ask({sessionID:n.sessionID,questions:t.questions,tool:n.callID?{messageID:n.messageID,callID:n.callID}:void 0}),s=t.questions.map((a,l)=>`"${a.question}"="${o[l]?.length?o[l].join(", "):"Unanswered"}"`).join(", ");return{title:`Asked ${t.questions.length} question${t.questions.length>1?"s":""}`,output:`User has answered your questions: ${s}. You can now continue with the user's answers in mind.`,metadata:{answers:o}}}).pipe(r.orDie),"execute")}}));import*as ao from"path";var Um='Performs exact string replacements in files. \n\nUsage:\n- You must use your `Read` tool at least once in the conversation before editing. This tool will error if you attempt an edit without reading the file. \n- When editing text from Read tool output, ensure you preserve the exact indentation (tabs/spaces) as it appears AFTER the line number prefix. The line number prefix format is: line number + colon + space (e.g., `1: `). Everything after that space is the actual file content to match. Never include any part of the line number prefix in the oldString or newString.\n- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.\n- Only use emojis if the user explicitly requests it. Avoid adding emojis to files unless asked.\n- The edit will FAIL if `oldString` is not found in the file with an error "oldString not found in content".\n- The edit will FAIL if `oldString` is found multiple times in the file with an error "Found multiple matches for oldString. Provide more surrounding lines in oldString to identify the correct match." Either provide a larger string with more surrounding context to make it unique or use `replaceAll` to change every instance of `oldString`. \n- Use `replaceAll` for replacing and renaming strings across the file. This parameter is useful if you want to rename a variable for instance.\n';import Jl from"path";var $t=r.fn("Tool.assertExternalDirectory")(function*(e,t,n){if(!t||n?.bypass)return!1;let o=yield*G.context,s=process.platform==="win32"?Ae.normalizePath(t):t;if(pi(s,o))return!1;let l=(n?.kind??"file")==="directory"?s:Jl.dirname(s),d=process.platform==="win32"?Ae.normalizePathPattern(Jl.join(l,"*")):Jl.join(l,"*").replaceAll("\\","/");return yield*e.ask({permission:"external_directory",patterns:[d],always:[d],metadata:{filepath:s,parentDir:l}}),!0});var Fm=65279,DI=String.fromCharCode(Fm);function pn(e){return e.charCodeAt(0)!==Fm?{bom:!1,text:e}:{bom:!0,text:e.slice(1)}}i(pn,"split");function Kt(e,t){let n=pn(e).text;return t?DI+n:n}i(Kt,"join");var io=r.fn("Bom.readFile")(function*(e,t){return pn(new TextDecoder("utf-8",{ignoreBOM:!0}).decode(yield*e.readFile(t)))}),Ao=r.fn("Bom.syncFile")(function*(e,t,n){let o=yield*io(e,t);return o.bom===n||(yield*e.writeWithDirs(t,Kt(o.text,n))),o.text});function Or(e){return e.replaceAll(`\r
1058
1058
  `,`
1059
- `)}i(Or,"normalizeLineEndings");function SI(e){return e.includes(`\r
1059
+ `)}i(Or,"normalizeLineEndings");function EI(e){return e.includes(`\r
1060
1060
  `)?`\r
1061
1061
  `:`
1062
- `}i(SI,"detectLineEnding");function Bm(e,t){return t===`
1062
+ `}i(EI,"detectLineEnding");function Bm(e,t){return t===`
1063
1063
  `?e:e.replaceAll(`
1064
1064
  `,`\r
1065
- `)}i(Bm,"convertToLineEnding");var $m=new Map;function II(e){let t=Ae.resolve(e),n=$m.get(t);if(n)return n;let o=Ad.makeUnsafe(1);return $m.set(t,o),o}i(II,"lock");var kI=c.Struct({filePath:c.String.annotate({description:"The absolute path to the file to modify"}),oldString:c.String.annotate({description:"The text to replace"}),newString:c.String.annotate({description:"The text to replace it with (must be different from oldString)"}),replaceAll:c.optional(c.Boolean).annotate({description:"Replace all occurrences of oldString (default false)"})}),Kl=Ge("edit",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*Jt.Service,o=yield*De.Service;return{description:Um,parameters:kI,execute:i((s,a)=>r.gen(function*(){if(!s.filePath)throw new Error("filePath is required");if(s.oldString===s.newString)throw new Error("No changes to apply: oldString and newString are identical.");let l=yield*G.context,d=ao.isAbsolute(s.filePath)?s.filePath:ao.join(l.directory,s.filePath);yield*$t(a,d);let p="",f="",u="";yield*II(d).withPermits(1)(r.gen(function*(){if(s.oldString===""){if(yield*t.existsSafe(d))throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let j=pn(s.newString),z=j.bom;f="",u=j.text,p=Fn(Dn(d,d,f,u)),yield*a.ask({permission:"edit",patterns:[ao.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:p}}),yield*t.writeWithDirs(d,Kt(u,z)),(yield*n.file(d))&&(u=yield*Ao(t,d,z)),yield*o.publish(mo.Event.Edited,{file:d}),yield*o.publish(_n.Event.Updated,{file:d,event:"add"});return}let k=yield*t.stat(d).pipe(r.catch(()=>r.succeed(void 0)));if(!k)throw new Error(`File ${d} not found`);if(k.type==="Directory")throw new Error(`Path is a directory, not a file: ${d}`);let w=yield*io(t,d);f=w.text;let I=SI(f),P=Bm(Or(s.oldString),I),x=Bm(Or(s.newString),I),A=pn(LI(f,P,x,s.replaceAll)),C=w.bom||A.bom;u=A.text,p=Fn(Dn(d,d,Or(f),Or(u))),yield*a.ask({permission:"edit",patterns:[ao.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:p}}),yield*t.writeWithDirs(d,Kt(u,C)),(yield*n.file(d))&&(u=yield*Ao(t,d,C)),yield*o.publish(mo.Event.Edited,{file:d}),yield*o.publish(_n.Event.Updated,{file:d,event:"change"}),p=Fn(Dn(d,d,Or(f),Or(u)))}).pipe(r.orDie));let g=0,y=0;for(let k of ts(f,u))k.added&&(g+=k.count||0),k.removed&&(y+=k.count||0);let b={file:d,patch:p,additions:g,deletions:y};yield*a.metadata({metadata:{diff:p,filediff:b,diagnostics:{}}});let S="Edit applied successfully.";yield*e.touchFile(d,"document");let T=yield*e.diagnostics(),m=Ae.normalizePath(d),h=ft.Diagnostic.report(d,T[m]??[]);return h&&(S+=`
1065
+ `)}i(Bm,"convertToLineEnding");var $m=new Map;function TI(e){let t=Ae.resolve(e),n=$m.get(t);if(n)return n;let o=Ad.makeUnsafe(1);return $m.set(t,o),o}i(TI,"lock");var PI=c.Struct({filePath:c.String.annotate({description:"The absolute path to the file to modify"}),oldString:c.String.annotate({description:"The text to replace"}),newString:c.String.annotate({description:"The text to replace it with (must be different from oldString)"}),replaceAll:c.optional(c.Boolean).annotate({description:"Replace all occurrences of oldString (default false)"})}),Kl=Ge("edit",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*Jt.Service,o=yield*De.Service;return{description:Um,parameters:PI,execute:i((s,a)=>r.gen(function*(){if(!s.filePath)throw new Error("filePath is required");if(s.oldString===s.newString)throw new Error("No changes to apply: oldString and newString are identical.");let l=yield*G.context,d=ao.isAbsolute(s.filePath)?s.filePath:ao.join(l.directory,s.filePath);yield*$t(a,d);let p="",f="",u="";yield*TI(d).withPermits(1)(r.gen(function*(){if(s.oldString===""){if(yield*t.existsSafe(d))throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let j=pn(s.newString),z=j.bom;f="",u=j.text,p=Fn(Dn(d,d,f,u)),yield*a.ask({permission:"edit",patterns:[ao.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:p}}),yield*t.writeWithDirs(d,Kt(u,z)),(yield*n.file(d))&&(u=yield*Ao(t,d,z)),yield*o.publish(mo.Event.Edited,{file:d}),yield*o.publish(_n.Event.Updated,{file:d,event:"add"});return}let k=yield*t.stat(d).pipe(r.catch(()=>r.succeed(void 0)));if(!k)throw new Error(`File ${d} not found`);if(k.type==="Directory")throw new Error(`Path is a directory, not a file: ${d}`);let w=yield*io(t,d);f=w.text;let I=EI(f),P=Bm(Or(s.oldString),I),x=Bm(Or(s.newString),I),A=pn(FI(f,P,x,s.replaceAll)),C=w.bom||A.bom;u=A.text,p=Fn(Dn(d,d,Or(f),Or(u))),yield*a.ask({permission:"edit",patterns:[ao.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:p}}),yield*t.writeWithDirs(d,Kt(u,C)),(yield*n.file(d))&&(u=yield*Ao(t,d,C)),yield*o.publish(mo.Event.Edited,{file:d}),yield*o.publish(_n.Event.Updated,{file:d,event:"change"}),p=Fn(Dn(d,d,Or(f),Or(u)))}).pipe(r.orDie));let g=0,y=0;for(let k of ts(f,u))k.added&&(g+=k.count||0),k.removed&&(y+=k.count||0);let b={file:d,patch:p,additions:g,deletions:y};yield*a.metadata({metadata:{diff:p,filediff:b,diagnostics:{}}});let S="Edit applied successfully.";yield*e.touchFile(d,"document");let T=yield*e.diagnostics(),m=Ae.normalizePath(d),h=ft.Diagnostic.report(d,T[m]??[]);return h&&(S+=`
1066
1066
 
1067
1067
  LSP errors detected in this file, please fix:
1068
- ${h}`),{metadata:{diagnostics:T,diff:p,filediff:b},title:`${ao.relative(l.worktree,d)}`,output:S}}),"execute")}})),qm=.65,DI=.65;function Wm(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let n=Array.from({length:e.length+1},(o,s)=>Array.from({length:t.length+1},(a,l)=>s===0?l:l===0?s:0));for(let o=1;o<=e.length;o++)for(let s=1;s<=t.length;s++){let a=e[o-1]===t[s-1]?0:1;n[o][s]=Math.min(n[o-1][s]+1,n[o][s-1]+1,n[o-1][s-1]+a)}return n[e.length][t.length]}i(Wm,"levenshtein");var EI=i(function*(e,t){yield t},"SimpleReplacer"),TI=i(function*(e,t){let n=e.split(`
1068
+ ${h}`),{metadata:{diagnostics:T,diff:p,filediff:b},title:`${ao.relative(l.worktree,d)}`,output:S}}),"execute")}})),qm=.65,RI=.65;function Wm(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let n=Array.from({length:e.length+1},(o,s)=>Array.from({length:t.length+1},(a,l)=>s===0?l:l===0?s:0));for(let o=1;o<=e.length;o++)for(let s=1;s<=t.length;s++){let a=e[o-1]===t[s-1]?0:1;n[o][s]=Math.min(n[o-1][s]+1,n[o][s-1]+1,n[o-1][s-1]+a)}return n[e.length][t.length]}i(Wm,"levenshtein");var CI=i(function*(e,t){yield t},"SimpleReplacer"),AI=i(function*(e,t){let n=e.split(`
1069
1069
  `),o=t.split(`
1070
- `);o[o.length-1]===""&&o.pop();for(let s=0;s<=n.length-o.length;s++){let a=!0;for(let l=0;l<o.length;l++){let d=n[s+l].trim(),p=o[l].trim();if(d!==p){a=!1;break}}if(a){let l=0;for(let p=0;p<s;p++)l+=n[p].length+1;let d=l;for(let p=0;p<o.length;p++)d+=n[s+p].length,p<o.length-1&&(d+=1);yield e.substring(l,d)}}},"LineTrimmedReplacer"),PI=i(function*(e,t){let n=e.split(`
1070
+ `);o[o.length-1]===""&&o.pop();for(let s=0;s<=n.length-o.length;s++){let a=!0;for(let l=0;l<o.length;l++){let d=n[s+l].trim(),p=o[l].trim();if(d!==p){a=!1;break}}if(a){let l=0;for(let p=0;p<s;p++)l+=n[p].length+1;let d=l;for(let p=0;p<o.length;p++)d+=n[s+p].length,p<o.length-1&&(d+=1);yield e.substring(l,d)}}},"LineTrimmedReplacer"),MI=i(function*(e,t){let n=e.split(`
1071
1071
  `),o=t.split(`
1072
- `);if(o.length<3)return;o[o.length-1]===""&&o.pop();let s=o[0].trim(),a=o[o.length-1].trim(),l=o.length,d=Math.max(1,Math.floor(l*.25)),p=[];for(let g=0;g<n.length;g++)if(n[g].trim()===s){for(let y=g+2;y<n.length;y++)if(n[y].trim()===a){let b=y-g+1;Math.abs(b-l)<=d&&p.push({startLine:g,endLine:y});break}}if(p.length===0)return;if(p.length===1){let{startLine:g,endLine:y}=p[0],b=y-g+1,S=0,T=Math.min(l-2,b-2);if(T>0)for(let m=1;m<l-1&&m<b-1;m++){let h=n[g+m].trim(),k=o[m].trim(),w=Math.max(h.length,k.length);if(w===0)continue;let I=Wm(h,k);if(S+=(1-I/w)/T,S>=qm)break}else S=1;if(S>=qm){let m=0;for(let k=0;k<g;k++)m+=n[k].length+1;let h=m;for(let k=g;k<=y;k++)h+=n[k].length,k<y&&(h+=1);yield e.substring(m,h)}return}let f=null,u=-1;for(let g of p){let{startLine:y,endLine:b}=g,S=b-y+1,T=0,m=Math.min(l-2,S-2);if(m>0){for(let h=1;h<l-1&&h<S-1;h++){let k=n[y+h].trim(),w=o[h].trim(),I=Math.max(k.length,w.length);if(I===0)continue;let P=Wm(k,w);T+=1-P/I}T/=m}else T=1;T>u&&(u=T,f=g)}if(u>=DI&&f){let{startLine:g,endLine:y}=f,b=0;for(let T=0;T<g;T++)b+=n[T].length+1;let S=b;for(let T=g;T<=y;T++)S+=n[T].length,T<y&&(S+=1);yield e.substring(b,S)}},"BlockAnchorReplacer"),RI=i(function*(e,t){let n=i(l=>l.replace(/\s+/g," ").trim(),"normalizeWhitespace"),o=n(t),s=e.split(`
1072
+ `);if(o.length<3)return;o[o.length-1]===""&&o.pop();let s=o[0].trim(),a=o[o.length-1].trim(),l=o.length,d=Math.max(1,Math.floor(l*.25)),p=[];for(let g=0;g<n.length;g++)if(n[g].trim()===s){for(let y=g+2;y<n.length;y++)if(n[y].trim()===a){let b=y-g+1;Math.abs(b-l)<=d&&p.push({startLine:g,endLine:y});break}}if(p.length===0)return;if(p.length===1){let{startLine:g,endLine:y}=p[0],b=y-g+1,S=0,T=Math.min(l-2,b-2);if(T>0)for(let m=1;m<l-1&&m<b-1;m++){let h=n[g+m].trim(),k=o[m].trim(),w=Math.max(h.length,k.length);if(w===0)continue;let I=Wm(h,k);if(S+=(1-I/w)/T,S>=qm)break}else S=1;if(S>=qm){let m=0;for(let k=0;k<g;k++)m+=n[k].length+1;let h=m;for(let k=g;k<=y;k++)h+=n[k].length,k<y&&(h+=1);yield e.substring(m,h)}return}let f=null,u=-1;for(let g of p){let{startLine:y,endLine:b}=g,S=b-y+1,T=0,m=Math.min(l-2,S-2);if(m>0){for(let h=1;h<l-1&&h<S-1;h++){let k=n[y+h].trim(),w=o[h].trim(),I=Math.max(k.length,w.length);if(I===0)continue;let P=Wm(k,w);T+=1-P/I}T/=m}else T=1;T>u&&(u=T,f=g)}if(u>=RI&&f){let{startLine:g,endLine:y}=f,b=0;for(let T=0;T<g;T++)b+=n[T].length+1;let S=b;for(let T=g;T<=y;T++)S+=n[T].length,T<y&&(S+=1);yield e.substring(b,S)}},"BlockAnchorReplacer"),_I=i(function*(e,t){let n=i(l=>l.replace(/\s+/g," ").trim(),"normalizeWhitespace"),o=n(t),s=e.split(`
1073
1073
  `);for(let l=0;l<s.length;l++){let d=s[l];if(n(d)===o)yield d;else if(n(d).includes(o)){let f=t.trim().split(/\s+/);if(f.length>0){let u=f.map(g=>g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let g=new RegExp(u),y=d.match(g);y&&(yield y[0])}catch{}}}}let a=t.split(`
1074
1074
  `);if(a.length>1)for(let l=0;l<=s.length-a.length;l++){let d=s.slice(l,l+a.length);n(d.join(`
1075
1075
  `))===o&&(yield d.join(`
1076
- `))}},"WhitespaceNormalizedReplacer"),CI=i(function*(e,t){let n=i(l=>{let d=l.split(`
1076
+ `))}},"WhitespaceNormalizedReplacer"),OI=i(function*(e,t){let n=i(l=>{let d=l.split(`
1077
1077
  `),p=d.filter(u=>u.trim().length>0);if(p.length===0)return l;let f=Math.min(...p.map(u=>{let g=u.match(/^(\s*)/);return g?g[1].length:0}));return d.map(u=>u.trim().length===0?u:u.slice(f)).join(`
1078
1078
  `)},"removeIndentation"),o=n(t),s=e.split(`
1079
1079
  `),a=t.split(`
1080
1080
  `);for(let l=0;l<=s.length-a.length;l++){let d=s.slice(l,l+a.length).join(`
1081
- `);n(d)===o&&(yield d)}},"IndentationFlexibleReplacer"),AI=i(function*(e,t){let n=i(l=>l.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(d,p)=>{switch(p){case"n":return`
1081
+ `);n(d)===o&&(yield d)}},"IndentationFlexibleReplacer"),LI=i(function*(e,t){let n=i(l=>l.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(d,p)=>{switch(p){case"n":return`
1082
1082
  `;case"t":return" ";case"r":return"\r";case"'":return"'";case'"':return'"';case"`":return"`";case"\\":return"\\";case`
1083
1083
  `:return`
1084
1084
  `;case"$":return"$";default:return d}}),"unescapeString"),o=n(t);e.includes(o)&&(yield o);let s=e.split(`
1085
1085
  `),a=o.split(`
1086
1086
  `);for(let l=0;l<=s.length-a.length;l++){let d=s.slice(l,l+a.length).join(`
1087
- `);n(d)===o&&(yield d)}},"EscapeNormalizedReplacer"),MI=i(function*(e,t){let n=0;for(;;){let o=e.indexOf(t,n);if(o===-1)break;yield t,n=o+t.length}},"MultiOccurrenceReplacer"),_I=i(function*(e,t){let n=t.trim();if(n===t)return;e.includes(n)&&(yield n);let o=e.split(`
1087
+ `);n(d)===o&&(yield d)}},"EscapeNormalizedReplacer"),NI=i(function*(e,t){let n=0;for(;;){let o=e.indexOf(t,n);if(o===-1)break;yield t,n=o+t.length}},"MultiOccurrenceReplacer"),jI=i(function*(e,t){let n=t.trim();if(n===t)return;e.includes(n)&&(yield n);let o=e.split(`
1088
1088
  `),s=t.split(`
1089
1089
  `);for(let a=0;a<=o.length-s.length;a++){let l=o.slice(a,a+s.length).join(`
1090
- `);l.trim()===n&&(yield l)}},"TrimmedBoundaryReplacer"),OI=i(function*(e,t){let n=t.split(`
1090
+ `);l.trim()===n&&(yield l)}},"TrimmedBoundaryReplacer"),UI=i(function*(e,t){let n=t.split(`
1091
1091
  `);if(n.length<3)return;n[n.length-1]===""&&n.pop();let o=e.split(`
1092
1092
  `),s=n[0].trim(),a=n[n.length-1].trim();for(let l=0;l<o.length;l++)if(o[l].trim()===s){for(let d=l+2;d<o.length;d++)if(o[d].trim()===a){let p=o.slice(l,d+1),f=p.join(`
1093
1093
  `);if(p.length===n.length){let u=0,g=0;for(let y=1;y<p.length-1;y++){let b=p[y].trim(),S=n[y].trim();(b.length>0||S.length>0)&&(g++,b===S&&u++)}if(g===0||u/g>=.5){yield f;break}}break}}},"ContextAwareReplacer");function Fn(e){let t=e.split(`
1094
1094
  `),n=t.filter(a=>(a.startsWith("+")||a.startsWith("-")||a.startsWith(" "))&&!a.startsWith("---")&&!a.startsWith("+++"));if(n.length===0)return e;let o=1/0;for(let a of n){let l=a.slice(1);if(l.trim().length>0){let d=l.match(/^(\s*)/);d&&(o=Math.min(o,d[1].length))}}return o===1/0||o===0?e:t.map(a=>{if((a.startsWith("+")||a.startsWith("-")||a.startsWith(" "))&&!a.startsWith("---")&&!a.startsWith("+++")){let l=a[0],d=a.slice(1);return l+d.slice(o)}return a}).join(`
1095
- `)}i(Fn,"trimDiff");function LI(e,t,n,o=!1){if(t===n)throw new Error("No changes to apply: oldString and newString are identical.");if(t==="")throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let s=!0;for(let a of[EI,TI,PI,RI,CI,AI,_I,OI,MI])for(let l of a(e,t)){let d=e.indexOf(l);if(d===-1)continue;if(s=!1,NI(l,t))throw new Error("Refusing replacement because the matched span is much larger than oldString. Re-read the file and provide the full exact oldString for the intended replacement.");if(o)return e.replaceAll(l,n);let p=e.lastIndexOf(l);if(d===p)return e.substring(0,d)+n+e.substring(d+l.length)}throw s?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}i(LI,"replace");function NI(e,t){let n=t.split(`
1095
+ `)}i(Fn,"trimDiff");function FI(e,t,n,o=!1){if(t===n)throw new Error("No changes to apply: oldString and newString are identical.");if(t==="")throw new Error("oldString cannot be empty when editing an existing file. Provide the exact text to replace, or use write for an intentional full-file replacement.");let s=!0;for(let a of[CI,AI,MI,_I,OI,LI,jI,UI,NI])for(let l of a(e,t)){let d=e.indexOf(l);if(d===-1)continue;if(s=!1,BI(l,t))throw new Error("Refusing replacement because the matched span is much larger than oldString. Re-read the file and provide the full exact oldString for the intended replacement.");if(o)return e.replaceAll(l,n);let p=e.lastIndexOf(l);if(d===p)return e.substring(0,d)+n+e.substring(d+l.length)}throw s?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}i(FI,"replace");function BI(e,t){let n=t.split(`
1096
1096
  `).length;return e.split(`
1097
- `).length>=Math.max(n+3,n*2)?!0:n===1?!1:e.trim().length>Math.max(t.trim().length+500,t.trim().length*4)}i(NI,"isDisproportionateMatch");import fa from"path";var Vm=`- Fast file pattern matching tool that works with any codebase size
1097
+ `).length>=Math.max(n+3,n*2)?!0:n===1?!1:e.trim().length>Math.max(t.trim().length+500,t.trim().length*4)}i(BI,"isDisproportionateMatch");import fa from"path";var Vm=`- Fast file pattern matching tool that works with any codebase size
1098
1098
  - Supports glob patterns like "**/*.js" or "src/**/*.ts"
1099
1099
  - Returns matching file paths
1100
1100
  - Use this tool when you need to find files by name patterns
1101
1101
  - When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
1102
1102
  - You have the capability to call multiple tools in a single response. It is always better to speculatively perform multiple searches as a batch that are potentially useful.
1103
- `;var jI=c.Struct({pattern:c.String.annotate({description:"The glob pattern to match files against"}),path:c.optional(c.String).annotate({description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.'})}),zm=Ge("glob",r.gen(function*(){let e=yield*Ae.Service,t=yield*Hn.Service;return{description:Vm,parameters:jI,execute:i((n,o)=>r.gen(function*(){let s=yield*G.context;yield*o.ask({permission:"glob",patterns:[n.pattern],always:["*"],metadata:{pattern:n.pattern,path:n.path}});let a=n.path??s.directory;if(a=fa.isAbsolute(a)?a:fa.resolve(s.directory,a),(yield*e.stat(a).pipe(r.catch(()=>r.succeed(void 0))))?.type==="File")throw new Error(`glob path must be a directory: ${a}`);yield*$t(o,a,{bypass:!1,kind:"directory"});let d=100,p=yield*t.glob({cwd:a,pattern:n.pattern,limit:d}),f=p.length===d,u=[];return p.length===0&&u.push("No files found"),p.length>0&&(u.push(...p.map(g=>fa.resolve(a,g.path))),f&&(u.push(""),u.push(`(Results are truncated: showing first ${d} results. Consider using a more specific path or pattern.)`))),{title:fa.relative(s.worktree,a),metadata:{count:p.length,truncated:f},output:u.join(`
1103
+ `;var $I=c.Struct({pattern:c.String.annotate({description:"The glob pattern to match files against"}),path:c.optional(c.String).annotate({description:'The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter "undefined" or "null" - simply omit it for the default behavior. Must be a valid directory path if provided.'})}),zm=Ge("glob",r.gen(function*(){let e=yield*Ae.Service,t=yield*Hn.Service;return{description:Vm,parameters:$I,execute:i((n,o)=>r.gen(function*(){let s=yield*G.context;yield*o.ask({permission:"glob",patterns:[n.pattern],always:["*"],metadata:{pattern:n.pattern,path:n.path}});let a=n.path??s.directory;if(a=fa.isAbsolute(a)?a:fa.resolve(s.directory,a),(yield*e.stat(a).pipe(r.catch(()=>r.succeed(void 0))))?.type==="File")throw new Error(`glob path must be a directory: ${a}`);yield*$t(o,a,{bypass:!1,kind:"directory"});let d=100,p=yield*t.glob({cwd:a,pattern:n.pattern,limit:d}),f=p.length===d,u=[];return p.length===0&&u.push("No files found"),p.length>0&&(u.push(...p.map(g=>fa.resolve(a,g.path))),f&&(u.push(""),u.push(`(Results are truncated: showing first ${d} results. Consider using a more specific path or pattern.)`))),{title:fa.relative(s.worktree,a),metadata:{count:p.length,truncated:f},output:u.join(`
1104
1104
  `)}}).pipe(r.orDie),"execute")}}));import Ts from"path";var Gm=`- Fast content search tool that works with any codebase size
1105
1105
  - Searches file contents using regular expressions
1106
1106
  - Supports full regex syntax (eg. "log.*Error", "function\\s+\\w+", etc.)
@@ -1109,7 +1109,7 @@ ${h}`),{metadata:{diagnostics:T,diff:p,filediff:b},title:`${ao.relative(l.worktr
1109
1109
  - Use this tool when you need to find files containing specific patterns
1110
1110
  - If you need to identify/count the number of matches within files, use the Bash tool with \`rg\` (ripgrep) directly. Do NOT use \`grep\`.
1111
1111
  - When you are doing an open-ended search that may require multiple rounds of globbing and grepping, use the Task tool instead
1112
- `;var UI=c.Struct({pattern:c.String.annotate({description:"The regex pattern to search for in file contents"}),path:c.optional(c.String).annotate({description:"The directory to search in. Defaults to the current working directory."}),include:c.optional(c.String).annotate({description:'File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'})}),Hm=Ge("grep",r.gen(function*(){let e=yield*Ae.Service,t=yield*Hn.Service;return{description:Gm,parameters:UI,execute:i((n,o)=>r.gen(function*(){let s={title:n.pattern,metadata:{matches:0,truncated:!1},output:"No files found"};if(!n.pattern)throw new Error("pattern is required");yield*o.ask({permission:"grep",patterns:[n.pattern],always:["*"],metadata:{pattern:n.pattern,path:n.path,include:n.include}});let a=yield*G.context,l=Ts.isAbsolute(n.path??a.directory)?n.path??a.directory:Ts.join(a.directory,n.path??"."),d=yield*e.stat(l).pipe(r.catch(()=>r.succeed(void 0)));yield*$t(o,l,{bypass:!1,kind:d?.type==="Directory"?"directory":"file"});let p=Ae.resolve(l),u=(yield*e.stat(p).pipe(r.catch(()=>r.succeed(void 0))))?.type==="Directory"?p:Ts.dirname(p),g=yield*t.grep({cwd:u,pattern:n.pattern,include:n.include,limit:100});if(g.length===0)return s;let y=g.map(I=>({path:Ts.resolve(d?.type==="Directory"?l:Ts.dirname(l),I.entry.path),line:I.line,text:I.text})),b=100,S=y.length===b,T=y;if(T.length===0)return s;let m=y.length,h=S||g.length===b,k=[`Found ${m} matches${h?" (more matches available)":""}`],w="";for(let I of T)w!==I.path&&(w!==""&&k.push(""),w=I.path,k.push(`${I.path}:`)),k.push(` Line ${I.line}: ${I.text}`);return S&&(k.push(""),k.push("(Results truncated. Consider using a more specific path or pattern.)")),{title:n.pattern,metadata:{matches:m,truncated:S},output:k.join(`
1112
+ `;var qI=c.Struct({pattern:c.String.annotate({description:"The regex pattern to search for in file contents"}),path:c.optional(c.String).annotate({description:"The directory to search in. Defaults to the current working directory."}),include:c.optional(c.String).annotate({description:'File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")'})}),Hm=Ge("grep",r.gen(function*(){let e=yield*Ae.Service,t=yield*Hn.Service;return{description:Gm,parameters:qI,execute:i((n,o)=>r.gen(function*(){let s={title:n.pattern,metadata:{matches:0,truncated:!1},output:"No files found"};if(!n.pattern)throw new Error("pattern is required");yield*o.ask({permission:"grep",patterns:[n.pattern],always:["*"],metadata:{pattern:n.pattern,path:n.path,include:n.include}});let a=yield*G.context,l=Ts.isAbsolute(n.path??a.directory)?n.path??a.directory:Ts.join(a.directory,n.path??"."),d=yield*e.stat(l).pipe(r.catch(()=>r.succeed(void 0)));yield*$t(o,l,{bypass:!1,kind:d?.type==="Directory"?"directory":"file"});let p=Ae.resolve(l),u=(yield*e.stat(p).pipe(r.catch(()=>r.succeed(void 0))))?.type==="Directory"?p:Ts.dirname(p),g=yield*t.grep({cwd:u,pattern:n.pattern,include:n.include,limit:100});if(g.length===0)return s;let y=g.map(I=>({path:Ts.resolve(d?.type==="Directory"?l:Ts.dirname(l),I.entry.path),line:I.line,text:I.text})),b=100,S=y.length===b,T=y;if(T.length===0)return s;let m=y.length,h=S||g.length===b,k=[`Found ${m} matches${h?" (more matches available)":""}`],w="";for(let I of T)w!==I.path&&(w!==""&&k.push(""),w=I.path,k.push(`${I.path}:`)),k.push(` Line ${I.line}: ${I.text}`);return S&&(k.push(""),k.push("(Results truncated. Consider using a more specific path or pattern.)")),{title:n.pattern,metadata:{matches:m,truncated:S},output:k.join(`
1113
1113
  `)}}).pipe(r.orDie),"execute")}}));import*as jt from"path";var Ym=`Read a file or directory from the local filesystem. If the path does not exist, an error is returned.
1114
1114
 
1115
1115
  Usage:
@@ -1124,21 +1124,21 @@ Usage:
1124
1124
  - Call this tool in parallel when you know there are multiple files you want to read.
1125
1125
  - Avoid tiny repeated slices (30 line chunks). If you need more context, read a larger window.
1126
1126
  - This tool can read image files and PDFs and return them as file attachments.
1127
- `;var Jm=2e3,Xl=2e3,FI=`... (line truncated to ${Xl} chars)`,Km=50*1024,BI=`${Km/1024} KB`,$I=4096,qI=new Set(["image/jpeg","image/png","image/gif","image/webp"]),ma=class extends c.TaggedErrorClass()("ReadStop",{}){static{i(this,"ReadStop")}},WI=c.Struct({filePath:c.String.annotate({description:"The absolute path to the file or directory to read"}),offset:c.optional(mn).annotate({description:"The line number to start reading from (1-indexed)"}),limit:c.optional(mn).annotate({description:"The maximum number of lines to read (defaults to 2000)"})}),Xm=Ge("read",r.gen(function*(){let e=yield*Ae.Service,t=yield*En.Service,n=yield*ft.Service,o=yield*Dt.Scope,s=r.fn("ReadTool.miss")(function*(g){let y=jt.dirname(g),b=jt.basename(g),S=yield*e.readDirectory(y).pipe(r.map(T=>T.filter(m=>m.toLowerCase().includes(b.toLowerCase())||b.toLowerCase().includes(m.toLowerCase())).map(m=>jt.join(y,m)).slice(0,3)),r.catch(()=>r.succeed([])));return S.length>0?yield*r.fail(new Error(`File not found: ${g}
1127
+ `;var Jm=2e3,Xl=2e3,WI=`... (line truncated to ${Xl} chars)`,Km=50*1024,VI=`${Km/1024} KB`,zI=4096,GI=new Set(["image/jpeg","image/png","image/gif","image/webp"]),ma=class extends c.TaggedErrorClass()("ReadStop",{}){static{i(this,"ReadStop")}},HI=c.Struct({filePath:c.String.annotate({description:"The absolute path to the file or directory to read"}),offset:c.optional(mn).annotate({description:"The line number to start reading from (1-indexed)"}),limit:c.optional(mn).annotate({description:"The maximum number of lines to read (defaults to 2000)"})}),Xm=Ge("read",r.gen(function*(){let e=yield*Ae.Service,t=yield*En.Service,n=yield*ft.Service,o=yield*Dt.Scope,s=r.fn("ReadTool.miss")(function*(g){let y=jt.dirname(g),b=jt.basename(g),S=yield*e.readDirectory(y).pipe(r.map(T=>T.filter(m=>m.toLowerCase().includes(b.toLowerCase())||b.toLowerCase().includes(m.toLowerCase())).map(m=>jt.join(y,m)).slice(0,3)),r.catch(()=>r.succeed([])));return S.length>0?yield*r.fail(new Error(`File not found: ${g}
1128
1128
 
1129
1129
  Did you mean one of these?
1130
1130
  ${S.join(`
1131
- `)}`)):yield*r.fail(new Error(`File not found: ${g}`))}),a=r.fn("ReadTool.list")(function*(g){let y=yield*e.readDirectoryEntries(g);return yield*r.forEach(y,r.fnUntraced(function*(b){return b.type==="directory"?b.name+"/":b.type!=="symlink"?b.name:(yield*e.stat(jt.join(g,b.name)).pipe(r.catch(()=>r.void)))?.type==="Directory"?b.name+"/":b.name}),{concurrency:"unbounded"}).pipe(r.map(b=>b.sort((S,T)=>S.localeCompare(T))))}),l=r.fn("ReadTool.warm")(function*(g){yield*n.touchFile(g).pipe(r.ignoreCause,r.forkIn(o))}),d=r.fn("ReadTool.readSample")(function*(g,y,b){return y===0?new Uint8Array:yield*r.scoped(r.gen(function*(){let S=yield*e.open(g,{flag:"r"});return xn.getOrElse(yield*S.readAlloc(Math.min(b,y)),()=>new Uint8Array)}))}),p=r.fn("ReadTool.lines")(function*(g,y){let b=y.offset-1,S=[],T={bytes:0,count:0,cut:!1,more:!1,done:!1},m=new TextDecoder("utf-8");return yield*e.stream(g).pipe(vt.map(h=>m.decode(h,{stream:!0})),vt.splitLines,vt.runForEach(h=>r.gen(function*(){if(T.done)return yield*new ma;if(T.count+=1,T.count<=b)return;if(S.length>=y.limit){T.more=!0;return}let k=h.length>Xl?h.substring(0,Xl)+FI:h,w=Buffer.byteLength(k,"utf-8")+(S.length>0?1:0);if(T.bytes+w<=Km){S.push(k),T.bytes+=w;return}return T.cut=!0,T.more=!0,T.done=!0,yield*new ma})),r.catchTag("ReadStop",()=>r.void)),{raw:S,count:T.count,cut:T.cut,more:T.more,offset:y.offset}}),f=i((g,y)=>{switch(jt.extname(g).toLowerCase()){case".zip":case".tar":case".gz":case".exe":case".dll":case".so":case".class":case".jar":case".war":case".7z":case".doc":case".docx":case".xls":case".xlsx":case".ppt":case".pptx":case".odt":case".ods":case".odp":case".bin":case".dat":case".obj":case".o":case".a":case".lib":case".wasm":case".pyc":case".pyo":return!0}if(y.length===0)return!1;let S=0;for(let T=0;T<y.length;T++){if(y[T]===0)return!0;(y[T]<9||y[T]>13&&y[T]<32)&&S++}return S/y.length>.3},"isBinaryFile"),u=r.fn("ReadTool.execute")(function*(g,y){let b=yield*G.context,S=g.filePath;jt.isAbsolute(S)||(S=jt.resolve(b.directory,S)),process.platform==="win32"&&(S=Ae.normalizePath(S));let T=jt.relative(b.worktree,S),m=yield*e.stat(S).pipe(r.catchIf(j=>"reason"in j&&j.reason._tag==="NotFound",()=>r.succeed(void 0)));if(yield*$t(y,S,{bypass:!!y.extra?.bypassCwdCheck,kind:m?.type==="Directory"?"directory":"file"}),yield*y.ask({permission:"read",patterns:[jt.relative(b.worktree,S)],always:["*"],metadata:{}}),!m)return yield*s(S);if(m.type==="Directory"){let j=yield*a(S),z=g.limit??Jm,ie=g.offset||1,L=ie-1,V=j.slice(L,L+z),D=L+V.length<j.length;return{title:T,output:[`<path>${S}</path>`,"<type>directory</type>","<entries>",V.join(`
1131
+ `)}`)):yield*r.fail(new Error(`File not found: ${g}`))}),a=r.fn("ReadTool.list")(function*(g){let y=yield*e.readDirectoryEntries(g);return yield*r.forEach(y,r.fnUntraced(function*(b){return b.type==="directory"?b.name+"/":b.type!=="symlink"?b.name:(yield*e.stat(jt.join(g,b.name)).pipe(r.catch(()=>r.void)))?.type==="Directory"?b.name+"/":b.name}),{concurrency:"unbounded"}).pipe(r.map(b=>b.sort((S,T)=>S.localeCompare(T))))}),l=r.fn("ReadTool.warm")(function*(g){yield*n.touchFile(g).pipe(r.ignoreCause,r.forkIn(o))}),d=r.fn("ReadTool.readSample")(function*(g,y,b){return y===0?new Uint8Array:yield*r.scoped(r.gen(function*(){let S=yield*e.open(g,{flag:"r"});return xn.getOrElse(yield*S.readAlloc(Math.min(b,y)),()=>new Uint8Array)}))}),p=r.fn("ReadTool.lines")(function*(g,y){let b=y.offset-1,S=[],T={bytes:0,count:0,cut:!1,more:!1,done:!1},m=new TextDecoder("utf-8");return yield*e.stream(g).pipe(vt.map(h=>m.decode(h,{stream:!0})),vt.splitLines,vt.runForEach(h=>r.gen(function*(){if(T.done)return yield*new ma;if(T.count+=1,T.count<=b)return;if(S.length>=y.limit){T.more=!0;return}let k=h.length>Xl?h.substring(0,Xl)+WI:h,w=Buffer.byteLength(k,"utf-8")+(S.length>0?1:0);if(T.bytes+w<=Km){S.push(k),T.bytes+=w;return}return T.cut=!0,T.more=!0,T.done=!0,yield*new ma})),r.catchTag("ReadStop",()=>r.void)),{raw:S,count:T.count,cut:T.cut,more:T.more,offset:y.offset}}),f=i((g,y)=>{switch(jt.extname(g).toLowerCase()){case".zip":case".tar":case".gz":case".exe":case".dll":case".so":case".class":case".jar":case".war":case".7z":case".doc":case".docx":case".xls":case".xlsx":case".ppt":case".pptx":case".odt":case".ods":case".odp":case".bin":case".dat":case".obj":case".o":case".a":case".lib":case".wasm":case".pyc":case".pyo":return!0}if(y.length===0)return!1;let S=0;for(let T=0;T<y.length;T++){if(y[T]===0)return!0;(y[T]<9||y[T]>13&&y[T]<32)&&S++}return S/y.length>.3},"isBinaryFile"),u=r.fn("ReadTool.execute")(function*(g,y){let b=yield*G.context,S=g.filePath;jt.isAbsolute(S)||(S=jt.resolve(b.directory,S)),process.platform==="win32"&&(S=Ae.normalizePath(S));let T=jt.relative(b.worktree,S),m=yield*e.stat(S).pipe(r.catchIf(j=>"reason"in j&&j.reason._tag==="NotFound",()=>r.succeed(void 0)));if(yield*$t(y,S,{bypass:!!y.extra?.bypassCwdCheck,kind:m?.type==="Directory"?"directory":"file"}),yield*y.ask({permission:"read",patterns:[jt.relative(b.worktree,S)],always:["*"],metadata:{}}),!m)return yield*s(S);if(m.type==="Directory"){let j=yield*a(S),z=g.limit??Jm,ie=g.offset||1,L=ie-1,V=j.slice(L,L+z),D=L+V.length<j.length;return{title:T,output:[`<path>${S}</path>`,"<type>directory</type>","<entries>",V.join(`
1132
1132
  `),D?`
1133
1133
  (Showing ${V.length} of ${j.length} entries. Use 'offset' parameter to read beyond entry ${ie+V.length})`:`
1134
1134
  (${j.length} entries)`,"</entries>"].join(`
1135
1135
  `),metadata:{preview:V.slice(0,20).join(`
1136
- `),truncated:D,loaded:[],display:{type:"directory",path:S,entries:V,offset:ie,totalEntries:j.length,truncated:D}}}}let h=yield*t.resolve(y.messages,S,y.messageID),k=yield*d(S,Number(m.size),$I),w=zu(k,Ae.mimeType(S));if(qI.has(w)||oc(w)){let j=yield*e.readFile(S),z=oc(w)?"PDF read successfully":"Image read successfully";return{title:T,output:z,metadata:{preview:z,truncated:!1,loaded:h.map(ie=>ie.filepath)},attachments:[{type:"file",mime:w,url:`data:${w};base64,${Buffer.from(j).toString("base64")}`}]}}if(f(S,k))return yield*r.fail(new Error(`Cannot read binary file: ${S}`));let P=yield*p(S,{limit:g.limit??Jm,offset:g.offset||1});if(P.count<P.offset&&!(P.count===0&&P.offset===1))return yield*r.fail(new Error(`Offset ${P.offset} is out of range for this file (${P.count} lines)`));let x=[`<path>${S}</path>`,"<type>file</type>",`<content>
1136
+ `),truncated:D,loaded:[],display:{type:"directory",path:S,entries:V,offset:ie,totalEntries:j.length,truncated:D}}}}let h=yield*t.resolve(y.messages,S,y.messageID),k=yield*d(S,Number(m.size),zI),w=zu(k,Ae.mimeType(S));if(GI.has(w)||oc(w)){let j=yield*e.readFile(S),z=oc(w)?"PDF read successfully":"Image read successfully";return{title:T,output:z,metadata:{preview:z,truncated:!1,loaded:h.map(ie=>ie.filepath)},attachments:[{type:"file",mime:w,url:`data:${w};base64,${Buffer.from(j).toString("base64")}`}]}}if(f(S,k))return yield*r.fail(new Error(`Cannot read binary file: ${S}`));let P=yield*p(S,{limit:g.limit??Jm,offset:g.offset||1});if(P.count<P.offset&&!(P.count===0&&P.offset===1))return yield*r.fail(new Error(`Offset ${P.offset} is out of range for this file (${P.count} lines)`));let x=[`<path>${S}</path>`,"<type>file</type>",`<content>
1137
1137
  `].join(`
1138
1138
  `);x+=P.raw.map((j,z)=>`${z+P.offset}: ${j}`).join(`
1139
1139
  `);let A=P.offset+P.raw.length-1,C=A+1,$=P.more||P.cut;return P.cut?x+=`
1140
1140
 
1141
- (Output capped at ${BI}. Showing lines ${P.offset}-${A}. Use offset=${C} to continue.)`:P.more?x+=`
1141
+ (Output capped at ${VI}. Showing lines ${P.offset}-${A}. Use offset=${C} to continue.)`:P.more?x+=`
1142
1142
 
1143
1143
  (Showing lines ${P.offset}-${A} of ${P.count}. Use offset=${C} to continue.)`:x+=`
1144
1144
 
@@ -1151,7 +1151,7 @@ ${h.map(j=>j.content).join(`
1151
1151
  `)}
1152
1152
  </system-reminder>`),{title:T,output:x,metadata:{preview:P.raw.slice(0,20).join(`
1153
1153
  `),truncated:$,loaded:h.map(j=>j.filepath),display:{type:"file",path:S,text:P.raw.join(`
1154
- `),lineStart:P.offset,lineEnd:A,totalLines:P.count,truncated:$}}}});return{description:Ym,parameters:WI,execute:i((g,y)=>u(g,y).pipe(r.orDie),"execute")}}));var Ql=`WHEN TO USE: research and exploration (synchronous, returns findings directly). For implementation work \u2014 file edits, feature changes, bug fixes \u2014 spawn a coder via subagent_operations spawn instead.
1154
+ `),lineStart:P.offset,lineEnd:A,totalLines:P.count,truncated:$}}}});return{description:Ym,parameters:HI,execute:i((g,y)=>u(g,y).pipe(r.orDie),"execute")}}));var Ql=`WHEN TO USE: research and exploration (synchronous, returns findings directly). For implementation work \u2014 file edits, feature changes, bug fixes \u2014 spawn a coder via subagent_operations spawn instead.
1155
1155
 
1156
1156
  Launch a new agent to handle complex, multistep tasks autonomously.
1157
1157
 
@@ -1175,12 +1175,12 @@ Usage notes:
1175
1175
  5. The agent's outputs should generally be trusted
1176
1176
  6. Clearly tell the agent whether you expect it to write code or just to do research (search, file reads, web fetches, etc.), since it is not aware of the user's intent. Tell it how to verify its work if possible (e.g., relevant test commands).
1177
1177
  7. If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.
1178
- `;var Mo={};fe(Mo,{ToolJsonSchema:()=>Mo,fromSchema:()=>Zm,fromTool:()=>VI});var Qm=new WeakMap;function Zm(e){let t=Qm.get(e);if(t)return t;let n=c.toJsonSchemaDocument(e,{additionalProperties:!0}),o=Bn({$schema:Vd.META_SCHEMA_URI_DRAFT_2020_12,...n.schema,...Object.keys(n.definitions).length>0?{$defs:n.definitions}:{}}),s=JI(ha(o));if(!zI(s))throw new Error("tool JSON Schema helper produced a non-schema value");return Qm.set(e,s),s}i(Zm,"fromSchema");function VI(e){return e.jsonSchema??Zm(e.parameters)}i(VI,"fromTool");function Bn(e,t={}){if(Array.isArray(e))return e.map(s=>Bn(s));if(!qt(e))return e;let n=Array.isArray(e.required)?new Set(e.required.filter(s=>typeof s=="string")):void 0,o=Object.fromEntries(Object.entries(e).map(([s,a])=>[s,s==="properties"&&qt(a)?Object.fromEntries(Object.entries(a).map(([l,d])=>[l,Bn(d,{stripNull:!n?.has(l)})])):Bn(a)]));if(o.additionalProperties===!0&&delete o.additionalProperties,t.stripNull&&Array.isArray(o.anyOf)){let s=o.anyOf.filter(a=>!qt(a)||a.type!=="null");if(s.length!==o.anyOf.length)return Bn({...o,anyOf:s})}if(Array.isArray(o.anyOf)){let s=o.anyOf,a=s.find(d=>qt(d)&&d.type==="number"),l=s.filter(d=>qt(d)&&Array.isArray(d.enum)&&d.enum.every(p=>GI(p)));if(a&&l.length===s.length-1){let{anyOf:d,...p}=o;return Bn({...a,...p})}if(HI(s)){let{anyOf:d,...p}=o;return Bn({type:"object",properties:{},...p})}if(s.length===1&&qt(s[0])){let{anyOf:d,...p}=o;return Bn({...s[0],...p})}}if(Array.isArray(o.allOf)&&o.allOf.every(qt)&&YI(o.allOf,o)){let{allOf:s,...a}=o;return Bn({...Object.assign({},...s),...a})}return o.type==="integer"&&o.maximum===void 0?{minimum:Number.MIN_SAFE_INTEGER,...o,maximum:Number.MAX_SAFE_INTEGER}:o}i(Bn,"normalize");function qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(qt,"isRecord");function zI(e){return typeof e=="boolean"||qt(e)}i(zI,"isJsonSchema");function GI(e){return e==="NaN"||e==="Infinity"||e==="-Infinity"}i(GI,"isNonFiniteNumber");function HI(e){return e.length===2&&e.some(t=>qt(t)&&t.type==="object"&&t.properties===void 0)&&e.some(t=>qt(t)&&t.type==="array"&&t.items===void 0)}i(HI,"isEmptyStructUnion");function YI(e,t){let n=new Set(Object.keys(t).filter(o=>o!=="allOf"));return e.every(o=>Object.keys(o).every(s=>n.has(s)?!1:(n.add(s),!0)))}i(YI,"canFlattenAllOf");function ha(e,t,n=new Set){if(Array.isArray(e))return e.map(s=>ha(s,t,n));if(!qt(e))return e;let o=t??(qt(e.$defs)?e.$defs:void 0);if(typeof e.$ref=="string"&&o){let s=e.$ref.match(/^#\/\$defs\/(.+)$/)?.[1]??e.$ref.match(/^#\/definitions\/(.+)$/)?.[1];if(s&&!n.has(s)){let a=o[s];if(a){let{$ref:l,...d}=e;return ha({...qt(a)?a:{},...d},o,new Set(n).add(s))}}}return Object.fromEntries(Object.entries(e).map(([s,a])=>[s,ha(a,o,n)]))}i(ha,"inlineLocalReferences");function JI(e){if(!qt(e)||Zl(e))return e;let{$defs:t,definitions:n,...o}=e;return o}i(JI,"dropDefinitionsIfResolved");function Zl(e){return Array.isArray(e)?e.some(Zl):qt(e)?typeof e.$ref=="string"&&(e.$ref.startsWith("#/$defs/")||e.$ref.startsWith("#/definitions/"))?!0:Object.values(e).some(Zl):!1}i(Zl,"hasLocalReference");function eh(e){let t=e.subagent.permission.some(o=>o.permission==="task"),n=e.subagent.permission.some(o=>o.permission==="todowrite");return[...e.parentSessionPermission.filter(o=>o.permission==="external_directory"||o.action==="deny"),...n?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...t?[]:[{permission:"task",pattern:"*",action:"deny"}]]}i(eh,"deriveSubagentSessionPermission");var Ps="task",KI=["Background mode: background=true launches the subagent asynchronously and returns immediately.","Foreground is the default; use it when you need the result before continuing.","Use background only for independent work that can run while you continue elsewhere.","You will be notified automatically when it finishes."].join(" "),XI=["The task is working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you launched and end your response."].join(`
1179
- `),QI=["Additional context sent to the running background task.","The task is still working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you sent and end your response."].join(`
1180
- `),th={description:c.String.annotate({description:"A short (3-5 words) description of the task"}),prompt:c.String.annotate({description:"The task for the agent to perform"}),subagent_type:c.String.annotate({description:"The type of specialized agent to use for this task"}),task_id:c.optional(c.String).annotate({description:"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)"}),command:c.optional(c.String).annotate({description:"The command that triggered this task"})},ZI=c.Struct(th),ek=c.Struct({...th,background:c.optional(c.Boolean).annotate({description:"Run the agent in the background. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress"})});function ga(e){let t=e.state==="error"?"task_error":"task_result";return[`<task id="${e.sessionID}" state="${e.state}">`,...e.summary?[`<summary>${e.summary}</summary>`]:[],`<${t}>`,e.text,`</${t}>`,"</task>"].join(`
1181
- `)}i(ga,"renderOutput");var _o=Ge(Ps,r.gen(function*(){let e=yield*Ft.Service,t=yield*bo.Service,n=yield*Oe.Service,o=yield*me.Service,s=yield*Dt.Scope,a=yield*Be.Service,l=yield*Qe.Service,d=r.fn("TaskTool.execute")(function*(p,f){let u=yield*n.get(),g=p.background===!0;if(g&&!a.experimentalBackgroundSubagents)return yield*r.fail(new Error("Background subagents require OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"));let y=yield*o.get(f.sessionID),b=y,S=0;for(;b.parentID;)S++,b=yield*o.get(b.parentID);if(S>=(u.subagent_depth??1))return yield*r.fail(new Error(`Subagent depth limit reached (${u.subagent_depth??1}). Increase "subagent_depth" to allow nested subagents.`));f.extra?.bypassAgentCheck||(yield*f.ask({permission:Ps,patterns:[p.subagent_type],always:["*"],metadata:{description:p.description,subagent_type:p.subagent_type}}));let T=yield*e.get(p.subagent_type);if(!T)return yield*r.fail(new Error(`Unknown agent type: ${p.subagent_type} is not a valid agent type`));let m=p.task_id?yield*o.get(Pt.make(p.task_id)).pipe(r.catchCause(()=>r.succeed(void 0))):void 0,h=eh({parentSessionPermission:y.permission??[],subagent:T}),k=[...T.permission.some(_=>_.permission==="todowrite")?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...T.permission.some(_=>_.permission===Ps)?[]:[{permission:Ps,pattern:"*",action:"deny"}],...u.experimental?.primary_tools?.map(_=>({permission:_,pattern:"*",action:"deny"}))??[]],w=m??(yield*o.create({parentID:f.sessionID,title:p.description+` (@${T.name} subagent)`,agent:T.name,metadata:{agentType:T.name,spawnedBy:"task-tool",callerSessionId:f.sessionID},permission:[...h,...k.filter(_=>!h.some(N=>N.permission===_.permission&&N.pattern===_.pattern&&N.action===_.action))]})),I=yield*Ze.get({sessionID:f.sessionID,messageID:f.messageID}).pipe(r.provideService(Qe.Service,l),r.orDie);if(I.info.role!=="assistant")return yield*r.fail(new Error("Not an assistant message"));let P=I.info.variant,x=T.model??{modelID:I.info.modelID,providerID:I.info.providerID},A={parentSessionId:f.sessionID,sessionId:w.id,model:x,...g?{background:!0}:{}};yield*f.metadata({title:p.description,metadata:A});let C=f.extra?.promptOps;if(!C)return yield*r.fail(new Error("TaskTool requires promptOps in ctx.extra"));let $=r.fn("TaskTool.runTask")(function*(){let _=yield*C.resolvePromptParts(p.prompt),N=yield*C.prompt({messageID:at.ascending(),sessionID:w.id,model:{modelID:x.modelID,providerID:x.providerID},variant:T.model?void 0:P,agent:T.name,parts:_});if(N.info.role==="assistant"&&N.info.error){let U="message"in N.info.error.data&&typeof N.info.error.data.message=="string"?N.info.error.data.message:N.info.error.name;return yield*r.fail(new Error(`Subagent failed (task_id: ${w.id}): ${U}`))}let W=N.parts.findLast(U=>U.type==="tool"&&U.state.status==="error");return W?.type==="tool"&&W.state.status==="error"?yield*r.fail(new Error(`Subagent failed (task_id: ${w.id}): ${W.state.error}`)):N.parts.findLast(U=>U.type==="text")?.text??""}),j=r.fn("TaskTool.injectBackgroundResult")(function*(_,N){let W=yield*o.get(f.sessionID);yield*C.prompt({sessionID:f.sessionID,agent:W.agent??f.agent,variant:P,parts:[{type:"text",synthetic:!0,text:ga({sessionID:w.id,state:_,summary:_==="completed"?`Background task completed: ${p.description}`:`Background task failed: ${p.description}`,text:N})}]}).pipe(r.ignore,r.forkIn(s,{startImmediately:!0}))}),z=r.fn("TaskTool.notifyBackgroundResult")(function*(_){yield*t.wait({id:_}).pipe(r.flatMap(N=>N.info?.status==="completed"?j("completed",N.info.output??""):N.info?.status==="error"?j("error",N.info.error??""):r.void),r.forkIn(s,{startImmediately:!0}))});if(yield*t.extend({id:w.id,run:$()}))return{title:p.description,metadata:{...A,background:!0,jobId:w.id},output:ga({sessionID:w.id,state:"running",summary:"Background task updated",text:QI})};let ie=yield*t.start({id:w.id,type:Ps,title:p.description,metadata:A,onPromote:r.all([f.metadata({title:p.description,metadata:{...A,background:!0,jobId:w.id}}),z(w.id)]),run:$().pipe(r.onInterrupt(()=>C.cancel(w.id)))});function L(){return{title:p.description,metadata:{...A,background:!0,jobId:ie.id},output:ga({sessionID:w.id,state:"running",summary:"Background task started",text:XI})}}if(i(L,"backgroundResult"),g)return yield*z(ie.id),L();let V=yield*zt.make(),D=C.cancel(w.id);function M(){V.fork(D)}return i(M,"onAbort"),yield*r.acquireUseRelease(r.sync(()=>{f.abort.addEventListener("abort",M)}),()=>r.gen(function*(){let _=yield*r.raceFirst(t.wait({id:w.id}).pipe(r.map(N=>N.info)),t.waitForPromotion(w.id));return _?.metadata?.background===!0?L():_?.status==="error"?yield*r.fail(new Error(_.error??"Task failed")):_?.status==="cancelled"?yield*r.fail(new Error("Task cancelled")):{title:p.description,metadata:A,output:ga({sessionID:w.id,state:"completed",text:_?.output??""})}}),(_,N)=>r.gen(function*(){bt.hasInterrupts(N)&&(yield*r.all([D,t.cancel(w.id)],{discard:!0}))}).pipe(r.ensuring(r.sync(()=>{f.abort.removeEventListener("abort",M)}))))});return{description:a.experimentalBackgroundSubagents?[Ql,KI].join(`
1178
+ `;var Mo={};fe(Mo,{ToolJsonSchema:()=>Mo,fromSchema:()=>Zm,fromTool:()=>YI});var Qm=new WeakMap;function Zm(e){let t=Qm.get(e);if(t)return t;let n=c.toJsonSchemaDocument(e,{additionalProperties:!0}),o=Bn({$schema:Vd.META_SCHEMA_URI_DRAFT_2020_12,...n.schema,...Object.keys(n.definitions).length>0?{$defs:n.definitions}:{}}),s=ZI(ha(o));if(!JI(s))throw new Error("tool JSON Schema helper produced a non-schema value");return Qm.set(e,s),s}i(Zm,"fromSchema");function YI(e){return e.jsonSchema??Zm(e.parameters)}i(YI,"fromTool");function Bn(e,t={}){if(Array.isArray(e))return e.map(s=>Bn(s));if(!qt(e))return e;let n=Array.isArray(e.required)?new Set(e.required.filter(s=>typeof s=="string")):void 0,o=Object.fromEntries(Object.entries(e).map(([s,a])=>[s,s==="properties"&&qt(a)?Object.fromEntries(Object.entries(a).map(([l,d])=>[l,Bn(d,{stripNull:!n?.has(l)})])):Bn(a)]));if(o.additionalProperties===!0&&delete o.additionalProperties,t.stripNull&&Array.isArray(o.anyOf)){let s=o.anyOf.filter(a=>!qt(a)||a.type!=="null");if(s.length!==o.anyOf.length)return Bn({...o,anyOf:s})}if(Array.isArray(o.anyOf)){let s=o.anyOf,a=s.find(d=>qt(d)&&d.type==="number"),l=s.filter(d=>qt(d)&&Array.isArray(d.enum)&&d.enum.every(p=>KI(p)));if(a&&l.length===s.length-1){let{anyOf:d,...p}=o;return Bn({...a,...p})}if(XI(s)){let{anyOf:d,...p}=o;return Bn({type:"object",properties:{},...p})}if(s.length===1&&qt(s[0])){let{anyOf:d,...p}=o;return Bn({...s[0],...p})}}if(Array.isArray(o.allOf)&&o.allOf.every(qt)&&QI(o.allOf,o)){let{allOf:s,...a}=o;return Bn({...Object.assign({},...s),...a})}return o.type==="integer"&&o.maximum===void 0?{minimum:Number.MIN_SAFE_INTEGER,...o,maximum:Number.MAX_SAFE_INTEGER}:o}i(Bn,"normalize");function qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(qt,"isRecord");function JI(e){return typeof e=="boolean"||qt(e)}i(JI,"isJsonSchema");function KI(e){return e==="NaN"||e==="Infinity"||e==="-Infinity"}i(KI,"isNonFiniteNumber");function XI(e){return e.length===2&&e.some(t=>qt(t)&&t.type==="object"&&t.properties===void 0)&&e.some(t=>qt(t)&&t.type==="array"&&t.items===void 0)}i(XI,"isEmptyStructUnion");function QI(e,t){let n=new Set(Object.keys(t).filter(o=>o!=="allOf"));return e.every(o=>Object.keys(o).every(s=>n.has(s)?!1:(n.add(s),!0)))}i(QI,"canFlattenAllOf");function ha(e,t,n=new Set){if(Array.isArray(e))return e.map(s=>ha(s,t,n));if(!qt(e))return e;let o=t??(qt(e.$defs)?e.$defs:void 0);if(typeof e.$ref=="string"&&o){let s=e.$ref.match(/^#\/\$defs\/(.+)$/)?.[1]??e.$ref.match(/^#\/definitions\/(.+)$/)?.[1];if(s&&!n.has(s)){let a=o[s];if(a){let{$ref:l,...d}=e;return ha({...qt(a)?a:{},...d},o,new Set(n).add(s))}}}return Object.fromEntries(Object.entries(e).map(([s,a])=>[s,ha(a,o,n)]))}i(ha,"inlineLocalReferences");function ZI(e){if(!qt(e)||Zl(e))return e;let{$defs:t,definitions:n,...o}=e;return o}i(ZI,"dropDefinitionsIfResolved");function Zl(e){return Array.isArray(e)?e.some(Zl):qt(e)?typeof e.$ref=="string"&&(e.$ref.startsWith("#/$defs/")||e.$ref.startsWith("#/definitions/"))?!0:Object.values(e).some(Zl):!1}i(Zl,"hasLocalReference");function eh(e){let t=e.subagent.permission.some(o=>o.permission==="task"),n=e.subagent.permission.some(o=>o.permission==="todowrite");return[...e.parentSessionPermission.filter(o=>o.permission==="external_directory"||o.action==="deny"),...n?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...t?[]:[{permission:"task",pattern:"*",action:"deny"}]]}i(eh,"deriveSubagentSessionPermission");var Ps="task",ek=["Background mode: background=true launches the subagent asynchronously and returns immediately.","Foreground is the default; use it when you need the result before continuing.","Use background only for independent work that can run while you continue elsewhere.","You will be notified automatically when it finishes."].join(" "),tk=["The task is working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you launched and end your response."].join(`
1179
+ `),nk=["Additional context sent to the running background task.","The task is still working in the background. You will be notified automatically when it finishes.","DO NOT sleep, poll for progress, ask the task for status, or duplicate this task's work \u2014 avoid working with the same files or topics it is using.","Work on non-overlapping tasks, or briefly tell the user what you sent and end your response."].join(`
1180
+ `),th={description:c.String.annotate({description:"A short (3-5 words) description of the task"}),prompt:c.String.annotate({description:"The task for the agent to perform"}),subagent_type:c.String.annotate({description:"The type of specialized agent to use for this task"}),task_id:c.optional(c.String).annotate({description:"This should only be set if you mean to resume a previous task (you can pass a prior task_id and the task will continue the same subagent session as before instead of creating a fresh one)"}),command:c.optional(c.String).annotate({description:"The command that triggered this task"})},ok=c.Struct(th),rk=c.Struct({...th,background:c.optional(c.Boolean).annotate({description:"Run the agent in the background. You will be notified when it completes. DO NOT sleep, poll, or proactively check on its progress"})});function ga(e){let t=e.state==="error"?"task_error":"task_result";return[`<task id="${e.sessionID}" state="${e.state}">`,...e.summary?[`<summary>${e.summary}</summary>`]:[],`<${t}>`,e.text,`</${t}>`,"</task>"].join(`
1181
+ `)}i(ga,"renderOutput");var _o=Ge(Ps,r.gen(function*(){let e=yield*Ft.Service,t=yield*bo.Service,n=yield*Oe.Service,o=yield*me.Service,s=yield*Dt.Scope,a=yield*Be.Service,l=yield*Qe.Service,d=r.fn("TaskTool.execute")(function*(p,f){let u=yield*n.get(),g=p.background===!0;if(g&&!a.experimentalBackgroundSubagents)return yield*r.fail(new Error("Background subagents require OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true"));let y=yield*o.get(f.sessionID),b=y,S=0;for(;b.parentID;)S++,b=yield*o.get(b.parentID);if(S>=(u.subagent_depth??1))return yield*r.fail(new Error(`Subagent depth limit reached (${u.subagent_depth??1}). Increase "subagent_depth" to allow nested subagents.`));f.extra?.bypassAgentCheck||(yield*f.ask({permission:Ps,patterns:[p.subagent_type],always:["*"],metadata:{description:p.description,subagent_type:p.subagent_type}}));let T=yield*e.get(p.subagent_type);if(!T)return yield*r.fail(new Error(`Unknown agent type: ${p.subagent_type} is not a valid agent type`));let m=p.task_id?yield*o.get(Pt.make(p.task_id)).pipe(r.catchCause(()=>r.succeed(void 0))):void 0,h=eh({parentSessionPermission:y.permission??[],subagent:T}),k=[...T.permission.some(_=>_.permission==="todowrite")?[]:[{permission:"todowrite",pattern:"*",action:"deny"}],...T.permission.some(_=>_.permission===Ps)?[]:[{permission:Ps,pattern:"*",action:"deny"}],...u.experimental?.primary_tools?.map(_=>({permission:_,pattern:"*",action:"deny"}))??[]],w=m??(yield*o.create({parentID:f.sessionID,title:p.description+` (@${T.name} subagent)`,agent:T.name,metadata:{agentType:T.name,spawnedBy:"task-tool",callerSessionId:f.sessionID},permission:[...h,...k.filter(_=>!h.some(N=>N.permission===_.permission&&N.pattern===_.pattern&&N.action===_.action))]})),I=yield*Ze.get({sessionID:f.sessionID,messageID:f.messageID}).pipe(r.provideService(Qe.Service,l),r.orDie);if(I.info.role!=="assistant")return yield*r.fail(new Error("Not an assistant message"));let P=I.info.variant,x=T.model??{modelID:I.info.modelID,providerID:I.info.providerID},A={parentSessionId:f.sessionID,sessionId:w.id,model:x,...g?{background:!0}:{}};yield*f.metadata({title:p.description,metadata:A});let C=f.extra?.promptOps;if(!C)return yield*r.fail(new Error("TaskTool requires promptOps in ctx.extra"));let $=r.fn("TaskTool.runTask")(function*(){let _=yield*C.resolvePromptParts(p.prompt),N=yield*C.prompt({messageID:at.ascending(),sessionID:w.id,model:{modelID:x.modelID,providerID:x.providerID},variant:T.model?void 0:P,agent:T.name,parts:_});if(N.info.role==="assistant"&&N.info.error){let U="message"in N.info.error.data&&typeof N.info.error.data.message=="string"?N.info.error.data.message:N.info.error.name;return yield*r.fail(new Error(`Subagent failed (task_id: ${w.id}): ${U}`))}let W=N.parts.findLast(U=>U.type==="tool"&&U.state.status==="error");return W?.type==="tool"&&W.state.status==="error"?yield*r.fail(new Error(`Subagent failed (task_id: ${w.id}): ${W.state.error}`)):N.parts.findLast(U=>U.type==="text")?.text??""}),j=r.fn("TaskTool.injectBackgroundResult")(function*(_,N){let W=yield*o.get(f.sessionID);yield*C.prompt({sessionID:f.sessionID,agent:W.agent??f.agent,variant:P,parts:[{type:"text",synthetic:!0,text:ga({sessionID:w.id,state:_,summary:_==="completed"?`Background task completed: ${p.description}`:`Background task failed: ${p.description}`,text:N})}]}).pipe(r.ignore,r.forkIn(s,{startImmediately:!0}))}),z=r.fn("TaskTool.notifyBackgroundResult")(function*(_){yield*t.wait({id:_}).pipe(r.flatMap(N=>N.info?.status==="completed"?j("completed",N.info.output??""):N.info?.status==="error"?j("error",N.info.error??""):r.void),r.forkIn(s,{startImmediately:!0}))});if(yield*t.extend({id:w.id,run:$()}))return{title:p.description,metadata:{...A,background:!0,jobId:w.id},output:ga({sessionID:w.id,state:"running",summary:"Background task updated",text:nk})};let ie=yield*t.start({id:w.id,type:Ps,title:p.description,metadata:A,onPromote:r.all([f.metadata({title:p.description,metadata:{...A,background:!0,jobId:w.id}}),z(w.id)]),run:$().pipe(r.onInterrupt(()=>C.cancel(w.id)))});function L(){return{title:p.description,metadata:{...A,background:!0,jobId:ie.id},output:ga({sessionID:w.id,state:"running",summary:"Background task started",text:tk})}}if(i(L,"backgroundResult"),g)return yield*z(ie.id),L();let V=yield*zt.make(),D=C.cancel(w.id);function M(){V.fork(D)}return i(M,"onAbort"),yield*r.acquireUseRelease(r.sync(()=>{f.abort.addEventListener("abort",M)}),()=>r.gen(function*(){let _=yield*r.raceFirst(t.wait({id:w.id}).pipe(r.map(N=>N.info)),t.waitForPromotion(w.id));return _?.metadata?.background===!0?L():_?.status==="error"?yield*r.fail(new Error(_.error??"Task failed")):_?.status==="cancelled"?yield*r.fail(new Error("Task cancelled")):{title:p.description,metadata:A,output:ga({sessionID:w.id,state:"completed",text:_?.output??""})}}),(_,N)=>r.gen(function*(){bt.hasInterrupts(N)&&(yield*r.all([D,t.cancel(w.id)],{discard:!0}))}).pipe(r.ensuring(r.sync(()=>{f.abort.removeEventListener("abort",M)}))))});return{description:a.experimentalBackgroundSubagents?[Ql,ek].join(`
1182
1182
 
1183
- `):Ql,parameters:ek,jsonSchema:a.experimentalBackgroundSubagents?void 0:Mo.fromSchema(ZI),execute:i((p,f)=>d(p,f).pipe(r.orDie),"execute")}}));var nh=`Create and maintain a structured task list for the current coding session. Tracks progress, organizes multi-step work, and surfaces status to the user.
1183
+ `):Ql,parameters:rk,jsonSchema:a.experimentalBackgroundSubagents?void 0:Mo.fromSchema(ok),execute:i((p,f)=>d(p,f).pipe(r.orDie),"execute")}}));var nh=`Create and maintain a structured task list for the current coding session. Tracks progress, organizes multi-step work, and surfaces status to the user.
1184
1184
 
1185
1185
  ## When to use
1186
1186
  Use proactively when:
@@ -1224,16 +1224,16 @@ Skip it:
1224
1224
  - "Run npm install and tell me what happened" -> one command
1225
1225
 
1226
1226
  When in doubt, use it.
1227
- `;var tk=c.Struct({todos:c.mutable(c.Array(Qn.Info)).annotate({description:"The updated todo list"})}),oh=Ge("todowrite",r.gen(function*(){let e=yield*Qn.Service;return{description:nh,parameters:tk,execute:i((t,n)=>r.gen(function*(){return yield*n.ask({permission:"todowrite",patterns:["*"],always:["*"],metadata:{}}),yield*e.update({sessionID:n.sessionID,todos:t.todos}),{title:`${t.todos.filter(o=>o.status!=="completed").length} todos`,output:JSON.stringify(t.todos,null,2),metadata:{todos:t.todos}}}),"execute")}}));var rh="Fetch a URL (http is upgraded to https) and return its content as markdown (default), text or html; very large pages may be summarized. Read-only. The result starts with a ready `Source:` line and its read time: a text that rests on the page ends with that line.\n";import{lookup as nk}from"node:dns/promises";import{isIP as sh}from"node:net";function ih(e){let[t,n]=e.split(".").map(o=>Number(o));return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}i(ih,"v4Blocked");function ok(e){let t=e.toLowerCase();if(t==="::"||t==="::1")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);return n?ih(n[1]):!!(/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||/^ff/.test(t))}i(ok,"v6Blocked");function rk(e){let t=sh(e);return t===4?ih(e):t===6?ok(e):!0}i(rk,"isNonPublicAddress");async function sk(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/g,"");if(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".local")||n.endsWith(".internal"))throw new Error(`webfetch reaches the public web only; ${t.host} is on this machine or its network`);let o=sh(n)?[n]:(await nk(n,{all:!0})).map(s=>s.address);if(o.length===0||o.some(rk))throw new Error(`webfetch reaches the public web only; ${t.host} resolves to an address on this machine or its network`)}i(sk,"assertPublicUrl");async function ed(e,t,n=5){let o=e;for(let s=0;s<=n;s++){await sk(o);let a=await fetch(o,{...t,redirect:"manual"}),l=a.headers.get("location");if(a.status>=300&&a.status<400&&l){o=new URL(l,o).toString();continue}return a}throw new Error(`webfetch stopped after ${n} redirects`)}i(ed,"fetchPublic");var ah=5*1024*1024,ik=30*1e3,ak=120*1e3,ck=c.Struct({url:c.String,format:c.Literals(["text","markdown","html"]).annotate({description:"Default markdown",default:"markdown"}).pipe(c.withDecodingDefault(r.succeed("markdown"))),timeout:c.optional(c.Number).annotate({description:"Seconds, max 120"})}),dh=Ge("webfetch",r.gen(function*(){return{description:rh,parameters:ck,execute:i((e,t)=>r.gen(function*(){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");yield*t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let n=Math.min((e.timeout??ik/1e3)*1e3,ak),o="*/*";switch(e.format){case"markdown":o="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case"text":o="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case"html":o="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:o="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"}let s={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:o,"Accept-Language":"en-US,en;q=0.9"},a=AbortSignal.any([AbortSignal.timeout(n),...t.abort?[t.abort]:[]]),l=yield*r.promise(async()=>{let k=await ed(e.url,{signal:a,headers:s});return k.status===403&&k.headers.get("cf-mitigated")==="challenge"?await ed(e.url,{signal:a,headers:{...s,"User-Agent":"opencode"}}):k});if(!l.ok)throw new Error(`Request failed with status code: ${l.status}`);let d=l.headers.get("content-length");if(d&&parseInt(d)>ah)throw new Error("Response too large (exceeds 5MB limit)");let p=yield*r.promise(()=>l.arrayBuffer());if(p.byteLength>ah)throw new Error("Response too large (exceeds 5MB limit)");let f=l.headers.get("content-type")||"",u=f.split(";")[0]?.trim().toLowerCase()||"",g=`${e.url} (${f})`;if(Vu(u)){let k=Buffer.from(p).toString("base64");return{title:g,output:"Image fetched successfully",metadata:{},attachments:[{type:"file",mime:u,url:`data:${u};base64,${k}`}]}}let y=new TextDecoder().decode(p),b=f.includes("text/html"),S=l.url||e.url,T=b?lk(y):u.includes("markdown")?(/^#\s+(.+)$/m.exec(y.slice(0,2e3))?.[1]??"").trim().slice(0,200):"",m={status:l.status,finalUrl:S,...T?{title:T}:{}},h=dk(T,S,l.status);switch(e.format){case"markdown":return{output:`${h}
1227
+ `;var sk=c.Struct({todos:c.mutable(c.Array(Qn.Info)).annotate({description:"The updated todo list"})}),oh=Ge("todowrite",r.gen(function*(){let e=yield*Qn.Service;return{description:nh,parameters:sk,execute:i((t,n)=>r.gen(function*(){return yield*n.ask({permission:"todowrite",patterns:["*"],always:["*"],metadata:{}}),yield*e.update({sessionID:n.sessionID,todos:t.todos}),{title:`${t.todos.filter(o=>o.status!=="completed").length} todos`,output:JSON.stringify(t.todos,null,2),metadata:{todos:t.todos}}}),"execute")}}));var rh="Fetch a URL (http is upgraded to https) and return its content as markdown (default), text or html; very large pages may be summarized. Read-only. The result starts with a ready `Source:` line and its read time: a text that rests on the page ends with that line.\n";import{lookup as ik}from"node:dns/promises";import{isIP as sh}from"node:net";function ih(e){let[t,n]=e.split(".").map(o=>Number(o));return t===0||t===10||t===127||t===100&&n>=64&&n<=127||t===169&&n===254||t===172&&n>=16&&n<=31||t===192&&n===168||t===198&&(n===18||n===19)||t>=224}i(ih,"v4Blocked");function ak(e){let t=e.toLowerCase();if(t==="::"||t==="::1")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);return n?ih(n[1]):!!(/^f[cd]/.test(t)||/^fe[89ab]/.test(t)||/^ff/.test(t))}i(ak,"v6Blocked");function ck(e){let t=sh(e);return t===4?ih(e):t===6?ak(e):!0}i(ck,"isNonPublicAddress");async function lk(e){let t=new URL(e),n=t.hostname.replace(/^\[|\]$/g,"");if(n==="localhost"||n.endsWith(".localhost")||n.endsWith(".local")||n.endsWith(".internal"))throw new Error(`webfetch reaches the public web only; ${t.host} is on this machine or its network`);let o=sh(n)?[n]:(await ik(n,{all:!0})).map(s=>s.address);if(o.length===0||o.some(ck))throw new Error(`webfetch reaches the public web only; ${t.host} resolves to an address on this machine or its network`)}i(lk,"assertPublicUrl");async function ed(e,t,n=5){let o=e;for(let s=0;s<=n;s++){await lk(o);let a=await fetch(o,{...t,redirect:"manual"}),l=a.headers.get("location");if(a.status>=300&&a.status<400&&l){o=new URL(l,o).toString();continue}return a}throw new Error(`webfetch stopped after ${n} redirects`)}i(ed,"fetchPublic");var ah=5*1024*1024,dk=30*1e3,uk=120*1e3,pk=c.Struct({url:c.String,format:c.Literals(["text","markdown","html"]).annotate({description:"Default markdown",default:"markdown"}).pipe(c.withDecodingDefault(r.succeed("markdown"))),timeout:c.optional(c.Number).annotate({description:"Seconds, max 120"})}),dh=Ge("webfetch",r.gen(function*(){return{description:rh,parameters:pk,execute:i((e,t)=>r.gen(function*(){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");yield*t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let n=Math.min((e.timeout??dk/1e3)*1e3,uk),o="*/*";switch(e.format){case"markdown":o="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case"text":o="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case"html":o="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:o="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8"}let s={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:o,"Accept-Language":"en-US,en;q=0.9"},a=AbortSignal.any([AbortSignal.timeout(n),...t.abort?[t.abort]:[]]),l=yield*r.promise(async()=>{let k=await ed(e.url,{signal:a,headers:s});return k.status===403&&k.headers.get("cf-mitigated")==="challenge"?await ed(e.url,{signal:a,headers:{...s,"User-Agent":"opencode"}}):k});if(!l.ok)throw new Error(`Request failed with status code: ${l.status}`);let d=l.headers.get("content-length");if(d&&parseInt(d)>ah)throw new Error("Response too large (exceeds 5MB limit)");let p=yield*r.promise(()=>l.arrayBuffer());if(p.byteLength>ah)throw new Error("Response too large (exceeds 5MB limit)");let f=l.headers.get("content-type")||"",u=f.split(";")[0]?.trim().toLowerCase()||"",g=`${e.url} (${f})`;if(Vu(u)){let k=Buffer.from(p).toString("base64");return{title:g,output:"Image fetched successfully",metadata:{},attachments:[{type:"file",mime:u,url:`data:${u};base64,${k}`}]}}let y=new TextDecoder().decode(p),b=f.includes("text/html"),S=l.url||e.url,T=b?fk(y):u.includes("markdown")?(/^#\s+(.+)$/m.exec(y.slice(0,2e3))?.[1]??"").trim().slice(0,200):"",m={status:l.status,finalUrl:S,...T?{title:T}:{}},h=mk(T,S,l.status);switch(e.format){case"markdown":return{output:`${h}
1228
1228
 
1229
- ${b?fk(y):y}`,title:g,metadata:m};case"text":return{output:`${h}
1229
+ ${b?yk(y):y}`,title:g,metadata:m};case"text":return{output:`${h}
1230
1230
 
1231
- ${b?uh(y):y}`,title:g,metadata:m};default:return{output:y,title:g,metadata:m}}}).pipe(r.orDie),"execute")}}));function lk(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(e);return t?uh(t[1]).replace(/\s+/g," ").trim().slice(0,200):""}i(lk,"titleOfHTML");function dk(e,t,n,o=new Date){return`Source: [${(e||t).replace(/[\[\]]/g,"")}](${t})
1232
- Read: ${o.toISOString().slice(0,16).replace("T"," ")} UTC, HTTP ${n}`}i(dk,"sourceHead");var uk=/<(script|style|noscript|iframe|object|embed|template|svg|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,pk=/<\/?(p|div|br|hr|li|ul|ol|tr|table|thead|tbody|h[1-6]|section|article|header|footer|nav|main|aside|pre|blockquote|dl|dt|dd|figure|figcaption|form|title)\b[^>]*>/gi,ch={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",copy:"\xA9",reg:"\xAE",trade:"\u2122",euro:"\u20AC",pound:"\xA3",laquo:"\xAB",raquo:"\xBB",middot:"\xB7",bull:"\u2022",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",times:"\xD7",deg:"\xB0",rarr:"\u2192",larr:"\u2190"};function lh(e,t){return Number.isInteger(e)&&e>0&&e<=1114111&&!(e>=55296&&e<=57343)?String.fromCodePoint(e):t}i(lh,"codePoint");function uh(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(uk," ").replace(/<t[dh]\b[^>]*>/gi," ").replace(pk,`
1231
+ ${b?uh(y):y}`,title:g,metadata:m};default:return{output:y,title:g,metadata:m}}}).pipe(r.orDie),"execute")}}));function fk(e){let t=/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(e);return t?uh(t[1]).replace(/\s+/g," ").trim().slice(0,200):""}i(fk,"titleOfHTML");function mk(e,t,n,o=new Date){return`Source: [${(e||t).replace(/[\[\]]/g,"")}](${t})
1232
+ Read: ${o.toISOString().slice(0,16).replace("T"," ")} UTC, HTTP ${n}`}i(mk,"sourceHead");var hk=/<(script|style|noscript|iframe|object|embed|template|svg|head)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,gk=/<\/?(p|div|br|hr|li|ul|ol|tr|table|thead|tbody|h[1-6]|section|article|header|footer|nav|main|aside|pre|blockquote|dl|dt|dd|figure|figcaption|form|title)\b[^>]*>/gi,ch={amp:"&",lt:"<",gt:">",quot:'"',apos:"'",nbsp:" ",ndash:"\u2013",mdash:"\u2014",hellip:"\u2026",copy:"\xA9",reg:"\xAE",trade:"\u2122",euro:"\u20AC",pound:"\xA3",laquo:"\xAB",raquo:"\xBB",middot:"\xB7",bull:"\u2022",lsquo:"\u2018",rsquo:"\u2019",ldquo:"\u201C",rdquo:"\u201D",times:"\xD7",deg:"\xB0",rarr:"\u2192",larr:"\u2190"};function lh(e,t){return Number.isInteger(e)&&e>0&&e<=1114111&&!(e>=55296&&e<=57343)?String.fromCodePoint(e):t}i(lh,"codePoint");function uh(e){return e.replace(/<!--[\s\S]*?-->/g,"").replace(hk," ").replace(/<t[dh]\b[^>]*>/gi," ").replace(gk,`
1233
1233
  `).replace(/<[^>]*>/g,"").replace(/&(?:#(\d+)|#x([0-9a-f]+)|([a-z][a-z0-9]*));/gi,(t,n,o,s)=>n?lh(Number(n),t):o?lh(parseInt(o,16),t):ch[s]??ch[s.toLowerCase()]??t).replace(/[ \t\f\v ]+/g," ").replace(/ ?\n ?/g,`
1234
1234
  `).replace(/\n{3,}/g,`
1235
1235
 
1236
- `).trim()}i(uh,"extractTextFromHTML");function fk(e){let t=new ju({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}i(fk,"convertHTMLToMarkdown");import*as Oo from"path";var ph=`Writes a file to the local filesystem.
1236
+ `).trim()}i(uh,"extractTextFromHTML");function yk(e){let t=new ju({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}i(yk,"convertHTMLToMarkdown");import*as Oo from"path";var ph=`Writes a file to the local filesystem.
1237
1237
 
1238
1238
  Usage:
1239
1239
  - This tool will overwrite the existing file if there is one at the provided path.
@@ -1241,22 +1241,22 @@ Usage:
1241
1241
  - ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
1242
1242
  - NEVER proactively create documentation files (*.md) or README files. Only create documentation files if explicitly requested by the User.
1243
1243
  - Only use emojis if the user explicitly requests it. Avoid writing emojis to files unless asked.
1244
- `;var mk=5,hk=c.Struct({content:c.String.annotate({description:"The content to write to the file"}),filePath:c.String.annotate({description:"The absolute path to the file to write (must be absolute, not relative)"})}),td=Ge("write",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*De.Service,o=yield*Jt.Service;return{description:ph,parameters:hk,execute:i((s,a)=>r.gen(function*(){let l=yield*G.context,d=Oo.isAbsolute(s.filePath)?s.filePath:Oo.join(l.directory,s.filePath);yield*$t(a,d);let p=yield*t.existsSafe(d),f=p?yield*io(t,d):{bom:!1,text:""},u=pn(s.content),g=f.bom||u.bom,y=f.text,b=u.text,S=Fn(Dn(d,d,y,b));yield*a.ask({permission:"edit",patterns:[Oo.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:S}}),yield*t.writeWithDirs(d,Kt(b,g)),(yield*o.file(d))&&(yield*Ao(t,d,g)),yield*n.publish(mo.Event.Edited,{file:d}),yield*n.publish(_n.Event.Updated,{file:d,event:p?"change":"add"});let T="Wrote file successfully.";yield*e.touchFile(d,"document");let m=yield*e.diagnostics(),h=Ae.normalizePath(d),k=0;for(let[w,I]of Object.entries(m)){let P=w===h;if(!P&&k>=mk)continue;let x=ft.Diagnostic.report(P?d:w,I);if(x){if(P){T+=`
1244
+ `;var bk=5,wk=c.Struct({content:c.String.annotate({description:"The content to write to the file"}),filePath:c.String.annotate({description:"The absolute path to the file to write (must be absolute, not relative)"})}),td=Ge("write",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*De.Service,o=yield*Jt.Service;return{description:ph,parameters:wk,execute:i((s,a)=>r.gen(function*(){let l=yield*G.context,d=Oo.isAbsolute(s.filePath)?s.filePath:Oo.join(l.directory,s.filePath);yield*$t(a,d);let p=yield*t.existsSafe(d),f=p?yield*io(t,d):{bom:!1,text:""},u=pn(s.content),g=f.bom||u.bom,y=f.text,b=u.text,S=Fn(Dn(d,d,y,b));yield*a.ask({permission:"edit",patterns:[Oo.relative(l.worktree,d)],always:["*"],metadata:{filepath:d,diff:S}}),yield*t.writeWithDirs(d,Kt(b,g)),(yield*o.file(d))&&(yield*Ao(t,d,g)),yield*n.publish(mo.Event.Edited,{file:d}),yield*n.publish(_n.Event.Updated,{file:d,event:p?"change":"add"});let T="Wrote file successfully.";yield*e.touchFile(d,"document");let m=yield*e.diagnostics(),h=Ae.normalizePath(d),k=0;for(let[w,I]of Object.entries(m)){let P=w===h;if(!P&&k>=bk)continue;let x=ft.Diagnostic.report(P?d:w,I);if(x){if(P){T+=`
1245
1245
 
1246
1246
  LSP errors detected in this file, please fix:
1247
1247
  ${x}`;continue}k++,T+=`
1248
1248
 
1249
1249
  LSP errors detected in other files:
1250
- ${x}`}}return{title:Oo.relative(l.worktree,d),metadata:{diagnostics:m,filepath:d,exists:p},output:T}}).pipe(r.orDie),"execute")}}));var gk=c.Struct({tool:c.String,error:c.String}),fh=Ge("invalid",r.succeed({description:"Do not use",parameters:gk,execute:i(e=>r.succeed({title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}),"execute")}));import hh from"path";var mh=`Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.
1250
+ ${x}`}}return{title:Oo.relative(l.worktree,d),metadata:{diagnostics:m,filepath:d,exists:p},output:T}}).pipe(r.orDie),"execute")}}));var vk=c.Struct({tool:c.String,error:c.String}),fh=Ge("invalid",r.succeed({description:"Do not use",parameters:vk,execute:i(e=>r.succeed({title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}),"execute")}));import hh from"path";var mh=`Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.
1251
1251
 
1252
1252
  Use this tool to inject the skill's instructions and resources into current conversation. The output may contain detailed workflow guidance as well as references to scripts, files, etc in the same directory as the skill.
1253
1253
 
1254
1254
  The skill name must match one of the skills listed in your system prompt.
1255
- `;var yk=c.Struct({name:c.String.annotate({description:"The name of the skill from available_skills"})}),gh=Ge("skill",r.gen(function*(){let e=yield*Xn.Service,t=yield*Hn.Service;return{description:mh,parameters:yk,execute:i((n,o)=>r.gen(function*(){let s=yield*e.require(n.name).pipe(r.catchTag("Skill.NotFoundError",p=>r.die(new Error(p.message))));yield*o.ask({permission:"skill",patterns:[n.name],always:[n.name],metadata:{}});let a=hh.dirname(s.location),l=a,d=yield*t.find({cwd:a,pattern:"!**/SKILL.md",hidden:!0,follow:!1,signal:o.abort,limit:10});return{title:`Loaded skill: ${s.name}`,output:[`<skill_content name="${s.name}">`,`# Skill: ${s.name}`,"",s.content.trim(),"",`Base directory for this skill: ${l}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","Note: file list is sampled.","","<skill_files>",d.map(p=>`<file>${hh.resolve(a,p.path)}</file>`).join(`
1255
+ `;var xk=c.Struct({name:c.String.annotate({description:"The name of the skill from available_skills"})}),gh=Ge("skill",r.gen(function*(){let e=yield*Xn.Service,t=yield*Hn.Service;return{description:mh,parameters:xk,execute:i((n,o)=>r.gen(function*(){let s=yield*e.require(n.name).pipe(r.catchTag("Skill.NotFoundError",p=>r.die(new Error(p.message))));yield*o.ask({permission:"skill",patterns:[n.name],always:[n.name],metadata:{}});let a=hh.dirname(s.location),l=a,d=yield*t.find({cwd:a,pattern:"!**/SKILL.md",hidden:!0,follow:!1,signal:o.abort,limit:10});return{title:`Loaded skill: ${s.name}`,output:[`<skill_content name="${s.name}">`,`# Skill: ${s.name}`,"",s.content.trim(),"",`Base directory for this skill: ${l}`,"Relative paths in this skill (e.g., scripts/, reference/) are relative to this base directory.","Note: file list is sampled.","","<skill_files>",d.map(p=>`<file>${hh.resolve(a,p.path)}</file>`).join(`
1256
1256
  `),"</skill_files>","</skill_content>"].join(`
1257
1257
  `),metadata:{name:s.name,dir:a}}}).pipe(r.orDie),"execute")}}));var yh=`Search the web and return summaries of the most relevant pages: current information beyond your knowledge cutoff. The current year is {{year}}: use it when searching for recent information. Summaries are not pages read: say which claims rest only on them.
1258
- `;var bh={exa:"websearch-exa",tavily:"websearch-tavily"},bk="https://mcp.exa.ai/mcp",wk="https://api.tavily.com/search",vh=8,vk=1e4,xk=25e3,xh=6e4,Sh=10*6e4,nd={"exa-key":"Exa",tavily:"Tavily",exa:"Exa, no key"},Lo=class extends Error{constructor(n){super("rate-limited");this.waitMs=n}waitMs;static{i(this,"RateLimited")}},Rs=class extends Error{constructor(n){super(`key refused (HTTP ${n})`);this.status=n}status;static{i(this,"KeyRefused")}},ya=new Map;function Ih(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,Sh):xh}i(Ih,"waitFrom");function Sk(e){let t=[],n=/^Title: (.*)\r?\nURL: (\S+)/gm;for(let o=n.exec(e);o;o=n.exec(e))t.push({title:o[1].trim(),url:o[2].trim()});return t}i(Sk,"hitsIn");async function wh(e,t,n){let o=await fetch(bk,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",...t?{"x-api-key":t}:{}},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||vh,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}}),signal:n});if(o.status===429)throw new Lo(Ih(o));if(t&&(o.status===401||o.status===403))throw new Rs(o.status);if(!o.ok)throw new Error(`Search error (${o.status}): ${await o.text()}`);for(let s of(await o.text()).split(`
1259
- `)){if(!s.startsWith("data: "))continue;let a=JSON.parse(s.substring(6));if(a.result?._meta?.["ai.exa/rateLimited"])throw new Lo(xh);if(a.result?.isError)throw new Error(`Search failed: ${a.result.content?.[0]?.text??"the search service reported an error"}`);let l=a.result?.content?.[0]?.text;if(l)return l}return""}i(wh,"searchExa");async function Ik(e,t,n){let o=await fetch(wk,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({query:e.query,max_results:Math.min(e.numResults||vh,20),search_depth:e.type==="fast"?"fast":"basic",include_published_date:!0}),signal:n});if(o.status===429)throw new Lo(Ih(o));if(o.status===432||o.status===433)throw new Lo(Sh);if(o.status===401||o.status===403)throw new Rs(o.status);if(!o.ok)throw new Error(`Search error (${o.status}): ${await o.text()}`);let s=await o.json(),a=e.contextMaxCharacters||vk,l=(s.results??[]).filter(p=>p.url),d=Math.max(200,Math.floor(a/Math.max(l.length,1)));return l.map(p=>`Title: ${(p.title??"").trim()||p.url}
1258
+ `;var bh={exa:"websearch-exa",tavily:"websearch-tavily"},Sk="https://mcp.exa.ai/mcp",Ik="https://api.tavily.com/search",vh=8,kk=1e4,Dk=25e3,xh=6e4,Sh=10*6e4,nd={"exa-key":"Exa",tavily:"Tavily",exa:"Exa, no key"},Lo=class extends Error{constructor(n){super("rate-limited");this.waitMs=n}waitMs;static{i(this,"RateLimited")}},Rs=class extends Error{constructor(n){super(`key refused (HTTP ${n})`);this.status=n}status;static{i(this,"KeyRefused")}},ya=new Map;function Ih(e){let t=Number(e.headers.get("retry-after"));return Number.isFinite(t)&&t>0?Math.min(t*1e3,Sh):xh}i(Ih,"waitFrom");function Ek(e){let t=[],n=/^Title: (.*)\r?\nURL: (\S+)/gm;for(let o=n.exec(e);o;o=n.exec(e))t.push({title:o[1].trim(),url:o[2].trim()});return t}i(Ek,"hitsIn");async function wh(e,t,n){let o=await fetch(Sk,{method:"POST",headers:{accept:"application/json, text/event-stream","content-type":"application/json",...t?{"x-api-key":t}:{}},body:JSON.stringify({jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||vh,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}}),signal:n});if(o.status===429)throw new Lo(Ih(o));if(t&&(o.status===401||o.status===403))throw new Rs(o.status);if(!o.ok)throw new Error(`Search error (${o.status}): ${await o.text()}`);for(let s of(await o.text()).split(`
1259
+ `)){if(!s.startsWith("data: "))continue;let a=JSON.parse(s.substring(6));if(a.result?._meta?.["ai.exa/rateLimited"])throw new Lo(xh);if(a.result?.isError)throw new Error(`Search failed: ${a.result.content?.[0]?.text??"the search service reported an error"}`);let l=a.result?.content?.[0]?.text;if(l)return l}return""}i(wh,"searchExa");async function Tk(e,t,n){let o=await fetch(Ik,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t}`},body:JSON.stringify({query:e.query,max_results:Math.min(e.numResults||vh,20),search_depth:e.type==="fast"?"fast":"basic",include_published_date:!0}),signal:n});if(o.status===429)throw new Lo(Ih(o));if(o.status===432||o.status===433)throw new Lo(Sh);if(o.status===401||o.status===403)throw new Rs(o.status);if(!o.ok)throw new Error(`Search error (${o.status}): ${await o.text()}`);let s=await o.json(),a=e.contextMaxCharacters||kk,l=(s.results??[]).filter(p=>p.url),d=Math.max(200,Math.floor(a/Math.max(l.length,1)));return l.map(p=>`Title: ${(p.title??"").trim()||p.url}
1260
1260
  URL: ${p.url}
1261
1261
  Published: ${p.published_date||"N/A"}
1262
1262
  Author: N/A
@@ -1265,11 +1265,11 @@ ${(p.content??"").trim().slice(0,d)}`).join(`
1265
1265
 
1266
1266
  ---
1267
1267
 
1268
- `)}i(Ik,"searchTavily");function kk(e){let t=Math.max(1,Math.ceil(e/1e3));return t<90?`about ${t} seconds`:`about ${Math.ceil(t/60)} minutes`}i(kk,"waitWords");async function Dk(e,t,n,o=Date.now){let s={exa:await n(bh.exa),tavily:await n(bh.tavily)},a=[...s.exa?[{backend:"exa-key",run:i(y=>wh(e,s.exa,y),"run")}]:[],...s.tavily?[{backend:"tavily",run:i(y=>Ik(e,s.tavily,y),"run")}]:[],{backend:"exa",run:i(y=>wh(e,void 0,y),"run")}],l=[s.exa,s.tavily].filter(y=>!!y),d=i(y=>l.reduce((b,S)=>b.split(S).join("[key]"),y),"clean"),p=[],f,u=0;for(let{backend:y,run:b}of a){if((ya.get(y)??0)>o()){u++;continue}let S=AbortSignal.any([AbortSignal.timeout(xk),t]);try{let T=await b(S);return ya.delete(y),{text:T,backend:y,refused:p}}catch(T){if(t.aborted)throw T;T instanceof Lo?(ya.set(y,o()+T.waitMs),u++):T instanceof Rs?p.push(`${nd[y]} (HTTP ${T.status})`):T instanceof Error&&(T.name==="AbortError"||T.name==="TimeoutError")?f=new Error(`Search request timed out (${nd[y]})`):f=new Error(d(T instanceof Error?T.message:String(T)))}}let g=p.length?` The search key in Settings was refused: ${p.join(", ")}.`:"";if(u>0&&!f){let y=Math.min(...a.map(b=>ya.get(b.backend)??1/0).filter(b=>b>o()))-o();throw new Error(`Search is rate-limited for the moment. Nothing was searched. Search again in ${kk(y)}, or open a page you already know.`+(l.length?"":" Free search allows a few searches a minute; a search key of the user's own (Settings, Providers) lifts the limit.")+g)}throw new Error(`${f?.message??"Search failed"}${g}`)}i(Dk,"runSearch");function Ek(e,t){let n=Sk(e.text),o=e.refused.length?`
1268
+ `)}i(Tk,"searchTavily");function Pk(e){let t=Math.max(1,Math.ceil(e/1e3));return t<90?`about ${t} seconds`:`about ${Math.ceil(t/60)} minutes`}i(Pk,"waitWords");async function Rk(e,t,n,o=Date.now){let s={exa:await n(bh.exa),tavily:await n(bh.tavily)},a=[...s.exa?[{backend:"exa-key",run:i(y=>wh(e,s.exa,y),"run")}]:[],...s.tavily?[{backend:"tavily",run:i(y=>Tk(e,s.tavily,y),"run")}]:[],{backend:"exa",run:i(y=>wh(e,void 0,y),"run")}],l=[s.exa,s.tavily].filter(y=>!!y),d=i(y=>l.reduce((b,S)=>b.split(S).join("[key]"),y),"clean"),p=[],f,u=0;for(let{backend:y,run:b}of a){if((ya.get(y)??0)>o()){u++;continue}let S=AbortSignal.any([AbortSignal.timeout(Dk),t]);try{let T=await b(S);return ya.delete(y),{text:T,backend:y,refused:p}}catch(T){if(t.aborted)throw T;T instanceof Lo?(ya.set(y,o()+T.waitMs),u++):T instanceof Rs?p.push(`${nd[y]} (HTTP ${T.status})`):T instanceof Error&&(T.name==="AbortError"||T.name==="TimeoutError")?f=new Error(`Search request timed out (${nd[y]})`):f=new Error(d(T instanceof Error?T.message:String(T)))}}let g=p.length?` The search key in Settings was refused: ${p.join(", ")}.`:"";if(u>0&&!f){let y=Math.min(...a.map(b=>ya.get(b.backend)??1/0).filter(b=>b>o()))-o();throw new Error(`Search is rate-limited for the moment. Nothing was searched. Search again in ${Pk(y)}, or open a page you already know.`+(l.length?"":" Free search allows a few searches a minute; a search key of the user's own (Settings, Providers) lifts the limit.")+g)}throw new Error(`${f?.message??"Search failed"}${g}`)}i(Rk,"runSearch");function Ck(e,t){let n=Ek(e.text),o=e.refused.length?`
1269
1269
 
1270
1270
  Note for the user: the search key in Settings was refused (${e.refused.join(", ")}); this search ran without it.`:"",s=`Search results (${nd[e.backend]}, ${new Date().toISOString().slice(0,16).replace("T"," ")} UTC). These are summaries; a page is read only when you open it.`;return{output:n.length||e.text?`${s}
1271
1271
 
1272
- ${e.text}${o}`:`No search results found. Please try a different query.${o}`,title:`Web search: ${t}`,metadata:{backend:e.backend,resultCount:n.length,hits:n.slice(0,8)}}}i(Ek,"searchResult");var Tk=c.Struct({query:c.String.annotate({description:"Websearch query"}),numResults:c.optional(c.Number).annotate({description:"Default 8"}),livecrawl:c.optional(c.Literals(["fallback","preferred"])).annotate({description:"Live crawling as a fallback for uncached pages (default) or preferred"}),type:c.optional(c.Literals(["auto","fast","deep"])).annotate({description:"Default auto"}),contextMaxCharacters:c.optional(c.Number).annotate({description:"Default 10000"})});var od=Ge("websearch",r.gen(function*(){let e=yield*Xt.Service,t=i(n=>r.runPromise(e.get(n).pipe(r.map(o=>o?.type==="api"&&o.key.trim()?o.key.trim():void 0),r.orElseSucceed(()=>{}))),"keyOf");return{get description(){return yh.replace("{{year}}",new Date().getFullYear().toString())},parameters:Tk,execute:i((n,o)=>r.gen(function*(){yield*o.ask({permission:"websearch",patterns:[n.query],always:["*"],metadata:{query:n.query,numResults:n.numResults,livecrawl:n.livecrawl,type:n.type,contextMaxCharacters:n.contextMaxCharacters}});let s=yield*r.promise(()=>Dk(n,o.abort,t));return Ek(s,n.query)}).pipe(r.orDie),"execute")}}));import rd from"path";var kh=`Interact with Language Server Protocol (LSP) servers to get code intelligence features.
1272
+ ${e.text}${o}`:`No search results found. Please try a different query.${o}`,title:`Web search: ${t}`,metadata:{backend:e.backend,resultCount:n.length,hits:n.slice(0,8)}}}i(Ck,"searchResult");var Ak=c.Struct({query:c.String.annotate({description:"Websearch query"}),numResults:c.optional(c.Number).annotate({description:"Default 8"}),livecrawl:c.optional(c.Literals(["fallback","preferred"])).annotate({description:"Live crawling as a fallback for uncached pages (default) or preferred"}),type:c.optional(c.Literals(["auto","fast","deep"])).annotate({description:"Default auto"}),contextMaxCharacters:c.optional(c.Number).annotate({description:"Default 10000"})});var od=Ge("websearch",r.gen(function*(){let e=yield*Xt.Service,t=i(n=>r.runPromise(e.get(n).pipe(r.map(o=>o?.type==="api"&&o.key.trim()?o.key.trim():void 0),r.orElseSucceed(()=>{}))),"keyOf");return{get description(){return yh.replace("{{year}}",new Date().getFullYear().toString())},parameters:Ak,execute:i((n,o)=>r.gen(function*(){yield*o.ask({permission:"websearch",patterns:[n.query],always:["*"],metadata:{query:n.query,numResults:n.numResults,livecrawl:n.livecrawl,type:n.type,contextMaxCharacters:n.contextMaxCharacters}});let s=yield*r.promise(()=>Rk(n,o.abort,t));return Ck(s,n.query)}).pipe(r.orDie),"execute")}}));import rd from"path";var kh=`Interact with Language Server Protocol (LSP) servers to get code intelligence features.
1273
1273
 
1274
1274
  Supported operations:
1275
1275
  - goToDefinition: Find where a symbol is defined
@@ -1293,20 +1293,20 @@ workspaceSymbol also accepts:
1293
1293
  For workspaceSymbol, filePath is not sent in the LSP workspace/symbol request. It is used by opencode to select and start the matching LSP server.
1294
1294
 
1295
1295
  Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.
1296
- `;import{pathToFileURL as Pk}from"url";var Rk=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],Ck=c.Struct({operation:c.Literals(Rk).annotate({description:"The LSP operation to perform"}),filePath:c.String.annotate({description:"The absolute or relative path to the file"}),line:c.Int.check(c.isGreaterThanOrEqualTo(1)).annotate({description:"The line number (1-based, as shown in editors)"}),character:c.Int.check(c.isGreaterThanOrEqualTo(1)).annotate({description:"The character offset (1-based, as shown in editors)"}),query:c.optional(c.String).annotate({description:"Search query for workspaceSymbol. Empty string requests all symbols."})}),Dh=Ge("lsp",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service;return{description:kh,parameters:Ck,execute:i((n,o)=>r.gen(function*(){let s=yield*G.context,a=rd.isAbsolute(n.filePath)?n.filePath:rd.join(s.directory,n.filePath);yield*$t(o,a);let l=n.operation==="workspaceSymbol"?{operation:n.operation}:n.operation==="documentSymbol"?{operation:n.operation,filePath:a}:{operation:n.operation,filePath:a,line:n.line,character:n.character};yield*o.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:l});let d=Pk(a).href,p={file:a,line:n.line-1,character:n.character-1},f=rd.relative(s.worktree,a),u=n.operation==="workspaceSymbol"?"":n.operation==="documentSymbol"?f:`${f}:${n.line}:${n.character}`,g=u?`${n.operation} ${u}`:n.operation;if(!(yield*t.existsSafe(a)))throw new Error(`File not found: ${a}`);if(!(yield*e.hasClients(a)))throw new Error("No LSP server available for this file type.");yield*e.touchFile(a,"document");let S=yield*(()=>{switch(n.operation){case"goToDefinition":return e.definition(p);case"findReferences":return e.references(p);case"hover":return e.hover(p);case"documentSymbol":return e.documentSymbol(d);case"workspaceSymbol":return e.workspaceSymbol(n.query??"");case"goToImplementation":return e.implementation(p);case"prepareCallHierarchy":return e.prepareCallHierarchy(p);case"incomingCalls":return e.incomingCalls(p);case"outgoingCalls":return e.outgoingCalls(p)}})();return{title:g,metadata:{result:S},output:S.length===0?`No results found for ${n.operation}`:JSON.stringify(S,null,2)}}).pipe(r.orDie),"execute")}}));import*as Tn from"path";var Nr={};fe(Nr,{ApplyPatchError:()=>Th,MaybeApplyPatch:()=>Ph,MaybeApplyPatchVerified:()=>Rh,Patch:()=>Nr,PatchSchema:()=>Ak,applyHunksToFiles:()=>Ah,applyPatch:()=>Fk,deriveNewContentsFromChunks:()=>id,maybeParseApplyPatch:()=>Ch,maybeParseApplyPatchVerified:()=>Bk,parsePatch:()=>Cs});import*as Lr from"path";var Ak=c.Struct({patchText:c.String.annotate({description:"The full patch text that describes all changes to be made"})}),Th=(s=>(s.ParseError="ParseError",s.IoError="IoError",s.ComputeReplacements="ComputeReplacements",s.ImplicitInvocation="ImplicitInvocation",s))(Th||{}),Ph=(s=>(s.Body="Body",s.ShellParseError="ShellParseError",s.PatchParseError="PatchParseError",s.NotApplyPatch="NotApplyPatch",s))(Ph||{}),Rh=(s=>(s.Body="Body",s.ShellParseError="ShellParseError",s.CorrectnessError="CorrectnessError",s.NotApplyPatch="NotApplyPatch",s))(Rh||{});function Mk(e,t){let n=e[t];if(n.startsWith("*** Add File:")){let o=n.slice(13).trim();return o?{filePath:o,nextIdx:t+1}:null}if(n.startsWith("*** Delete File:")){let o=n.slice(16).trim();return o?{filePath:o,nextIdx:t+1}:null}if(n.startsWith("*** Update File:")){let o=n.slice(16).trim(),s,a=t+1;return a<e.length&&e[a].startsWith("*** Move to:")&&(s=e[a].slice(12).trim(),a++),o?{filePath:o,movePath:s,nextIdx:a}:null}return null}i(Mk,"parsePatchHeader");function _k(e,t){let n=[],o=t;for(;o<e.length&&!e[o].startsWith("***");)if(e[o].startsWith("@@")){let s=e[o].substring(2).trim();o++;let a=[],l=[],d=!1;for(;o<e.length&&!e[o].startsWith("@@")&&!e[o].startsWith("***");){let p=e[o];if(p==="*** End of File"){d=!0,o++;break}if(p.startsWith(" ")){let f=p.substring(1);a.push(f),l.push(f)}else p.startsWith("-")?a.push(p.substring(1)):p.startsWith("+")&&l.push(p.substring(1));o++}n.push({old_lines:a,new_lines:l,change_context:s||void 0,is_end_of_file:d||void 0})}else o++;return{chunks:n,nextIdx:o}}i(_k,"parseUpdateFileChunks");function Ok(e,t){let n="",o=t;for(;o<e.length&&!e[o].startsWith("***");)e[o].startsWith("+")&&(n+=e[o].substring(1)+`
1296
+ `;import{pathToFileURL as Mk}from"url";var _k=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],Ok=c.Struct({operation:c.Literals(_k).annotate({description:"The LSP operation to perform"}),filePath:c.String.annotate({description:"The absolute or relative path to the file"}),line:c.Int.check(c.isGreaterThanOrEqualTo(1)).annotate({description:"The line number (1-based, as shown in editors)"}),character:c.Int.check(c.isGreaterThanOrEqualTo(1)).annotate({description:"The character offset (1-based, as shown in editors)"}),query:c.optional(c.String).annotate({description:"Search query for workspaceSymbol. Empty string requests all symbols."})}),Dh=Ge("lsp",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service;return{description:kh,parameters:Ok,execute:i((n,o)=>r.gen(function*(){let s=yield*G.context,a=rd.isAbsolute(n.filePath)?n.filePath:rd.join(s.directory,n.filePath);yield*$t(o,a);let l=n.operation==="workspaceSymbol"?{operation:n.operation}:n.operation==="documentSymbol"?{operation:n.operation,filePath:a}:{operation:n.operation,filePath:a,line:n.line,character:n.character};yield*o.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:l});let d=Mk(a).href,p={file:a,line:n.line-1,character:n.character-1},f=rd.relative(s.worktree,a),u=n.operation==="workspaceSymbol"?"":n.operation==="documentSymbol"?f:`${f}:${n.line}:${n.character}`,g=u?`${n.operation} ${u}`:n.operation;if(!(yield*t.existsSafe(a)))throw new Error(`File not found: ${a}`);if(!(yield*e.hasClients(a)))throw new Error("No LSP server available for this file type.");yield*e.touchFile(a,"document");let S=yield*(()=>{switch(n.operation){case"goToDefinition":return e.definition(p);case"findReferences":return e.references(p);case"hover":return e.hover(p);case"documentSymbol":return e.documentSymbol(d);case"workspaceSymbol":return e.workspaceSymbol(n.query??"");case"goToImplementation":return e.implementation(p);case"prepareCallHierarchy":return e.prepareCallHierarchy(p);case"incomingCalls":return e.incomingCalls(p);case"outgoingCalls":return e.outgoingCalls(p)}})();return{title:g,metadata:{result:S},output:S.length===0?`No results found for ${n.operation}`:JSON.stringify(S,null,2)}}).pipe(r.orDie),"execute")}}));import*as Tn from"path";var Nr={};fe(Nr,{ApplyPatchError:()=>Th,MaybeApplyPatch:()=>Ph,MaybeApplyPatchVerified:()=>Rh,Patch:()=>Nr,PatchSchema:()=>Lk,applyHunksToFiles:()=>Ah,applyPatch:()=>Wk,deriveNewContentsFromChunks:()=>id,maybeParseApplyPatch:()=>Ch,maybeParseApplyPatchVerified:()=>Vk,parsePatch:()=>Cs});import*as Lr from"path";var Lk=c.Struct({patchText:c.String.annotate({description:"The full patch text that describes all changes to be made"})}),Th=(s=>(s.ParseError="ParseError",s.IoError="IoError",s.ComputeReplacements="ComputeReplacements",s.ImplicitInvocation="ImplicitInvocation",s))(Th||{}),Ph=(s=>(s.Body="Body",s.ShellParseError="ShellParseError",s.PatchParseError="PatchParseError",s.NotApplyPatch="NotApplyPatch",s))(Ph||{}),Rh=(s=>(s.Body="Body",s.ShellParseError="ShellParseError",s.CorrectnessError="CorrectnessError",s.NotApplyPatch="NotApplyPatch",s))(Rh||{});function Nk(e,t){let n=e[t];if(n.startsWith("*** Add File:")){let o=n.slice(13).trim();return o?{filePath:o,nextIdx:t+1}:null}if(n.startsWith("*** Delete File:")){let o=n.slice(16).trim();return o?{filePath:o,nextIdx:t+1}:null}if(n.startsWith("*** Update File:")){let o=n.slice(16).trim(),s,a=t+1;return a<e.length&&e[a].startsWith("*** Move to:")&&(s=e[a].slice(12).trim(),a++),o?{filePath:o,movePath:s,nextIdx:a}:null}return null}i(Nk,"parsePatchHeader");function jk(e,t){let n=[],o=t;for(;o<e.length&&!e[o].startsWith("***");)if(e[o].startsWith("@@")){let s=e[o].substring(2).trim();o++;let a=[],l=[],d=!1;for(;o<e.length&&!e[o].startsWith("@@")&&!e[o].startsWith("***");){let p=e[o];if(p==="*** End of File"){d=!0,o++;break}if(p.startsWith(" ")){let f=p.substring(1);a.push(f),l.push(f)}else p.startsWith("-")?a.push(p.substring(1)):p.startsWith("+")&&l.push(p.substring(1));o++}n.push({old_lines:a,new_lines:l,change_context:s||void 0,is_end_of_file:d||void 0})}else o++;return{chunks:n,nextIdx:o}}i(jk,"parseUpdateFileChunks");function Uk(e,t){let n="",o=t;for(;o<e.length&&!e[o].startsWith("***");)e[o].startsWith("+")&&(n+=e[o].substring(1)+`
1297
1297
  `),o++;return n.endsWith(`
1298
- `)&&(n=n.slice(0,-1)),{content:n,nextIdx:o}}i(Ok,"parseAddFileContent");function Lk(e){let t=e.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return t?t[2]:e}i(Lk,"stripHeredoc");function Cs(e){let n=Lk(e.trim()).split(`
1299
- `),o=[],s=0,a="*** Begin Patch",l="*** End Patch",d=n.findIndex(f=>f.trim()===a),p=n.findIndex(f=>f.trim()===l);if(d===-1||p===-1||d>=p)throw new Error("Invalid patch format: missing Begin/End markers");for(s=d+1;s<p;){let f=Mk(n,s);if(!f){s++;continue}if(n[s].startsWith("*** Add File:")){let{content:u,nextIdx:g}=Ok(n,f.nextIdx);o.push({type:"add",path:f.filePath,contents:u}),s=g}else if(n[s].startsWith("*** Delete File:"))o.push({type:"delete",path:f.filePath}),s=f.nextIdx;else if(n[s].startsWith("*** Update File:")){let{chunks:u,nextIdx:g}=_k(n,f.nextIdx);o.push({type:"update",path:f.filePath,move_path:f.movePath,chunks:u}),s=g}else s++}return{hunks:o}}i(Cs,"parsePatch");function Ch(e){let t=["apply_patch","applypatch"];if(e.length===2&&t.includes(e[0]))try{let{hunks:n}=Cs(e[1]);return{type:"Body",args:{patch:e[1],hunks:n}}}catch(n){return{type:"PatchParseError",error:n}}if(e.length===3&&e[0]==="bash"&&e[1]==="-lc"){let o=e[2].match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(o){let s=o[2];try{let{hunks:a}=Cs(s);return{type:"Body",args:{patch:s,hunks:a}}}catch(a){return{type:"PatchParseError",error:a}}}}return{type:"NotApplyPatch"}}i(Ch,"maybeParseApplyPatch");function id(e,t,n){let o=pn(n),s=o.text.split(`
1300
- `);s.length>0&&s[s.length-1]===""&&s.pop();let a=Nk(s,e,t),l=jk(s,a);(l.length===0||l[l.length-1]!=="")&&l.push("");let d=pn(l.join(`
1301
- `)),p=d.text;return{unified_diff:Uk(o.text,p),content:p,bom:o.bom||d.bom}}i(id,"deriveNewContentsFromChunks");function Nk(e,t,n){let o=[],s=0;for(let a of n){if(a.change_context){let f=sd(e,[a.change_context],s);if(f===-1)throw new Error(`Failed to find context '${a.change_context}' in ${t}`);s=f+1}if(a.old_lines.length===0){let f=e.length>0&&e[e.length-1]===""?e.length-1:e.length;o.push([f,0,a.new_lines]);continue}let l=a.old_lines,d=a.new_lines,p=sd(e,l,s,a.is_end_of_file);if(p===-1&&l.length>0&&l[l.length-1]===""&&(l=l.slice(0,-1),d.length>0&&d[d.length-1]===""&&(d=d.slice(0,-1)),p=sd(e,l,s,a.is_end_of_file)),p!==-1)o.push([p,l.length,d]),s=p+l.length;else throw new Error(`Failed to find expected lines in ${t}:
1298
+ `)&&(n=n.slice(0,-1)),{content:n,nextIdx:o}}i(Uk,"parseAddFileContent");function Fk(e){let t=e.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return t?t[2]:e}i(Fk,"stripHeredoc");function Cs(e){let n=Fk(e.trim()).split(`
1299
+ `),o=[],s=0,a="*** Begin Patch",l="*** End Patch",d=n.findIndex(f=>f.trim()===a),p=n.findIndex(f=>f.trim()===l);if(d===-1||p===-1||d>=p)throw new Error("Invalid patch format: missing Begin/End markers");for(s=d+1;s<p;){let f=Nk(n,s);if(!f){s++;continue}if(n[s].startsWith("*** Add File:")){let{content:u,nextIdx:g}=Uk(n,f.nextIdx);o.push({type:"add",path:f.filePath,contents:u}),s=g}else if(n[s].startsWith("*** Delete File:"))o.push({type:"delete",path:f.filePath}),s=f.nextIdx;else if(n[s].startsWith("*** Update File:")){let{chunks:u,nextIdx:g}=jk(n,f.nextIdx);o.push({type:"update",path:f.filePath,move_path:f.movePath,chunks:u}),s=g}else s++}return{hunks:o}}i(Cs,"parsePatch");function Ch(e){let t=["apply_patch","applypatch"];if(e.length===2&&t.includes(e[0]))try{let{hunks:n}=Cs(e[1]);return{type:"Body",args:{patch:e[1],hunks:n}}}catch(n){return{type:"PatchParseError",error:n}}if(e.length===3&&e[0]==="bash"&&e[1]==="-lc"){let o=e[2].match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(o){let s=o[2];try{let{hunks:a}=Cs(s);return{type:"Body",args:{patch:s,hunks:a}}}catch(a){return{type:"PatchParseError",error:a}}}}return{type:"NotApplyPatch"}}i(Ch,"maybeParseApplyPatch");function id(e,t,n){let o=pn(n),s=o.text.split(`
1300
+ `);s.length>0&&s[s.length-1]===""&&s.pop();let a=Bk(s,e,t),l=$k(s,a);(l.length===0||l[l.length-1]!=="")&&l.push("");let d=pn(l.join(`
1301
+ `)),p=d.text;return{unified_diff:qk(o.text,p),content:p,bom:o.bom||d.bom}}i(id,"deriveNewContentsFromChunks");function Bk(e,t,n){let o=[],s=0;for(let a of n){if(a.change_context){let f=sd(e,[a.change_context],s);if(f===-1)throw new Error(`Failed to find context '${a.change_context}' in ${t}`);s=f+1}if(a.old_lines.length===0){let f=e.length>0&&e[e.length-1]===""?e.length-1:e.length;o.push([f,0,a.new_lines]);continue}let l=a.old_lines,d=a.new_lines,p=sd(e,l,s,a.is_end_of_file);if(p===-1&&l.length>0&&l[l.length-1]===""&&(l=l.slice(0,-1),d.length>0&&d[d.length-1]===""&&(d=d.slice(0,-1)),p=sd(e,l,s,a.is_end_of_file)),p!==-1)o.push([p,l.length,d]),s=p+l.length;else throw new Error(`Failed to find expected lines in ${t}:
1302
1302
  ${a.old_lines.join(`
1303
- `)}`)}return o.sort((a,l)=>a[0]-l[0]),o}i(Nk,"computeReplacements");function jk(e,t){let n=[...e];for(let o=t.length-1;o>=0;o--){let[s,a,l]=t[o];n.splice(s,a);for(let d=0;d<l.length;d++)n.splice(s+d,0,l[d])}return n}i(jk,"applyReplacements");function Eh(e){return e.replace(/[‘’‚‛]/g,"'").replace(/[“”„‟]/g,'"').replace(/[‐‑‒–—―]/g,"-").replace(/…/g,"...").replace(/ /g," ")}i(Eh,"normalizeUnicode");function ba(e,t,n,o,s){if(s){let a=e.length-t.length;if(a>=n){let l=!0;for(let d=0;d<t.length;d++)if(!o(e[a+d],t[d])){l=!1;break}if(l)return a}}for(let a=n;a<=e.length-t.length;a++){let l=!0;for(let d=0;d<t.length;d++)if(!o(e[a+d],t[d])){l=!1;break}if(l)return a}return-1}i(ba,"tryMatch");function sd(e,t,n,o=!1){if(t.length===0)return-1;let s=ba(e,t,n,(p,f)=>p===f,o);if(s!==-1)return s;let a=ba(e,t,n,(p,f)=>p.trimEnd()===f.trimEnd(),o);if(a!==-1)return a;let l=ba(e,t,n,(p,f)=>p.trim()===f.trim(),o);return l!==-1?l:ba(e,t,n,(p,f)=>Eh(p.trim())===Eh(f.trim()),o)}i(sd,"seekSequence");function Uk(e,t){let n=e.split(`
1303
+ `)}`)}return o.sort((a,l)=>a[0]-l[0]),o}i(Bk,"computeReplacements");function $k(e,t){let n=[...e];for(let o=t.length-1;o>=0;o--){let[s,a,l]=t[o];n.splice(s,a);for(let d=0;d<l.length;d++)n.splice(s+d,0,l[d])}return n}i($k,"applyReplacements");function Eh(e){return e.replace(/[‘’‚‛]/g,"'").replace(/[“”„‟]/g,'"').replace(/[‐‑‒–—―]/g,"-").replace(/…/g,"...").replace(/ /g," ")}i(Eh,"normalizeUnicode");function ba(e,t,n,o,s){if(s){let a=e.length-t.length;if(a>=n){let l=!0;for(let d=0;d<t.length;d++)if(!o(e[a+d],t[d])){l=!1;break}if(l)return a}}for(let a=n;a<=e.length-t.length;a++){let l=!0;for(let d=0;d<t.length;d++)if(!o(e[a+d],t[d])){l=!1;break}if(l)return a}return-1}i(ba,"tryMatch");function sd(e,t,n,o=!1){if(t.length===0)return-1;let s=ba(e,t,n,(p,f)=>p===f,o);if(s!==-1)return s;let a=ba(e,t,n,(p,f)=>p.trimEnd()===f.trimEnd(),o);if(a!==-1)return a;let l=ba(e,t,n,(p,f)=>p.trim()===f.trim(),o);return l!==-1?l:ba(e,t,n,(p,f)=>Eh(p.trim())===Eh(f.trim()),o)}i(sd,"seekSequence");function qk(e,t){let n=e.split(`
1304
1304
  `),o=t.split(`
1305
1305
  `),s=`@@ -1 +1 @@
1306
1306
  `,a=Math.max(n.length,o.length),l=!1;for(let d=0;d<a;d++){let p=n[d]||"",f=o[d]||"";p!==f?(p&&(s+=`-${p}
1307
1307
  `),f&&(s+=`+${f}
1308
1308
  `),l=!0):p&&(s+=` ${p}
1309
- `)}return l?s:""}i(Uk,"generateUnifiedDiff");var Ah=r.fn("Patch.applyHunksToFiles")(function*(e){if(e.length===0)return yield*r.fail(new Error("No files were modified."));let t=yield*Ae.Service,n=[],o=[],s=[];for(let a of e)switch(a.type){case"add":{yield*t.writeWithDirs(a.path,a.contents),n.push(a.path),yield*r.logInfo(`Added file: ${a.path}`);break}case"delete":{yield*t.remove(a.path),s.push(a.path),yield*r.logInfo(`Deleted file: ${a.path}`);break}case"update":{let l=yield*t.readFileString(a.path),d=id(a.path,a.chunks,l);a.move_path?(yield*t.writeWithDirs(a.move_path,Kt(d.content,d.bom)),yield*t.remove(a.path),o.push(a.move_path),yield*r.logInfo(`Moved file: ${a.path} -> ${a.move_path}`)):(yield*t.writeWithDirs(a.path,Kt(d.content,d.bom)),o.push(a.path),yield*r.logInfo(`Updated file: ${a.path}`));break}}return{added:n,modified:o,deleted:s}}),Fk=r.fn("Patch.applyPatch")(function*(e){let{hunks:t}=Cs(e);return yield*Ah(t)}),Bk=r.fn("Patch.maybeParseApplyPatchVerified")(function*(e,t){if(e.length===1)try{return Cs(e[0]),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}let n=Ch(e);switch(n.type){case"Body":{let o=yield*Ae.Service,s=n.args,a=s.workdir?Lr.resolve(t,s.workdir):t,l=new Map;for(let d of s.hunks){let p=Lr.resolve(a,d.type==="update"&&d.move_path?d.move_path:d.path);switch(d.type){case"add":l.set(p,{type:"add",content:d.contents});break;case"delete":{let f=Lr.resolve(a,d.path),u=yield*o.readFileString(f).pipe(r.catch(()=>r.succeed(void 0)));if(u===void 0)return{type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${f}`)};l.set(p,{type:"delete",content:u});break}case"update":{let f=Lr.resolve(a,d.path),u=yield*o.readFileString(f).pipe(r.catch(g=>r.succeed(new Error(`Failed to read file ${f}: ${g}`,{cause:g}))));if(u instanceof Error)return{type:"CorrectnessError",error:u};try{let g=id(f,d.chunks,u);l.set(p,{type:"update",unified_diff:g.unified_diff,move_path:d.move_path?Lr.resolve(a,d.move_path):void 0,new_content:g.content})}catch(g){return{type:"CorrectnessError",error:g}}break}}}return{type:"Body",action:{changes:l,patch:s.patch,cwd:a}}}case"PatchParseError":return{type:"CorrectnessError",error:n.error};case"NotApplyPatch":return{type:"NotApplyPatch"}}});var Mh=`Use the \`apply_patch\` tool to edit files. Your patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:
1309
+ `)}return l?s:""}i(qk,"generateUnifiedDiff");var Ah=r.fn("Patch.applyHunksToFiles")(function*(e){if(e.length===0)return yield*r.fail(new Error("No files were modified."));let t=yield*Ae.Service,n=[],o=[],s=[];for(let a of e)switch(a.type){case"add":{yield*t.writeWithDirs(a.path,a.contents),n.push(a.path),yield*r.logInfo(`Added file: ${a.path}`);break}case"delete":{yield*t.remove(a.path),s.push(a.path),yield*r.logInfo(`Deleted file: ${a.path}`);break}case"update":{let l=yield*t.readFileString(a.path),d=id(a.path,a.chunks,l);a.move_path?(yield*t.writeWithDirs(a.move_path,Kt(d.content,d.bom)),yield*t.remove(a.path),o.push(a.move_path),yield*r.logInfo(`Moved file: ${a.path} -> ${a.move_path}`)):(yield*t.writeWithDirs(a.path,Kt(d.content,d.bom)),o.push(a.path),yield*r.logInfo(`Updated file: ${a.path}`));break}}return{added:n,modified:o,deleted:s}}),Wk=r.fn("Patch.applyPatch")(function*(e){let{hunks:t}=Cs(e);return yield*Ah(t)}),Vk=r.fn("Patch.maybeParseApplyPatchVerified")(function*(e,t){if(e.length===1)try{return Cs(e[0]),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}let n=Ch(e);switch(n.type){case"Body":{let o=yield*Ae.Service,s=n.args,a=s.workdir?Lr.resolve(t,s.workdir):t,l=new Map;for(let d of s.hunks){let p=Lr.resolve(a,d.type==="update"&&d.move_path?d.move_path:d.path);switch(d.type){case"add":l.set(p,{type:"add",content:d.contents});break;case"delete":{let f=Lr.resolve(a,d.path),u=yield*o.readFileString(f).pipe(r.catch(()=>r.succeed(void 0)));if(u===void 0)return{type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${f}`)};l.set(p,{type:"delete",content:u});break}case"update":{let f=Lr.resolve(a,d.path),u=yield*o.readFileString(f).pipe(r.catch(g=>r.succeed(new Error(`Failed to read file ${f}: ${g}`,{cause:g}))));if(u instanceof Error)return{type:"CorrectnessError",error:u};try{let g=id(f,d.chunks,u);l.set(p,{type:"update",unified_diff:g.unified_diff,move_path:d.move_path?Lr.resolve(a,d.move_path):void 0,new_content:g.content})}catch(g){return{type:"CorrectnessError",error:g}}break}}}return{type:"Body",action:{changes:l,patch:s.patch,cwd:a}}}case"PatchParseError":return{type:"CorrectnessError",error:n.error};case"NotApplyPatch":return{type:"NotApplyPatch"}}});var Mh=`Use the \`apply_patch\` tool to edit files. Your patch language is a stripped\u2011down, file\u2011oriented diff format designed to be easy to parse and safe to apply. You can think of it as a high\u2011level envelope:
1310
1310
 
1311
1311
  *** Begin Patch
1312
1312
  [ one or more file sections ]
@@ -1339,7 +1339,7 @@ It is important to remember:
1339
1339
 
1340
1340
  - You must include a header with your intended action (Add/Delete/Update)
1341
1341
  - You must prefix new lines with \`+\` even when creating a new file
1342
- `;var $k=c.Struct({patchText:c.String.annotate({description:"The full patch text that describes all changes to be made"})}),ad=Ge("apply_patch",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*Jt.Service,o=yield*De.Service,s=r.fn("ApplyPatchTool.execute")(function*(a,l){if(!a.patchText)return yield*r.fail(new Error("patchText is required"));let d;try{d=Nr.parsePatch(a.patchText).hunks}catch(h){return yield*r.fail(new Error(`apply_patch verification failed: ${h}`))}if(d.length===0)return a.patchText.replace(/\r\n/g,`
1342
+ `;var zk=c.Struct({patchText:c.String.annotate({description:"The full patch text that describes all changes to be made"})}),ad=Ge("apply_patch",r.gen(function*(){let e=yield*ft.Service,t=yield*Ae.Service,n=yield*Jt.Service,o=yield*De.Service,s=r.fn("ApplyPatchTool.execute")(function*(a,l){if(!a.patchText)return yield*r.fail(new Error("patchText is required"));let d;try{d=Nr.parsePatch(a.patchText).hunks}catch(h){return yield*r.fail(new Error(`apply_patch verification failed: ${h}`))}if(d.length===0)return a.patchText.replace(/\r\n/g,`
1343
1343
  `).replace(/\r/g,`
1344
1344
  `).trim()===`*** Begin Patch
1345
1345
  *** End Patch`?yield*r.fail(new Error("patch rejected: empty patch")):yield*r.fail(new Error("apply_patch verification failed: no hunks found"));let p=yield*G.context,f=[],u="";for(let h of d){let k=Tn.resolve(p.directory,h.path);switch(yield*$t(l,k),h.type){case"add":{let I=h.contents.length===0||h.contents.endsWith(`
@@ -1353,10 +1353,10 @@ ${f.map(h=>{if(h.type==="add")return`A ${Tn.relative(p.worktree,h.filePath).repl
1353
1353
  `)}`;for(let h of f){if(h.type==="delete")continue;let k=h.movePath??h.filePath,w=ft.Diagnostic.report(k,S[Ae.normalizePath(k)]??[]);if(!w)continue;let I=Tn.relative(p.worktree,k).replaceAll("\\","/");m+=`
1354
1354
 
1355
1355
  LSP errors detected in ${I}, please fix:
1356
- ${w}`}return{title:m,metadata:{diff:u,files:g,diagnostics:S},output:m}});return{description:Mh,parameters:$k,execute:i((a,l)=>s(a,l).pipe(r.orDie),"execute")}}));import _h from"path";import{pathToFileURL as qk}from"url";function Lh(e,t={exa:!1,parallel:!1}){return e===sn.ID.opencode||e===sn.ID.make("opencode-go")||t.exa||t.parallel}i(Lh,"webSearchEnabled");var jr=class extends Re.Service()("@opencode/ToolRegistry"){static{i(this,"Service")}},Wk=Te.effect(jr,r.gen(function*(){let e=yield*Oe.Service,t=yield*pt.Service,n=yield*Ft.Service,o=yield*Yu,s=yield*Be.Service,a=yield*cn.Service,l=yield*fh,d=yield*_o,p=yield*Xm,f=yield*jm,u=yield*oh,g=yield*Dh,y=yield*Lm,b=yield*dh,S=yield*od,T=yield*zm,m=yield*td,h=yield*Kl,k=yield*Hm,w=yield*ad,I=yield*gh,P=yield*Ft.Service,x=s.experimentalCodeMode?yield*r.promise(()=>import("./code-mode-H3HRSD24.js")):void 0,A=x?yield*x.CodeModeTool:void 0,C=yield*G.make(r.fn("ToolRegistry.state")(function*(D){let M=[];function _(ce,re){let R=re.args??{},q=Object.entries(R),ne=q.every(Mt=>Nh(Mt[1]))?ii.object(R):void 0,Ue=ne?Hk(ne):Gk(q),ot=ne?c.declare(Mt=>ne.safeParse(Mt).success):c.Unknown;return{id:ce,parameters:ot,jsonSchema:Ue,description:re.description,execute:i((Mt,et)=>r.gen(function*(){let Pn=yield*zt.make(),E={...et,ask:i(Q=>Pn.promise(et.ask(Q)),"ask"),directory:D.directory,worktree:D.worktree},Y=yield*r.promise(()=>re.execute(Mt,E)),ve=typeof Y=="string"?Y:Y.output,de=typeof Y=="string"?{}:Y.metadata??{},te=typeof Y=="string"?void 0:Y.attachments,oe=yield*P.get(et.agent),ae=yield*o.output(ve,{},oe);return{title:typeof Y=="string"?"":Y.title??"",output:ae.truncated?ae.content:ve,attachments:te,metadata:{...de,truncated:ae.truncated,...ae.truncated&&{outputPath:ae.outputPath}}}}).pipe(r.withSpan("Tool.execute",{attributes:{"tool.name":ce,"session.id":et.sessionID,"message.id":et.messageID,...et.callID?{"tool.call_id":et.callID}:{}}})),"execute")}}i(_,"fromPlugin");let W=(yield*e.directories()).flatMap(ce=>Xd.scanSync("{tool,tools}/*.{js,ts}",{cwd:ce,absolute:!0,dot:!0,symlink:!0}));W.length&&(yield*e.waitForDependencies());for(let ce of W){let re=_h.basename(ce,_h.extname(ce)),R=yield*r.promise(()=>import(qk(ce).href));for(let[q,H]of Object.entries(R))Vk(H)&&M.push(_(q==="default"?re:`${re}_${q}`,H))}let U=yield*t.list();for(let ce of U)for(let[re,R]of Object.entries(ce.tool??{}))M.push(_(re,R));yield*e.get();let we=!s.alchemyLab&&["app","cli","desktop"].includes(s.client)||s.enableQuestionTool,pe=yield*r.all({invalid:Rt(l),read:Rt(p),glob:Rt(T),grep:Rt(k),edit:Rt(h),write:Rt(m),task:Rt(d),fetch:Rt(b),todo:Rt(u),search:Rt(S),skill:Rt(I),patch:Rt(w),question:Rt(f),lsp:Rt(g),plan:Rt(y),...A?{execute:Rt(A)}:{}});return{custom:M,builtin:[pe.invalid,...we?[pe.question]:[],pe.read,pe.glob,pe.grep,pe.edit,pe.write,pe.task,pe.fetch,pe.todo,pe.search,pe.skill,pe.patch,...pe.execute?[pe.execute]:[],...s.experimentalLspTool?[pe.lsp]:[],...s.experimentalPlanMode&&!s.alchemyLab&&s.client==="cli"?[pe.plan]:[]],task:pe.task,read:pe.read}})),$=r.fn("ToolRegistry.all")(function*(){let D=yield*G.get(C);return[...D.builtin,...D.custom]}),j=r.fn("ToolRegistry.ids")(function*(){return(yield*$()).map(D=>D.id)}),z=r.fn("ToolRegistry.describeTask")(function*(D){return["Available agent types and the tools they have access to:",(yield*n.list()).filter(U=>U.mode!=="primary").filter(U=>Ke.evaluate("task",U.name,D.permission).action!=="deny").toSorted((U,we)=>U.name.localeCompare(we.name)).map(U=>`- ${U.name}: ${U.description??"This subagent should only be called manually by the user."}`).join(`
1356
+ ${w}`}return{title:m,metadata:{diff:u,files:g,diagnostics:S},output:m}});return{description:Mh,parameters:zk,execute:i((a,l)=>s(a,l).pipe(r.orDie),"execute")}}));import _h from"path";import{pathToFileURL as Gk}from"url";function Lh(e,t={exa:!1,parallel:!1}){return e===sn.ID.opencode||e===sn.ID.make("opencode-go")||t.exa||t.parallel}i(Lh,"webSearchEnabled");var jr=class extends Re.Service()("@opencode/ToolRegistry"){static{i(this,"Service")}},Hk=Te.effect(jr,r.gen(function*(){let e=yield*Oe.Service,t=yield*pt.Service,n=yield*Ft.Service,o=yield*Yu,s=yield*Be.Service,a=yield*cn.Service,l=yield*fh,d=yield*_o,p=yield*Xm,f=yield*jm,u=yield*oh,g=yield*Dh,y=yield*Lm,b=yield*dh,S=yield*od,T=yield*zm,m=yield*td,h=yield*Kl,k=yield*Hm,w=yield*ad,I=yield*gh,P=yield*Ft.Service,x=s.experimentalCodeMode?yield*r.promise(()=>import("./code-mode-YYOGD36U.js")):void 0,A=x?yield*x.CodeModeTool:void 0,C=yield*G.make(r.fn("ToolRegistry.state")(function*(D){let M=[];function _(ce,re){let R=re.args??{},q=Object.entries(R),ne=q.every(Mt=>Nh(Mt[1]))?ii.object(R):void 0,Ue=ne?Xk(ne):Kk(q),ot=ne?c.declare(Mt=>ne.safeParse(Mt).success):c.Unknown;return{id:ce,parameters:ot,jsonSchema:Ue,description:re.description,execute:i((Mt,et)=>r.gen(function*(){let Pn=yield*zt.make(),E={...et,ask:i(Q=>Pn.promise(et.ask(Q)),"ask"),directory:D.directory,worktree:D.worktree},Y=yield*r.promise(()=>re.execute(Mt,E)),ve=typeof Y=="string"?Y:Y.output,de=typeof Y=="string"?{}:Y.metadata??{},te=typeof Y=="string"?void 0:Y.attachments,oe=yield*P.get(et.agent),ae=yield*o.output(ve,{},oe);return{title:typeof Y=="string"?"":Y.title??"",output:ae.truncated?ae.content:ve,attachments:te,metadata:{...de,truncated:ae.truncated,...ae.truncated&&{outputPath:ae.outputPath}}}}).pipe(r.withSpan("Tool.execute",{attributes:{"tool.name":ce,"session.id":et.sessionID,"message.id":et.messageID,...et.callID?{"tool.call_id":et.callID}:{}}})),"execute")}}i(_,"fromPlugin");let W=(yield*e.directories()).flatMap(ce=>Xd.scanSync("{tool,tools}/*.{js,ts}",{cwd:ce,absolute:!0,dot:!0,symlink:!0}));W.length&&(yield*e.waitForDependencies());for(let ce of W){let re=_h.basename(ce,_h.extname(ce)),R=yield*r.promise(()=>import(Gk(ce).href));for(let[q,H]of Object.entries(R))Yk(H)&&M.push(_(q==="default"?re:`${re}_${q}`,H))}let U=yield*t.list();for(let ce of U)for(let[re,R]of Object.entries(ce.tool??{}))M.push(_(re,R));yield*e.get();let we=!s.alchemyLab&&["app","cli","desktop"].includes(s.client)||s.enableQuestionTool,pe=yield*r.all({invalid:Rt(l),read:Rt(p),glob:Rt(T),grep:Rt(k),edit:Rt(h),write:Rt(m),task:Rt(d),fetch:Rt(b),todo:Rt(u),search:Rt(S),skill:Rt(I),patch:Rt(w),question:Rt(f),lsp:Rt(g),plan:Rt(y),...A?{execute:Rt(A)}:{}});return{custom:M,builtin:[pe.invalid,...we?[pe.question]:[],pe.read,pe.glob,pe.grep,pe.edit,pe.write,pe.task,pe.fetch,pe.todo,pe.search,pe.skill,pe.patch,...pe.execute?[pe.execute]:[],...s.experimentalLspTool?[pe.lsp]:[],...s.experimentalPlanMode&&!s.alchemyLab&&s.client==="cli"?[pe.plan]:[]],task:pe.task,read:pe.read}})),$=r.fn("ToolRegistry.all")(function*(){let D=yield*G.get(C);return[...D.builtin,...D.custom]}),j=r.fn("ToolRegistry.ids")(function*(){return(yield*$()).map(D=>D.id)}),z=r.fn("ToolRegistry.describeTask")(function*(D){return["Available agent types and the tools they have access to:",(yield*n.list()).filter(U=>U.mode!=="primary").filter(U=>Ke.evaluate("task",U.name,D.permission).action!=="deny").toSorted((U,we)=>U.name.localeCompare(we.name)).map(U=>`- ${U.name}: ${U.description??"This subagent should only be called manually by the user."}`).join(`
1357
1357
  `)].join(`
1358
1358
  `)}),ie=r.fn("ToolRegistry.describeCodeMode")(function*(D){if(!x)return;let M=Ke.merge(D.agent.permission,D.permission??[]),_=Ke.visibleTools(yield*a.tools(),M);if(Object.keys(_).length!==0)return x.describeCatalog(_,Object.keys(yield*a.clients()).map(gi.sanitize))}),L=r.fn("ToolRegistry.tools")(function*(D){let M=(yield*$()).filter(W=>{if(W.id===od.id)return Lh(D.providerID,{exa:s.enableExa,parallel:s.enableParallel});let U=D.modelID.includes("gpt-")&&!D.modelID.includes("oss")&&!D.modelID.includes("gpt-4");return W.id===ad.id?U:W.id===Kl.id||W.id===td.id?!U:!0}),_=M.some(W=>W.id==="execute")?yield*ie(D):void 0,N=M.filter(W=>W.id!=="execute"||_);return yield*r.forEach(N,r.fnUntraced(function*(W){let U={description:W.description,parameters:W.parameters,jsonSchema:W.jsonSchema};yield*t.trigger("tool.definition",{toolID:W.id},U);let we=U.parameters===W.parameters||U.jsonSchema!==W.jsonSchema?U.jsonSchema:void 0;return{id:W.id,description:[U.description,W.id===_o.id?yield*z(D.agent):void 0,W.id==="execute"?_:void 0].filter(Boolean).join(`
1359
- `),parameters:U.parameters,jsonSchema:we,execute:W.execute,formatValidationError:W.formatValidationError}}),{concurrency:"unbounded"})}),V=r.fn("ToolRegistry.named")(function*(){let D=yield*G.get(C);return{task:D.task,read:D.read}});return jr.of({ids:j,all:$,named:V,tools:L})}));function Nh(e){return typeof e=="object"&&e!==null&&"_zod"in e}i(Nh,"isZodType");function Vk(e){return typeof e=="object"&&e!==null&&"args"in e&&"description"in e&&"execute"in e}i(Vk,"isPluginTool");function zk(e){return typeof e=="boolean"||typeof e=="object"&&e!==null&&!Array.isArray(e)}i(zk,"isJsonSchemaDefinition");function Gk(e){let t=Object.fromEntries(e.filter(n=>zk(n[1])));return{type:"object",properties:t,required:Object.keys(t)}}i(Gk,"legacyJsonSchema");function Hk(e){let t=cd(ii.toJSONSchema(e,{io:"input",metadata:Yk(e)}));if(!Oh(t))throw new Error("plugin tool Zod schema produced a non-object JSON Schema");let{$defs:n,...o}=t;return n&&Oh(n)?{...o,definitions:n}:o}i(Hk,"zodJsonSchema");function Yk(e){let t=ii.registry(),n=new WeakSet,o=i(s=>{if(!(typeof s!="object"||s===null)&&!n.has(s)){if(n.add(s),Nh(s)){let a=typeof s.meta=="function"?s.meta():void 0,l=typeof s.description=="string"?s.description:void 0,d={...a&&typeof a=="object"?a:{},...l?{description:l}:{}};Object.keys(d).length&&t.add(s,d),o(s._zod.def);return}for(let a of Object.values(s))o(a)}},"collect");return o(e),t}i(Yk,"zodMetadataRegistry");function cd(e){return Array.isArray(e)?e.map(t=>cd(t)):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).filter(t=>!((t[0]==="exclusiveMaximum"||t[0]==="exclusiveMinimum")&&typeof t[1]=="boolean")).map(([t,n])=>[t,cd(n)]))}i(cd,"normalizeZodJsonSchema");function Oh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Oh,"isJsonSchemaObject");var Jk=ke.make({service:jr,layer:Wk,deps:[Oe.node,pt.node,Qt.node,Qn.node,Ft.node,Xn.node,me.node,bo.node,yt.node,ft.node,En.node,Ae.node,De.node,In,ni.node,Jt.node,Ju,Be.node,cn.node,Qe.node,Hn.node,Xt.node]});var Br={};fe(Br,{CommandInput:()=>CD,LoopInput:()=>fd,PromptInput:()=>PD,Service:()=>Fr,SessionPrompt:()=>Br,ShellInput:()=>RD,createStructuredOutputTool:()=>sg,node:()=>OD});import eg from"path";import wD from"os";import wa from"node:crypto";var Uh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",va=32;var Kk=16,Fh=10,jh=0xffffffffffff;var No;(function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID"})(No||(No={}));var jo=class extends Error{static{i(this,"ULIDError")}constructor(t,n){super(`${n} (${t})`),this.name="ULIDError",this.code=t}};function Xk(e){let t=Math.floor(e()*va)%va;return Uh.charAt(t)}i(Xk,"randomChar");function Qk(e){let t=Zk(),n=t&&(t.crypto||t.msCrypto)||(typeof wa<"u"?wa:null);if(typeof n?.getRandomValues=="function")return()=>{let o=new Uint8Array(1);return n.getRandomValues(o),o[0]/255};if(typeof n?.randomBytes=="function")return()=>n.randomBytes(1).readUInt8()/255;if(wa?.randomBytes)return()=>wa.randomBytes(1).readUInt8()/255;throw new jo(No.PRNGDetectFailure,"Failed to find a reliable PRNG")}i(Qk,"detectPRNG");function Zk(){return nD()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}i(Zk,"detectRoot");function eD(e,t){let n="";for(;e>0;e--)n=Xk(t)+n;return n}i(eD,"encodeRandom");function tD(e,t=Fh){if(isNaN(e))throw new jo(No.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>jh)throw new jo(No.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${jh}: ${e}`);if(e<0)throw new jo(No.EncodeTimeNegative,`Time must be positive: ${e}`);if(Number.isInteger(e)===!1)throw new jo(No.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let n,o="";for(let s=t;s>0;s--)n=e%va,o=Uh.charAt(n)+o,e=(e-n)/va;return o}i(tD,"encodeTime");function nD(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}i(nD,"inWebWorker");function ld(e,t){let n=t||Qk(),o=!e||isNaN(e)?Date.now():e;return tD(o,Fh)+eD(Kk,n)}i(ld,"ulid");import{pathToFileURL as vD,fileURLToPath as ud}from"url";var As={};fe(As,{ShellID:()=>As,ToolID:()=>aD,toKind:()=>iD});var oD=["bash","pwsh","powershell","cmd"],rD=new Set(oD);function sD(e){return rD.has(e)}i(sD,"isKind");function iD(e){return sD(e)?e:"bash"}i(iD,"toKind");var aD="bash";function Bh(e){let t=e.indexOf(",");if(t===-1)return"";let n=e.slice(0,t),o=e.slice(t+1);return n.includes(";base64")?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(o)}i(Bh,"decodeDataUrl");var Ms={};fe(Ms,{SessionReminders:()=>Ms,apply:()=>lD});import cD from"path";var $h=`<system-reminder>
1359
+ `),parameters:U.parameters,jsonSchema:we,execute:W.execute,formatValidationError:W.formatValidationError}}),{concurrency:"unbounded"})}),V=r.fn("ToolRegistry.named")(function*(){let D=yield*G.get(C);return{task:D.task,read:D.read}});return jr.of({ids:j,all:$,named:V,tools:L})}));function Nh(e){return typeof e=="object"&&e!==null&&"_zod"in e}i(Nh,"isZodType");function Yk(e){return typeof e=="object"&&e!==null&&"args"in e&&"description"in e&&"execute"in e}i(Yk,"isPluginTool");function Jk(e){return typeof e=="boolean"||typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Jk,"isJsonSchemaDefinition");function Kk(e){let t=Object.fromEntries(e.filter(n=>Jk(n[1])));return{type:"object",properties:t,required:Object.keys(t)}}i(Kk,"legacyJsonSchema");function Xk(e){let t=cd(ii.toJSONSchema(e,{io:"input",metadata:Qk(e)}));if(!Oh(t))throw new Error("plugin tool Zod schema produced a non-object JSON Schema");let{$defs:n,...o}=t;return n&&Oh(n)?{...o,definitions:n}:o}i(Xk,"zodJsonSchema");function Qk(e){let t=ii.registry(),n=new WeakSet,o=i(s=>{if(!(typeof s!="object"||s===null)&&!n.has(s)){if(n.add(s),Nh(s)){let a=typeof s.meta=="function"?s.meta():void 0,l=typeof s.description=="string"?s.description:void 0,d={...a&&typeof a=="object"?a:{},...l?{description:l}:{}};Object.keys(d).length&&t.add(s,d),o(s._zod.def);return}for(let a of Object.values(s))o(a)}},"collect");return o(e),t}i(Qk,"zodMetadataRegistry");function cd(e){return Array.isArray(e)?e.map(t=>cd(t)):typeof e!="object"||e===null?e:Object.fromEntries(Object.entries(e).filter(t=>!((t[0]==="exclusiveMaximum"||t[0]==="exclusiveMinimum")&&typeof t[1]=="boolean")).map(([t,n])=>[t,cd(n)]))}i(cd,"normalizeZodJsonSchema");function Oh(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Oh,"isJsonSchemaObject");var Zk=ke.make({service:jr,layer:Hk,deps:[Oe.node,pt.node,Qt.node,Qn.node,Ft.node,Xn.node,me.node,bo.node,yt.node,ft.node,En.node,Ae.node,De.node,In,ni.node,Jt.node,Ju,Be.node,cn.node,Qe.node,Hn.node,Xt.node]});var Br={};fe(Br,{CommandInput:()=>OD,LoopInput:()=>fd,PromptInput:()=>MD,Service:()=>Fr,SessionPrompt:()=>Br,ShellInput:()=>_D,createStructuredOutputTool:()=>sg,node:()=>UD});import eg from"path";import ID from"os";import wa from"node:crypto";var Uh="0123456789ABCDEFGHJKMNPQRSTVWXYZ",va=32;var eD=16,Fh=10,jh=0xffffffffffff;var No;(function(e){e.Base32IncorrectEncoding="B32_ENC_INVALID",e.DecodeTimeInvalidCharacter="DEC_TIME_CHAR",e.DecodeTimeValueMalformed="DEC_TIME_MALFORMED",e.EncodeTimeNegative="ENC_TIME_NEG",e.EncodeTimeSizeExceeded="ENC_TIME_SIZE_EXCEED",e.EncodeTimeValueMalformed="ENC_TIME_MALFORMED",e.PRNGDetectFailure="PRNG_DETECT",e.ULIDInvalid="ULID_INVALID",e.Unexpected="UNEXPECTED",e.UUIDInvalid="UUID_INVALID"})(No||(No={}));var jo=class extends Error{static{i(this,"ULIDError")}constructor(t,n){super(`${n} (${t})`),this.name="ULIDError",this.code=t}};function tD(e){let t=Math.floor(e()*va)%va;return Uh.charAt(t)}i(tD,"randomChar");function nD(e){let t=oD(),n=t&&(t.crypto||t.msCrypto)||(typeof wa<"u"?wa:null);if(typeof n?.getRandomValues=="function")return()=>{let o=new Uint8Array(1);return n.getRandomValues(o),o[0]/255};if(typeof n?.randomBytes=="function")return()=>n.randomBytes(1).readUInt8()/255;if(wa?.randomBytes)return()=>wa.randomBytes(1).readUInt8()/255;throw new jo(No.PRNGDetectFailure,"Failed to find a reliable PRNG")}i(nD,"detectPRNG");function oD(){return iD()?self:typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:null}i(oD,"detectRoot");function rD(e,t){let n="";for(;e>0;e--)n=tD(t)+n;return n}i(rD,"encodeRandom");function sD(e,t=Fh){if(isNaN(e))throw new jo(No.EncodeTimeValueMalformed,`Time must be a number: ${e}`);if(e>jh)throw new jo(No.EncodeTimeSizeExceeded,`Cannot encode a time larger than ${jh}: ${e}`);if(e<0)throw new jo(No.EncodeTimeNegative,`Time must be positive: ${e}`);if(Number.isInteger(e)===!1)throw new jo(No.EncodeTimeValueMalformed,`Time must be an integer: ${e}`);let n,o="";for(let s=t;s>0;s--)n=e%va,o=Uh.charAt(n)+o,e=(e-n)/va;return o}i(sD,"encodeTime");function iD(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}i(iD,"inWebWorker");function ld(e,t){let n=t||nD(),o=!e||isNaN(e)?Date.now():e;return sD(o,Fh)+rD(eD,n)}i(ld,"ulid");import{pathToFileURL as kD,fileURLToPath as ud}from"url";var As={};fe(As,{ShellID:()=>As,ToolID:()=>uD,toKind:()=>dD});var aD=["bash","pwsh","powershell","cmd"],cD=new Set(aD);function lD(e){return cD.has(e)}i(lD,"isKind");function dD(e){return lD(e)?e:"bash"}i(dD,"toKind");var uD="bash";function Bh(e){let t=e.indexOf(",");if(t===-1)return"";let n=e.slice(0,t),o=e.slice(t+1);return n.includes(";base64")?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(o)}i(Bh,"decodeDataUrl");var Ms={};fe(Ms,{SessionReminders:()=>Ms,apply:()=>fD});import pD from"path";var $h=`<system-reminder>
1360
1360
  # Plan Mode - System Reminder
1361
1361
 
1362
1362
  CRITICAL: Plan mode ACTIVE - you are in READ-ONLY phase. STRICTLY FORBIDDEN:
@@ -1457,34 +1457,34 @@ This is critical - your turn should only end with either asking the user a quest
1457
1457
 
1458
1458
  NOTE: At any point in time through this workflow you should feel free to ask the user questions or clarifications. Don't make large assumptions about user intent. The goal is to present a well researched plan to the user, and tie any loose ends before implementation begins.
1459
1459
  </system-reminder>
1460
- `;var lD=r.fn("SessionReminders.apply")(function*(e){let t=yield*Be.Service,n=yield*Ae.Service,o=yield*me.Service,s=e.messages.findLast(u=>u.info.role==="user");if(!s)return e.messages;if(!t.experimentalPlanMode)return e.agent.name==="plan"&&s.parts.push({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:$h,synthetic:!0}),e.messages.some(g=>g.info.role==="assistant"&&g.info.agent==="plan")&&e.agent.name==="build"&&s.parts.push({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:xa,synthetic:!0}),e.messages;let a=e.messages.findLast(u=>u.info.role==="assistant");if(e.agent.name!=="plan"&&a?.info.agent==="plan"){let u=yield*G.context,g=me.plan(e.session,u),y=yield*n.existsSafe(g),b=yield*o.updatePart({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:y?`${xa}
1460
+ `;var fD=r.fn("SessionReminders.apply")(function*(e){let t=yield*Be.Service,n=yield*Ae.Service,o=yield*me.Service,s=e.messages.findLast(u=>u.info.role==="user");if(!s)return e.messages;if(!t.experimentalPlanMode)return e.agent.name==="plan"&&s.parts.push({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:$h,synthetic:!0}),e.messages.some(g=>g.info.role==="assistant"&&g.info.agent==="plan")&&e.agent.name==="build"&&s.parts.push({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:xa,synthetic:!0}),e.messages;let a=e.messages.findLast(u=>u.info.role==="assistant");if(e.agent.name!=="plan"&&a?.info.agent==="plan"){let u=yield*G.context,g=me.plan(e.session,u),y=yield*n.existsSafe(g),b=yield*o.updatePart({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:y?`${xa}
1461
1461
 
1462
- A plan file exists at ${g}. You should execute on the plan defined within it`:xa,synthetic:!0});return s.parts.push(b),e.messages}if(e.agent.name!=="plan"||a?.info.agent==="plan")return e.messages;let l=yield*G.context,d=me.plan(e.session,l),p=yield*n.existsSafe(d);p||(yield*n.ensureDir(cD.dirname(d)).pipe(r.catch(r.die)));let f=yield*o.updatePart({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:qh.replace("${planInfo}",()=>p?`A plan file already exists at ${d}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${d} using the write tool.`),synthetic:!0});return s.parts.push(f),e.messages});var Os={};fe(Os,{SessionTools:()=>Os,resolve:()=>dD});var qn={list:"list_mcp_resources",listTemplates:"list_mcp_resource_templates",read:"read_mcp_resource"},Sa=10*1024*1024,zh=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),dD=r.fn("SessionTools.resolve")(function*(e){let t={},n=yield*zt.make(),o=yield*pt.Service,s=yield*Ke.Service,a=yield*$n.Service,l=yield*cn.Service,d=yield*wo.Service,p=yield*Be.Service,f=i((g,y)=>({sessionID:e.session.id,abort:y.abortSignal,messageID:e.processor.message.id,callID:y.toolCallId,extra:{model:e.model,bypassAgentCheck:e.bypassAgentCheck,promptOps:e.promptOps},agent:e.agent.name,messages:e.messages,metadata:i(b=>e.processor.updateToolCall(y.toolCallId,S=>["running","pending"].includes(S.state.status)?{...S,state:{title:b.title,metadata:b.metadata,status:"running",input:g,time:S.state.status==="running"?S.state.time:{start:Date.now()}}}:S),"metadata"),ask:i(b=>s.ask({...b,sessionID:e.session.id,tool:{messageID:e.processor.message.id,callID:y.toolCallId},ruleset:Ke.merge(e.agent.permission,e.session.permission??[])}).pipe(r.orDie),"ask")}),"context");for(let g of yield*a.tools({modelID:uo.ID.make(e.model.api.id),providerID:e.model.providerID,agent:e.agent,permission:e.session.permission})){let y=Xe.schema(e.model,Mo.fromTool(g));t[g.id]={description:g.description,inputSchema:yn(y),execute(b,S){return Ht.run(e.gate,()=>n.promise(r.gen(function*(){let T=f(b,S);yield*o.trigger("tool.execute.before",{tool:g.id,sessionID:T.sessionID,callID:T.callID},{args:b});let m=yield*g.execute(b,T),h={...m,attachments:m.attachments?.map(k=>({...k,id:Fe.ascending(),sessionID:T.sessionID,messageID:e.processor.message.id}))};return yield*o.trigger("tool.execute.after",{tool:g.id,sessionID:T.sessionID,callID:T.callID,args:b},h),S.abortSignal?.aborted&&(yield*e.processor.completeToolCall(S.toolCallId,h)),h})))}}}if(Object.values(yield*l.clients()).some(g=>!!g.getServerCapabilities()?.resources)&&(t[qn.list]={description:"Lists resources provided by connected MCP servers. Resources provide context such as files, database schemas, or application-specific information.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resources from every connected server."}},additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=Wh(g),S=f(_s(g),y),T=yield*l.clients(),m=Object.entries(T).filter(A=>!!A[1].getServerCapabilities()?.resources).map(A=>A[0]).sort((A,C)=>A.localeCompare(C));if(b.server&&!m.includes(b.server))throw new Error(m.length===0?`MCP server "${b.server}" does not support resources`:`MCP server "${b.server}" does not support resources. Available resource servers: ${m.join(", ")}`);let h=b.server?[`mcp:${b.server}:*`]:m.map(A=>`mcp:${A}:*`);yield*o.trigger("tool.execute.before",{tool:qn.list,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:b.server?{server:b.server}:{},patterns:h,always:h});let w=Object.values(yield*l.resources(b.server)).filter(A=>!b.server||A.client===b.server).toSorted((A,C)=>(A.client+"\0"+A.name+"\0"+A.uri).localeCompare(C.client+"\0"+C.name+"\0"+C.uri)),I=JSON.stringify({resources:w.map(pD)},null,2),P=yield*d.output(I,{},e.agent),x={title:b.server?`MCP resources: ${b.server}`:"MCP resources",metadata:{count:w.length,servers:m,...b.server?{server:b.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*o.trigger("tool.execute.after",{tool:qn.list,sessionID:S.sessionID,callID:y.toolCallId,args:g},x),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,x)),x}))}},t[qn.listTemplates]={description:"Lists resource templates provided by connected MCP servers. Resource templates are parameterized resources that can be read after filling in their URI template.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resource templates from every connected server."}},additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=Wh(g),S=f(_s(g),y),T=yield*l.clients(),m=Object.entries(T).filter(A=>!!A[1].getServerCapabilities()?.resources).map(A=>A[0]).sort((A,C)=>A.localeCompare(C));if(b.server&&!m.includes(b.server))throw new Error(m.length===0?`MCP server "${b.server}" does not support resources`:`MCP server "${b.server}" does not support resources. Available resource servers: ${m.join(", ")}`);let h=b.server?[`mcp:${b.server}:*`]:m.map(A=>`mcp:${A}:*`);yield*o.trigger("tool.execute.before",{tool:qn.listTemplates,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:b.server?{server:b.server}:{},patterns:h,always:h});let w=Object.values(yield*l.resourceTemplates(b.server)).filter(A=>!b.server||A.client===b.server).toSorted((A,C)=>(A.client+"\0"+A.name+"\0"+A.uriTemplate).localeCompare(C.client+"\0"+C.name+"\0"+C.uriTemplate)),I=JSON.stringify({resourceTemplates:w.map(fD)},null,2),P=yield*d.output(I,{},e.agent),x={title:b.server?`MCP resource templates: ${b.server}`:"MCP resource templates",metadata:{count:w.length,servers:m,...b.server?{server:b.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*o.trigger("tool.execute.after",{tool:qn.listTemplates,sessionID:S.sessionID,callID:y.toolCallId,args:g},x),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,x)),x}))}},t[qn.read]={description:"Read a specific resource from an MCP server using the server name and resource URI. The URI is an MCP identifier and does not need to be a file URL.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"MCP server name exactly as returned by list_mcp_resources."},uri:{type:"string",description:"Resource URI to read. Use the exact URI string returned by list_mcp_resources."}},required:["server","uri"],additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=uD(g),S=f(_s(g),y),m=(yield*l.clients())[b.server];if(!m)throw new Error(`MCP server "${b.server}" is not connected`);if(!m.getServerCapabilities()?.resources)throw new Error(`MCP server "${b.server}" does not support resources`);yield*o.trigger("tool.execute.before",{tool:qn.read,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:{server:b.server,uri:b.uri},patterns:[`mcp:${b.server}:${b.uri}`],always:[`mcp:${b.server}:*`]});let h=yield*l.readResource(b.server,b.uri);if(!h)throw new Error(`Failed to read MCP resource: ${b.server}/${b.uri}`);let k=mD(b.server,b.uri,h),w=yield*d.output(k.text,{},e.agent),I={title:`MCP resource: ${b.uri}`,metadata:{server:b.server,uri:b.uri,contents:k.contents,attachments:k.attachments.length,truncated:w.truncated,...w.truncated&&{outputPath:w.outputPath}},output:w.content,attachments:k.attachments.map(P=>({...P,id:Fe.ascending(),sessionID:S.sessionID,messageID:e.processor.message.id}))};return yield*o.trigger("tool.execute.after",{tool:qn.read,sessionID:S.sessionID,callID:y.toolCallId,args:g},I),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,I)),I}))}}),p.experimentalCodeMode)return t;for(let[g,y]of Object.entries(yield*l.tools())){let b=gi.convertTool(y.def,y.client,y.timeout),S=b.execute;if(!S)continue;let T=yield*r.promise(()=>Promise.resolve(fi(b.inputSchema).jsonSchema)),m=Xe.schema(e.model,{...T,properties:T.properties??{}});b.inputSchema=yn(m),b.execute=(h,k)=>Ht.run(e.gate,()=>n.promise(r.gen(function*(){let w=f(h,k);yield*o.trigger("tool.execute.before",{tool:g,sessionID:w.sessionID,callID:k.toolCallId},{args:h});let I=yield*r.gen(function*(){yield*w.ask({permission:g,metadata:{},patterns:["*"],always:["*"]});let j={sessionId:w.sessionID,messageId:e.processor.message.id};return yield*r.promise(()=>S(h,{...k,callContext:j}))}).pipe(r.withSpan("Tool.execute",{attributes:{"tool.name":g,"tool.call_id":k.toolCallId,"session.id":w.sessionID,"message.id":e.processor.message.id}}));yield*o.trigger("tool.execute.after",{tool:g,sessionID:w.sessionID,callID:k.toolCallId,args:h},I);let P=[],x=[];for(let j of I.content)if(j.type==="text")P.push(j.text);else if(j.type==="image")x.push({type:"file",mime:j.mimeType,url:`data:${j.mimeType};base64,${j.data}`});else if(j.type==="resource"){let{resource:z}=j;if(z.text&&P.push(z.text),z.blob){let ie=z.mimeType??"application/octet-stream",L=Hh(z.blob);if(!zh.has(ie)){P.push(`[Binary MCP resource omitted: ${z.uri} (${ie}, ${Ur(L)}) is not a supported attachment type]`);continue}if(L>Sa){P.push(`[Binary MCP resource omitted: ${z.uri} (${ie}, ${Ur(L)}) exceeds ${Ur(Sa)}]`);continue}x.push({type:"file",mime:ie,url:`data:${ie};base64,${z.blob}`,filename:z.uri})}}let A=yield*d.output(P.join(`
1462
+ A plan file exists at ${g}. You should execute on the plan defined within it`:xa,synthetic:!0});return s.parts.push(b),e.messages}if(e.agent.name!=="plan"||a?.info.agent==="plan")return e.messages;let l=yield*G.context,d=me.plan(e.session,l),p=yield*n.existsSafe(d);p||(yield*n.ensureDir(pD.dirname(d)).pipe(r.catch(r.die)));let f=yield*o.updatePart({id:Fe.ascending(),messageID:s.info.id,sessionID:s.info.sessionID,type:"text",text:qh.replace("${planInfo}",()=>p?`A plan file already exists at ${d}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${d} using the write tool.`),synthetic:!0});return s.parts.push(f),e.messages});var Os={};fe(Os,{SessionTools:()=>Os,resolve:()=>mD});var qn={list:"list_mcp_resources",listTemplates:"list_mcp_resource_templates",read:"read_mcp_resource"},Sa=10*1024*1024,zh=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),mD=r.fn("SessionTools.resolve")(function*(e){let t={},n=yield*zt.make(),o=yield*pt.Service,s=yield*Ke.Service,a=yield*$n.Service,l=yield*cn.Service,d=yield*wo.Service,p=yield*Be.Service,f=i((g,y)=>({sessionID:e.session.id,abort:y.abortSignal,messageID:e.processor.message.id,callID:y.toolCallId,extra:{model:e.model,bypassAgentCheck:e.bypassAgentCheck,promptOps:e.promptOps},agent:e.agent.name,messages:e.messages,metadata:i(b=>e.processor.updateToolCall(y.toolCallId,S=>["running","pending"].includes(S.state.status)?{...S,state:{title:b.title,metadata:b.metadata,status:"running",input:g,time:S.state.status==="running"?S.state.time:{start:Date.now()}}}:S),"metadata"),ask:i(b=>s.ask({...b,sessionID:e.session.id,tool:{messageID:e.processor.message.id,callID:y.toolCallId},ruleset:Ke.merge(e.agent.permission,e.session.permission??[])}).pipe(r.orDie),"ask")}),"context");for(let g of yield*a.tools({modelID:uo.ID.make(e.model.api.id),providerID:e.model.providerID,agent:e.agent,permission:e.session.permission})){let y=Xe.schema(e.model,Mo.fromTool(g));t[g.id]={description:g.description,inputSchema:yn(y),execute(b,S){return Ht.run(e.gate,()=>n.promise(r.gen(function*(){let T=f(b,S);yield*o.trigger("tool.execute.before",{tool:g.id,sessionID:T.sessionID,callID:T.callID},{args:b});let m=yield*g.execute(b,T),h={...m,attachments:m.attachments?.map(k=>({...k,id:Fe.ascending(),sessionID:T.sessionID,messageID:e.processor.message.id}))};return yield*o.trigger("tool.execute.after",{tool:g.id,sessionID:T.sessionID,callID:T.callID,args:b},h),S.abortSignal?.aborted&&(yield*e.processor.completeToolCall(S.toolCallId,h)),h})))}}}if(Object.values(yield*l.clients()).some(g=>!!g.getServerCapabilities()?.resources)&&(t[qn.list]={description:"Lists resources provided by connected MCP servers. Resources provide context such as files, database schemas, or application-specific information.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resources from every connected server."}},additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=Wh(g),S=f(_s(g),y),T=yield*l.clients(),m=Object.entries(T).filter(A=>!!A[1].getServerCapabilities()?.resources).map(A=>A[0]).sort((A,C)=>A.localeCompare(C));if(b.server&&!m.includes(b.server))throw new Error(m.length===0?`MCP server "${b.server}" does not support resources`:`MCP server "${b.server}" does not support resources. Available resource servers: ${m.join(", ")}`);let h=b.server?[`mcp:${b.server}:*`]:m.map(A=>`mcp:${A}:*`);yield*o.trigger("tool.execute.before",{tool:qn.list,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:b.server?{server:b.server}:{},patterns:h,always:h});let w=Object.values(yield*l.resources(b.server)).filter(A=>!b.server||A.client===b.server).toSorted((A,C)=>(A.client+"\0"+A.name+"\0"+A.uri).localeCompare(C.client+"\0"+C.name+"\0"+C.uri)),I=JSON.stringify({resources:w.map(gD)},null,2),P=yield*d.output(I,{},e.agent),x={title:b.server?`MCP resources: ${b.server}`:"MCP resources",metadata:{count:w.length,servers:m,...b.server?{server:b.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*o.trigger("tool.execute.after",{tool:qn.list,sessionID:S.sessionID,callID:y.toolCallId,args:g},x),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,x)),x}))}},t[qn.listTemplates]={description:"Lists resource templates provided by connected MCP servers. Resource templates are parameterized resources that can be read after filling in their URI template.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"Optional MCP server name. When omitted, lists resource templates from every connected server."}},additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=Wh(g),S=f(_s(g),y),T=yield*l.clients(),m=Object.entries(T).filter(A=>!!A[1].getServerCapabilities()?.resources).map(A=>A[0]).sort((A,C)=>A.localeCompare(C));if(b.server&&!m.includes(b.server))throw new Error(m.length===0?`MCP server "${b.server}" does not support resources`:`MCP server "${b.server}" does not support resources. Available resource servers: ${m.join(", ")}`);let h=b.server?[`mcp:${b.server}:*`]:m.map(A=>`mcp:${A}:*`);yield*o.trigger("tool.execute.before",{tool:qn.listTemplates,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:b.server?{server:b.server}:{},patterns:h,always:h});let w=Object.values(yield*l.resourceTemplates(b.server)).filter(A=>!b.server||A.client===b.server).toSorted((A,C)=>(A.client+"\0"+A.name+"\0"+A.uriTemplate).localeCompare(C.client+"\0"+C.name+"\0"+C.uriTemplate)),I=JSON.stringify({resourceTemplates:w.map(yD)},null,2),P=yield*d.output(I,{},e.agent),x={title:b.server?`MCP resource templates: ${b.server}`:"MCP resource templates",metadata:{count:w.length,servers:m,...b.server?{server:b.server}:{},truncated:P.truncated,...P.truncated&&{outputPath:P.outputPath}},output:P.content};return yield*o.trigger("tool.execute.after",{tool:qn.listTemplates,sessionID:S.sessionID,callID:y.toolCallId,args:g},x),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,x)),x}))}},t[qn.read]={description:"Read a specific resource from an MCP server using the server name and resource URI. The URI is an MCP identifier and does not need to be a file URL.",inputSchema:yn(Xe.schema(e.model,{type:"object",properties:{server:{type:"string",description:"MCP server name exactly as returned by list_mcp_resources."},uri:{type:"string",description:"Resource URI to read. Use the exact URI string returned by list_mcp_resources."}},required:["server","uri"],additionalProperties:!1})),execute(g,y){return n.promise(r.gen(function*(){let b=hD(g),S=f(_s(g),y),m=(yield*l.clients())[b.server];if(!m)throw new Error(`MCP server "${b.server}" is not connected`);if(!m.getServerCapabilities()?.resources)throw new Error(`MCP server "${b.server}" does not support resources`);yield*o.trigger("tool.execute.before",{tool:qn.read,sessionID:S.sessionID,callID:y.toolCallId},{args:g}),yield*S.ask({permission:"read",metadata:{server:b.server,uri:b.uri},patterns:[`mcp:${b.server}:${b.uri}`],always:[`mcp:${b.server}:*`]});let h=yield*l.readResource(b.server,b.uri);if(!h)throw new Error(`Failed to read MCP resource: ${b.server}/${b.uri}`);let k=bD(b.server,b.uri,h),w=yield*d.output(k.text,{},e.agent),I={title:`MCP resource: ${b.uri}`,metadata:{server:b.server,uri:b.uri,contents:k.contents,attachments:k.attachments.length,truncated:w.truncated,...w.truncated&&{outputPath:w.outputPath}},output:w.content,attachments:k.attachments.map(P=>({...P,id:Fe.ascending(),sessionID:S.sessionID,messageID:e.processor.message.id}))};return yield*o.trigger("tool.execute.after",{tool:qn.read,sessionID:S.sessionID,callID:y.toolCallId,args:g},I),y.abortSignal?.aborted&&(yield*e.processor.completeToolCall(y.toolCallId,I)),I}))}}),p.experimentalCodeMode)return t;for(let[g,y]of Object.entries(yield*l.tools())){let b=gi.convertTool(y.def,y.client,y.timeout),S=b.execute;if(!S)continue;let T=yield*r.promise(()=>Promise.resolve(fi(b.inputSchema).jsonSchema)),m=Xe.schema(e.model,{...T,properties:T.properties??{}});b.inputSchema=yn(m),b.execute=(h,k)=>Ht.run(e.gate,()=>n.promise(r.gen(function*(){let w=f(h,k);yield*o.trigger("tool.execute.before",{tool:g,sessionID:w.sessionID,callID:k.toolCallId},{args:h});let I=yield*r.gen(function*(){yield*w.ask({permission:g,metadata:{},patterns:["*"],always:["*"]});let j={sessionId:w.sessionID,messageId:e.processor.message.id};return yield*r.promise(()=>S(h,{...k,callContext:j}))}).pipe(r.withSpan("Tool.execute",{attributes:{"tool.name":g,"tool.call_id":k.toolCallId,"session.id":w.sessionID,"message.id":e.processor.message.id}}));yield*o.trigger("tool.execute.after",{tool:g,sessionID:w.sessionID,callID:k.toolCallId,args:h},I);let P=[],x=[];for(let j of I.content)if(j.type==="text")P.push(j.text);else if(j.type==="image")x.push({type:"file",mime:j.mimeType,url:`data:${j.mimeType};base64,${j.data}`});else if(j.type==="resource"){let{resource:z}=j;if(z.text&&P.push(z.text),z.blob){let ie=z.mimeType??"application/octet-stream",L=Hh(z.blob);if(!zh.has(ie)){P.push(`[Binary MCP resource omitted: ${z.uri} (${ie}, ${Ur(L)}) is not a supported attachment type]`);continue}if(L>Sa){P.push(`[Binary MCP resource omitted: ${z.uri} (${ie}, ${Ur(L)}) exceeds ${Ur(Sa)}]`);continue}x.push({type:"file",mime:ie,url:`data:${ie};base64,${z.blob}`,filename:z.uri})}}let A=yield*d.output(P.join(`
1463
1463
 
1464
- `),{},e.agent),$={title:"",metadata:{...I.metadata,truncated:A.truncated,...A.truncated&&{outputPath:A.outputPath}},output:A.content,attachments:x.map(j=>({...j,id:Fe.ascending(),sessionID:w.sessionID,messageID:e.processor.message.id})),content:I.content};return k.abortSignal?.aborted&&(yield*e.processor.completeToolCall(k.toolCallId,$)),$}))),t[g]=b}return t});function _s(e){return ut(e)?e:{}}i(_s,"toRecord");function Wh(e){let t=_s(e);return{server:Gh(t,"server")}}i(Wh,"parseListMcpResourcesArgs");function uD(e){let t=_s(e);return{server:Vh(t,"server"),uri:Vh(t,"uri")}}i(uD,"parseReadMcpResourceArgs");function Gh(e,t){let n=e[t];if(!(n==null||n==="")){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}i(Gh,"optionalString");function Vh(e,t){let n=Gh(e,t);if(n)return n;throw new Error(`${t} is required`)}i(Vh,"requiredString");function pD(e){return{...Object.fromEntries(Object.entries(e).filter(n=>n[0]!=="client")),server:e.client}}i(pD,"formatMcpResource");function fD(e){return{...Object.fromEntries(Object.entries(e).filter(n=>n[0]!=="client")),server:e.client}}i(fD,"formatMcpResourceTemplate");function mD(e,t,n){let o=(Array.isArray(n.contents)?n.contents:[n.contents]).filter(ut),s=[],a=[];for(let l of o){let d=typeof l.uri=="string"?l.uri:t,p=typeof l.mimeType=="string"?l.mimeType:"application/octet-stream";if(typeof l.text=="string"){s.push(`Resource: ${d}
1464
+ `),{},e.agent),$={title:"",metadata:{...I.metadata,truncated:A.truncated,...A.truncated&&{outputPath:A.outputPath}},output:A.content,attachments:x.map(j=>({...j,id:Fe.ascending(),sessionID:w.sessionID,messageID:e.processor.message.id})),content:I.content};return k.abortSignal?.aborted&&(yield*e.processor.completeToolCall(k.toolCallId,$)),$}))),t[g]=b}return t});function _s(e){return ut(e)?e:{}}i(_s,"toRecord");function Wh(e){let t=_s(e);return{server:Gh(t,"server")}}i(Wh,"parseListMcpResourcesArgs");function hD(e){let t=_s(e);return{server:Vh(t,"server"),uri:Vh(t,"uri")}}i(hD,"parseReadMcpResourceArgs");function Gh(e,t){let n=e[t];if(!(n==null||n==="")){if(typeof n!="string")throw new Error(`${t} must be a string`);return n}}i(Gh,"optionalString");function Vh(e,t){let n=Gh(e,t);if(n)return n;throw new Error(`${t} is required`)}i(Vh,"requiredString");function gD(e){return{...Object.fromEntries(Object.entries(e).filter(n=>n[0]!=="client")),server:e.client}}i(gD,"formatMcpResource");function yD(e){return{...Object.fromEntries(Object.entries(e).filter(n=>n[0]!=="client")),server:e.client}}i(yD,"formatMcpResourceTemplate");function bD(e,t,n){let o=(Array.isArray(n.contents)?n.contents:[n.contents]).filter(ut),s=[],a=[];for(let l of o){let d=typeof l.uri=="string"?l.uri:t,p=typeof l.mimeType=="string"?l.mimeType:"application/octet-stream";if(typeof l.text=="string"){s.push(`Resource: ${d}
1465
1465
  MIME: ${p}
1466
1466
  ${l.text}`);continue}if(typeof l.blob=="string"){let f=Hh(l.blob);if(!zh.has(p)){s.push(`[Binary MCP resource omitted: ${d} (${p}, ${Ur(f)}) is not a supported attachment type]`);continue}if(f>Sa){s.push(`[Binary MCP resource omitted: ${d} (${p}, ${Ur(f)}) exceeds ${Ur(Sa)}]`);continue}s.push(`[Binary MCP resource attached: ${d} (${p})]`),a.push({type:"file",mime:p,url:`data:${p};base64,${l.blob}`,filename:d});continue}s.push(`[MCP resource content without text or blob: ${d}]`)}return{contents:o.length,attachments:a,text:s.join(`
1467
1467
 
1468
- `)||`MCP resource ${t} from ${e} returned no contents.`}}i(mD,"formatMcpResourceContent");function Hh(e){let t=e.replace(/\s/g,""),n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-n)}i(Hh,"base64Size");function Ur(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}i(Ur,"formatBytes");var hD=new Set(["inbox-chat","via-herald"]);function Yh(e){let t=e.map(n=>n?.metadata?.alchemy?.kind).filter(n=>typeof n=="string"&&n.length>0);return t.length===0?!0:t.some(n=>hD.has(n))}i(Yh,"writtenByAPerson");var gD="[from AlchemyLab, not a user message]";function Jh(e){let t=e.startsWith(gD);return["<system-reminder>",t?"This note reached you while you worked:":"The user sent the following message:",e,"",t?"Take it into account and continue with your tasks.":"Please address this message and continue with your tasks.","</system-reminder>"].join(`
1469
- `)}i(Jh,"raisedMidTurn");var yD=/\bto=functions\.|^\s*functions\.[A-Za-z_]+\s*[({]/m;function Kh(e){let t=e.filter(s=>s.type==="text"),n=t.filter(s=>(s.text??"").trim().length>0&&!yD.test(s.text??"")),o=n.length>0?n[n.length-1]:void 0;return{drop:t.filter(s=>s!==o).map(s=>s.id),answered:o!==void 0}}i(Kh,"asideTextToDrop");function Xh(e){let t=e.filter(s=>!(s.info.role==="assistant"&&s.info.aside)&&!(s.info.role==="user"&&s.info.quiet)),n=Ze.latest(t),o=n.user?void 0:Ze.latest(e.filter(s=>s.info.role==="user")).user;return{lastUser:n.user??o,lastAssistant:n.assistant,lastFinished:n.finished,tasks:n.tasks}}i(Xh,"scanForLoop");import Qh from"fs";import bD from"path";var Ia={info:i((e,t)=>process.stderr.write(`level=INFO service=session.pause message=${JSON.stringify(e)} ${JSON.stringify(t??{})}
1468
+ `)||`MCP resource ${t} from ${e} returned no contents.`}}i(bD,"formatMcpResourceContent");function Hh(e){let t=e.replace(/\s/g,""),n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-n)}i(Hh,"base64Size");function Ur(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}i(Ur,"formatBytes");var wD=new Set(["inbox-chat","via-herald"]);function Yh(e){let t=e.map(n=>n?.metadata?.alchemy?.kind).filter(n=>typeof n=="string"&&n.length>0);return t.length===0?!0:t.some(n=>wD.has(n))}i(Yh,"writtenByAPerson");var vD="[from AlchemyLab, not a user message]";function Jh(e){let t=e.startsWith(vD);return["<system-reminder>",t?"This note reached you while you worked:":"The user sent the following message:",e,"",t?"Take it into account and continue with your tasks.":"Please address this message and continue with your tasks.","</system-reminder>"].join(`
1469
+ `)}i(Jh,"raisedMidTurn");var xD=/\bto=functions\.|^\s*functions\.[A-Za-z_]+\s*[({]/m;function Kh(e){let t=e.filter(s=>s.type==="text"),n=t.filter(s=>(s.text??"").trim().length>0&&!xD.test(s.text??"")),o=n.length>0?n[n.length-1]:void 0;return{drop:t.filter(s=>s!==o).map(s=>s.id),answered:o!==void 0}}i(Kh,"asideTextToDrop");function Xh(e){let t=e.filter(s=>!(s.info.role==="assistant"&&s.info.aside)&&!(s.info.role==="user"&&s.info.quiet)),n=Ze.latest(t),o=n.user?void 0:Ze.latest(e.filter(s=>s.info.role==="user")).user;return{lastUser:n.user??o,lastAssistant:n.assistant,lastFinished:n.finished,tasks:n.tasks}}i(Xh,"scanForLoop");import Qh from"fs";import SD from"path";var Ia={info:i((e,t)=>process.stderr.write(`level=INFO service=session.pause message=${JSON.stringify(e)} ${JSON.stringify(t??{})}
1470
1470
  `),"info"),warn:i((e,t)=>process.stderr.write(`level=WARN service=session.pause message=${JSON.stringify(e)} ${JSON.stringify(t??{})}
1471
- `),"warn")},Zh=bD.join(Se.Path.state,"pause.json"),Uo=!1,Fo=new Set;try{let e=JSON.parse(Qh.readFileSync(Zh,"utf8"));Uo=e?.paused===!0;for(let t of Array.isArray(e?.waiting)?e.waiting:[])typeof t=="string"&&Fo.add(t)}catch{}function dd(){try{Qh.writeFileSync(Zh,JSON.stringify({paused:Uo,waiting:[...Fo]}))}catch(e){Ia.warn("could not save the pause state",{error:String(e)})}}i(dd,"save");var Bo;(a=>{function e(){return Uo}a.isPaused=e,i(e,"isPaused");function t(l){Fo.has(l)||(Fo.add(l),Ia.info("turn held while paused",{sessionID:l}),dd())}a.hold=t,i(t,"hold");function n(){Uo||(Uo=!0,Ia.info("paused"),dd())}a.pause=n,i(n,"pause");function o(){let l=[...Fo];return Uo=!1,Fo.clear(),Ia.info("resumed",{waiting:l.length}),dd(),l}a.resume=o,i(o,"resume");function s(){return{paused:Uo,waiting:[...Fo]}}a.state=s,i(s,"state")})(Bo||={});globalThis.AI_SDK_LOG_WARNINGS=!1;var xD=c.decodeUnknownExit(dt.Info),SD=c.decodeUnknownExit(dt.Part),tg=10*1024*1024,ID=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),kD=`Use this tool to return your final response in the requested structured format.
1471
+ `),"warn")},Zh=SD.join(Se.Path.state,"pause.json"),Uo=!1,Fo=new Set;try{let e=JSON.parse(Qh.readFileSync(Zh,"utf8"));Uo=e?.paused===!0;for(let t of Array.isArray(e?.waiting)?e.waiting:[])typeof t=="string"&&Fo.add(t)}catch{}function dd(){try{Qh.writeFileSync(Zh,JSON.stringify({paused:Uo,waiting:[...Fo]}))}catch(e){Ia.warn("could not save the pause state",{error:String(e)})}}i(dd,"save");var Bo;(a=>{function e(){return Uo}a.isPaused=e,i(e,"isPaused");function t(l){Fo.has(l)||(Fo.add(l),Ia.info("turn held while paused",{sessionID:l}),dd())}a.hold=t,i(t,"hold");function n(){Uo||(Uo=!0,Ia.info("paused"),dd())}a.pause=n,i(n,"pause");function o(){let l=[...Fo];return Uo=!1,Fo.clear(),Ia.info("resumed",{waiting:l.length}),dd(),l}a.resume=o,i(o,"resume");function s(){return{paused:Uo,waiting:[...Fo]}}a.state=s,i(s,"state")})(Bo||={});globalThis.AI_SDK_LOG_WARNINGS=!1;var DD=c.decodeUnknownExit(dt.Info),ED=c.decodeUnknownExit(dt.Part),tg=10*1024*1024,TD=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),PD=`Use this tool to return your final response in the requested structured format.
1472
1472
 
1473
1473
  IMPORTANT:
1474
1474
  - You MUST call this tool exactly once at the end of your response
1475
1475
  - The input must be valid JSON matching the required schema
1476
1476
  - Complete all necessary research and tool calls BEFORE calling this tool
1477
- - This tool provides your final answer - no further actions are taken after calling it`,DD="IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.";function ED(e){let t=e.replace(/\s/g,""),n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-n)}i(ED,"mcpResourceBase64Size");function pd(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}i(pd,"formatMcpResourceBytes");function ng(e){return e.state.status==="error"&&e.state.metadata?.interrupted===!0}i(ng,"isOrphanedInterruptedTool");var Fr=class extends Re.Service()("@opencode/SessionPrompt"){static{i(this,"Service")}},TD=Te.effect(Fr,r.gen(function*(){let e=yield*ln.Service,t=yield*me.Service,n=yield*Ft.Service,o=yield*yt.Service,s=yield*jn.Service,a=yield*gr.Service,l=yield*pt.Service,d=yield*yi.Service,p=yield*Oe.Service,f=yield*Ke.Service,u=yield*Ae.Service,g=yield*cn.Service,y=yield*ft.Service,b=yield*$n.Service,S=yield*wo.Service,T=yield*bn.Service,m=yield*Wd.ChildProcessSpawner,h=yield*Dt.Scope,k=yield*En.Service,w=yield*Ln.Service,I=yield*br.Service,P=yield*un.Service,x=yield*eo.Service,A=yield*dn.Service,C=yield*De.Service,$=yield*Be.Service,j=yield*Qe.Service,{db:z}=j,ie=r.fn("SessionPrompt.ops")(function*(){return{cancel:i(E=>L(E),"cancel"),resolvePromptParts:i(E=>M(E),"resolvePromptParts"),prompt:i(E=>q(E).pipe(r.catch(r.die)),"prompt")}}),L=r.fn("SessionPrompt.cancel")(function*(E){yield*r.logInfo("cancel",{"session.id":E}),yield*w.cancel(E)}),V=new Map,D=r.fn("SessionPrompt.stopForPause")(function*(){let E=yield*w.busy();for(let Y of E)Bo.hold(Y);return yield*r.forEach(E,Y=>w.cancel(Y),{concurrency:"unbounded",discard:!0}),E}),M=r.fn("SessionPrompt.resolvePromptParts")(function*(E){let Y=yield*G.context,ve=[{type:"text",text:E}],de=Xa.files(E),te=new Set;return yield*r.forEach(de,r.fnUntraced(function*(oe){let ae=oe[1];if(!ae||te.has(ae))return;te.add(ae);let Q=ae.startsWith("~/")?eg.join(wD.homedir(),ae.slice(2)):eg.resolve(Y.worktree,ae),je=yield*u.stat(Q).pipe(r.option);if(xn.isNone(je)){let Ne=yield*n.get(ae);Ne&&ve.push({type:"agent",name:Ne.name});return}let Je=je.value;ve.push({type:"file",url:vD(Q).href,filename:ae,mime:Je.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:"unbounded",discard:!0}),ve}),_=r.fn("SessionPrompt.ensureTitle")(function*(E){if(E.session.parentID||!me.isDefaultTitle(E.session.title))return;let Y=i(J=>J.info.role==="user"&&!J.parts.every(v=>"synthetic"in v&&v.synthetic),"real"),ve=E.history.findIndex(Y);if(ve===-1||E.history.filter(Y).length!==1)return;let de=E.history.slice(0,ve+1),te=de[ve];if(!te||te.info.role!=="user")return;let oe=te.info,ae=te.parts.filter(J=>J.type==="subtask"),Q=ae.length>0&&te.parts.every(J=>J.type==="subtask"),je=yield*n.get("title");if(!je)return;let Je=je.model?yield*o.getModel(je.model.providerID,je.model.modelID):(yield*o.getSmallModel(E.providerID))??(yield*o.getModel(E.providerID,E.modelID)),Ne=Q?[{role:"user",content:ae.map(J=>J.prompt).join(`
1477
+ - This tool provides your final answer - no further actions are taken after calling it`,RD="IMPORTANT: The user has requested structured output. You MUST use the StructuredOutput tool to provide your final response. Do NOT respond with plain text - you MUST call the StructuredOutput tool with your answer formatted according to the schema.";function CD(e){let t=e.replace(/\s/g,""),n=t.endsWith("==")?2:t.endsWith("=")?1:0;return Math.max(0,Math.floor(t.length*3/4)-n)}i(CD,"mcpResourceBase64Size");function pd(e){return e<1024?`${e} B`:e<1024*1024?`${Math.ceil(e/1024)} KB`:`${Math.ceil(e/(1024*1024))} MB`}i(pd,"formatMcpResourceBytes");function ng(e){return e.state.status==="error"&&e.state.metadata?.interrupted===!0}i(ng,"isOrphanedInterruptedTool");var Fr=class extends Re.Service()("@opencode/SessionPrompt"){static{i(this,"Service")}},AD=Te.effect(Fr,r.gen(function*(){let e=yield*ln.Service,t=yield*me.Service,n=yield*Ft.Service,o=yield*yt.Service,s=yield*jn.Service,a=yield*gr.Service,l=yield*pt.Service,d=yield*yi.Service,p=yield*Oe.Service,f=yield*Ke.Service,u=yield*Ae.Service,g=yield*cn.Service,y=yield*ft.Service,b=yield*$n.Service,S=yield*wo.Service,T=yield*bn.Service,m=yield*Wd.ChildProcessSpawner,h=yield*Dt.Scope,k=yield*En.Service,w=yield*Ln.Service,I=yield*br.Service,P=yield*un.Service,x=yield*eo.Service,A=yield*dn.Service,C=yield*De.Service,$=yield*Be.Service,j=yield*Qe.Service,{db:z}=j,ie=r.fn("SessionPrompt.ops")(function*(){return{cancel:i(E=>L(E),"cancel"),resolvePromptParts:i(E=>M(E),"resolvePromptParts"),prompt:i(E=>q(E).pipe(r.catch(r.die)),"prompt")}}),L=r.fn("SessionPrompt.cancel")(function*(E){yield*r.logInfo("cancel",{"session.id":E}),yield*w.cancel(E)}),V=new Map,D=r.fn("SessionPrompt.stopForPause")(function*(){let E=yield*w.busy();for(let Y of E)Bo.hold(Y);return yield*r.forEach(E,Y=>w.cancel(Y),{concurrency:"unbounded",discard:!0}),E}),M=r.fn("SessionPrompt.resolvePromptParts")(function*(E){let Y=yield*G.context,ve=[{type:"text",text:E}],de=Xa.files(E),te=new Set;return yield*r.forEach(de,r.fnUntraced(function*(oe){let ae=oe[1];if(!ae||te.has(ae))return;te.add(ae);let Q=ae.startsWith("~/")?eg.join(ID.homedir(),ae.slice(2)):eg.resolve(Y.worktree,ae),je=yield*u.stat(Q).pipe(r.option);if(xn.isNone(je)){let Ne=yield*n.get(ae);Ne&&ve.push({type:"agent",name:Ne.name});return}let Je=je.value;ve.push({type:"file",url:kD(Q).href,filename:ae,mime:Je.type==="Directory"?"application/x-directory":"text/plain"})}),{concurrency:"unbounded",discard:!0}),ve}),_=r.fn("SessionPrompt.ensureTitle")(function*(E){if(E.session.parentID||!me.isDefaultTitle(E.session.title))return;let Y=i(J=>J.info.role==="user"&&!J.parts.every(v=>"synthetic"in v&&v.synthetic),"real"),ve=E.history.findIndex(Y);if(ve===-1||E.history.filter(Y).length!==1)return;let de=E.history.slice(0,ve+1),te=de[ve];if(!te||te.info.role!=="user")return;let oe=te.info,ae=te.parts.filter(J=>J.type==="subtask"),Q=ae.length>0&&te.parts.every(J=>J.type==="subtask"),je=yield*n.get("title");if(!je)return;let Je=je.model?yield*o.getModel(je.model.providerID,je.model.modelID):(yield*o.getSmallModel(E.providerID))??(yield*o.getModel(E.providerID,E.modelID)),Ne=Q?[{role:"user",content:ae.map(J=>J.prompt).join(`
1478
1478
  `)}]:yield*Ze.toModelMessagesEffect(de,Je),xe=(yield*A.stream({agent:je,user:oe,system:[],small:!0,tools:{},model:Je,sessionID:E.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
1479
1479
  `},...Ne]}).pipe(Ud(rt.is.textDelta),Ld(J=>J.text),qd,r.orDie)).replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
1480
1480
  `).map(J=>J.trim()).find(J=>J.length>0);if(!xe)return;let We=xe.length>100?xe.substring(0,97)+"...":xe;yield*t.setTitle({sessionID:E.session.id,title:We}).pipe(r.catchCause(J=>r.logError("failed to generate title",{error:tt.squash(J)})))}),N=r.fn("SessionPrompt.handleSubtask")(function*(E){let{task:Y,model:ve,lastUser:de,sessionID:te,session:oe,msgs:ae}=E,Q=yield*G.context,je=yield*ie(),{task:Je}=yield*b.named(),Ne=Y.model?yield*U(Y.model.providerID,Y.model.modelID,te):ve,He=yield*t.updateMessage({id:at.ascending(),role:"assistant",parentID:de.id,sessionID:te,mode:Y.agent,agent:Y.agent,variant:de.model.variant,path:{cwd:Q.directory,root:Q.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:Ne.id,providerID:Ne.providerID,time:{created:Date.now()}}),xe=yield*t.updatePart({id:Fe.ascending(),messageID:He.id,sessionID:He.sessionID,type:"tool",callID:ld(),tool:_o.id,state:{status:"running",input:{prompt:Y.prompt,description:Y.description,subagent_type:Y.agent,command:Y.command},time:{start:Date.now()}}}),We={prompt:Y.prompt,description:Y.description,subagent_type:Y.agent,command:Y.command};yield*l.trigger("tool.execute.before",{tool:_o.id,sessionID:te,callID:xe.id},{args:We});let J=yield*n.get(Y.agent);if(!J){let le=(yield*n.list()).filter(X=>!X.hidden).map(X=>X.name),ue=le.length?` Available agents: ${le.join(", ")}`:"",K=new kn.Unknown({message:`Agent not found: "${Y.agent}".${ue}`});throw yield*C.publish(me.Event.Error,{sessionID:te,error:K.toObject()}),K}let v,O=new AbortController,F=yield*Je.execute(We,{agent:Y.agent,messageID:He.id,sessionID:te,abort:O.signal,callID:xe.callID,extra:{bypassAgentCheck:!0,promptOps:je},messages:ae,metadata:i(le=>r.gen(function*(){xe=yield*t.updatePart({...xe,type:"tool",state:{...xe.state,...le}})}),"metadata"),ask:i(le=>f.ask({...le,sessionID:te,ruleset:Ke.merge(J.permission,oe.permission??[])}).pipe(r.orDie),"ask")}).pipe(r.catchCause(le=>{let ue=tt.squash(le);return v=ue instanceof Error?ue:new Error(String(ue)),r.logError("subtask execution failed",{error:v,agent:Y.agent,description:Y.description})}),r.onInterrupt(()=>r.gen(function*(){O.abort(),He.finish="tool-calls",He.time.completed=Date.now(),yield*t.updateMessage(He),xe.state.status==="running"&&(yield*t.updatePart({...xe,state:{status:"error",error:"Cancelled",time:{start:xe.state.time.start,end:Date.now()},metadata:xe.state.metadata,input:xe.state.input}}))}))),Z=F?.attachments?.map(le=>({...le,id:Fe.ascending(),sessionID:te,messageID:He.id}));if(yield*l.trigger("tool.execute.after",{tool:_o.id,sessionID:te,callID:xe.id,args:We},F),He.finish="tool-calls",He.time.completed=Date.now(),yield*t.updateMessage(He),F&&xe.state.status==="running"&&(yield*t.updatePart({...xe,state:{status:"completed",input:xe.state.input,title:F.title,metadata:F.metadata,output:F.output,attachments:Z,time:{...xe.state.time,end:Date.now()}}})),F||(yield*t.updatePart({...xe,state:{status:"error",error:v?`Tool execution failed: ${v.message}`:"Tool execution failed",time:{start:xe.state.status==="running"?xe.state.time.start:Date.now(),end:Date.now()},metadata:xe.state.status==="pending"?void 0:xe.state.metadata,input:xe.state.input}})),!Y.command)return;let _e={id:at.ascending(),sessionID:te,role:"user",time:{created:Date.now()},agent:de.agent,model:de.model};yield*t.updateMessage(_e),yield*t.updatePart({id:Fe.ascending(),messageID:_e.id,sessionID:te,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0})}),W=r.fn("SessionPrompt.shellImpl")(function*(E,Y){return yield*r.uninterruptibleMask(ve=>r.gen(function*(){let de=Y?Y.open.pipe(r.asVoid):r.void,{msg:te,part:oe,cwd:ae}=yield*r.gen(function*(){let J=yield*G.context,v=yield*t.get(E.sessionID).pipe(r.orDie);v.revert&&(yield*I.cleanup(v));let O=yield*n.get(E.agent);if(!O){let X=(yield*n.list()).filter(Pe=>!Pe.hidden).map(Pe=>Pe.name),he=X.length?` Available agents: ${X.join(", ")}`:"",ge=new kn.Unknown({message:`Agent not found: "${E.agent}".${he}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:ge.toObject()}),ge}let F=E.model??O.model??(yield*we(E.sessionID)),Z={id:E.messageID??at.ascending(),sessionID:E.sessionID,time:{created:Date.now()},role:"user",agent:E.agent,model:{providerID:F.providerID,modelID:F.modelID}};yield*t.updateMessage(Z);let _e={type:"text",id:Fe.ascending(),messageID:Z.id,sessionID:E.sessionID,text:"The following tool was executed by the user",synthetic:!0};yield*t.updatePart(_e);let le={id:at.ascending(),sessionID:E.sessionID,parentID:Z.id,mode:E.agent,agent:E.agent,cost:0,path:{cwd:J.directory,root:J.worktree},time:{created:Date.now()},role:"assistant",tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:F.modelID,providerID:F.providerID};yield*t.updateMessage(le);let ue=Date.now(),K={type:"tool",id:Fe.ascending(),messageID:le.id,sessionID:E.sessionID,tool:As.ToolID,callID:ld(),state:{status:"running",time:{start:ue},input:{command:E.command}}};return yield*t.updatePart(K),{msg:le,part:K,cwd:J.directory}}).pipe(r.ensuring(de)),Q=yield*p.get(),je=ai.preferred(Q.shell),Je=ai.args(je,E.command,ae),Ne="",He=!1,xe=r.uninterruptible(r.gen(function*(){He&&(Ne+=`
1481
1481
 
1482
1482
  `+["<metadata>","User aborted the command","</metadata>"].join(`
1483
- `));let J=Date.now();te.time.completed||(te.time.completed=J,yield*t.updateMessage(te)),oe.state.status==="running"&&(oe.state={status:"completed",time:{...oe.state.time,end:J},input:oe.state.input,title:"",metadata:{output:Ne},output:Ne},yield*t.updatePart(oe))})),We=yield*ve(r.gen(function*(){let J=yield*l.trigger("shell.env",{cwd:ae,sessionID:E.sessionID,callID:oe.callID},{env:{}}),v=Vn.make(je,Je,{cwd:ae,extendEnv:!0,env:{...J.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),O=yield*m.spawn(v);yield*Js(Bd(O.all),F=>r.gen(function*(){Ne+=F,oe.state.status==="running"&&(oe.state.metadata={output:Ne},yield*t.updatePart(oe))})),yield*O.exitCode}).pipe(r.scoped,r.orDie)).pipe(r.exit);return bt.isFailure(We)&&tt.hasInterrupts(We.cause)&&!tt.hasDies(We.cause)&&(He=!0),yield*xe,bt.isFailure(We)&&!He&&!tt.hasInterruptsOnly(We.cause)?yield*r.failCause(We.cause):{info:te,parts:[oe]}}))}),U=r.fn("SessionPrompt.getModel")(function*(E,Y,ve){let de=yield*o.getModel(E,Y).pipe(r.exit);if(bt.isSuccess(de))return de.value;let te=tt.squash(de.cause);if(yt.ModelNotFoundError.isInstance(te)){let oe=te.suggestions?.length?` Did you mean: ${te.suggestions.join(", ")}?`:"";yield*C.publish(me.Event.Error,{sessionID:ve,error:new kn.Unknown({message:`Model not found: ${te.providerID}/${te.modelID}.${oe}`}).toObject()})}return yield*r.die(te)}),we=r.fnUntraced(function*(E){let Y=yield*z.select({model:Tt.model}).from(Tt).where(St(Tt.id,E)).get().pipe(r.orDie);if(Y?.model)return{providerID:sn.ID.make(Y.model.providerID),modelID:uo.ID.make(Y.model.id),...Y.model.variant&&Y.model.variant!=="default"?{variant:Y.model.variant}:{}};let ve=yield*t.findMessage(E,de=>de.info.role==="user"&&!!de.info.model).pipe(r.orDie);return xn.isSome(ve)&&ve.value.info.role==="user"?ve.value.info.model:yield*o.defaultModel().pipe(r.orDie)}),pe=r.fn("SessionPrompt.createUserMessage")(function*(E){let Y=E.agent?void 0:(yield*t.get(E.sessionID).pipe(r.orElseSucceed(()=>{})))?.agent,ve=E.agent||(Y&&(yield*n.get(Y))?Y:void 0),de=ve?yield*n.get(ve):yield*n.defaultInfo();if(!de){let J=(yield*n.list()).filter(F=>!F.hidden).map(F=>F.name),v=J.length?` Available agents: ${J.join(", ")}`:"",O=new kn.Unknown({message:`Agent not found: "${ve}".${v}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:O.toObject()}),O}let te=E.model??de.model??(yield*we(E.sessionID)),oe=!E.variant&&de.variant?yield*o.getModel(te.providerID,te.modelID).pipe(r.catchIf(yt.ModelNotFoundError.isInstance,()=>r.succeed(void 0))):void 0,ae=E.variant??Xe.nearestVariant(de.variant,Object.keys(oe?.variants??{})),Q={id:E.messageID??at.ascending(),role:"user",sessionID:E.sessionID,time:{created:Date.now()},tools:E.tools,...E.noReply===!0?{quiet:!0}:{},agent:de.name,model:{providerID:te.providerID,modelID:te.modelID,variant:ae},system:E.system,format:E.format},je=yield*t.get(E.sessionID).pipe(r.orDie);(je.agent!==Q.agent||je.model?.providerID!==Q.model.providerID||je.model?.id!==Q.model.modelID||(je.model?.variant==="default"?void 0:je.model?.variant)!==Q.model.variant)&&(yield*t.setAgentModel({sessionID:E.sessionID,agent:Q.agent,model:{id:Q.model.modelID,providerID:Q.model.providerID,variant:Q.model.variant??"default"},time:Q.time.created})),yield*r.addFinalizer(()=>k.clear(Q.id));let Je=i(J=>({...J,id:J.id?Fe.make(J.id):Fe.ascending()}),"assign"),Ne=r.fn("SessionPrompt.resolveUserPart")(function*(J){if(J.type==="file"){if(J.source?.type==="resource"){let{clientName:O,uri:F}=J.source;yield*r.logInfo("mcp resource",{clientName:O,uri:F,mime:J.mime});let Z=[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${J.filename} (${F})`}],_e=yield*g.readResource(O,F).pipe(r.exit);if(bt.isSuccess(_e)){let le=_e.value;if(!le)throw new Error(`Resource not found: ${O}/${F}`);let ue=Array.isArray(le.contents)?le.contents:[le.contents];for(let K of ue)if(!(!K||typeof K!="object")){if("text"in K&&typeof K.text=="string"&&K.text)Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:K.text});else if("blob"in K&&typeof K.blob=="string"&&K.blob){let X="mimeType"in K&&typeof K.mimeType=="string"?K.mimeType:J.mime,he="uri"in K&&typeof K.uri=="string"?K.uri:J.filename,ge=ED(K.blob);if(!ID.has(X)){Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${he??F} (${X}, ${pd(ge)}) is not a supported attachment type]`});continue}if(ge>tg){Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${he??F} (${X}, ${pd(ge)}) exceeds ${pd(tg)}]`});continue}Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource attached: ${he??F} (${X})]`}),Z.push({messageID:Q.id,sessionID:E.sessionID,type:"file",mime:X,filename:he,url:`data:${X};base64,${K.blob}`})}}}else{let le=tt.squash(_e.cause);yield*r.logError("failed to read MCP resource",{error:le,clientName:O,uri:F});let ue=le instanceof Error?le.message:String(le);Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${J.filename}: ${ue}`})}return Z}let v=new URL(J.url);switch(v.protocol){case"data:":if(J.mime==="text/plain")return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:J.filename})}`},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:Bh(J.url)},{...J,messageID:Q.id,sessionID:E.sessionID}];break;case"file:":{yield*r.logInfo("file",{mime:J.mime});let O=ud(J.url),F=(yield*u.isDir(O))?"application/x-directory":J.mime,{read:Z}=yield*b.named(),_e=i((le,ue)=>{let K=new AbortController;return Z.execute(le,{sessionID:E.sessionID,abort:K.signal,agent:E.agent,messageID:Q.id,extra:{bypassCwdCheck:!0,...ue},messages:[],metadata:i(()=>r.void,"metadata"),ask:i(()=>r.void,"ask")}).pipe(r.onInterrupt(()=>r.sync(()=>K.abort())))},"execRead");if(F==="text/plain"){let le,ue,K={start:v.searchParams.get("start"),end:v.searchParams.get("end")};if(K.start!=null){let Pe=J.url.split("?")[0],Ye=parseInt(K.start),wt=K.end?parseInt(K.end):void 0;if(Ye===wt){let zo=yield*y.documentSymbol(Pe).pipe(r.catch(()=>r.succeed([])));for(let Gr of zo){let It;if("range"in Gr?It=Gr.range:"location"in Gr&&(It=Gr.location.range),It?.start?.line&&It?.start?.line===Ye){Ye=It.start.line,wt=It?.end?.line??Ye;break}}}le=Math.max(Ye,1),wt&&(ue=wt-(le-1))}let X={filePath:O,offset:le,limit:ue},he=[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(X)}`}],ge=yield*o.getModel(Q.model.providerID,Q.model.modelID).pipe(r.flatMap(Pe=>_e(X,{model:Pe})),r.exit);if(bt.isSuccess(ge)){let Pe=ge.value;he.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:Pe.output}),Pe.attachments?.length?he.push(...Pe.attachments.map(Ye=>({...Ye,synthetic:!0,filename:Ye.filename??J.filename,messageID:Q.id,sessionID:E.sessionID}))):he.push({...J,mime:F,messageID:Q.id,sessionID:E.sessionID})}else{let Pe=tt.squash(ge.cause);yield*r.logError("failed to read file",{error:Pe,filepath:O});let Ye=Pe instanceof Error?Pe.message:String(Pe);yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:new kn.Unknown({message:Ye}).toObject()}),he.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${O} with the following error: ${Ye}`})}return he}if(F==="application/x-directory"){let le={filePath:O},ue=yield*_e(le).pipe(r.exit);if(bt.isFailure(ue)){let K=tt.squash(ue.cause);yield*r.logError("failed to read directory",{error:K,filepath:O});let X=K instanceof Error?K.message:String(K);return yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:new kn.Unknown({message:X}).toObject()}),[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${O} with the following error: ${X}`}]}return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(le)}`},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:ue.value.output},{...J,mime:F,messageID:Q.id,sessionID:E.sessionID}]}return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${O}"}`},{id:J.id,messageID:Q.id,sessionID:E.sessionID,type:"file",url:`data:${F};base64,`+Buffer.from(yield*u.readFile(O).pipe(r.catch(r.die))).toString("base64"),mime:F,filename:J.filename,source:J.source}]}}}if(J.type==="agent"){let O=Ke.evaluate("task",J.name,de.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...J,messageID:Q.id,sessionID:E.sessionID},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+J.name+O}]}return[{...J,messageID:Q.id,sessionID:E.sessionID}]}),He=yield*r.forEach(E.parts,Ne,{concurrency:"unbounded"}).pipe(r.map(J=>J.flat().map(Je)));yield*l.trigger("chat.message",{sessionID:E.sessionID,agent:E.agent,model:E.model,messageID:E.messageID,variant:E.variant},{message:Q,parts:He});let xe=yield*r.forEach(He,J=>J.type==="file"&&J.mime.startsWith("image/")?T.normalize(J).pipe(r.catchIf(v=>v instanceof bn.ResizerUnavailableError,()=>r.succeed(J))):r.succeed(J)),We=xD(Q,{errors:"all",propertyOrder:"original"});bt.isFailure(We)&&(yield*r.logError("invalid user message before save",{sessionID:E.sessionID,messageID:Q.id,agent:Q.agent,model:Q.model,cause:tt.pretty(We.cause)}));for(let[J,v]of xe.entries()){let O=SD(v,{errors:"all",propertyOrder:"original"});bt.isSuccess(O)||(yield*r.logError("invalid user part before save",{sessionID:E.sessionID,messageID:Q.id,partID:v.id,partType:v.type,index:J,cause:tt.pretty(O.cause),part:v}))}yield*t.updateMessage(Q);for(let J of xe)yield*t.updatePart(J);return{info:Q,parts:xe}},r.scoped),ce=r.fn("SessionPrompt.inFlightTool")(function*(E){let Y=yield*Ze.filterCompactedEffect(E).pipe(r.provideService(Qe.Service,j));for(let ve=Y.length-1;ve>=0;ve--){let de=Y[ve];if(de.info.role!=="assistant"||de.info.aside)continue;let te=de.parts.find(oe=>oe.type==="tool"&&(oe.state.status==="running"||oe.state.status==="pending"));return te&&te.type==="tool"?te.tool:null}return null}),re=["A tool you called is still running and its result has not arrived. The user just wrote to you.","Answer them now, in a sentence or two, from what you already know. You cannot use tools until the run returns, so do not promise to look anything up.","Do not restate at length what you are doing; if their message changes the work, say what you will do once the run returns."].join(" "),R=r.fn("SessionPrompt.aside")(function*(E){let Y=yield*G.context,ve=yield*Ze.filterCompactedEffect(E.sessionID).pipe(r.provideService(Qe.Service,j)),de=yield*U(E.user.model.providerID,E.user.model.modelID,E.sessionID),te=yield*n.get(E.user.agent);if(!te)return null;let oe={id:at.ascending(),parentID:E.user.id,role:"assistant",mode:te.name,agent:te.name,variant:E.user.model.variant,path:{cwd:Y.directory,root:Y.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:de.id,providerID:de.providerID,time:{created:Date.now()},sessionID:E.sessionID,aside:!0};yield*t.updateMessage(oe);let ae=yield*s.create({assistantMessage:oe,sessionID:E.sessionID,model:de}),[Q,je,Je]=yield*r.all([x.environment(de),k.system().pipe(r.orDie),Ze.toModelMessagesEffect(ve,de,{runningToolNote:`[${E.running} is still running. You are answering the user beside it; its result arrives when it finishes.]`})]);yield*r.logInfo("aside",{"session.id":E.sessionID,running:E.running,messageID:oe.id}),yield*ae.process({user:E.user,agent:te,permission:E.session.permission,sessionID:E.sessionID,parentSessionID:E.session.parentID,system:[...Q,...je,re],messages:Je,tools:{},model:de});let Ne=yield*H(E.sessionID);if(Ne.info.id!==oe.id)return Ne;let{drop:He,answered:xe}=Kh(Ne.parts);if(!xe)return yield*r.logWarning("aside wrote no usable answer; the message waits for the run",{"session.id":E.sessionID,messageID:oe.id}),yield*t.removeMessage({sessionID:E.sessionID,messageID:oe.id}),null;for(let We of He)yield*t.removePart({sessionID:E.sessionID,messageID:oe.id,partID:We});return He.length>0?yield*H(E.sessionID):Ne}),q=r.fn("SessionPrompt.prompt")(function*(E){let Y=yield*t.get(E.sessionID).pipe(r.orDie);yield*I.cleanup(Y);let ve=yield*pe(E);yield*t.touch(E.sessionID);let de=[];for(let[ae,Q]of Object.entries(E.tools??{}))de.push({permission:ae,action:Q?"allow":"deny",pattern:"*"});if(de.length>0&&(Y.permission=de,yield*t.setPermission({sessionID:Y.id,permission:de})),E.noReply===!0)return ve;let te=(yield*w.busy()).includes(E.sessionID);if(te&&Yh(ve.parts)){let ae=Ht.endForPerson(E.sessionID),Q=ae?null:yield*ce(E.sessionID);if(V.set(ve.info.id,{sessionID:E.sessionID,at:Date.now(),how:ae?"step ended":Q?`in ${Q}`:"between steps"}),Q){let je=yield*R({sessionID:E.sessionID,session:Y,user:ve.info,running:Q}).pipe(r.catchCause(Je=>r.logWarning("aside failed; the message waits for the run",{"session.id":E.sessionID,cause:String(Je)}).pipe(r.as(null))));if(je)return je}}let oe=yield*Mt({sessionID:E.sessionID});return te&&ec.compareAscending(oe.info.id,ve.info.id)<0&&(oe=yield*Mt({sessionID:E.sessionID})),oe}),H=r.fnUntraced(function*(E){let Y=yield*t.findMessage(E,de=>de.info.role!=="user").pipe(r.orDie);if(xn.isSome(Y))return Y.value;let ve=yield*t.messages({sessionID:E,limit:1}).pipe(r.orDie);if(ve.length>0)return ve[0];throw new Error("Impossible")}),ne=r.fn("SessionPrompt.turnPrefix")(function*(E){let Y=yield*ie(),ve=yield*Os.resolve({...E,promptOps:Y}).pipe(r.provideService(pt.Service,l),r.provideService(Ke.Service,f),r.provideService($n.Service,b),r.provideService(cn.Service,g),r.provideService(wo.Service,S),r.provideService(Be.Service,$)),[de,te,oe,ae]=yield*r.all([x.skills(E.agent),x.environment(E.model),k.system().pipe(r.orDie),x.mcp(E.agent,E.session.permission)]),Q=[...te,...oe,...ae?[ae]:[],...de?[de]:[]];return{tools:ve,system:Q}}),Ue=i((E,Y,ve)=>de=>r.gen(function*(){let te=ve.find(Je=>Je.info.id===de.parentID)?.info;if(!te||te.role!=="user"||te.format?.type==="json_schema")return;let oe=yield*n.get(de.agent);if(!oe)return;let{tools:ae,system:Q}=yield*ne({agent:oe,session:E,model:Y,processor:{message:{id:de.id},updateToolCall:i(()=>r.succeed(void 0),"updateToolCall"),completeToolCall:i(()=>r.void,"completeToolCall")},bypassAgentCheck:!1,messages:ve}),je=Object.fromEntries(Object.entries(ae).map(([Je,Ne])=>[Je,{...Ne,execute:i(async()=>"Not run: this step only writes the summary.","execute")}]));return{agent:oe,user:te,system:Q,tools:je,permission:E.permission,parentSessionID:E.parentID}}).pipe(r.catchCause(te=>r.logWarning("compaction: the session's prefix could not be rebuilt; summarizing without it",{"session.id":E.id,cause:String(te).slice(0,500)}).pipe(r.as(void 0)))),"compactionPrefix"),ot=r.fn("SessionPrompt.run")(function*(E){let Y=yield*G.context,ve,de=0,te=yield*t.get(E).pipe(r.orDie);for(;;){if(Bo.isPaused()){Bo.hold(E);break}yield*e.set(E,{type:"busy"}),yield*r.logInfo("loop",{"session.id":E,step:de});let oe=yield*Ze.filterCompactedEffect(E).pipe(r.provideService(Qe.Service,j)),{lastUser:ae,lastAssistant:Q,lastFinished:je,tasks:Je}=Xh(oe);if(!ae)throw new Error("No user message found in stream. This should never happen.");let Ne=oe.findLast(X=>X.info.role==="assistant"&&X.info.id===Q?.id),He=Ne?.parts.some(X=>X.type==="tool"&&!X.metadata?.providerExecuted&&!ng(X))??!1;if(Q?.finish&&!["tool-calls","unknown"].includes(Q.finish)&&!He&&Q.parentID===ae.id){let X=Ne?.parts.find(he=>he.type==="tool"&&ng(he));X&&(yield*r.logWarning("loop exit with orphaned interrupted tool",{"session.id":E,messageID:Q.id,tool:X.tool,callID:X.callID})),yield*r.logInfo("exiting loop",{"session.id":E});break}de++,de===1&&(yield*_({session:te,modelID:ae.model.modelID,providerID:ae.model.providerID,history:oe}).pipe(r.ignore,r.forkIn(h)));let xe=yield*U(ae.model.providerID,ae.model.modelID,E),We=Je.pop();if(We?.type==="subtask"){yield*N({task:We,model:xe,lastUser:ae,sessionID:E,session:te,msgs:oe});continue}if(We?.type==="compaction"){if((yield*a.process({messages:oe,parentID:ae.id,sessionID:E,auto:We.auto,overflow:We.overflow,prefix:Ue(te,xe,oe)}))==="stop")break;continue}if(je&&je.summary!==!0&&(yield*a.isOverflow({tokens:je.tokens,model:xe}))){yield*a.create({sessionID:E,agent:ae.agent,model:ae.model,auto:!0});continue}let J=yield*n.get(ae.agent);if(!J){let X=(yield*n.list()).filter(Pe=>!Pe.hidden).map(Pe=>Pe.name),he=X.length?` Available agents: ${X.join(", ")}`:"",ge=new kn.Unknown({message:`Agent not found: "${ae.agent}".${he}`});throw yield*C.publish(me.Event.Error,{sessionID:E,error:ge.toObject()}),ge}let v=J.steps??1/0,O=de>=v;oe=yield*Ms.apply({messages:oe,agent:J,session:te}).pipe(r.provideService(Be.Service,$),r.provideService(Ae.Service,u),r.provideService(me.Service,t));let F={id:at.ascending(),parentID:ae.id,role:"assistant",mode:J.name,agent:J.name,variant:ae.model.variant,path:{cwd:Y.directory,root:Y.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:xe.id,providerID:xe.providerID,time:{created:Date.now()},sessionID:E};yield*t.updateMessage(F);for(let[X,he]of V)he.sessionID===E&&(V.delete(X),yield*r.logWarning("person message read",{"session.id":E,messageID:X,how:he.how,waitedMs:Date.now()-he.at}));let Z=Promise.withResolvers(),_e=Ht.open(E,()=>Z.resolve()),le=r.gen(function*(){F.time.completed||(F.error??=Ze.fromError(new DOMException("Aborted","AbortError"),{providerID:F.providerID,aborted:!0}),F.time.completed=Date.now(),yield*t.updateMessage(F))}),ue=yield*s.create({assistantMessage:F,sessionID:E,model:xe,preempt:r.promise(()=>Z.promise)}).pipe(r.onInterrupt(()=>le));if((yield*r.gen(function*(){let he=oe.findLast(It=>It.info.role==="user")?.parts.some(It=>It.type==="agent")??!1,{tools:ge,system:Pe}=yield*ne({agent:J,session:te,model:xe,processor:ue,bypassAgentCheck:he,messages:oe,gate:_e});if(ae.format?.type==="json_schema"&&(ge.StructuredOutput=sg({schema:ae.format.schema,onSuccess(It){ve=It}})),de===1&&(yield*P.summarize({sessionID:E,messageID:ae.id}).pipe(r.ignore,r.forkIn(h))),de>1&&je){let It=new Set(oe.filter(_t=>_t.info.role==="assistant"&&_t.info.aside).map(_t=>_t.info.parentID));for(let _t of oe)if(!(_t.info.role!=="user"||ec.compareAscending(_t.info.id,je.id)<=0)&&!It.has(_t.info.id))for(let vn of _t.parts)vn.type!=="text"||vn.ignored||vn.synthetic||vn.text.trim()&&(vn.text=Jh(vn.text))}yield*l.trigger("experimental.chat.messages.transform",{},{messages:oe});let Ye=yield*Ze.toModelMessagesEffect(oe,xe),wt=ae.format??{type:"text"};wt.type==="json_schema"&&Pe.push(DD);let zo=yield*ue.process({user:ae,agent:J,permission:te.permission,sessionID:E,parentSessionID:te.parentID,system:Pe,messages:[...Ye,...O?[{role:"assistant",content:Ou}]:[]],tools:ge,model:xe,toolChoice:wt.type==="json_schema"?"required":void 0,storeSystem:st.on()?It=>r.gen(function*(){let _t=st.newestStored(oe),vn=oe.at(-1)?.info.id;if(!_t||!vn)return;let Aa=_t.value.system?.at(-1);if(Aa&&Aa.after===vn&&Aa.text===It)return;let Ig=st.withSystem(_t.value,{after:vn,text:It});_t.part.metadata={..._t.part.metadata,[st.METADATA_KEY]:Ig},yield*t.updatePart(_t.part)}):void 0});if(ve!==void 0)return ue.message.structured=ve,ue.message.finish=ue.message.finish??"stop",yield*t.updateMessage(ue.message),"break";if(ue.message.finish&&!["tool-calls","unknown"].includes(ue.message.finish)&&!ue.message.error){if(ue.message.finish==="content-filter")return ue.message.error=new dt.ContentFilterError({message:"The response was blocked by the provider's content filter"}).toObject(),yield*t.updateMessage(ue.message),yield*C.publish(me.Event.Error,{sessionID:E,error:ue.message.error}),"break";if(wt.type==="json_schema")return ue.message.error=new dt.StructuredOutputError({message:"Model did not produce structured output",retries:0}).toObject(),yield*t.updateMessage(ue.message),"break"}return zo==="stop"?"break":(zo==="compact"&&(yield*a.create({sessionID:E,agent:ae.agent,model:ae.model,auto:!0,overflow:!ue.message.finish})),"continue")}).pipe(r.ensuring(r.sync(()=>Ht.close(E,_e))),r.ensuring(k.clear(ue.message.id)),r.onInterrupt(()=>le)))==="break")break}return yield*a.prune({sessionID:E}).pipe(r.ignore,r.forkIn(h)),yield*H(E)}),Mt=r.fn("SessionPrompt.loop")(function*(E){return Bo.isPaused()?(Bo.hold(E.sessionID),yield*H(E.sessionID)):yield*w.ensureRunning(E.sessionID,H(E.sessionID),ot(E.sessionID))}),et=r.fn("SessionPrompt.shell")(function*(E){let Y=yield*Cd.make();return yield*w.startShell(E.sessionID,H(E.sessionID),W(E,Y),Y)}),Pn=r.fn("SessionPrompt.command")(function*(E){yield*r.logInfo("command",{"session.id":E.sessionID,command:E.command,agent:E.agent});let Y=yield*d.get(E.command);if(!Y){let K=(yield*d.list()).map(ge=>ge.name),X=K.length?` Available commands: ${K.join(", ")}`:"",he=new kn.Unknown({message:`Command not found: "${E.command}".${X}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:he.toObject()}),he}let ve=Y.agent??E.agent,te=(E.arguments.match(MD)??[]).map(K=>K.replace(_D,"")),oe=yield*r.promise(async()=>Y.template),ae=oe.match(og)??[],Q=0;for(let K of ae){let X=Number(K.slice(1));X>Q&&(Q=X)}let je=oe.replaceAll(og,(K,X)=>{let he=Number(X),ge=he-1;return ge>=te.length?"":he===Q?te.slice(ge).join(" "):te[ge]}),Je=oe.includes("$ARGUMENTS"),Ne=je.replaceAll("$ARGUMENTS",E.arguments);ae.length===0&&!Je&&E.arguments.trim()&&(Ne=Ne+`
1483
+ `));let J=Date.now();te.time.completed||(te.time.completed=J,yield*t.updateMessage(te)),oe.state.status==="running"&&(oe.state={status:"completed",time:{...oe.state.time,end:J},input:oe.state.input,title:"",metadata:{output:Ne},output:Ne},yield*t.updatePart(oe))})),We=yield*ve(r.gen(function*(){let J=yield*l.trigger("shell.env",{cwd:ae,sessionID:E.sessionID,callID:oe.callID},{env:{}}),v=Vn.make(je,Je,{cwd:ae,extendEnv:!0,env:{...J.env,TERM:"dumb"},stdin:"ignore",forceKillAfter:"3 seconds"}),O=yield*m.spawn(v);yield*Js(Bd(O.all),F=>r.gen(function*(){Ne+=F,oe.state.status==="running"&&(oe.state.metadata={output:Ne},yield*t.updatePart(oe))})),yield*O.exitCode}).pipe(r.scoped,r.orDie)).pipe(r.exit);return bt.isFailure(We)&&tt.hasInterrupts(We.cause)&&!tt.hasDies(We.cause)&&(He=!0),yield*xe,bt.isFailure(We)&&!He&&!tt.hasInterruptsOnly(We.cause)?yield*r.failCause(We.cause):{info:te,parts:[oe]}}))}),U=r.fn("SessionPrompt.getModel")(function*(E,Y,ve){let de=yield*o.getModel(E,Y).pipe(r.exit);if(bt.isSuccess(de))return de.value;let te=tt.squash(de.cause);if(yt.ModelNotFoundError.isInstance(te)){let oe=te.suggestions?.length?` Did you mean: ${te.suggestions.join(", ")}?`:"";yield*C.publish(me.Event.Error,{sessionID:ve,error:new kn.Unknown({message:`Model not found: ${te.providerID}/${te.modelID}.${oe}`}).toObject()})}return yield*r.die(te)}),we=r.fnUntraced(function*(E){let Y=yield*z.select({model:Tt.model}).from(Tt).where(St(Tt.id,E)).get().pipe(r.orDie);if(Y?.model)return{providerID:sn.ID.make(Y.model.providerID),modelID:uo.ID.make(Y.model.id),...Y.model.variant&&Y.model.variant!=="default"?{variant:Y.model.variant}:{}};let ve=yield*t.findMessage(E,de=>de.info.role==="user"&&!!de.info.model).pipe(r.orDie);return xn.isSome(ve)&&ve.value.info.role==="user"?ve.value.info.model:yield*o.defaultModel().pipe(r.orDie)}),pe=r.fn("SessionPrompt.createUserMessage")(function*(E){let Y=E.agent?void 0:(yield*t.get(E.sessionID).pipe(r.orElseSucceed(()=>{})))?.agent,ve=E.agent||(Y&&(yield*n.get(Y))?Y:void 0),de=ve?yield*n.get(ve):yield*n.defaultInfo();if(!de){let J=(yield*n.list()).filter(F=>!F.hidden).map(F=>F.name),v=J.length?` Available agents: ${J.join(", ")}`:"",O=new kn.Unknown({message:`Agent not found: "${ve}".${v}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:O.toObject()}),O}let te=E.model??de.model??(yield*we(E.sessionID)),oe=!E.variant&&de.variant?yield*o.getModel(te.providerID,te.modelID).pipe(r.catchIf(yt.ModelNotFoundError.isInstance,()=>r.succeed(void 0))):void 0,ae=E.variant??Xe.nearestVariant(de.variant,Object.keys(oe?.variants??{})),Q={id:E.messageID??at.ascending(),role:"user",sessionID:E.sessionID,time:{created:Date.now()},tools:E.tools,...E.noReply===!0?{quiet:!0}:{},agent:de.name,model:{providerID:te.providerID,modelID:te.modelID,variant:ae},system:E.system,format:E.format},je=yield*t.get(E.sessionID).pipe(r.orDie);(je.agent!==Q.agent||je.model?.providerID!==Q.model.providerID||je.model?.id!==Q.model.modelID||(je.model?.variant==="default"?void 0:je.model?.variant)!==Q.model.variant)&&(yield*t.setAgentModel({sessionID:E.sessionID,agent:Q.agent,model:{id:Q.model.modelID,providerID:Q.model.providerID,variant:Q.model.variant??"default"},time:Q.time.created})),yield*r.addFinalizer(()=>k.clear(Q.id));let Je=i(J=>({...J,id:J.id?Fe.make(J.id):Fe.ascending()}),"assign"),Ne=r.fn("SessionPrompt.resolveUserPart")(function*(J){if(J.type==="file"){if(J.source?.type==="resource"){let{clientName:O,uri:F}=J.source;yield*r.logInfo("mcp resource",{clientName:O,uri:F,mime:J.mime});let Z=[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Reading MCP resource: ${J.filename} (${F})`}],_e=yield*g.readResource(O,F).pipe(r.exit);if(bt.isSuccess(_e)){let le=_e.value;if(!le)throw new Error(`Resource not found: ${O}/${F}`);let ue=Array.isArray(le.contents)?le.contents:[le.contents];for(let K of ue)if(!(!K||typeof K!="object")){if("text"in K&&typeof K.text=="string"&&K.text)Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:K.text});else if("blob"in K&&typeof K.blob=="string"&&K.blob){let X="mimeType"in K&&typeof K.mimeType=="string"?K.mimeType:J.mime,he="uri"in K&&typeof K.uri=="string"?K.uri:J.filename,ge=CD(K.blob);if(!TD.has(X)){Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${he??F} (${X}, ${pd(ge)}) is not a supported attachment type]`});continue}if(ge>tg){Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource omitted: ${he??F} (${X}, ${pd(ge)}) exceeds ${pd(tg)}]`});continue}Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`[Binary MCP resource attached: ${he??F} (${X})]`}),Z.push({messageID:Q.id,sessionID:E.sessionID,type:"file",mime:X,filename:he,url:`data:${X};base64,${K.blob}`})}}}else{let le=tt.squash(_e.cause);yield*r.logError("failed to read MCP resource",{error:le,clientName:O,uri:F});let ue=le instanceof Error?le.message:String(le);Z.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Failed to read MCP resource ${J.filename}: ${ue}`})}return Z}let v=new URL(J.url);switch(v.protocol){case"data:":if(J.mime==="text/plain")return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:J.filename})}`},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:Bh(J.url)},{...J,messageID:Q.id,sessionID:E.sessionID}];break;case"file:":{yield*r.logInfo("file",{mime:J.mime});let O=ud(J.url),F=(yield*u.isDir(O))?"application/x-directory":J.mime,{read:Z}=yield*b.named(),_e=i((le,ue)=>{let K=new AbortController;return Z.execute(le,{sessionID:E.sessionID,abort:K.signal,agent:E.agent,messageID:Q.id,extra:{bypassCwdCheck:!0,...ue},messages:[],metadata:i(()=>r.void,"metadata"),ask:i(()=>r.void,"ask")}).pipe(r.onInterrupt(()=>r.sync(()=>K.abort())))},"execRead");if(F==="text/plain"){let le,ue,K={start:v.searchParams.get("start"),end:v.searchParams.get("end")};if(K.start!=null){let Pe=J.url.split("?")[0],Ye=parseInt(K.start),wt=K.end?parseInt(K.end):void 0;if(Ye===wt){let zo=yield*y.documentSymbol(Pe).pipe(r.catch(()=>r.succeed([])));for(let Gr of zo){let It;if("range"in Gr?It=Gr.range:"location"in Gr&&(It=Gr.location.range),It?.start?.line&&It?.start?.line===Ye){Ye=It.start.line,wt=It?.end?.line??Ye;break}}}le=Math.max(Ye,1),wt&&(ue=wt-(le-1))}let X={filePath:O,offset:le,limit:ue},he=[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(X)}`}],ge=yield*o.getModel(Q.model.providerID,Q.model.modelID).pipe(r.flatMap(Pe=>_e(X,{model:Pe})),r.exit);if(bt.isSuccess(ge)){let Pe=ge.value;he.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:Pe.output}),Pe.attachments?.length?he.push(...Pe.attachments.map(Ye=>({...Ye,synthetic:!0,filename:Ye.filename??J.filename,messageID:Q.id,sessionID:E.sessionID}))):he.push({...J,mime:F,messageID:Q.id,sessionID:E.sessionID})}else{let Pe=tt.squash(ge.cause);yield*r.logError("failed to read file",{error:Pe,filepath:O});let Ye=Pe instanceof Error?Pe.message:String(Pe);yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:new kn.Unknown({message:Ye}).toObject()}),he.push({messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${O} with the following error: ${Ye}`})}return he}if(F==="application/x-directory"){let le={filePath:O},ue=yield*_e(le).pipe(r.exit);if(bt.isFailure(ue)){let K=tt.squash(ue.cause);yield*r.logError("failed to read directory",{error:K,filepath:O});let X=K instanceof Error?K.message:String(K);return yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:new kn.Unknown({message:X}).toObject()}),[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Read tool failed to read ${O} with the following error: ${X}`}]}return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(le)}`},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:ue.value.output},{...J,mime:F,messageID:Q.id,sessionID:E.sessionID}]}return[{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:`Called the Read tool with the following input: {"filePath":"${O}"}`},{id:J.id,messageID:Q.id,sessionID:E.sessionID,type:"file",url:`data:${F};base64,`+Buffer.from(yield*u.readFile(O).pipe(r.catch(r.die))).toString("base64"),mime:F,filename:J.filename,source:J.source}]}}}if(J.type==="agent"){let O=Ke.evaluate("task",J.name,de.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return[{...J,messageID:Q.id,sessionID:E.sessionID},{messageID:Q.id,sessionID:E.sessionID,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+J.name+O}]}return[{...J,messageID:Q.id,sessionID:E.sessionID}]}),He=yield*r.forEach(E.parts,Ne,{concurrency:"unbounded"}).pipe(r.map(J=>J.flat().map(Je)));yield*l.trigger("chat.message",{sessionID:E.sessionID,agent:E.agent,model:E.model,messageID:E.messageID,variant:E.variant},{message:Q,parts:He});let xe=yield*r.forEach(He,J=>J.type==="file"&&J.mime.startsWith("image/")?T.normalize(J).pipe(r.catchIf(v=>v instanceof bn.ResizerUnavailableError,()=>r.succeed(J))):r.succeed(J)),We=DD(Q,{errors:"all",propertyOrder:"original"});bt.isFailure(We)&&(yield*r.logError("invalid user message before save",{sessionID:E.sessionID,messageID:Q.id,agent:Q.agent,model:Q.model,cause:tt.pretty(We.cause)}));for(let[J,v]of xe.entries()){let O=ED(v,{errors:"all",propertyOrder:"original"});bt.isSuccess(O)||(yield*r.logError("invalid user part before save",{sessionID:E.sessionID,messageID:Q.id,partID:v.id,partType:v.type,index:J,cause:tt.pretty(O.cause),part:v}))}yield*t.updateMessage(Q);for(let J of xe)yield*t.updatePart(J);return{info:Q,parts:xe}},r.scoped),ce=r.fn("SessionPrompt.inFlightTool")(function*(E){let Y=yield*Ze.filterCompactedEffect(E).pipe(r.provideService(Qe.Service,j));for(let ve=Y.length-1;ve>=0;ve--){let de=Y[ve];if(de.info.role!=="assistant"||de.info.aside)continue;let te=de.parts.find(oe=>oe.type==="tool"&&(oe.state.status==="running"||oe.state.status==="pending"));return te&&te.type==="tool"?te.tool:null}return null}),re=["A tool you called is still running and its result has not arrived. The user just wrote to you.","Answer them now, in a sentence or two, from what you already know. You cannot use tools until the run returns, so do not promise to look anything up.","Do not restate at length what you are doing; if their message changes the work, say what you will do once the run returns."].join(" "),R=r.fn("SessionPrompt.aside")(function*(E){let Y=yield*G.context,ve=yield*Ze.filterCompactedEffect(E.sessionID).pipe(r.provideService(Qe.Service,j)),de=yield*U(E.user.model.providerID,E.user.model.modelID,E.sessionID),te=yield*n.get(E.user.agent);if(!te)return null;let oe={id:at.ascending(),parentID:E.user.id,role:"assistant",mode:te.name,agent:te.name,variant:E.user.model.variant,path:{cwd:Y.directory,root:Y.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:de.id,providerID:de.providerID,time:{created:Date.now()},sessionID:E.sessionID,aside:!0};yield*t.updateMessage(oe);let ae=yield*s.create({assistantMessage:oe,sessionID:E.sessionID,model:de}),[Q,je,Je]=yield*r.all([x.environment(de),k.system().pipe(r.orDie),Ze.toModelMessagesEffect(ve,de,{runningToolNote:`[${E.running} is still running. You are answering the user beside it; its result arrives when it finishes.]`})]);yield*r.logInfo("aside",{"session.id":E.sessionID,running:E.running,messageID:oe.id}),yield*ae.process({user:E.user,agent:te,permission:E.session.permission,sessionID:E.sessionID,parentSessionID:E.session.parentID,system:[...Q,...je,re],messages:Je,tools:{},model:de});let Ne=yield*H(E.sessionID);if(Ne.info.id!==oe.id)return Ne;let{drop:He,answered:xe}=Kh(Ne.parts);if(!xe)return yield*r.logWarning("aside wrote no usable answer; the message waits for the run",{"session.id":E.sessionID,messageID:oe.id}),yield*t.removeMessage({sessionID:E.sessionID,messageID:oe.id}),null;for(let We of He)yield*t.removePart({sessionID:E.sessionID,messageID:oe.id,partID:We});return He.length>0?yield*H(E.sessionID):Ne}),q=r.fn("SessionPrompt.prompt")(function*(E){let Y=yield*t.get(E.sessionID).pipe(r.orDie);yield*I.cleanup(Y);let ve=yield*pe(E);yield*t.touch(E.sessionID);let de=[];for(let[ae,Q]of Object.entries(E.tools??{}))de.push({permission:ae,action:Q?"allow":"deny",pattern:"*"});if(de.length>0&&(Y.permission=de,yield*t.setPermission({sessionID:Y.id,permission:de})),E.noReply===!0)return ve;let te=(yield*w.busy()).includes(E.sessionID);if(te&&Yh(ve.parts)){let ae=Ht.endForPerson(E.sessionID),Q=ae?null:yield*ce(E.sessionID);if(V.set(ve.info.id,{sessionID:E.sessionID,at:Date.now(),how:ae?"step ended":Q?`in ${Q}`:"between steps"}),Q){let je=yield*R({sessionID:E.sessionID,session:Y,user:ve.info,running:Q}).pipe(r.catchCause(Je=>r.logWarning("aside failed; the message waits for the run",{"session.id":E.sessionID,cause:String(Je)}).pipe(r.as(null))));if(je)return je}}let oe=yield*Mt({sessionID:E.sessionID});return te&&ec.compareAscending(oe.info.id,ve.info.id)<0&&(oe=yield*Mt({sessionID:E.sessionID})),oe}),H=r.fnUntraced(function*(E){let Y=yield*t.findMessage(E,de=>de.info.role!=="user").pipe(r.orDie);if(xn.isSome(Y))return Y.value;let ve=yield*t.messages({sessionID:E,limit:1}).pipe(r.orDie);if(ve.length>0)return ve[0];throw new Error("Impossible")}),ne=r.fn("SessionPrompt.turnPrefix")(function*(E){let Y=yield*ie(),ve=yield*Os.resolve({...E,promptOps:Y}).pipe(r.provideService(pt.Service,l),r.provideService(Ke.Service,f),r.provideService($n.Service,b),r.provideService(cn.Service,g),r.provideService(wo.Service,S),r.provideService(Be.Service,$)),[de,te,oe,ae]=yield*r.all([x.skills(E.agent),x.environment(E.model),k.system().pipe(r.orDie),x.mcp(E.agent,E.session.permission)]),Q=[...te,...oe,...ae?[ae]:[],...de?[de]:[]];return{tools:ve,system:Q}}),Ue=i((E,Y,ve)=>de=>r.gen(function*(){let te=ve.find(Je=>Je.info.id===de.parentID)?.info;if(!te||te.role!=="user"||te.format?.type==="json_schema")return;let oe=yield*n.get(de.agent);if(!oe)return;let{tools:ae,system:Q}=yield*ne({agent:oe,session:E,model:Y,processor:{message:{id:de.id},updateToolCall:i(()=>r.succeed(void 0),"updateToolCall"),completeToolCall:i(()=>r.void,"completeToolCall")},bypassAgentCheck:!1,messages:ve}),je=Object.fromEntries(Object.entries(ae).map(([Je,Ne])=>[Je,{...Ne,execute:i(async()=>"Not run: this step only writes the summary.","execute")}]));return{agent:oe,user:te,system:Q,tools:je,permission:E.permission,parentSessionID:E.parentID}}).pipe(r.catchCause(te=>r.logWarning("compaction: the session's prefix could not be rebuilt; summarizing without it",{"session.id":E.id,cause:String(te).slice(0,500)}).pipe(r.as(void 0)))),"compactionPrefix"),ot=r.fn("SessionPrompt.run")(function*(E){let Y=yield*G.context,ve,de=0,te=yield*t.get(E).pipe(r.orDie);for(;;){if(Bo.isPaused()){Bo.hold(E);break}yield*e.set(E,{type:"busy"}),yield*r.logInfo("loop",{"session.id":E,step:de});let oe=yield*Ze.filterCompactedEffect(E).pipe(r.provideService(Qe.Service,j)),{lastUser:ae,lastAssistant:Q,lastFinished:je,tasks:Je}=Xh(oe);if(!ae)throw new Error("No user message found in stream. This should never happen.");let Ne=oe.findLast(X=>X.info.role==="assistant"&&X.info.id===Q?.id),He=Ne?.parts.some(X=>X.type==="tool"&&!X.metadata?.providerExecuted&&!ng(X))??!1;if(Q?.finish&&!["tool-calls","unknown"].includes(Q.finish)&&!He&&Q.parentID===ae.id){let X=Ne?.parts.find(he=>he.type==="tool"&&ng(he));X&&(yield*r.logWarning("loop exit with orphaned interrupted tool",{"session.id":E,messageID:Q.id,tool:X.tool,callID:X.callID})),yield*r.logInfo("exiting loop",{"session.id":E});break}de++,de===1&&(yield*_({session:te,modelID:ae.model.modelID,providerID:ae.model.providerID,history:oe}).pipe(r.ignore,r.forkIn(h)));let xe=yield*U(ae.model.providerID,ae.model.modelID,E),We=Je.pop();if(We?.type==="subtask"){yield*N({task:We,model:xe,lastUser:ae,sessionID:E,session:te,msgs:oe});continue}if(We?.type==="compaction"){if((yield*a.process({messages:oe,parentID:ae.id,sessionID:E,auto:We.auto,overflow:We.overflow,prefix:Ue(te,xe,oe)}))==="stop")break;continue}if(je&&je.summary!==!0&&(yield*a.isOverflow({tokens:je.tokens,model:xe}))){yield*a.create({sessionID:E,agent:ae.agent,model:ae.model,auto:!0});continue}let J=yield*n.get(ae.agent);if(!J){let X=(yield*n.list()).filter(Pe=>!Pe.hidden).map(Pe=>Pe.name),he=X.length?` Available agents: ${X.join(", ")}`:"",ge=new kn.Unknown({message:`Agent not found: "${ae.agent}".${he}`});throw yield*C.publish(me.Event.Error,{sessionID:E,error:ge.toObject()}),ge}let v=J.steps??1/0,O=de>=v;oe=yield*Ms.apply({messages:oe,agent:J,session:te}).pipe(r.provideService(Be.Service,$),r.provideService(Ae.Service,u),r.provideService(me.Service,t));let F={id:at.ascending(),parentID:ae.id,role:"assistant",mode:J.name,agent:J.name,variant:ae.model.variant,path:{cwd:Y.directory,root:Y.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelID:xe.id,providerID:xe.providerID,time:{created:Date.now()},sessionID:E};yield*t.updateMessage(F);for(let[X,he]of V)he.sessionID===E&&(V.delete(X),yield*r.logWarning("person message read",{"session.id":E,messageID:X,how:he.how,waitedMs:Date.now()-he.at}));let Z=Promise.withResolvers(),_e=Ht.open(E,()=>Z.resolve()),le=r.gen(function*(){F.time.completed||(F.error??=Ze.fromError(new DOMException("Aborted","AbortError"),{providerID:F.providerID,aborted:!0}),F.time.completed=Date.now(),yield*t.updateMessage(F))}),ue=yield*s.create({assistantMessage:F,sessionID:E,model:xe,preempt:r.promise(()=>Z.promise)}).pipe(r.onInterrupt(()=>le));if((yield*r.gen(function*(){let he=oe.findLast(It=>It.info.role==="user")?.parts.some(It=>It.type==="agent")??!1,{tools:ge,system:Pe}=yield*ne({agent:J,session:te,model:xe,processor:ue,bypassAgentCheck:he,messages:oe,gate:_e});if(ae.format?.type==="json_schema"&&(ge.StructuredOutput=sg({schema:ae.format.schema,onSuccess(It){ve=It}})),de===1&&(yield*P.summarize({sessionID:E,messageID:ae.id}).pipe(r.ignore,r.forkIn(h))),de>1&&je){let It=new Set(oe.filter(_t=>_t.info.role==="assistant"&&_t.info.aside).map(_t=>_t.info.parentID));for(let _t of oe)if(!(_t.info.role!=="user"||ec.compareAscending(_t.info.id,je.id)<=0)&&!It.has(_t.info.id))for(let vn of _t.parts)vn.type!=="text"||vn.ignored||vn.synthetic||vn.text.trim()&&(vn.text=Jh(vn.text))}yield*l.trigger("experimental.chat.messages.transform",{},{messages:oe});let Ye=yield*Ze.toModelMessagesEffect(oe,xe),wt=ae.format??{type:"text"};wt.type==="json_schema"&&Pe.push(RD);let zo=yield*ue.process({user:ae,agent:J,permission:te.permission,sessionID:E,parentSessionID:te.parentID,system:Pe,messages:[...Ye,...O?[{role:"assistant",content:Ou}]:[]],tools:ge,model:xe,toolChoice:wt.type==="json_schema"?"required":void 0,storeSystem:st.on()?It=>r.gen(function*(){let _t=st.newestStored(oe),vn=oe.at(-1)?.info.id;if(!_t||!vn)return;let Aa=_t.value.system?.at(-1);if(Aa&&Aa.after===vn&&Aa.text===It)return;let Ig=st.withSystem(_t.value,{after:vn,text:It});_t.part.metadata={..._t.part.metadata,[st.METADATA_KEY]:Ig},yield*t.updatePart(_t.part)}):void 0});if(ve!==void 0)return ue.message.structured=ve,ue.message.finish=ue.message.finish??"stop",yield*t.updateMessage(ue.message),"break";if(ue.message.finish&&!["tool-calls","unknown"].includes(ue.message.finish)&&!ue.message.error){if(ue.message.finish==="content-filter")return ue.message.error=new dt.ContentFilterError({message:"The response was blocked by the provider's content filter"}).toObject(),yield*t.updateMessage(ue.message),yield*C.publish(me.Event.Error,{sessionID:E,error:ue.message.error}),"break";if(wt.type==="json_schema")return ue.message.error=new dt.StructuredOutputError({message:"Model did not produce structured output",retries:0}).toObject(),yield*t.updateMessage(ue.message),"break"}return zo==="stop"?"break":(zo==="compact"&&(yield*a.create({sessionID:E,agent:ae.agent,model:ae.model,auto:!0,overflow:!ue.message.finish})),"continue")}).pipe(r.ensuring(r.sync(()=>Ht.close(E,_e))),r.ensuring(k.clear(ue.message.id)),r.onInterrupt(()=>le)))==="break")break}return yield*a.prune({sessionID:E}).pipe(r.ignore,r.forkIn(h)),yield*H(E)}),Mt=r.fn("SessionPrompt.loop")(function*(E){return Bo.isPaused()?(Bo.hold(E.sessionID),yield*H(E.sessionID)):yield*w.ensureRunning(E.sessionID,H(E.sessionID),ot(E.sessionID))}),et=r.fn("SessionPrompt.shell")(function*(E){let Y=yield*Cd.make();return yield*w.startShell(E.sessionID,H(E.sessionID),W(E,Y),Y)}),Pn=r.fn("SessionPrompt.command")(function*(E){yield*r.logInfo("command",{"session.id":E.sessionID,command:E.command,agent:E.agent});let Y=yield*d.get(E.command);if(!Y){let K=(yield*d.list()).map(ge=>ge.name),X=K.length?` Available commands: ${K.join(", ")}`:"",he=new kn.Unknown({message:`Command not found: "${E.command}".${X}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:he.toObject()}),he}let ve=Y.agent??E.agent,te=(E.arguments.match(ND)??[]).map(K=>K.replace(jD,"")),oe=yield*r.promise(async()=>Y.template),ae=oe.match(og)??[],Q=0;for(let K of ae){let X=Number(K.slice(1));X>Q&&(Q=X)}let je=oe.replaceAll(og,(K,X)=>{let he=Number(X),ge=he-1;return ge>=te.length?"":he===Q?te.slice(ge).join(" "):te[ge]}),Je=oe.includes("$ARGUMENTS"),Ne=je.replaceAll("$ARGUMENTS",E.arguments);ae.length===0&&!Je&&E.arguments.trim()&&(Ne=Ne+`
1484
1484
 
1485
- `+E.arguments);let He=Xa.shell(Ne);if(He.length>0){let K=yield*p.get(),X=ai.preferred(K.shell),he=yield*r.promise(()=>Promise.all(He.map(async([,Pe])=>(await it.text([Pe],{shell:X,nothrow:!0})).text))),ge=0;Ne=Ne.replace(AD,()=>he[ge++])}Ne=Ne.trim();let xe=yield*r.gen(function*(){if(Y.model)return yt.parseModel(Y.model);if(Y.agent){let K=yield*n.get(Y.agent);if(K?.model)return K.model}return E.model?yt.parseModel(E.model):yield*we(E.sessionID)});yield*U(xe.providerID,xe.modelID,E.sessionID);let We=ve?yield*n.get(ve):yield*n.defaultInfo();if(!We){let K=(yield*n.list()).filter(ge=>!ge.hidden).map(ge=>ge.name),X=K.length?` Available agents: ${K.join(", ")}`:"",he=new kn.Unknown({message:`Agent not found: "${ve}".${X}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:he.toObject()}),he}let J=yield*M(Ne),v=new Set(E.parts?.filter(K=>new URL(K.url).protocol==="file:").map(K=>ud(K.url))),O=J.filter(K=>K.type!=="file"||!v.has(ud(K.url))),F=We.mode==="subagent"&&Y.subtask!==!1||Y.subtask===!0,Z=F?[{type:"subtask",agent:We.name,description:Y.description??"",command:E.command,model:{providerID:xe.providerID,modelID:xe.modelID},prompt:J.find(K=>K.type==="text")?.text??""}]:[...O,...E.parts??[]],_e=F?E.agent??(yield*n.defaultInfo()).name:We.name,le=F?E.model?yt.parseModel(E.model):yield*we(E.sessionID):xe;yield*l.trigger("command.execute.before",{command:E.command,sessionID:E.sessionID,arguments:E.arguments},{parts:Z});let ue=yield*q({sessionID:E.sessionID,messageID:E.messageID,model:le,agent:_e,parts:Z,variant:E.variant});return yield*C.publish(yi.Event.Executed,{name:E.command,sessionID:E.sessionID,arguments:E.arguments,messageID:ue.info.id}),ue});return Fr.of({cancel:L,stopForPause:D,prompt:q,loop:Mt,shell:et,command:Pn,resolvePromptParts:M})})),rg=c.Struct({providerID:sn.ID,modelID:uo.ID}),PD=c.Struct({sessionID:Pt,messageID:c.optional(at),model:c.optional(rg),agent:c.optional(c.String),noReply:c.optional(c.Boolean),tools:c.optional(c.Record(c.String,c.Boolean)).annotate({description:"@deprecated tools and permissions have been merged, you can set permissions on the session itself now"}),format:c.optional(dt.Format),system:c.optional(c.String),variant:c.optional(c.String),parts:c.Array(c.Union([dt.TextPartInput,dt.FilePartInput,dt.AgentPartInput,dt.SubtaskPartInput]).annotate({discriminator:"type"}))}),fd=class extends c.Class("SessionPrompt.LoopInput")({sessionID:Pt}){static{i(this,"LoopInput")}},RD=c.Struct({sessionID:Pt,messageID:c.optional(at),agent:c.String,model:c.optional(rg),command:c.String}),CD=c.Struct({messageID:c.optional(at),sessionID:Pt,agent:c.optional(c.String),model:c.optional(c.String),arguments:c.String,command:c.String,variant:c.optional(c.String),parts:c.optional(c.Array(c.Union([c.Struct({id:c.optional(Fe),type:c.Literal("file"),mime:c.String,filename:c.optional(c.String),url:c.String,source:c.optional(dt.FilePartSource)})]).annotate({discriminator:"type"})))});function sg(e){let{$schema:t,...n}=e.schema;return{description:kD,inputSchema:yn(n),async execute(o){return e.onSuccess(o),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:o}){return{type:"text",value:o.output}}}}i(sg,"createStructuredOutputTool");var AD=/!`([^`]+)`/g,MD=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,og=/\$(\d+)/g,_D=/^["']|["']$/g,OD=ke.make({service:Fr,layer:TD,deps:[ln.node,me.node,Ft.node,yt.node,jn.node,gr.node,pt.node,yi.node,Oe.node,Ke.node,Ae.node,cn.node,ft.node,$n.node,wo.node,bn.node,ni.node,En.node,Ln.node,br.node,un.node,eo.node,dn.node,De.node,Be.node,Qe.node]});var $o={};fe($o,{ApplyInput:()=>XD,ApplyResult:()=>QD,Event:()=>ug,FileDiff:()=>JD,FileStatus:()=>KD,Info:()=>YD,Mode:()=>HD,PatchApplyError:()=>js,Service:()=>co,Vcs:()=>$o,node:()=>yd});var Ls={};fe(Ls,{BranchUpdated:()=>ig,Definitions:()=>LD,VcsEvent:()=>Ls});var ig=Et.define({type:"vcs.branch.updated",schema:{branch:hn(c.String)}}),LD=Et.inventory(ig);var md=2147483647,ag=1e7,gd=1e7,ka=i(e=>Nu(Lu(e,e,"","","","",{context:0})),"emptyPatch"),cg=i(e=>new Map(e.map(t=>[t.file,{additions:t.additions,deletions:t.deletions}])),"nums"),ND=i((...e)=>{let t=new Map;return e.flat().forEach(n=>{t.has(n.file)||t.set(n.file,n)}),[...t.values()]},"merge"),jD=i(()=>({patches:new Map,capped:!1}),"emptyBatch"),hd=i(e=>{let t="";for(let n=1;n<e.length;n++){let o=e[n];if(o==='"')return{value:t,end:n+1};if(o!=="\\"){t+=o;continue}let s=e[++n];s==="t"?t+=" ":s==="n"?t+=`
1486
- `:s==="r"?t+="\r":s==='"'||s==="\\"?t+=s:t+=s??""}},"parseQuotedPath"),UD=i(e=>e.startsWith('"')?hd(e)?.value??e:e.split(" ")[0],"parsePathToken"),Ns=i(e=>{if(!e||e==="/dev/null")return;let t=UD(e);return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t},"fileFromDiffPath"),FD=i(e=>{if(e.startsWith('"')){let n=hd(e),o=n?e.slice(n.end).trimStart():void 0;return o?o.startsWith('"')?Ns(hd(o)?.value):Ns(o):void 0}let t=e.indexOf(" b/");if(t!==-1)return Ns(e.slice(t+1))},"fileFromGitHeader"),BD=i(e=>{let t=/^\+\+\+ (.+)$/m.exec(e)?.[1],n=/^--- (.+)$/m.exec(e)?.[1],o=Ns(t)??Ns(n);if(o)return o;let s=/^diff --git (.+)$/m.exec(e)?.[1];return FD(s??"")},"fileFromPatchChunk"),$D=i(e=>{let t=[...e.text.matchAll(/(?:^|\n)diff --git /g)].map(o=>o[0].startsWith(`
1487
- `)?o.index+1:o.index),n=t.map((o,s)=>e.text.slice(o,t[s+1]??e.text.length));return e.truncated?n.slice(0,-1):n},"splitGitPatch"),qD=r.fnUntraced(function*(e,t,n,o,s){if(o.length===0)return{patches:new Map,capped:!1};let a=yield*e.patchAll(t,n,{context:s?.context??md,maxOutputBytes:gd});return{patches:$D(a).reduce((l,d,p)=>{let f=BD(d)??o[p]?.file;return f&&l.set(f,(l.get(f)??"")+d),l},new Map),capped:a.truncated}}),WD=r.fnUntraced(function*(e,t,n,o,s){let a=o.code==="??"||!n?yield*e.patchUntracked(t,o.file,{context:s?.context??md,maxOutputBytes:ag}):yield*e.patch(t,n,o.file,{context:s?.context??md,maxOutputBytes:ag});return!a.truncated&&a.text?a.text:ka(o.file)}),VD=i((e,t,n)=>n+Buffer.byteLength(t)<=gd?{patch:t,capped:!1}:{patch:ka(e),capped:!0},"totalPatch"),zD=r.fnUntraced(function*(e,t,n,o,s,a,l){if(a)return ka(o.file);let d=s.patches.get(o.file);return d!==void 0?d:o.code!=="??"&&s.capped?ka(o.file):yield*WD(e,t,n,o,l)}),lg=r.fnUntraced(function*(e,t,n,o,s,a,l){let d=[],p=0,f=!1;for(let u of o.toSorted((g,y)=>g.file.localeCompare(y.file))){let g=s.get(u.file)??(u.status==="added"?yield*e.statUntracked(t,u.file):void 0),y=yield*zD(e,t,n,u,a,f,l),b=f?{patch:y,capped:!0}:VD(u.file,y,p);f=f||b.capped,f||(p+=Buffer.byteLength(b.patch),f=p>=gd),d.push({file:u.file,patch:b.patch,additions:g?.additions??0,deletions:g?.deletions??0,status:u.status})}return d}),dg=r.fnUntraced(function*(e,t,n,o){let[s,a,l]=yield*r.all([e.diff(t,n),e.stats(t,n),e.status(t)],{concurrency:3});return yield*lg(e,t,n,ND(s,l.filter(d=>d.code==="??")),cg(a),yield*qD(e,t,n,s,o),o)}),GD=r.fnUntraced(function*(e,t,n,o){return n?yield*dg(e,t,n,o):yield*lg(e,t,n,yield*e.status(t),new Map,jD(),o)}),HD=c.Literals(["git","branch"]),ug=Ls,YD=c.Struct({branch:c.optional(c.String),default_branch:c.optional(c.String)}).annotate({identifier:"VcsInfo"}),JD=c.Struct({file:c.String,patch:c.optional(c.String),additions:c.Finite,deletions:c.Finite,status:c.optional(c.Literals(["added","deleted","modified"]))}).annotate({identifier:"VcsFileDiff"}),KD=c.Struct({file:c.String,additions:c.Finite,deletions:c.Finite,status:c.Literals(["added","deleted","modified"])}).annotate({identifier:"VcsFileStatus"}),XD=c.Struct({patch:c.String}),QD=c.Struct({applied:c.Boolean}),js=class extends c.TaggedErrorClass()("VcsPatchApplyError",{message:c.String,reason:c.Literals(["non-git","not-clean"])}){static{i(this,"PatchApplyError")}},co=class extends Re.Service()("@opencode/Vcs"){static{i(this,"Service")}},ZD=Te.effect(co,r.gen(function*(){let e=yield*tc.Service,t=yield*De.Service,n=yield*Dt.Scope,o=yield*G.make(r.fn("Vcs.state")(function*(s){if(s.project.vcs!=="git")return{current:void 0,root:void 0};let a=r.fnUntraced(function*(){return yield*e.branch(s.directory)}),[l,d]=yield*r.all([e.branch(s.directory),e.defaultBranch(s.directory)],{concurrency:2}),p={current:l,root:d},f=yield*t.listen(u=>u.type!==_n.Event.Updated.type||u.location?.directory!==s.directory?r.void:u.data.file.endsWith("HEAD")?r.gen(function*(){let y=yield*a();y!==p.current&&(p.current=y,yield*t.publish(ug.BranchUpdated,{branch:y}))}):r.void);return yield*r.addFinalizer(()=>f),p}));return co.of({init:r.fn("Vcs.init")(function*(){yield*G.get(o).pipe(r.forkIn(n))}),branch:r.fn("Vcs.branch")(function*(){return yield*G.use(o,s=>s.current)}),defaultBranch:r.fn("Vcs.defaultBranch")(function*(){return yield*G.use(o,s=>s.root?.name)}),status:r.fn("Vcs.status")(function*(){let s=yield*G.context;if(s.project.vcs!=="git")return[];let a=(yield*e.hasHead(s.directory))?"HEAD":void 0,[l,d]=yield*r.all([e.status(s.directory),a?e.stats(s.directory,a):r.succeed([])],{concurrency:2}),p=cg(d);return yield*r.forEach(l.toSorted((f,u)=>f.file.localeCompare(u.file)),f=>r.gen(function*(){let u=p.get(f.file)??(f.status==="added"?yield*e.statUntracked(s.worktree,f.file):void 0);return{file:f.file,additions:u?.additions??0,deletions:u?.deletions??0,status:f.status}}))}),diff:r.fn("Vcs.diff")(function*(s,a){let l=yield*G.get(o),d=yield*G.context;if(d.project.vcs!=="git")return[];if(s==="git")return yield*GD(e,d.directory,(yield*e.hasHead(d.directory))?"HEAD":void 0,a);if(!l.root)return[];if(l.current&&l.current===l.root.name)return[];let p=yield*e.mergeBase(d.directory,l.root.ref);return p?yield*dg(e,d.directory,p,a):[]}),diffRaw:r.fn("Vcs.diffRaw")(function*(){let s=yield*G.context;if(s.project.vcs!=="git")return"";let[a,l]=yield*r.all([e.hasHead(s.directory),e.status(s.directory)],{concurrency:2}),d=a?(yield*e.patchAll(s.directory,"HEAD")).text:"",p=yield*r.forEach(l.filter(f=>f.code==="??"),f=>e.patchUntracked(s.directory,f.file).pipe(r.map(u=>u.text)));return[d,...p].filter(Boolean).join(`
1488
- `)}),apply:r.fn("Vcs.apply")(function*(s){let a=yield*G.context;return a.project.vcs!=="git"?yield*new js({message:"Patch can't be applied because the project is not git-based",reason:"non-git"}):(yield*e.applyPatch(a.directory,s.patch)).exitCode!==0?yield*new js({message:"Patch can't be applied",reason:"not-clean"}):{applied:!0}})})})),yd=ke.make({service:co,layer:ZD,deps:[tc.node,De.node]});var Wn={};fe(Wn,{Service:()=>Wo,ShareNext:()=>Wn,node:()=>sE,use:()=>tE});var qo=Kd("session_share",{session_id:Kr().primaryKey().references(()=>Tt.id,{onDelete:"cascade"}),id:Kr().notNull(),secret:Kr().notNull(),url:Kr().notNull(),...du});var $r=process.env.OPENCODE_DISABLE_SHARE==="true"||process.env.OPENCODE_DISABLE_SHARE==="1",eE=c.Struct({id:c.String,url:c.String,secret:c.String}),Wo=class extends Re.Service()("@opencode/ShareNext"){static{i(this,"Service")}},tE=Wt(Wo);function fg(e){return{create:`/api/${e}`,sync:i(t=>`/api/${e}/${t}/sync`,"sync"),remove:i(t=>`/api/${e}/${t}`,"remove"),data:i(t=>`/api/${e}/${t}/data`,"data")}}i(fg,"api");var nE=fg("share"),oE=fg("shares");function pg(e){switch(e.type){case"session":return"session";case"message":return`message/${e.data.id}`;case"part":return`part/${e.data.messageID}/${e.data.id}`;case"session_diff":return"session_diff";case"model":return"model"}}i(pg,"key");var rE=Te.effect(Wo,r.gen(function*(){let e=yield*Ya.Service,t=yield*De.Service,n=yield*Oe.Service,{db:o}=yield*Qe.Service,s=yield*fn.HttpClient,a=fn.filterStatusOk(s),l=yield*yt.Service,d=yield*me.Service;function p(w,I){return r.gen(function*(){if($r||!(yield*y(w)))return;let x=yield*G.get(f),A=x.queue.get(w);if(A){for(let $ of I)A.set(pg($),$);return}let C=new Map(I.map($=>[pg($),$]));x.queue.set(w,C),yield*b(w).pipe(r.delay(1e3),r.catchCause($=>r.logError("share flush failed",{sessionID:w,cause:$})),r.forkIn(x.scope))})}i(p,"sync");let f=yield*G.make(r.fn("ShareNext.state")(function*(w){let I={queue:new Map,scope:yield*Dt.make(),shared:new Map};if(yield*r.addFinalizer(()=>Dt.close(I.scope,bt.void).pipe(r.andThen(r.sync(()=>{I.queue.clear(),I.shared.clear()})))),$r)return I;let P=i((x,A)=>t.listen(C=>C.type!==x.type||C.location?.directory!==w.directory?r.void:A(C.data).pipe(r.catchCause($=>r.logError("share subscriber failed",{type:x.type,cause:$})))),"watch");return yield*P(me.Event.Updated,x=>r.gen(function*(){let A=x.info;yield*p(A.id,[{type:"session",data:structuredClone(A)}])})),yield*P(Ze.Event.Updated,x=>r.gen(function*(){let A=x.info;if(yield*p(A.sessionID,[{type:"message",data:structuredClone(A)}]),A.role!=="user")return;let C=yield*l.getModel(A.model.providerID,A.model.modelID);yield*p(A.sessionID,[{type:"model",data:[C]}])})),yield*P(Ze.Event.PartUpdated,x=>p(x.part.sessionID,[{type:"part",data:structuredClone(x.part)}])),yield*P(me.Event.Diff,x=>p(x.sessionID,[{type:"session_diff",data:structuredClone(x.diff)}])),yield*P(me.Event.Deleted,x=>k(x.sessionID)),I})),u=r.fn("ShareNext.request")(function*(){let w={},I=yield*e.active();if(xn.isNone(I)||!I.value.active_org_id){let x=(yield*n.get()).enterprise?.url??"https://opncd.ai";return{headers:w,api:nE,baseUrl:x}}let P=yield*e.token(I.value.id);if(xn.isNone(P))throw new Error("No active account token available for sharing");return w.authorization=`Bearer ${P.value}`,w["x-org-id"]=I.value.active_org_id,{headers:w,api:oE,baseUrl:I.value.url}}),g=r.fnUntraced(function*(w){let I=yield*o.select().from(qo).where(St(qo.session_id,w)).get().pipe(r.orDie);if(I)return{id:I.id,secret:I.secret,url:I.url}}),y=r.fnUntraced(function*(w){let I=yield*G.get(f);if(I.shared.has(w)){let x=I.shared.get(w);return x===null?void 0:x}let P=yield*g(w);return I.shared.set(w,P??null),P}),b=r.fn("ShareNext.flush")(function*(w){if($r)return;let I=yield*G.get(f),P=I.queue.get(w);if(!P)return;I.queue.delete(w);let x=yield*y(w);if(!x)return;let A=yield*u(),C=yield*Ve.post(`${A.baseUrl}${A.api.sync(x.id)}`).pipe(Ve.setHeaders(A.headers),Ve.bodyJson({secret:x.secret,data:Array.from(P.values())}),r.flatMap($=>s.execute($)));C.status>=400&&(yield*r.logWarning("failed to sync share",{sessionID:w,shareID:x.id,status:C.status}))}),S=r.fn("ShareNext.full")(function*(w){yield*r.logInfo("full sync",{sessionID:w});let I=yield*d.get(w),P=yield*d.diff(w),x=yield*d.messages({sessionID:w}),A=yield*r.forEach(Array.from(new Map(x.filter(C=>C.info.role==="user").map(C=>C.info.model).map(C=>[`${C.providerID}/${C.modelID}`,C])).values()),C=>l.getModel(sn.ID.make(C.providerID),uo.ID.make(C.modelID)),{concurrency:8});yield*p(w,[{type:"session",data:I},...x.map(C=>({type:"message",data:C.info})),...x.flatMap(C=>C.parts.map($=>({type:"part",data:$}))),{type:"session_diff",data:P},{type:"model",data:A}])}),T=r.fn("ShareNext.init")(function*(){$r||(yield*G.get(f))}),m=r.fn("ShareNext.url")(function*(){return(yield*u()).baseUrl}),h=r.fn("ShareNext.create")(function*(w){if($r)return{id:"",url:"",secret:""};yield*r.logInfo("creating share",{sessionID:w});let I=yield*u(),P=yield*Ve.post(`${I.baseUrl}${I.api.create}`).pipe(Ve.setHeaders(I.headers),Ve.bodyJson({sessionID:w}),r.flatMap(A=>a.execute(A)),r.flatMap(zn.schemaBodyJson(eE)));yield*o.insert(qo).values({session_id:w,id:P.id,secret:P.secret,url:P.url}).onConflictDoUpdate({target:qo.session_id,set:{id:P.id,secret:P.secret,url:P.url}}).run().pipe(r.orDie);let x=yield*G.get(f);return x.shared.set(w,P),yield*S(w).pipe(r.catchCause(A=>r.logError("share full sync failed",{sessionID:w,cause:A})),r.forkIn(x.scope)),P}),k=r.fn("ShareNext.remove")(function*(w){if($r)return;yield*r.logInfo("removing share",{sessionID:w});let I=yield*G.get(f),P=yield*y(w);if(!P){I.shared.delete(w),I.queue.delete(w);return}let x=yield*u();yield*Ve.delete(`${x.baseUrl}${x.api.remove(P.id)}`).pipe(Ve.setHeaders(x.headers),Ve.bodyJson({secret:P.secret}),r.flatMap(A=>a.execute(A))),yield*o.delete(qo).where(St(qo.session_id,w)).run().pipe(r.orDie),I.shared.delete(w),I.queue.delete(w)});return Wo.of({init:T,url:m,request:u,create:h,remove:k})})),sE=ke.make({service:Wo,layer:rE,deps:[Ya.node,De.node,Oe.node,Qe.node,In,yt.node,me.node]});var qr={};fe(qr,{AppNodeBuilderV1:()=>qr,build:()=>lE});var Us={};fe(Us,{InstanceBootstrap:()=>Us,Service:()=>Zo,node:()=>aE});var iE=Te.effect(Zo,r.gen(function*(){let e=yield*Oe.Service,t=yield*Jt.Service,n=yield*ft.Service,o=yield*pt.Service,s=yield*Ku,a=yield*Wn.Service,l=yield*an.Service,d=yield*co,p=r.gen(function*(){let f=yield*G.context;yield*r.logInfo("bootstrapping",{directory:f.directory}),yield*e.get(),yield*o.init(),yield*r.forEach([n,a,t,d,l,s],u=>u.init().pipe(r.catchCause(g=>r.logWarning("init failed",{cause:g}))),{concurrency:"unbounded",discard:!0}).pipe(r.withSpan("InstanceBootstrap.init"))}).pipe(r.withSpan("InstanceBootstrap"));return Zo.of({run:p})})),aE=Xs({service:Zo,layer:iE,deps:[Oe.node,Jt.node,ft.node,pt.node,Xu,Wn.node,an.node,yd]});var cE=[er.bootstrapNode,Us.node];function lE(e,t=[]){return vo.build(e,t.concat([cE]))}i(lE,"build");var vd={};fe(vd,{ConnectionStatus:()=>hE,CreateInput:()=>gE,Event:()=>wd,Info:()=>Ea,Service:()=>Vo,SessionEventsNotFoundError:()=>Pa,SessionWarpHttpError:()=>$s,SessionWarpInput:()=>yE,SyncAbortedError:()=>Ca,SyncHttpError:()=>Bs,SyncTimeoutError:()=>Ra,Workspace:()=>vd,WorkspaceNotFoundError:()=>Ta,node:()=>vE,use:()=>bE});function bd(e){return e.signal?.aborted?r.fail(e.signal.reason??new Error("Request aborted")):r.callback(t=>{let n=i(()=>{s(),t(r.fail(e.signal?.reason??new Error("Request aborted")))},"abort"),o=i(l=>{try{if(!e.fn(l))return;s(),t(r.void)}catch(d){s(),t(r.fail(d))}},"handler"),s=i(()=>{clearTimeout(a),Qo.off("event",o),e.signal?.removeEventListener("abort",n)},"cleanup"),a=setTimeout(()=>{s(),t(r.fail(new Error("Timed out waiting for global event")))},e.timeout);return Qo.on("event",o),e.signal?.addEventListener("abort",n,{once:!0}),r.sync(s)})}i(bd,"waitEvent");var rn={};fe(rn,{WorkspaceAdapterRuntime:()=>rn,configure:()=>uE,create:()=>pE,list:()=>fE,remove:()=>mE,target:()=>dE});var Fs=r.gen(function*(){return{instance:yield*Bu,workspaceID:yield*ui}}),dE=i(e=>r.gen(function*(){let t=ns(e.projectID,e.type),n=yield*Fs;return yield*zt.fromPromise(()=>t.target(e,n))}),"target"),uE=i((e,t)=>r.gen(function*(){let n=yield*Fs;return yield*zt.fromPromise(()=>e.configure(t,n))}),"configure"),pE=i((e,t,n,o)=>r.gen(function*(){let s=yield*Fs;return yield*zt.fromPromise(()=>e.create(t,n,o,s))}),"create"),fE=i(e=>r.gen(function*(){let t=yield*Fs;return yield*zt.fromPromise(()=>Promise.resolve(e.list?.(t)??[]))}),"list"),mE=i(e=>r.gen(function*(){let t=ns(e.projectID,e.type),n=yield*Fs;return yield*zt.fromPromise(()=>t.remove(e,n))}),"remove");var Ea=c.Struct({...Gu.fields,timeUsed:c.Number}).annotate({identifier:"Workspace"}),hE=qa.ConnectionStatus,wd=qa;function Da(e){return{id:e.id,type:e.type,branch:e.branch,name:e.name,directory:e.directory,extra:e.extra,projectID:e.project_id,timeUsed:e.time_used}}i(Da,"fromRow");var gE=c.Struct({id:c.optional(ho.ID),type:Ea.fields.type,branch:Ea.fields.branch,projectID:uu.ID,extra:c.optional(Ea.fields.extra)}),yE=c.Struct({workspaceID:c.NullOr(ho.ID),sessionID:Pt,copyChanges:c.optional(c.Boolean)}),Bs=class extends c.TaggedErrorClass()("WorkspaceSyncHttpError",{message:c.String,status:c.Number,body:c.optional(c.String)}){static{i(this,"SyncHttpError")}},Ta=class extends c.TaggedErrorClass()("WorkspaceNotFoundError",{message:c.String,workspaceID:ho.ID}){static{i(this,"WorkspaceNotFoundError")}},Pa=class extends c.TaggedErrorClass()("WorkspaceSessionEventsNotFoundError",{message:c.String,sessionID:Pt}){static{i(this,"SessionEventsNotFoundError")}},$s=class extends c.TaggedErrorClass()("WorkspaceSessionWarpHttpError",{message:c.String,workspaceID:ho.ID,sessionID:Pt,status:c.Number,body:c.String}){static{i(this,"SessionWarpHttpError")}},Ra=class extends c.TaggedErrorClass()("WorkspaceSyncTimeoutError",{message:c.String,state:c.Record(c.String,c.Number)}){static{i(this,"SyncTimeoutError")}},Ca=class extends c.TaggedErrorClass()("WorkspaceSyncAbortedError",{message:c.String,cause:c.optional(c.Defect())}){static{i(this,"SyncAbortedError")}},Vo=class extends Re.Service()("@opencode/Workspace"){static{i(this,"Service")}},bE=Wt(Vo),wE=Te.effect(Vo,r.gen(function*(){let e=yield*Xt.Service,t=yield*me.Service,n=yield*Br.Service,o=yield*fn.HttpClient,s=yield*De.Service,a=yield*$o.Service,l=yield*Be.Service,d=yield*Ae.Service,{db:p}=yield*Qe.Service,f=new Map,u=yield*Ho.make(),g=i((L,V)=>{if(f.get(L)?.status===V)return;let M={workspaceID:L,status:V};f.set(L,M),Qo.emit("event",{directory:"global",workspace:L,payload:{type:wd.Status.type,properties:M}})},"setStatus"),y=r.fn("Workspace.connectSSE")(function*(L,V){let D=yield*o.execute(Ve.get(Wr(L,"/global/event"),{headers:new Headers(V),accept:"text/event-stream"}));return D.status<200||D.status>=300?yield*new Bs({message:`Workspace sync HTTP failure: ${D.status}`,status:D.status}):D.stream}),b=r.fn("Workspace.parseSSE")(function*(L,V){yield*L.pipe(vt.decodeText(),vt.splitLines,vt.mapAccum(()=>({data:[],id:void 0,retry:1e3}),(D,M)=>{if(M==="")return D.data.length?[{...D,data:[]},[{data:D.data.join(`
1485
+ `+E.arguments);let He=Xa.shell(Ne);if(He.length>0){let K=yield*p.get(),X=ai.preferred(K.shell),he=yield*r.promise(()=>Promise.all(He.map(async([,Pe])=>(await it.text([Pe],{shell:X,nothrow:!0})).text))),ge=0;Ne=Ne.replace(LD,()=>he[ge++])}Ne=Ne.trim();let xe=yield*r.gen(function*(){if(Y.model)return yt.parseModel(Y.model);if(Y.agent){let K=yield*n.get(Y.agent);if(K?.model)return K.model}return E.model?yt.parseModel(E.model):yield*we(E.sessionID)});yield*U(xe.providerID,xe.modelID,E.sessionID);let We=ve?yield*n.get(ve):yield*n.defaultInfo();if(!We){let K=(yield*n.list()).filter(ge=>!ge.hidden).map(ge=>ge.name),X=K.length?` Available agents: ${K.join(", ")}`:"",he=new kn.Unknown({message:`Agent not found: "${ve}".${X}`});throw yield*C.publish(me.Event.Error,{sessionID:E.sessionID,error:he.toObject()}),he}let J=yield*M(Ne),v=new Set(E.parts?.filter(K=>new URL(K.url).protocol==="file:").map(K=>ud(K.url))),O=J.filter(K=>K.type!=="file"||!v.has(ud(K.url))),F=We.mode==="subagent"&&Y.subtask!==!1||Y.subtask===!0,Z=F?[{type:"subtask",agent:We.name,description:Y.description??"",command:E.command,model:{providerID:xe.providerID,modelID:xe.modelID},prompt:J.find(K=>K.type==="text")?.text??""}]:[...O,...E.parts??[]],_e=F?E.agent??(yield*n.defaultInfo()).name:We.name,le=F?E.model?yt.parseModel(E.model):yield*we(E.sessionID):xe;yield*l.trigger("command.execute.before",{command:E.command,sessionID:E.sessionID,arguments:E.arguments},{parts:Z});let ue=yield*q({sessionID:E.sessionID,messageID:E.messageID,model:le,agent:_e,parts:Z,variant:E.variant});return yield*C.publish(yi.Event.Executed,{name:E.command,sessionID:E.sessionID,arguments:E.arguments,messageID:ue.info.id}),ue});return Fr.of({cancel:L,stopForPause:D,prompt:q,loop:Mt,shell:et,command:Pn,resolvePromptParts:M})})),rg=c.Struct({providerID:sn.ID,modelID:uo.ID}),MD=c.Struct({sessionID:Pt,messageID:c.optional(at),model:c.optional(rg),agent:c.optional(c.String),noReply:c.optional(c.Boolean),tools:c.optional(c.Record(c.String,c.Boolean)).annotate({description:"@deprecated tools and permissions have been merged, you can set permissions on the session itself now"}),format:c.optional(dt.Format),system:c.optional(c.String),variant:c.optional(c.String),parts:c.Array(c.Union([dt.TextPartInput,dt.FilePartInput,dt.AgentPartInput,dt.SubtaskPartInput]).annotate({discriminator:"type"}))}),fd=class extends c.Class("SessionPrompt.LoopInput")({sessionID:Pt}){static{i(this,"LoopInput")}},_D=c.Struct({sessionID:Pt,messageID:c.optional(at),agent:c.String,model:c.optional(rg),command:c.String}),OD=c.Struct({messageID:c.optional(at),sessionID:Pt,agent:c.optional(c.String),model:c.optional(c.String),arguments:c.String,command:c.String,variant:c.optional(c.String),parts:c.optional(c.Array(c.Union([c.Struct({id:c.optional(Fe),type:c.Literal("file"),mime:c.String,filename:c.optional(c.String),url:c.String,source:c.optional(dt.FilePartSource)})]).annotate({discriminator:"type"})))});function sg(e){let{$schema:t,...n}=e.schema;return{description:PD,inputSchema:yn(n),async execute(o){return e.onSuccess(o),{output:"Structured output captured successfully.",title:"Structured Output",metadata:{valid:!0}}},toModelOutput({output:o}){return{type:"text",value:o.output}}}}i(sg,"createStructuredOutputTool");var LD=/!`([^`]+)`/g,ND=/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi,og=/\$(\d+)/g,jD=/^["']|["']$/g,UD=ke.make({service:Fr,layer:AD,deps:[ln.node,me.node,Ft.node,yt.node,jn.node,gr.node,pt.node,yi.node,Oe.node,Ke.node,Ae.node,cn.node,ft.node,$n.node,wo.node,bn.node,ni.node,En.node,Ln.node,br.node,un.node,eo.node,dn.node,De.node,Be.node,Qe.node]});var $o={};fe($o,{ApplyInput:()=>tE,ApplyResult:()=>nE,Event:()=>ug,FileDiff:()=>ZD,FileStatus:()=>eE,Info:()=>QD,Mode:()=>XD,PatchApplyError:()=>js,Service:()=>co,Vcs:()=>$o,node:()=>yd});var Ls={};fe(Ls,{BranchUpdated:()=>ig,Definitions:()=>FD,VcsEvent:()=>Ls});var ig=Et.define({type:"vcs.branch.updated",schema:{branch:hn(c.String)}}),FD=Et.inventory(ig);var md=2147483647,ag=1e7,gd=1e7,ka=i(e=>Nu(Lu(e,e,"","","","",{context:0})),"emptyPatch"),cg=i(e=>new Map(e.map(t=>[t.file,{additions:t.additions,deletions:t.deletions}])),"nums"),BD=i((...e)=>{let t=new Map;return e.flat().forEach(n=>{t.has(n.file)||t.set(n.file,n)}),[...t.values()]},"merge"),$D=i(()=>({patches:new Map,capped:!1}),"emptyBatch"),hd=i(e=>{let t="";for(let n=1;n<e.length;n++){let o=e[n];if(o==='"')return{value:t,end:n+1};if(o!=="\\"){t+=o;continue}let s=e[++n];s==="t"?t+=" ":s==="n"?t+=`
1486
+ `:s==="r"?t+="\r":s==='"'||s==="\\"?t+=s:t+=s??""}},"parseQuotedPath"),qD=i(e=>e.startsWith('"')?hd(e)?.value??e:e.split(" ")[0],"parsePathToken"),Ns=i(e=>{if(!e||e==="/dev/null")return;let t=qD(e);return t.startsWith("a/")||t.startsWith("b/")?t.slice(2):t},"fileFromDiffPath"),WD=i(e=>{if(e.startsWith('"')){let n=hd(e),o=n?e.slice(n.end).trimStart():void 0;return o?o.startsWith('"')?Ns(hd(o)?.value):Ns(o):void 0}let t=e.indexOf(" b/");if(t!==-1)return Ns(e.slice(t+1))},"fileFromGitHeader"),VD=i(e=>{let t=/^\+\+\+ (.+)$/m.exec(e)?.[1],n=/^--- (.+)$/m.exec(e)?.[1],o=Ns(t)??Ns(n);if(o)return o;let s=/^diff --git (.+)$/m.exec(e)?.[1];return WD(s??"")},"fileFromPatchChunk"),zD=i(e=>{let t=[...e.text.matchAll(/(?:^|\n)diff --git /g)].map(o=>o[0].startsWith(`
1487
+ `)?o.index+1:o.index),n=t.map((o,s)=>e.text.slice(o,t[s+1]??e.text.length));return e.truncated?n.slice(0,-1):n},"splitGitPatch"),GD=r.fnUntraced(function*(e,t,n,o,s){if(o.length===0)return{patches:new Map,capped:!1};let a=yield*e.patchAll(t,n,{context:s?.context??md,maxOutputBytes:gd});return{patches:zD(a).reduce((l,d,p)=>{let f=VD(d)??o[p]?.file;return f&&l.set(f,(l.get(f)??"")+d),l},new Map),capped:a.truncated}}),HD=r.fnUntraced(function*(e,t,n,o,s){let a=o.code==="??"||!n?yield*e.patchUntracked(t,o.file,{context:s?.context??md,maxOutputBytes:ag}):yield*e.patch(t,n,o.file,{context:s?.context??md,maxOutputBytes:ag});return!a.truncated&&a.text?a.text:ka(o.file)}),YD=i((e,t,n)=>n+Buffer.byteLength(t)<=gd?{patch:t,capped:!1}:{patch:ka(e),capped:!0},"totalPatch"),JD=r.fnUntraced(function*(e,t,n,o,s,a,l){if(a)return ka(o.file);let d=s.patches.get(o.file);return d!==void 0?d:o.code!=="??"&&s.capped?ka(o.file):yield*HD(e,t,n,o,l)}),lg=r.fnUntraced(function*(e,t,n,o,s,a,l){let d=[],p=0,f=!1;for(let u of o.toSorted((g,y)=>g.file.localeCompare(y.file))){let g=s.get(u.file)??(u.status==="added"?yield*e.statUntracked(t,u.file):void 0),y=yield*JD(e,t,n,u,a,f,l),b=f?{patch:y,capped:!0}:YD(u.file,y,p);f=f||b.capped,f||(p+=Buffer.byteLength(b.patch),f=p>=gd),d.push({file:u.file,patch:b.patch,additions:g?.additions??0,deletions:g?.deletions??0,status:u.status})}return d}),dg=r.fnUntraced(function*(e,t,n,o){let[s,a,l]=yield*r.all([e.diff(t,n),e.stats(t,n),e.status(t)],{concurrency:3});return yield*lg(e,t,n,BD(s,l.filter(d=>d.code==="??")),cg(a),yield*GD(e,t,n,s,o),o)}),KD=r.fnUntraced(function*(e,t,n,o){return n?yield*dg(e,t,n,o):yield*lg(e,t,n,yield*e.status(t),new Map,$D(),o)}),XD=c.Literals(["git","branch"]),ug=Ls,QD=c.Struct({branch:c.optional(c.String),default_branch:c.optional(c.String)}).annotate({identifier:"VcsInfo"}),ZD=c.Struct({file:c.String,patch:c.optional(c.String),additions:c.Finite,deletions:c.Finite,status:c.optional(c.Literals(["added","deleted","modified"]))}).annotate({identifier:"VcsFileDiff"}),eE=c.Struct({file:c.String,additions:c.Finite,deletions:c.Finite,status:c.Literals(["added","deleted","modified"])}).annotate({identifier:"VcsFileStatus"}),tE=c.Struct({patch:c.String}),nE=c.Struct({applied:c.Boolean}),js=class extends c.TaggedErrorClass()("VcsPatchApplyError",{message:c.String,reason:c.Literals(["non-git","not-clean"])}){static{i(this,"PatchApplyError")}},co=class extends Re.Service()("@opencode/Vcs"){static{i(this,"Service")}},oE=Te.effect(co,r.gen(function*(){let e=yield*tc.Service,t=yield*De.Service,n=yield*Dt.Scope,o=yield*G.make(r.fn("Vcs.state")(function*(s){if(s.project.vcs!=="git")return{current:void 0,root:void 0};let a=r.fnUntraced(function*(){return yield*e.branch(s.directory)}),[l,d]=yield*r.all([e.branch(s.directory),e.defaultBranch(s.directory)],{concurrency:2}),p={current:l,root:d},f=yield*t.listen(u=>u.type!==_n.Event.Updated.type||u.location?.directory!==s.directory?r.void:u.data.file.endsWith("HEAD")?r.gen(function*(){let y=yield*a();y!==p.current&&(p.current=y,yield*t.publish(ug.BranchUpdated,{branch:y}))}):r.void);return yield*r.addFinalizer(()=>f),p}));return co.of({init:r.fn("Vcs.init")(function*(){yield*G.get(o).pipe(r.forkIn(n))}),branch:r.fn("Vcs.branch")(function*(){return yield*G.use(o,s=>s.current)}),defaultBranch:r.fn("Vcs.defaultBranch")(function*(){return yield*G.use(o,s=>s.root?.name)}),status:r.fn("Vcs.status")(function*(){let s=yield*G.context;if(s.project.vcs!=="git")return[];let a=(yield*e.hasHead(s.directory))?"HEAD":void 0,[l,d]=yield*r.all([e.status(s.directory),a?e.stats(s.directory,a):r.succeed([])],{concurrency:2}),p=cg(d);return yield*r.forEach(l.toSorted((f,u)=>f.file.localeCompare(u.file)),f=>r.gen(function*(){let u=p.get(f.file)??(f.status==="added"?yield*e.statUntracked(s.worktree,f.file):void 0);return{file:f.file,additions:u?.additions??0,deletions:u?.deletions??0,status:f.status}}))}),diff:r.fn("Vcs.diff")(function*(s,a){let l=yield*G.get(o),d=yield*G.context;if(d.project.vcs!=="git")return[];if(s==="git")return yield*KD(e,d.directory,(yield*e.hasHead(d.directory))?"HEAD":void 0,a);if(!l.root)return[];if(l.current&&l.current===l.root.name)return[];let p=yield*e.mergeBase(d.directory,l.root.ref);return p?yield*dg(e,d.directory,p,a):[]}),diffRaw:r.fn("Vcs.diffRaw")(function*(){let s=yield*G.context;if(s.project.vcs!=="git")return"";let[a,l]=yield*r.all([e.hasHead(s.directory),e.status(s.directory)],{concurrency:2}),d=a?(yield*e.patchAll(s.directory,"HEAD")).text:"",p=yield*r.forEach(l.filter(f=>f.code==="??"),f=>e.patchUntracked(s.directory,f.file).pipe(r.map(u=>u.text)));return[d,...p].filter(Boolean).join(`
1488
+ `)}),apply:r.fn("Vcs.apply")(function*(s){let a=yield*G.context;return a.project.vcs!=="git"?yield*new js({message:"Patch can't be applied because the project is not git-based",reason:"non-git"}):(yield*e.applyPatch(a.directory,s.patch)).exitCode!==0?yield*new js({message:"Patch can't be applied",reason:"not-clean"}):{applied:!0}})})})),yd=ke.make({service:co,layer:oE,deps:[tc.node,De.node]});var Wn={};fe(Wn,{Service:()=>Wo,ShareNext:()=>Wn,node:()=>lE,use:()=>sE});var qo=Kd("session_share",{session_id:Kr().primaryKey().references(()=>Tt.id,{onDelete:"cascade"}),id:Kr().notNull(),secret:Kr().notNull(),url:Kr().notNull(),...du});var $r=process.env.OPENCODE_DISABLE_SHARE==="true"||process.env.OPENCODE_DISABLE_SHARE==="1",rE=c.Struct({id:c.String,url:c.String,secret:c.String}),Wo=class extends Re.Service()("@opencode/ShareNext"){static{i(this,"Service")}},sE=Wt(Wo);function fg(e){return{create:`/api/${e}`,sync:i(t=>`/api/${e}/${t}/sync`,"sync"),remove:i(t=>`/api/${e}/${t}`,"remove"),data:i(t=>`/api/${e}/${t}/data`,"data")}}i(fg,"api");var iE=fg("share"),aE=fg("shares");function pg(e){switch(e.type){case"session":return"session";case"message":return`message/${e.data.id}`;case"part":return`part/${e.data.messageID}/${e.data.id}`;case"session_diff":return"session_diff";case"model":return"model"}}i(pg,"key");var cE=Te.effect(Wo,r.gen(function*(){let e=yield*Ya.Service,t=yield*De.Service,n=yield*Oe.Service,{db:o}=yield*Qe.Service,s=yield*fn.HttpClient,a=fn.filterStatusOk(s),l=yield*yt.Service,d=yield*me.Service;function p(w,I){return r.gen(function*(){if($r||!(yield*y(w)))return;let x=yield*G.get(f),A=x.queue.get(w);if(A){for(let $ of I)A.set(pg($),$);return}let C=new Map(I.map($=>[pg($),$]));x.queue.set(w,C),yield*b(w).pipe(r.delay(1e3),r.catchCause($=>r.logError("share flush failed",{sessionID:w,cause:$})),r.forkIn(x.scope))})}i(p,"sync");let f=yield*G.make(r.fn("ShareNext.state")(function*(w){let I={queue:new Map,scope:yield*Dt.make(),shared:new Map};if(yield*r.addFinalizer(()=>Dt.close(I.scope,bt.void).pipe(r.andThen(r.sync(()=>{I.queue.clear(),I.shared.clear()})))),$r)return I;let P=i((x,A)=>t.listen(C=>C.type!==x.type||C.location?.directory!==w.directory?r.void:A(C.data).pipe(r.catchCause($=>r.logError("share subscriber failed",{type:x.type,cause:$})))),"watch");return yield*P(me.Event.Updated,x=>r.gen(function*(){let A=x.info;yield*p(A.id,[{type:"session",data:structuredClone(A)}])})),yield*P(Ze.Event.Updated,x=>r.gen(function*(){let A=x.info;if(yield*p(A.sessionID,[{type:"message",data:structuredClone(A)}]),A.role!=="user")return;let C=yield*l.getModel(A.model.providerID,A.model.modelID);yield*p(A.sessionID,[{type:"model",data:[C]}])})),yield*P(Ze.Event.PartUpdated,x=>p(x.part.sessionID,[{type:"part",data:structuredClone(x.part)}])),yield*P(me.Event.Diff,x=>p(x.sessionID,[{type:"session_diff",data:structuredClone(x.diff)}])),yield*P(me.Event.Deleted,x=>k(x.sessionID)),I})),u=r.fn("ShareNext.request")(function*(){let w={},I=yield*e.active();if(xn.isNone(I)||!I.value.active_org_id){let x=(yield*n.get()).enterprise?.url??"https://opncd.ai";return{headers:w,api:iE,baseUrl:x}}let P=yield*e.token(I.value.id);if(xn.isNone(P))throw new Error("No active account token available for sharing");return w.authorization=`Bearer ${P.value}`,w["x-org-id"]=I.value.active_org_id,{headers:w,api:aE,baseUrl:I.value.url}}),g=r.fnUntraced(function*(w){let I=yield*o.select().from(qo).where(St(qo.session_id,w)).get().pipe(r.orDie);if(I)return{id:I.id,secret:I.secret,url:I.url}}),y=r.fnUntraced(function*(w){let I=yield*G.get(f);if(I.shared.has(w)){let x=I.shared.get(w);return x===null?void 0:x}let P=yield*g(w);return I.shared.set(w,P??null),P}),b=r.fn("ShareNext.flush")(function*(w){if($r)return;let I=yield*G.get(f),P=I.queue.get(w);if(!P)return;I.queue.delete(w);let x=yield*y(w);if(!x)return;let A=yield*u(),C=yield*Ve.post(`${A.baseUrl}${A.api.sync(x.id)}`).pipe(Ve.setHeaders(A.headers),Ve.bodyJson({secret:x.secret,data:Array.from(P.values())}),r.flatMap($=>s.execute($)));C.status>=400&&(yield*r.logWarning("failed to sync share",{sessionID:w,shareID:x.id,status:C.status}))}),S=r.fn("ShareNext.full")(function*(w){yield*r.logInfo("full sync",{sessionID:w});let I=yield*d.get(w),P=yield*d.diff(w),x=yield*d.messages({sessionID:w}),A=yield*r.forEach(Array.from(new Map(x.filter(C=>C.info.role==="user").map(C=>C.info.model).map(C=>[`${C.providerID}/${C.modelID}`,C])).values()),C=>l.getModel(sn.ID.make(C.providerID),uo.ID.make(C.modelID)),{concurrency:8});yield*p(w,[{type:"session",data:I},...x.map(C=>({type:"message",data:C.info})),...x.flatMap(C=>C.parts.map($=>({type:"part",data:$}))),{type:"session_diff",data:P},{type:"model",data:A}])}),T=r.fn("ShareNext.init")(function*(){$r||(yield*G.get(f))}),m=r.fn("ShareNext.url")(function*(){return(yield*u()).baseUrl}),h=r.fn("ShareNext.create")(function*(w){if($r)return{id:"",url:"",secret:""};yield*r.logInfo("creating share",{sessionID:w});let I=yield*u(),P=yield*Ve.post(`${I.baseUrl}${I.api.create}`).pipe(Ve.setHeaders(I.headers),Ve.bodyJson({sessionID:w}),r.flatMap(A=>a.execute(A)),r.flatMap(zn.schemaBodyJson(rE)));yield*o.insert(qo).values({session_id:w,id:P.id,secret:P.secret,url:P.url}).onConflictDoUpdate({target:qo.session_id,set:{id:P.id,secret:P.secret,url:P.url}}).run().pipe(r.orDie);let x=yield*G.get(f);return x.shared.set(w,P),yield*S(w).pipe(r.catchCause(A=>r.logError("share full sync failed",{sessionID:w,cause:A})),r.forkIn(x.scope)),P}),k=r.fn("ShareNext.remove")(function*(w){if($r)return;yield*r.logInfo("removing share",{sessionID:w});let I=yield*G.get(f),P=yield*y(w);if(!P){I.shared.delete(w),I.queue.delete(w);return}let x=yield*u();yield*Ve.delete(`${x.baseUrl}${x.api.remove(P.id)}`).pipe(Ve.setHeaders(x.headers),Ve.bodyJson({secret:P.secret}),r.flatMap(A=>a.execute(A))),yield*o.delete(qo).where(St(qo.session_id,w)).run().pipe(r.orDie),I.shared.delete(w),I.queue.delete(w)});return Wo.of({init:T,url:m,request:u,create:h,remove:k})})),lE=ke.make({service:Wo,layer:cE,deps:[Ya.node,De.node,Oe.node,Qe.node,In,yt.node,me.node]});var qr={};fe(qr,{AppNodeBuilderV1:()=>qr,build:()=>fE});var Us={};fe(Us,{InstanceBootstrap:()=>Us,Service:()=>Zo,node:()=>uE});var dE=Te.effect(Zo,r.gen(function*(){let e=yield*Oe.Service,t=yield*Jt.Service,n=yield*ft.Service,o=yield*pt.Service,s=yield*Ku,a=yield*Wn.Service,l=yield*an.Service,d=yield*co,p=r.gen(function*(){let f=yield*G.context;yield*r.logInfo("bootstrapping",{directory:f.directory}),yield*e.get(),yield*o.init(),yield*r.forEach([n,a,t,d,l,s],u=>u.init().pipe(r.catchCause(g=>r.logWarning("init failed",{cause:g}))),{concurrency:"unbounded",discard:!0}).pipe(r.withSpan("InstanceBootstrap.init"))}).pipe(r.withSpan("InstanceBootstrap"));return Zo.of({run:p})})),uE=Xs({service:Zo,layer:dE,deps:[Oe.node,Jt.node,ft.node,pt.node,Xu,Wn.node,an.node,yd]});var pE=[er.bootstrapNode,Us.node];function fE(e,t=[]){return vo.build(e,t.concat([pE]))}i(fE,"build");var vd={};fe(vd,{ConnectionStatus:()=>wE,CreateInput:()=>vE,Event:()=>wd,Info:()=>Ea,Service:()=>Vo,SessionEventsNotFoundError:()=>Pa,SessionWarpHttpError:()=>$s,SessionWarpInput:()=>xE,SyncAbortedError:()=>Ca,SyncHttpError:()=>Bs,SyncTimeoutError:()=>Ra,Workspace:()=>vd,WorkspaceNotFoundError:()=>Ta,node:()=>kE,use:()=>SE});function bd(e){return e.signal?.aborted?r.fail(e.signal.reason??new Error("Request aborted")):r.callback(t=>{let n=i(()=>{s(),t(r.fail(e.signal?.reason??new Error("Request aborted")))},"abort"),o=i(l=>{try{if(!e.fn(l))return;s(),t(r.void)}catch(d){s(),t(r.fail(d))}},"handler"),s=i(()=>{clearTimeout(a),Qo.off("event",o),e.signal?.removeEventListener("abort",n)},"cleanup"),a=setTimeout(()=>{s(),t(r.fail(new Error("Timed out waiting for global event")))},e.timeout);return Qo.on("event",o),e.signal?.addEventListener("abort",n,{once:!0}),r.sync(s)})}i(bd,"waitEvent");var rn={};fe(rn,{WorkspaceAdapterRuntime:()=>rn,configure:()=>hE,create:()=>gE,list:()=>yE,remove:()=>bE,target:()=>mE});var Fs=r.gen(function*(){return{instance:yield*Bu,workspaceID:yield*ui}}),mE=i(e=>r.gen(function*(){let t=ns(e.projectID,e.type),n=yield*Fs;return yield*zt.fromPromise(()=>t.target(e,n))}),"target"),hE=i((e,t)=>r.gen(function*(){let n=yield*Fs;return yield*zt.fromPromise(()=>e.configure(t,n))}),"configure"),gE=i((e,t,n,o)=>r.gen(function*(){let s=yield*Fs;return yield*zt.fromPromise(()=>e.create(t,n,o,s))}),"create"),yE=i(e=>r.gen(function*(){let t=yield*Fs;return yield*zt.fromPromise(()=>Promise.resolve(e.list?.(t)??[]))}),"list"),bE=i(e=>r.gen(function*(){let t=ns(e.projectID,e.type),n=yield*Fs;return yield*zt.fromPromise(()=>t.remove(e,n))}),"remove");var Ea=c.Struct({...Gu.fields,timeUsed:c.Number}).annotate({identifier:"Workspace"}),wE=qa.ConnectionStatus,wd=qa;function Da(e){return{id:e.id,type:e.type,branch:e.branch,name:e.name,directory:e.directory,extra:e.extra,projectID:e.project_id,timeUsed:e.time_used}}i(Da,"fromRow");var vE=c.Struct({id:c.optional(ho.ID),type:Ea.fields.type,branch:Ea.fields.branch,projectID:uu.ID,extra:c.optional(Ea.fields.extra)}),xE=c.Struct({workspaceID:c.NullOr(ho.ID),sessionID:Pt,copyChanges:c.optional(c.Boolean)}),Bs=class extends c.TaggedErrorClass()("WorkspaceSyncHttpError",{message:c.String,status:c.Number,body:c.optional(c.String)}){static{i(this,"SyncHttpError")}},Ta=class extends c.TaggedErrorClass()("WorkspaceNotFoundError",{message:c.String,workspaceID:ho.ID}){static{i(this,"WorkspaceNotFoundError")}},Pa=class extends c.TaggedErrorClass()("WorkspaceSessionEventsNotFoundError",{message:c.String,sessionID:Pt}){static{i(this,"SessionEventsNotFoundError")}},$s=class extends c.TaggedErrorClass()("WorkspaceSessionWarpHttpError",{message:c.String,workspaceID:ho.ID,sessionID:Pt,status:c.Number,body:c.String}){static{i(this,"SessionWarpHttpError")}},Ra=class extends c.TaggedErrorClass()("WorkspaceSyncTimeoutError",{message:c.String,state:c.Record(c.String,c.Number)}){static{i(this,"SyncTimeoutError")}},Ca=class extends c.TaggedErrorClass()("WorkspaceSyncAbortedError",{message:c.String,cause:c.optional(c.Defect())}){static{i(this,"SyncAbortedError")}},Vo=class extends Re.Service()("@opencode/Workspace"){static{i(this,"Service")}},SE=Wt(Vo),IE=Te.effect(Vo,r.gen(function*(){let e=yield*Xt.Service,t=yield*me.Service,n=yield*Br.Service,o=yield*fn.HttpClient,s=yield*De.Service,a=yield*$o.Service,l=yield*Be.Service,d=yield*Ae.Service,{db:p}=yield*Qe.Service,f=new Map,u=yield*Ho.make(),g=i((L,V)=>{if(f.get(L)?.status===V)return;let M={workspaceID:L,status:V};f.set(L,M),Qo.emit("event",{directory:"global",workspace:L,payload:{type:wd.Status.type,properties:M}})},"setStatus"),y=r.fn("Workspace.connectSSE")(function*(L,V){let D=yield*o.execute(Ve.get(Wr(L,"/global/event"),{headers:new Headers(V),accept:"text/event-stream"}));return D.status<200||D.status>=300?yield*new Bs({message:`Workspace sync HTTP failure: ${D.status}`,status:D.status}):D.stream}),b=r.fn("Workspace.parseSSE")(function*(L,V){yield*L.pipe(vt.decodeText(),vt.splitLines,vt.mapAccum(()=>({data:[],id:void 0,retry:1e3}),(D,M)=>{if(M==="")return D.data.length?[{...D,data:[]},[{data:D.data.join(`
1489
1489
  `),id:D.id,retry:D.retry}]]:[D,[]];let _=M.indexOf(":"),N=_===-1?M:M.slice(0,_),W=_===-1?"":M.slice(_+(M[_+1]===" "?2:1));if(N==="data")return[{...D,data:[...D.data,W]},[]];if(N==="id")return[{...D,id:W},[]];if(N==="retry"){let U=Number.parseInt(W,10);return[Number.isNaN(U)?D:{...D,retry:U},[]]}return[D,[]]},{onHalt:i(D=>D.data.length?[{data:D.data.join(`
1490
- `),id:D.id,retry:D.retry}]:[],"onHalt")}),vt.map(D=>{try{return JSON.parse(D.data)}catch{return{type:"sse.message",properties:{data:D.data,id:D.id||void 0,retry:D.retry}}}}),vt.runForEach(V))}),S=i(L=>r.gen(function*(){if(!L.workspaceID)return yield*L.local();let V=yield*A(L.workspaceID);if(!V)return L.fallback;let D=yield*rn.target(V);if(D.type==="local")return yield*(yield*er.Service).provide({directory:D.directory},L.local());let M=yield*o.execute(L.remote({workspace:V,target:D})).pipe(r.catch(N=>r.logWarning("workspace target request failed",{workspaceID:V.id,error:Kn(N)}).pipe(r.as(void 0))));if(!M)return L.fallback;if(M.status<200||M.status>=300){let N=yield*M.text.pipe(r.catch(()=>r.succeed("")));return yield*r.logWarning("workspace target request failed",{workspaceID:V.id,status:M.status,body:N}),L.fallback}return yield*(L.response==="text"?M.text:M.json).pipe(r.map(N=>N),r.catch(N=>r.logWarning("workspace target response decode failed",{workspaceID:V.id,error:Kn(N)}).pipe(r.as(L.fallback))))}),"runInWorkspace"),T=r.fn("Workspace.syncHistory")(function*(L,V,D){let M=(yield*p.select({id:Tt.id}).from(Tt).where(St(Tt.workspace_id,L.id)).all().pipe(r.orDie)).map(U=>U.id),_=M.length?Object.fromEntries((yield*p.select().from(po).where(Ua(po.aggregate_id,M)).all().pipe(r.orDie)).map(U=>[U.aggregate_id,U.seq])):{},N=yield*o.execute(Ve.post(Wr(V,"/sync/history"),{headers:new Headers(D),body:Jr.jsonUnsafe(_)}));if(N.status<200||N.status>=300){let U=yield*N.text;return yield*new Bs({message:`Workspace history HTTP failure: ${N.status} ${U}`,status:N.status,body:U})}let W=yield*N.json;yield*r.forEach(W,U=>s.replay({id:mu.ID.make(U.id),aggregateID:U.aggregate_id,seq:U.seq,type:U.type,data:U.data},{publish:!0,ownerID:L.id}).pipe(r.provideService(ui,L.id)),{discard:!0})}),m=r.fn("Workspace.syncWorkspaceLoop")(function*(L){let V=yield*rn.target(L);if(V.type==="local")return;let D=0;for(;;){g(L.id,"connecting");let M=yield*y(V.url,V.headers).pipe(r.tap(()=>T(L,V.url,V.headers)),r.catch(_=>r.gen(function*(){return g(L.id,"error"),yield*r.logWarning("failed to connect to global sync",{workspace:L.name,error:Kn(_)}),null})));M&&(D=0,g(L.id,"connected"),yield*b(M,_=>r.gen(function*(){if(!_||typeof _!="object"||!("payload"in _))return;let N=_.payload;if(N.type!=="server.heartbeat"&&!(N.type==="sync"&&N.syncEvent&&(yield*s.replay(N.syncEvent,{publish:!0,ownerID:L.id}).pipe(r.as(!1),r.catchCause(U=>r.logWarning("failed to replay global event",U).pipe(r.annotateLogs({workspaceID:L.id}),r.as(!0)))))))try{let W=_;Qo.emit("event",{directory:W.directory,project:W.project,workspace:L.id,payload:W.payload})}catch(W){yield*r.logWarning("failed to emit global event",{workspaceID:L.id,error:Kn(W)})}})),g(L.id,"disconnected")),yield*r.sleep(`${Math.min(12e4,1e3*2**D)} millis`),D+=1}}),h=r.fn("Workspace.startSync")(function*(L){if(!l.experimentalWorkspaces)return;let V=yield*rn.target(L).pipe(r.catch(M=>r.gen(function*(){return g(L.id,"error"),yield*r.logWarning("workspace target failed",{workspaceID:L.id,error:Kn(M)}),null})));if(!V)return;if(V.type==="local"){g(L.id,(yield*d.existsSafe(V.directory))?"connected":"error");return}(yield*Ho.has(u,L.id))&&f.get(L.id)?.status!=="error"||(g(L.id,"disconnected"),yield*Ho.run(u,L.id,m(L).pipe(r.catch(M=>r.gen(function*(){g(L.id,"error"),yield*r.logWarning("workspace listener failed",{workspaceID:L.id,error:Kn(M)})})))))}),k=r.fn("Workspace.stopSync")(function*(L){yield*Ho.remove(u,L),f.delete(L)}),w=r.fn("Workspace.create")(function*(L){let V=ho.ID.ascending(L.id),D=ns(L.projectID,L.type),M=yield*rn.configure(D,{...L,id:V,name:hu.create(),directory:null,extra:L.extra??null}),_={id:V,type:M.type,branch:M.branch??null,name:M.name??null,directory:M.directory??null,extra:M.extra??null,projectID:L.projectID,timeUsed:Date.now()};yield*p.insert(Vt).values({id:_.id,type:_.type,branch:_.branch,name:_.name,directory:_.directory,extra:_.extra,project_id:_.projectID,time_used:_.timeUsed}).run().pipe(r.orDie);let N={OPENCODE_AUTH_CONTENT:JSON.stringify(yield*e.all()),OPENCODE_WORKSPACE_ID:M.id,OPENCODE_EXPERIMENTAL_WORKSPACES:"true",OTEL_EXPORTER_OTLP_HEADERS:process.env.OTEL_EXPORTER_OTLP_HEADERS,OTEL_EXPORTER_OTLP_ENDPOINT:process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_RESOURCE_ATTRIBUTES:process.env.OTEL_RESOURCE_ATTRIBUTES};return yield*rn.create(D,M,N),yield*r.all([bd({timeout:mg,fn(W){if(W.workspace===_.id&&W.payload.type===wd.Status.type){let{status:U}=W.payload.properties;return U==="error"||U==="connected"}return!1}}),h(_)],{concurrency:2,discard:!0}),_}),I=r.fn("Workspace.sessionWarp")(function*(L){return yield*r.gen(function*(){let V=yield*p.select({workspaceID:Tt.workspace_id}).from(Tt).where(St(Tt.id,L.sessionID)).get().pipe(r.orDie);if(V?.workspaceID){let ce=yield*A(V.workspaceID);if(ce){let re=yield*rn.target(ce);re.type==="remote"?yield*T(ce,re.url,re.headers).pipe(r.catch(R=>r.logWarning("session warp final source sync failed",{workspaceID:ce.id,sessionID:L.sessionID,error:Kn(R)}))):yield*n.cancel(L.sessionID),yield*s.claim(L.sessionID,L.workspaceID??ce.projectID)}}let D=L.copyChanges&&V?.workspaceID?yield*S({workspaceID:V?.workspaceID??void 0,local:i(()=>a.diffRaw(),"local"),remote:i(({target:ce})=>Ve.get(Wr(ce.url,"/vcs/diff/raw"),{headers:new Headers(ce.headers)}),"remote"),fallback:"",response:"text"}).pipe(r.provide(qr.build(er.node))):"";if(D&&(yield*S({workspaceID:L.workspaceID??void 0,local:i(()=>a.apply({patch:D}),"local"),remote:i(({target:ce})=>Ve.post(Wr(ce.url,"/vcs/apply"),{headers:new Headers(ce.headers),body:Jr.jsonUnsafe({patch:D})}),"remote"),fallback:{applied:!1}}).pipe(r.provide(qr.build(er.node)))),L.workspaceID===null){yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:void 0});return}let M=L.workspaceID,_=yield*A(M);if(!_)return yield*new Ta({message:`Workspace not found: ${M}`,workspaceID:M});let N=yield*rn.target(_);if(N.type==="local"){yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:L.workspaceID});return}let W=yield*p.select({id:An.id,aggregateID:An.aggregate_id,seq:An.seq,type:An.type,data:An.data}).from(An).where(St(An.aggregate_id,L.sessionID)).orderBy(Zs(An.seq)).all().pipe(r.orDie);if(W.length===0)return yield*new Pa({message:`No events found for session: ${L.sessionID}`,sessionID:L.sessionID});let U=_a.chunksOf(W,10),we=_a.size(U);yield*r.forEach(U,(ce,re)=>r.gen(function*(){let R=yield*o.execute(Ve.post(Wr(N.url,"/sync/replay"),{headers:new Headers(N.headers),body:Jr.jsonUnsafe({directory:_.directory??"",events:ce})}));if(R.status<200||R.status>=300){let q=yield*R.text;return yield*new $s({message:`Failed to warp session ${L.sessionID} into workspace ${M}: HTTP ${R.status} ${q}`,workspaceID:M,sessionID:L.sessionID,status:R.status,body:q})}}),{discard:!0});let pe=yield*o.execute(Ve.post(Wr(N.url,"/sync/steal"),{headers:new Headers(N.headers),body:Jr.jsonUnsafe({sessionID:L.sessionID})}));if(pe.status<200||pe.status>=300){let ce=yield*pe.text;return yield*new $s({message:`Failed to steal session ${L.sessionID} into workspace ${M}: HTTP ${pe.status} ${ce}`,workspaceID:M,sessionID:L.sessionID,status:pe.status,body:ce})}yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:L.workspaceID})})}),P=r.fn("Workspace.list")(function*(L){return l.experimentalWorkspaces?(yield*p.select().from(Vt).where(St(Vt.project_id,L.id)).all().pipe(r.orDie)).map(Da).sort((V,D)=>V.id.localeCompare(D.id)):[]}),x=r.fn("Workspace.syncList")(function*(L){let V=new Set((yield*P(L)).map(M=>M.name)),D=yield*r.forEach(Qu(L.id),([M,_])=>rn.list(_).pipe(r.catchCause(N=>r.logWarning("workspace adapter list failed",{type:M,error:N}).pipe(r.as([])))),{concurrency:"unbounded"}).pipe(r.map(M=>M.flat()));yield*r.forEach(D,M=>r.gen(function*(){if(V.has(M.name))return;V.add(M.name);let _={id:ho.ID.ascending(),type:M.type,branch:M.branch,name:M.name,directory:M.directory,extra:M.extra,projectID:M.projectID,timeUsed:Date.now()};yield*p.insert(Vt).values({id:_.id,type:_.type,branch:_.branch,name:_.name,directory:_.directory,extra:_.extra,project_id:_.projectID,time_used:_.timeUsed}).run().pipe(r.orDie),yield*h(_)}),{concurrency:1})}),A=r.fn("Workspace.get")(function*(L){let V=yield*p.select().from(Vt).where(St(Vt.id,L)).get().pipe(r.orDie);if(V)return Da(V)}),C=r.fn("Workspace.remove")(function*(L){let V=yield*p.select({id:Tt.id,parentID:Tt.parent_id}).from(Tt).where(St(Tt.workspace_id,L)).all().pipe(r.orDie),D=new Set(V.map(N=>N.id));yield*r.forEach(V.filter(N=>!N.parentID||!D.has(N.parentID)),N=>t.remove(N.id).pipe(r.catchIf(mi.isInstance,()=>r.void)),{discard:!0});let M=yield*p.select().from(Vt).where(St(Vt.id,L)).get().pipe(r.orDie);if(!M)return;yield*k(L);let _=Da(M);return yield*r.catchCause(r.gen(function*(){yield*rn.remove(_)}),()=>r.logError("adapter not available when removing workspace",{type:M.type})),yield*p.delete(Vt).where(St(Vt.id,L)).run().pipe(r.orDie),_}),$=r.fn("Workspace.status")(function*(){return[...f.values()]}),j=r.fn("Workspace.isSyncing")(function*(L){return(yield*Ho.has(u,L))&&f.get(L)?.status!=="error"}),z=r.fn("Workspace.waitForSync")(function*(L,V,D,M=mg){(yield*gg(p,V))||(yield*r.catch(hg({db:p,workspaceID:L,state:V,signal:D,timeout:M}),()=>D?.aborted?r.fail(new Ca({message:D.reason instanceof Error?D.reason.message:"Request aborted",cause:D.reason})):r.fail(new Ra({message:`Timed out waiting for sync fence: ${JSON.stringify(V)}`,state:V}))))}),ie=r.fn("Workspace.startWorkspaceSyncing")(function*(L){if(!l.experimentalWorkspaces)return;let V=yield*p.selectDistinct({workspace:Vt}).from(Vt).where(St(Vt.project_id,L)).all().pipe(r.orDie);for(let{workspace:D}of V)yield*h(Da(D)).pipe(r.catch(M=>r.sync(()=>{g(D.id,"error")})),r.forkDetach)});return Vo.of({create:w,sessionWarp:I,list:P,syncList:x,get:A,remove:C,status:$,isSyncing:j,waitForSync:z,startWorkspaceSyncing:ie})})),mg=5e3;function hg(e){return r.suspend(()=>bd({timeout:e.timeout,signal:e.signal,fn(t){return t.workspace===e.workspaceID||t.payload.type==="sync"}}).pipe(r.andThen(gg(e.db,e.state)),r.flatMap(t=>t?r.void:hg(e))))}i(hg,"waitUntilSynced");function gg(e,t){let n=Object.keys(t);return n.length===0?r.succeed(!0):e.select({id:po.aggregate_id,seq:po.seq}).from(po).where(Ua(po.aggregate_id,n)).all().pipe(r.orDie,r.map(o=>{let s=Object.fromEntries(o.map(a=>[a.id,a.seq]));return n.every(a=>(s[a]??-1)>=t[a])}))}i(gg,"synced");function Wr(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/$/,"")}${t}`,n.search="",n.hash="",n}i(Wr,"route");var vE=ke.make({service:Vo,layer:wE,deps:[Xt.node,me.node,Br.node,In,De.node,$o.node,Be.node,Ae.node,Qe.node]});var Sd={};fe(Sd,{Event:()=>SE,Info:()=>kE,Installation:()=>Sd,Service:()=>lo,USER_AGENT:()=>DE,UpgradeFailedError:()=>Vr,getReleaseType:()=>IE,isLocal:()=>TE,isPreview:()=>EE,latest:()=>LE,method:()=>NE,node:()=>Sg,upgrade:()=>jE,use:()=>_E,userAgent:()=>vg});import wg from"path";var Ws=kd(kg());var qs={};fe(qs,{Definitions:()=>xE,InstallationEvent:()=>qs,UpdateAvailable:()=>bg,Updated:()=>yg});var yg=Et.define({type:"installation.updated",schema:{version:c.String}}),bg=Et.define({type:"installation.update-available",schema:{version:c.String}}),xE=Et.inventory(yg,bg);var SE=qs;function IE(e,t){let n=Ws.default.major(e),o=Ws.default.minor(e),s=Ws.default.major(t),a=Ws.default.minor(t);return s>n?"major":a>o?"minor":"patch"}i(IE,"getReleaseType");var kE=c.Struct({version:c.String,latest:c.String}).annotate({identifier:"InstallationInfo"});function vg(e="cli"){return`opencode/${Zr}/${Qr}/${e}`}i(vg,"userAgent");var DE=vg();function EE(){return Zr!=="latest"}i(EE,"isPreview");function TE(){return Zr==="local"}i(TE,"isLocal");var Vr=class extends c.TaggedErrorClass()("UpgradeFailedError",{stderr:c.String}){static{i(this,"UpgradeFailedError")}get message(){return this.stderr}},PE=c.Struct({tag_name:c.String}),xg=c.Struct({version:c.String}),RE=c.Struct({versions:c.Struct({stable:c.String})}),CE=c.Struct({formulae:c.Array(c.Struct({versions:c.Struct({stable:c.String})}))}),AE=c.Struct({d:c.Struct({results:c.Array(c.Struct({Version:c.String}))})}),ME=xg,lo=class extends Re.Service()("@opencode/Installation"){static{i(this,"Service")}},_E=Wt(lo),OE=Te.effect(lo,r.gen(function*(){let e=yield*fn.HttpClient,t=fn.filterStatusOk(li(e)),n=yield*Ko.Service,o=r.fnUntraced(function*(u,g){return(yield*n.run(Vn.make(u[0],u.slice(1),{cwd:g?.cwd,env:g?.env,extendEnv:!0}))).stdout.toString("utf8")},r.catch(()=>r.succeed(""))),s=r.fnUntraced(function*(u,g){let y=yield*n.run(Vn.make(u[0],u.slice(1),{cwd:g?.cwd,env:g?.env,extendEnv:!0}));return{code:y.exitCode,stdout:y.stdout.toString("utf8"),stderr:y.stderr.toString("utf8")}},r.catch(u=>r.succeed({code:1,stdout:"",stderr:gn(u)}))),a=r.fnUntraced(function*(){return(yield*o(["brew","list","--formula","anomalyco/tap/opencode"])).includes("opencode")?"anomalyco/tap/opencode":((yield*o(["brew","list","--formula","opencode"])).includes("opencode"),"opencode")}),l=i((u,g)=>u==="choco"?"not running from an elevated command shell":g?`Upgrade failed for ${u} (exit code ${g.code}).`:`Upgrade failed for ${u}.`,"upgradeFailure"),d=r.fnUntraced(function*(){return(yield*o(["bash","--version"]))?"bash":"sh"}),p=r.fnUntraced(function*(u){let y=yield*(yield*t.execute(Ve.get("https://opencode.ai/install"))).text,b=new TextEncoder().encode(y),S=yield*d(),T=yield*n.run(Vn.make(S,[],{stdin:vt.make(b),env:{VERSION:u},extendEnv:!0}));return{code:T.exitCode,stdout:T.stdout.toString("utf8"),stderr:T.stderr.toString("utf8")}},r.mapError(()=>new Vr({stderr:l("curl")}))),f={info:r.fn("Installation.info")(function*(){return{version:Qr,latest:yield*f.latest()}}),method:r.fn("Installation.method")(function*(){if(process.execPath.includes(wg.join(".opencode","bin"))||process.execPath.includes(wg.join(".local","bin")))return"curl";let u=process.execPath.toLowerCase(),g=[{name:"npm",command:i(()=>o(["npm","list","-g","--depth=0"]),"command")},{name:"yarn",command:i(()=>o(["yarn","global","list"]),"command")},{name:"pnpm",command:i(()=>o(["pnpm","list","-g","--depth=0"]),"command")},{name:"bun",command:i(()=>o(["bun","pm","ls","-g"]),"command")},{name:"brew",command:i(()=>o(["brew","list","--formula","opencode"]),"command")},{name:"scoop",command:i(()=>o(["scoop","list","opencode"]),"command")},{name:"choco",command:i(()=>o(["choco","list","--limit-output","opencode"]),"command")}];g.sort((y,b)=>{let S=u.includes(y.name),T=u.includes(b.name);return S&&!T?-1:!S&&T?1:0});for(let y of g){let b=yield*y.command(),S=y.name==="brew"||y.name==="choco"||y.name==="scoop"?"opencode":"opencode-ai";if(b.includes(S))return y.name}return"unknown"}),latest:r.fn("Installation.latest")(function*(u){let g=u||(yield*f.method());if(g==="brew"){let S=yield*a();if(S.includes("/")){let h=yield*o(["brew","info","--json=v2",S]);return(yield*c.decodeUnknownEffect(c.fromJsonString(CE))(h)).formulae[0].versions.stable}let T=yield*t.execute(Ve.get("https://formulae.brew.sh/api/formula/opencode.json").pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(RE)(T)).versions.stable}if(g==="npm"||g==="bun"||g==="pnpm"){let S=yield*t.execute(Ve.get(`${yield*Tu.registry(process.cwd())}/opencode-ai/${Zr}`).pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(xg)(S)).version}if(g==="choco"){let S=yield*t.execute(Ve.get("https://community.chocolatey.org/api/v2/Packages?$filter=Id%20eq%20%27opencode%27%20and%20IsLatestVersion&$select=Version").pipe(Ve.setHeaders({Accept:"application/json;odata=verbose"})));return(yield*zn.schemaBodyJson(AE)(S)).d.results[0].Version}if(g==="scoop"){let S=yield*t.execute(Ve.get("https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/opencode.json").pipe(Ve.setHeaders({Accept:"application/json"})));return(yield*zn.schemaBodyJson(ME)(S)).version}let y=yield*t.execute(Ve.get("https://api.github.com/repos/anomalyco/opencode/releases/latest").pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(PE)(y)).tag_name.replace(/^v/,"")},r.orDie),upgrade:r.fn("Installation.upgrade")(function*(u,g){let y;switch(u){case"curl":y=yield*p(g);break;case"npm":y=yield*s(["npm","install","-g",`opencode-ai@${g}`]);break;case"pnpm":y=yield*s(["pnpm","install","-g",`opencode-ai@${g}`]);break;case"bun":y=yield*s(["bun","install","-g",`opencode-ai@${g}`]);break;case"brew":{let b=yield*a(),S={HOMEBREW_NO_AUTO_UPDATE:"1"};if(b.includes("/")){let T=yield*s(["brew","tap","anomalyco/tap"],{env:S});if(T.code!==0){y=T;break}let h=(yield*o(["brew","--repo","anomalyco/tap"])).trim();if(h){let k=yield*s(["git","pull","--ff-only"],{cwd:h,env:S});if(k.code!==0){y=k;break}}}y=yield*s(["brew","upgrade",b],{env:S});break}case"choco":y=yield*s(["choco","upgrade","opencode",`--version=${g}`,"-y"]);break;case"scoop":y=yield*s(["scoop","install",`opencode@${g}`]);break;default:return yield*new Vr({stderr:`Unknown installation method: ${u}`})}if(!y||y.code!==0)return yield*new Vr({stderr:l(u,y)});yield*r.logInfo("upgraded",{method:u,target:g,stdout:y.stdout,stderr:y.stderr}),yield*o([process.execPath,"--version"])})};return lo.of(f)})),Sg=ke.make({service:lo,layer:OE,deps:[In,Ko.node]}),{runPromise:xd}=Eu(lo,vo.build(Sg)),LE=i((...e)=>xd(t=>t.latest(...e)),"latest"),NE=i(()=>xd(e=>e.method()),"method"),jE=i((...e)=>xd(t=>t.upgrade(...e)),"upgrade");var Id={};fe(Id,{Service:()=>zr,SessionShare:()=>Id,node:()=>FE});var zr=class extends Re.Service()("@opencode/SessionShare"){static{i(this,"Service")}},UE=Te.effect(zr,r.gen(function*(){let e=yield*Oe.Service,t=yield*me.Service,n=yield*Wn.Service,o=yield*Dt.Scope,s=yield*Be.Service,a=r.fn("SessionShare.share")(function*(p){if((yield*e.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let u=yield*n.create(p);return yield*t.setShare({sessionID:p,share:{url:u.url}}),u}),l=r.fn("SessionShare.unshare")(function*(p){yield*n.remove(p),yield*t.setShare({sessionID:p,share:void 0})}),d=r.fn("SessionShare.create")(function*(p){let f=yield*t.create(p);if(f.parentID)return f;let u=yield*e.get();return(s.autoShare||u.share==="auto")&&(yield*a(f.id).pipe(r.ignore,r.forkIn(o))),f});return zr.of({create:d,share:a,unshare:l})})),FE=ke.make({service:zr,layer:UE,deps:[Oe.node,me.node,Wn.node,Be.node]});export{vo as a,sc as b,Ot as c,ac as d,Qt as e,Qn as f,or as g,ln as h,Ln as i,dn as j,un as k,jn as l,ys as m,gr as n,br as o,En as p,Ds as q,ft as r,Jt as s,Mo as t,bh as u,$n as v,Bo as w,Br as x,Ls as y,$o as z,rn as A,Wn as B,qr as C,vd as D,qs as E,Sd as F,Id as G};
1490
+ `),id:D.id,retry:D.retry}]:[],"onHalt")}),vt.map(D=>{try{return JSON.parse(D.data)}catch{return{type:"sse.message",properties:{data:D.data,id:D.id||void 0,retry:D.retry}}}}),vt.runForEach(V))}),S=i(L=>r.gen(function*(){if(!L.workspaceID)return yield*L.local();let V=yield*A(L.workspaceID);if(!V)return L.fallback;let D=yield*rn.target(V);if(D.type==="local")return yield*(yield*er.Service).provide({directory:D.directory},L.local());let M=yield*o.execute(L.remote({workspace:V,target:D})).pipe(r.catch(N=>r.logWarning("workspace target request failed",{workspaceID:V.id,error:Kn(N)}).pipe(r.as(void 0))));if(!M)return L.fallback;if(M.status<200||M.status>=300){let N=yield*M.text.pipe(r.catch(()=>r.succeed("")));return yield*r.logWarning("workspace target request failed",{workspaceID:V.id,status:M.status,body:N}),L.fallback}return yield*(L.response==="text"?M.text:M.json).pipe(r.map(N=>N),r.catch(N=>r.logWarning("workspace target response decode failed",{workspaceID:V.id,error:Kn(N)}).pipe(r.as(L.fallback))))}),"runInWorkspace"),T=r.fn("Workspace.syncHistory")(function*(L,V,D){let M=(yield*p.select({id:Tt.id}).from(Tt).where(St(Tt.workspace_id,L.id)).all().pipe(r.orDie)).map(U=>U.id),_=M.length?Object.fromEntries((yield*p.select().from(po).where(Ua(po.aggregate_id,M)).all().pipe(r.orDie)).map(U=>[U.aggregate_id,U.seq])):{},N=yield*o.execute(Ve.post(Wr(V,"/sync/history"),{headers:new Headers(D),body:Jr.jsonUnsafe(_)}));if(N.status<200||N.status>=300){let U=yield*N.text;return yield*new Bs({message:`Workspace history HTTP failure: ${N.status} ${U}`,status:N.status,body:U})}let W=yield*N.json;yield*r.forEach(W,U=>s.replay({id:mu.ID.make(U.id),aggregateID:U.aggregate_id,seq:U.seq,type:U.type,data:U.data},{publish:!0,ownerID:L.id}).pipe(r.provideService(ui,L.id)),{discard:!0})}),m=r.fn("Workspace.syncWorkspaceLoop")(function*(L){let V=yield*rn.target(L);if(V.type==="local")return;let D=0;for(;;){g(L.id,"connecting");let M=yield*y(V.url,V.headers).pipe(r.tap(()=>T(L,V.url,V.headers)),r.catch(_=>r.gen(function*(){return g(L.id,"error"),yield*r.logWarning("failed to connect to global sync",{workspace:L.name,error:Kn(_)}),null})));M&&(D=0,g(L.id,"connected"),yield*b(M,_=>r.gen(function*(){if(!_||typeof _!="object"||!("payload"in _))return;let N=_.payload;if(N.type!=="server.heartbeat"&&!(N.type==="sync"&&N.syncEvent&&(yield*s.replay(N.syncEvent,{publish:!0,ownerID:L.id}).pipe(r.as(!1),r.catchCause(U=>r.logWarning("failed to replay global event",U).pipe(r.annotateLogs({workspaceID:L.id}),r.as(!0)))))))try{let W=_;Qo.emit("event",{directory:W.directory,project:W.project,workspace:L.id,payload:W.payload})}catch(W){yield*r.logWarning("failed to emit global event",{workspaceID:L.id,error:Kn(W)})}})),g(L.id,"disconnected")),yield*r.sleep(`${Math.min(12e4,1e3*2**D)} millis`),D+=1}}),h=r.fn("Workspace.startSync")(function*(L){if(!l.experimentalWorkspaces)return;let V=yield*rn.target(L).pipe(r.catch(M=>r.gen(function*(){return g(L.id,"error"),yield*r.logWarning("workspace target failed",{workspaceID:L.id,error:Kn(M)}),null})));if(!V)return;if(V.type==="local"){g(L.id,(yield*d.existsSafe(V.directory))?"connected":"error");return}(yield*Ho.has(u,L.id))&&f.get(L.id)?.status!=="error"||(g(L.id,"disconnected"),yield*Ho.run(u,L.id,m(L).pipe(r.catch(M=>r.gen(function*(){g(L.id,"error"),yield*r.logWarning("workspace listener failed",{workspaceID:L.id,error:Kn(M)})})))))}),k=r.fn("Workspace.stopSync")(function*(L){yield*Ho.remove(u,L),f.delete(L)}),w=r.fn("Workspace.create")(function*(L){let V=ho.ID.ascending(L.id),D=ns(L.projectID,L.type),M=yield*rn.configure(D,{...L,id:V,name:hu.create(),directory:null,extra:L.extra??null}),_={id:V,type:M.type,branch:M.branch??null,name:M.name??null,directory:M.directory??null,extra:M.extra??null,projectID:L.projectID,timeUsed:Date.now()};yield*p.insert(Vt).values({id:_.id,type:_.type,branch:_.branch,name:_.name,directory:_.directory,extra:_.extra,project_id:_.projectID,time_used:_.timeUsed}).run().pipe(r.orDie);let N={OPENCODE_AUTH_CONTENT:JSON.stringify(yield*e.all()),OPENCODE_WORKSPACE_ID:M.id,OPENCODE_EXPERIMENTAL_WORKSPACES:"true",OTEL_EXPORTER_OTLP_HEADERS:process.env.OTEL_EXPORTER_OTLP_HEADERS,OTEL_EXPORTER_OTLP_ENDPOINT:process.env.OTEL_EXPORTER_OTLP_ENDPOINT,OTEL_RESOURCE_ATTRIBUTES:process.env.OTEL_RESOURCE_ATTRIBUTES};return yield*rn.create(D,M,N),yield*r.all([bd({timeout:mg,fn(W){if(W.workspace===_.id&&W.payload.type===wd.Status.type){let{status:U}=W.payload.properties;return U==="error"||U==="connected"}return!1}}),h(_)],{concurrency:2,discard:!0}),_}),I=r.fn("Workspace.sessionWarp")(function*(L){return yield*r.gen(function*(){let V=yield*p.select({workspaceID:Tt.workspace_id}).from(Tt).where(St(Tt.id,L.sessionID)).get().pipe(r.orDie);if(V?.workspaceID){let ce=yield*A(V.workspaceID);if(ce){let re=yield*rn.target(ce);re.type==="remote"?yield*T(ce,re.url,re.headers).pipe(r.catch(R=>r.logWarning("session warp final source sync failed",{workspaceID:ce.id,sessionID:L.sessionID,error:Kn(R)}))):yield*n.cancel(L.sessionID),yield*s.claim(L.sessionID,L.workspaceID??ce.projectID)}}let D=L.copyChanges&&V?.workspaceID?yield*S({workspaceID:V?.workspaceID??void 0,local:i(()=>a.diffRaw(),"local"),remote:i(({target:ce})=>Ve.get(Wr(ce.url,"/vcs/diff/raw"),{headers:new Headers(ce.headers)}),"remote"),fallback:"",response:"text"}).pipe(r.provide(qr.build(er.node))):"";if(D&&(yield*S({workspaceID:L.workspaceID??void 0,local:i(()=>a.apply({patch:D}),"local"),remote:i(({target:ce})=>Ve.post(Wr(ce.url,"/vcs/apply"),{headers:new Headers(ce.headers),body:Jr.jsonUnsafe({patch:D})}),"remote"),fallback:{applied:!1}}).pipe(r.provide(qr.build(er.node)))),L.workspaceID===null){yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:void 0});return}let M=L.workspaceID,_=yield*A(M);if(!_)return yield*new Ta({message:`Workspace not found: ${M}`,workspaceID:M});let N=yield*rn.target(_);if(N.type==="local"){yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:L.workspaceID});return}let W=yield*p.select({id:An.id,aggregateID:An.aggregate_id,seq:An.seq,type:An.type,data:An.data}).from(An).where(St(An.aggregate_id,L.sessionID)).orderBy(Zs(An.seq)).all().pipe(r.orDie);if(W.length===0)return yield*new Pa({message:`No events found for session: ${L.sessionID}`,sessionID:L.sessionID});let U=_a.chunksOf(W,10),we=_a.size(U);yield*r.forEach(U,(ce,re)=>r.gen(function*(){let R=yield*o.execute(Ve.post(Wr(N.url,"/sync/replay"),{headers:new Headers(N.headers),body:Jr.jsonUnsafe({directory:_.directory??"",events:ce})}));if(R.status<200||R.status>=300){let q=yield*R.text;return yield*new $s({message:`Failed to warp session ${L.sessionID} into workspace ${M}: HTTP ${R.status} ${q}`,workspaceID:M,sessionID:L.sessionID,status:R.status,body:q})}}),{discard:!0});let pe=yield*o.execute(Ve.post(Wr(N.url,"/sync/steal"),{headers:new Headers(N.headers),body:Jr.jsonUnsafe({sessionID:L.sessionID})}));if(pe.status<200||pe.status>=300){let ce=yield*pe.text;return yield*new $s({message:`Failed to steal session ${L.sessionID} into workspace ${M}: HTTP ${pe.status} ${ce}`,workspaceID:M,sessionID:L.sessionID,status:pe.status,body:ce})}yield*t.setWorkspace({sessionID:L.sessionID,workspaceID:L.workspaceID})})}),P=r.fn("Workspace.list")(function*(L){return l.experimentalWorkspaces?(yield*p.select().from(Vt).where(St(Vt.project_id,L.id)).all().pipe(r.orDie)).map(Da).sort((V,D)=>V.id.localeCompare(D.id)):[]}),x=r.fn("Workspace.syncList")(function*(L){let V=new Set((yield*P(L)).map(M=>M.name)),D=yield*r.forEach(Qu(L.id),([M,_])=>rn.list(_).pipe(r.catchCause(N=>r.logWarning("workspace adapter list failed",{type:M,error:N}).pipe(r.as([])))),{concurrency:"unbounded"}).pipe(r.map(M=>M.flat()));yield*r.forEach(D,M=>r.gen(function*(){if(V.has(M.name))return;V.add(M.name);let _={id:ho.ID.ascending(),type:M.type,branch:M.branch,name:M.name,directory:M.directory,extra:M.extra,projectID:M.projectID,timeUsed:Date.now()};yield*p.insert(Vt).values({id:_.id,type:_.type,branch:_.branch,name:_.name,directory:_.directory,extra:_.extra,project_id:_.projectID,time_used:_.timeUsed}).run().pipe(r.orDie),yield*h(_)}),{concurrency:1})}),A=r.fn("Workspace.get")(function*(L){let V=yield*p.select().from(Vt).where(St(Vt.id,L)).get().pipe(r.orDie);if(V)return Da(V)}),C=r.fn("Workspace.remove")(function*(L){let V=yield*p.select({id:Tt.id,parentID:Tt.parent_id}).from(Tt).where(St(Tt.workspace_id,L)).all().pipe(r.orDie),D=new Set(V.map(N=>N.id));yield*r.forEach(V.filter(N=>!N.parentID||!D.has(N.parentID)),N=>t.remove(N.id).pipe(r.catchIf(mi.isInstance,()=>r.void)),{discard:!0});let M=yield*p.select().from(Vt).where(St(Vt.id,L)).get().pipe(r.orDie);if(!M)return;yield*k(L);let _=Da(M);return yield*r.catchCause(r.gen(function*(){yield*rn.remove(_)}),()=>r.logError("adapter not available when removing workspace",{type:M.type})),yield*p.delete(Vt).where(St(Vt.id,L)).run().pipe(r.orDie),_}),$=r.fn("Workspace.status")(function*(){return[...f.values()]}),j=r.fn("Workspace.isSyncing")(function*(L){return(yield*Ho.has(u,L))&&f.get(L)?.status!=="error"}),z=r.fn("Workspace.waitForSync")(function*(L,V,D,M=mg){(yield*gg(p,V))||(yield*r.catch(hg({db:p,workspaceID:L,state:V,signal:D,timeout:M}),()=>D?.aborted?r.fail(new Ca({message:D.reason instanceof Error?D.reason.message:"Request aborted",cause:D.reason})):r.fail(new Ra({message:`Timed out waiting for sync fence: ${JSON.stringify(V)}`,state:V}))))}),ie=r.fn("Workspace.startWorkspaceSyncing")(function*(L){if(!l.experimentalWorkspaces)return;let V=yield*p.selectDistinct({workspace:Vt}).from(Vt).where(St(Vt.project_id,L)).all().pipe(r.orDie);for(let{workspace:D}of V)yield*h(Da(D)).pipe(r.catch(M=>r.sync(()=>{g(D.id,"error")})),r.forkDetach)});return Vo.of({create:w,sessionWarp:I,list:P,syncList:x,get:A,remove:C,status:$,isSyncing:j,waitForSync:z,startWorkspaceSyncing:ie})})),mg=5e3;function hg(e){return r.suspend(()=>bd({timeout:e.timeout,signal:e.signal,fn(t){return t.workspace===e.workspaceID||t.payload.type==="sync"}}).pipe(r.andThen(gg(e.db,e.state)),r.flatMap(t=>t?r.void:hg(e))))}i(hg,"waitUntilSynced");function gg(e,t){let n=Object.keys(t);return n.length===0?r.succeed(!0):e.select({id:po.aggregate_id,seq:po.seq}).from(po).where(Ua(po.aggregate_id,n)).all().pipe(r.orDie,r.map(o=>{let s=Object.fromEntries(o.map(a=>[a.id,a.seq]));return n.every(a=>(s[a]??-1)>=t[a])}))}i(gg,"synced");function Wr(e,t){let n=new URL(e);return n.pathname=`${n.pathname.replace(/\/$/,"")}${t}`,n.search="",n.hash="",n}i(Wr,"route");var kE=ke.make({service:Vo,layer:IE,deps:[Xt.node,me.node,Br.node,In,De.node,$o.node,Be.node,Ae.node,Qe.node]});var Sd={};fe(Sd,{Event:()=>EE,Info:()=>PE,Installation:()=>Sd,Service:()=>lo,USER_AGENT:()=>RE,UpgradeFailedError:()=>Vr,getReleaseType:()=>TE,isLocal:()=>AE,isPreview:()=>CE,latest:()=>FE,method:()=>BE,node:()=>Sg,upgrade:()=>$E,use:()=>jE,userAgent:()=>vg});import wg from"path";var Ws=kd(kg());var qs={};fe(qs,{Definitions:()=>DE,InstallationEvent:()=>qs,UpdateAvailable:()=>bg,Updated:()=>yg});var yg=Et.define({type:"installation.updated",schema:{version:c.String}}),bg=Et.define({type:"installation.update-available",schema:{version:c.String}}),DE=Et.inventory(yg,bg);var EE=qs;function TE(e,t){let n=Ws.default.major(e),o=Ws.default.minor(e),s=Ws.default.major(t),a=Ws.default.minor(t);return s>n?"major":a>o?"minor":"patch"}i(TE,"getReleaseType");var PE=c.Struct({version:c.String,latest:c.String}).annotate({identifier:"InstallationInfo"});function vg(e="cli"){return`opencode/${Zr}/${Qr}/${e}`}i(vg,"userAgent");var RE=vg();function CE(){return Zr!=="latest"}i(CE,"isPreview");function AE(){return Zr==="local"}i(AE,"isLocal");var Vr=class extends c.TaggedErrorClass()("UpgradeFailedError",{stderr:c.String}){static{i(this,"UpgradeFailedError")}get message(){return this.stderr}},ME=c.Struct({tag_name:c.String}),xg=c.Struct({version:c.String}),_E=c.Struct({versions:c.Struct({stable:c.String})}),OE=c.Struct({formulae:c.Array(c.Struct({versions:c.Struct({stable:c.String})}))}),LE=c.Struct({d:c.Struct({results:c.Array(c.Struct({Version:c.String}))})}),NE=xg,lo=class extends Re.Service()("@opencode/Installation"){static{i(this,"Service")}},jE=Wt(lo),UE=Te.effect(lo,r.gen(function*(){let e=yield*fn.HttpClient,t=fn.filterStatusOk(li(e)),n=yield*Ko.Service,o=r.fnUntraced(function*(u,g){return(yield*n.run(Vn.make(u[0],u.slice(1),{cwd:g?.cwd,env:g?.env,extendEnv:!0}))).stdout.toString("utf8")},r.catch(()=>r.succeed(""))),s=r.fnUntraced(function*(u,g){let y=yield*n.run(Vn.make(u[0],u.slice(1),{cwd:g?.cwd,env:g?.env,extendEnv:!0}));return{code:y.exitCode,stdout:y.stdout.toString("utf8"),stderr:y.stderr.toString("utf8")}},r.catch(u=>r.succeed({code:1,stdout:"",stderr:gn(u)}))),a=r.fnUntraced(function*(){return(yield*o(["brew","list","--formula","anomalyco/tap/opencode"])).includes("opencode")?"anomalyco/tap/opencode":((yield*o(["brew","list","--formula","opencode"])).includes("opencode"),"opencode")}),l=i((u,g)=>u==="choco"?"not running from an elevated command shell":g?`Upgrade failed for ${u} (exit code ${g.code}).`:`Upgrade failed for ${u}.`,"upgradeFailure"),d=r.fnUntraced(function*(){return(yield*o(["bash","--version"]))?"bash":"sh"}),p=r.fnUntraced(function*(u){let y=yield*(yield*t.execute(Ve.get("https://opencode.ai/install"))).text,b=new TextEncoder().encode(y),S=yield*d(),T=yield*n.run(Vn.make(S,[],{stdin:vt.make(b),env:{VERSION:u},extendEnv:!0}));return{code:T.exitCode,stdout:T.stdout.toString("utf8"),stderr:T.stderr.toString("utf8")}},r.mapError(()=>new Vr({stderr:l("curl")}))),f={info:r.fn("Installation.info")(function*(){return{version:Qr,latest:yield*f.latest()}}),method:r.fn("Installation.method")(function*(){if(process.execPath.includes(wg.join(".opencode","bin"))||process.execPath.includes(wg.join(".local","bin")))return"curl";let u=process.execPath.toLowerCase(),g=[{name:"npm",command:i(()=>o(["npm","list","-g","--depth=0"]),"command")},{name:"yarn",command:i(()=>o(["yarn","global","list"]),"command")},{name:"pnpm",command:i(()=>o(["pnpm","list","-g","--depth=0"]),"command")},{name:"bun",command:i(()=>o(["bun","pm","ls","-g"]),"command")},{name:"brew",command:i(()=>o(["brew","list","--formula","opencode"]),"command")},{name:"scoop",command:i(()=>o(["scoop","list","opencode"]),"command")},{name:"choco",command:i(()=>o(["choco","list","--limit-output","opencode"]),"command")}];g.sort((y,b)=>{let S=u.includes(y.name),T=u.includes(b.name);return S&&!T?-1:!S&&T?1:0});for(let y of g){let b=yield*y.command(),S=y.name==="brew"||y.name==="choco"||y.name==="scoop"?"opencode":"opencode-ai";if(b.includes(S))return y.name}return"unknown"}),latest:r.fn("Installation.latest")(function*(u){let g=u||(yield*f.method());if(g==="brew"){let S=yield*a();if(S.includes("/")){let h=yield*o(["brew","info","--json=v2",S]);return(yield*c.decodeUnknownEffect(c.fromJsonString(OE))(h)).formulae[0].versions.stable}let T=yield*t.execute(Ve.get("https://formulae.brew.sh/api/formula/opencode.json").pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(_E)(T)).versions.stable}if(g==="npm"||g==="bun"||g==="pnpm"){let S=yield*t.execute(Ve.get(`${yield*Tu.registry(process.cwd())}/opencode-ai/${Zr}`).pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(xg)(S)).version}if(g==="choco"){let S=yield*t.execute(Ve.get("https://community.chocolatey.org/api/v2/Packages?$filter=Id%20eq%20%27opencode%27%20and%20IsLatestVersion&$select=Version").pipe(Ve.setHeaders({Accept:"application/json;odata=verbose"})));return(yield*zn.schemaBodyJson(LE)(S)).d.results[0].Version}if(g==="scoop"){let S=yield*t.execute(Ve.get("https://raw.githubusercontent.com/ScoopInstaller/Main/master/bucket/opencode.json").pipe(Ve.setHeaders({Accept:"application/json"})));return(yield*zn.schemaBodyJson(NE)(S)).version}let y=yield*t.execute(Ve.get("https://api.github.com/repos/anomalyco/opencode/releases/latest").pipe(Ve.acceptJson));return(yield*zn.schemaBodyJson(ME)(y)).tag_name.replace(/^v/,"")},r.orDie),upgrade:r.fn("Installation.upgrade")(function*(u,g){let y;switch(u){case"curl":y=yield*p(g);break;case"npm":y=yield*s(["npm","install","-g",`opencode-ai@${g}`]);break;case"pnpm":y=yield*s(["pnpm","install","-g",`opencode-ai@${g}`]);break;case"bun":y=yield*s(["bun","install","-g",`opencode-ai@${g}`]);break;case"brew":{let b=yield*a(),S={HOMEBREW_NO_AUTO_UPDATE:"1"};if(b.includes("/")){let T=yield*s(["brew","tap","anomalyco/tap"],{env:S});if(T.code!==0){y=T;break}let h=(yield*o(["brew","--repo","anomalyco/tap"])).trim();if(h){let k=yield*s(["git","pull","--ff-only"],{cwd:h,env:S});if(k.code!==0){y=k;break}}}y=yield*s(["brew","upgrade",b],{env:S});break}case"choco":y=yield*s(["choco","upgrade","opencode",`--version=${g}`,"-y"]);break;case"scoop":y=yield*s(["scoop","install",`opencode@${g}`]);break;default:return yield*new Vr({stderr:`Unknown installation method: ${u}`})}if(!y||y.code!==0)return yield*new Vr({stderr:l(u,y)});yield*r.logInfo("upgraded",{method:u,target:g,stdout:y.stdout,stderr:y.stderr}),yield*o([process.execPath,"--version"])})};return lo.of(f)})),Sg=ke.make({service:lo,layer:UE,deps:[In,Ko.node]}),{runPromise:xd}=Eu(lo,vo.build(Sg)),FE=i((...e)=>xd(t=>t.latest(...e)),"latest"),BE=i(()=>xd(e=>e.method()),"method"),$E=i((...e)=>xd(t=>t.upgrade(...e)),"upgrade");var Id={};fe(Id,{Service:()=>zr,SessionShare:()=>Id,node:()=>WE});var zr=class extends Re.Service()("@opencode/SessionShare"){static{i(this,"Service")}},qE=Te.effect(zr,r.gen(function*(){let e=yield*Oe.Service,t=yield*me.Service,n=yield*Wn.Service,o=yield*Dt.Scope,s=yield*Be.Service,a=r.fn("SessionShare.share")(function*(p){if((yield*e.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let u=yield*n.create(p);return yield*t.setShare({sessionID:p,share:{url:u.url}}),u}),l=r.fn("SessionShare.unshare")(function*(p){yield*n.remove(p),yield*t.setShare({sessionID:p,share:void 0})}),d=r.fn("SessionShare.create")(function*(p){let f=yield*t.create(p);if(f.parentID)return f;let u=yield*e.get();return(s.autoShare||u.share==="auto")&&(yield*a(f.id).pipe(r.ignore,r.forkIn(o))),f});return zr.of({create:d,share:a,unshare:l})})),WE=ke.make({service:zr,layer:qE,deps:[Oe.node,me.node,Wn.node,Be.node]});export{vo as a,sc as b,Ot as c,ac as d,Qt as e,Qn as f,or as g,ln as h,Ln as i,dn as j,un as k,jn as l,ys as m,gr as n,br as o,En as p,Ds as q,ft as r,Jt as s,Mo as t,bh as u,$n as v,Bo as w,Br as x,Ls as y,$o as z,rn as A,Wn as B,qr as C,vd as D,qs as E,Sd as F,Id as G};