alchemylab-opencode 2.0.4 → 2.0.5

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 (45) hide show
  1. package/dist/{anthropic-FVULF7C3.js → anthropic-YQ2VCNTB.js} +1 -1
  2. package/dist/{app-runtime-LDQWNGWP.js → app-runtime-GFPPHAHM.js} +1 -1
  3. package/dist/{chunk-OT2YNR56.js → chunk-55SXVZ3J.js} +1 -1
  4. package/dist/{chunk-R2GWBJEP.js → chunk-5AXNRW7L.js} +1 -1
  5. package/dist/{chunk-UPEPL4I2.js → chunk-6AKI3RBD.js} +1 -1
  6. package/dist/{chunk-G7PFO5HG.js → chunk-B7LCUFWA.js} +8 -8
  7. package/dist/{chunk-DWEYXIQI.js → chunk-BAULQCM7.js} +3 -3
  8. package/dist/{chunk-5BLZCAU6.js → chunk-EXCQNXCF.js} +1 -1
  9. package/dist/chunk-FLHFX43G.js +55 -0
  10. package/dist/chunk-HEEAGIBZ.js +1490 -0
  11. package/dist/{chunk-NGT6LCW6.js → chunk-LUMNYJ5D.js} +1 -1
  12. package/dist/{chunk-B74WSFN4.js → chunk-ROZTUM2T.js} +3 -3
  13. package/dist/{chunk-OUVSKG2H.js → chunk-VG5EGQPG.js} +1 -1
  14. package/dist/{chunk-2JE3QYG6.js → chunk-XMCVYTKN.js} +1 -1
  15. package/dist/{chunk-7XX6TY62.js → chunk-YDNJZVRR.js} +1 -1
  16. package/dist/{chunk-4GJE6OMN.js → chunk-YWZH5MZN.js} +1 -1
  17. package/dist/{chunk-TK5R7QUN.js → chunk-ZR6CXXUN.js} +1 -1
  18. package/dist/{code-mode-YYOGD36U.js → code-mode-LEVRRN6O.js} +1 -1
  19. package/dist/{dist-KM5HCPZX.js → dist-37YOR7EF.js} +1 -1
  20. package/dist/{dist-YUH4RKR5.js → dist-Y7XJ2TDX.js} +1 -1
  21. package/dist/{dist-es-W5GYOX6F.js → dist-es-2V53AUOV.js} +1 -1
  22. package/dist/{dist-es-G5UIJOU7.js → dist-es-HYEV5NJY.js} +2 -2
  23. package/dist/{dist-es-6PLFRCS4.js → dist-es-IQZPYE6S.js} +1 -1
  24. package/dist/{dist-es-HYIIGUNX.js → dist-es-NJU2JDGG.js} +1 -1
  25. package/dist/{dist-es-LSR2QCFZ.js → dist-es-PEWVLOVZ.js} +1 -1
  26. package/dist/{photon-W56QZY4L.js → photon-5AJPGVCX.js} +1 -1
  27. package/dist/run.js +1 -1
  28. package/dist/serve.js +1 -1
  29. package/dist/{server-LVIHYOCY.js → server-4GCT6Z5B.js} +2 -2
  30. package/dist/{session-6OPJNJMK.js → session-Y3Y6G2WT.js} +1 -1
  31. package/dist/{src-3NCXEROI.js → src-X7ZXQLNN.js} +1 -1
  32. package/dist/{worktree-32M5MTFE.js → worktree-YPE74GDD.js} +1 -1
  33. package/package.json +1 -1
  34. package/dist/chunk-DADVNQTM.js +0 -1490
  35. package/dist/chunk-FOHYZ7MJ.js +0 -55
  36. /package/dist/{dist-CYBRID2F.js → dist-RDYS4XXO.js} +0 -0
  37. /package/dist/{lib-ZP7Q6A3E.js → lib-JC7MYWBJ.js} +0 -0
  38. /package/dist/{mime-types-46EO4HOZ.js → mime-types-2T5FPOIB.js} +0 -0
  39. /package/dist/{signin-OCIW23YM.js → signin-U2KKV7OZ.js} +0 -0
  40. /package/dist/{src-YAAFIGTW.js → src-ABUDV3W3.js} +0 -0
  41. /package/dist/{src-LXWGIUZH.js → src-NICVS6EV.js} +0 -0
  42. /package/dist/{sso-oidc-OMMKINFE.js → sso-oidc-KFJXXBLA.js} +0 -0
  43. /package/dist/{sts-MWK22JIX.js → sts-XIN552ID.js} +0 -0
  44. /package/dist/{token-QPO3OAGS.js → token-D3TCB33O.js} +0 -0
  45. /package/dist/{token-util-YGPCEEPO.js → token-util-IOCO6RZC.js} +0 -0
@@ -0,0 +1,55 @@
1
+ // Built by esbuild from opencode-server source
2
+ if (typeof globalThis.Bun === 'undefined') {
3
+ globalThis.Bun = {
4
+ version: '0.0.0-node-compat',
5
+ stdin: { async text() { const chunks = []; for await (const c of process.stdin) chunks.push(c); return Buffer.concat(chunks).toString(); } },
6
+ which(cmd) { try { return require('child_process').execFileSync('which', [cmd], { encoding: 'utf8' }).trim(); } catch { return null; } },
7
+ };
8
+ }
9
+ if (typeof globalThis.__name === 'undefined') { globalThis.__name = (t, n) => { Object.defineProperty(t, 'name', { value: n, configurable: true }); return t; }; }
10
+ if (typeof globalThis.__export === 'undefined') { globalThis.__export = (t, a) => { for (const k in a) Object.defineProperty(t, k, { get: a[k], enumerable: true }); }; }
11
+ import { createRequire as __alchemyCreateRequire } from 'node:module';
12
+ const require = __alchemyCreateRequire(import.meta.url);
13
+ import { fileURLToPath as __alchemyFileURLToPath } from 'node:url';
14
+ import { dirname as __alchemyDirname } from 'node:path';
15
+ const __alchemy_filename = __alchemyFileURLToPath(import.meta.url);
16
+ const __alchemy_dirname = __alchemyDirname(__alchemy_filename);
17
+
18
+ import{C as Zn,Da as $,La as dn,Ma as Yn,_a as ln,aa as Qn,db as er,h as an,ib as un,k as At,kb as pn,l as Gn,lb as mn,m as Hn,mb as gn,n as vt,o as cn,p as _e,q as fn,r as Y,u as Ft,v as U,w as ge,x as le}from"./chunk-BAULQCM7.js";import{b as Xn,i as Kn}from"./chunk-WKZYINC7.js";import{La as tn,Ma as nn,Oa as Bn,Pa as K,Ra as ke,Sa as yt,Sc as Jn,Va as rn,Wa as It,Ya as Rt,Za as wt,_a as jt,_c as st,ab as Xe,b as Kt,bc as Vn,bd as sn,c as Yt,fd as zn,ha as Se,ia as On,ib as Un,ma as Oe,mb as it,nb as Wn,pa as G,pc as ot,qa as en,qb as me,ta as Ln,ub as $n,uc as on,vb as qn}from"./chunk-YDNJZVRR.js";import{t as we,x as rt}from"./chunk-VWLJXTZ5.js";import{Bc as gt,Bf as d,Ig as Fn,Tc as De,aa as Ae,bb as Fe,bh as Xt,dc as ce,jd as ht,lc as Ie,nb as Qt,pd as Ct,pj as S,zd as An}from"./chunk-ELPXQ32J.js";import{a as p,e as je}from"./chunk-2MRHL4B2.js";var Cn={};je(Cn,{ArchivedTimestamp:()=>Tn,BusyError:()=>_n,ChildrenInput:()=>Bo,CreateInput:()=>Fo,Event:()=>Go,ForkInput:()=>Oo,GetInput:()=>Lo,GlobalInfo:()=>Ao,Info:()=>$r,MessagesInput:()=>zo,Metadata:()=>Zt,ProjectInfo:()=>qr,RemoveInput:()=>Uo,Service:()=>tt,Session:()=>Cn,SetArchivedInput:()=>$o,SetMetadataInput:()=>qo,SetPermissionInput:()=>Vo,SetRevertInput:()=>Jo,SetTitleInput:()=>Wo,fromRow:()=>Mt,getUsage:()=>Zo,isDefaultTitle:()=>Mo,node:()=>es,plan:()=>Ho,toRow:()=>_o,use:()=>Qo});import Nt from"path";var at={};je(at,{BackgroundJob:()=>at,Service:()=>Le,node:()=>Xr});var Be={};je(Be,{BackgroundJob:()=>Be,Service:()=>Le,make:()=>rr,node:()=>Zr});var Dt={};je(Dt,{Identifier:()=>Dt,ascending:()=>Vr,create:()=>nr,descending:()=>Jr,timestamp:()=>zr});var hn={job:"job",event:"evt",session:"ses",message:"msg",permission:"per",question:"que",part:"prt",pty:"pty",tool:"tool",workspace:"wrk"};function Vr(e,t){return tr(e,"ascending",t)}p(Vr,"ascending");function Jr(e,t){return tr(e,"descending",t)}p(Jr,"descending");function tr(e,t,n){if(!n)return nr(hn[e],t);if(!n.startsWith(hn[e]))throw new Error(`ID ${n} does not start with ${hn[e]}`);return n}p(tr,"generateID");function nr(e,t,n){return e+"_"+Ln(t==="descending",n)}p(nr,"create");function zr(e){let t=e.split("_")[0],n=e.slice(t.length+1,t.length+13),r=BigInt("0x"+n);return Number(r/BigInt(4096))}p(zr,"timestamp");var Le=class extends Fe.Service()("@opencode/BackgroundJob"){static{p(this,"Service")}};function fe(e){return{...e.info,...e.info.metadata?{metadata:{...e.info.metadata}}:{}}}p(fe,"snapshot");function Gr(e){return e instanceof Error?e.message:String(e)}p(Gr,"errorText");var rr=d.gen(function*(){let e={jobs:yield*we.make(new Map),scope:yield*gt.Scope},t=d.fn("BackgroundJob.settle")(function*(l,g,m,h){let w=yield*Ct.currentTimeMillis,D=yield*we.modify(e.jobs,b=>{let E=b.get(l);if(!E)return[{},b];if(E.token!==g)return[{},b];if(E.info.status!=="running")return[{info:fe(E)},b];let I=E.pending-1,P=Ie.isSuccess(h)&&(!E.output||m>E.output.sequence)?{sequence:m,text:h.value}:E.output;if(Ie.isSuccess(h)&&I>0)return[{},new Map(b).set(l,{...E,pending:I,output:P})];let O=Ie.isSuccess(h)?"completed":ht.hasInterruptsOnly(h.cause)?"cancelled":"error",V={...E,onPromote:void 0,pending:0,output:P,info:{...E.info,status:O,completed_at:w,...P?{output:P.text}:{},...Ie.isFailure(h)?{error:Gr(ht.squash(h.cause))}:{}}};return[{info:fe(V),done:E.done,scope:E.scope},new Map(b).set(l,V)]});return D.info&&D.done&&(yield*ce.succeed(D.done,D.info).pipe(d.ignore)),D.scope&&(yield*gt.close(D.scope,Ie.void).pipe(d.forkIn(e.scope,{startImmediately:!0}))),D.info}),n=d.fn("BackgroundJob.fork")(function*(l,g,m,h,w){return yield*w.pipe(d.matchCauseEffect({onSuccess:p(D=>t(g,m,h,Ie.succeed(D)),"onSuccess"),onFailure:p(D=>t(g,m,h,Ie.failCause(D)),"onFailure")}),d.asVoid,d.forkIn(l,{startImmediately:!0}))}),r=d.fn("BackgroundJob.list")(function*(){return Array.from((yield*we.get(e.jobs)).values()).map(fe).toSorted((l,g)=>l.started_at-g.started_at)}),i=d.fn("BackgroundJob.get")(function*(l){let g=(yield*we.get(e.jobs)).get(l);if(g)return fe(g)}),o=d.fn("BackgroundJob.start")(function*(l){return yield*d.uninterruptibleMask(g=>d.gen(function*(){let m=l.id??Dt.ascending("job"),h=yield*Ct.currentTimeMillis,w=yield*ce.make(),D=yield*ce.make(),b=yield*ce.make(),E=yield*we.modifyEffect(e.jobs,d.fnUntraced(function*(I){let P=I.get(m);if(P?.info.status==="running")return[{info:fe(P)},I];let O=yield*gt.fork(e.scope,"parallel"),V={},H={info:{id:m,type:l.type,title:l.title,status:"running",started_at:h,metadata:l.metadata},done:w,scope:O,token:V,pending:1,next:1,tail:b,promoted:D,onPromote:l.onPromote};return[{info:fe(H),scope:O,token:V},new Map(I).set(m,H)]}));return"scope"in E&&(yield*n(E.scope,m,E.token,0,g(l.run).pipe(d.ensuring(ce.succeed(b,void 0))))),E.info}))}),s=d.fn("BackgroundJob.extend")(function*(l){return yield*d.uninterruptibleMask(g=>d.gen(function*(){let m=yield*ce.make(),h=yield*we.modify(e.jobs,w=>{let D=w.get(l.id);return!D||D.info.status!=="running"?[{extended:!1},w]:[{extended:!0,previous:D.tail,scope:D.scope,tail:m,token:D.token,sequence:D.next},new Map(w).set(l.id,{...D,pending:D.pending+1,next:D.next+1,tail:m})]});return h.extended?(yield*n(h.scope,l.id,h.token,h.sequence,ce.await(h.previous).pipe(d.andThen(g(l.run)),d.ensuring(ce.succeed(h.tail,void 0)))),!0):!1}))}),a=d.fn("BackgroundJob.wait")(function*(l){let g=(yield*we.get(e.jobs)).get(l.id);if(!g)return{timedOut:!1};if(g.info.status!=="running")return{info:fe(g),timedOut:!1};if(l.timeout===void 0)return{info:yield*ce.await(g.done),timedOut:!1};if(l.timeout<=0)return{info:fe(g),timedOut:!0};let m=yield*ce.await(g.done).pipe(d.timeoutOption(l.timeout));return m._tag==="Some"?{info:m.value,timedOut:!1}:{info:fe(g),timedOut:!0}}),f=d.fn("BackgroundJob.waitForPromotion")(function*(l){let g=(yield*we.get(e.jobs)).get(l);return!g||g.info.status!=="running"?yield*d.never:g.info.metadata?.background===!0?fe(g):yield*ce.await(g.promoted)}),c=d.fn("BackgroundJob.promote")(function*(l){let g=yield*we.modifyEffect(e.jobs,d.fnUntraced(function*(m){let h=m.get(l);if(!h||h.info.status!=="running")return[{},m];if(h.info.metadata?.background===!0)return[{info:fe(h)},m];let w={...h,onPromote:void 0,info:{...h.info,metadata:{...h.info.metadata,background:!0}}};return[{info:fe(w),onPromote:h.onPromote,promoted:h.promoted},new Map(m).set(l,w)]}));return g.info&&g.promoted&&(yield*ce.succeed(g.promoted,g.info).pipe(d.ignore)),g.onPromote&&(yield*g.onPromote.pipe(d.ignore)),g.info}),u=d.fn("BackgroundJob.cancel")(function*(l){let g=yield*Ct.currentTimeMillis,m=yield*we.modify(e.jobs,h=>{let w=h.get(l);if(!w)return[{},h];if(w.info.status!=="running")return[{info:fe(w)},h];let D={...w,onPromote:void 0,pending:0,info:{...w.info,status:"cancelled",completed_at:g}};return[{info:fe(D),done:w.done,scope:w.scope},new Map(h).set(l,D)]});return m.info&&m.done&&(yield*ce.succeed(m.done,m.info).pipe(d.ignore)),m.scope&&(yield*gt.close(m.scope,Ie.void)),m.info});return Le.of({list:r,get:i,start:o,extend:s,wait:a,waitForPromotion:f,promote:c,cancel:u})}),Hr=De.effect(Le,rr),Zr=On({service:Le,layer:Hr,deps:[]});var Qr=De.effect(Be.Service,d.gen(function*(){let e=yield*$.make(()=>Be.make);return Be.Service.of({list:p(()=>$.useEffect(e,t=>t.list()),"list"),get:p(t=>$.useEffect(e,n=>n.get(t)),"get"),start:p(t=>$.useEffect(e,n=>n.start(t)),"start"),extend:p(t=>$.useEffect(e,n=>n.extend(t)),"extend"),wait:p(t=>$.useEffect(e,n=>n.wait(t)),"wait"),waitForPromotion:p(t=>$.useEffect(e,n=>n.waitForPromotion(t)),"waitForPromotion"),promote:p(t=>$.useEffect(e,n=>n.promote(t)),"promote"),cancel:p(t=>$.useEffect(e,n=>n.cancel(t)),"cancel")})})),Xr=Se.make({service:Be.Service,layer:Qr,deps:[]});var ct=9e15,qe=1e9,yn="0123456789abcdef",Bt="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ut="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",In={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ct,maxE:ct,crypto:!1},ar,Te,j=!0,$t="[DecimalError] ",$e=$t+"Invalid argument: ",cr=$t+"Precision limit exceeded",fr=$t+"crypto unavailable",dr="[object Decimal]",ie=Math.floor,ee=Math.pow,Kr=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Yr=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,ei=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,lr=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,ve=1e7,T=7,ti=9007199254740991,ni=Bt.length-1,wn=Ut.length-1,v={toStringTag:dr};v.absoluteValue=v.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),M(e)};v.ceil=function(){return M(new this.constructor(this),this.e+1,2)};v.clampedTo=v.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error($e+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};v.comparedTo=v.cmp=function(e){var t,n,r,i,o=this,s=o.d,a=(e=new o.constructor(e)).d,f=o.s,c=e.s;if(!s||!a)return!f||!c?NaN:f!==c?f:s===a?0:!s^f<0?1:-1;if(!s[0]||!a[0])return s[0]?f:a[0]?-c:0;if(f!==c)return f;if(o.e!==e.e)return o.e>e.e^f<0?1:-1;for(r=s.length,i=a.length,t=0,n=r<i?r:i;t<n;++t)if(s[t]!==a[t])return s[t]>a[t]^f<0?1:-1;return r===i?0:r>i^f<0?1:-1};v.cosine=v.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+T,r.rounding=1,n=ri(r,hr(r,n)),r.precision=e,r.rounding=t,M(Te==2||Te==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};v.cubeRoot=v.cbrt=function(){var e,t,n,r,i,o,s,a,f,c,u=this,l=u.constructor;if(!u.isFinite()||u.isZero())return new l(u);for(j=!1,o=u.s*ee(u.s*u,1/3),!o||Math.abs(o)==1/0?(n=te(u.d),e=u.e,(o=(e-n.length+1)%3)&&(n+=o==1||o==-2?"0":"00"),o=ee(n,1/3),e=ie((e+1)/3)-(e%3==(e<0?-1:2)),o==1/0?n="5e"+e:(n=o.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new l(n),r.s=u.s):r=new l(o.toString()),s=(e=l.precision)+3;;)if(a=r,f=a.times(a).times(a),c=f.plus(u),r=q(c.plus(u).times(a),c.plus(f),s+2,1),te(a.d).slice(0,s)===(n=te(r.d)).slice(0,s))if(n=n.slice(s-3,s+1),n=="9999"||!i&&n=="4999"){if(!i&&(M(a,e+1,0),a.times(a).times(a).eq(u))){r=a;break}s+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(M(r,e+1,1),t=!r.times(r).times(r).eq(u));break}return j=!0,M(r,e,l.rounding,t)};v.decimalPlaces=v.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-ie(this.e/T))*T,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};v.dividedBy=v.div=function(e){return q(this,new this.constructor(e))};v.dividedToIntegerBy=v.divToInt=function(e){var t=this,n=t.constructor;return M(q(t,new n(e),0,1,1),n.precision,n.rounding)};v.equals=v.eq=function(e){return this.cmp(e)===0};v.floor=function(){return M(new this.constructor(this),this.e+1,3)};v.greaterThan=v.gt=function(e){return this.cmp(e)>0};v.greaterThanOrEqualTo=v.gte=function(e){var t=this.cmp(e);return t==1||t===0};v.hyperbolicCosine=v.cosh=function(){var e,t,n,r,i,o=this,s=o.constructor,a=new s(1);if(!o.isFinite())return new s(o.s?1/0:NaN);if(o.isZero())return a;n=s.precision,r=s.rounding,s.precision=n+Math.max(o.e,o.sd())+4,s.rounding=1,i=o.d.length,i<32?(e=Math.ceil(i/3),t=(1/Vt(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),o=ft(s,1,o.times(t),new s(1),!0);for(var f,c=e,u=new s(8);c--;)f=o.times(o),o=a.minus(f.times(u.minus(f.times(u))));return M(o,s.precision=n,s.rounding=r,!0)};v.hyperbolicSine=v.sinh=function(){var e,t,n,r,i=this,o=i.constructor;if(!i.isFinite()||i.isZero())return new o(i);if(t=o.precision,n=o.rounding,o.precision=t+Math.max(i.e,i.sd())+4,o.rounding=1,r=i.d.length,r<3)i=ft(o,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/Vt(5,e)),i=ft(o,2,i,i,!0);for(var s,a=new o(5),f=new o(16),c=new o(20);e--;)s=i.times(i),i=i.times(a.plus(s.times(f.times(s).plus(c))))}return o.precision=t,o.rounding=n,M(i,t,n,!0)};v.hyperbolicTangent=v.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,q(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};v.inverseCosine=v.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?Ee(t,r,i):new t(0):new t(NaN):e.isZero()?Ee(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};v.inverseHyperbolicCosine=v.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,j=!1,n=n.times(n).minus(1).sqrt().plus(n),j=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};v.inverseHyperbolicSine=v.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,j=!1,n=n.times(n).plus(1).sqrt().plus(n),j=!0,r.precision=e,r.rounding=t,n.ln())};v.inverseHyperbolicTangent=v.atanh=function(){var e,t,n,r,i=this,o=i.constructor;return i.isFinite()?i.e>=0?new o(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=o.precision,t=o.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?M(new o(i),e,t,!0):(o.precision=n=r-i.e,i=q(i.plus(1),new o(1).minus(i),n+e,1),o.precision=e+4,o.rounding=1,i=i.ln(),o.precision=e,o.rounding=t,i.times(.5))):new o(NaN)};v.inverseSine=v.asin=function(){var e,t,n,r,i=this,o=i.constructor;return i.isZero()?new o(i):(t=i.abs().cmp(1),n=o.precision,r=o.rounding,t!==-1?t===0?(e=Ee(o,n+4,r).times(.5),e.s=i.s,e):new o(NaN):(o.precision=n+6,o.rounding=1,i=i.div(new o(1).minus(i.times(i)).sqrt().plus(1)).atan(),o.precision=n,o.rounding=r,i.times(2)))};v.inverseTangent=v.atan=function(){var e,t,n,r,i,o,s,a,f,c=this,u=c.constructor,l=u.precision,g=u.rounding;if(c.isFinite()){if(c.isZero())return new u(c);if(c.abs().eq(1)&&l+4<=wn)return s=Ee(u,l+4,g).times(.25),s.s=c.s,s}else{if(!c.s)return new u(NaN);if(l+4<=wn)return s=Ee(u,l+4,g).times(.5),s.s=c.s,s}for(u.precision=a=l+10,u.rounding=1,n=Math.min(28,a/T+2|0),e=n;e;--e)c=c.div(c.times(c).plus(1).sqrt().plus(1));for(j=!1,t=Math.ceil(a/T),r=1,f=c.times(c),s=new u(c),i=c;e!==-1;)if(i=i.times(f),o=s.minus(i.div(r+=2)),i=i.times(f),s=o.plus(i.div(r+=2)),s.d[t]!==void 0)for(e=t;s.d[e]===o.d[e]&&e--;);return n&&(s=s.times(2<<n-1)),j=!0,M(s,u.precision=l,u.rounding=g,!0)};v.isFinite=function(){return!!this.d};v.isInteger=v.isInt=function(){return!!this.d&&ie(this.e/T)>this.d.length-2};v.isNaN=function(){return!this.s};v.isNegative=v.isNeg=function(){return this.s<0};v.isPositive=v.isPos=function(){return this.s>0};v.isZero=function(){return!!this.d&&this.d[0]===0};v.lessThan=v.lt=function(e){return this.cmp(e)<0};v.lessThanOrEqualTo=v.lte=function(e){return this.cmp(e)<1};v.logarithm=v.log=function(e){var t,n,r,i,o,s,a,f,c=this,u=c.constructor,l=u.precision,g=u.rounding,m=5;if(e==null)e=new u(10),t=!0;else{if(e=new u(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new u(NaN);t=e.eq(10)}if(n=c.d,c.s<0||!n||!n[0]||c.eq(1))return new u(n&&!n[0]?-1/0:c.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)o=!0;else{for(i=n[0];i%10===0;)i/=10;o=i!==1}if(j=!1,a=l+m,s=We(c,a),r=t?Wt(u,a+10):We(e,a),f=q(s,r,a,1),St(f.d,i=l,g))do if(a+=10,s=We(c,a),r=t?Wt(u,a+10):We(e,a),f=q(s,r,a,1),!o){+te(f.d).slice(i+1,i+15)+1==1e14&&(f=M(f,l+1,0));break}while(St(f.d,i+=10,g));return j=!0,M(f,l,g)};v.minus=v.sub=function(e){var t,n,r,i,o,s,a,f,c,u,l,g,m=this,h=m.constructor;if(e=new h(e),!m.d||!e.d)return!m.s||!e.s?e=new h(NaN):m.d?e.s=-e.s:e=new h(e.d||m.s!==e.s?m:NaN),e;if(m.s!=e.s)return e.s=-e.s,m.plus(e);if(c=m.d,g=e.d,a=h.precision,f=h.rounding,!c[0]||!g[0]){if(g[0])e.s=-e.s;else if(c[0])e=new h(m);else return new h(f===3?-0:0);return j?M(e,a,f):e}if(n=ie(e.e/T),u=ie(m.e/T),c=c.slice(),o=u-n,o){for(l=o<0,l?(t=c,o=-o,s=g.length):(t=g,n=u,s=c.length),r=Math.max(Math.ceil(a/T),s)+2,o>r&&(o=r,t.length=1),t.reverse(),r=o;r--;)t.push(0);t.reverse()}else{for(r=c.length,s=g.length,l=r<s,l&&(s=r),r=0;r<s;r++)if(c[r]!=g[r]){l=c[r]<g[r];break}o=0}for(l&&(t=c,c=g,g=t,e.s=-e.s),s=c.length,r=g.length-s;r>0;--r)c[s++]=0;for(r=g.length;r>o;){if(c[--r]<g[r]){for(i=r;i&&c[--i]===0;)c[i]=ve-1;--c[i],c[r]+=ve}c[r]-=g[r]}for(;c[--s]===0;)c.pop();for(;c[0]===0;c.shift())--n;return c[0]?(e.d=c,e.e=qt(c,n),j?M(e,a,f):e):new h(f===3?-0:0)};v.modulo=v.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?M(new r(n),r.precision,r.rounding):(j=!1,r.modulo==9?(t=q(n,e.abs(),0,3,1),t.s*=e.s):t=q(n,e,0,r.modulo,1),t=t.times(e),j=!0,n.minus(t))};v.naturalExponential=v.exp=function(){return vn(this)};v.naturalLogarithm=v.ln=function(){return We(this)};v.negated=v.neg=function(){var e=new this.constructor(this);return e.s=-e.s,M(e)};v.plus=v.add=function(e){var t,n,r,i,o,s,a,f,c,u,l=this,g=l.constructor;if(e=new g(e),!l.d||!e.d)return!l.s||!e.s?e=new g(NaN):l.d||(e=new g(e.d||l.s===e.s?l:NaN)),e;if(l.s!=e.s)return e.s=-e.s,l.minus(e);if(c=l.d,u=e.d,a=g.precision,f=g.rounding,!c[0]||!u[0])return u[0]||(e=new g(l)),j?M(e,a,f):e;if(o=ie(l.e/T),r=ie(e.e/T),c=c.slice(),i=o-r,i){for(i<0?(n=c,i=-i,s=u.length):(n=u,r=o,s=c.length),o=Math.ceil(a/T),s=o>s?o+1:s+1,i>s&&(i=s,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(s=c.length,i=u.length,s-i<0&&(i=s,n=u,u=c,c=n),t=0;i;)t=(c[--i]=c[i]+u[i]+t)/ve|0,c[i]%=ve;for(t&&(c.unshift(t),++r),s=c.length;c[--s]==0;)c.pop();return e.d=c,e.e=qt(c,r),j?M(e,a,f):e};v.precision=v.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error($e+e);return n.d?(t=ur(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};v.round=function(){var e=this,t=e.constructor;return M(new t(e),e.e+1,t.rounding)};v.sine=v.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+T,r.rounding=1,n=oi(r,hr(r,n)),r.precision=e,r.rounding=t,M(Te>2?n.neg():n,e,t,!0)):new r(NaN)};v.squareRoot=v.sqrt=function(){var e,t,n,r,i,o,s=this,a=s.d,f=s.e,c=s.s,u=s.constructor;if(c!==1||!a||!a[0])return new u(!c||c<0&&(!a||a[0])?NaN:a?s:1/0);for(j=!1,c=Math.sqrt(+s),c==0||c==1/0?(t=te(a),(t.length+f)%2==0&&(t+="0"),c=Math.sqrt(t),f=ie((f+1)/2)-(f<0||f%2),c==1/0?t="5e"+f:(t=c.toExponential(),t=t.slice(0,t.indexOf("e")+1)+f),r=new u(t)):r=new u(c.toString()),n=(f=u.precision)+3;;)if(o=r,r=o.plus(q(s,o,n+2,1)).times(.5),te(o.d).slice(0,n)===(t=te(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(M(o,f+1,0),o.times(o).eq(s))){r=o;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(M(r,f+1,1),e=!r.times(r).eq(s));break}return j=!0,M(r,f,u.rounding,e)};v.tangent=v.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=q(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,M(Te==2||Te==4?n.neg():n,e,t,!0)):new r(NaN)};v.times=v.mul=function(e){var t,n,r,i,o,s,a,f,c,u=this,l=u.constructor,g=u.d,m=(e=new l(e)).d;if(e.s*=u.s,!g||!g[0]||!m||!m[0])return new l(!e.s||g&&!g[0]&&!m||m&&!m[0]&&!g?NaN:!g||!m?e.s/0:e.s*0);for(n=ie(u.e/T)+ie(e.e/T),f=g.length,c=m.length,f<c&&(o=g,g=m,m=o,s=f,f=c,c=s),o=[],s=f+c,r=s;r--;)o.push(0);for(r=c;--r>=0;){for(t=0,i=f+r;i>r;)a=o[i]+m[r]*g[i-r-1]+t,o[i--]=a%ve|0,t=a/ve|0;o[i]=(o[i]+t)%ve|0}for(;!o[--s];)o.pop();return t?++n:o.shift(),e.d=o,e.e=qt(o,n),j?M(e,l.precision,l.rounding):e};v.toBinary=function(e,t){return Dn(this,2,e,t)};v.toDecimalPlaces=v.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(de(e,0,qe),t===void 0?t=r.rounding:de(t,0,8),M(n,e+n.e+1,t))};v.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=be(r,!0):(de(e,0,qe),t===void 0?t=i.rounding:de(t,0,8),r=M(new i(r),e+1,t),n=be(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};v.toFixed=function(e,t){var n,r,i=this,o=i.constructor;return e===void 0?n=be(i):(de(e,0,qe),t===void 0?t=o.rounding:de(t,0,8),r=M(new o(i),e+i.e+1,t),n=be(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};v.toFraction=function(e){var t,n,r,i,o,s,a,f,c,u,l,g,m=this,h=m.d,w=m.constructor;if(!h)return new w(m);if(c=n=new w(1),r=f=new w(0),t=new w(r),o=t.e=ur(h)-m.e-1,s=o%T,t.d[0]=ee(10,s<0?T+s:s),e==null)e=o>0?t:c;else{if(a=new w(e),!a.isInt()||a.lt(c))throw Error($e+a);e=a.gt(t)?o>0?t:c:a}for(j=!1,a=new w(te(h)),u=w.precision,w.precision=o=h.length*T*2;l=q(a,t,0,1,1),i=n.plus(l.times(r)),i.cmp(e)!=1;)n=r,r=i,i=c,c=f.plus(l.times(i)),f=i,i=t,t=a.minus(l.times(i)),a=i;return i=q(e.minus(n),r,0,1,1),f=f.plus(i.times(c)),n=n.plus(i.times(r)),f.s=c.s=m.s,g=q(c,r,o,1).minus(m).abs().cmp(q(f,n,o,1).minus(m).abs())<1?[c,r]:[f,n],w.precision=u,j=!0,g};v.toHexadecimal=v.toHex=function(e,t){return Dn(this,16,e,t)};v.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:de(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(j=!1,n=q(n,e,0,t,1).times(e),j=!0,M(n)):(e.s=n.s,n=e),n};v.toNumber=function(){return+this};v.toOctal=function(e,t){return Dn(this,8,e,t)};v.toPower=v.pow=function(e){var t,n,r,i,o,s,a=this,f=a.constructor,c=+(e=new f(e));if(!a.d||!e.d||!a.d[0]||!e.d[0])return new f(ee(+a,c));if(a=new f(a),a.eq(1))return a;if(r=f.precision,o=f.rounding,e.eq(1))return M(a,r,o);if(t=ie(e.e/T),t>=e.d.length-1&&(n=c<0?-c:c)<=ti)return i=pr(f,a,n,r),e.s<0?new f(1).div(i):M(i,r,o);if(s=a.s,s<0){if(t<e.d.length-1)return new f(NaN);if((e.d[t]&1)==0&&(s=1),a.e==0&&a.d[0]==1&&a.d.length==1)return a.s=s,a}return n=ee(+a,c),t=n==0||!isFinite(n)?ie(c*(Math.log("0."+te(a.d))/Math.LN10+a.e+1)):new f(n+"").e,t>f.maxE+1||t<f.minE-1?new f(t>0?s/0:0):(j=!1,f.rounding=a.s=1,n=Math.min(12,(t+"").length),i=vn(e.times(We(a,r+n)),r),i.d&&(i=M(i,r+5,1),St(i.d,r,o)&&(t=r+10,i=M(vn(e.times(We(a,t+n)),t),t+5,1),+te(i.d).slice(r+1,r+15)+1==1e14&&(i=M(i,r+1,0)))),i.s=s,j=!0,f.rounding=o,M(i,r,o))};v.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=be(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(de(e,1,qe),t===void 0?t=i.rounding:de(t,0,8),r=M(new i(r),e,t),n=be(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};v.toSignificantDigits=v.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(de(e,1,qe),t===void 0?t=r.rounding:de(t,0,8)),M(new r(n),e,t)};v.toString=function(){var e=this,t=e.constructor,n=be(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};v.truncated=v.trunc=function(){return M(new this.constructor(this),this.e+1,1)};v.valueOf=v.toJSON=function(){var e=this,t=e.constructor,n=be(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function te(e){var t,n,r,i=e.length-1,o="",s=e[0];if(i>0){for(o+=s,t=1;t<i;t++)r=e[t]+"",n=T-r.length,n&&(o+=Ue(n)),o+=r;s=e[t],r=s+"",n=T-r.length,n&&(o+=Ue(n))}else if(s===0)return"0";for(;s%10===0;)s/=10;return o+s}p(te,"digitsToString");function de(e,t,n){if(e!==~~e||e<t||e>n)throw Error($e+e)}p(de,"checkInt32");function St(e,t,n,r){var i,o,s,a;for(o=e[0];o>=10;o/=10)--t;return--t<0?(t+=T,i=0):(i=Math.ceil((t+1)/T),t%=T),o=ee(10,T-t),a=e[i]%o|0,r==null?t<3?(t==0?a=a/100|0:t==1&&(a=a/10|0),s=n<4&&a==99999||n>3&&a==49999||a==5e4||a==0):s=(n<4&&a+1==o||n>3&&a+1==o/2)&&(e[i+1]/o/100|0)==ee(10,t-2)-1||(a==o/2||a==0)&&(e[i+1]/o/100|0)==0:t<4?(t==0?a=a/1e3|0:t==1?a=a/100|0:t==2&&(a=a/10|0),s=(r||n<4)&&a==9999||!r&&n>3&&a==4999):s=((r||n<4)&&a+1==o||!r&&n>3&&a+1==o/2)&&(e[i+1]/o/1e3|0)==ee(10,t-3)-1,s}p(St,"checkRoundingDigits");function Ot(e,t,n){for(var r,i=[0],o,s=0,a=e.length;s<a;){for(o=i.length;o--;)i[o]*=t;for(i[0]+=yn.indexOf(e.charAt(s++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}p(Ot,"convertBase");function ri(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/Vt(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=ft(e,1,t.times(i),new e(1));for(var o=n;o--;){var s=t.times(t);t=s.times(s).minus(s).times(8).plus(1)}return e.precision-=n,t}p(ri,"cosine");var q=(function(){function e(r,i,o){var s,a=0,f=r.length;for(r=r.slice();f--;)s=r[f]*i+a,r[f]=s%o|0,a=s/o|0;return a&&r.unshift(a),r}p(e,"multiplyInteger");function t(r,i,o,s){var a,f;if(o!=s)f=o>s?1:-1;else for(a=f=0;a<o;a++)if(r[a]!=i[a]){f=r[a]>i[a]?1:-1;break}return f}p(t,"compare");function n(r,i,o,s){for(var a=0;o--;)r[o]-=a,a=r[o]<i[o]?1:0,r[o]=a*s+r[o]-i[o];for(;!r[0]&&r.length>1;)r.shift()}return p(n,"subtract"),function(r,i,o,s,a,f){var c,u,l,g,m,h,w,D,b,E,I,P,O,V,H,ae,he,ne,re,Ce,Pe=r.constructor,He=r.s==i.s?1:-1,Z=r.d,k=i.d;if(!Z||!Z[0]||!k||!k[0])return new Pe(!r.s||!i.s||(Z?k&&Z[0]==k[0]:!k)?NaN:Z&&Z[0]==0||!k?He*0:He/0);for(f?(m=1,u=r.e-i.e):(f=ve,m=T,u=ie(r.e/m)-ie(i.e/m)),re=k.length,he=Z.length,b=new Pe(He),E=b.d=[],l=0;k[l]==(Z[l]||0);l++);if(k[l]>(Z[l]||0)&&u--,o==null?(V=o=Pe.precision,s=Pe.rounding):a?V=o+(r.e-i.e)+1:V=o,V<0)E.push(1),h=!0;else{if(V=V/m+2|0,l=0,re==1){for(g=0,k=k[0],V++;(l<he||g)&&V--;l++)H=g*f+(Z[l]||0),E[l]=H/k|0,g=H%k|0;h=g||l<he}else{for(g=f/(k[0]+1)|0,g>1&&(k=e(k,g,f),Z=e(Z,g,f),re=k.length,he=Z.length),ae=re,I=Z.slice(0,re),P=I.length;P<re;)I[P++]=0;Ce=k.slice(),Ce.unshift(0),ne=k[0],k[1]>=f/2&&++ne;do g=0,c=t(k,I,re,P),c<0?(O=I[0],re!=P&&(O=O*f+(I[1]||0)),g=O/ne|0,g>1?(g>=f&&(g=f-1),w=e(k,g,f),D=w.length,P=I.length,c=t(w,I,D,P),c==1&&(g--,n(w,re<D?Ce:k,D,f))):(g==0&&(c=g=1),w=k.slice()),D=w.length,D<P&&w.unshift(0),n(I,w,P,f),c==-1&&(P=I.length,c=t(k,I,re,P),c<1&&(g++,n(I,re<P?Ce:k,P,f))),P=I.length):c===0&&(g++,I=[0]),E[l++]=g,c&&I[0]?I[P++]=Z[ae]||0:(I=[Z[ae]],P=1);while((ae++<he||I[0]!==void 0)&&V--);h=I[0]!==void 0}E[0]||E.shift()}if(m==1)b.e=u,ar=h;else{for(l=1,g=E[0];g>=10;g/=10)l++;b.e=l+u*m-1,M(b,a?o+b.e+1:o,s,h)}return b}})();function M(e,t,n,r){var i,o,s,a,f,c,u,l,g,m=e.constructor;e:if(t!=null){if(l=e.d,!l)return e;for(i=1,a=l[0];a>=10;a/=10)i++;if(o=t-i,o<0)o+=T,s=t,u=l[g=0],f=u/ee(10,i-s-1)%10|0;else if(g=Math.ceil((o+1)/T),a=l.length,g>=a)if(r){for(;a++<=g;)l.push(0);u=f=0,i=1,o%=T,s=o-T+1}else break e;else{for(u=a=l[g],i=1;a>=10;a/=10)i++;o%=T,s=o-T+i,f=s<0?0:u/ee(10,i-s-1)%10|0}if(r=r||t<0||l[g+1]!==void 0||(s<0?u:u%ee(10,i-s-1)),c=n<4?(f||r)&&(n==0||n==(e.s<0?3:2)):f>5||f==5&&(n==4||r||n==6&&(o>0?s>0?u/ee(10,i-s):0:l[g-1])%10&1||n==(e.s<0?8:7)),t<1||!l[0])return l.length=0,c?(t-=e.e+1,l[0]=ee(10,(T-t%T)%T),e.e=-t||0):l[0]=e.e=0,e;if(o==0?(l.length=g,a=1,g--):(l.length=g+1,a=ee(10,T-o),l[g]=s>0?(u/ee(10,i-s)%ee(10,s)|0)*a:0),c)for(;;)if(g==0){for(o=1,s=l[0];s>=10;s/=10)o++;for(s=l[0]+=a,a=1;s>=10;s/=10)a++;o!=a&&(e.e++,l[0]==ve&&(l[0]=1));break}else{if(l[g]+=a,l[g]!=ve)break;l[g--]=0,a=1}for(o=l.length;l[--o]===0;)l.pop()}return j&&(e.e>m.maxE?(e.d=null,e.e=NaN):e.e<m.minE&&(e.e=0,e.d=[0])),e}p(M,"finalise");function be(e,t,n){if(!e.isFinite())return gr(e);var r,i=e.e,o=te(e.d),s=o.length;return t?(n&&(r=n-s)>0?o=o.charAt(0)+"."+o.slice(1)+Ue(r):s>1&&(o=o.charAt(0)+"."+o.slice(1)),o=o+(e.e<0?"e":"e+")+e.e):i<0?(o="0."+Ue(-i-1)+o,n&&(r=n-s)>0&&(o+=Ue(r))):i>=s?(o+=Ue(i+1-s),n&&(r=n-i-1)>0&&(o=o+"."+Ue(r))):((r=i+1)<s&&(o=o.slice(0,r)+"."+o.slice(r)),n&&(r=n-s)>0&&(i+1===s&&(o+="."),o+=Ue(r))),o}p(be,"finiteToString");function qt(e,t){var n=e[0];for(t*=T;n>=10;n/=10)t++;return t}p(qt,"getBase10Exponent");function Wt(e,t,n){if(t>ni)throw j=!0,n&&(e.precision=n),Error(cr);return M(new e(Bt),t,1,!0)}p(Wt,"getLn10");function Ee(e,t,n){if(t>wn)throw Error(cr);return M(new e(Ut),t,n,!0)}p(Ee,"getPi");function ur(e){var t=e.length-1,n=t*T+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}p(ur,"getPrecision");function Ue(e){for(var t="";e--;)t+="0";return t}p(Ue,"getZeroString");function pr(e,t,n,r){var i,o=new e(1),s=Math.ceil(r/T+4);for(j=!1;;){if(n%2&&(o=o.times(t),or(o.d,s)&&(i=!0)),n=ie(n/2),n===0){n=o.d.length-1,i&&o.d[n]===0&&++o.d[n];break}t=t.times(t),or(t.d,s)}return j=!0,o}p(pr,"intPow");function ir(e){return e.d[e.d.length-1]&1}p(ir,"isOdd");function mr(e,t,n){for(var r,i,o=new e(t[0]),s=0;++s<t.length;){if(i=new e(t[s]),!i.s){o=i;break}r=o.cmp(i),(r===n||r===0&&o.s===n)&&(o=i)}return o}p(mr,"maxOrMin");function vn(e,t){var n,r,i,o,s,a,f,c=0,u=0,l=0,g=e.constructor,m=g.rounding,h=g.precision;if(!e.d||!e.d[0]||e.e>17)return new g(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(j=!1,f=h):f=t,a=new g(.03125);e.e>-2;)e=e.times(a),l+=5;for(r=Math.log(ee(2,l))/Math.LN10*2+5|0,f+=r,n=o=s=new g(1),g.precision=f;;){if(o=M(o.times(e),f,1),n=n.times(++u),a=s.plus(q(o,n,f,1)),te(a.d).slice(0,f)===te(s.d).slice(0,f)){for(i=l;i--;)s=M(s.times(s),f,1);if(t==null)if(c<3&&St(s.d,f-r,m,c))g.precision=f+=10,n=o=a=new g(1),u=0,c++;else return M(s,g.precision=h,m,j=!0);else return g.precision=h,s}s=a}}p(vn,"naturalExponential");function We(e,t){var n,r,i,o,s,a,f,c,u,l,g,m=1,h=10,w=e,D=w.d,b=w.constructor,E=b.rounding,I=b.precision;if(w.s<0||!D||!D[0]||!w.e&&D[0]==1&&D.length==1)return new b(D&&!D[0]?-1/0:w.s!=1?NaN:D?0:w);if(t==null?(j=!1,u=I):u=t,b.precision=u+=h,n=te(D),r=n.charAt(0),Math.abs(o=w.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)w=w.times(e),n=te(w.d),r=n.charAt(0),m++;o=w.e,r>1?(w=new b("0."+n),o++):w=new b(r+"."+n.slice(1))}else return c=Wt(b,u+2,I).times(o+""),w=We(new b(r+"."+n.slice(1)),u-h).plus(c),b.precision=I,t==null?M(w,I,E,j=!0):w;for(l=w,f=s=w=q(w.minus(1),w.plus(1),u,1),g=M(w.times(w),u,1),i=3;;){if(s=M(s.times(g),u,1),c=f.plus(q(s,new b(i),u,1)),te(c.d).slice(0,u)===te(f.d).slice(0,u))if(f=f.times(2),o!==0&&(f=f.plus(Wt(b,u+2,I).times(o+""))),f=q(f,new b(m),u,1),t==null)if(St(f.d,u-h,E,a))b.precision=u+=h,c=s=w=q(l.minus(1),l.plus(1),u,1),g=M(w.times(w),u,1),i=a=1;else return M(f,b.precision=I,E,j=!0);else return b.precision=I,f;f=c,i+=2}}p(We,"naturalLogarithm");function gr(e){return String(e.s*e.s/0)}p(gr,"nonFiniteToString");function Lt(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%T,n<0&&(r+=T),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=T;r<i;)e.d.push(+t.slice(r,r+=T));t=t.slice(r),r=T-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),j&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}p(Lt,"parseDecimal");function ii(e,t){var n,r,i,o,s,a,f,c,u;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),lr.test(t))return Lt(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Yr.test(t))n=16,t=t.toLowerCase();else if(Kr.test(t))n=2;else if(ei.test(t))n=8;else throw Error($e+t);for(o=t.search(/p/i),o>0?(f=+t.slice(o+1),t=t.substring(2,o)):t=t.slice(2),o=t.indexOf("."),s=o>=0,r=e.constructor,s&&(t=t.replace(".",""),a=t.length,o=a-o,i=pr(r,new r(n),o,o*2)),c=Ot(t,n,ve),u=c.length-1,o=u;c[o]===0;--o)c.pop();return o<0?new r(e.s*0):(e.e=qt(c,u),e.d=c,j=!1,s&&(e=q(e,i,a*4)),f&&(e=e.times(Math.abs(f)<54?ee(2,f):ue.pow(2,f))),j=!0,e)}p(ii,"parseOther");function oi(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:ft(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Vt(5,n)),t=ft(e,2,t,t);for(var i,o=new e(5),s=new e(16),a=new e(20);n--;)i=t.times(t),t=t.times(o.plus(i.times(s.times(i).minus(a))));return t}p(oi,"sine");function ft(e,t,n,r,i){var o,s,a,f,c=1,u=e.precision,l=Math.ceil(u/T);for(j=!1,f=n.times(n),a=new e(r);;){if(s=q(a.times(f),new e(t++*t++),u,1),a=i?r.plus(s):r.minus(s),r=q(s.times(f),new e(t++*t++),u,1),s=a.plus(r),s.d[l]!==void 0){for(o=l;s.d[o]===a.d[o]&&o--;);if(o==-1)break}o=a,a=r,r=s,s=o,c++}return j=!0,s.d.length=l+1,s}p(ft,"taylorSeries");function Vt(e,t){for(var n=e;--t;)n*=e;return n}p(Vt,"tinyPow");function hr(e,t){var n,r=t.s<0,i=Ee(e,e.precision,1),o=i.times(.5);if(t=t.abs(),t.lte(o))return Te=r?4:1,t;if(n=t.divToInt(i),n.isZero())Te=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(o))return Te=ir(n)?r?2:3:r?4:1,t;Te=ir(n)?r?1:4:r?3:2}return t.minus(i).abs()}p(hr,"toLessThanHalfPi");function Dn(e,t,n,r){var i,o,s,a,f,c,u,l,g,m=e.constructor,h=n!==void 0;if(h?(de(n,1,qe),r===void 0?r=m.rounding:de(r,0,8)):(n=m.precision,r=m.rounding),!e.isFinite())u=gr(e);else{for(u=be(e),s=u.indexOf("."),h?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,s>=0&&(u=u.replace(".",""),g=new m(1),g.e=u.length-s,g.d=Ot(be(g),10,i),g.e=g.d.length),l=Ot(u,10,i),o=f=l.length;l[--f]==0;)l.pop();if(!l[0])u=h?"0p+0":"0";else{if(s<0?o--:(e=new m(e),e.d=l,e.e=o,e=q(e,g,n,r,0,i),l=e.d,o=e.e,c=ar),s=l[n],a=i/2,c=c||l[n+1]!==void 0,c=r<4?(s!==void 0||c)&&(r===0||r===(e.s<0?3:2)):s>a||s===a&&(r===4||c||r===6&&l[n-1]&1||r===(e.s<0?8:7)),l.length=n,c)for(;++l[--n]>i-1;)l[n]=0,n||(++o,l.unshift(1));for(f=l.length;!l[f-1];--f);for(s=0,u="";s<f;s++)u+=yn.charAt(l[s]);if(h){if(f>1)if(t==16||t==8){for(s=t==16?4:3,--f;f%s;f++)u+="0";for(l=Ot(u,i,t),f=l.length;!l[f-1];--f);for(s=1,u="1.";s<f;s++)u+=yn.charAt(l[s])}else u=u.charAt(0)+"."+u.slice(1);u=u+(o<0?"p":"p+")+o}else if(o<0){for(;++o;)u="0"+u;u="0."+u}else if(++o>f)for(o-=f;o--;)u+="0";else o<f&&(u=u.slice(0,o)+"."+u.slice(o))}u=(t==16?"0x":t==2?"0b":t==8?"0o":"")+u}return e.s<0?"-"+u:u}p(Dn,"toStringBinary");function or(e,t){if(e.length>t)return e.length=t,!0}p(or,"truncate");function si(e){return new this(e).abs()}p(si,"abs");function ai(e){return new this(e).acos()}p(ai,"acos");function ci(e){return new this(e).acosh()}p(ci,"acosh");function fi(e,t){return new this(e).plus(t)}p(fi,"add");function di(e){return new this(e).asin()}p(di,"asin");function li(e){return new this(e).asinh()}p(li,"asinh");function ui(e){return new this(e).atan()}p(ui,"atan");function pi(e){return new this(e).atanh()}p(pi,"atanh");function mi(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,o=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=Ee(this,o,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?Ee(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=Ee(this,o,1).times(.5),n.s=e.s):t.s<0?(this.precision=o,this.rounding=1,n=this.atan(q(e,t,o,1)),t=Ee(this,o,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(q(e,t,o,1)),n}p(mi,"atan2");function gi(e){return new this(e).cbrt()}p(gi,"cbrt");function hi(e){return M(e=new this(e),e.e+1,2)}p(hi,"ceil");function yi(e,t,n){return new this(e).clamp(t,n)}p(yi,"clamp");function Ii(e){if(!e||typeof e!="object")throw Error($t+"Object expected");var t,n,r,i=e.defaults===!0,o=["precision",1,qe,"rounding",0,8,"toExpNeg",-ct,0,"toExpPos",0,ct,"maxE",0,ct,"minE",-ct,0,"modulo",0,9];for(t=0;t<o.length;t+=3)if(n=o[t],i&&(this[n]=In[n]),(r=e[n])!==void 0)if(ie(r)===r&&r>=o[t+1]&&r<=o[t+2])this[n]=r;else throw Error($e+n+": "+r);if(n="crypto",i&&(this[n]=In[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(fr);else this[n]=!1;else throw Error($e+n+": "+r);return this}p(Ii,"config");function wi(e){return new this(e).cos()}p(wi,"cos");function vi(e){return new this(e).cosh()}p(vi,"cosh");function yr(e){var t,n,r;function i(o){var s,a,f,c=this;if(!(c instanceof i))return new i(o);if(c.constructor=i,sr(o)){c.s=o.s,j?!o.d||o.e>i.maxE?(c.e=NaN,c.d=null):o.e<i.minE?(c.e=0,c.d=[0]):(c.e=o.e,c.d=o.d.slice()):(c.e=o.e,c.d=o.d?o.d.slice():o.d);return}if(f=typeof o,f==="number"){if(o===0){c.s=1/o<0?-1:1,c.e=0,c.d=[0];return}if(o<0?(o=-o,c.s=-1):c.s=1,o===~~o&&o<1e7){for(s=0,a=o;a>=10;a/=10)s++;j?s>i.maxE?(c.e=NaN,c.d=null):s<i.minE?(c.e=0,c.d=[0]):(c.e=s,c.d=[o]):(c.e=s,c.d=[o]);return}if(o*0!==0){o||(c.s=NaN),c.e=NaN,c.d=null;return}return Lt(c,o.toString())}if(f==="string")return(a=o.charCodeAt(0))===45?(o=o.slice(1),c.s=-1):(a===43&&(o=o.slice(1)),c.s=1),lr.test(o)?Lt(c,o):ii(c,o);if(f==="bigint")return o<0?(o=-o,c.s=-1):c.s=1,Lt(c,o.toString());throw Error($e+o)}if(p(i,"Decimal"),i.prototype=v,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=Ii,i.clone=yr,i.isDecimal=sr,i.abs=si,i.acos=ai,i.acosh=ci,i.add=fi,i.asin=di,i.asinh=li,i.atan=ui,i.atanh=pi,i.atan2=mi,i.cbrt=gi,i.ceil=hi,i.clamp=yi,i.cos=wi,i.cosh=vi,i.div=Di,i.exp=Si,i.floor=ki,i.hypot=Ei,i.ln=bi,i.log=xi,i.log10=Ni,i.log2=Pi,i.max=Mi,i.min=_i,i.mod=Ti,i.mul=Ci,i.pow=Ri,i.random=ji,i.round=Ai,i.sign=Fi,i.sin=Oi,i.sinh=Li,i.sqrt=Bi,i.sub=Ui,i.sum=Wi,i.tan=$i,i.tanh=qi,i.trunc=Vi,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}p(yr,"clone");function Di(e,t){return new this(e).div(t)}p(Di,"div");function Si(e){return new this(e).exp()}p(Si,"exp");function ki(e){return M(e=new this(e),e.e+1,3)}p(ki,"floor");function Ei(){var e,t,n=new this(0);for(j=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return j=!0,new this(1/0);n=t}return j=!0,n.sqrt()}p(Ei,"hypot");function sr(e){return e instanceof ue||e&&e.toStringTag===dr||!1}p(sr,"isDecimalInstance");function bi(e){return new this(e).ln()}p(bi,"ln");function xi(e,t){return new this(e).log(t)}p(xi,"log");function Pi(e){return new this(e).log(2)}p(Pi,"log2");function Ni(e){return new this(e).log(10)}p(Ni,"log10");function Mi(){return mr(this,arguments,-1)}p(Mi,"max");function _i(){return mr(this,arguments,1)}p(_i,"min");function Ti(e,t){return new this(e).mod(t)}p(Ti,"mod");function Ci(e,t){return new this(e).mul(t)}p(Ci,"mul");function Ri(e,t){return new this(e).pow(t)}p(Ri,"pow");function ji(e){var t,n,r,i,o=0,s=new this(1),a=[];if(e===void 0?e=this.precision:de(e,1,qe),r=Math.ceil(e/T),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));o<r;)i=t[o],i>=429e7?t[o]=crypto.getRandomValues(new Uint32Array(1))[0]:a[o++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);o<r;)i=t[o]+(t[o+1]<<8)+(t[o+2]<<16)+((t[o+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,o):(a.push(i%1e7),o+=4);o=r/4}else throw Error(fr);else for(;o<r;)a[o++]=Math.random()*1e7|0;for(r=a[--o],e%=T,r&&e&&(i=ee(10,T-e),a[o]=(r/i|0)*i);a[o]===0;o--)a.pop();if(o<0)n=0,a=[0];else{for(n=-1;a[0]===0;n-=T)a.shift();for(r=1,i=a[0];i>=10;i/=10)r++;r<T&&(n-=T-r)}return s.e=n,s.d=a,s}p(ji,"random");function Ai(e){return M(e=new this(e),e.e+1,this.rounding)}p(Ai,"round");function Fi(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}p(Fi,"sign");function Oi(e){return new this(e).sin()}p(Oi,"sin");function Li(e){return new this(e).sinh()}p(Li,"sinh");function Bi(e){return new this(e).sqrt()}p(Bi,"sqrt");function Ui(e,t){return new this(e).sub(t)}p(Ui,"sub");function Wi(){var e=0,t=arguments,n=new this(t[e]);for(j=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return j=!0,M(n,this.precision,this.rounding)}p(Wi,"sum");function $i(e){return new this(e).tan()}p($i,"tan");function qi(e){return new this(e).tanh()}p(qi,"tanh");function Vi(e){return M(e=new this(e),e.e+1,1)}p(Vi,"trunc");v[Symbol.for("nodejs.util.inspect.custom")]=v.toString;v[Symbol.toStringTag]="Decimal";var ue=v.constructor=yr(In);Bt=new ue(Bt);Ut=new ue(Ut);var kn={};je(kn,{NotFoundError:()=>xe,Service:()=>dt,Storage:()=>kn,node:()=>ro});import oe from"path";var xe=class e extends S.TaggedErrorClass()("NotFoundError",{message:S.String}){static{p(this,"NotFoundError")}static isInstance(t){return t instanceof e}},Ji=S.Struct({path:S.optional(S.Struct({root:S.optional(S.String)}))}),zi=S.Struct({id:S.String}),Gi=S.Struct({id:S.String}),Hi=S.Struct({additions:Oe,deletions:Oe}),Zi=S.Struct({id:S.String,projectID:S.String,summary:S.Struct({diffs:S.Array(Hi)})}),Qi=S.decodeUnknownOption(Ji),Xi=S.decodeUnknownOption(zi),Ki=S.decodeUnknownOption(Gi),Yi=S.decodeUnknownOption(Zi),dt=class extends Fe.Service()("@opencode/Storage"){static{p(this,"Service")}};function eo(e,t){return oe.join(e,...t)+".json"}p(eo,"file");function Sn(e){return!e||typeof e!="object"?!1:"code"in e&&e.code==="ENOENT"?!0:"reason"in e&&e.reason&&typeof e.reason=="object"&&"_tag"in e.reason?e.reason._tag==="NotFound":!1}p(Sn,"missing");function to(e){let t=Number.parseInt(e,10);return Number.isNaN(t)?0:t}p(to,"parseMigration");var Ir=[d.fn("Storage.migration.1")(function*(e,t,n){let r=oe.resolve(e,"../project");if(!(yield*t.isDir(r)))return;let i=yield*t.glob("*",{cwd:r,include:"all"});for(let o of i){let s=oe.join(r,o);if(!(yield*t.isDir(s)))continue;yield*d.logInfo(`migrating project ${o}`);let a=o,f="/";if(a!=="global"){for(let l of yield*t.glob("storage/session/message/*/*.json",{cwd:s,absolute:!0})){let g=Qi(yield*t.readJson(l),{onExcessProperty:"preserve"}),m=Ae.isSome(g)?g.value.path?.root:void 0;if(m){f=m;break}}if(!f||!(yield*t.isDir(f)))continue;let c=yield*n.run(["rev-list","--max-parents=0","--all"],{cwd:f}),[u]=c.text().split(`
19
+ `).filter(Boolean).map(l=>l.trim()).toSorted();if(!u)continue;a=u,yield*t.writeWithDirs(oe.join(e,"project",a+".json"),JSON.stringify({id:u,vcs:"git",worktree:f,time:{created:Date.now(),initialized:Date.now()}},null,2)),yield*d.logInfo(`migrating sessions for project ${a}`);for(let l of yield*t.glob("storage/session/info/*.json",{cwd:s,absolute:!0})){let g=oe.join(e,"session",a,oe.basename(l));yield*d.logInfo("copying",{sessionFile:l,dest:g});let m=yield*t.readJson(l),h=Xi(m,{onExcessProperty:"preserve"});if(yield*t.writeWithDirs(g,JSON.stringify(m,null,2)),!Ae.isNone(h)){yield*d.logInfo(`migrating messages for session ${h.value.id}`);for(let w of yield*t.glob(`storage/session/message/${h.value.id}/*.json`,{cwd:s,absolute:!0})){let D=oe.join(e,"message",h.value.id,oe.basename(w));yield*d.logInfo("copying",{msgFile:w,dest:D});let b=yield*t.readJson(w),E=Ki(b,{onExcessProperty:"preserve"});if(yield*t.writeWithDirs(D,JSON.stringify(b,null,2)),!Ae.isNone(E)){yield*d.logInfo(`migrating parts for message ${E.value.id}`);for(let I of yield*t.glob(`storage/session/part/${h.value.id}/${E.value.id}/*.json`,{cwd:s,absolute:!0})){let P=oe.join(e,"part",E.value.id,oe.basename(I)),O=yield*t.readJson(I);yield*d.logInfo("copying",{partFile:I,dest:P}),yield*t.writeWithDirs(P,JSON.stringify(O,null,2))}}}}}}}}),d.fn("Storage.migration.2")(function*(e,t){for(let n of yield*t.glob("session/*/*.json",{cwd:e,absolute:!0})){let r=yield*t.readJson(n),i=Yi(r,{onExcessProperty:"preserve"});if(Ae.isNone(i))continue;let o=i.value.summary.diffs;yield*t.writeWithDirs(oe.join(e,"session_diff",i.value.id+".json"),JSON.stringify(o,null,2)),yield*t.writeWithDirs(oe.join(e,"session",i.value.projectID,i.value.id+".json"),JSON.stringify({...r,summary:{additions:o.reduce((s,a)=>s+a.additions,0),deletions:o.reduce((s,a)=>s+a.deletions,0)}},null,2))}})],no=De.effect(dt,d.gen(function*(){let e=yield*ot.Service,t=yield*mn.Service,n=yield*Xt.make({lookup:p(()=>rt.make(),"lookup"),idleTimeToLive:0}),r=yield*d.cached(d.gen(function*(){let m=oe.join(it.Path.data,"storage"),h=oe.join(m,"migration"),w=yield*e.readFileString(h).pipe(d.map(to),d.catchIf(Sn,()=>d.succeed(0)),d.orElseSucceed(()=>0));for(let D=w;D<Ir.length;D++){yield*d.logInfo("running migration",{index:D});let b=Ir[D],E=yield*d.exit(b(m,e,t));if(Ie.isFailure(E)){yield*d.logError("failed to run migration",{index:D,cause:E.cause});break}yield*e.writeWithDirs(h,String(D+1))}return{dir:m}})),i=p(m=>d.fail(new xe({message:`Resource not found: ${m}`})),"fail"),o=p((m,h)=>h.pipe(d.catchIf(Sn,()=>i(m))),"wrap"),s=d.fnUntraced(function*(m,h){yield*e.writeWithDirs(m,JSON.stringify(h,null,2))}),a=p((m,h)=>d.scoped(d.gen(function*(){let w=eo((yield*r).dir,m);return yield*h(w,yield*Xt.get(n,w))})),"withResolved"),f=d.fn("Storage.remove")(function*(m){yield*a(m,(h,w)=>rt.withWriteLock(w,e.remove(h).pipe(d.catchIf(Sn,()=>d.void))))}),c=p(m=>d.gen(function*(){return yield*a(m,(w,D)=>rt.withReadLock(D,o(w,e.readJson(w))))}),"read"),u=p((m,h)=>d.gen(function*(){return yield*a(m,(D,b)=>rt.withWriteLock(b,d.gen(function*(){let E=yield*o(D,e.readJson(D));return h(E),yield*s(D,E),E})))}),"update"),l=p((m,h)=>d.gen(function*(){yield*a(m,(w,D)=>rt.withWriteLock(D,s(w,h)))}),"write"),g=d.fn("Storage.list")(function*(m){let h=(yield*r).dir,w=oe.join(h,...m);return(yield*e.glob("**/*",{cwd:w,include:"file"}).pipe(d.catch(()=>d.succeed([])))).map(b=>[...m,...b.slice(0,-5).split(oe.sep)]).toSorted((b,E)=>b.join("/").localeCompare(E.join("/")))});return dt.of({remove:f,read:c,update:u,write:l,list:g})})),ro=Se.make({service:dt,layer:no,deps:[ot.node,mn.node]});var ze={};je(ze,{Event:()=>fo,MessageV2:()=>ze,SYNTHETIC_ATTACHMENT_PROMPT:()=>br,cursor:()=>Nn,dateNote:()=>Mr,filterCompacted:()=>Rr,filterCompactedEffect:()=>yo,fromError:()=>wo,get:()=>ho,isMedia:()=>Et,latest:()=>Io,node:()=>vo,page:()=>_r,parts:()=>Cr,stream:()=>Tr,toModelMessages:()=>go,toModelMessagesEffect:()=>Nr});var se=Qn.ID,Ve=S.String.check(S.isStartsWith("msg")).pipe(S.brand("MessageID"),en(e=>({ascending:p(t=>e.make(un.ascending("message",t)),"ascending")}))),Jt=S.String.check(S.isStartsWith("prt")).pipe(S.brand("PartID"),en(e=>({ascending:p(t=>e.make(un.ascending("part",t)),"ascending")})));var Je={};je(Je,{HeaderTimeoutError:()=>En,ProviderError:()=>Je,RESPONSE_FAILED_CODE:()=>Sr,RESPONSE_INCOMPLETE_CODE:()=>Dr,ResponseStreamError:()=>bn,parseAPICallError:()=>ao,parseStreamError:()=>so,quotaExhaustion:()=>Pn,statedRetryDelayMs:()=>xn});import{STATUS_CODES as wr}from"http";function lt(e){return e()}p(lt,"iife");var En=class extends Error{constructor(n){super(`Provider response headers timed out after ${n}ms`);this.ms=n}ms;static{p(this,"HeaderTimeoutError")}name="ProviderHeaderTimeoutError"},bn=class extends Error{static{p(this,"ResponseStreamError")}name="ProviderResponseStreamError";constructor(t,n){super(t,n)}},Dr="response_incomplete",Sr="response_failed";function io(e){let t=e.statusCode;return t&&t===404||e.isRetryable}p(io,"isOpenAiErrorRetryable");function oo(e,t){return lt(()=>{let n=t.message;if(n===""){if(t.responseBody)return t.responseBody;if(t.statusCode){let r=wr[t.statusCode];if(r)return r}return"Unknown error"}if(!t.responseBody||t.statusCode&&n!==wr[t.statusCode])return n;try{let r=JSON.parse(t.responseBody),i=r.message||r.error||r.error?.message;if(i&&typeof i=="string")return`${n}: ${i}`}catch{}return/^\s*<!doctype|^\s*<html/i.test(t.responseBody)?t.statusCode===401?"Unauthorized: request was blocked by a gateway or proxy. Your authentication token may be missing or expired \u2014 try running `opencode auth login <your provider URL>` to re-authenticate.":t.statusCode===403?"Forbidden: request was blocked by a gateway or proxy. You may not have permission to access this resource \u2014 check your account and provider settings.":n:`${n}: ${t.responseBody}`}).trim()}p(oo,"message");function kt(e){if(typeof e=="string")try{let t=JSON.parse(e);return t&&typeof t=="object"?t:void 0}catch{return}if(typeof e=="object"&&e!==null)return e}p(kt,"json");var vr=new Set(["usage_limit_reached","insufficient_quota","billing_hard_limit_reached","quota_exceeded"]);function xn(e){let t=kt(e),n=t&&typeof t.error=="object"?t.error:void 0,r=Array.isArray(n?.details)?n.details:[];for(let i of r){if(!i||typeof i!="object")continue;let o=i;if(typeof o["@type"]!="string"||!o["@type"].endsWith("google.rpc.RetryInfo"))continue;let s=typeof o.retryDelay=="string"?/^(\d+(?:\.\d+)?)s$/.exec(o.retryDelay):null;if(s)return Math.ceil(Number.parseFloat(s[1])*1e3)}}p(xn,"statedRetryDelayMs");function Pn(e){let t=xn(e.body);if(t!==void 0&&t<=6e5)return;let n=kt(e.body),r=lt(()=>{if(!n)return;let h=n.error;return h&&typeof h=="object"?h:n}),i=typeof r?.type=="string"?r.type:"",o=typeof r?.code=="string"?r.code:"",s=typeof r?.message=="string"?r.message:e.message??"",a=typeof r?.resets_at=="number"?r.resets_at:void 0,f=typeof r?.resets_in_seconds=="number"?r.resets_in_seconds:void 0,c=typeof r?.plan_type=="string"?r.plan_type:void 0,u=vr.has(i)||vr.has(o),l=e.statusCode===429||e.statusCode===402,g=/usage limit|quota/i.test(s),m=(f??0)>600||a!==void 0&&a*1e3-Date.now()>6e5;if(u||l&&(g||m))return{message:s||"Provider usage limit reached",planType:c,resetsAt:a??(f!==void 0?Math.round(Date.now()/1e3)+f:void 0)??(t!==void 0?Math.round((Date.now()+t)/1e3):void 0)}}p(Pn,"quotaExhaustion");function so(e){let t=kt(e),n=typeof t?.message=="string"?kt(t.message)??t:t;if(!n)return;let r=JSON.stringify(n);if(n.type!=="error")return;switch(n?.error?.code){case"context_length_exceeded":return{type:"context_overflow",message:"Input exceeds context window of this model",responseBody:r};case"insufficient_quota":return{type:"quota",message:"Quota exceeded. Check your plan and billing details.",responseBody:r};case"usage_not_included":return{type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:!1,responseBody:r};case"invalid_prompt":return{type:"api_error",message:typeof n?.error?.message=="string"?n?.error?.message:"Invalid prompt.",isRetryable:!1,responseBody:r};case"server_is_overloaded":case"server_error":return{type:"api_error",message:typeof n?.error?.message=="string"?n?.error?.message:"Server error.",isRetryable:!0,responseBody:r};case Dr:return{type:"unknown",message:typeof n?.error?.message=="string"?n?.error?.message:"The response failed.",responseBody:r}}let i=Pn({body:n});if(i)return{type:"quota",message:i.message,planType:i.planType,resetsAt:i.resetsAt,responseBody:r};if(n?.error?.type===Sr){let o=typeof n.error.code=="string"?n.error.code:"";return{type:"api_error",message:typeof n.error.message=="string"&&n.error.message?n.error.message:"The response failed.",isRetryable:!/invalid|policy/i.test(o),responseBody:r}}return{type:"api_error",message:typeof n?.error?.message=="string"?n.error.message:"Server error.",isRetryable:!0,responseBody:r}}p(so,"parseStreamError");function ao(e){let t=oo(e.providerID,e.error),n=kt(e.error.responseBody);if(Vn(t)||e.error.statusCode===413||n?.error?.code==="context_length_exceeded")return{type:"context_overflow",message:t,responseBody:e.error.responseBody};let r=Pn({statusCode:e.error.statusCode,body:n,message:t});if(r)return{type:"quota",message:r.message,statusCode:e.error.statusCode,planType:r.planType,resetsAt:r.resetsAt,responseBody:e.error.responseBody};let i=e.error.url?{url:e.error.url}:void 0;return{type:"api_error",message:t,statusCode:e.error.statusCode,isRetryable:e.providerID.startsWith("openai")?io(e.error):e.error.isRetryable,responseHeaders:lt(()=>{let o=xn(e.error.responseBody),s=e.error.responseHeaders;return o===void 0||s?.["retry-after"]||s?.["retry-after-ms"]?s:{...s??{},"retry-after-ms":String(o)}}),responseBody:e.error.responseBody,metadata:i}}p(ao,"parseAPICallError");var Ke=p((e,t)=>t.every((n,r)=>e[r]===n),"startsWith");function co(e){return e==="application/pdf"}p(co,"isPdfAttachment");function Et(e){return e.startsWith("image/")||co(e)}p(Et,"isMedia");function As(e){return e.startsWith("image/")&&e!=="image/svg+xml"&&e!=="image/vnd.fastbidsheet"}p(As,"isImageAttachment");function Fs(e,t){return Ke(e,[137,80,78,71,13,10,26,10])?"image/png":Ke(e,[255,216,255])?"image/jpeg":Ke(e,[71,73,70,56])?"image/gif":Ke(e,[66,77])?"image/bmp":Ke(e,[37,80,68,70,45])?"application/pdf":Ke(e,[82,73,70,70])&&Ke(e.subarray(8),[87,69,66,80])?"image/webp":t}p(Fs,"sniffAttachmentMime");var br="Attached media from tool result:";function kr(e,t){if(!t||e.length<=t)return e;let n=e.length-t;return`${e.slice(0,t)}
20
+ [Tool output truncated for compaction: omitted ${n} chars]`}p(kr,"truncateToolOutput");var fo={Updated:Y.Event.MessageUpdated,Removed:Y.Event.MessageRemoved,PartUpdated:Y.Event.PartUpdated,PartDelta:Y.Event.PartDelta,PartRemoved:Y.Event.PartRemoved},lo=S.Struct({id:Ve,time:S.Finite.check(S.isGreaterThanOrEqualTo(0))}),uo=S.decodeUnknownSync(lo),Nn={encode(e){return Buffer.from(JSON.stringify(e)).toString("base64url")},decode(e){return uo(JSON.parse(Buffer.from(e,"base64url").toString("utf8")))}},xr=p(e=>({...e.data,id:e.id,sessionID:e.session_id}),"info"),Pr=p(e=>({...e.data,id:e.id,sessionID:e.session_id,messageID:e.message_id}),"part"),po=p(e=>yt(It(ge.time_created,e.time),ke(K(ge.time_created,e.time),It(ge.id,e.id))),"older");function mo(e,t){let n=t.map(i=>i.id),r=new Map;return d.gen(function*(){if(n.length>0){let i=yield*e.select().from(le).where(Rt(le.message_id,n)).orderBy(le.message_id,le.id).all().pipe(d.orDie);for(let o of i){let s=Pr(o),a=r.get(o.message_id);a?a.push(s):r.set(o.message_id,[s])}}return t.map(i=>({info:xr(i),parts:r.get(i.id)??[]}))})}p(mo,"hydrate");function zt(e){if(!e)return;let{providerExecuted:t,...n}=e;return Object.keys(n).length>0?n:void 0}p(zt,"providerMeta");var Nr=d.fnUntraced(function*(e,t,n){let r=[],i=new Set,o=dn.view(e,t),s,a=p(m=>{for(let[h,w]of(m?o?.after.get(m):void 0)?.entries()??[])r.push({id:`${m}-system-${h}`,role:"system",parts:[{type:"text",text:w}]})},"systemAfter"),f=p(m=>{if(t.api.npm==="@ai-sdk/anthropic"||t.api.npm==="@ai-sdk/openai"||t.api.npm==="@ai-sdk/amazon-bedrock/mantle")return!0;if(t.api.npm==="@ai-sdk/amazon-bedrock"){if(!m.mime.startsWith("image/"))return!1;let h=t.api.id.toLowerCase();return h.includes("anthropic.")||h.includes("nova")||h.includes("llama4")||h.includes("llama-4")}if(t.api.npm==="@ai-sdk/xai")return m.mime.startsWith("image/");if(t.api.npm==="@ai-sdk/google-vertex/anthropic")return!0;if(t.api.npm==="@ai-sdk/google"){let h=t.api.id.toLowerCase();return h.includes("gemini-3")&&!h.includes("gemini-2")}return!1},"supportsMediaInToolResult"),c=p(m=>t.api.npm==="@ai-sdk/xai"&&m.mime.startsWith("image/")&&!["image/png","image/jpeg","image/webp"].includes(m.mime),"rejectedByProvider"),u=p(m=>{let h=m.output;if(typeof h=="string")return{type:"text",value:h};if(typeof h=="object"){let w=h,D=(w.attachments??[]).filter(b=>b.url.startsWith("data:")&&b.url.includes(","));return{type:"content",value:[...w.text?[{type:"text",text:w.text}]:[],...D.map(b=>({type:"media",mediaType:b.mime,data:lt(()=>{let E=b.url.indexOf(",");return E===-1?b.url:b.url.slice(E+1)})}))]}}return{type:"json",value:h}},"toModelOutput"),l;for(let m of e)if(o&&(a(s),s=m.info.id),m.parts.length!==0&&!o?.drop.has(m.info.id)){if(m.info.role==="user"){let h={id:m.info.id,role:"user",parts:[]},w=new Date(m.info.time.created).toDateString(),D=Mr(l,w);l=w;for(let b of m.parts)b.type==="text"&&!b.ignored&&b.text!==""&&h.parts.push({type:"text",text:b.text}),b.type==="file"&&b.mime!=="text/plain"&&b.mime!=="application/x-directory"&&(n?.stripMedia&&Et(b.mime)?h.parts.push({type:"text",text:`[Attached ${b.mime}: ${b.filename??"file"}]`}):h.parts.push({type:"file",url:b.url,mediaType:b.mime,filename:b.filename})),b.type==="compaction"&&!o?.skip.has(m.info.id)&&h.parts.push({type:"text",text:"What did we do so far?"}),b.type==="subtask"&&h.parts.push({type:"text",text:"The following tool was executed by the user"});h.parts.length>0&&(D&&h.parts.unshift({type:"text",text:D}),r.push(h))}if(m.info.role==="assistant"){let h=`${t.providerID}/${t.id}`!=`${m.info.providerID}/${m.info.modelID}`,w=o?.blocks.get(m.info.id);if(w){dn.remember(w),r.push({id:m.info.id,role:"assistant",parts:[{type:"text",text:w.content,providerMetadata:{anthropic:{type:"compaction"}}}]});continue}let D=[];if(m.info.error&&!(vt.isInstance(m.info.error)&&m.parts.some(I=>I.type!=="step-start"&&I.type!=="reasoning")))continue;if(m.info.aside){let I=m.parts.filter(P=>P.type==="text"&&!P.ignored).map(P=>P.text.trim()).filter(Boolean).join(`
21
+ `);I&&r.push({id:m.info.id,role:"user",parts:[{type:"text",text:`[While a tool was running you already answered the user's message above: "${I}". Do not answer it again; carry on with your work.]`}]});continue}let b={id:m.info.id,role:"assistant",parts:[]},E=m.parts.some(I=>I.type!=="reasoning"?!1:I.metadata?.anthropic?.signature!=null);for(let I of m.parts){if(I.type==="text"){let P=I.text===""&&E?" ":I.text;b.parts.push({type:"text",text:P,...h?{}:{providerMetadata:I.metadata}})}if(I.type==="step-start"&&b.parts.push({type:"step-start"}),I.type==="tool"){if(i.add(I.tool),I.state.status==="completed"){let P=I.state.time.compacted?"[Old tool result content cleared]":kr(I.state.output,n?.toolOutputMaxChars),O=I.state.time.compacted||n?.stripMedia?[]:(I.state.attachments??[]).filter(ne=>!c(ne)),H=O.filter(ne=>Et(ne.mime)).filter(ne=>!f(ne));H.length>0&&D.push(...H);let ae=O.filter(ne=>!Et(ne.mime)||f(ne)),he=ae.length>0?{text:P,attachments:ae}:P;b.parts.push({type:"tool-"+I.tool,state:"output-available",toolCallId:I.callID,input:I.state.input,output:he,...I.metadata?.providerExecuted?{providerExecuted:!0}:{},...h?{}:{callProviderMetadata:zt(I.metadata)}})}if(I.state.status==="error"){let P=I.state.metadata?.interrupted===!0?I.state.metadata.output:void 0;typeof P=="string"?b.parts.push({type:"tool-"+I.tool,state:"output-available",toolCallId:I.callID,input:I.state.input,output:P,...I.metadata?.providerExecuted?{providerExecuted:!0}:{},...h?{}:{callProviderMetadata:zt(I.metadata)}}):b.parts.push({type:"tool-"+I.tool,state:"output-error",toolCallId:I.callID,input:I.state.input,errorText:kr(I.state.error,n?.toolOutputMaxChars),...I.metadata?.providerExecuted?{providerExecuted:!0}:{},...h?{}:{callProviderMetadata:zt(I.metadata)}})}(I.state.status==="pending"||I.state.status==="running")&&b.parts.push({type:"tool-"+I.tool,state:"output-error",toolCallId:I.callID,input:I.state.input,errorText:n?.runningToolNote??"[Tool execution was interrupted]",...I.metadata?.providerExecuted?{providerExecuted:!0}:{},...h?{}:{callProviderMetadata:zt(I.metadata)}})}if(I.type==="reasoning"){if(h){I.text.trim().length>0&&b.parts.push({type:"text",text:I.text});continue}b.parts.push({type:"reasoning",text:I.text,providerMetadata:I.metadata})}}b.parts.length>0&&(r.push(b),D.length>0&&r.push({id:Ve.ascending(),role:"user",parts:[{type:"text",text:br},...D.map(I=>({type:"file",url:I.url,mediaType:I.mime,filename:I.filename}))]}))}}o&&a(s);let g=Object.fromEntries(Array.from(i).map(m=>[m,{toModelOutput:u}]));return yield*d.promise(()=>er(r.filter(m=>m.parts.some(h=>h.type!=="step-start")),{tools:g}))});function Mr(e,t){return e!==void 0&&e!==t?`Today's date is now: ${t}`:null}p(Mr,"dateNote");function go(e,t,n){return d.runPromise(Nr(e,t,n))}p(go,"toModelMessages");var _r=d.fn("MessageV2.page")(function*(e){let{db:t}=yield*me.Service,n=e.before?Nn.decode(e.before):void 0,r=n?ke(K(ge.session_id,e.sessionID),po(n)):K(ge.session_id,e.sessionID),i=yield*t.select().from(ge).where(r).orderBy(Xe(ge.time_created),Xe(ge.id)).limit(e.limit+1).all().pipe(d.orDie);if(i.length===0)return(yield*t.select({id:U.id}).from(U).where(K(U.id,e.sessionID)).get().pipe(d.orDie))?{items:[],more:!1}:yield*new xe({message:`Session not found: ${e.sessionID}`});let o=i.length>e.limit,s=o?i.slice(0,e.limit):i,a=yield*mo(t,s);a.reverse();let f=s.at(-1);return{items:a,more:o,cursor:o&&f?Nn.encode({id:f.id,time:f.time_created}):void 0}});function Tr(e){return d.gen(function*(){let n=[],r;for(;;){let i=yield*_r({sessionID:e,limit:50,before:r}).pipe(d.catchIf(xe.isInstance,()=>d.succeed({items:[],more:!1,cursor:void 0})));if(i.items.length===0)break;for(let o=i.items.length-1;o>=0;o--){let s=i.items[o];s&&n.push(s)}if(!i.more||!i.cursor)break;r=i.cursor}return n})}p(Tr,"stream");function Cr(e){return d.gen(function*(){let{db:t}=yield*me.Service;return(yield*t.select().from(le).where(K(le.message_id,e)).orderBy(le.id).all().pipe(d.orDie)).map(Pr)})}p(Cr,"parts");var ho=d.fn("MessageV2.get")(function*(e){let{db:t}=yield*me.Service,n=yield*t.select().from(ge).where(ke(K(ge.id,e.messageID),K(ge.session_id,e.sessionID))).get().pipe(d.orDie);return n?{info:xr(n),parts:yield*Cr(e.messageID)}:yield*new xe({message:`Message not found: ${e.messageID}`})});function Rr(e){let t=[],n=new Set,r;for(let c of e){if(t.push(c),r){if(c.info.id===r)break;continue}if(c.info.role==="user"&&n.has(c.info.id)){let u=c.parts.find(l=>l.type==="compaction");if(!u)continue;if(!u.tail_start_id||(r=u.tail_start_id,c.info.id===r))break;continue}if(c.info.role==="user"&&n.has(c.info.id)&&c.parts.some(u=>u.type==="compaction"))break;c.info.role==="assistant"&&c.info.summary&&c.info.finish&&!c.info.error&&n.add(c.info.parentID)}t.reverse();let i=t.findLastIndex(c=>c.info.role==="user"&&c.parts.some(u=>u.type==="compaction"&&u.tail_start_id!==void 0)),o=t[i],s=o?.parts.find(c=>c.type==="compaction"&&c.tail_start_id!==void 0),a=o?t.findIndex((c,u)=>u>i&&c.info.role==="assistant"&&c.info.summary&&c.info.parentID===o.info.id):-1,f=s?.tail_start_id?t.findIndex(c=>c.info.id===s.tail_start_id):-1;return f>=0&&f<i&&a>i?[...t.slice(i,a+1),...t.slice(f,i),...t.slice(a+1)]:t}p(Rr,"filterCompacted");var yo=d.fnUntraced(function*(e){return Rr(yield*Tr(e))});function Io(e){let t,n,r;for(let o of e){let s=o.info;s.role==="user"&&Gt(s,t)&&(t=s),s.role==="assistant"&&Gt(s,n)&&(n=s),s.role==="assistant"&&s.finish&&Gt(s,r)&&(r=s)}let i=e.flatMap(o=>r&&!Gt(o.info,r)?[]:o.parts.filter(s=>s.type==="compaction"||s.type==="subtask"));return{user:t,assistant:n,finished:r,tasks:i}}p(Io,"latest");function Gt(e,t){return t?e.time.created!==t.time.created?e.time.created>t.time.created:e.id>t.id:!0}p(Gt,"isAfter");function wo(e,t){switch(!0){case(e instanceof DOMException&&e.name==="AbortError"):return new vt({message:e.message},{cause:e}).toObject();case Gn.isInstance(e):return e;case _e.isInstance(e):return e.toObject();case Kn.isInstance(e):return new Hn({providerID:t.providerID,message:e.message},{cause:e}).toObject();case Er(e)!==void 0:{let r=Er(e);return new _e({message:"Connection reset by server",isRetryable:!0,metadata:{code:r.code??"",syscall:r.syscall??"",message:r.message??""}},{cause:e}).toObject()}case(e instanceof TypeError&&e.message==="terminated"):{if(t.aborted)return new vt({message:e.message},{cause:e}).toObject();let r=e.cause;return new _e({message:"Connection closed by server",isRetryable:!0,metadata:{code:typeof r?.code=="string"?r.code:"",message:typeof r?.message=="string"?r.message:""}},{cause:e}).toObject()}case(e instanceof Error&&e.code==="ZlibError"):return t.aborted?new vt({message:e.message},{cause:e}).toObject():new _e({message:"Response decompression failed",isRetryable:!0,metadata:{code:e.code,message:e.message}},{cause:e}).toObject();case e instanceof Je.HeaderTimeoutError:return new _e({message:e.message,isRetryable:!0,metadata:{code:e.name,timeoutMs:String(e.ms)}},{cause:e}).toObject();case e instanceof Je.ResponseStreamError:return new _e({message:e.message,isRetryable:!0,metadata:{code:e.name}},{cause:e}).toObject();case Xn.isInstance(e):let n=Je.parseAPICallError({providerID:t.providerID,error:e});return n.type==="context_overflow"?new fn({message:n.message,responseBody:n.responseBody},{cause:e}).toObject():n.type==="quota"?new cn({providerID:t.providerID,message:n.message,planType:n.planType,resetsAt:n.resetsAt,statusCode:n.statusCode,responseBody:n.responseBody},{cause:e}).toObject():new _e({message:n.message,statusCode:n.statusCode,isRetryable:n.isRetryable,responseHeaders:n.responseHeaders,responseBody:n.responseBody,metadata:n.metadata},{cause:e}).toObject();case e instanceof Error:return new At.Unknown({message:Yn(e)},{cause:e}).toObject();default:try{let r=Je.parseStreamError(e);if(r)return r.type==="context_overflow"?new fn({message:r.message,responseBody:r.responseBody},{cause:e}).toObject():r.type==="quota"?new cn({providerID:t.providerID,message:r.message,planType:r.planType,resetsAt:r.resetsAt,responseBody:r.responseBody},{cause:e}).toObject():r.type==="unknown"?new At.Unknown({message:r.message},{cause:e}).toObject():new _e({message:r.message,isRetryable:r.isRetryable,responseBody:r.responseBody},{cause:e}).toObject()}catch{}return new At.Unknown({message:JSON.stringify(e)},{cause:e}).toObject()}}p(wo,"fromError");function Er(e){let t=e;for(let n=0;n<4&&t;n++){if(t?.code==="ECONNRESET")return t;t=t?.cause}}p(Er,"connectionResetError");var vo=Se.group([me.node]);var Pt={};je(Pt,{FileDiff:()=>bo,Patch:()=>Eo,Service:()=>pt,Snapshot:()=>Pt,node:()=>No});var bt=class{static{p(this,"Diff")}diff(t,n,r={}){let i;typeof r=="function"?(i=r,r={}):"callback"in r&&(i=r.callback);let o=this.castInput(t,r),s=this.castInput(n,r),a=this.removeEmpty(this.tokenize(o,r)),f=this.removeEmpty(this.tokenize(s,r));return this.diffWithOptionsObj(a,f,r,i)}diffWithOptionsObj(t,n,r,i){var o;let s=p(E=>{if(E=this.postProcess(E,r),i){setTimeout(function(){i(E)},0);return}else return E},"done"),a=n.length,f=t.length,c=1,u=a+f;r.maxEditLength!=null&&(u=Math.min(u,r.maxEditLength));let l=(o=r.timeout)!==null&&o!==void 0?o:1/0,g=Date.now()+l,m=[{oldPos:-1,lastComponent:void 0}],h=this.extractCommon(m[0],n,t,0,r);if(m[0].oldPos+1>=f&&h+1>=a)return s(this.buildValues(m[0].lastComponent,n,t));let w=-1/0,D=1/0,b=p(()=>{for(let E=Math.max(w,-c);E<=Math.min(D,c);E+=2){let I,P=m[E-1],O=m[E+1];P&&(m[E-1]=void 0);let V=!1;if(O){let ae=O.oldPos-E;V=O&&0<=ae&&ae<a}let H=P&&P.oldPos+1<f;if(!V&&!H){m[E]=void 0;continue}if(!H||V&&P.oldPos<O.oldPos?I=this.addToPath(O,!0,!1,0,r):I=this.addToPath(P,!1,!0,1,r),h=this.extractCommon(I,n,t,E,r),I.oldPos+1>=f&&h+1>=a)return s(this.buildValues(I.lastComponent,n,t))||!0;m[E]=I,I.oldPos+1>=f&&(D=Math.min(D,E-1)),h+1>=a&&(w=Math.max(w,E+1))}c++},"execEditLength");if(i)p(function E(){setTimeout(function(){if(c>u||Date.now()>g)return i(void 0);b()||E()},0)},"exec")();else for(;c<=u&&Date.now()<=g;){let E=b();if(E)return E}}addToPath(t,n,r,i,o){let s=t.lastComponent;return s&&!o.oneChangePerToken&&s.added===n&&s.removed===r?{oldPos:t.oldPos+i,lastComponent:{count:s.count+1,added:n,removed:r,previousComponent:s.previousComponent}}:{oldPos:t.oldPos+i,lastComponent:{count:1,added:n,removed:r,previousComponent:s}}}extractCommon(t,n,r,i,o){let s=n.length,a=r.length,f=t.oldPos,c=f-i,u=0;for(;c+1<s&&f+1<a&&this.equals(r[f+1],n[c+1],o);)c++,f++,u++,o.oneChangePerToken&&(t.lastComponent={count:1,previousComponent:t.lastComponent,added:!1,removed:!1});return u&&!o.oneChangePerToken&&(t.lastComponent={count:u,previousComponent:t.lastComponent,added:!1,removed:!1}),t.oldPos=f,c}equals(t,n,r){return r.comparator?r.comparator(t,n):t===n||!!r.ignoreCase&&t.toLowerCase()===n.toLowerCase()}removeEmpty(t){let n=[];for(let r=0;r<t.length;r++)t[r]&&n.push(t[r]);return n}castInput(t,n){return t}tokenize(t,n){return Array.from(t)}join(t){return t.join("")}postProcess(t,n){return t}get useLongestToken(){return!1}buildValues(t,n,r){let i=[],o;for(;t;)i.push(t),o=t.previousComponent,delete t.previousComponent,t=o;i.reverse();let s=i.length,a=0,f=0,c=0;for(;a<s;a++){let u=i[a];if(u.removed)u.value=this.join(r.slice(c,c+u.count)),c+=u.count;else{if(!u.added&&this.useLongestToken){let l=n.slice(f,f+u.count);l=l.map(function(g,m){let h=r[c+m];return h.length>g.length?h:g}),u.value=this.join(l)}else u.value=this.join(n.slice(f,f+u.count));f+=u.count,u.added||(c+=u.count)}}return i}};var Mn=class extends bt{static{p(this,"LineDiff")}constructor(){super(...arguments),this.tokenize=Do}equals(t,n,r){return r.ignoreWhitespace?((!r.newlineIsToken||!t.includes(`
22
+ `))&&(t=t.trim()),(!r.newlineIsToken||!n.includes(`
23
+ `))&&(n=n.trim())):r.ignoreNewlineAtEof&&!r.newlineIsToken&&(t.endsWith(`
24
+ `)&&(t=t.slice(0,-1)),n.endsWith(`
25
+ `)&&(n=n.slice(0,-1))),super.equals(t,n,r)}},jr=new Mn;function Ht(e,t,n){return jr.diff(e,t,n)}p(Ht,"diffLines");function Do(e,t){t.stripTrailingCr&&(e=e.replace(/\r\n/g,`
26
+ `));let n=[],r=e.split(/(\n|\r\n)/);r[r.length-1]||r.pop();for(let i=0;i<r.length;i++){let o=r[i];i%2&&!t.newlineIsToken?n[n.length-1]+=o:n.push(o)}return n}p(Do,"tokenize");function xt(e,t,n,r,i,o,s){let a;s?typeof s=="function"?a={callback:s}:a=s:a={},typeof a.context>"u"&&(a.context=4);let f=a.context;if(a.newlineIsToken)throw new Error("newlineIsToken may not be used with patch-generation functions, only with diffing functions");if(a.callback){let{callback:u}=a;Ht(n,r,Object.assign(Object.assign({},a),{callback:p(l=>{let g=c(l);u(g)},"callback")}))}else return c(Ht(n,r,a));function c(u){if(!u)return;u.push({value:"",lines:[]});function l(E){return E.map(function(I){return" "+I})}p(l,"contextLines");let g=[],m=0,h=0,w=[],D=1,b=1;for(let E=0;E<u.length;E++){let I=u[E],P=I.lines||ko(I.value);if(I.lines=P,I.added||I.removed){if(!m){let O=u[E-1];m=D,h=b,O&&(w=f>0?l(O.lines.slice(-f)):[],m-=w.length,h-=w.length)}for(let O of P)w.push((I.added?"+":"-")+O);I.added?b+=P.length:D+=P.length}else{if(m)if(P.length<=f*2&&E<u.length-2)for(let O of l(P))w.push(O);else{let O=Math.min(P.length,f);for(let H of l(P.slice(0,O)))w.push(H);let V={oldStart:m,oldLines:D-m+O,newStart:h,newLines:b-h+O,lines:w};g.push(V),m=0,h=0,w=[]}D+=P.length,b+=P.length}}for(let E of g)for(let I=0;I<E.lines.length;I++)E.lines[I].endsWith(`
27
+ `)?E.lines[I]=E.lines[I].slice(0,-1):(E.lines.splice(I+1,0,"\"),I++);return{oldFileName:e,newFileName:t,oldHeader:i,newHeader:o,hunks:g}}p(c,"diffLinesResultToPatch")}p(xt,"structuredPatch");function ut(e){if(Array.isArray(e))return e.map(ut).join(`
28
+ `);let t=[];e.oldFileName==e.newFileName&&t.push("Index: "+e.oldFileName),t.push("==================================================================="),t.push("--- "+e.oldFileName+(typeof e.oldHeader>"u"?"":" "+e.oldHeader)),t.push("+++ "+e.newFileName+(typeof e.newHeader>"u"?"":" "+e.newHeader));for(let n=0;n<e.hunks.length;n++){let r=e.hunks[n];r.oldLines===0&&(r.oldStart-=1),r.newLines===0&&(r.newStart-=1),t.push("@@ -"+r.oldStart+","+r.oldLines+" +"+r.newStart+","+r.newLines+" @@");for(let i of r.lines)t.push(i)}return t.join(`
29
+ `)+`
30
+ `}p(ut,"formatPatch");function So(e,t,n,r,i,o,s){if(typeof s=="function"&&(s={callback:s}),s?.callback){let{callback:a}=s;xt(e,t,n,r,i,o,Object.assign(Object.assign({},s),{callback:p(f=>{a(f?ut(f):void 0)},"callback")}))}else{let a=xt(e,t,n,r,i,o,s);return a?ut(a):void 0}}p(So,"createTwoFilesPatch");function ko(e){let t=e.endsWith(`
31
+ `),n=e.split(`
32
+ `).map(r=>r+`
33
+ `);return t?n.pop():n.push(n.pop().slice(0,-1)),n}p(ko,"splitLines");import pe from"path";var Eo=S.Struct({hash:S.String,files:S.mutable(S.Array(S.String))}),bo=zn,Ar="7.days",xo=2*1024*1024,et=["-c","core.longpaths=true","-c","core.symlinks=true"],Ge=["-c","core.autocrlf=false",...et],Ye=[...Ge,"-c","core.quotepath=false"],pt=class extends Fe.Service()("@opencode/Snapshot"){static{p(this,"Service")}},Po=De.effect(pt,d.gen(function*(){let e=yield*ot.Service,t=yield*on.Service,n=yield*ln.Service,r=new Map,i=p(s=>{let a=r.get(s);if(a)return a;let f=Fn.makeUnsafe(1);return r.set(s,f),f},"lock"),o=yield*$.make(d.fn("Snapshot.state")(function*(s){let a={directory:s.directory,worktree:s.worktree,gitdir:pe.join(it.Path.data,"snapshot",s.project.id,Un.fast(s.worktree)),vcs:s.project.vcs},f=p(k=>["--git-dir",a.gitdir,"--work-tree",a.worktree,...k],"args"),c=p(k=>k.join("\0")+"\0","encodeNulTerminatedPaths"),u=p(k=>c(k.map(_=>`:(top,literal)${_}`)),"encodeTopLevelLiteralPathspecs"),l=d.fnUntraced(function*(k,_){let y=yield*t.run(Yt.make("git",k,{cwd:_?.cwd,env:_?.env,extendEnv:!0}),{stdin:_?.stdin});return{code:Kt.ExitCode(y.exitCode),text:y.stdout.toString("utf8"),stderr:y.stderr.toString("utf8")}},d.catch(k=>d.succeed({code:Kt.ExitCode(1),text:"",stderr:k instanceof Error?k.message:String(k)}))),g=d.fnUntraced(function*(k){if(!k.length)return new Set;let _=k.map(x=>x.startsWith(":")?`./${x}`:x),y=yield*l([...Ye,"--git-dir",pe.join(a.worktree,".git"),"--work-tree",a.worktree,"check-ignore","--no-index","--stdin","-z"],{cwd:a.worktree,stdin:c(_)});return y.code!==0&&y.code!==1?new Set:new Set(y.text.split("\0").filter(Boolean).map(x=>x.startsWith("./:")?x.slice(2):x))}),m=d.fnUntraced(function*(k){k.length&&(yield*l([...Ge,...f(["rm","--cached","-f","--ignore-unmatch","--pathspec-from-file=-","--pathspec-file-nul"])],{cwd:a.worktree,stdin:u(k)}))}),h=d.fnUntraced(function*(k){if(!k.length)return;let _=yield*l([...Ge,...f(["add","--all","--sparse","--pathspec-from-file=-","--pathspec-file-nul"])],{cwd:a.worktree,stdin:u(k)});_.code!==0&&(yield*d.logWarning("failed to add snapshot files",{exitCode:_.code,stderr:_.stderr}))}),w=p(k=>e.exists(k).pipe(d.orDie),"exists"),D=p(k=>e.readFileString(k).pipe(d.catch(()=>d.succeed(""))),"read"),b=p(k=>e.remove(k).pipe(d.catch(()=>d.void)),"remove"),E=p(k=>i(a.gitdir).withPermits(1)(k),"locked"),I=d.fnUntraced(function*(){return a.vcs!=="git"?!1:(yield*n.get()).snapshot!==!1}),P=d.fnUntraced(function*(){let _=(yield*l(["rev-parse","--path-format=absolute","--git-path","info/exclude"],{cwd:a.worktree})).text.trim();if(_&&(yield*w(_)))return _}),O=d.fnUntraced(function*(k=[]){let _=yield*P(),y=pe.join(a.gitdir,"info","exclude"),x=[_?(yield*D(_)).trimEnd():"",...k.map(C=>`/${C.replaceAll("\\","/")}`)].filter(Boolean).join(`
34
+ `);yield*e.ensureDir(pe.join(a.gitdir,"info")).pipe(d.orDie),yield*e.writeFileString(y,x?`${x}
35
+ `:"").pipe(d.orDie)}),V=d.fnUntraced(function*(){if(a.vcs!=="git")return;let k=yield*l(["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:a.worktree});if(k.code!==0)return;let _=k.text.trim();if(!_||!(yield*w(_)))return;let y=pe.join(_,"objects"),x=(yield*D(pe.join(y,"info","alternates"))).split(`
36
+ `).map(N=>N.trim()).filter(Boolean),C=[];for(let N of[y,...x])(yield*w(N))&&C.push(N);if(!C.length)return;yield*e.ensureDir(pe.join(a.gitdir,"objects","info")).pipe(d.orDie),yield*e.writeFileString(pe.join(a.gitdir,"objects","info","alternates"),C.join(`
37
+ `)+`
38
+ `).pipe(d.orDie);let J=pe.join(_,"index");(yield*w(J))&&(yield*e.copyFile(J,pe.join(a.gitdir,"index")).pipe(d.catch(()=>d.void)))}),H=d.fnUntraced(function*(){yield*O();let[k,_]=yield*d.all([l([...Ye,...f(["diff-files","--name-only","-z","--","."])],{cwd:a.directory}),l([...Ye,...f(["ls-files","--full-name","--others","--exclude-standard","-z","--","."])],{cwd:a.directory})],{concurrency:2});if(k.code!==0||_.code!==0){yield*d.logWarning("failed to list snapshot files",{diffCode:k.code,diffStderr:k.stderr,otherCode:_.code,otherStderr:_.stderr});return}let y=k.text.split("\0").filter(Boolean),x=_.text.split("\0").filter(Boolean),C=Array.from(new Set([...y,...x]));if(!C.length)return;let J=yield*g(C);if(J.size>0){let B=Array.from(J);yield*d.logInfo("removing gitignored files from snapshot",{count:B.length}),yield*m(B)}let N=C.filter(B=>!J.has(B));if(!N.length)return;let F=new Set((yield*d.all(N.map(B=>e.stat(pe.join(a.worktree,B)).pipe(d.catch(()=>d.void)).pipe(d.map(Q=>!Q||Q.type!=="File"?void 0:(typeof Q.size=="bigint"?Number(Q.size):Q.size)>xo?B:void 0))),{concurrency:8})).filter(B=>!!B)),A=new Set(x.filter(B=>F.has(B)));yield*O(Array.from(A)),yield*h(N.filter(B=>!A.has(B)))}),ae=d.fnUntraced(function*(){return yield*E(d.gen(function*(){if(!(yield*I())||!(yield*w(a.gitdir)))return;let k=yield*l(f(["gc",`--prune=${Ar}`]),{cwd:a.directory});if(k.code!==0){yield*d.logWarning("cleanup failed",{exitCode:k.code,stderr:k.stderr});return}yield*d.logInfo("cleanup",{prune:Ar})}))}),he=d.fnUntraced(function*(){return yield*E(d.gen(function*(){if(!(yield*I()))return;let k=yield*w(a.gitdir);yield*e.ensureDir(a.gitdir).pipe(d.orDie),k||(yield*l(["init"],{env:{GIT_DIR:a.gitdir,GIT_WORK_TREE:a.worktree}}),yield*l(["--git-dir",a.gitdir,"config","core.autocrlf","false"]),yield*l(["--git-dir",a.gitdir,"config","core.longpaths","true"]),yield*l(["--git-dir",a.gitdir,"config","core.symlinks","true"]),yield*l(["--git-dir",a.gitdir,"config","core.fsmonitor","false"]),yield*l(["--git-dir",a.gitdir,"config","feature.manyFiles","true"]),yield*l(["--git-dir",a.gitdir,"config","index.version","4"]),yield*l(["--git-dir",a.gitdir,"config","index.threads","true"]),yield*l(["--git-dir",a.gitdir,"config","core.untrackedCache","true"]),yield*V(),yield*d.logInfo("initialized")),yield*H();let y=(yield*l(f(["write-tree"]),{cwd:a.directory})).text.trim();return yield*d.logInfo("tracking",{hash:y,cwd:a.directory,git:a.gitdir}),y}))}),ne=d.fnUntraced(function*(k){return yield*E(d.gen(function*(){yield*H();let _=yield*l([...Ye,...f(["diff","--cached","--no-ext-diff","--name-only",k,"--","."])],{cwd:a.directory});if(_.code!==0)return yield*d.logWarning("failed to get diff",{hash:k,exitCode:_.code}),{hash:k,files:[]};let y=_.text.trim().split(`
39
+ `).map(C=>C.trim()).filter(Boolean),x=yield*g(y);return{hash:k,files:y.filter(C=>!x.has(C)).map(C=>pe.join(a.worktree,C).replaceAll("\\","/"))}}))}),re=p(()=>{if(!$n.allows(a.worktree))return new Error(`snapshot restore refused: ${a.worktree} is the user's project folder. Nothing was written.`)},"assertRestorable"),Ce=d.fnUntraced(function*(k){let _=re();return _?(yield*d.logError("refused to restore a snapshot in the user's project folder",{worktree:a.worktree}),yield*d.die(_)):yield*E(d.gen(function*(){yield*d.logInfo("restore",{commit:k});let y=yield*l([...et,...f(["read-tree",k])],{cwd:a.worktree});if(y.code===0){let x=yield*l([...et,...f(["checkout-index","-a","-f"])],{cwd:a.worktree});if(x.code===0)return;yield*d.logError("failed to restore snapshot",{snapshot:k,exitCode:x.code,stderr:x.stderr});return}yield*d.logError("failed to restore snapshot",{snapshot:k,exitCode:y.code,stderr:y.stderr})}))}),Pe=d.fnUntraced(function*(k){let _=re();return _?yield*d.die(_):yield*E(d.gen(function*(){let y=[],x=new Set;for(let N of k)for(let F of N.files)x.has(F)||(x.add(F),y.push({hash:N.hash,file:F,rel:pe.relative(a.worktree,F).replaceAll("\\","/")}));let C=d.fnUntraced(function*(N){if(yield*d.logInfo("reverting",{file:N.file,hash:N.hash}),(yield*l([...et,...f(["checkout",N.hash,"--",N.file])],{cwd:a.worktree})).code===0)return;let A=yield*l([...et,...f(["ls-tree",N.hash,"--",N.rel])],{cwd:a.worktree});if(A.code===0&&A.text.trim()){yield*d.logInfo("file existed in snapshot but checkout failed, keeping",{file:N.file,hash:N.hash});return}yield*d.logInfo("file did not exist in snapshot, deleting",{file:N.file,hash:N.hash}),yield*b(N.file)}),J=p((N,F)=>N===F||N.startsWith(`${F}/`)||F.startsWith(`${N}/`),"clash");for(let N=0;N<y.length;){let F=y[N],A=[F],B=N+1;for(;B<y.length&&A.length<100;){let R=y[B];if(R.hash!==F.hash||A.some(z=>J(z.rel,R.rel)))break;A.push(R),B+=1}if(A.length===1){yield*C(F),N=B;continue}let Q=yield*l([...et,...f(["ls-tree","--name-only",F.hash,"--",...A.map(R=>R.rel)])],{cwd:a.worktree});if(Q.code!==0){yield*d.logInfo("batched ls-tree failed, falling back to single-file revert",{hash:F.hash,files:A.length});for(let R of A)yield*C(R);N=B;continue}let Re=new Set(Q.text.trim().split(`
40
+ `).map(R=>R.trim()).filter(Boolean)),L=A.filter(R=>Re.has(R.rel));if(L.length&&(yield*d.logInfo("reverting",{hash:F.hash,files:L.length}),(yield*l([...et,...f(["checkout",F.hash,"--",...L.map(z=>z.file)])],{cwd:a.worktree})).code!==0)){yield*d.logInfo("batched checkout failed, falling back to single-file revert",{hash:F.hash,files:L.length});for(let z of A)yield*C(z);N=B;continue}for(let R of A)Re.has(R.rel)||(yield*d.logInfo("file did not exist in snapshot, deleting",{file:R.file,hash:R.hash}),yield*b(R.file));N=B}}))}),He=d.fnUntraced(function*(k){return yield*E(d.gen(function*(){yield*H();let _=yield*l([...Ye,...f(["diff","--cached","--no-ext-diff",k,"--","."])],{cwd:a.worktree});return _.code!==0?(yield*d.logWarning("failed to get diff",{hash:k,exitCode:_.code,stderr:_.stderr}),""):_.text.trim()}))}),Z=d.fnUntraced(function*(k,_){return yield*E(d.gen(function*(){let y=d.fnUntraced(function*(L){return L.binary?["",""]:L.status==="added"?["",yield*l([...Ge,...f(["show",`${_}:${L.file}`])]).pipe(d.map(R=>R.text))]:L.status==="deleted"?[yield*l([...Ge,...f(["show",`${k}:${L.file}`])]).pipe(d.map(R=>R.text)),""]:yield*d.all([l([...Ge,...f(["show",`${k}:${L.file}`])]).pipe(d.map(R=>R.text)),l([...Ge,...f(["show",`${_}:${L.file}`])]).pipe(d.map(R=>R.text))],{concurrency:2})}),x=d.fnUntraced(function*(L){let R=L.flatMap(X=>X.binary?[]:X.status==="added"?[{file:X.file,side:"after",ref:`${_}:${X.file}`}]:X.status==="deleted"?[{file:X.file,side:"before",ref:`${k}:${X.file}`}]:[{file:X.file,side:"before",ref:`${k}:${X.file}`},{file:X.file,side:"after",ref:`${_}:${X.file}`}]);if(!R.length)return new Map;let z=yield*t.run(Yt.make("git",[...Ge,...f(["cat-file","--batch"])],{cwd:a.directory,extendEnv:!0}),{stdin:R.map(X=>X.ref).join(`
41
+ `)+`
42
+ `});if(z.exitCode!==0){yield*d.logInfo("git cat-file --batch failed during snapshot diff, falling back to per-file git show",{stderr:z.stderr.toString("utf8"),refs:R.length});return}let W=z.stdout,ye=p((X,Qe)=>{},"fail"),Ne=new Map,Ze=new TextDecoder,Me=0;for(let X of R){let Qe=Me;for(;Qe<W.length&&W[Qe]!==10;)Qe+=1;if(Qe>=W.length)return ye("git cat-file --batch returned a truncated header during snapshot diff, falling back to per-file git show");let _t=Ze.decode(W.slice(Me,Qe));Me=Qe+1;let Tt=Ne.get(X.file)??{before:"",after:""};if(_t.endsWith(" missing")){Ne.set(X.file,Tt);continue}let Rn=_t.match(/^[0-9a-f]+ blob (\d+)$/);if(!Rn)return ye("git cat-file --batch returned an unexpected header during snapshot diff, falling back to per-file git show",{head:_t});let nt=Number(Rn[1]);if(!Number.isInteger(nt)||nt<0||Me+nt>=W.length||W[Me+nt]!==10)return ye("git cat-file --batch returned truncated content during snapshot diff, falling back to per-file git show",{head:_t});let jn=Ze.decode(W.slice(Me,Me+nt));X.side==="before"&&(Tt.before=jn),X.side==="after"&&(Tt.after=jn),Ne.set(X.file,Tt),Me+=nt+1}return Me!==W.length?ye("git cat-file --batch returned trailing data during snapshot diff, falling back to per-file git show"):Ne},d.scoped,d.catch(()=>d.succeed(void 0))),C=[],J=new Map,N=yield*l([...Ye,...f(["diff","--no-ext-diff","--name-status","--no-renames",k,_,"--","."])],{cwd:a.directory});for(let L of N.text.trim().split(`
43
+ `)){if(!L)continue;let[R,z]=L.split(" ");!R||!z||J.set(z,R.startsWith("A")?"added":R.startsWith("D")?"deleted":"modified")}let A=(yield*l([...Ye,...f(["diff","--no-ext-diff","--no-renames","--numstat",k,_,"--","."])],{cwd:a.directory})).text.trim().split(`
44
+ `).filter(Boolean).flatMap(L=>{let[R,z,W]=L.split(" ");if(!W)return[];let ye=R==="-"&&z==="-",Ne=ye?0:parseInt(R),Ze=ye?0:parseInt(z);return[{file:W,status:J.get(W)??"modified",binary:ye,additions:Number.isFinite(Ne)?Ne:0,deletions:Number.isFinite(Ze)?Ze:0}]}),B=yield*g(A.map(L=>L.file));if(B.size>0){let L=A.filter(R=>!B.has(R.file));A.length=0,A.push(...L)}let Q=100,Re=p((L,R,z)=>ut(xt(L,L,R,z,"","",{context:Number.MAX_SAFE_INTEGER})),"patch");for(let L=0;L<A.length;L+=Q){let R=A.slice(L,L+Q),z=yield*x(R);for(let W of R){let ye=z?.get(W.file)??{before:"",after:""},[Ne,Ze]=W.binary?["",""]:z?[ye.before,ye.after]:yield*y(W);C.push({file:W.file,patch:W.binary?"":Re(W.file,Ne,Ze),additions:W.additions,deletions:W.deletions,status:W.status})}}return C}))});return yield*ae().pipe(d.catchCause(k=>d.logError("cleanup loop failed",{cause:ht.pretty(k)})),d.repeat(An.spaced(Qt.hours(1))),d.delay(Qt.minutes(1)),d.forkScoped),{cleanup:ae,track:he,patch:ne,restore:Ce,revert:Pe,diff:He,diffFull:Z}}));return pt.of({init:d.fn("Snapshot.init")(function*(){yield*$.get(o)}),cleanup:d.fn("Snapshot.cleanup")(function*(){return yield*$.useEffect(o,s=>s.cleanup())}),track:d.fn("Snapshot.track")(function*(){return yield*$.useEffect(o,s=>s.track())}),patch:d.fn("Snapshot.patch")(function*(s){return yield*$.useEffect(o,a=>a.patch(s))}),restore:d.fn("Snapshot.restore")(function*(s){return yield*$.useEffect(o,a=>a.restore(s))}),revert:d.fn("Snapshot.revert")(function*(s){return yield*$.useEffect(o,a=>a.revert(s))}),diff:d.fn("Snapshot.diff")(function*(s){return yield*$.useEffect(o,a=>a.diff(s))}),diffFull:d.fn("Snapshot.diffFull")(function*(s,a){return yield*$.useEffect(o,f=>f.diffFull(s,a))})})})),No=Se.make({service:pt,layer:Po,deps:[ot.node,on.node,ln.node]});var Or="New session - ",Lr="Child session - ";function Mo(e){return new RegExp(`^(${Or}|${Lr})\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$`).test(e)}p(Mo,"isDefaultTitle");function Mt(e){let t=e.summary_additions!==null||e.summary_deletions!==null||e.summary_files!==null?{additions:e.summary_additions??0,deletions:e.summary_deletions??0,files:e.summary_files??0,diffs:e.summary_diffs??void 0}:void 0,n=e.share_url?{url:e.share_url}:void 0,r=e.revert?{messageID:Ve.make(e.revert.messageID),partID:e.revert.partID?Jt.make(e.revert.partID):void 0,snapshot:e.revert.snapshot,diff:e.revert.diff}:void 0;return{id:e.id,slug:e.slug,projectID:e.project_id,workspaceID:e.workspace_id??void 0,directory:e.directory,path:e.path??void 0,parentID:e.parent_id??void 0,title:e.title,agent:e.agent??void 0,model:e.model?{id:nn.ID.make(e.model.id),providerID:tn.ID.make(e.model.providerID),variant:e.model.variant}:void 0,version:e.version,summary:t,cost:e.cost,tokens:{input:e.tokens_input,output:e.tokens_output,reasoning:e.tokens_reasoning,cache:{read:e.tokens_cache_read,write:e.tokens_cache_write}},share:n,metadata:e.metadata??void 0,revert:r,permission:e.permission?[...e.permission]:void 0,time:{created:e.time_created,updated:e.time_updated,compacting:e.time_compacting??void 0,archived:e.time_archived??void 0}}}p(Mt,"fromRow");function _o(e){return{id:e.id,project_id:e.projectID,workspace_id:e.workspaceID,parent_id:e.parentID,slug:e.slug,directory:e.directory,path:e.path,title:e.title,agent:e.agent,model:e.model,version:e.version,share_url:e.share?.url,summary_additions:e.summary?.additions,summary_deletions:e.summary?.deletions,summary_files:e.summary?.files,summary_diffs:e.summary?.diffs,metadata:e.metadata,cost:e.cost??0,tokens_input:(e.tokens??mt).input,tokens_output:(e.tokens??mt).output,tokens_reasoning:(e.tokens??mt).reasoning,tokens_cache_read:(e.tokens??mt).cache.read,tokens_cache_write:(e.tokens??mt).cache.write,revert:e.revert?{messageID:Jn.ID.make(e.revert.messageID),partID:e.revert.partID,snapshot:e.revert.snapshot,diff:e.revert.diff}:null,permission:e.permission,time_created:e.time.created,time_updated:e.time.updated,time_compacting:e.time.compacting,time_archived:e.time.archived}}p(_o,"toRow");function To(e){let t=e.match(/^(.+) \(fork #(\d+)\)$/);if(t){let n=t[1],r=parseInt(t[2],10);return`${n} (fork #${r+1})`}return`${e} (fork #1)`}p(To,"getForkedTitle");function Fr(e,t){return Nt.relative(Nt.resolve(e),t).replaceAll("\\","/")}p(Fr,"sessionPath");var Br=S.Struct({additions:S.Finite,deletions:S.Finite,files:S.Finite,diffs:G(S.Array(Pt.FileDiff))}),Co=S.Struct({input:S.Finite,output:S.Finite,reasoning:S.Finite,cache:S.Struct({read:S.Finite,write:S.Finite})}),mt={input:0,output:0,reasoning:0,cache:{read:0,write:0}},Ro=S.Struct({url:S.String}),Tn=S.Finite,jo=S.Struct({created:Oe,updated:Oe,compacting:G(Oe),archived:G(Tn)}),Ur=S.Struct({messageID:Ve,partID:G(Jt),snapshot:G(S.String),diff:G(S.String)}),Wr=S.Struct({id:nn.ID,providerID:tn.ID,variant:G(S.String)}),Zt=S.Record(S.String,S.Any),$r=S.Struct({id:se,slug:S.String,projectID:sn.ID,workspaceID:G(an.ID),directory:S.String,path:G(S.String),parentID:G(se),summary:G(Br),cost:G(S.Finite),tokens:G(Co),share:G(Ro),title:S.String,agent:G(S.String),model:G(Wr),version:S.String,metadata:G(Zt),time:jo,permission:G(Ft.Ruleset),revert:G(Ur)}).annotate({identifier:"Session"}),qr=S.Struct({id:sn.ID,name:G(S.String),worktree:S.String}).annotate({identifier:"ProjectSummary"}),Ao=S.Struct({...$r.fields,project:S.NullOr(qr)}).annotate({identifier:"GlobalSession"}),Fo=S.optional(S.Struct({parentID:S.optional(se),title:S.optional(S.String),agent:S.optional(S.String),model:S.optional(Wr),metadata:S.optional(Zt),permission:S.optional(Ft.Ruleset),workspaceID:S.optional(an.ID)})),Oo=S.Struct({sessionID:se,messageID:S.optional(Ve)}),Lo=se,Bo=se,Uo=se,Wo=S.Struct({sessionID:se,title:S.String}),$o=S.Struct({sessionID:se,time:S.optional(Tn)}),qo=S.Struct({sessionID:se,metadata:Zt}),Vo=S.Struct({sessionID:se,permission:Ft.Ruleset}),Jo=S.Struct({sessionID:se,revert:S.optional(Ur),summary:S.optional(Br)}),zo=S.Struct({sessionID:se,limit:S.optional(Oe)}),Go={Created:Y.Event.Created,Updated:Y.Event.Updated,Deleted:Y.Event.Deleted,Diff:Y.Event.Diff,Error:Y.Event.Error};function Ho(e,t){let n=t.project.vcs?Nt.join(t.worktree,".opencode","plans"):Nt.join(it.Path.data,"plans");return Nt.join(n,[e.time.created,e.slug].join("-")+".md")}p(Ho,"plan");var Zo=p(e=>{let t=p(D=>Number.isFinite(D)?D:0,"finite"),n=p(D=>Math.max(0,t(D)),"safe"),r=n(e.usage.inputTokens??0),i=n(e.usage.outputTokens??0),o=n(e.usage.reasoningTokens??0),s=n(e.usage.cacheReadInputTokens??0),a=n(Number(e.usage.cacheWriteInputTokens??e.metadata?.anthropic?.cacheCreationInputTokens??e.metadata?.vertex?.cacheCreationInputTokens??e.metadata?.bedrock?.usage?.cacheWriteInputTokens??e.metadata?.venice?.usage?.cacheCreationInputTokens??0)),f=n(r-s-a),u={total:e.usage.totalTokens,input:f,output:n(i-o),reasoning:o,cache:{write:a,read:s}},l=(e.metadata?.anthropic??e.metadata?.vertex)?.usage,g=Math.min(a,n(Number(l?.cache_creation?.ephemeral_1h_input_tokens??0))),m=r,h=e.model.cost?.tiers?.filter(D=>D.tier.type==="context"&&m>D.tier.size).sort((D,b)=>b.tier.size-D.tier.size)[0]??(e.model.cost?.experimentalOver200K&&m>2e5?e.model.cost.experimentalOver200K:e.model.cost),w=e.metadata?.copilot?.totalNanoAiu;return{cost:typeof w=="number"&&Number.isFinite(w)&&w>=0?new ue(w).div(1e11).toNumber():n(new ue(0).add(new ue(u.input).mul(t(h?.input??0)).div(1e6)).add(new ue(u.output).mul(t(h?.output??0)).div(1e6)).add(new ue(u.cache.read).mul(t(h?.cache?.read??0)).div(1e6)).add(new ue(u.cache.write-g).mul(t(h?.cache?.write??0)).div(1e6)).add(new ue(g).mul(t(h?.input??0)*2).div(1e6)).add(new ue(u.reasoning).mul(t(h?.output??0)).div(1e6)).toNumber()),tokens:u}},"getUsage"),_n=class extends S.TaggedErrorClass()("SessionBusyError",{sessionID:se}){static{p(this,"BusyError")}},tt=class extends Fe.Service()("@opencode/Session"){static{p(this,"Service")}},Qo=qn(tt),Xo=De.effect(tt,d.gen(function*(){let{db:e}=yield*me.Service,t=yield*me.Service,n=yield*at.Service,r=yield*pn.Service,i=yield*gn.Service,o=d.fn("Session.createNext")(function*(y){let x=yield*$.context,C={id:se.descending(y.id),slug:Zn.create(),version:Wn,projectID:x.project.id,directory:y.directory,path:y.path,workspaceID:y.workspaceID,parentID:y.parentID,title:y.title??(y.parentID?Lr:Or)+new Date().toISOString(),agent:y.agent,model:y.model,metadata:y.metadata,permission:y.permission?[...y.permission]:void 0,cost:0,tokens:mt,time:{created:Date.now(),updated:Date.now()}};return yield*d.logInfo("created",C),yield*r.publish(Y.Event.Created,{sessionID:C.id,info:C}),C}),s=d.fn("Session.get")(function*(y){let x=yield*e.select().from(U).where(K(U.id,y)).get().pipe(d.orDie);return x?Mt(x):yield*d.fail(new xe({message:`Session not found: ${y}`}))}),a=d.fn("Session.list")(function*(y){let x=yield*$.context;return yield*Yo(e,{projectID:x.project.id,experimentalWorkspaces:i.experimentalWorkspaces,...y})}),f=d.fn("Session.listGlobal")(function*(y){let x=[];y?.directory&&x.push(K(U.directory,y.directory)),y?.roots&&x.push(wt(U.parent_id)),y?.start&&x.push(rn(U.time_updated,y.start)),y?.cursor&&x.push(It(U.time_updated,y.cursor)),y?.search&&x.push(jt(U.title,`%${y.search}%`)),y?.archived||x.push(wt(U.time_archived));let J=yield*(x.length>0?e.select().from(U).where(ke(...x)):e.select().from(U)).orderBy(Xe(U.time_updated),Xe(U.id)).limit(y?.limit??100).all().pipe(d.orDie),N=[...new Set(J.map(A=>A.project_id))],F=new Map;if(N.length>0){let A=yield*e.select({id:st.id,name:st.name,worktree:st.worktree}).from(st).where(Rt(st.id,N)).all().pipe(d.orDie);for(let B of A)F.set(B.id,{id:B.id,name:B.name??void 0,worktree:B.worktree})}return J.map(A=>({...Mt(A),project:F.get(A.project_id)??null}))}),c=d.fn("Session.children")(function*(y){return(yield*e.select().from(U).where(ke(K(U.parent_id,y))).all().pipe(d.orDie)).map(Mt)}),u=d.fnUntraced(function*(y){let x=yield*s(y);try{(yield*$.directory.pipe(d.as(!0),d.catchCause(()=>d.succeed(!1))))&&(yield*Ko(n,y));let J=yield*c(y);for(let N of J)yield*u(N.id);yield*r.publish(Y.Event.Deleted,{sessionID:y,info:x}),yield*r.remove(y)}catch(C){yield*d.logError("failed to remove session",{sessionID:y,error:C})}}),l=p(y=>d.gen(function*(){return yield*r.publish(Y.Event.MessageUpdated,{sessionID:y.sessionID,info:y}),y}).pipe(d.withSpan("Session.updateMessage")),"updateMessage"),g=p(y=>d.gen(function*(){return yield*r.publish(Y.Event.PartUpdated,{sessionID:y.sessionID,part:structuredClone(y),time:Date.now()}),y}).pipe(d.withSpan("Session.updatePart")),"updatePart"),m=d.fn("Session.getPart")(function*(y){let x=yield*e.select().from(le).where(ke(K(le.session_id,y.sessionID),K(le.message_id,y.messageID),K(le.id,y.partID))).get().pipe(d.orDie);if(x)return{...x.data,id:x.id,sessionID:x.session_id,messageID:x.message_id}}),h=d.fn("Session.create")(function*(y){let x=yield*$.context,C=yield*$.workspaceID;return yield*o({parentID:y?.parentID,directory:x.directory,path:Fr(x.worktree,x.directory),title:y?.title,agent:y?.agent,model:y?.model,metadata:y?.metadata,permission:y?.permission,workspaceID:y?.workspaceID??C})}),w=d.fn("Session.fork")(function*(y){let x=yield*$.context,C=yield*s(y.sessionID),J=To(C.title),N=yield*o({directory:x.directory,path:Fr(x.worktree,x.directory),workspaceID:C.workspaceID,title:J,metadata:structuredClone(C.metadata)}),F=yield*Pe({sessionID:y.sessionID}),A=new Map,B=y.messageID?F.findIndex(Q=>Q.info.id===y.messageID):F.length;for(let Q of F.slice(0,B<0?F.length:B)){let Re=Ve.ascending();A.set(Q.info.id,Re);let L=Q.info.role==="assistant"&&Q.info.parentID?A.get(Q.info.parentID):void 0,R=yield*l({...Q.info,sessionID:N.id,id:Re,...L&&{parentID:L}});for(let z of Q.parts){let W={...z,id:Jt.ascending(),messageID:R.id,sessionID:N.id};W.type==="compaction"&&W.tail_start_id&&(W.tail_start_id=A.get(W.tail_start_id)),yield*g(W)}}return N}),D=p((y,x)=>d.gen(function*(){let C=yield*s(y),J={...C,...x,time:x.time?{...C.time,...x.time}:C.time,share:x.share===null?void 0:x.share?{...C.share,...x.share}:C.share,summary:x.summary===null?void 0:x.summary??C.summary,revert:x.revert===null?void 0:x.revert??C.revert,permission:x.permission===null?void 0:x.permission??C.permission};yield*r.publish(Y.Event.Updated,{sessionID:y,info:J})}),"patch"),b=d.fn("Session.touch")(function*(y){yield*D(y,{time:{updated:Date.now()}}).pipe(d.orDie)}),E=d.fn("Session.setTitle")(function*(y){yield*D(y.sessionID,{title:y.title}).pipe(d.orDie)}),I=d.fn("Session.setArchived")(function*(y){yield*D(y.sessionID,{time:{archived:y.time}}).pipe(d.orDie)}),P=d.fn("Session.setMetadata")(function*(y){yield*D(y.sessionID,{metadata:y.metadata,time:{updated:Date.now()}}).pipe(d.orDie)}),O=d.fn("Session.setAgentModel")(function*(y){yield*D(y.sessionID,{agent:y.agent,model:y.model,time:{updated:y.time}}).pipe(d.orDie)}),V=d.fn("Session.setPermission")(function*(y){yield*D(y.sessionID,{permission:[...y.permission],time:{updated:Date.now()}}).pipe(d.orDie)}),H=d.fn("Session.setRevert")(function*(y){yield*D(y.sessionID,{summary:y.summary,time:{updated:Date.now()},revert:y.revert}).pipe(d.orDie)}),ae=d.fn("Session.clearRevert")(function*(y){yield*D(y,{time:{updated:Date.now()},revert:null}).pipe(d.orDie)}),he=d.fn("Session.setSummary")(function*(y){yield*D(y.sessionID,{time:{updated:Date.now()},summary:y.summary}).pipe(d.orDie)}),ne=d.fn("Session.setShare")(function*(y){yield*D(y.sessionID,{share:y.share??null,time:{updated:Date.now()}}).pipe(d.orDie)}),re=d.fn("Session.setWorkspace")(function*(y){yield*D(y.sessionID,{workspaceID:y.workspaceID,time:{updated:Date.now()}}).pipe(d.orDie)}),Ce=d.fn("Session.diff")(function*(y){return[]}),Pe=d.fn("Session.messages")(function*(y){if(y.limit)return(yield*ze.page({sessionID:y.sessionID,limit:y.limit}).pipe(d.provideService(me.Service,t))).items;let x=50,C=[],J;for(;;){let N=yield*ze.page({sessionID:y.sessionID,limit:x,before:J}).pipe(d.provideService(me.Service,t));if(N.items.length===0)break;for(let F=N.items.length-1;F>=0;F--){let A=N.items[F];A&&C.push(A)}if(!N.more||!N.cursor)break;J=N.cursor}return C.reverse()}),He=d.fn("Session.removeMessage")(function*(y){return yield*r.publish(Y.Event.MessageRemoved,{sessionID:y.sessionID,messageID:y.messageID}),y.messageID}),Z=d.fn("Session.removePart")(function*(y){return yield*r.publish(Y.Event.PartRemoved,{sessionID:y.sessionID,messageID:y.messageID,partID:y.partID}),y.partID}),k=d.fnUntraced(function*(y){yield*r.publish(ze.Event.PartDelta,y)}),_=d.fn("Session.findMessage")(function*(y,x){let J;for(;;){let N=yield*ze.page({sessionID:y,limit:50,before:J}).pipe(d.provideService(me.Service,t));if(N.items.length===0)break;for(let F=N.items.length-1;F>=0;F--){let A=N.items[F];if(A&&x(A))return Ae.some(A)}if(!N.more||!N.cursor)break;J=N.cursor}return Ae.none()});return tt.of({list:a,listGlobal:f,create:h,fork:w,touch:b,get:s,setTitle:E,setArchived:I,setMetadata:P,setAgentModel:O,setPermission:V,setRevert:H,clearRevert:ae,setSummary:he,setShare:ne,setWorkspace:re,diff:Ce,messages:Pe,children:c,remove:u,updateMessage:l,removeMessage:He,removePart:Z,updatePart:g,getPart:m,updatePartDelta:k,findMessage:_})})),Ko=d.fn("Session.cancelBackgroundJobs")(function*(e,t){let n=yield*e.list();yield*d.forEach(n.filter(r=>r.status!=="running"?!1:r.id===t||r.metadata?.sessionId===t?!0:r.metadata?.parentSessionId===t),r=>e.cancel(r.id),{concurrency:"unbounded",discard:!0})});function Yo(e,t){let n=[K(U.project_id,t.projectID)];if(t.workspaceID&&n.push(K(U.workspace_id,t.workspaceID)),t.path!==void 0){if(t.path){let i=[K(U.path,t.path),jt(U.path,Bn.param(`${t.path}/%`,U.path))];n.push(t.directory?yt(...i,ke(wt(U.path),K(U.directory,t.directory))):yt(...i))}}else t.scope!=="project"&&t.directory&&n.push(K(U.directory,t.directory));t.roots&&n.push(wt(U.parent_id)),t.start&&n.push(rn(U.time_updated,t.start)),t.search&&n.push(jt(U.title,`%${t.search}%`));let r=t.limit??100;return e.select().from(U).where(ke(...n)).orderBy(Xe(U.time_updated)).limit(r).all().pipe(d.orDie,d.map(i=>i.map(Mt)))}p(Yo,"listByProject");var es=Se.make({service:tt,layer:Xo,deps:[at.node,gn.node,me.node,pn.node]});export{Ht as a,xt as b,ut as c,So as d,lt as e,Je as f,at as g,xe as h,kn as i,se as j,Ve as k,Jt as l,co as m,As as n,Fs as o,ze as p,Pt as q,Mo as r,Mt as s,_o as t,Tn as u,Zt as v,$r as w,qr as x,Ao as y,Fo as z,Oo as A,Lo as B,Bo as C,Uo as D,Wo as E,$o as F,qo as G,Vo as H,Jo as I,zo as J,Go as K,Ho as L,Zo as M,_n as N,tt as O,Qo as P,es as Q,Cn as R};
45
+ /*! Bundled license information:
46
+
47
+ decimal.js/decimal.mjs:
48
+ (*!
49
+ * decimal.js v10.5.0
50
+ * An arbitrary-precision Decimal type for JavaScript.
51
+ * https://github.com/MikeMcl/decimal.js
52
+ * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
53
+ * MIT Licence
54
+ *)
55
+ */