@qitqode/qitqode-android-arm64 0.2.3 → 0.2.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.
- package/bundle/{chunk-52w60e1f.js → chunk-03bp59wq.js} +1 -1
- package/bundle/{chunk-083wpv6r.js → chunk-0g7acwt1.js} +1 -1
- package/bundle/{chunk-8mm92zn2.js → chunk-0j5rzaxx.js} +1 -1
- package/bundle/{chunk-fsahzvd5.js → chunk-13rsd5vv.js} +1 -1
- package/bundle/{chunk-xq2kcar4.js → chunk-2b3fn9xv.js} +1 -1
- package/bundle/{chunk-65t9b9eq.js → chunk-2nv1scj9.js} +1 -1
- package/bundle/{chunk-msdypt5f.js → chunk-36xm6mgm.js} +1 -1
- package/bundle/{chunk-0nbteyb0.js → chunk-3akv2xqh.js} +1 -1
- package/bundle/{chunk-nftgx6bz.js → chunk-3cqrz7g1.js} +1 -1
- package/bundle/{chunk-qqxrvyx0.js → chunk-41cq88js.js} +1 -1
- package/bundle/{chunk-0nqf1k20.js → chunk-44723rmb.js} +1 -1
- package/bundle/{chunk-cejyed1j.js → chunk-45k7qm85.js} +1 -1
- package/bundle/{chunk-qznr1emx.js → chunk-52frd9p0.js} +4 -4
- package/bundle/{chunk-h99tj1e4.js → chunk-5gsdnejs.js} +1 -1
- package/bundle/{chunk-4websxrs.js → chunk-5qsr1q4t.js} +1 -1
- package/bundle/{chunk-rscfes01.js → chunk-6sxx56b2.js} +1 -1
- package/bundle/{chunk-hzrxmdqm.js → chunk-6t48g4x5.js} +1 -1
- package/bundle/{chunk-3atcc483.js → chunk-7ayb3k5p.js} +1 -1
- package/bundle/{chunk-4dnntf9k.js → chunk-826r9svy.js} +1 -1
- package/bundle/{chunk-ha8b2n4x.js → chunk-89b4k585.js} +1 -1
- package/bundle/{chunk-tdyvps17.js → chunk-93gdcrbc.js} +1 -1
- package/bundle/{chunk-n0b0dfqk.js → chunk-98b7ecrk.js} +1 -1
- package/bundle/{chunk-88q0mtgp.js → chunk-a9a0cwmf.js} +1 -1
- package/bundle/{chunk-56v352f8.js → chunk-acpjrs02.js} +1 -1
- package/bundle/{chunk-78pt314g.js → chunk-af81r4v7.js} +1 -1
- package/bundle/{chunk-g06a4chw.js → chunk-bbdp6dj4.js} +1 -1
- package/bundle/{chunk-7knnz5f1.js → chunk-bch1rj72.js} +1 -1
- package/bundle/{chunk-0vxnkstz.js → chunk-c55f729m.js} +1 -1
- package/bundle/{chunk-nvwzam7a.js → chunk-cfjjx3sh.js} +1 -1
- package/bundle/{chunk-z4kjxtjq.js → chunk-cq9sd32h.js} +1 -1
- package/bundle/{chunk-qktzz0sy.js → chunk-ct693qsd.js} +1 -1
- package/bundle/{chunk-zgv1e250.js → chunk-dt5aae7t.js} +1 -1
- package/bundle/{chunk-enmsp09e.js → chunk-eb4y8bjv.js} +1 -1
- package/bundle/{chunk-dqp4nmxs.js → chunk-fxx0z4yb.js} +1 -1
- package/bundle/{chunk-4086z5ys.js → chunk-g3y5xemb.js} +1 -1
- package/bundle/{chunk-262s2yz2.js → chunk-h5pnng66.js} +1 -1
- package/bundle/{chunk-yvn8dmah.js → chunk-hgmqz75r.js} +1 -1
- package/bundle/{chunk-nbd13scz.js → chunk-jxwey5py.js} +1 -1
- package/bundle/{chunk-s2gg38y0.js → chunk-jyt2xvha.js} +1 -1
- package/bundle/{chunk-h823m51m.js → chunk-kdj7xvz7.js} +1 -1
- package/bundle/{chunk-a7wmadf1.js → chunk-kf2f3mza.js} +1 -1
- package/bundle/{chunk-0vakk88p.js → chunk-kj8cmn7z.js} +1 -1
- package/bundle/{chunk-rp9r3cvt.js → chunk-kn8w69g9.js} +1 -1
- package/bundle/{chunk-epgcsjfp.js → chunk-kxwkab31.js} +1 -1
- package/bundle/{chunk-49xhybc2.js → chunk-m7v4ky0y.js} +1 -1
- package/bundle/{chunk-96wwns35.js → chunk-mtpzcc14.js} +1 -1
- package/bundle/{chunk-jvybgsz5.js → chunk-np12r26m.js} +1 -1
- package/bundle/{chunk-bvf2dcq4.js → chunk-nw3e93y8.js} +1 -1
- package/bundle/{chunk-wg55bwqh.js → chunk-nymf08b4.js} +2 -2
- package/bundle/{chunk-tza09w2q.js → chunk-pxv12ctq.js} +1 -1
- package/bundle/{chunk-qqrc1h5b.js → chunk-r1xh50b2.js} +1 -1
- package/bundle/{chunk-qrxqfp59.js → chunk-rn043d0r.js} +1 -1
- package/bundle/chunk-rrd0fdra.js +2 -0
- package/bundle/{chunk-z8mj4z6e.js → chunk-sf5zc4kc.js} +1 -1
- package/bundle/{chunk-vdxar0ct.js → chunk-t5xxs5kp.js} +1 -1
- package/bundle/{chunk-p27a88vp.js → chunk-t9pwz4ws.js} +1 -1
- package/bundle/{chunk-5bjtq8t2.js → chunk-ty2vg1a5.js} +1 -1
- package/bundle/{chunk-azpnrnv9.js → chunk-v3nqkqhz.js} +307 -305
- package/bundle/{chunk-v6h3nes1.js → chunk-vp9scf28.js} +1 -1
- package/bundle/{chunk-565855py.js → chunk-vwh6mv37.js} +1 -1
- package/bundle/chunk-w2cb8cry.js +2 -0
- package/bundle/{chunk-47z3x3dp.js → chunk-wmezdcdh.js} +2 -2
- package/bundle/{chunk-9fyz4sxa.js → chunk-xhtcegk0.js} +1 -1
- package/bundle/{chunk-brws2aht.js → chunk-xmb8jy13.js} +1 -1
- package/bundle/{chunk-6tstcwxp.js → chunk-xqnzmr7a.js} +1 -1
- package/bundle/{chunk-16w710kf.js → chunk-xy3c8f1h.js} +1 -1
- package/bundle/{chunk-jrwnz64e.js → chunk-xynwfaf1.js} +1 -1
- package/bundle/{chunk-p3rd2q47.js → chunk-yfzyzsr4.js} +1 -1
- package/bundle/{chunk-snbw69t6.js → chunk-yv5aehqq.js} +1 -1
- package/bundle/{chunk-c74cxhjb.js → chunk-zgcabs1k.js} +1 -1
- package/bundle/index.js +18 -18
- package/bundle/worker.js +1 -1
- package/package.json +1 -1
- package/bundle/chunk-hbyrwmne.js +0 -2
- package/bundle/chunk-x9ptmxt7.js +0 -2
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a as $B,b as zB}from"./chunk-
|
|
3
|
-
`+B}async function d(B){let V=a({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let $=await V.event.subscribe(),z=YB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),D=$.stream[Symbol.asyncIterator](),C=z.completion.then(()=>"DONE");(async()=>{try{while(!0){let W=await Promise.race([D.next(),C]);if(W==="DONE")break;let N=W;if(N.done)break;let G=N.value;z.onEvent(G);let K=G.properties;if(G.type==="message.part.updated"){let J=K?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let F=String(J.text??"").trim();if(F)process.stdout.write(F+M)}}if(G.type==="permission.asked"){if(!K||K.sessionID!==Y)continue;await V.permission.reply({requestID:String(K.id),reply:"once"})}if(G.type==="session.error"){if(!K||K.sessionID!==Y||!K.error)continue;let J=K.error,F=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(F)}}}finally{z.stop(),await D.return?.(void 0).catch(()=>{})}})().catch((W)=>{console.error(W),process.exit(1)});let y=B.model?e.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:y,parts:[{type:"text",text:B.prompt}]}),z.markStarted(),await z.completion}var aB=BB({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>g(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(i).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(WB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=VB();try{JB();let X=XB(B);if(X){H.error(X),process.exitCode=1;return}let Z=bB(B)??B.model,Y=q(process.env.PWD??process.cwd()),$=B.project?q(h.isAbsolute(B.project)?B.project:h.join(Y,B.project)):q(process.cwd());if(B.project&&!await E($)){let J=QB(B.project,$);if(H.error(J.error),J.hint)H.println(J.hint);process.exitCode=1;return}let z=T($);if(z){if(B.project){H.error("Cannot start in "+$+": "+z),process.exitCode=1;return}let J=q(GB.homedir());if(T(J)){H.error("Cannot start in "+$+": "+z),process.exitCode=1;return}x.warn("unsafe start directory, falling back to home",{requested:$,home:J}),$=J}let D=await FB();try{process.chdir($)}catch{H.error("Failed to change directory to "+$);return}let C=q(process.cwd()),I=p({[u]:"worker",[c]:l()}),y=new Worker(D,{env:I});y.onerror=(J)=>{x.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let W=n(y),N=()=>{W.call("reload",void 0).catch((J)=>{x.warn("worker reload failed",{error:A(J)})})};process.on("SIGUSR2",N);let G=!1,K=async()=>{if(G)return;G=!0,process.off("SIGUSR2",N),await o(W.call("shutdown",void 0),5000).catch((J)=>{x.warn("worker shutdown failed",{error:A(J)})}),y.terminate()};try{let J=import("./chunk-
|
|
2
|
+
import{a as $B,b as zB}from"./chunk-7ayb3k5p.js";import"./chunk-5gsdnejs.js";import"./chunk-ehb4hd9c.js";import{B as XB}from"./chunk-gsez13bg.js";import{C as JB,E as VB}from"./chunk-c8k32724.js";import"./chunk-ct693qsd.js";import{X as YB,Y as ZB}from"./chunk-5ysbwr4x.js";import"./chunk-ff548b0j.js";import"./chunk-zc0cdvcv.js";import{ae as BB}from"./chunk-5w76kdjr.js";import{$f as i,Yf as g,Zf as w,_f as O}from"./chunk-41cq88js.js";import{dg as H}from"./chunk-eg3syjtv.js";import{Fg as r}from"./chunk-36xm6mgm.js";import{Bh as S}from"./chunk-v3nqkqhz.js";import"./chunk-w46g7kdq.js";import"./chunk-bd21p9zz.js";import"./chunk-p54bzjtv.js";import"./chunk-ha1w0xzh.js";import"./chunk-6m9jb0s9.js";import"./chunk-vygkwwjd.js";import{Qj as o,Tk as e,xj as U}from"./chunk-52frd9p0.js";import"./chunk-xqnzmr7a.js";import{Ml as T}from"./chunk-r1xh50b2.js";import"./chunk-13rsd5vv.js";import"./chunk-mh19kwzw.js";import"./chunk-a9a0cwmf.js";import"./chunk-nw3e93y8.js";import"./chunk-9zm6r55d.js";import"./chunk-vcygx6hs.js";import"./chunk-khzzmyk2.js";import"./chunk-y7hgevfv.js";import"./chunk-47k5jy1p.js";import{ao as a,go as s,vo as t}from"./chunk-kn8w69g9.js";import"./chunk-ph8hn1wt.js";import"./chunk-ptqk1j2r.js";import"./chunk-cqtkxwd8.js";import"./chunk-pr7z5dj8.js";import"./chunk-dnnkq5y4.js";import"./chunk-t239rvej.js";import"./chunk-yz25607t.js";import"./chunk-7hvf9dgx.js";import"./chunk-wkg3c643.js";import"./chunk-fhqfqd5v.js";import"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import{Gr as n}from"./chunk-t5xxs5kp.js";import"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-nj1ntakd.js";import"./chunk-cmb62jkt.js";import"./chunk-tkrwcjkr.js";import{bs as f}from"./chunk-w2cb8cry.js";import{As as u,Bs as l,Ds as p,zs as c}from"./chunk-kj8cmn7z.js";import{Hs as A}from"./chunk-r5zy4za0.js";import{Qs as x}from"./chunk-tr6rdr6h.js";import{ct as E,et as q}from"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import{eH as P}from"./chunk-qnvsqnz5.js";import"./chunk-pxm4qvqk.js";import"./chunk-j8fcfhr2.js";import{wO as v}from"./chunk-r9w0thdk.js";import h from"path";import{fileURLToPath as KB}from"url";import{writeHeapSnapshot as MB}from"v8";import GB,{EOL as M}from"os";var WB={free:"free",default:"default",fast:"fast",economy:"economical",power:"power",orchestrated:"orchestrated"},m=ZB;function R(B){if(B.agent)return B.agent;return m}function QB(B,V){if(h.isAbsolute(B)||B.includes("/")||B.includes("\\")||B.startsWith(".")||B.startsWith("~"))return{error:"Directory not found: "+V};return{error:`Unknown command "${B}"`,hint:"Run `qitqode --help` to see the available commands, or pass an existing directory to start the TUI there."}}function bB(B){for(let[V,X]of Object.entries(WB))if(B[V]){let Z=f[X];if(Z)return`${Z.providerID}/${Z.modelID}`}return}function jB(B){return async(X,Z)=>{let Y=new Request(X,Z),$=Y.body?await Y.text():void 0,z=await B.call("fetch",{url:Y.url,method:Y.method,headers:Object.fromEntries(Y.headers.entries()),body:$});return new Response(z.body,{status:z.status,headers:z.headers})}}function CB(B){return{subscribe:async(V)=>{return B.on("global.event",(X)=>{V(X)})}}}async function FB(){if(typeof globalThis.QITQODE_WORKER_PATH<"u")return globalThis.QITQODE_WORKER_PATH;let B=new URL("./cli/cmd/tui/worker.js",import.meta.url);if(await E(KB(B)))return B;return new URL("./worker.ts",import.meta.url)}async function _B(B){let V=process.stdin.isTTY?void 0:await Bun.stdin.text();if(!B)return V;if(!V)return B;return V+`
|
|
3
|
+
`+B}async function d(B){let V=a({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let $=await V.event.subscribe(),z=YB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),D=$.stream[Symbol.asyncIterator](),C=z.completion.then(()=>"DONE");(async()=>{try{while(!0){let W=await Promise.race([D.next(),C]);if(W==="DONE")break;let N=W;if(N.done)break;let G=N.value;z.onEvent(G);let K=G.properties;if(G.type==="message.part.updated"){let J=K?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let F=String(J.text??"").trim();if(F)process.stdout.write(F+M)}}if(G.type==="permission.asked"){if(!K||K.sessionID!==Y)continue;await V.permission.reply({requestID:String(K.id),reply:"once"})}if(G.type==="session.error"){if(!K||K.sessionID!==Y||!K.error)continue;let J=K.error,F=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(F)}}}finally{z.stop(),await D.return?.(void 0).catch(()=>{})}})().catch((W)=>{console.error(W),process.exit(1)});let y=B.model?e.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:y,parts:[{type:"text",text:B.prompt}]}),z.markStarted(),await z.completion}var aB=BB({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>g(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(i).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(WB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=VB();try{JB();let X=XB(B);if(X){H.error(X),process.exitCode=1;return}let Z=bB(B)??B.model,Y=q(process.env.PWD??process.cwd()),$=B.project?q(h.isAbsolute(B.project)?B.project:h.join(Y,B.project)):q(process.cwd());if(B.project&&!await E($)){let J=QB(B.project,$);if(H.error(J.error),J.hint)H.println(J.hint);process.exitCode=1;return}let z=T($);if(z){if(B.project){H.error("Cannot start in "+$+": "+z),process.exitCode=1;return}let J=q(GB.homedir());if(T(J)){H.error("Cannot start in "+$+": "+z),process.exitCode=1;return}x.warn("unsafe start directory, falling back to home",{requested:$,home:J}),$=J}let D=await FB();try{process.chdir($)}catch{H.error("Failed to change directory to "+$);return}let C=q(process.cwd()),I=p({[u]:"worker",[c]:l()}),y=new Worker(D,{env:I});y.onerror=(J)=>{x.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let W=n(y),N=()=>{W.call("reload",void 0).catch((J)=>{x.warn("worker reload failed",{error:A(J)})})};process.on("SIGUSR2",N);let G=!1,K=async()=>{if(G)return;G=!0,process.off("SIGUSR2",N),await o(W.call("shutdown",void 0),5000).catch((J)=>{x.warn("worker shutdown failed",{error:A(J)})}),y.terminate()};try{let J=import("./chunk-mtpzcc14.js"),F=import("./chunk-hgmqz75r.js").then(({TuiConfig:_})=>_.get()),L=await _B(B.prompt),HB=await F;if(B.headless&&w(O(B))){H.error("--headless cannot be combined with network-listener flags (--port, --hostname, --mdns)"),process.exitCode=1;return}let k=O(B),j=w(k)?{url:(await W.call("server",k)).url,fetch:void 0,events:void 0}:{url:"http://qitqode.internal",fetch:jB(W),events:CB(W)};if(setTimeout(()=>{W.call("checkUpgrade",{directory:C}).catch(()=>{})},1000).unref?.(),B.headless){if(!L){H.error("--headless requires a prompt: pass --prompt or pipe input via stdin"),process.exitCode=1;return}if(B.sso){try{let Q=await r({tryOpen:!1,onCode:(b)=>{if(process.stdout.write(M),process.stdout.write(" To sign in, open: "+b.verificationUri+M),process.stdout.write(" and enter code: "+b.userCode+M),b.verificationUriComplete)process.stdout.write(M+" Or open this link directly:"+M+" "+b.verificationUriComplete+M);process.stdout.write(M+" Waiting for approval... (ctrl+c to cancel)"+M)}});await S.runPromise(P.gen(function*(){yield*(yield*U.Service).set("forgewise",t(Q,{rotateRefreshToken:!0}))})),process.stdout.write(" Signed in as "+(Q.name||Q.email)+M)}catch(Q){H.error("SSO sign-in failed: "+A(Q)),process.exitCode=1;return}await d({url:j.url,fetch:j.fetch,prompt:L,model:Z,agent:R(B)??m,directory:C});return}let _=$B(typeof B["api-key"]==="string"?String(B["api-key"]):"");if(_)await S.runPromise(zB(_));else if(!await S.runPromise(P.gen(function*(){if(yield*P.promise(()=>s()))return!0;return!!(yield*(yield*U.Service).get("forgewise"))}))){H.error(`Not signed in. Use one of:
|
|
4
4
|
qitqode auth login (browser / device-code flow)
|
|
5
5
|
qitqode auth login --api-key (paste a Qortex API key)
|
|
6
6
|
--api-key <key> (inline for this run)
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{W as R9}from"./chunk-
|
|
2
|
+
import{W as R9}from"./chunk-3akv2xqh.js";import{Pd as E9}from"./chunk-2nv1scj9.js";import{Qd as P6,Td as p$,Ud as S9,Vd as U9,Yd as H9,Zd as q6}from"./chunk-ff548b0j.js";import"./chunk-zc0cdvcv.js";import{ae as T0}from"./chunk-5w76kdjr.js";import{dg as O}from"./chunk-eg3syjtv.js";import{$g as j9,Bh as E$,xh as I9}from"./chunk-v3nqkqhz.js";import"./chunk-w46g7kdq.js";import"./chunk-bd21p9zz.js";import"./chunk-p54bzjtv.js";import"./chunk-ha1w0xzh.js";import"./chunk-6m9jb0s9.js";import"./chunk-vygkwwjd.js";import{Nj as O6,Oj as M0,Tk as w9,Vk as D9,cl as b9,wj as T9}from"./chunk-52frd9p0.js";import{pl as N9}from"./chunk-xqnzmr7a.js";import{El as A0,Nl as T$}from"./chunk-r1xh50b2.js";import"./chunk-13rsd5vv.js";import"./chunk-mh19kwzw.js";import"./chunk-a9a0cwmf.js";import"./chunk-nw3e93y8.js";import"./chunk-9zm6r55d.js";import"./chunk-vcygx6hs.js";import"./chunk-khzzmyk2.js";import"./chunk-y7hgevfv.js";import"./chunk-47k5jy1p.js";import"./chunk-kn8w69g9.js";import"./chunk-ph8hn1wt.js";import"./chunk-ptqk1j2r.js";import"./chunk-cqtkxwd8.js";import"./chunk-pr7z5dj8.js";import"./chunk-dnnkq5y4.js";import"./chunk-t239rvej.js";import"./chunk-yz25607t.js";import"./chunk-7hvf9dgx.js";import"./chunk-wkg3c643.js";import"./chunk-fhqfqd5v.js";import"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import"./chunk-t5xxs5kp.js";import{Nr as C6}from"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-nj1ntakd.js";import"./chunk-cmb62jkt.js";import"./chunk-tkrwcjkr.js";import"./chunk-w2cb8cry.js";import{hs as F9,ks as R6,ls as M9,qs as A9}from"./chunk-kj8cmn7z.js";import"./chunk-r5zy4za0.js";import"./chunk-tr6rdr6h.js";import{ft as L9}from"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import{eH as V9}from"./chunk-qnvsqnz5.js";import"./chunk-pxm4qvqk.js";import"./chunk-j8fcfhr2.js";import{sO as q0,tO as D,wO as E}from"./chunk-r9w0thdk.js";var JZ=D((zZ)=>{/*!
|
|
3
3
|
* content-type
|
|
4
4
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
5
5
|
* MIT Licensed
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Tl as an,Ul as _i,Vl as bn,Wl as Ni,Yl as Yr,Zl as zr}from"./chunk-fsahzvd5.js";import{$l as yo,Am as Z,Bm as go,Cm as Kn,Dm as lo,Em as so,Fm as _o,Gm as No,Hm as po,Im as Ao,Jm as To,Km as Ir,Lm as Oo,Mm as $o,Nm as Do,Om as Lr,Pm as vo,Qm as dr,Rm as Bo,Sm as Gr,Tm as Jr,Um as Mr,Vm as Sr,Wm as Cr,Xm as Hr,Ym as Qo,Zm as Io,_l as uo,_m as Fo,bm as er,cm as mr,dm as ur,dn as ui,em as yr,fm as fr,gm as gr,hm as lr,im as sr,jm as _r,km as Nr,lm as pr,mm as Ar,nm as V,om as Tr,pm as Or,qm as $r,rm as Dr,sm as vr,tm as Br,um as j,vm as v,wm as yn,xm as un,ym as Xo,zm as Qr}from"./chunk-mh19kwzw.js";import{Kn as Fn,On as jn}from"./chunk-vcygx6hs.js";import{Pn as gi}from"./chunk-khzzmyk2.js";import{Qn as Mo}from"./chunk-y7hgevfv.js";import{Bq as ni,vq as Wn,wq as hn,xq as Nn,yq as hr,zq as ti}from"./chunk-xq2kcar4.js";import{Cq as ri}from"./chunk-qrxqfp59.js";import{Dr as gn}from"./chunk-vdxar0ct.js";import{as as ro}from"./chunk-tkrwcjkr.js";import{es as Ro}from"./chunk-0vakk88p.js";import{Ns as nn,Ws as c}from"./chunk-tr6rdr6h.js";import{Zs as Xr,at as qo,bt as k,ft as mo,kt as $n}from"./chunk-at22twxx.js";import{lt as a}from"./chunk-kgptyf7n.js";import{az as pn,iz as Jn,wz as Cn}from"./chunk-55fcmswd.js";import{DE as h,LD as Ko,SD as Xn,TN as N,ZD as ln,eH as r,hK as Zr,iJ as Uo,lB as cn,mI as Ln,nE as Ur,zB as vn}from"./chunk-qnvsqnz5.js";import{uO as On}from"./chunk-r9w0thdk.js";var Vo={};On(Vo,{run:()=>$i});var mn={time_created:j().notNull().$default(()=>Date.now()),time_updated:j().notNull().$onUpdate(()=>Date.now())};var J=un("project",{id:v().$type().primaryKey(),worktree:v().notNull(),vcs:v(),name:v(),icon_url:v(),icon_color:v(),...mn,time_initialized:j(),sandboxes:v({mode:"json"}).notNull().$type(),commands:v({mode:"json"}).$type()});var fn=un("session",{id:v().$type().primaryKey(),project_id:v().$type().notNull().references(()=>J.id,{onDelete:"cascade"}),workspace_id:v().$type(),parent_id:v().$type(),context_from:v().$type(),context_watermark:v().$type(),slug:v().notNull(),directory:v().notNull(),title:v().notNull(),version:v().notNull(),share_url:v(),summary_additions:j(),summary_deletions:j(),summary_files:j(),summary_diffs:v({mode:"json"}).$type(),revert:v({mode:"json"}).$type(),permission:v({mode:"json"}).$type(),...mn,time_compacting:j(),time_archived:j(),last_checkpoint_message_id:v().$type()},(n)=>[yn("session_project_idx").on(n.project_id),yn("session_workspace_idx").on(n.workspace_id),yn("session_parent_idx").on(n.parent_id),yn("session_context_from_idx").on(n.context_from)]),eo=un("message",{id:v().$type().primaryKey(),session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),agent_id:v().notNull().default("main"),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("message_session_time_created_id_idx").on(n.session_id,n.time_created,n.id),yn("message_session_agent_idx").on(n.session_id,n.agent_id,n.id)]),Yo=un("part",{id:v().$type().primaryKey(),message_id:v().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:v().$type().notNull(),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("part_message_id_id_idx").on(n.message_id,n.id),yn("part_session_idx").on(n.session_id)]),zo=un("todo",{session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),content:v().notNull(),status:v().notNull(),position:j().notNull(),...mn},(n)=>[Xo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),co=un("permission",{project_id:v().primaryKey().references(()=>J.id,{onDelete:"cascade"}),...mn,data:v({mode:"json"}).notNull().$type()});var ko=un("session_share",{session_id:v().primaryKey().references(()=>fn.id,{onDelete:"cascade"}),id:v().notNull(),secret:v().notNull(),url:v().notNull(),...mn});import z from"path";var U=c.create({service:"json-migration"});async function $i(n,o){let i=z.join($n.Path.data,"storage");if(!await mo.exists(i))return U.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};U.info("starting json to sqlite migration",{storageDir:i});let l=performance.now();n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = OFF"),n.run("PRAGMA cache_size = 10000"),n.run("PRAGMA temp_store = MEMORY");let e={projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]},A={sessions:0,todos:0,permissions:0,shares:0},_=e.errors,T=1000,M=Date.now();async function x(f){return qo.scan(f,{cwd:i,absolute:!0})}async function C(f,d,S){let B=S-d,p=Array(B);for(let E=0;E<B;E++)p[E]=mo.readJson(f[d+E]);let G=await Promise.allSettled(p),W=Array(B);for(let E=0;E<G.length;E++){let q=G[E];if(q.status==="fulfilled"){W[E]=q.value;continue}_.push(`failed to read ${f[d+E]}: ${q.reason}`)}return W}function H(f,d,S){if(f.length===0)return 0;try{return n.insert(d).values(f).onConflictDoNothing().run(),f.length}catch(B){return _.push(`failed to migrate ${S} batch: ${B}`),0}}U.info("scanning files...");let[K,$,Q,L,g,s,m]=await Promise.all([x("project/*.json"),x("session/*/*.json"),x("message/*/*.json"),x("part/*/*.json"),x("todo/*.json"),x("permission/*.json"),x("session_share/*.json")]);U.info("file scan complete",{projects:K.length,sessions:$.length,messages:Q.length,parts:L.length,todos:g.length,permissions:s.length,shares:m.length});let y=Math.max(1,K.length+$.length+Q.length+L.length+g.length+s.length+m.length),t=o?.progress,u=0,D=(f,d)=>{u=Math.min(y,u+d),t?.({current:u,total:y,label:f})};t?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let I=new Set,O=[];for(let f=0;f<K.length;f+=T){let d=Math.min(f+T,K.length),S=await C(K,f,d);O.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename(K[f+B],".json");I.add(G),O.push({id:G,worktree:p.worktree??"/",vcs:p.vcs,name:p.name??void 0,icon_url:p.icon?.url,icon_color:p.icon?.color,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_initialized:p.time?.initialized,sandboxes:p.sandboxes??[],commands:p.commands})}e.projects+=H(O,J,"project"),D("projects",d-f)}U.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-l)});let P=$.map((f)=>z.basename(z.dirname(f))),Y=new Set,en=[];for(let f=0;f<$.length;f+=T){let d=Math.min(f+T,$.length),S=await C($,f,d);en.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename($[f+B],".json"),W=P[f+B];if(!I.has(W)){A.sessions++;continue}Y.add(G),en.push({id:G,project_id:W,parent_id:p.parentID??null,slug:p.slug??"",directory:p.directory??"",title:p.title??"",version:p.version??"",share_url:p.share?.url??null,summary_additions:p.summary?.additions??null,summary_deletions:p.summary?.deletions??null,summary_files:p.summary?.files??null,summary_diffs:p.summary?.diffs??null,revert:p.revert??null,permission:p.permission??null,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_compacting:p.time?.compacting??null,time_archived:p.time?.archived??null})}e.sessions+=H(en,fn,"session"),D("sessions",d-f)}if(U.info("migrated sessions",{count:e.sessions}),A.sessions>0)U.warn("skipped orphaned sessions",{count:A.sessions});let sn=[],R=[],kn=new Map;for(let f of Q){let d=z.basename(z.dirname(f));if(!Y.has(d))continue;sn.push(f),R.push(d)}for(let f=0;f<sn.length;f+=T){let d=Math.min(f+T,sn.length),S=await C(sn,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=sn[f+G],q=z.basename(E,".json"),xn=R[f+G];kn.set(q,xn);let Bn=W;delete Bn.id,delete Bn.sessionID,B[p++]={id:q,session_id:xn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:Bn}}B.length=p,e.messages+=H(B,eo,"message"),D("messages",d-f)}U.info("migrated messages",{count:e.messages});for(let f=0;f<L.length;f+=T){let d=Math.min(f+T,L.length),S=await C(L,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=L[f+G],q=z.basename(E,".json"),xn=z.basename(z.dirname(E)),Bn=kn.get(xn);if(!Bn){_.push(`part missing message session: ${E}`);continue}if(!Y.has(Bn))continue;let wn=W;delete wn.id,delete wn.messageID,delete wn.sessionID,B[p++]={id:q,message_id:xn,session_id:Bn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:wn}}B.length=p,e.parts+=H(B,Yo,"part"),D("parts",d-f)}U.info("migrated parts",{count:e.parts});let Tn=g.map((f)=>z.basename(f,".json"));for(let f=0;f<g.length;f+=T){let d=Math.min(f+T,g.length),S=await C(g,f,d),B=[];for(let p=0;p<S.length;p++){let G=S[p];if(!G)continue;let W=Tn[f+p];if(!Y.has(W)){A.todos++;continue}if(!Array.isArray(G)){_.push(`todo not an array: ${g[f+p]}`);continue}for(let E=0;E<G.length;E++){let q=G[E];if(!q?.content||!q?.status)continue;B.push({session_id:W,content:q.content,status:q.status,position:E,time_created:M,time_updated:M})}}e.todos+=H(B,zo,"todo"),D("todos",d-f)}if(U.info("migrated todos",{count:e.todos}),A.todos>0)U.warn("skipped orphaned todos",{count:A.todos});let qn=s.map((f)=>z.basename(f,".json")),Hn=[];for(let f=0;f<s.length;f+=T){let d=Math.min(f+T,s.length),S=await C(s,f,d);Hn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=qn[f+B];if(!I.has(G)){A.permissions++;continue}Hn.push({project_id:G,data:p})}e.permissions+=H(Hn,co,"permission"),D("permissions",d-f)}if(U.info("migrated permissions",{count:e.permissions}),A.permissions>0)U.warn("skipped orphaned permissions",{count:A.permissions});let Vn=m.map((f)=>z.basename(f,".json")),dn=[];for(let f=0;f<m.length;f+=T){let d=Math.min(f+T,m.length),S=await C(m,f,d);dn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=Vn[f+B];if(!Y.has(G)){A.shares++;continue}if(!p?.id||!p?.secret||!p?.url){_.push(`session_share missing id/secret/url: ${m[f+B]}`);continue}dn.push({session_id:G,id:p.id,secret:p.secret,url:p.url})}e.shares+=H(dn,ko,"session_share"),D("shares",d-f)}if(U.info("migrated session shares",{count:e.shares}),A.shares>0)U.warn("skipped orphaned session shares",{count:A.shares});if(n.run("COMMIT"),U.info("json migration complete",{projects:e.projects,sessions:e.sessions,messages:e.messages,parts:e.parts,todos:e.todos,permissions:e.permissions,shares:e.shares,errorCount:e.errors.length,duration:Math.round(performance.now()-l)}),e.errors.length>0)U.warn("migration errors",{errors:e.errors.slice(0,20)});return t?.({current:y,total:y,label:"complete"}),e}var In={};On(In,{use:()=>Ce,transaction:()=>xe,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>V,relationsOrderToSQL:()=>Rt,relationsFilterToSQL:()=>Kt,relationToSQL:()=>xt,relationExtrasToSQL:()=>Ht,processRelations:()=>Ct,placeholder:()=>Or,param:()=>Ar,orderSelectedFields:()=>oe,orderByOperators:()=>St,or:()=>lo,operators:()=>Mt,notLike:()=>Gr,notInArray:()=>Ir,notIlike:()=>Mr,notExists:()=>Lr,notBetween:()=>dr,not:()=>so,noopMapper:()=>Nr,noopEncoder:()=>_r,noopDecoder:()=>sr,ne:()=>go,name:()=>gr,min:()=>tr,max:()=>ir,mapUpdateSet:()=>ne,mapResultRow:()=>ht,mapRelationalRow:()=>Jt,mapColumnsInSQLToAlias:()=>it,mapColumnsInAliasedSQLToAlias:()=>rt,lte:()=>Ao,lt:()=>po,like:()=>Bo,l2Distance:()=>Xt,l1Distance:()=>Zt,jaccardDistance:()=>Ut,isWithEnum:()=>bt,isView:()=>vr,isTable:()=>Yi,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>lr,isConfig:()=>at,is:()=>Mi,innerProduct:()=>Wt,inArray:()=>To,ilike:()=>Jr,haveSameKeys:()=>jt,hasOwnEntityKind:()=>Ji,hammingDistance:()=>Pt,gte:()=>No,gt:()=>_o,getViewSelectedFields:()=>Ft,getViewName:()=>Br,getTableUniqueName:()=>Xi,getTableName:()=>Zi,getTableLikeName:()=>wt,getTableColumns:()=>Vt,getTableAsAliasSQL:()=>Gt,getOriginalColumnFromAlias:()=>ot,getOrderByOperators:()=>dt,getColumns:()=>qt,getColumnTable:()=>Ci,getColumnNameAndConfig:()=>kt,getChannelPath:()=>li,fillPlaceholders:()=>$r,fieldSelectionToSQL:()=>Lt,extractTablesFromSchema:()=>It,extractExtendedColumnType:()=>mt,exists:()=>Do,eq:()=>Z,entityKind:()=>Gi,effect:()=>He,desc:()=>Io,defineRelationsPart:()=>Qt,defineRelations:()=>Bt,createRelationsHelper:()=>vt,countDistinct:()=>bo,count:()=>fo,cosineDistance:()=>Et,close:()=>Se,buildRelationsParts:()=>Dt,buildRelations:()=>$t,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ct,asc:()=>Qo,arrayOverlaps:()=>Hr,arrayContains:()=>Sr,arrayContained:()=>Cr,applyMixins:()=>zt,and:()=>Kn,aliasedTableColumn:()=>nt,aliasedTable:()=>hi,aliasedRelation:()=>bi,aliasedColumn:()=>ai,WithSubquery:()=>ci,ViewSelectionAliasProxyHandler:()=>ji,ViewBaseConfig:()=>ki,View:()=>Dr,TransactionRollbackError:()=>ft,TableSchema:()=>Ui,TableColumns:()=>Wi,TableAliasProxyHandler:()=>Fi,Table:()=>Pi,Subquery:()=>zi,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>Ot,RelationsBuilderTable:()=>Tt,RelationsBuilderJunctionColumn:()=>At,RelationsBuilderColumn:()=>pt,RelationTableAliasProxyHandler:()=>wi,Relation:()=>Nt,QueryPromise:()=>tt,Placeholder:()=>Tr,Path:()=>Eo,Param:()=>pr,OriginalName:()=>Ei,One:()=>_t,NotFoundError:()=>Me,NoopLogger:()=>di,Name:()=>fr,Many:()=>st,IsAlias:()=>Ri,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Ki,ExtraConfigBuilder:()=>xi,DrizzleQueryError:()=>yt,DrizzleError:()=>ut,DefaultLogger:()=>Li,Count:()=>lt,ConsoleLogWriter:()=>Ii,ColumnTableAliasProxyHandler:()=>Vi,ColumnBuilder:()=>et,ColumnAliasProxyHandler:()=>qi,Column:()=>Si,Client:()=>Mn,CONSTANTS:()=>Yt,BaseName:()=>Hi,AggregatedField:()=>gt});import Di from"crypto";import wo,{existsSync as vi,readdirSync as Bi}from"fs";import{join as Qi}from"path";function jo(n){if(wo.existsSync(`${n.migrationsFolder}/meta/_journal.json`))throw Error('We detected that you have old drizzle-kit migration folders. You must upgrade drizzle-kit and run "drizzle-kit up"');let o=n.migrationsFolder,i=[],l=Bi(o).map((e)=>({path:Qi(o,e,"migration.sql"),name:e})).filter((e)=>vi(e.path));l.sort((e,A)=>e.name.localeCompare(A.name));for(let e of l){let A=e.path,_=e.name.slice(0,14),T=wo.readFileSync(A).toString(),M=T.split("--> statement-breakpoint").map((C)=>{return C}),x=Fo(_);i.push({sql:M,bps:!0,folderMillis:x,hash:Di.createHash("sha256").update(T).digest("hex"),name:e.name})}return i}function ao(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let l=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,A=l.map((_)=>({sql:_.sql.split("--> statement-breakpoint"),folderMillis:_.timestamp,hash:"",bps:!0,name:_.name}));return n.dialect.migrate(A,n.session,{migrationsTable:e})}let i=jo(o);return n.dialect.migrate(i,n.session,o)}function fo(n){return V`count(${n||V.raw("*")})`.mapWith(Number)}function bo(n){return V`count(distinct ${n})`.mapWith(Number)}function ho(n){return V`avg(${n})`.mapWith(String)}function nr(n){return V`avg(distinct ${n})`.mapWith(String)}function or(n){return V`sum(${n})`.mapWith(String)}function rr(n){return V`sum(distinct ${n})`.mapWith(String)}function ir(n){return V`max(${n})`.mapWith(uo(n,yo)?n:String)}function tr(n){return V`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Un={};On(Un,{workspaceID:()=>De,useEffect:()=>Qe,use:()=>Be,make:()=>ve,invalidate:()=>Le,has:()=>Ie,get:()=>xo,directory:()=>no,context:()=>Ho,bind:()=>$e});import{EventEmitter as ie}from"events";var Rn=new ie;var Lo=new Set;function xr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function Go(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function En(n){return n()}var jr={};On(jr,{setInitialized:()=>se,list:()=>ge,layer:()=>Fr,get:()=>le,fromRow:()=>_n,defaultLayer:()=>Co,UpdateInput:()=>fe,Service:()=>Gn,Info:()=>Vr,Event:()=>wr});import*as F from"fs/promises";import*as cr from"os";import*as Dn from"path";var te=N.String.pipe(N.brand("ProjectID")),w=te.pipe(Fn((n)=>({global:n.make("global"),zod:a.string().pipe(a.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Er from"crypto";async function Jo(n){let o=b.resolve(n);while(!0){let i=b.join(o,".git"),l=await Qn.stat(i).catch(()=>null);if(l){if(l.isDirectory())return i;let _=(await Qn.readFile(i,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!_)return null;let T=b.isAbsolute(_[1])?_[1]:b.resolve(o,_[1]);return b.resolve(T,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Kr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function Rr(n){let o=await Kr(n);if(o)return o;let i=Er.randomUUID();try{return await Qn.writeFile(n,i,{flag:"wx"}),i}catch(l){if(l.code!=="EEXIST")throw l;let e=await Kr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Pr(n){let o=await Jo(n);if(o){let l=b.join(o,"qitqode-project-id");return w.make(await Rr(l))}let i=b.join(n,".qitqode-project-id");return w.make(await Rr(i))}async function me(n){let o=await Jo(n);if(!o)return;let i=Dn.join(n,".qitqode-project-id"),l=Dn.join(o,"qitqode-project-id"),e=(T)=>F.access(T).then(()=>!0).catch(()=>!1);if(await e(i)){if(!await e(l)){let T=await F.readFile(i,"utf-8");await F.writeFile(l,T)}await F.unlink(i).catch(()=>{})}let A=Dn.join(o,"info","exclude");if(await F.mkdir(Dn.dirname(A),{recursive:!0}),!(await F.readFile(A,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await F.appendFile(A,`
|
|
2
|
+
import{Tl as an,Ul as _i,Vl as bn,Wl as Ni,Yl as Yr,Zl as zr}from"./chunk-13rsd5vv.js";import{$l as yo,Am as Z,Bm as go,Cm as Kn,Dm as lo,Em as so,Fm as _o,Gm as No,Hm as po,Im as Ao,Jm as To,Km as Ir,Lm as Oo,Mm as $o,Nm as Do,Om as Lr,Pm as vo,Qm as dr,Rm as Bo,Sm as Gr,Tm as Jr,Um as Mr,Vm as Sr,Wm as Cr,Xm as Hr,Ym as Qo,Zm as Io,_l as uo,_m as Fo,bm as er,cm as mr,dm as ur,dn as ui,em as yr,fm as fr,gm as gr,hm as lr,im as sr,jm as _r,km as Nr,lm as pr,mm as Ar,nm as V,om as Tr,pm as Or,qm as $r,rm as Dr,sm as vr,tm as Br,um as j,vm as v,wm as yn,xm as un,ym as Xo,zm as Qr}from"./chunk-mh19kwzw.js";import{Kn as Fn,On as jn}from"./chunk-vcygx6hs.js";import{Pn as gi}from"./chunk-khzzmyk2.js";import{Qn as Mo}from"./chunk-y7hgevfv.js";import{Bq as ni,vq as Wn,wq as hn,xq as Nn,yq as hr,zq as ti}from"./chunk-2b3fn9xv.js";import{Cq as ri}from"./chunk-rn043d0r.js";import{Dr as gn}from"./chunk-t5xxs5kp.js";import{as as ro}from"./chunk-tkrwcjkr.js";import{es as Ro}from"./chunk-kj8cmn7z.js";import{Ns as nn,Ws as c}from"./chunk-tr6rdr6h.js";import{Zs as Xr,at as qo,bt as k,ft as mo,kt as $n}from"./chunk-at22twxx.js";import{lt as a}from"./chunk-kgptyf7n.js";import{az as pn,iz as Jn,wz as Cn}from"./chunk-55fcmswd.js";import{DE as h,LD as Ko,SD as Xn,TN as N,ZD as ln,eH as r,hK as Zr,iJ as Uo,lB as cn,mI as Ln,nE as Ur,zB as vn}from"./chunk-qnvsqnz5.js";import{uO as On}from"./chunk-r9w0thdk.js";var Vo={};On(Vo,{run:()=>$i});var mn={time_created:j().notNull().$default(()=>Date.now()),time_updated:j().notNull().$onUpdate(()=>Date.now())};var J=un("project",{id:v().$type().primaryKey(),worktree:v().notNull(),vcs:v(),name:v(),icon_url:v(),icon_color:v(),...mn,time_initialized:j(),sandboxes:v({mode:"json"}).notNull().$type(),commands:v({mode:"json"}).$type()});var fn=un("session",{id:v().$type().primaryKey(),project_id:v().$type().notNull().references(()=>J.id,{onDelete:"cascade"}),workspace_id:v().$type(),parent_id:v().$type(),context_from:v().$type(),context_watermark:v().$type(),slug:v().notNull(),directory:v().notNull(),title:v().notNull(),version:v().notNull(),share_url:v(),summary_additions:j(),summary_deletions:j(),summary_files:j(),summary_diffs:v({mode:"json"}).$type(),revert:v({mode:"json"}).$type(),permission:v({mode:"json"}).$type(),...mn,time_compacting:j(),time_archived:j(),last_checkpoint_message_id:v().$type()},(n)=>[yn("session_project_idx").on(n.project_id),yn("session_workspace_idx").on(n.workspace_id),yn("session_parent_idx").on(n.parent_id),yn("session_context_from_idx").on(n.context_from)]),eo=un("message",{id:v().$type().primaryKey(),session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),agent_id:v().notNull().default("main"),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("message_session_time_created_id_idx").on(n.session_id,n.time_created,n.id),yn("message_session_agent_idx").on(n.session_id,n.agent_id,n.id)]),Yo=un("part",{id:v().$type().primaryKey(),message_id:v().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:v().$type().notNull(),...mn,data:v({mode:"json"}).notNull().$type()},(n)=>[yn("part_message_id_id_idx").on(n.message_id,n.id),yn("part_session_idx").on(n.session_id)]),zo=un("todo",{session_id:v().$type().notNull().references(()=>fn.id,{onDelete:"cascade"}),content:v().notNull(),status:v().notNull(),position:j().notNull(),...mn},(n)=>[Xo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),co=un("permission",{project_id:v().primaryKey().references(()=>J.id,{onDelete:"cascade"}),...mn,data:v({mode:"json"}).notNull().$type()});var ko=un("session_share",{session_id:v().primaryKey().references(()=>fn.id,{onDelete:"cascade"}),id:v().notNull(),secret:v().notNull(),url:v().notNull(),...mn});import z from"path";var U=c.create({service:"json-migration"});async function $i(n,o){let i=z.join($n.Path.data,"storage");if(!await mo.exists(i))return U.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};U.info("starting json to sqlite migration",{storageDir:i});let l=performance.now();n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = OFF"),n.run("PRAGMA cache_size = 10000"),n.run("PRAGMA temp_store = MEMORY");let e={projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]},A={sessions:0,todos:0,permissions:0,shares:0},_=e.errors,T=1000,M=Date.now();async function x(f){return qo.scan(f,{cwd:i,absolute:!0})}async function C(f,d,S){let B=S-d,p=Array(B);for(let E=0;E<B;E++)p[E]=mo.readJson(f[d+E]);let G=await Promise.allSettled(p),W=Array(B);for(let E=0;E<G.length;E++){let q=G[E];if(q.status==="fulfilled"){W[E]=q.value;continue}_.push(`failed to read ${f[d+E]}: ${q.reason}`)}return W}function H(f,d,S){if(f.length===0)return 0;try{return n.insert(d).values(f).onConflictDoNothing().run(),f.length}catch(B){return _.push(`failed to migrate ${S} batch: ${B}`),0}}U.info("scanning files...");let[K,$,Q,L,g,s,m]=await Promise.all([x("project/*.json"),x("session/*/*.json"),x("message/*/*.json"),x("part/*/*.json"),x("todo/*.json"),x("permission/*.json"),x("session_share/*.json")]);U.info("file scan complete",{projects:K.length,sessions:$.length,messages:Q.length,parts:L.length,todos:g.length,permissions:s.length,shares:m.length});let y=Math.max(1,K.length+$.length+Q.length+L.length+g.length+s.length+m.length),t=o?.progress,u=0,D=(f,d)=>{u=Math.min(y,u+d),t?.({current:u,total:y,label:f})};t?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let I=new Set,O=[];for(let f=0;f<K.length;f+=T){let d=Math.min(f+T,K.length),S=await C(K,f,d);O.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename(K[f+B],".json");I.add(G),O.push({id:G,worktree:p.worktree??"/",vcs:p.vcs,name:p.name??void 0,icon_url:p.icon?.url,icon_color:p.icon?.color,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_initialized:p.time?.initialized,sandboxes:p.sandboxes??[],commands:p.commands})}e.projects+=H(O,J,"project"),D("projects",d-f)}U.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-l)});let P=$.map((f)=>z.basename(z.dirname(f))),Y=new Set,en=[];for(let f=0;f<$.length;f+=T){let d=Math.min(f+T,$.length),S=await C($,f,d);en.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=z.basename($[f+B],".json"),W=P[f+B];if(!I.has(W)){A.sessions++;continue}Y.add(G),en.push({id:G,project_id:W,parent_id:p.parentID??null,slug:p.slug??"",directory:p.directory??"",title:p.title??"",version:p.version??"",share_url:p.share?.url??null,summary_additions:p.summary?.additions??null,summary_deletions:p.summary?.deletions??null,summary_files:p.summary?.files??null,summary_diffs:p.summary?.diffs??null,revert:p.revert??null,permission:p.permission??null,time_created:p.time?.created??M,time_updated:p.time?.updated??M,time_compacting:p.time?.compacting??null,time_archived:p.time?.archived??null})}e.sessions+=H(en,fn,"session"),D("sessions",d-f)}if(U.info("migrated sessions",{count:e.sessions}),A.sessions>0)U.warn("skipped orphaned sessions",{count:A.sessions});let sn=[],R=[],kn=new Map;for(let f of Q){let d=z.basename(z.dirname(f));if(!Y.has(d))continue;sn.push(f),R.push(d)}for(let f=0;f<sn.length;f+=T){let d=Math.min(f+T,sn.length),S=await C(sn,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=sn[f+G],q=z.basename(E,".json"),xn=R[f+G];kn.set(q,xn);let Bn=W;delete Bn.id,delete Bn.sessionID,B[p++]={id:q,session_id:xn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:Bn}}B.length=p,e.messages+=H(B,eo,"message"),D("messages",d-f)}U.info("migrated messages",{count:e.messages});for(let f=0;f<L.length;f+=T){let d=Math.min(f+T,L.length),S=await C(L,f,d),B=Array(S.length),p=0;for(let G=0;G<S.length;G++){let W=S[G];if(!W)continue;let E=L[f+G],q=z.basename(E,".json"),xn=z.basename(z.dirname(E)),Bn=kn.get(xn);if(!Bn){_.push(`part missing message session: ${E}`);continue}if(!Y.has(Bn))continue;let wn=W;delete wn.id,delete wn.messageID,delete wn.sessionID,B[p++]={id:q,message_id:xn,session_id:Bn,time_created:W.time?.created??M,time_updated:W.time?.updated??M,data:wn}}B.length=p,e.parts+=H(B,Yo,"part"),D("parts",d-f)}U.info("migrated parts",{count:e.parts});let Tn=g.map((f)=>z.basename(f,".json"));for(let f=0;f<g.length;f+=T){let d=Math.min(f+T,g.length),S=await C(g,f,d),B=[];for(let p=0;p<S.length;p++){let G=S[p];if(!G)continue;let W=Tn[f+p];if(!Y.has(W)){A.todos++;continue}if(!Array.isArray(G)){_.push(`todo not an array: ${g[f+p]}`);continue}for(let E=0;E<G.length;E++){let q=G[E];if(!q?.content||!q?.status)continue;B.push({session_id:W,content:q.content,status:q.status,position:E,time_created:M,time_updated:M})}}e.todos+=H(B,zo,"todo"),D("todos",d-f)}if(U.info("migrated todos",{count:e.todos}),A.todos>0)U.warn("skipped orphaned todos",{count:A.todos});let qn=s.map((f)=>z.basename(f,".json")),Hn=[];for(let f=0;f<s.length;f+=T){let d=Math.min(f+T,s.length),S=await C(s,f,d);Hn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=qn[f+B];if(!I.has(G)){A.permissions++;continue}Hn.push({project_id:G,data:p})}e.permissions+=H(Hn,co,"permission"),D("permissions",d-f)}if(U.info("migrated permissions",{count:e.permissions}),A.permissions>0)U.warn("skipped orphaned permissions",{count:A.permissions});let Vn=m.map((f)=>z.basename(f,".json")),dn=[];for(let f=0;f<m.length;f+=T){let d=Math.min(f+T,m.length),S=await C(m,f,d);dn.length=0;for(let B=0;B<S.length;B++){let p=S[B];if(!p)continue;let G=Vn[f+B];if(!Y.has(G)){A.shares++;continue}if(!p?.id||!p?.secret||!p?.url){_.push(`session_share missing id/secret/url: ${m[f+B]}`);continue}dn.push({session_id:G,id:p.id,secret:p.secret,url:p.url})}e.shares+=H(dn,ko,"session_share"),D("shares",d-f)}if(U.info("migrated session shares",{count:e.shares}),A.shares>0)U.warn("skipped orphaned session shares",{count:A.shares});if(n.run("COMMIT"),U.info("json migration complete",{projects:e.projects,sessions:e.sessions,messages:e.messages,parts:e.parts,todos:e.todos,permissions:e.permissions,shares:e.shares,errorCount:e.errors.length,duration:Math.round(performance.now()-l)}),e.errors.length>0)U.warn("migration errors",{errors:e.errors.slice(0,20)});return t?.({current:y,total:y,label:"complete"}),e}var In={};On(In,{use:()=>Ce,transaction:()=>xe,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>V,relationsOrderToSQL:()=>Rt,relationsFilterToSQL:()=>Kt,relationToSQL:()=>xt,relationExtrasToSQL:()=>Ht,processRelations:()=>Ct,placeholder:()=>Or,param:()=>Ar,orderSelectedFields:()=>oe,orderByOperators:()=>St,or:()=>lo,operators:()=>Mt,notLike:()=>Gr,notInArray:()=>Ir,notIlike:()=>Mr,notExists:()=>Lr,notBetween:()=>dr,not:()=>so,noopMapper:()=>Nr,noopEncoder:()=>_r,noopDecoder:()=>sr,ne:()=>go,name:()=>gr,min:()=>tr,max:()=>ir,mapUpdateSet:()=>ne,mapResultRow:()=>ht,mapRelationalRow:()=>Jt,mapColumnsInSQLToAlias:()=>it,mapColumnsInAliasedSQLToAlias:()=>rt,lte:()=>Ao,lt:()=>po,like:()=>Bo,l2Distance:()=>Xt,l1Distance:()=>Zt,jaccardDistance:()=>Ut,isWithEnum:()=>bt,isView:()=>vr,isTable:()=>Yi,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>lr,isConfig:()=>at,is:()=>Mi,innerProduct:()=>Wt,inArray:()=>To,ilike:()=>Jr,haveSameKeys:()=>jt,hasOwnEntityKind:()=>Ji,hammingDistance:()=>Pt,gte:()=>No,gt:()=>_o,getViewSelectedFields:()=>Ft,getViewName:()=>Br,getTableUniqueName:()=>Xi,getTableName:()=>Zi,getTableLikeName:()=>wt,getTableColumns:()=>Vt,getTableAsAliasSQL:()=>Gt,getOriginalColumnFromAlias:()=>ot,getOrderByOperators:()=>dt,getColumns:()=>qt,getColumnTable:()=>Ci,getColumnNameAndConfig:()=>kt,getChannelPath:()=>li,fillPlaceholders:()=>$r,fieldSelectionToSQL:()=>Lt,extractTablesFromSchema:()=>It,extractExtendedColumnType:()=>mt,exists:()=>Do,eq:()=>Z,entityKind:()=>Gi,effect:()=>He,desc:()=>Io,defineRelationsPart:()=>Qt,defineRelations:()=>Bt,createRelationsHelper:()=>vt,countDistinct:()=>bo,count:()=>fo,cosineDistance:()=>Et,close:()=>Se,buildRelationsParts:()=>Dt,buildRelations:()=>$t,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ct,asc:()=>Qo,arrayOverlaps:()=>Hr,arrayContains:()=>Sr,arrayContained:()=>Cr,applyMixins:()=>zt,and:()=>Kn,aliasedTableColumn:()=>nt,aliasedTable:()=>hi,aliasedRelation:()=>bi,aliasedColumn:()=>ai,WithSubquery:()=>ci,ViewSelectionAliasProxyHandler:()=>ji,ViewBaseConfig:()=>ki,View:()=>Dr,TransactionRollbackError:()=>ft,TableSchema:()=>Ui,TableColumns:()=>Wi,TableAliasProxyHandler:()=>Fi,Table:()=>Pi,Subquery:()=>zi,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>Ot,RelationsBuilderTable:()=>Tt,RelationsBuilderJunctionColumn:()=>At,RelationsBuilderColumn:()=>pt,RelationTableAliasProxyHandler:()=>wi,Relation:()=>Nt,QueryPromise:()=>tt,Placeholder:()=>Tr,Path:()=>Eo,Param:()=>pr,OriginalName:()=>Ei,One:()=>_t,NotFoundError:()=>Me,NoopLogger:()=>di,Name:()=>fr,Many:()=>st,IsAlias:()=>Ri,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Ki,ExtraConfigBuilder:()=>xi,DrizzleQueryError:()=>yt,DrizzleError:()=>ut,DefaultLogger:()=>Li,Count:()=>lt,ConsoleLogWriter:()=>Ii,ColumnTableAliasProxyHandler:()=>Vi,ColumnBuilder:()=>et,ColumnAliasProxyHandler:()=>qi,Column:()=>Si,Client:()=>Mn,CONSTANTS:()=>Yt,BaseName:()=>Hi,AggregatedField:()=>gt});import Di from"crypto";import wo,{existsSync as vi,readdirSync as Bi}from"fs";import{join as Qi}from"path";function jo(n){if(wo.existsSync(`${n.migrationsFolder}/meta/_journal.json`))throw Error('We detected that you have old drizzle-kit migration folders. You must upgrade drizzle-kit and run "drizzle-kit up"');let o=n.migrationsFolder,i=[],l=Bi(o).map((e)=>({path:Qi(o,e,"migration.sql"),name:e})).filter((e)=>vi(e.path));l.sort((e,A)=>e.name.localeCompare(A.name));for(let e of l){let A=e.path,_=e.name.slice(0,14),T=wo.readFileSync(A).toString(),M=T.split("--> statement-breakpoint").map((C)=>{return C}),x=Fo(_);i.push({sql:M,bps:!0,folderMillis:x,hash:Di.createHash("sha256").update(T).digest("hex"),name:e.name})}return i}function ao(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let l=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,A=l.map((_)=>({sql:_.sql.split("--> statement-breakpoint"),folderMillis:_.timestamp,hash:"",bps:!0,name:_.name}));return n.dialect.migrate(A,n.session,{migrationsTable:e})}let i=jo(o);return n.dialect.migrate(i,n.session,o)}function fo(n){return V`count(${n||V.raw("*")})`.mapWith(Number)}function bo(n){return V`count(distinct ${n})`.mapWith(Number)}function ho(n){return V`avg(${n})`.mapWith(String)}function nr(n){return V`avg(distinct ${n})`.mapWith(String)}function or(n){return V`sum(${n})`.mapWith(String)}function rr(n){return V`sum(distinct ${n})`.mapWith(String)}function ir(n){return V`max(${n})`.mapWith(uo(n,yo)?n:String)}function tr(n){return V`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Un={};On(Un,{workspaceID:()=>De,useEffect:()=>Qe,use:()=>Be,make:()=>ve,invalidate:()=>Le,has:()=>Ie,get:()=>xo,directory:()=>no,context:()=>Ho,bind:()=>$e});import{EventEmitter as ie}from"events";var Rn=new ie;var Lo=new Set;function xr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function Go(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function En(n){return n()}var jr={};On(jr,{setInitialized:()=>se,list:()=>ge,layer:()=>Fr,get:()=>le,fromRow:()=>_n,defaultLayer:()=>Co,UpdateInput:()=>fe,Service:()=>Gn,Info:()=>Vr,Event:()=>wr});import*as F from"fs/promises";import*as cr from"os";import*as Dn from"path";var te=N.String.pipe(N.brand("ProjectID")),w=te.pipe(Fn((n)=>({global:n.make("global"),zod:a.string().pipe(a.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Er from"crypto";async function Jo(n){let o=b.resolve(n);while(!0){let i=b.join(o,".git"),l=await Qn.stat(i).catch(()=>null);if(l){if(l.isDirectory())return i;let _=(await Qn.readFile(i,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!_)return null;let T=b.isAbsolute(_[1])?_[1]:b.resolve(o,_[1]);return b.resolve(T,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Kr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function Rr(n){let o=await Kr(n);if(o)return o;let i=Er.randomUUID();try{return await Qn.writeFile(n,i,{flag:"wx"}),i}catch(l){if(l.code!=="EEXIST")throw l;let e=await Kr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Pr(n){let o=await Jo(n);if(o){let l=b.join(o,"qitqode-project-id");return w.make(await Rr(l))}let i=b.join(n,".qitqode-project-id");return w.make(await Rr(i))}async function me(n){let o=await Jo(n);if(!o)return;let i=Dn.join(n,".qitqode-project-id"),l=Dn.join(o,"qitqode-project-id"),e=(T)=>F.access(T).then(()=>!0).catch(()=>!1);if(await e(i)){if(!await e(l)){let T=await F.readFile(i,"utf-8");await F.writeFile(l,T)}await F.unlink(i).catch(()=>{})}let A=Dn.join(o,"info","exclude");if(await F.mkdir(Dn.dirname(A),{recursive:!0}),!(await F.readFile(A,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await F.appendFile(A,`
|
|
3
3
|
.qitqode-project-id
|
|
4
4
|
`)}var Wr=c.create({service:"project"}),ue=262144,So=N.Literal("git"),kr=N.Struct({url:N.optional(N.String),override:N.optional(N.String),color:N.optional(N.String)}),qr=N.Struct({start:N.optional(N.String.annotate({description:"Startup script to run when creating a new workspace (worktree)"}))}),ye=N.Struct({created:N.Number,updated:N.Number,initialized:N.optional(N.Number)}),Vr=N.Struct({id:w,worktree:N.String,vcs:N.optional(So),name:N.optional(N.String),icon:N.optional(kr),commands:N.optional(qr),time:ye,sandboxes:N.Array(N.String)}).annotate({identifier:"Project"}).pipe(Fn((n)=>({zod:jn(n)}))),wr={Updated:zr.define("project.updated",Vr.zod)};function _n(n){let o=n.icon_url||n.icon_color?{url:n.icon_url??void 0,color:n.icon_color??void 0}:void 0;return{id:n.id,worktree:n.worktree,vcs:n.vcs?N.decodeUnknownSync(So)(n.vcs):void 0,name:n.name??void 0,icon:o,time:{created:n.time_created,updated:n.time_updated,initialized:n.time_initialized??void 0},sandboxes:n.sandboxes,commands:n.commands??void 0}}var fe=a.object({projectID:w.zod,name:a.string().optional(),icon:jn(kr).optional(),commands:jn(qr).optional()});class Gn extends vn.Service()("@qitqode/Project"){}var Fr=h.effect(Gn,r.gen(function*(){let n=yield*k.Service,o=yield*Zr.Path,i=yield*an.ChildProcessSpawner,l=r.fnUntraced(function*(t,u){return yield*Yr(i,t,u)},r.catch(()=>r.succeed({code:1,text:"",stderr:""}))),e=(t)=>r.sync(()=>In.use(t)),A=(t)=>r.sync(()=>Rn.emit("event",{directory:"global",project:t.id,payload:{type:wr.Updated.type,properties:t}})),_=N.decodeUnknownSync(N.optional(So))(nn.QITQODE_FAKE_VCS),T=(t,u)=>{if(!u)return t;if(u=u.replace(/[\r\n]+$/,""),!u)return t;if(u=k.windowsPath(u),o.isAbsolute(u))return o.normalize(u);return o.resolve(t,u)},M=yield*Ur.Scope,x=r.fn("Project.fromDirectory")(function*(t){Wr.info("fromDirectory",{directory:t});let u=yield*r.gen(function*(){if(nn.QITQODE_DISABLE_GIT)return{id:w.global,worktree:t,sandbox:t,vcs:_};let Y=(yield*n.up({targets:[".git"],start:t}).pipe(r.orDie))[0];if(!Y)return{id:w.global,worktree:"/",sandbox:"/",vcs:_};let en=o.dirname(Y),sn=process.env.HOME??process.env.USERPROFILE??cr.homedir();if(en===sn||Dn.parse(en).root===en)return Wr.warn("ignoring .git at home or filesystem root, snapshots disabled",{dotgit:Y}),{id:w.global,worktree:t,sandbox:t,vcs:_};let R=en,kn=yield*r.sync(()=>Mo("git")),Tn;if(!kn)return{id:Tn??w.global,worktree:R,sandbox:R,vcs:_};let qn=yield*l(["rev-parse","--git-common-dir"],{cwd:R});if(qn.code!==0)return{id:Tn??w.global,worktree:R,sandbox:R,vcs:_};let Hn=(()=>{let dn=T(R,qn.text.trim());return dn===R?R:o.dirname(dn)})();if(Tn==null)yield*r.promise(()=>me(R)),Tn=yield*r.promise(()=>Pr(R));let Vn=yield*l(["rev-parse","--show-toplevel"],{cwd:R});if(Vn.code!==0)return{id:Tn,worktree:R,sandbox:R,vcs:_};return R=T(R,Vn.text.trim()),{id:Tn,sandbox:R,worktree:Hn,vcs:"git"}}),D=yield*e((P)=>P.select().from(J).where(Z(J.id,u.id)).get()),I=D?_n(D):{id:u.id,worktree:u.worktree,vcs:u.vcs,sandboxes:[],time:{created:Date.now(),updated:Date.now()}};if(nn.QITQODE_EXPERIMENTAL_ICON_DISCOVERY)yield*C(I).pipe(r.ignore,r.forkIn(M));let O={...I,worktree:u.worktree,vcs:u.vcs,time:{...I.time,updated:Date.now()}};if(u.sandbox!==O.worktree&&!O.sandboxes.includes(u.sandbox))O.sandboxes.push(u.sandbox);if(O.sandboxes=yield*r.forEach(O.sandboxes,(P)=>n.exists(P).pipe(r.orDie,r.map((Y)=>Y?P:void 0)),{concurrency:16}).pipe(r.map((P)=>P.filter((Y)=>Y!==void 0))),yield*e((P)=>P.insert(J).values({id:O.id,worktree:O.worktree,vcs:O.vcs??null,name:O.name,icon_url:O.icon?.url,icon_color:O.icon?.color,time_created:O.time.created,time_updated:O.time.updated,time_initialized:O.time.initialized,sandboxes:O.sandboxes,commands:O.commands}).onConflictDoUpdate({target:J.id,set:{worktree:O.worktree,vcs:O.vcs??null,name:O.name,icon_url:O.icon?.url,icon_color:O.icon?.color,time_updated:O.time.updated,time_initialized:O.time.initialized,sandboxes:O.sandboxes,commands:O.commands}}).run()),u.id!==w.global)yield*e((P)=>P.update(fn).set({project_id:u.id}).where(Kn(Z(fn.project_id,w.global),Z(fn.directory,u.worktree))).run());return yield*A(O),{project:O,sandbox:u.sandbox}}),C=r.fn("Project.discover")(function*(t){if(t.vcs!=="git")return;if(t.icon?.override)return;if(t.icon?.url)return;let D=(yield*n.glob("**/favicon.{ico,png,svg,jpg,jpeg,webp}",{cwd:t.worktree,absolute:!0,include:"file"}).pipe(r.orDie)).sort((sn,R)=>sn.length-R.length)[0];if(!D)return;let I=yield*n.stat(D).pipe(r.orDie);if(Number(I.size)>ue)return;let O=yield*n.readFile(D).pipe(r.orDie),P=Buffer.from(O).toString("base64"),en=`data:${k.mimeType(D)};base64,${P}`;yield*$({projectID:t.id,icon:{url:en}})}),H=r.fn("Project.list")(function*(){return yield*e((t)=>t.select().from(J).all().map(_n))}),K=r.fn("Project.get")(function*(t){let u=yield*e((D)=>D.select().from(J).where(Z(J.id,t)).get());return u?_n(u):void 0}),$=r.fn("Project.update")(function*(t){let u=yield*e((I)=>I.update(J).set({name:t.name,icon_url:t.icon?.url,icon_color:t.icon?.color,commands:t.commands,time_updated:Date.now()}).where(Z(J.id,t.projectID)).returning().get());if(!u)throw Error(`Project not found: ${t.projectID}`);let D=_n(u);return yield*A(D),D}),Q=r.fn("Project.initGit")(function*(t){if(t.project.vcs==="git")return t.project;if(!(yield*r.sync(()=>Mo("git"))))throw Error("Git is not installed");let u=yield*l(["init","--quiet"],{cwd:t.directory});if(u.code!==0)throw Error(u.stderr.trim()||u.text.trim()||"Failed to initialize git repository");let{project:D}=yield*x(t.directory);return D}),L=r.fn("Project.setInitialized")(function*(t){yield*e((u)=>u.update(J).set({time_initialized:Date.now()}).where(Z(J.id,t)).run())}),g=r.fn("Project.sandboxes")(function*(t){let u=yield*e((I)=>I.select().from(J).where(Z(J.id,t)).get());if(!u)return[];let D=_n(u);return yield*r.forEach(D.sandboxes,(I)=>n.isDir(I).pipe(r.orDie,r.map((O)=>O?I:void 0)),{concurrency:16}).pipe(r.map((I)=>I.filter((O)=>O!==void 0)))}),s=r.fnUntraced(function*(t,u){let D=yield*e((I)=>I.update(J).set({sandboxes:u,time_updated:Date.now()}).where(Z(J.id,t)).returning().get());if(!D)throw Error(`Project not found: ${t}`);yield*A(_n(D))}),m=r.fn("Project.addSandbox")(function*(t,u){let D=yield*e((O)=>O.select().from(J).where(Z(J.id,t)).get());if(!D)throw Error(`Project not found: ${t}`);let I=[...D.sandboxes];if(!I.includes(u))I.push(u);yield*s(t,I)}),y=r.fn("Project.removeSandbox")(function*(t,u){let D=yield*e((O)=>O.select().from(J).where(Z(J.id,t)).get());if(!D)throw Error(`Project not found: ${t}`);let I=D.sandboxes.filter((O)=>O!==u);yield*s(t,I)});return Gn.of({fromDirectory:x,discover:C,list:H,get:K,update:$,initGit:Q,setInitialized:L,sandboxes:g,addSandbox:m,removeSandbox:y})})),Co=Fr.pipe(h.provide(bn),h.provide(k.defaultLayer),h.provide(Xr.layer));function ge(){return In.use((n)=>n.select().from(J).all().map((o)=>_n(o)))}function le(n){let o=In.use((i)=>i.select().from(J).where(Z(J.id,n)).get());if(!o)return;return _n(o)}function se(n){In.use((o)=>o.update(J).set({time_initialized:Date.now()}).where(Z(J.id,n)).run())}import{parse as _e}from"path";var rn=gn.create("instance");hr(()=>rn.use());var tn=new Map,Ne=ni(Gn,Co),pe=new Set(["/etc","/proc","/sys","/dev","/boot","/root","/var","/private/etc","/private/var"]);function Ae(n){if(n===_e(n).root)return"filesystem root is not a valid project directory";for(let o of pe)if(n===o||k.contains(o,n))return"target is a protected system directory";return null}function Te(n){let o=Ae(n);if(o)throw Error("Access denied: "+o)}var Pn={all:void 0};function ar(n){return En(async()=>{let o=n.project&&n.worktree?{directory:n.directory,worktree:n.worktree,project:n.project}:await Ne.runPromise((i)=>i.fromDirectory(n.directory)).then(({project:i,sandbox:l})=>({directory:n.directory,worktree:l,project:i}));return await rn.provide(o,async()=>{await n.init?.()}),o})}function br(n,o){let i=o.catch((l)=>{if(tn.get(n)===i)tn.delete(n);throw l});return tn.set(n,i),i}var on={async provide(n){let o=k.resolve(n.directory);Te(o);let i=tn.get(o);if(!i)c.Default.info("creating instance",{directory:o}),i=br(o,ar({directory:o,init:n.init}));let l=await i;return rn.provide(l,async()=>{return n.fn()})},get current(){return rn.use()},get directory(){return rn.use().directory},get worktree(){return rn.use().worktree},get project(){return rn.use().project},containsPath(n,o){let i=o??on;if(k.contains(i.directory,n))return!0;if(i.worktree==="/")return!1;return k.contains(i.worktree,n)},bind(n){let o=rn.use();return(...i)=>rn.provide(o,()=>n(...i))},restore(n,o){return rn.provide(n,o)},async reload(n){let o=k.resolve(n.directory);c.Default.info("reloading instance",{directory:o}),await Go(o),tn.delete(o);let i=br(o,ar({...n,directory:o}));return Rn.emit("event",{directory:o,project:n.project?.id,workspace:Nn.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:o}}}),await i},async dispose(){let{directory:n,project:o}=on;c.Default.info("disposing instance",{directory:n}),await Go(n),tn.delete(n),Rn.emit("event",{directory:n,project:o.id,workspace:Nn.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:n}}})},async disposeAll(){if(Pn.all)return Pn.all;return Pn.all=En(async()=>{c.Default.info("disposing all instances");let n=[...tn.entries()];for(let[o,i]of n){if(tn.get(o)!==i)continue;let l=await i.catch((e)=>{c.Default.warn("instance dispose failed",{key:o,error:e});return});if(!l){if(tn.get(o)===i)tn.delete(o);continue}if(tn.get(o)!==i)continue;await rn.provide(l,async()=>{await on.dispose()})}}).finally(()=>{Pn.all=void 0}),Pn.all}};var oi="~qitqode/InstanceState",$e=(n)=>{try{return on.bind(n)}catch(l){if(!(l instanceof gn.NotFound))throw l}let o=Ln.getCurrent(),i=o?vn.getReferenceUnsafe(o.context,Wn):void 0;if(!i)return n;return(...l)=>on.restore(i,()=>n(...l))},Ho=r.gen(function*(){return(yield*Wn)??on.current}),De=r.gen(function*(){return(yield*hn)??Nn.workspaceID}),no=r.map(Ho,(n)=>n.directory),ve=(n)=>r.gen(function*(){let o=yield*Jn.make({capacity:Number.POSITIVE_INFINITY,lookup:()=>r.gen(function*(){return yield*n(yield*Ho)})}),i=xr((l)=>r.runPromise(Jn.invalidate(o,l).pipe(r.provide(ri))));return yield*r.addFinalizer(()=>r.sync(i)),{[oi]:oi,cache:o}}),xo=(n)=>r.gen(function*(){return yield*Jn.get(n.cache,yield*no)}),Be=(n,o)=>r.map(xo(n),o),Qe=(n,o)=>r.flatMap(xo(n),o),Ie=(n)=>r.gen(function*(){return yield*Jn.has(n.cache,yield*no)}),Le=(n)=>r.gen(function*(){return yield*Jn.invalidate(n.cache,yield*no)});var ei={};On(ei,{make:()=>de});function ii(n,o,i){if(n&&o!==void 0)return Nn.restore(o,()=>on.restore(n,i));if(n)return on.restore(n,i);if(o!==void 0)return Nn.restore(o,i);return i()}function de(){return r.gen(function*(){let n=yield*r.context(),i=(yield*Wn)??(()=>{try{return on.current}catch(_){if(!(_ instanceof gn.NotFound))throw _}})(),l=(yield*hn)??Nn.workspaceID,e=(_)=>ti(_,{instance:i,workspace:l}),A=(_)=>e(_).pipe(r.provide(n));return{promise:(_)=>ii(i,l,()=>r.runPromise(A(_))),fork:(_)=>ii(i,l,()=>r.runFork(A(_)))}})}var mi={};On(mi,{make:()=>Ge,Cancelled:()=>Zn});class Zn extends N.TaggedErrorClass()("RunnerCancelled",{}){}var Ge=(n,o)=>{let i=pn.makeUnsafe({_tag:"Idle"}),l=o?.onIdle??r.void,e=o?.onBusy??r.void,A=o?.onInterrupt,_=0,T=()=>pn.getUnsafe(i),M=()=>{return _+=1,_},x=(m,y)=>Xn.isFailure(y)&&Ko.hasInterruptsOnly(y.cause)?ln.fail(m,new Zn).pipe(r.asVoid):ln.done(m,y).pipe(r.asVoid),C=()=>pn.modify(i,(m)=>[m._tag==="Idle"?l:r.void,m]).pipe(r.flatten),H=(m,y,t)=>pn.modify(i,(u)=>[r.gen(function*(){if(u._tag==="Running"&&u.run.id===m)yield*l;yield*x(y,t)}),u._tag==="Running"&&u.run.id===m?{_tag:"Idle"}:u]).pipe(r.flatten),K=(m,y)=>r.gen(function*(){let t=M(),u=yield*m.pipe(r.onExit((D)=>H(t,y,D)),r.forkIn(n));return{id:t,done:y,fiber:u}}),$=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){if(y._tag==="Shell"&&y.shell.id===m)return[l,{_tag:"Idle"}];if(y._tag==="ShellThenRun"&&y.shell.id===m){let t=yield*K(y.run.work,y.run.done);return[r.void,{_tag:"Running",run:t}]}return[r.void,y]})).pipe(r.flatten),Q=(m)=>Ln.interrupt(m.fiber),L=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){switch(y._tag){case"Running":case"ShellThenRun":if(o?.onReentryWarn)yield*o.onReentryWarn({label:o.label??"(unlabeled)",existingRunId:y.run.id});return[ln.await(y.run.done),y];case"Shell":{let t={id:M(),done:yield*ln.make(),work:m};return[ln.await(t.done),{_tag:"ShellThenRun",shell:y.shell,run:t}]}case"Idle":{let t=yield*ln.make(),u=yield*K(m,t);return[ln.await(t),{_tag:"Running",run:u}]}}})).pipe(r.flatten,r.catch((y)=>y instanceof Zn?A??r.die(y):r.fail(y))),g=(m)=>pn.modifyEffect(i,r.fnUntraced(function*(y){if(y._tag!=="Idle")return[r.sync(()=>{if(o?.busy)o.busy();throw Error("Runner is busy")}),y];yield*e;let t=M(),u=yield*m.pipe(r.ensuring($(t)),r.forkChild),D={id:t,fiber:u};return[r.gen(function*(){let I=yield*Ln.await(u);if(Xn.isSuccess(I))return I.value;if(Ko.hasInterruptsOnly(I.cause)&&A)return yield*A;return yield*r.failCause(I.cause)}),{_tag:"Shell",shell:D}]})).pipe(r.flatten),s=pn.modify(i,(m)=>{switch(m._tag){case"Idle":return[r.void,m];case"Running":return[r.gen(function*(){yield*Ln.interrupt(m.run.fiber);let y=yield*Ln.await(m.run.fiber);yield*x(m.run.done,y),yield*ln.await(m.run.done).pipe(r.exit,r.asVoid),yield*C()}),{_tag:"Idle"}];case"Shell":return[r.gen(function*(){yield*Q(m.shell),yield*C()}),{_tag:"Idle"}];case"ShellThenRun":return[r.gen(function*(){yield*ln.fail(m.run.done,new Zn).pipe(r.asVoid),yield*Q(m.shell),yield*C()}),{_tag:"Idle"}]}}).pipe(r.flatten);return{get state(){return T()},get busy(){return T()._tag!=="Idle"},ensureRunning:L,startShell:g,cancel:s}};import{Database as Je}from"bun:sqlite";function yi(n){let o=new Je(n,{create:!0});return ui({client:o})}var Me=ro.create("NotFoundError",a.object({message:a.string()})),fi=c.create({service:"db"});function li(){if(["latest","beta","prod"].includes(Ro)||nn.QITQODE_DISABLE_CHANNEL_DB)return oo.join($n.Path.data,"qitqode.db");let n=Ro.replace(/[^a-zA-Z0-9._-]/g,"-");return oo.join($n.Path.data,`qitqode-${n}.db`)}var Eo=En(()=>{if(nn.QITQODE_DB){if(nn.QITQODE_DB===":memory:"||oo.isAbsolute(nn.QITQODE_DB))return nn.QITQODE_DB;return oo.join($n.Path.data,nn.QITQODE_DB)}return li()}),Mn=gi(()=>{fi.info("opening database",{path:Eo});let n=yi(Eo);n.run("PRAGMA journal_mode = WAL"),n.run("PRAGMA synchronous = NORMAL"),n.run("PRAGMA busy_timeout = 5000"),n.run("PRAGMA cache_size = -64000"),n.run("PRAGMA foreign_keys = ON"),n.run("PRAGMA wal_checkpoint(PASSIVE)");let o=[{sql:"CREATE TABLE `project` (\n\t`id` text PRIMARY KEY,\n\t`worktree` text NOT NULL,\n\t`vcs` text,\n\t`name` text,\n\t`icon_url` text,\n\t`icon_color` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`time_initialized` integer,\n\t`sandboxes` text NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `message` (\n\t`id` text PRIMARY KEY,\n\t`session_id` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_message_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `part` (\n\t`id` text PRIMARY KEY,\n\t`message_id` text NOT NULL,\n\t`session_id` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_part_message_id_message_id_fk` FOREIGN KEY (`message_id`) REFERENCES `message`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `permission` (\n\t`project_id` text PRIMARY KEY,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_permission_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `session` (\n\t`id` text PRIMARY KEY,\n\t`project_id` text NOT NULL,\n\t`parent_id` text,\n\t`slug` text NOT NULL,\n\t`directory` text NOT NULL,\n\t`title` text NOT NULL,\n\t`version` text NOT NULL,\n\t`share_url` text,\n\t`summary_additions` integer,\n\t`summary_deletions` integer,\n\t`summary_files` integer,\n\t`summary_diffs` text,\n\t`revert` text,\n\t`permission` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`time_compacting` integer,\n\t`time_archived` integer,\n\tCONSTRAINT `fk_session_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `todo` (\n\t`session_id` text NOT NULL,\n\t`content` text NOT NULL,\n\t`status` text NOT NULL,\n\t`priority` text NOT NULL,\n\t`position` integer NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `todo_pk` PRIMARY KEY(`session_id`, `position`),\n\tCONSTRAINT `fk_todo_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE TABLE `session_share` (\n\t`session_id` text PRIMARY KEY,\n\t`id` text NOT NULL,\n\t`secret` text NOT NULL,\n\t`url` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `fk_session_share_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE INDEX `message_session_idx` ON `message` (`session_id`);--> statement-breakpoint\nCREATE INDEX `part_message_idx` ON `part` (`message_id`);--> statement-breakpoint\nCREATE INDEX `part_session_idx` ON `part` (`session_id`);--> statement-breakpoint\nCREATE INDEX `session_project_idx` ON `session` (`project_id`);--> statement-breakpoint\nCREATE INDEX `session_parent_idx` ON `session` (`parent_id`);--> statement-breakpoint\nCREATE INDEX `todo_session_idx` ON `todo` (`session_id`);",timestamp:1769552633000,name:"20260127222353_familiar_lady_ursula"},{sql:"ALTER TABLE `project` ADD `commands` text;",timestamp:1770830228000,name:"20260211171708_add_project_commands"},{sql:"CREATE TABLE `control_account` (\n\t`email` text NOT NULL,\n\t`url` text NOT NULL,\n\t`access_token` text NOT NULL,\n\t`refresh_token` text NOT NULL,\n\t`token_expiry` integer,\n\t`active` integer NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\tCONSTRAINT `control_account_pk` PRIMARY KEY(`email`, `url`)\n);\n",timestamp:1770993676000,name:"20260213144116_wakeful_the_professor"},{sql:"CREATE TABLE `workspace` (\n\t`id` text PRIMARY KEY,\n\t`branch` text,\n\t`project_id` text NOT NULL,\n\t`config` text NOT NULL,\n\tCONSTRAINT `fk_workspace_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n",timestamp:1772056728000,name:"20260225215848_workspace"},{sql:"ALTER TABLE `session` ADD `workspace_id` text;--> statement-breakpoint\nCREATE INDEX `session_workspace_idx` ON `session` (`workspace_id`);",timestamp:1772228279000,name:"20260227213759_add_session_workspace_id"},{sql:"CREATE TABLE `account` (\n\t`id` text PRIMARY KEY,\n\t`email` text NOT NULL,\n\t`url` text NOT NULL,\n\t`access_token` text NOT NULL,\n\t`refresh_token` text NOT NULL,\n\t`token_expiry` integer,\n\t`selected_org_id` text,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `account_state` (\n\t`id` integer PRIMARY KEY NOT NULL,\n\t`active_account_id` text,\n\tFOREIGN KEY (`active_account_id`) REFERENCES `account`(`id`) ON UPDATE no action ON DELETE set null\n);\n",timestamp:1772310750000,name:"20260228203230_blue_harpoon"},{sql:"ALTER TABLE `workspace` ADD `type` text NOT NULL;--> statement-breakpoint\nALTER TABLE `workspace` ADD `name` text;--> statement-breakpoint\nALTER TABLE `workspace` ADD `directory` text;--> statement-breakpoint\nALTER TABLE `workspace` ADD `extra` text;--> statement-breakpoint\nALTER TABLE `workspace` DROP COLUMN `config`;",timestamp:1772579546000,name:"20260303231226_add_workspace_fields"},{sql:"ALTER TABLE `account_state` ADD `active_org_id` text;--> statement-breakpoint\nUPDATE `account_state` SET `active_org_id` = (SELECT `selected_org_id` FROM `account` WHERE `account`.`id` = `account_state`.`active_account_id`);--> statement-breakpoint\nALTER TABLE `account` DROP COLUMN `selected_org_id`;\n",timestamp:1773097200000,name:"20260309230000_move_org_to_state"},{sql:"DROP INDEX IF EXISTS `message_session_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `part_message_idx`;--> statement-breakpoint\nCREATE INDEX `message_session_time_created_id_idx` ON `message` (`session_id`,`time_created`,`id`);--> statement-breakpoint\nCREATE INDEX `part_message_id_id_idx` ON `part` (`message_id`,`id`);",timestamp:1773290071000,name:"20260312043431_session_message_cursor"},{sql:"CREATE TABLE `event_sequence` (\n\t`aggregate_id` text PRIMARY KEY,\n\t`seq` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE TABLE `event` (\n\t`id` text PRIMARY KEY,\n\t`aggregate_id` text NOT NULL,\n\t`seq` integer NOT NULL,\n\t`type` text NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_event_aggregate_id_event_sequence_aggregate_id_fk` FOREIGN KEY (`aggregate_id`) REFERENCES `event_sequence`(`aggregate_id`) ON DELETE CASCADE\n);\n",timestamp:1774309702000,name:"20260323234822_events"},{sql:"PRAGMA foreign_keys=OFF;--> statement-breakpoint\nCREATE TABLE `__new_workspace` (\n\t`id` text PRIMARY KEY,\n\t`type` text NOT NULL,\n\t`name` text DEFAULT '' NOT NULL,\n\t`branch` text,\n\t`directory` text,\n\t`extra` text,\n\t`project_id` text NOT NULL,\n\tCONSTRAINT `fk_workspace_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nINSERT INTO `__new_workspace`(`id`, `type`, `branch`, `name`, `directory`, `extra`, `project_id`) SELECT `id`, `type`, `branch`, `name`, `directory`, `extra`, `project_id` FROM `workspace`;--> statement-breakpoint\nDROP TABLE `workspace`;--> statement-breakpoint\nALTER TABLE `__new_workspace` RENAME TO `workspace`;--> statement-breakpoint\nPRAGMA foreign_keys=ON;",timestamp:1775843113000,name:"20260410174513_workspace-name"},{sql:"CREATE TABLE `session_entry` (\n\t`id` text PRIMARY KEY,\n\t`session_id` text NOT NULL,\n\t`type` text NOT NULL,\n\t`time_created` integer NOT NULL,\n\t`time_updated` integer NOT NULL,\n\t`data` text NOT NULL,\n\tCONSTRAINT `fk_session_entry_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n);\n--> statement-breakpoint\nCREATE INDEX `session_entry_session_idx` ON `session_entry` (`session_id`);--> statement-breakpoint\nCREATE INDEX `session_entry_session_type_idx` ON `session_entry` (`session_id`,`type`);--> statement-breakpoint\nCREATE INDEX `session_entry_time_created_idx` ON `session_entry` (`time_created`);",timestamp:1776103196000,name:"20260413175956_chief_energizer"},{sql:"ALTER TABLE `session` ADD `context_from` text;--> statement-breakpoint\nALTER TABLE `session` ADD `context_watermark` text;--> statement-breakpoint\nCREATE INDEX `session_context_from_idx` ON `session` (`context_from`);\n",timestamp:1776873600000,name:"20260422160000_context_inheritance"},{sql:"CREATE TABLE `task_registry` (\n `id` text PRIMARY KEY,\n `parent_session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `status` text NOT NULL,\n `agent` text NOT NULL,\n `description` text NOT NULL,\n `context_mode` text NOT NULL,\n `background` integer NOT NULL,\n `last_turn_time` integer NOT NULL,\n `turn_count` integer NOT NULL DEFAULT 0,\n `error` text,\n `time_completed` integer,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `task_registry_parent_idx` ON `task_registry` (`parent_session_id`);--> statement-breakpoint\nCREATE INDEX `task_registry_status_idx` ON `task_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `task_registry_status_last_turn_idx` ON `task_registry` (`status`, `last_turn_time`);\n",timestamp:1776877200000,name:"20260422170000_task_registry"},{sql:"DROP INDEX IF EXISTS `session_entry_session_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `session_entry_session_type_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `session_entry_time_created_idx`;--> statement-breakpoint\nDROP TABLE IF EXISTS `session_entry`;\n",timestamp:1776956061000,name:"20260423145421_remove_session_entry"},{sql:"DROP INDEX IF EXISTS `task_registry_parent_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `task_registry_status_idx`;--> statement-breakpoint\nDROP INDEX IF EXISTS `task_registry_status_last_turn_idx`;--> statement-breakpoint\nALTER TABLE `task_registry` RENAME TO `actor_registry`;--> statement-breakpoint\nCREATE INDEX `actor_registry_parent_idx` ON `actor_registry` (`parent_session_id`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_idx` ON `actor_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_last_turn_idx` ON `actor_registry` (`status`, `last_turn_time`);\n",timestamp:1778803200000,name:"20260515000000_actor_rename"},{sql:"CREATE TABLE `memory_fts` (\n `path` text PRIMARY KEY NOT NULL,\n `scope` text NOT NULL,\n `scope_id` text DEFAULT '' NOT NULL,\n `type` text NOT NULL,\n `body` text NOT NULL,\n `fingerprint` text NOT NULL,\n `last_indexed_at` integer NOT NULL\n);\n--> statement-breakpoint\nCREATE INDEX `memory_fts_scope_idx` ON `memory_fts` (`scope`, `scope_id`);\n--> statement-breakpoint\nCREATE INDEX `memory_fts_type_idx` ON `memory_fts` (`type`);\n--> statement-breakpoint\nCREATE VIRTUAL TABLE `memory_fts_idx` USING fts5(\n body,\n content='memory_fts',\n content_rowid='rowid',\n tokenize='unicode61 remove_diacritics 1'\n);\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.rowid;\nEND;\n--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.rowid;\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n",timestamp:1778806800000,name:"20260515010000_memory_fts"},{sql:"CREATE TABLE `task` (\n `id` text NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `parent_task_id` text,\n `kind` text NOT NULL DEFAULT 'user',\n `status` text NOT NULL,\n `focus` integer NOT NULL DEFAULT 0,\n `summary` text NOT NULL,\n `created_at` integer NOT NULL,\n `last_event_at` integer NOT NULL,\n `ended_at` integer,\n `cleanup_after` integer,\n PRIMARY KEY (`session_id`, `id`)\n);--> statement-breakpoint\nCREATE INDEX `task_session_idx` ON `task` (`session_id`);--> statement-breakpoint\nCREATE INDEX `task_parent_idx` ON `task` (`session_id`, `parent_task_id`);--> statement-breakpoint\nCREATE INDEX `task_status_idx` ON `task` (`status`);--> statement-breakpoint\nCREATE INDEX `task_kind_idx` ON `task` (`kind`);--> statement-breakpoint\nCREATE UNIQUE INDEX `task_focus_per_session_idx` ON `task` (`session_id`) WHERE focus = 1;--> statement-breakpoint\nCREATE TABLE `task_event` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `task_id` text NOT NULL,\n `at` integer NOT NULL,\n `kind` text NOT NULL,\n `summary` text,\n FOREIGN KEY (`session_id`, `task_id`) REFERENCES `task`(`session_id`, `id`) ON DELETE CASCADE\n);--> statement-breakpoint\nCREATE INDEX `task_event_task_idx` ON `task_event` (`session_id`, `task_id`, `at`);\n",timestamp:1778810400000,name:"20260515020000_user_task"},{sql:"ALTER TABLE `session` ADD `last_checkpoint_message_id` text;\n",timestamp:1779148800000,name:"20260519000000_last_checkpoint_message_id"},{sql:"ALTER TABLE `message` ADD `agent_id` text;--> statement-breakpoint\nCREATE INDEX `message_session_agent_idx` ON `message` (`session_id`,`agent_id`,`id`);\n",timestamp:1779321600000,name:"20260521000000_message_agent_id"},{sql:"DROP TABLE `actor_registry`;--> statement-breakpoint\nCREATE TABLE `actor_registry` (\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `actor_id` text NOT NULL,\n `mode` text NOT NULL,\n `parent_actor_id` text,\n `status` text NOT NULL,\n `agent` text NOT NULL,\n `description` text NOT NULL,\n `context_mode` text NOT NULL,\n `context_watermark` text,\n `background` integer NOT NULL,\n `tools` text,\n `last_turn_time` integer NOT NULL,\n `turn_count` integer NOT NULL DEFAULT 0,\n `error` text,\n `time_completed` integer,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n PRIMARY KEY (`session_id`, `actor_id`)\n);--> statement-breakpoint\nCREATE INDEX `actor_registry_session_agent_idx` ON `actor_registry` (`session_id`, `agent`);--> statement-breakpoint\nCREATE INDEX `actor_registry_session_parent_idx` ON `actor_registry` (`session_id`, `parent_actor_id`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_idx` ON `actor_registry` (`status`);--> statement-breakpoint\nCREATE INDEX `actor_registry_status_last_turn_idx` ON `actor_registry` (`status`, `last_turn_time`);\n",timestamp:1779321660000,name:"20260521000100_actor_registry_v6"},{sql:"DROP TRIGGER IF EXISTS `memory_fts_ai`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_ad`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_au`;--> statement-breakpoint\nDROP TABLE IF EXISTS `memory_fts_idx`;--> statement-breakpoint\nDROP TABLE IF EXISTS `memory_fts`;--> statement-breakpoint\nCREATE TABLE `memory_fts` (\n `id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,\n `path` text NOT NULL UNIQUE,\n `scope` text NOT NULL,\n `scope_id` text DEFAULT '' NOT NULL,\n `type` text NOT NULL,\n `body` text NOT NULL,\n `fingerprint` text NOT NULL,\n `last_indexed_at` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `memory_fts_scope_idx` ON `memory_fts` (`scope`, `scope_id`);--> statement-breakpoint\nCREATE INDEX `memory_fts_type_idx` ON `memory_fts` (`type`);--> statement-breakpoint\nCREATE VIRTUAL TABLE `memory_fts_idx` USING fts5(\n body,\n content='memory_fts',\n content_rowid='id',\n tokenize='unicode61 remove_diacritics 1'\n);--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.id;\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n DELETE FROM `memory_fts_idx` WHERE rowid = OLD.id;\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;\n",timestamp:1779325200000,name:"20260521010000_memory_fts_v6"},{sql:"-- Fix v6.1 trigger pattern: external content FTS5 vtab requires the 'delete'\n-- magic command to remove OLD body's tokens, NOT a plain DELETE FROM the vtab.\n-- The previous DELETE FROM pattern was contentless-mode syntax misapplied to\n-- external-content mode, leaving stale tokens accumulating until vtab corrupts.\nDROP TRIGGER IF EXISTS `memory_fts_ai`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_ad`;--> statement-breakpoint\nDROP TRIGGER IF EXISTS `memory_fts_au`;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ai` AFTER INSERT ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_ad` AFTER DELETE ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(`memory_fts_idx`, rowid, body) VALUES('delete', OLD.id, OLD.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `memory_fts_au` AFTER UPDATE ON `memory_fts` BEGIN\n INSERT INTO `memory_fts_idx`(`memory_fts_idx`, rowid, body) VALUES('delete', OLD.id, OLD.body);\n INSERT INTO `memory_fts_idx`(rowid, body) VALUES (NEW.id, NEW.body);\nEND;\n",timestamp:1779328800000,name:"20260521020000_memory_fts_triggers"},{sql:"UPDATE `message` SET `agent_id` = 'main' WHERE `agent_id` IS NULL;--> statement-breakpoint\nCREATE TABLE `message_new` (\n `id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `agent_id` text NOT NULL DEFAULT 'main',\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n `data` text NOT NULL\n);--> statement-breakpoint\nINSERT INTO `message_new` SELECT `id`, `session_id`, COALESCE(`agent_id`, 'main'), `time_created`, `time_updated`, `data` FROM `message`;--> statement-breakpoint\nDROP TABLE `message`;--> statement-breakpoint\nALTER TABLE `message_new` RENAME TO `message`;--> statement-breakpoint\nCREATE INDEX `message_session_time_created_id_idx` ON `message` (`session_id`,`time_created`,`id`);--> statement-breakpoint\nCREATE INDEX `message_session_agent_idx` ON `message` (`session_id`,`agent_id`,`id`);\n",timestamp:1779753600000,name:"20260526000000_agent_id_main"},{sql:"ALTER TABLE `actor_registry` ADD COLUMN `last_outcome` text;--> statement-breakpoint\nALTER TABLE `actor_registry` ADD COLUMN `lifecycle` text NOT NULL DEFAULT 'ephemeral';--> statement-breakpoint\nALTER TABLE `actor_registry` RENAME COLUMN `error` TO `last_error`;--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'success' WHERE `status` = 'completed';--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'failure' WHERE `status` = 'failed';--> statement-breakpoint\nUPDATE `actor_registry` SET `last_outcome` = 'cancelled' WHERE `status` = 'cancelled';--> statement-breakpoint\nUPDATE `actor_registry` SET `status` = 'idle' WHERE `status` IN ('completed','failed','cancelled');--> statement-breakpoint\nUPDATE `actor_registry` SET `lifecycle` = CASE `mode` WHEN 'peer' THEN 'persistent' WHEN 'main' THEN 'persistent' ELSE 'ephemeral' END;\n",timestamp:1779840000000,name:"20260527000000_actor_lifecycle"},{sql:"CREATE TABLE `inbox` (\n `id` text PRIMARY KEY NOT NULL,\n `receiver_session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `receiver_actor_id` text NOT NULL,\n `sender_session_id` text,\n `sender_actor_id` text,\n `type` text NOT NULL DEFAULT 'text',\n `content` text NOT NULL,\n `created_at` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `inbox_receiver_idx` ON `inbox` (`receiver_session_id`,`receiver_actor_id`,`id`);--> statement-breakpoint\nCREATE INDEX `inbox_created_idx` ON `inbox` (`created_at`);\n",timestamp:1779840060000,name:"20260527000100_inbox"},{sql:"-- todo: drop priority column\nALTER TABLE `todo` DROP COLUMN `priority`;\n--> statement-breakpoint\n\n-- task: drop focus-dependent index before dropping its column\nDROP INDEX `task_focus_per_session_idx`;\n--> statement-breakpoint\nDROP INDEX `task_kind_idx`;\n--> statement-breakpoint\nALTER TABLE `task` DROP COLUMN `focus`;\n--> statement-breakpoint\nALTER TABLE `task` DROP COLUMN `kind`;\n--> statement-breakpoint\n\n-- migrate status values: proposed/active -> open\nUPDATE `task` SET `status` = 'open' WHERE `status` IN ('proposed', 'active');\n",timestamp:1780012800000,name:"20260529000000_task_todo_redesign"},{sql:"ALTER TABLE `task` ADD COLUMN `owner` text;\n",timestamp:1780444800000,name:"20260603000000_task_in_progress_owner"},{sql:"CREATE TABLE `workflow_run` (\n `id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL REFERENCES `session`(`id`) ON DELETE CASCADE,\n `name` text NOT NULL,\n `status` text NOT NULL,\n `running` integer NOT NULL DEFAULT 0,\n `succeeded` integer NOT NULL DEFAULT 0,\n `failed` integer NOT NULL DEFAULT 0,\n `current_phase` text,\n `parent_actor_id` text,\n `args` text,\n `error` text,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `workflow_run_session_idx` ON `workflow_run` (`session_id`);--> statement-breakpoint\nCREATE INDEX `workflow_run_status_idx` ON `workflow_run` (`status`);\n",timestamp:1780444800000,name:"20260603000000_workflow_run"},{sql:"ALTER TABLE `workflow_run` ADD COLUMN `script_sha` text;\n",timestamp:1780531200000,name:"20260604000000_workflow_script_sha"},{sql:"CREATE TABLE `claude_import` (\n `source_uuid` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL,\n `source_path` text NOT NULL,\n `source_mtime` integer NOT NULL,\n `time_imported` integer NOT NULL\n);\n",timestamp:1780876800000,name:"20260608000000_claude_import"},{sql:"ALTER TABLE `claude_import` ADD `message_ids` text;\n",timestamp:1780880400000,name:"20260608010000_claude_import_message_ids"},{sql:"CREATE TABLE `history_fts` (\n `part_id` text PRIMARY KEY NOT NULL,\n `session_id` text NOT NULL,\n `message_id` text NOT NULL,\n `project_id` text NOT NULL,\n `kind` text NOT NULL,\n `tool_name` text,\n `body` text NOT NULL,\n `time_created` integer NOT NULL\n);--> statement-breakpoint\nCREATE INDEX `history_fts_session_idx` ON `history_fts` (`session_id`, `time_created`);--> statement-breakpoint\nCREATE INDEX `history_fts_project_idx` ON `history_fts` (`project_id`, `time_created`);--> statement-breakpoint\nCREATE INDEX `history_fts_message_idx` ON `history_fts` (`message_id`);--> statement-breakpoint\nCREATE VIRTUAL TABLE `history_fts_idx` USING fts5(\n body,\n content='history_fts',\n content_rowid='rowid',\n tokenize='unicode61 remove_diacritics 1'\n);--> statement-breakpoint\nCREATE TRIGGER `history_fts_ai` AFTER INSERT ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `history_fts_ad` AFTER DELETE ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(`history_fts_idx`, rowid, body) VALUES('delete', OLD.rowid, OLD.body);\nEND;--> statement-breakpoint\nCREATE TRIGGER `history_fts_au` AFTER UPDATE ON `history_fts` BEGIN\n INSERT INTO `history_fts_idx`(`history_fts_idx`, rowid, body) VALUES('delete', OLD.rowid, OLD.body);\n INSERT INTO `history_fts_idx`(rowid, body) VALUES (NEW.rowid, NEW.body);\nEND;\n",timestamp:1780963200000,name:"20260609000000_history_fts"},{sql:"ALTER TABLE `workflow_run` ADD COLUMN `agent_timeout_ms` integer;\n",timestamp:1781046000000,name:"20260609230000_workflow_agent_timeout"},{sql:"CREATE TABLE `external_import` (\n `source` text NOT NULL,\n `source_key` text NOT NULL,\n `session_id` text NOT NULL,\n `source_path` text NOT NULL,\n `source_mtime` integer NOT NULL,\n `time_imported` integer NOT NULL,\n `message_ids` text,\n PRIMARY KEY (`source`, `source_key`)\n);\n\nINSERT INTO `external_import` (`source`, `source_key`, `session_id`, `source_path`, `source_mtime`, `time_imported`, `message_ids`)\nSELECT 'cc', `source_uuid`, `session_id`, `source_path`, `source_mtime`, `time_imported`, `message_ids`\nFROM `claude_import`;\n\nDROP TABLE `claude_import`;\n",timestamp:1781222400000,name:"20260612000000_external_import"}];if(o.length>0){if(fi.info("applying migrations",{count:o.length,mode:"bundled"}),nn.QITQODE_SKIP_MIGRATIONS)for(let i of o)i.sql="select 1;";ao(n,o)}return n});function Se(){Mn().$client.close(),Mn.reset()}var Yn=gn.create("database");function Ce(n){try{return n(Yn.use().tx)}catch(o){if(o instanceof gn.NotFound){let i=[],l=Yn.provide({effects:i,tx:Mn()},()=>n(Mn()));for(let e of i)e();return l}throw o}}function He(n){let o=Un.bind(n);try{Yn.use().effects.push(o)}catch{o()}}function xe(n,o){try{return n(Yn.use().tx)}catch(i){if(i instanceof gn.NotFound){let l=[],e=Un.bind((_)=>Yn.provide({tx:_,effects:l},()=>n(_))),A=Mn().transaction(e,{behavior:o?.behavior});for(let _ of l)_();return A}throw i}}var Oi={};On(Oi,{layer:()=>Ti,defaultLayer:()=>we,Service:()=>to,NotFoundError:()=>Zo});import X from"path";var Sn={};On(Sn,{layer:()=>pi,defaultLayer:()=>Ee,Service:()=>io,Git:()=>Sn});var Ke=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],zn=(n)=>n.text().trim(),Po=(n)=>n.split("\x00").filter(Boolean),Re=(n)=>({exitCode:1,text:()=>"",stdout:Buffer.alloc(0),stderr:Buffer.from(n instanceof Error?n.message:String(n))}),si=(n)=>{if(n==="??")return"added";if(n.includes("U"))return"modified";if(n.includes("A")&&!n.includes("D"))return"added";if(n.includes("D")&&!n.includes("A"))return"deleted";return"modified"};class io extends vn.Service()("@qitqode/Git"){}var pi=h.effect(io,r.gen(function*(){let n=yield*an.ChildProcessSpawner,o=r.fn("Git.run")(function*(g,s){let m=_i.make("git",[...Ke,...g],{cwd:s.cwd,env:s.env,extendEnv:!0,stdin:"ignore",stdout:"pipe",stderr:"pipe"}),y=yield*Ni(n,m);return{exitCode:y.code,text:()=>y.text,stdout:Buffer.from(y.text),stderr:Buffer.from(y.stderr)}},r.scoped,r.catch((g)=>r.succeed(Re(g)))),i=r.fn("Git.text")(function*(g,s){return(yield*o(g,s)).text()}),l=r.fn("Git.lines")(function*(g,s){return(yield*i(g,s)).split(/\r?\n/).map((m)=>m.trim()).filter(Boolean)}),e=r.fnUntraced(function*(g){return yield*l(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:g})}),A=r.fnUntraced(function*(g,s){let m=yield*o(["config","init.defaultBranch"],{cwd:g}),y=zn(m);if(!y||!s.includes(y))return;return{name:y,ref:y}}),_=r.fnUntraced(function*(g){let s=yield*l(["remote"],{cwd:g});if(s.includes("origin"))return"origin";if(s.length===1)return s[0];if(s.includes("upstream"))return"upstream";return s[0]}),T=r.fn("Git.branch")(function*(g){let s=yield*o(["symbolic-ref","--quiet","--short","HEAD"],{cwd:g});if(s.exitCode!==0)return;return zn(s)||void 0}),M=r.fn("Git.prefix")(function*(g){let s=yield*o(["rev-parse","--show-prefix"],{cwd:g});if(s.exitCode!==0)return"";return zn(s)}),x=r.fn("Git.defaultBranch")(function*(g){let s=yield*_(g);if(s){let t=yield*o(["symbolic-ref",`refs/remotes/${s}/HEAD`],{cwd:g});if(t.exitCode===0){let u=zn(t).replace(/^refs\/remotes\//,""),D=u.startsWith(`${s}/`)?u.slice(`${s}/`.length):"";if(D)return{name:D,ref:u}}}let m=yield*e(g),y=yield*A(g,m);if(y)return y;if(m.includes("main"))return{name:"main",ref:"main"};if(m.includes("master"))return{name:"master",ref:"master"}}),C=r.fn("Git.hasHead")(function*(g){return(yield*o(["rev-parse","--verify","HEAD"],{cwd:g})).exitCode===0}),H=r.fn("Git.mergeBase")(function*(g,s,m="HEAD"){let y=yield*o(["merge-base",s,m],{cwd:g});if(y.exitCode!==0)return;return zn(y)||void 0}),K=r.fn("Git.show")(function*(g,s,m,y=""){let t=y?`${y}${m}`:m,u=yield*o(["show",`${s}:${t}`],{cwd:g});if(u.exitCode!==0)return"";if(u.stdout.includes(0))return"";return u.text()}),$=r.fn("Git.status")(function*(g){return Po(yield*i(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:g})).flatMap((s)=>{let m=s.slice(3);if(!m)return[];let y=s.slice(0,2);return[{file:m,code:y,status:si(y)}]})}),Q=r.fn("Git.diff")(function*(g,s){let m=Po(yield*i(["diff","--no-ext-diff","--no-renames","--name-status","-z",s,"--","."],{cwd:g}));return m.flatMap((y,t)=>{if(t%2!==0)return[];let u=m[t+1];if(!y||!u)return[];return[{file:u,code:y,status:si(y)}]})}),L=r.fn("Git.stats")(function*(g,s){return Po(yield*i(["diff","--no-ext-diff","--no-renames","--numstat","-z",s,"--","."],{cwd:g})).flatMap((m)=>{let y=m.indexOf("\t"),t=m.indexOf("\t",y+1);if(y===-1||t===-1)return[];let u=m.slice(t+1);if(!u)return[];let D=m.slice(0,y),I=m.slice(y+1,t),O=D==="-"?0:Number.parseInt(D||"0",10),P=I==="-"?0:Number.parseInt(I||"0",10);return[{file:u,additions:Number.isFinite(O)?O:0,deletions:Number.isFinite(P)?P:0}]})});return io.of({run:o,branch:T,prefix:M,defaultBranch:x,hasHead:C,mergeBase:H,show:K,status:$,diff:Q,stats:L})})),Ee=pi.pipe(h.provide(bn));var An=c.create({service:"storage"}),Zo=ro.create("NotFoundError",a.object({message:a.string()})),Pe=N.Struct({path:N.optional(N.Struct({root:N.optional(N.String)}))}),We=N.Struct({id:N.String}),Ue=N.Struct({id:N.String}),Ze=N.Struct({additions:N.Number,deletions:N.Number}),Xe=N.Struct({id:N.String,projectID:N.String,summary:N.Struct({diffs:N.Array(Ze)})}),Ye=N.decodeUnknownOption(Pe),ze=N.decodeUnknownOption(We),ce=N.decodeUnknownOption(Ue),ke=N.decodeUnknownOption(Xe);class to extends vn.Service()("@qitqode/Storage"){}function qe(n,o){return X.join(n,...o)+".json"}function Wo(n){if(!n||typeof n!=="object")return!1;if("code"in n&&n.code==="ENOENT")return!0;if("reason"in n&&n.reason&&typeof n.reason==="object"&&"_tag"in n.reason)return n.reason._tag==="NotFound";return!1}function Ve(n){let o=Number.parseInt(n,10);return Number.isNaN(o)?0:o}var Ai=[r.fn("Storage.migration.1")(function*(n,o,i){let l=X.resolve(n,"../project");if(!(yield*o.isDir(l)))return;let e=yield*o.glob("*",{cwd:l,include:"all"});for(let A of e){let _=X.join(l,A);if(!(yield*o.isDir(_)))continue;An.info(`migrating project ${A}`);let T=A,M="/";if(T!=="global"){for(let H of yield*o.glob("storage/session/message/*/*.json",{cwd:_,absolute:!0})){let K=Ye(yield*o.readJson(H),{onExcessProperty:"preserve"}),$=cn.isSome(K)?K.value.path?.root:void 0;if(!$)continue;M=$;break}if(!M)continue;if(!(yield*o.isDir(M)))continue;let x=yield*i.run(["rev-list","--max-parents=0","--all"],{cwd:M}),[C]=x.text().split(`
|
|
5
5
|
`).filter(Boolean).map((H)=>H.trim()).toSorted();if(!C)continue;T=C,yield*o.writeWithDirs(X.join(n,"project",T+".json"),JSON.stringify({id:C,vcs:"git",worktree:M,time:{created:Date.now(),initialized:Date.now()}},null,2)),An.info(`migrating sessions for project ${T}`);for(let H of yield*o.glob("storage/session/info/*.json",{cwd:_,absolute:!0})){let K=X.join(n,"session",T,X.basename(H));An.info("copying",{sessionFile:H,dest:K});let $=yield*o.readJson(H),Q=ze($,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(K,JSON.stringify($,null,2)),cn.isNone(Q))continue;An.info(`migrating messages for session ${Q.value.id}`);for(let L of yield*o.glob(`storage/session/message/${Q.value.id}/*.json`,{cwd:_,absolute:!0})){let g=X.join(n,"message",Q.value.id,X.basename(L));An.info("copying",{msgFile:L,dest:g});let s=yield*o.readJson(L),m=ce(s,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(g,JSON.stringify(s,null,2)),cn.isNone(m))continue;An.info(`migrating parts for message ${m.value.id}`);for(let y of yield*o.glob(`storage/session/part/${Q.value.id}/${m.value.id}/*.json`,{cwd:_,absolute:!0})){let t=X.join(n,"part",m.value.id,X.basename(y)),u=yield*o.readJson(y);An.info("copying",{partFile:y,dest:t}),yield*o.writeWithDirs(t,JSON.stringify(u,null,2))}}}}}}),r.fn("Storage.migration.2")(function*(n,o){for(let i of yield*o.glob("session/*/*.json",{cwd:n,absolute:!0})){let l=yield*o.readJson(i),e=ke(l,{onExcessProperty:"preserve"});if(cn.isNone(e))continue;let A=e.value.summary.diffs;yield*o.writeWithDirs(X.join(n,"session_diff",e.value.id+".json"),JSON.stringify(A,null,2)),yield*o.writeWithDirs(X.join(n,"session",e.value.projectID,e.value.id+".json"),JSON.stringify({...l,summary:{additions:A.reduce((_,T)=>_+T.additions,0),deletions:A.reduce((_,T)=>_+T.deletions,0)}},null,2))}})],Ti=h.effect(to,r.gen(function*(){let n=yield*k.Service,o=yield*Sn.Service,i=yield*Uo.make({lookup:()=>Cn.make(),idleTimeToLive:0}),l=yield*r.cached(r.gen(function*(){let $=X.join($n.Path.data,"storage"),Q=X.join($,"migration"),L=yield*n.readFileString(Q).pipe(r.map(Ve),r.catchIf(Wo,()=>r.succeed(0)),r.orElseSucceed(()=>0));for(let g=L;g<Ai.length;g++){An.info("running migration",{index:g});let s=Ai[g],m=yield*r.exit(s($,n,o));if(Xn.isFailure(m)){An.error("failed to run migration",{index:g,cause:m.cause});break}yield*n.writeWithDirs(Q,String(g+1))}return{dir:$}})),e=($)=>r.fail(new Zo({message:`Resource not found: ${$}`})),A=($,Q)=>Q.pipe(r.catchIf(Wo,()=>e($))),_=r.fnUntraced(function*($,Q){yield*n.writeWithDirs($,JSON.stringify(Q,null,2))}),T=($,Q)=>r.scoped(r.gen(function*(){let L=qe((yield*l).dir,$);return yield*Q(L,yield*Uo.get(i,L))})),M=r.fn("Storage.remove")(function*($){yield*T($,(Q,L)=>Cn.withWriteLock(L,n.remove(Q).pipe(r.catchIf(Wo,()=>r.void))))}),x=($)=>r.gen(function*(){return yield*T($,(L,g)=>Cn.withReadLock(g,A(L,n.readJson(L))))}),C=($,Q)=>r.gen(function*(){return yield*T($,(g,s)=>Cn.withWriteLock(s,r.gen(function*(){let m=yield*A(g,n.readJson(g));return Q(m),yield*_(g,m),m})))}),H=($,Q)=>r.gen(function*(){yield*T($,(L,g)=>Cn.withWriteLock(g,_(L,Q)))}),K=r.fn("Storage.list")(function*($){let Q=(yield*l).dir,L=X.join(Q,...$);return(yield*n.glob("**/*",{cwd:L,include:"file"}).pipe(r.catch(()=>r.succeed([])))).map((s)=>[...$,...s.slice(0,-5).split(X.sep)]).toSorted((s,m)=>s.join("/").localeCompare(m.join("/")))});return to.of({remove:M,read:x,update:C,write:H,list:K})})),we=Ti.pipe(h.provide(k.defaultLayer),h.provide(Sn.defaultLayer));export{Rn as ql,xr as rl,En as sl,mn as tl,J as ul,fn as vl,eo as wl,Yo as xl,zo as yl,co as zl,ko as Al,Vo as Bl,fo as Cl,In as Dl,Sn as El,Zo as Fl,Oi as Gl,w as Hl,Jo as Il,Pr as Jl,se as Kl,jr as Ll,Ae as Ml,on as Nl,Un as Ol,de as Pl,ei as Ql,mi as Rl};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$q as AQ,Iq as mJ,Jq as vJ,Kq as dJ,Lq as lJ,Oq as d,Pq as l,Rq as uJ,Sq as cJ,Vq as pJ,Wq as iJ,Xq as nJ,Yq as aJ,Zq as rJ}from"./chunk-73r8bjjz.js";import{Cs as FQ,ds as CQ,es as DQ}from"./chunk-0vakk88p.js";import{Ns as x,Ws as GJ}from"./chunk-tr6rdr6h.js";import{$D as wQ,$N as g,DE as z,DG as xJ,ED as qQ,EF as EJ,HG as fJ,IF as MJ,JE as b,LD as _J,LE as CJ,LF as oJ,PF as RJ,QL as j,RF as VJ,SG as E,UF as hJ,VE as DJ,WE as FJ,XE as AJ,XG as yJ,YG as bJ,_D as BQ,aO as eJ,bC as GQ,bG as jJ,cE as $J,dE as UJ,dO as HQ,eB as wJ,eH as I,eO as WQ,fM as o,fO as R,hB as HJ,hF as t,hG as NJ,iE as zJ,iF as OJ,kB as WJ,kF as y,lI as gJ,mB as $Q,pC as IJ,rA as tJ,sC as PJ,sG as kJ,tE as ZJ,uB as f,vC as T,wG as LJ,xF as TJ,yC as KJ,zG as SJ}from"./chunk-qnvsqnz5.js";import{sO as zQ,uO as u,wO as S}from"./chunk-r9w0thdk.js";var IX={};u(IX,{resource:()=>BJ,layer:()=>EQ,enabled:()=>OQ,Observability:()=>WX});var p={};u(p,{make:()=>IQ,layer:()=>ZX});var VQ=AJ.pipe(FJ,DJ((J)=>{if(lJ(J)&&J.reason._tag==="StatusCodeError"&&J.reason.response.status===429){let Q=HJ(J.reason.response.headers["retry-after"]).pipe(WJ(CJ),wJ(()=>5));return t(T(Q))}return t(T(1))})),sJ=E(function*(J){let Q=yield*jJ(),X=f(Q,b),Y=f(Q,UJ),$=fJ(Q),G=KJ(IJ(J.exportInterval),PJ),B=void 0,C=nJ(f(Q,pJ)).pipe(iJ(NJ(rJ,!1)),aJ({schedule:VQ,times:3})),V=vJ({"user-agent":`effect-opentelemetry-${J.label}/0.0.0`});if(J.headers)V=dJ(mJ(J.headers),V);let r=uJ(J.url,{headers:V}),O=[],s=OJ(()=>{if(B!==void 0&&X.currentTimeMillisUnsafe()<B)return y;else if(B!==void 0)B=void 0;let h=O;if(J.maxBatchSize!=="disabled"){if(O.length===0)return y;O=[]}return C.execute(cJ(r,J.body(h))).pipe(EJ,SJ(!1))}).pipe(MJ((h)=>{if(B!==void 0)return y;return B=X.currentTimeMillisUnsafe()+60000,O=[],yJ("Disabling exporter for 60 seconds",h)}),bJ({package:"@effect/opentelemetry",module:J.label}));return yield*zJ(Y,s.pipe(RJ,kJ,VJ(J.shutdownTimeout))),yield*hJ(G).pipe(TJ(s),LJ,xJ(Y)),{push(h){if(B!==void 0)return;if(O.push(h),J.maxBatchSize!=="disabled"&&O.length>=J.maxBatchSize)gJ($(s),Y)}}});var jQ=(J)=>{let Q=J.attributes?e(Object.entries(J.attributes)):[];if(Q.push({key:"service.name",value:{stringValue:J.serviceName}}),J.serviceVersion)Q.push({key:"service.version",value:{stringValue:J.serviceVersion}});return{attributes:Q,droppedAttributesCount:0}},JQ=E(function*(J){let Q={...yield*g(o(eJ(j,j)),"OTEL_RESOURCE_ATTRIBUTES"),...J?.attributes},X=J?.serviceName??Q["service.name"]??(yield*g(j,"OTEL_SERVICE_NAME"));delete Q["service.name"];let Y=J?.serviceVersion??Q["service.version"]??(yield*g(o(j),"OTEL_SERVICE_VERSION"));return delete Q["service.version"],jQ({serviceName:X,serviceVersion:Y,attributes:Q})},oJ),QQ=(J)=>{let Q=J.attributes.find((X)=>X.key==="service.name");if(!Q||!Q.value.stringValue)throw Error("Resource does not contain a service name");return Q.value.stringValue},e=(J)=>{let Q=[];for(let[X,Y]of J)Q.push({key:X,value:m(Y)});return Q},m=(J)=>{if(Array.isArray(J))return{arrayValue:{values:J.map(m)}};switch(typeof J){case"string":return{stringValue:J};case"bigint":return{intValue:Number(J)};case"number":return Number.isInteger(J)?{intValue:J}:{doubleValue:J};case"boolean":return{boolValue:J};default:return{stringValue:tJ(J)}}};var c={};u(c,{layerProtobuf:()=>YX,layerJson:()=>XX,OtlpSerialization:()=>M});var N={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},k=(J,Q)=>J<<3|Q,D=(J)=>{let Q=[],X=typeof J==="bigint"?J:BigInt(J);while(X>0x7fn)Q.push(Number(X&0x7fn)|128),X>>=7n;return Q.push(Number(X)),new Uint8Array(Q)};var kQ=(J)=>{let Q=new Uint8Array(8);return new DataView(Q.buffer).setBigUint64(0,J,!0),Q},LQ=(J)=>{let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,J,!0),Q},SQ=(J)=>{let Q=new Uint8Array(8);return new DataView(Q.buffer).setFloat64(0,J,!0),Q},xQ=(J)=>new TextEncoder().encode(J),fQ=(J)=>{let Q=new Uint8Array(J.length/2);for(let X=0;X<J.length;X+=2)Q[X/2]=parseInt(J.slice(X,X+2),16);return Q},Z=(...J)=>{let Q=J.reduce(($,G)=>$+G.length,0),X=new Uint8Array(Q),Y=0;for(let $ of J)X.set($,Y),Y+=$.length;return X},q=(J,Q)=>Z(D(k(J,N.Varint)),D(Q));var JJ=(J,Q)=>q(J,Q?1:0),W=(J,Q)=>Z(D(k(J,N.Fixed64)),kQ(Q)),v=(J,Q)=>Z(D(k(J,N.Fixed32)),LQ(Q)),F=(J,Q)=>Z(D(k(J,N.Fixed64)),SQ(Q)),L=(J,Q)=>Z(D(k(J,N.LengthDelimited)),D(Q.length),Q),K=(J,Q)=>L(J,xQ(Q)),U=(J,Q)=>L(J,fQ(Q)),w=(J,Q)=>L(J,Q),_=(J,Q,X)=>Z(...Q.map((Y)=>w(J,X(Y))));var H=(J,Q)=>Q!==void 0&&Q!==""?K(J,Q):new Uint8Array(0);var QJ=(J)=>{if(J.stringValue!==void 0&&J.stringValue!==null)return K(1,J.stringValue);if(J.boolValue!==void 0&&J.boolValue!==null)return JJ(2,J.boolValue);if(J.intValue!==void 0&&J.intValue!==null)return q(3,BigInt(J.intValue));if(J.doubleValue!==void 0&&J.doubleValue!==null)return F(4,J.doubleValue);if(J.arrayValue!==void 0)return w(5,bQ(J.arrayValue));if(J.kvlistValue!==void 0)return w(6,gQ(J.kvlistValue));if(J.bytesValue!==void 0)return L(7,J.bytesValue);return new Uint8Array(0)},bQ=(J)=>_(1,J.values,QJ),gQ=(J)=>_(1,J.values,P),P=(J)=>Z(K(1,J.key),w(2,QJ(J.value))),XJ=(J)=>Z(K(1,J.name),H(2,J.version),J.attributes?_(3,J.attributes,P):new Uint8Array(0),J.droppedAttributesCount?q(4,J.droppedAttributesCount):new Uint8Array(0)),YJ=(J)=>Z(_(1,J.attributes,P),J.droppedAttributesCount>0?q(2,J.droppedAttributesCount):new Uint8Array(0));var mQ=(J)=>Z(H(2,J.message),q(3,J.code)),vQ=(J)=>Z(W(1,BigInt(J.timeUnixNano)),K(2,J.name),_(3,J.attributes,P),J.droppedAttributesCount>0?q(4,J.droppedAttributesCount):new Uint8Array(0)),dQ=(J)=>Z(U(1,J.traceId),U(2,J.spanId),H(3,J.traceState),_(4,J.attributes,P),J.droppedAttributesCount>0?q(5,J.droppedAttributesCount):new Uint8Array(0),J.flags!==void 0?v(6,J.flags):new Uint8Array(0)),lQ=(J)=>Z(U(1,J.traceId),U(2,J.spanId),H(3,J.traceState),J.parentSpanId!==void 0?U(4,J.parentSpanId):new Uint8Array(0),K(5,J.name),q(6,J.kind),W(7,BigInt(J.startTimeUnixNano)),W(8,BigInt(J.endTimeUnixNano)),_(9,J.attributes,P),J.droppedAttributesCount>0?q(10,J.droppedAttributesCount):new Uint8Array(0),_(11,J.events,vQ),J.droppedEventsCount>0?q(12,J.droppedEventsCount):new Uint8Array(0),_(13,J.links,dQ),J.droppedLinksCount>0?q(14,J.droppedLinksCount):new Uint8Array(0),w(15,mQ(J.status)),J.flags!==void 0?v(16,J.flags):new Uint8Array(0)),uQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.spans,lQ),H(3,J.schemaUrl)),cQ=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeSpans,uQ),H(3,J.schemaUrl)),XQ=(J)=>_(1,J.resourceSpans,cQ);var YQ=(J)=>Z(W(2,BigInt(J.startTimeUnixNano)),W(3,BigInt(J.timeUnixNano)),J.asDouble!==void 0?F(4,J.asDouble):new Uint8Array(0),J.asInt!==void 0?W(6,BigInt(J.asInt)):new Uint8Array(0),_(7,J.attributes,P),J.flags!==void 0?q(8,J.flags):new Uint8Array(0)),pQ=(J)=>{let Q=Z(...J.bucketCounts.map((Y)=>W(6,BigInt(Y)))),X=Z(...J.explicitBounds.map((Y)=>F(7,Y)));return Z(W(2,BigInt(J.startTimeUnixNano)),W(3,BigInt(J.timeUnixNano)),W(4,BigInt(J.count)),J.sum!==void 0?F(5,J.sum):new Uint8Array(0),Q,X,_(9,J.attributes,P),J.flags!==void 0?q(10,J.flags):new Uint8Array(0),J.min!==void 0?F(11,J.min):new Uint8Array(0),J.max!==void 0?F(12,J.max):new Uint8Array(0))},iQ=(J)=>_(1,J.dataPoints,YQ),nQ=(J)=>Z(_(1,J.dataPoints,YQ),q(2,J.aggregationTemporality),JJ(3,J.isMonotonic)),aQ=(J)=>Z(_(1,J.dataPoints,pQ),q(2,J.aggregationTemporality)),rQ=(J)=>Z(K(1,J.name),H(2,J.description),H(3,J.unit),J.gauge!==void 0?w(5,iQ(J.gauge)):new Uint8Array(0),J.sum!==void 0?w(7,nQ(J.sum)):new Uint8Array(0),J.histogram!==void 0?w(9,aQ(J.histogram)):new Uint8Array(0)),sQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.metrics,rQ),H(3,J.schemaUrl)),tQ=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeMetrics,sQ),H(3,J.schemaUrl)),ZQ=(J)=>_(1,J.resourceMetrics,tQ);var oQ=(J)=>Z(W(1,BigInt(J.timeUnixNano)),J.severityNumber!==void 0?q(2,J.severityNumber):new Uint8Array(0),H(3,J.severityText),J.body!==void 0?w(5,QJ(J.body)):new Uint8Array(0),_(6,J.attributes,P),J.droppedAttributesCount!==void 0&&J.droppedAttributesCount>0?q(7,J.droppedAttributesCount):new Uint8Array(0),J.flags!==void 0?v(8,J.flags):new Uint8Array(0),J.traceId!==void 0&&J.traceId!==""?U(9,J.traceId):new Uint8Array(0),J.spanId!==void 0&&J.spanId!==""?U(10,J.spanId):new Uint8Array(0),J.observedTimeUnixNano!==void 0?W(11,BigInt(J.observedTimeUnixNano)):new Uint8Array(0)),eQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.logRecords,oQ),H(3,J.schemaUrl)),JX=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeLogs,eQ),H(3,J.schemaUrl)),_Q=(J)=>_(1,J.resourceLogs,JX);class M extends $Q()("effect/observability/OtlpSerialization"){}var XX=ZJ(M,{traces:(J)=>l(J),metrics:(J)=>l(J),logs:(J)=>l(J)}),YX=ZJ(M,{traces:(J)=>d(XQ(J),"application/x-protobuf"),metrics:(J)=>d(ZQ(J),"application/x-protobuf"),logs:(J)=>d(_Q(J),"application/x-protobuf")});var IQ=E(function*(J){let Q=yield*M,X=yield*JQ(J.resource),Y={name:QQ(X)},$=yield*sJ({label:"OtlpLogger",url:J.url,headers:J.headers,maxBatchSize:J.maxBatchSize??1000,exportInterval:J.exportInterval??T(1),body:(B)=>Q.logs({resourceLogs:[{resource:X,scopeLogs:[{scope:Y,logRecords:B}]}]}),shutdownTimeout:J.shutdownTimeout??T(3)}),G={excludeLogSpans:J.excludeLogSpans??!1,clock:yield*b};return HQ((B)=>{$.push(_X(B,G))})}),ZX=(J)=>WQ([IQ(J)],{mergeWithExisting:J.mergeWithExisting??!0}),_X=(J,Q)=>{let Y=Q.clock.currentTimeNanosUnsafe().toString(),$=J.date.getTime(),G=e(Object.entries(J.fiber.getRef(BQ)));if(G.push({key:"fiberId",value:{intValue:J.fiber.id}}),!Q.excludeLogSpans)for(let[V,r]of J.fiber.getRef(wQ))G.push({key:`logSpan.${V}`,value:{stringValue:`${$-r}ms`}});if(J.cause.reasons.length>0)G.push({key:"log.error",value:{stringValue:qQ(J.cause)}});let B=GQ(J.message),C={severityNumber:$X(J.logLevel),severityText:J.logLevel,timeUnixNano:Y,observedTimeUnixNano:Y,attributes:G,body:m(B.length===1?B[0]:B),droppedAttributesCount:0};if(J.fiber.currentSpan)C.traceId=J.fiber.currentSpan.traceId,C.spanId=J.fiber.currentSpan.spanId;return C},$X=(J)=>{switch(J){case"Trace":return A.SEVERITY_NUMBER_TRACE;case"Debug":return A.SEVERITY_NUMBER_DEBUG;case"Info":return A.SEVERITY_NUMBER_INFO;case"Warn":return A.SEVERITY_NUMBER_WARN;case"Error":return A.SEVERITY_NUMBER_ERROR;case"Fatal":return A.SEVERITY_NUMBER_FATAL;default:return A.SEVERITY_NUMBER_UNSPECIFIED}},A={SEVERITY_NUMBER_UNSPECIFIED:0,SEVERITY_NUMBER_TRACE:1,SEVERITY_NUMBER_TRACE2:2,SEVERITY_NUMBER_TRACE3:3,SEVERITY_NUMBER_TRACE4:4,SEVERITY_NUMBER_DEBUG:5,SEVERITY_NUMBER_DEBUG2:6,SEVERITY_NUMBER_DEBUG3:7,SEVERITY_NUMBER_DEBUG4:8,SEVERITY_NUMBER_INFO:9,SEVERITY_NUMBER_INFO2:10,SEVERITY_NUMBER_INFO3:11,SEVERITY_NUMBER_INFO4:12,SEVERITY_NUMBER_WARN:13,SEVERITY_NUMBER_WARN2:14,SEVERITY_NUMBER_WARN3:15,SEVERITY_NUMBER_WARN4:16,SEVERITY_NUMBER_ERROR:17,SEVERITY_NUMBER_ERROR2:18,SEVERITY_NUMBER_ERROR3:19,SEVERITY_NUMBER_ERROR4:20,SEVERITY_NUMBER_FATAL:21,SEVERITY_NUMBER_FATAL2:22,SEVERITY_NUMBER_FATAL3:23,SEVERITY_NUMBER_FATAL4:24};var UQ={};u(UQ,{logger:()=>n,layer:()=>qJ,create:()=>KQ});var GX=(J)=>J==="sessionID"?"session.id":J,PQ=(J)=>Object.fromEntries(Object.entries(J??{}).filter((Q)=>Q[1]!==void 0&&Q[1]!==null).map(([Q,X])=>[GX(Q),X])),qX=(J)=>{if(Array.isArray(J))return J.map((Q)=>String(Q)).join(" ");return J===void 0?"":String(J)},i=(J,Q,X,Y)=>{let $=PQ({...Q,...Y}),G=J(X);return Object.keys($).length?I.annotateLogs(G,$):G},n=R.make((J)=>{let Q=PQ(J.fiber.getRef($J.CurrentLogAnnotations)),X=J.date.getTime();for(let[B,C]of J.fiber.getRef($J.CurrentLogSpans))Q[`logSpan.${B}`]=`${X-C}ms`;if(J.cause.reasons.length>0)Q.cause=_J.pretty(J.cause);let Y=typeof Q.service==="string"?Q.service:void 0;if(Y)delete Q.service;let $=Y?GJ.create({service:Y}):GJ.Default,G=qX(J.message);switch(J.logLevel){case"Trace":case"Debug":return $.debug(G,Q);case"Warn":return $.warn(G,Q);case"Error":case"Fatal":return $.error(G,Q);default:return $.info(G,Q)}}),qJ=R.layer([n],{mergeWithExisting:!1}),KQ=(J={})=>({debug:(Q,X)=>i((Y)=>I.logDebug(Y),J,Q,X),info:(Q,X)=>i((Y)=>I.logInfo(Y),J,Q,X),warn:(Q,X)=>i((Y)=>I.logWarning(Y),J,Q,X),error:(Q,X)=>i((Y)=>I.logError(Y),J,Q,X),with:(Q)=>KQ({...J,...Q})});var a=x.OTEL_EXPORTER_OTLP_ENDPOINT,OQ=!!a,BX=crypto.randomUUID(),TQ=x.OTEL_EXPORTER_OTLP_HEADERS?x.OTEL_EXPORTER_OTLP_HEADERS.split(",").reduce((J,Q)=>{let[X,...Y]=Q.split("=");return J[X]=Y.join("="),J},{}):void 0;function BJ(){let J=FQ("main"),Q=(()=>{let X=process.env.OTEL_RESOURCE_ATTRIBUTES;if(!X)return{};try{return Object.fromEntries(X.split(",").map((Y)=>{let $=Y.indexOf("=");if($<1)throw Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry");return[decodeURIComponent(Y.slice(0,$)),decodeURIComponent(Y.slice($+1))]}))}catch{return{}}})();return{serviceName:"qitqode",serviceVersion:CQ,attributes:{...Q,"deployment.environment.name":DQ,"qitqode.client":x.QITQODE_CLIENT,"qitqode.process_role":J.processRole,"qitqode.run_id":J.runID,"service.instance.id":BX}}}function wX(){return R.layer([n,p.make({url:`${a}/v1/logs`,resource:BJ(),headers:TQ})],{mergeWithExisting:!1}).pipe(z.provide(c.layerJson),z.provide(AQ.layer))}var HX=async()=>{let J=await import("./chunk-rrv0n73b.js"),Q=await import("./chunk-5c2438af.js"),X=await import("./chunk-ejqzcdcx.js"),{AsyncLocalStorageContextManager:Y}=await import("./chunk-5tky3csh.js").then((m)=>zQ(m.default,1)),{context:$}=await import("./chunk-535nm66j.js").then((m)=>zQ(m.default,1)),G=new Y;return G.enable(),$.setGlobalContextManager(G),J.layer(()=>({resource:BJ(),spanProcessor:new X.BatchSpanProcessor(new Q.OTLPTraceExporter({url:`${a}/v1/traces`,headers:TQ}))}))},EQ=!a?qJ:z.unwrap(I.gen(function*(){let J=yield*I.promise(HX);return z.mergeAll(J,wX())})),WX={enabled:OQ,layer:EQ};var aX=z.makeMemoMapUnsafe();
|
|
2
|
+
import{$q as AQ,Iq as mJ,Jq as vJ,Kq as dJ,Lq as lJ,Oq as d,Pq as l,Rq as uJ,Sq as cJ,Vq as pJ,Wq as iJ,Xq as nJ,Yq as aJ,Zq as rJ}from"./chunk-73r8bjjz.js";import{Cs as FQ,ds as CQ,es as DQ}from"./chunk-kj8cmn7z.js";import{Ns as x,Ws as GJ}from"./chunk-tr6rdr6h.js";import{$D as wQ,$N as g,DE as z,DG as xJ,ED as qQ,EF as EJ,HG as fJ,IF as MJ,JE as b,LD as _J,LE as CJ,LF as oJ,PF as RJ,QL as j,RF as VJ,SG as E,UF as hJ,VE as DJ,WE as FJ,XE as AJ,XG as yJ,YG as bJ,_D as BQ,aO as eJ,bC as GQ,bG as jJ,cE as $J,dE as UJ,dO as HQ,eB as wJ,eH as I,eO as WQ,fM as o,fO as R,hB as HJ,hF as t,hG as NJ,iE as zJ,iF as OJ,kB as WJ,kF as y,lI as gJ,mB as $Q,pC as IJ,rA as tJ,sC as PJ,sG as kJ,tE as ZJ,uB as f,vC as T,wG as LJ,xF as TJ,yC as KJ,zG as SJ}from"./chunk-qnvsqnz5.js";import{sO as zQ,uO as u,wO as S}from"./chunk-r9w0thdk.js";var IX={};u(IX,{resource:()=>BJ,layer:()=>EQ,enabled:()=>OQ,Observability:()=>WX});var p={};u(p,{make:()=>IQ,layer:()=>ZX});var VQ=AJ.pipe(FJ,DJ((J)=>{if(lJ(J)&&J.reason._tag==="StatusCodeError"&&J.reason.response.status===429){let Q=HJ(J.reason.response.headers["retry-after"]).pipe(WJ(CJ),wJ(()=>5));return t(T(Q))}return t(T(1))})),sJ=E(function*(J){let Q=yield*jJ(),X=f(Q,b),Y=f(Q,UJ),$=fJ(Q),G=KJ(IJ(J.exportInterval),PJ),B=void 0,C=nJ(f(Q,pJ)).pipe(iJ(NJ(rJ,!1)),aJ({schedule:VQ,times:3})),V=vJ({"user-agent":`effect-opentelemetry-${J.label}/0.0.0`});if(J.headers)V=dJ(mJ(J.headers),V);let r=uJ(J.url,{headers:V}),O=[],s=OJ(()=>{if(B!==void 0&&X.currentTimeMillisUnsafe()<B)return y;else if(B!==void 0)B=void 0;let h=O;if(J.maxBatchSize!=="disabled"){if(O.length===0)return y;O=[]}return C.execute(cJ(r,J.body(h))).pipe(EJ,SJ(!1))}).pipe(MJ((h)=>{if(B!==void 0)return y;return B=X.currentTimeMillisUnsafe()+60000,O=[],yJ("Disabling exporter for 60 seconds",h)}),bJ({package:"@effect/opentelemetry",module:J.label}));return yield*zJ(Y,s.pipe(RJ,kJ,VJ(J.shutdownTimeout))),yield*hJ(G).pipe(TJ(s),LJ,xJ(Y)),{push(h){if(B!==void 0)return;if(O.push(h),J.maxBatchSize!=="disabled"&&O.length>=J.maxBatchSize)gJ($(s),Y)}}});var jQ=(J)=>{let Q=J.attributes?e(Object.entries(J.attributes)):[];if(Q.push({key:"service.name",value:{stringValue:J.serviceName}}),J.serviceVersion)Q.push({key:"service.version",value:{stringValue:J.serviceVersion}});return{attributes:Q,droppedAttributesCount:0}},JQ=E(function*(J){let Q={...yield*g(o(eJ(j,j)),"OTEL_RESOURCE_ATTRIBUTES"),...J?.attributes},X=J?.serviceName??Q["service.name"]??(yield*g(j,"OTEL_SERVICE_NAME"));delete Q["service.name"];let Y=J?.serviceVersion??Q["service.version"]??(yield*g(o(j),"OTEL_SERVICE_VERSION"));return delete Q["service.version"],jQ({serviceName:X,serviceVersion:Y,attributes:Q})},oJ),QQ=(J)=>{let Q=J.attributes.find((X)=>X.key==="service.name");if(!Q||!Q.value.stringValue)throw Error("Resource does not contain a service name");return Q.value.stringValue},e=(J)=>{let Q=[];for(let[X,Y]of J)Q.push({key:X,value:m(Y)});return Q},m=(J)=>{if(Array.isArray(J))return{arrayValue:{values:J.map(m)}};switch(typeof J){case"string":return{stringValue:J};case"bigint":return{intValue:Number(J)};case"number":return Number.isInteger(J)?{intValue:J}:{doubleValue:J};case"boolean":return{boolValue:J};default:return{stringValue:tJ(J)}}};var c={};u(c,{layerProtobuf:()=>YX,layerJson:()=>XX,OtlpSerialization:()=>M});var N={Varint:0,Fixed64:1,LengthDelimited:2,Fixed32:5},k=(J,Q)=>J<<3|Q,D=(J)=>{let Q=[],X=typeof J==="bigint"?J:BigInt(J);while(X>0x7fn)Q.push(Number(X&0x7fn)|128),X>>=7n;return Q.push(Number(X)),new Uint8Array(Q)};var kQ=(J)=>{let Q=new Uint8Array(8);return new DataView(Q.buffer).setBigUint64(0,J,!0),Q},LQ=(J)=>{let Q=new Uint8Array(4);return new DataView(Q.buffer).setUint32(0,J,!0),Q},SQ=(J)=>{let Q=new Uint8Array(8);return new DataView(Q.buffer).setFloat64(0,J,!0),Q},xQ=(J)=>new TextEncoder().encode(J),fQ=(J)=>{let Q=new Uint8Array(J.length/2);for(let X=0;X<J.length;X+=2)Q[X/2]=parseInt(J.slice(X,X+2),16);return Q},Z=(...J)=>{let Q=J.reduce(($,G)=>$+G.length,0),X=new Uint8Array(Q),Y=0;for(let $ of J)X.set($,Y),Y+=$.length;return X},q=(J,Q)=>Z(D(k(J,N.Varint)),D(Q));var JJ=(J,Q)=>q(J,Q?1:0),W=(J,Q)=>Z(D(k(J,N.Fixed64)),kQ(Q)),v=(J,Q)=>Z(D(k(J,N.Fixed32)),LQ(Q)),F=(J,Q)=>Z(D(k(J,N.Fixed64)),SQ(Q)),L=(J,Q)=>Z(D(k(J,N.LengthDelimited)),D(Q.length),Q),K=(J,Q)=>L(J,xQ(Q)),U=(J,Q)=>L(J,fQ(Q)),w=(J,Q)=>L(J,Q),_=(J,Q,X)=>Z(...Q.map((Y)=>w(J,X(Y))));var H=(J,Q)=>Q!==void 0&&Q!==""?K(J,Q):new Uint8Array(0);var QJ=(J)=>{if(J.stringValue!==void 0&&J.stringValue!==null)return K(1,J.stringValue);if(J.boolValue!==void 0&&J.boolValue!==null)return JJ(2,J.boolValue);if(J.intValue!==void 0&&J.intValue!==null)return q(3,BigInt(J.intValue));if(J.doubleValue!==void 0&&J.doubleValue!==null)return F(4,J.doubleValue);if(J.arrayValue!==void 0)return w(5,bQ(J.arrayValue));if(J.kvlistValue!==void 0)return w(6,gQ(J.kvlistValue));if(J.bytesValue!==void 0)return L(7,J.bytesValue);return new Uint8Array(0)},bQ=(J)=>_(1,J.values,QJ),gQ=(J)=>_(1,J.values,P),P=(J)=>Z(K(1,J.key),w(2,QJ(J.value))),XJ=(J)=>Z(K(1,J.name),H(2,J.version),J.attributes?_(3,J.attributes,P):new Uint8Array(0),J.droppedAttributesCount?q(4,J.droppedAttributesCount):new Uint8Array(0)),YJ=(J)=>Z(_(1,J.attributes,P),J.droppedAttributesCount>0?q(2,J.droppedAttributesCount):new Uint8Array(0));var mQ=(J)=>Z(H(2,J.message),q(3,J.code)),vQ=(J)=>Z(W(1,BigInt(J.timeUnixNano)),K(2,J.name),_(3,J.attributes,P),J.droppedAttributesCount>0?q(4,J.droppedAttributesCount):new Uint8Array(0)),dQ=(J)=>Z(U(1,J.traceId),U(2,J.spanId),H(3,J.traceState),_(4,J.attributes,P),J.droppedAttributesCount>0?q(5,J.droppedAttributesCount):new Uint8Array(0),J.flags!==void 0?v(6,J.flags):new Uint8Array(0)),lQ=(J)=>Z(U(1,J.traceId),U(2,J.spanId),H(3,J.traceState),J.parentSpanId!==void 0?U(4,J.parentSpanId):new Uint8Array(0),K(5,J.name),q(6,J.kind),W(7,BigInt(J.startTimeUnixNano)),W(8,BigInt(J.endTimeUnixNano)),_(9,J.attributes,P),J.droppedAttributesCount>0?q(10,J.droppedAttributesCount):new Uint8Array(0),_(11,J.events,vQ),J.droppedEventsCount>0?q(12,J.droppedEventsCount):new Uint8Array(0),_(13,J.links,dQ),J.droppedLinksCount>0?q(14,J.droppedLinksCount):new Uint8Array(0),w(15,mQ(J.status)),J.flags!==void 0?v(16,J.flags):new Uint8Array(0)),uQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.spans,lQ),H(3,J.schemaUrl)),cQ=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeSpans,uQ),H(3,J.schemaUrl)),XQ=(J)=>_(1,J.resourceSpans,cQ);var YQ=(J)=>Z(W(2,BigInt(J.startTimeUnixNano)),W(3,BigInt(J.timeUnixNano)),J.asDouble!==void 0?F(4,J.asDouble):new Uint8Array(0),J.asInt!==void 0?W(6,BigInt(J.asInt)):new Uint8Array(0),_(7,J.attributes,P),J.flags!==void 0?q(8,J.flags):new Uint8Array(0)),pQ=(J)=>{let Q=Z(...J.bucketCounts.map((Y)=>W(6,BigInt(Y)))),X=Z(...J.explicitBounds.map((Y)=>F(7,Y)));return Z(W(2,BigInt(J.startTimeUnixNano)),W(3,BigInt(J.timeUnixNano)),W(4,BigInt(J.count)),J.sum!==void 0?F(5,J.sum):new Uint8Array(0),Q,X,_(9,J.attributes,P),J.flags!==void 0?q(10,J.flags):new Uint8Array(0),J.min!==void 0?F(11,J.min):new Uint8Array(0),J.max!==void 0?F(12,J.max):new Uint8Array(0))},iQ=(J)=>_(1,J.dataPoints,YQ),nQ=(J)=>Z(_(1,J.dataPoints,YQ),q(2,J.aggregationTemporality),JJ(3,J.isMonotonic)),aQ=(J)=>Z(_(1,J.dataPoints,pQ),q(2,J.aggregationTemporality)),rQ=(J)=>Z(K(1,J.name),H(2,J.description),H(3,J.unit),J.gauge!==void 0?w(5,iQ(J.gauge)):new Uint8Array(0),J.sum!==void 0?w(7,nQ(J.sum)):new Uint8Array(0),J.histogram!==void 0?w(9,aQ(J.histogram)):new Uint8Array(0)),sQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.metrics,rQ),H(3,J.schemaUrl)),tQ=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeMetrics,sQ),H(3,J.schemaUrl)),ZQ=(J)=>_(1,J.resourceMetrics,tQ);var oQ=(J)=>Z(W(1,BigInt(J.timeUnixNano)),J.severityNumber!==void 0?q(2,J.severityNumber):new Uint8Array(0),H(3,J.severityText),J.body!==void 0?w(5,QJ(J.body)):new Uint8Array(0),_(6,J.attributes,P),J.droppedAttributesCount!==void 0&&J.droppedAttributesCount>0?q(7,J.droppedAttributesCount):new Uint8Array(0),J.flags!==void 0?v(8,J.flags):new Uint8Array(0),J.traceId!==void 0&&J.traceId!==""?U(9,J.traceId):new Uint8Array(0),J.spanId!==void 0&&J.spanId!==""?U(10,J.spanId):new Uint8Array(0),J.observedTimeUnixNano!==void 0?W(11,BigInt(J.observedTimeUnixNano)):new Uint8Array(0)),eQ=(J)=>Z(w(1,XJ(J.scope)),_(2,J.logRecords,oQ),H(3,J.schemaUrl)),JX=(J)=>Z(w(1,YJ(J.resource)),_(2,J.scopeLogs,eQ),H(3,J.schemaUrl)),_Q=(J)=>_(1,J.resourceLogs,JX);class M extends $Q()("effect/observability/OtlpSerialization"){}var XX=ZJ(M,{traces:(J)=>l(J),metrics:(J)=>l(J),logs:(J)=>l(J)}),YX=ZJ(M,{traces:(J)=>d(XQ(J),"application/x-protobuf"),metrics:(J)=>d(ZQ(J),"application/x-protobuf"),logs:(J)=>d(_Q(J),"application/x-protobuf")});var IQ=E(function*(J){let Q=yield*M,X=yield*JQ(J.resource),Y={name:QQ(X)},$=yield*sJ({label:"OtlpLogger",url:J.url,headers:J.headers,maxBatchSize:J.maxBatchSize??1000,exportInterval:J.exportInterval??T(1),body:(B)=>Q.logs({resourceLogs:[{resource:X,scopeLogs:[{scope:Y,logRecords:B}]}]}),shutdownTimeout:J.shutdownTimeout??T(3)}),G={excludeLogSpans:J.excludeLogSpans??!1,clock:yield*b};return HQ((B)=>{$.push(_X(B,G))})}),ZX=(J)=>WQ([IQ(J)],{mergeWithExisting:J.mergeWithExisting??!0}),_X=(J,Q)=>{let Y=Q.clock.currentTimeNanosUnsafe().toString(),$=J.date.getTime(),G=e(Object.entries(J.fiber.getRef(BQ)));if(G.push({key:"fiberId",value:{intValue:J.fiber.id}}),!Q.excludeLogSpans)for(let[V,r]of J.fiber.getRef(wQ))G.push({key:`logSpan.${V}`,value:{stringValue:`${$-r}ms`}});if(J.cause.reasons.length>0)G.push({key:"log.error",value:{stringValue:qQ(J.cause)}});let B=GQ(J.message),C={severityNumber:$X(J.logLevel),severityText:J.logLevel,timeUnixNano:Y,observedTimeUnixNano:Y,attributes:G,body:m(B.length===1?B[0]:B),droppedAttributesCount:0};if(J.fiber.currentSpan)C.traceId=J.fiber.currentSpan.traceId,C.spanId=J.fiber.currentSpan.spanId;return C},$X=(J)=>{switch(J){case"Trace":return A.SEVERITY_NUMBER_TRACE;case"Debug":return A.SEVERITY_NUMBER_DEBUG;case"Info":return A.SEVERITY_NUMBER_INFO;case"Warn":return A.SEVERITY_NUMBER_WARN;case"Error":return A.SEVERITY_NUMBER_ERROR;case"Fatal":return A.SEVERITY_NUMBER_FATAL;default:return A.SEVERITY_NUMBER_UNSPECIFIED}},A={SEVERITY_NUMBER_UNSPECIFIED:0,SEVERITY_NUMBER_TRACE:1,SEVERITY_NUMBER_TRACE2:2,SEVERITY_NUMBER_TRACE3:3,SEVERITY_NUMBER_TRACE4:4,SEVERITY_NUMBER_DEBUG:5,SEVERITY_NUMBER_DEBUG2:6,SEVERITY_NUMBER_DEBUG3:7,SEVERITY_NUMBER_DEBUG4:8,SEVERITY_NUMBER_INFO:9,SEVERITY_NUMBER_INFO2:10,SEVERITY_NUMBER_INFO3:11,SEVERITY_NUMBER_INFO4:12,SEVERITY_NUMBER_WARN:13,SEVERITY_NUMBER_WARN2:14,SEVERITY_NUMBER_WARN3:15,SEVERITY_NUMBER_WARN4:16,SEVERITY_NUMBER_ERROR:17,SEVERITY_NUMBER_ERROR2:18,SEVERITY_NUMBER_ERROR3:19,SEVERITY_NUMBER_ERROR4:20,SEVERITY_NUMBER_FATAL:21,SEVERITY_NUMBER_FATAL2:22,SEVERITY_NUMBER_FATAL3:23,SEVERITY_NUMBER_FATAL4:24};var UQ={};u(UQ,{logger:()=>n,layer:()=>qJ,create:()=>KQ});var GX=(J)=>J==="sessionID"?"session.id":J,PQ=(J)=>Object.fromEntries(Object.entries(J??{}).filter((Q)=>Q[1]!==void 0&&Q[1]!==null).map(([Q,X])=>[GX(Q),X])),qX=(J)=>{if(Array.isArray(J))return J.map((Q)=>String(Q)).join(" ");return J===void 0?"":String(J)},i=(J,Q,X,Y)=>{let $=PQ({...Q,...Y}),G=J(X);return Object.keys($).length?I.annotateLogs(G,$):G},n=R.make((J)=>{let Q=PQ(J.fiber.getRef($J.CurrentLogAnnotations)),X=J.date.getTime();for(let[B,C]of J.fiber.getRef($J.CurrentLogSpans))Q[`logSpan.${B}`]=`${X-C}ms`;if(J.cause.reasons.length>0)Q.cause=_J.pretty(J.cause);let Y=typeof Q.service==="string"?Q.service:void 0;if(Y)delete Q.service;let $=Y?GJ.create({service:Y}):GJ.Default,G=qX(J.message);switch(J.logLevel){case"Trace":case"Debug":return $.debug(G,Q);case"Warn":return $.warn(G,Q);case"Error":case"Fatal":return $.error(G,Q);default:return $.info(G,Q)}}),qJ=R.layer([n],{mergeWithExisting:!1}),KQ=(J={})=>({debug:(Q,X)=>i((Y)=>I.logDebug(Y),J,Q,X),info:(Q,X)=>i((Y)=>I.logInfo(Y),J,Q,X),warn:(Q,X)=>i((Y)=>I.logWarning(Y),J,Q,X),error:(Q,X)=>i((Y)=>I.logError(Y),J,Q,X),with:(Q)=>KQ({...J,...Q})});var a=x.OTEL_EXPORTER_OTLP_ENDPOINT,OQ=!!a,BX=crypto.randomUUID(),TQ=x.OTEL_EXPORTER_OTLP_HEADERS?x.OTEL_EXPORTER_OTLP_HEADERS.split(",").reduce((J,Q)=>{let[X,...Y]=Q.split("=");return J[X]=Y.join("="),J},{}):void 0;function BJ(){let J=FQ("main"),Q=(()=>{let X=process.env.OTEL_RESOURCE_ATTRIBUTES;if(!X)return{};try{return Object.fromEntries(X.split(",").map((Y)=>{let $=Y.indexOf("=");if($<1)throw Error("Invalid OTEL_RESOURCE_ATTRIBUTES entry");return[decodeURIComponent(Y.slice(0,$)),decodeURIComponent(Y.slice($+1))]}))}catch{return{}}})();return{serviceName:"qitqode",serviceVersion:CQ,attributes:{...Q,"deployment.environment.name":DQ,"qitqode.client":x.QITQODE_CLIENT,"qitqode.process_role":J.processRole,"qitqode.run_id":J.runID,"service.instance.id":BX}}}function wX(){return R.layer([n,p.make({url:`${a}/v1/logs`,resource:BJ(),headers:TQ})],{mergeWithExisting:!1}).pipe(z.provide(c.layerJson),z.provide(AQ.layer))}var HX=async()=>{let J=await import("./chunk-rrv0n73b.js"),Q=await import("./chunk-5c2438af.js"),X=await import("./chunk-ejqzcdcx.js"),{AsyncLocalStorageContextManager:Y}=await import("./chunk-5tky3csh.js").then((m)=>zQ(m.default,1)),{context:$}=await import("./chunk-535nm66j.js").then((m)=>zQ(m.default,1)),G=new Y;return G.enable(),$.setGlobalContextManager(G),J.layer(()=>({resource:BJ(),spanProcessor:new X.BatchSpanProcessor(new Q.OTLPTraceExporter({url:`${a}/v1/traces`,headers:TQ}))}))},EQ=!a?qJ:z.unwrap(I.gen(function*(){let J=yield*I.promise(HX);return z.mergeAll(J,wX())})),WX={enabled:OQ,layer:EQ};var aX=z.makeMemoMapUnsafe();
|
|
3
3
|
export{qJ as Cq,UQ as Dq,EQ as Eq,WX as Fq,IX as Gq,aX as Hq};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{cl as a}from"./chunk-52frd9p0.js";import"./chunk-xqnzmr7a.js";import"./chunk-r1xh50b2.js";import"./chunk-13rsd5vv.js";import"./chunk-mh19kwzw.js";import"./chunk-a9a0cwmf.js";import"./chunk-nw3e93y8.js";import"./chunk-9zm6r55d.js";import"./chunk-vcygx6hs.js";import"./chunk-khzzmyk2.js";import"./chunk-y7hgevfv.js";import"./chunk-47k5jy1p.js";import"./chunk-kn8w69g9.js";import"./chunk-ph8hn1wt.js";import"./chunk-ptqk1j2r.js";import"./chunk-cqtkxwd8.js";import"./chunk-pr7z5dj8.js";import"./chunk-dnnkq5y4.js";import"./chunk-t239rvej.js";import"./chunk-yz25607t.js";import"./chunk-7hvf9dgx.js";import"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import"./chunk-t5xxs5kp.js";import"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-nj1ntakd.js";import"./chunk-cmb62jkt.js";import"./chunk-tkrwcjkr.js";import"./chunk-w2cb8cry.js";import"./chunk-kj8cmn7z.js";import"./chunk-r5zy4za0.js";import"./chunk-tr6rdr6h.js";import"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import"./chunk-qnvsqnz5.js";import"./chunk-j8fcfhr2.js";import"./chunk-r9w0thdk.js";export{a as Session};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Aq as b,Bq as c,zq as a}from"./chunk-
|
|
2
|
+
import{Aq as b,Bq as c,zq as a}from"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import"./chunk-t5xxs5kp.js";import"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-kj8cmn7z.js";import"./chunk-r5zy4za0.js";import"./chunk-tr6rdr6h.js";import"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import"./chunk-qnvsqnz5.js";import"./chunk-r9w0thdk.js";export{c as makeRuntime,a as attachWith,b as attach};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Lr as x}from"./chunk-ztyy3ga3.js";import{As as H,ds as K,es as j,ss as V,zs as q}from"./chunk-
|
|
2
|
+
import{Lr as x}from"./chunk-ztyy3ga3.js";import{As as H,ds as K,es as j,ss as V,zs as q}from"./chunk-kj8cmn7z.js";import{ft as M,kt as I}from"./chunk-at22twxx.js";import{ZD as v,eH as _}from"./chunk-qnvsqnz5.js";import{uO as a}from"./chunk-r9w0thdk.js";var U={};a(U,{validateArchiveMetadata:()=>P,validateArchiveEntries:()=>g,replaceDirectoryAtomically:()=>C,extractZip:()=>p,assertArchiveDestinationSafe:()=>T});import m from"path";import c from"fs/promises";function g(o,r){let n=m.resolve(r);for(let e of o){let t=e.trim().replaceAll("\\","/");if(!t)continue;if(t.includes("\x00")||m.posix.isAbsolute(t)||/^[a-z]:\//i.test(t))throw Error(`Unsafe archive entry: ${e}`);if(t.split("/").includes(".."))throw Error(`Unsafe archive entry: ${e}`);let s=m.resolve(n,...t.split("/"));if(s!==n&&!s.startsWith(`${n}${m.sep}`))throw Error(`Unsafe archive entry: ${e}`)}}function P(o){for(let r of o.split(/\r?\n/))if(/^[bclps]/.test(r))throw Error("Archive contains an unsafe special entry")}async function u(o){let r=await c.readdir(o,{withFileTypes:!0});await Promise.all(r.map(async(n)=>{let e=m.join(o,n.name);if(n.isSymbolicLink())throw Error(`Archive contains a symbolic link: ${n.name}`);if(n.isDirectory())await u(e)}))}async function b(o){return c.lstat(o).catch((r)=>{if(r.code==="ENOENT")return;throw r})}async function T(o){let r=m.resolve(o),n=m.parse(r),e=n.root;for(let t of r.slice(n.root.length).split(m.sep).filter(Boolean)){e=m.join(e,t);let s=await b(e);if(!s)return;if(s.isSymbolicLink())throw Error(`Archive destination contains a symbolic link: ${e}`)}}async function C(o,r){let n=m.resolve(r);await T(n);let e=await b(n);if(e&&!e.isDirectory())throw Error("Archive destination must be a directory");let t=m.join(m.dirname(n),`.qitqode-backup-${crypto.randomUUID()}`);if(e)await c.rename(n,t);try{await c.rename(o,n)}catch(s){if(e)await c.rename(t,n);throw s}if(e)await c.rm(t,{recursive:!0,force:!0})}async function p(o,r){let n=m.resolve(o),e=m.resolve(r),t=await x(process.platform==="win32"?["tar","-tf",n]:["unzip","-Z1",n]);g(t.stdout.toString().split(/\r?\n/),e);let s=await x(process.platform==="win32"?["tar","-tvf",n]:["unzip","-Z","-l",n]);P(s.stdout.toString()),await T(m.dirname(e)),await c.mkdir(m.dirname(e),{recursive:!0}),await T(m.dirname(e));let f=await c.mkdtemp(m.join(m.dirname(e),".qitqode-extract-"));try{if(process.platform==="win32"){let w=n.replace(/'/g,"''"),R=f.replace(/'/g,"''"),S=`$global:ProgressPreference = 'SilentlyContinue'; Expand-Archive -Path '${w}' -DestinationPath '${R}' -Force`;await x(["powershell","-NoProfile","-NonInteractive","-Command",S])}else await x(["unzip","-o","-q",n,"-d",f]);await u(f),await C(f,e)}finally{await c.rm(f,{recursive:!0,force:!0})}}var $={};a($,{isValidHex:()=>J,hexToRgb:()=>F,hexToAnsiBold:()=>y});function J(o){if(!o)return!1;return/^#[0-9a-fA-F]{6}$/.test(o)}function F(o){let r=parseInt(o.slice(1,3),16),n=parseInt(o.slice(3,5),16),e=parseInt(o.slice(5,7),16);return{r,g:n,b:e}}function y(o){if(!J(o))return;let{r,g:n,b:e}=F(o);return`\x1B[38;2;${r};${n};${e}m\x1B[1m`}var Q={};a(Q,{awaitDeferred:()=>k});function k(o,r){return _.ensuring(v.await(o),_.sync(r))}import d from"os";import oo from"path";var i;async function A(){if(i)return i;let o=oo.join(I.Path.data,"installation_id"),r=await M.readText(o).catch(()=>{return});if(r&&r.trim())return i=r.trim(),i;return i=crypto.randomUUID(),await M.write(o,i),i}function ro(){if(process.env.USER)return process.env.USER;if(process.env.USERNAME)return process.env.USERNAME;return d.userInfo().username}function no(){return Intl.DateTimeFormat().resolvedOptions().locale}function eo(){return Intl.DateTimeFormat().resolvedOptions().timeZone}async function to(){let o=d.cpus();return{os:{platform:d.platform(),arch:d.arch(),release:d.release(),hostname:d.hostname()},cpu:{model:o[0]?.model??"unknown",count:o.length},memory:{total_bytes:d.totalmem()},user:{username:ro(),homedir:d.homedir()},runtime:{bun_version:Bun.version,node_version:process.versions.node,pid:process.pid,timezone:eo(),locale:no()},paths:{cwd:process.cwd(),data:I.Path.data,config:I.Path.config},qitqode:{version:K,channel:j,installation_id:await A(),run_id:q,process_role:H}}}var W={};a(W,{toString:()=>mo,parse:()=>co,match:()=>so,fromParsedKey:()=>fo});function so(o,r){if(!o)return!1;let n={...o,super:o.super??!1},e={...r,super:r.super??!1};return V(n,e)}function fo(o,r=!1){return{name:o.name===" "?"space":o.name,ctrl:o.ctrl,meta:o.meta,shift:o.shift,super:o.super??!1,leader:r}}function mo(o){if(!o)return"";let r=[];if(o.ctrl)r.push("ctrl");if(o.meta)r.push("alt");if(o.super)r.push("super");if(o.shift)r.push("shift");if(o.name)if(o.name==="delete")r.push("del");else r.push(o.name);let n=r.join("+");if(o.leader)n=n?`<leader> ${n}`:"<leader>";return n}function co(o){if(o==="none")return[];return o.split(",").map((r)=>{let e=r.replace(/<leader>/g,"leader+").toLowerCase().split("+"),t={ctrl:!1,meta:!1,shift:!1,leader:!1,name:""};for(let s of e)switch(s){case"ctrl":t.ctrl=!0;break;case"alt":case"meta":case"option":t.meta=!0;break;case"super":t.super=!0;break;case"shift":t.shift=!0;break;case"leader":t.leader=!0;break;case"esc":t.name="escape";break;default:t.name=s;break}return t})}var B={};a(B,{create:()=>io,NotFound:()=>O});import{AsyncLocalStorage as ao}from"async_hooks";class O extends Error{name;constructor(o){super(`No context found for ${o}`);this.name=o}}function io(o){let r=new ao;return{use(){let n=r.getStore();if(!n)throw new O(o);return n},provide(n,e){return r.run(n,e)}}}var X={};a(X,{truncateMiddle:()=>To,truncate:()=>Ro,todayTimeOrDateTime:()=>xo,titlecase:()=>wo,time:()=>N,pluralize:()=>Mo,number:()=>Io,duration:()=>Eo,datetime:()=>G});function wo(o){return o.replace(/\b\w/g,(r)=>r.toUpperCase())}function N(o){return new Date(o).toLocaleTimeString(void 0,{timeStyle:"short"})}function G(o){let r=new Date(o),n=N(o),e=r.toLocaleDateString();return`${n} \xB7 ${e}`}function xo(o){let r=new Date(o),n=new Date;if(r.getFullYear()===n.getFullYear()&&r.getMonth()===n.getMonth()&&r.getDate()===n.getDate())return N(o);else return G(o)}function Io(o){if(o>=1e6)return(o/1e6).toFixed(1)+"M";else if(o>=1000)return(o/1000).toFixed(1)+"K";return o.toString()}function Eo(o){if(o<1000)return`${o}ms`;if(o<60000)return`${(o/1000).toFixed(1)}s`;if(o<3600000){let e=Math.floor(o/60000),t=Math.floor(o%60000/1000);return`${e}m ${t}s`}if(o<86400000){let e=Math.floor(o/3600000),t=Math.floor(o%3600000/60000);return`${e}h ${t}m`}let r=Math.floor(o%86400000/3600000);return`${Math.floor(o/86400000)}d ${r}h`}function Ro(o,r){if(r<=0)return"";if(o.length<=r)return o;return o.slice(0,r-1)+"\u2026"}function To(o,r=35){if(r<=0)return"";if(o.length<=r)return o;let n="\u2026",e=Math.ceil((r-n.length)/2),t=Math.floor((r-n.length)/2);return o.slice(0,e)+n+(t>0?o.slice(-t):"")}function Mo(o,r,n){return(o===1?r:n).replace("{}",o.toString())}var h={};a(h,{write:()=>Oo,read:()=>_o});var E=new Map;function Y(o){if(!E.has(o))E.set(o,{readers:0,writer:!1,waitingReaders:[],waitingWriters:[]});return E.get(o)}function So(o){let r=E.get(o);if(!r||r.writer||r.readers>0)return;if(r.waitingWriters.length>0){r.waitingWriters.shift()();return}while(r.waitingReaders.length>0)r.waitingReaders.shift()();if(r.readers===0&&!r.writer&&r.waitingReaders.length===0&&r.waitingWriters.length===0)E.delete(o)}function L(o){return new Promise((r)=>{let n=()=>{o.acquire();let e=!1;r({[Symbol.dispose]:()=>{if(e)return;e=!0,o.release(),So(o.key)}})};if(o.available())n();else o.waiting.push(n)})}async function _o(o){let r=Y(o);return L({key:o,available:()=>!r.writer&&r.waitingWriters.length===0,acquire:()=>r.readers++,release:()=>r.readers--,waiting:r.waitingReaders})}async function Oo(o){let r=Y(o);return L({key:o,available:()=>!r.writer&&r.readers===0,acquire:()=>{r.writer=!0},release:()=>{r.writer=!1},waiting:r.waitingWriters})}var z={};a(z,{listen:()=>No,emit:()=>go,client:()=>Po});function No(o){onmessage=async(r)=>{let n=JSON.parse(r.data);if(n.type==="rpc.request")try{let e=await o[n.method](n.input);postMessage(JSON.stringify({type:"rpc.result",result:e,id:n.id}))}catch(e){postMessage(JSON.stringify({type:"rpc.result",error:e instanceof Error?e.message:String(e),id:n.id}))}}}function go(o,r){postMessage(JSON.stringify({type:"rpc.event",event:o,data:r}))}function Po(o){let r=new Map,n=new Map,e=0;return o.onmessage=async(t)=>{let s=JSON.parse(t.data);if(s.type==="rpc.result"){let f=r.get(s.id);if(f)if(r.delete(s.id),"error"in s)f.reject(Error(typeof s.error==="string"?s.error:"RPC call failed"));else f.resolve(s.result)}if(s.type==="rpc.event"){let f=n.get(s.event);if(f)for(let w of f)w(s.data)}},{call(t,s){let f=e++;return new Promise((w,R)=>{r.set(f,{resolve:w,reject:R});try{o.postMessage(JSON.stringify({type:"rpc.request",method:t,input:s,id:f}))}catch(S){r.delete(f),R(S)}})},on(t,s){let f=n.get(t);if(!f)f=new Set,n.set(t,f);return f.add(s),()=>{f.delete(s)}}}}var D={};a(D,{estimate:()=>Z});function Z(o){return Math.max(0,Math.round((o||"").length/4))}export{U as xr,$ as yr,Q as zr,A as Ar,to as Br,W as Cr,B as Dr,X as Er,h as Fr,Po as Gr,z as Hr,D as Ir};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T as I}from"./chunk-gbkz04ke.js";import{U as i,W as r}from"./chunk-
|
|
2
|
+
import{T as I}from"./chunk-gbkz04ke.js";import{U as i,W as r}from"./chunk-3akv2xqh.js";import{Hd as c}from"./chunk-bwbqkfv0.js";import{Id as g}from"./chunk-32j0q58h.js";import{Jd as y}from"./chunk-0cnwsf8p.js";import{Kd as k}from"./chunk-2md6sx8d.js";import{Ld as A}from"./chunk-wyj8cpx5.js";import{Qd as w,Rd as u,Td as W,Ud as L,Vd as T,Xd as p,Yd as o,Zd as b,_d as P}from"./chunk-ff548b0j.js";import"./chunk-zc0cdvcv.js";import{ae as z}from"./chunk-5w76kdjr.js";import{dg as Y}from"./chunk-eg3syjtv.js";import{Bh as M}from"./chunk-v3nqkqhz.js";import"./chunk-w46g7kdq.js";import"./chunk-bd21p9zz.js";import"./chunk-p54bzjtv.js";import"./chunk-ha1w0xzh.js";import"./chunk-6m9jb0s9.js";import"./chunk-vygkwwjd.js";import{Qk as a,dl as s,xj as R}from"./chunk-52frd9p0.js";import{pl as V}from"./chunk-xqnzmr7a.js";import{Nl as n}from"./chunk-r1xh50b2.js";import"./chunk-13rsd5vv.js";import"./chunk-mh19kwzw.js";import"./chunk-a9a0cwmf.js";import"./chunk-nw3e93y8.js";import"./chunk-9zm6r55d.js";import"./chunk-vcygx6hs.js";import"./chunk-khzzmyk2.js";import"./chunk-y7hgevfv.js";import"./chunk-47k5jy1p.js";import"./chunk-kn8w69g9.js";import"./chunk-ph8hn1wt.js";import"./chunk-ptqk1j2r.js";import"./chunk-cqtkxwd8.js";import"./chunk-pr7z5dj8.js";import"./chunk-dnnkq5y4.js";import"./chunk-t239rvej.js";import"./chunk-yz25607t.js";import"./chunk-7hvf9dgx.js";import"./chunk-wkg3c643.js";import"./chunk-fhqfqd5v.js";import"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import"./chunk-t5xxs5kp.js";import{Nr as l}from"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-nj1ntakd.js";import"./chunk-cmb62jkt.js";import"./chunk-tkrwcjkr.js";import"./chunk-w2cb8cry.js";import{ks as d}from"./chunk-kj8cmn7z.js";import"./chunk-r5zy4za0.js";import"./chunk-tr6rdr6h.js";import{kt as v}from"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import{eH as O}from"./chunk-qnvsqnz5.js";import"./chunk-pxm4qvqk.js";import"./chunk-j8fcfhr2.js";import{wO as H1}from"./chunk-r9w0thdk.js";import f from"path";import{pathToFileURL as J1}from"url";import Q1 from"os";import{access as S1,readdir as X1}from"fs/promises";var q1={en:A,zh:k,ja:c,fr:y,ru:g},B1=q1[I()]??A;function U($,B){let J=B1[$]??A[$]??$;if(!B)return J;return J.replace(/\{(\w+)\}/g,(X,H)=>(H in B)?String(B[H]):`{${H}}`)}import{text as Z1}from"stream/consumers";var D=($,B)=>M.runPromise(O.gen(function*(){yield*(yield*R.Service).set($,B)}));async function t(){let $=await p({message:"Enter your API key",validate:(B)=>B&&B.length>0?void 0:"Required"});if(w($))throw new Y.CancelledError;return $}async function h($,B){let J=$.provider??B;if("refresh"in $){let{type:X,provider:H,refresh:Z,access:j,expires:q,metadata:S,...G}=$;await D(J,{type:"oauth",refresh:Z,access:j,expires:q,...G})}if("key"in $)await D(J,{type:"api",key:$.key,...$.metadata?{metadata:$.metadata}:{}})}async function x($,B,J){let X=0;if(J){let j=$.auth.methods.findIndex((q)=>q.label.toLowerCase()===J.toLowerCase());if(j===-1)W.error(`Unknown method "${J}" for ${B}. Available: ${$.auth.methods.map((q)=>q.label).join(", ")}`),process.exit(1);X=j}else if($.auth.methods.length>1){let j=await b({message:"Login method",options:$.auth.methods.map((q,S)=>({label:q.label,value:S.toString()}))});if(w(j))throw new Y.CancelledError;X=parseInt(j)}let H=$.auth.methods[X];await new Promise((j)=>setTimeout(j,10));let Z={};if(H.prompts)for(let j of H.prompts){if(j.when){let q=Z[j.when.key];if(q===void 0)continue;if(!(j.when.op==="eq"?q===j.when.value:q!==j.when.value))continue}if(j.condition&&!j.condition(Z))continue;if(j.type==="select"){let q=await b({message:j.message,options:j.options});if(w(q))throw new Y.CancelledError;Z[j.key]=q}else{let q=await P({message:j.message,placeholder:j.placeholder,validate:j.validate?(S)=>j.validate(S??""):void 0});if(w(q))throw new Y.CancelledError;Z[j.key]=q}}if(H.type==="oauth"){let j=await H.authorize(Z);if(j.url)W.info("Go to: "+j.url);if(j.method==="auto"){if(j.instructions)W.info(j.instructions);let q=o();q.start("Waiting for authorization...");let S=await j.callback();if(S.type==="failed")q.stop("Failed to authorize",1);if(S.type==="success")await h(S,B),q.stop("Login successful")}if(j.method==="code"){let q=await P({message:"Paste the authorization code here: ",validate:(G)=>G&&G.length>0?void 0:"Required"});if(w(q))throw new Y.CancelledError;let S=await j.callback(q);if(S.type==="failed")W.error("Failed to authorize");if(S.type==="success")await h(S,B),W.success("Login successful")}return T("Done"),!0}if(H.type==="api"){if(H.authorize){let j=await t(),q=await H.authorize(Z);if(q.type==="failed")W.error("Failed to authorize");if(q.type==="success"){let S=q.provider??B;await D(S,{type:"api",key:q.key??j}),W.success("Login successful")}return T("Done"),!0}}return!1}function G1($){let B=new Set,J=[];for(let X of $.hooks){if(!X.auth)continue;let H=X.auth.provider;if(B.has(H))continue;if(B.add(H),Object.hasOwn($.existingProviders,H))continue;if($.disabled.has(H))continue;if($.enabled&&!$.enabled.has(H))continue;J.push({id:H,name:$.providerNames[H]??H})}return J}function m($){let B=$?.loginExtension;if(!B||typeof B!=="object")return;let J=B;if(typeof J.id!=="string"||typeof J.run!=="function")return;return J}async function W1(){try{let J=await import("./chunk-wbw9zv3h.js");for(let X of Object.values(J.modules??{})){let H=m(X);if(H)return H}}catch{}let $=f.join(import.meta.dir,"..","..","ext");await S1($).catch(()=>{return});let B=await X1($).catch(()=>[]);for(let J of B.filter((X)=>X.endsWith(".ts")&&!X.endsWith(".d.ts")))try{let X=m(await import(J1(f.join($,J)).href));if(X)return X}catch{}return}var l1=z({command:"providers",aliases:["auth"],describe:"manage AI providers and credentials",builder:($)=>$.command(Y1).command(_1).command(F1).command(K1).demandCommand(),async handler(){}}),Y1=z({command:"list",aliases:["ls"],describe:"list providers and credentials",async handler($){Y.empty();let B=f.join(v.Path.data,"auth.json"),J=Q1.homedir(),X=B===J||B.startsWith(J+f.sep)?"~"+B.slice(J.length):B;L(`Credentials ${Y.Style.TEXT_DIM}${X}`);let H=await M.runPromise(O.gen(function*(){let q=yield*R.Service;return Object.entries(yield*q.all())})),Z=await V.get();for(let[q,S]of H){let G=Z[q]?.name||q;W.info(`${G} ${Y.Style.TEXT_DIM}${S.type}`)}T(`${H.length} credentials`);let j=[];for(let[q,S]of Object.entries(Z))for(let G of S.env)if(process.env[G])j.push({provider:S.name||q,envVar:G});if(j.length>0){Y.empty(),L("Environment");for(let{provider:q,envVar:S}of j)W.info(`${q} ${Y.Style.TEXT_DIM}${S}`);T(`${j.length} environment variable`+(j.length===1?"":"s"))}}}),_1=z({command:"login [url]",describe:"log in to a provider",builder:($)=>$.positional("url",{describe:"qitqode auth provider",type:"string"}).option("provider",{alias:["p"],describe:"provider id or name to log in to (skips provider selection)",type:"string"}).option("method",{alias:["m"],describe:"login method label (skips method selection)",type:"string"}),async handler($){await n.provide({directory:process.cwd(),async fn(){if(Y.empty(),L("Add credential"),$.url){let Q=$.url.replace(/\/+$/,""),_=await fetch(`${Q}/.well-known/opencode`).then((j1)=>j1.json());W.info(`Running \`${_.auth.command.join(" ")}\``);let F=l.spawn(_.auth.command,{stdout:"pipe"});if(!F.stdout){W.error("Failed"),T("Done");return}let[C,N]=await Promise.all([F.exited,Z1(F.stdout)]);if(C!==0){W.error("Failed"),T("Done");return}await D(Q,{type:"wellknown",key:_.auth.env,token:N.trim()}),W.success("Logged into "+Q),T("Done");return}await V.refresh(!0).catch(()=>{});let B=await M.runPromise(s.Service.use((Q)=>Q.get())),J=new Set(B.disabled_providers??[]),X=B.enabled_providers?new Set(B.enabled_providers):void 0,H=await V.get().then((Q)=>{let _={};for(let[F,C]of Object.entries(Q))if((X?X.has(F):!0)&&!J.has(F))_[F]=C;return _}),Z=await M.runPromise(O.gen(function*(){return yield*(yield*a.Service).list()})),j=i,q=G1({hooks:Z,existingProviders:H,disabled:J,enabled:X,providerNames:Object.fromEntries(Object.entries(B.provider??{}).map(([Q,_])=>[Q,_.name]))}),S=[...r(d(H),j,(Q)=>({openai:"ChatGPT Plus/Pro or API key"})[Q.id]),...q.map((Q)=>({label:Q.name,value:Q.id,hint:"plugin"}))],G=await W1(),e=G?[G.id,...G.aliases??[]]:[],K;if(G&&$.provider&&e.includes($.provider)){await G.run();return}else if($.provider){let Q=$.provider,_=S.find((N)=>N.value===Q),F=S.find((N)=>N.label.toLowerCase()===Q.toLowerCase()),C=_??F;if(!C)W.error(`Unknown provider "${Q}"`),process.exit(1);K=C.value}else{let Q=await b({message:U("cli.providers.select"),options:[...G?.menu?[{label:G.menu.label,value:G.id,hint:G.menu.hint}]:[],{label:U("cli.providers.other"),value:"__other__"}]});if(w(Q))throw new Y.CancelledError;if(G&&Q===G.id){await G.run();return}let _=await u({message:U("cli.providers.select"),maxItems:8,options:[...S,{value:"other",label:"Other"}]});if(w(_))throw new Y.CancelledError;K=_}let E=Z.findLast((Q)=>Q.auth?.provider===K);if(E&&E.auth){if(await x({auth:E.auth},K,$.method))return}if(K==="other"){let Q=await P({message:"Enter provider id",validate:(F)=>F&&F.match(/^[0-9a-z-]+$/)?void 0:"a-z, 0-9 and hyphens only"});if(w(Q))throw new Y.CancelledError;K=Q.replace(/^@ai-sdk\//,"");let _=Z.findLast((F)=>F.auth?.provider===K);if(_&&_.auth){if(await x({auth:_.auth},K,$.method))return}W.warn(`This only stores a credential for ${K} - you will need configure it in qitqode.json, check the docs for examples.`)}if(K==="amazon-bedrock")W.info(`Amazon Bedrock authentication priority:
|
|
3
3
|
1. Bearer token (AWS_BEARER_TOKEN_BEDROCK or /connect)
|
|
4
4
|
2. AWS credential chain (profile, access keys, IAM roles, EKS IRSA)
|
|
5
5
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Td as q,Ud as K,Vd as D,Yd as L,Zd as N}from"./chunk-ff548b0j.js";import"./chunk-zc0cdvcv.js";import{dg as B}from"./chunk-eg3syjtv.js";import{Bh as G}from"./chunk-
|
|
2
|
+
import{Td as q,Ud as K,Vd as D,Yd as L,Zd as N}from"./chunk-ff548b0j.js";import"./chunk-zc0cdvcv.js";import{dg as B}from"./chunk-eg3syjtv.js";import{Bh as G}from"./chunk-v3nqkqhz.js";import"./chunk-w46g7kdq.js";import"./chunk-bd21p9zz.js";import"./chunk-p54bzjtv.js";import"./chunk-ha1w0xzh.js";import"./chunk-6m9jb0s9.js";import"./chunk-vygkwwjd.js";import"./chunk-52frd9p0.js";import{fl as C}from"./chunk-xqnzmr7a.js";import"./chunk-r1xh50b2.js";import"./chunk-13rsd5vv.js";import"./chunk-mh19kwzw.js";import"./chunk-a9a0cwmf.js";import"./chunk-nw3e93y8.js";import"./chunk-9zm6r55d.js";import"./chunk-vcygx6hs.js";import"./chunk-khzzmyk2.js";import"./chunk-y7hgevfv.js";import"./chunk-47k5jy1p.js";import"./chunk-kn8w69g9.js";import"./chunk-ph8hn1wt.js";import"./chunk-ptqk1j2r.js";import"./chunk-cqtkxwd8.js";import"./chunk-pr7z5dj8.js";import"./chunk-dnnkq5y4.js";import"./chunk-t239rvej.js";import"./chunk-yz25607t.js";import"./chunk-7hvf9dgx.js";import"./chunk-wkg3c643.js";import"./chunk-fhqfqd5v.js";import"./chunk-2b3fn9xv.js";import"./chunk-rn043d0r.js";import"./chunk-73r8bjjz.js";import"./chunk-t5xxs5kp.js";import"./chunk-ztyy3ga3.js";import"./chunk-mmjgf680.js";import"./chunk-nj1ntakd.js";import"./chunk-cmb62jkt.js";import"./chunk-tkrwcjkr.js";import"./chunk-w2cb8cry.js";import{ds as J}from"./chunk-kj8cmn7z.js";import"./chunk-r5zy4za0.js";import"./chunk-tr6rdr6h.js";import"./chunk-at22twxx.js";import"./chunk-kgptyf7n.js";import"./chunk-j9h1sp4g.js";import"./chunk-p6crzjtf.js";import"./chunk-55fcmswd.js";import"./chunk-qnvsqnz5.js";import"./chunk-pxm4qvqk.js";import"./chunk-j8fcfhr2.js";import"./chunk-r9w0thdk.js";var X={command:"upgrade [target]",describe:"upgrade qitqode to the latest or a specific version",builder:(z)=>{return z.positional("target",{describe:"version to upgrade to, for ex '0.1.48' or 'v0.1.48'",type:"string"}).option("method",{alias:"m",describe:"installation method to use",type:"string",choices:["curl","npm","pnpm","bun","brew","choco","scoop"]})},handler:async(z)=>{B.empty(),B.println(B.logo(" ")),B.empty(),K("Upgrade");let O=await G.runPromise(C.Service.use((j)=>j.method())),E=z.method??O;if(E==="unknown"){if(q.error(`qitqode is installed to ${process.execPath} and may be managed by a package manager`),!await N({message:"Install anyways?",options:[{label:"Yes",value:!0},{label:"No",value:!1}],initialValue:!1})){D("Done");return}}q.info("Using method: "+E);let F=z.target?z.target.replace(/^v/,""):await G.runPromise(C.Service.use((j)=>j.latest()));if(J===F){q.warn(`qitqode upgrade skipped: ${F} is already installed`),D("Done");return}q.info(`From ${J} \u2192 ${F}`);let H=L();H.start("Upgrading...");let x=await G.runPromise(C.Service.use((j)=>j.upgrade(E,F))).catch((j)=>j);if(x){if(H.stop("Upgrade failed",1),x instanceof C.UpgradeFailedError)if(E==="choco"&&x.stderr.includes("not running from an elevated command shell"))q.error("Please run the terminal as Administrator and try again");else q.error(x.stderr);else if(x instanceof Error)q.error(x.message);D("Done");return}H.stop("Upgrade complete"),D("Done")}};export{X as UpgradeCommand};
|