@qitqode/qitqode-android-arm64 0.1.31 → 0.1.32

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/bundle/{chunk-c14s0kxq.js → chunk-02jtpxe0.js} +1 -1
  2. package/bundle/{chunk-6t1ehq36.js → chunk-096pd6c4.js} +1 -1
  3. package/bundle/{chunk-jcjbr3q7.js → chunk-0c2p3a6v.js} +1 -1
  4. package/bundle/{chunk-53w4zqps.js → chunk-0c5rxty9.js} +1 -1
  5. package/bundle/{chunk-9mjz6e27.js → chunk-0e86gt9r.js} +1 -1
  6. package/bundle/{chunk-6bpe215q.js → chunk-15j5cn4t.js} +1 -1
  7. package/bundle/{chunk-0w0ctb90.js → chunk-1r95p0tp.js} +1 -1
  8. package/bundle/{chunk-mh0j6dzy.js → chunk-20702epe.js} +1 -1
  9. package/bundle/{chunk-04n2ycg5.js → chunk-257me4z3.js} +4 -4
  10. package/bundle/{chunk-83gqkmth.js → chunk-2phz0bn9.js} +1 -1
  11. package/bundle/{chunk-1fswr17z.js → chunk-2wajs9xv.js} +1 -1
  12. package/bundle/{chunk-3ytjm3az.js → chunk-3nx7112w.js} +1 -1
  13. package/bundle/{chunk-drvkj3xg.js → chunk-3wetyrjs.js} +1 -1
  14. package/bundle/{chunk-20f83ca0.js → chunk-4sc82a27.js} +1 -1
  15. package/bundle/{chunk-4gkk28xk.js → chunk-56z7x7h4.js} +1 -1
  16. package/bundle/{chunk-hnctaq8s.js → chunk-59yqvk48.js} +1 -1
  17. package/bundle/{chunk-0yt5njh7.js → chunk-5jx0yadh.js} +2 -2
  18. package/bundle/{chunk-6bphjajd.js → chunk-5pb551dx.js} +1 -1
  19. package/bundle/{chunk-anwnwfjf.js → chunk-634pnryq.js} +1 -1
  20. package/bundle/{chunk-cnmq5xtq.js → chunk-6aqyhfag.js} +2 -2
  21. package/bundle/{chunk-gcw4rn10.js → chunk-764fksh3.js} +1 -1
  22. package/bundle/{chunk-cmbh77cs.js → chunk-7tr9ejyk.js} +1 -1
  23. package/bundle/{chunk-ssajqv72.js → chunk-7z777y9k.js} +1 -1
  24. package/bundle/{chunk-qvnb3j71.js → chunk-85wcc1tp.js} +1 -1
  25. package/bundle/{chunk-csz0dgyp.js → chunk-89w3yhf8.js} +1 -1
  26. package/bundle/chunk-8dwq41q1.js +28 -0
  27. package/bundle/{chunk-11x3t2tt.js → chunk-8r6ht39z.js} +1 -1
  28. package/bundle/{chunk-d68fzyw7.js → chunk-9gazyynx.js} +1 -1
  29. package/bundle/{chunk-ehhas0ew.js → chunk-ad72gb5f.js} +1 -1
  30. package/bundle/{chunk-gbrnn2dk.js → chunk-avf8v3hb.js} +1 -1
  31. package/bundle/{chunk-fq0x3esz.js → chunk-caj1b9y7.js} +2 -2
  32. package/bundle/chunk-d0damw6y.js +2 -0
  33. package/bundle/{chunk-qbc36nbb.js → chunk-d3ermm6d.js} +1 -1
  34. package/bundle/{chunk-c1bdzxbx.js → chunk-d9hbhkbq.js} +1 -1
  35. package/bundle/{chunk-bgw4fvg2.js → chunk-e5mv5wnt.js} +1 -1
  36. package/bundle/{chunk-31mnd3ph.js → chunk-ew9pdrp9.js} +1 -1
  37. package/bundle/{chunk-redjxn13.js → chunk-ezfy0b6q.js} +1 -1
  38. package/bundle/{chunk-takew94z.js → chunk-gz8sz7z1.js} +1 -1
  39. package/bundle/{chunk-abd1cfpg.js → chunk-h6f3kbz2.js} +1 -1
  40. package/bundle/{chunk-r4ndwym0.js → chunk-hnvn2c25.js} +1 -1
  41. package/bundle/{chunk-pxvk3syj.js → chunk-jdynx7m6.js} +1 -1
  42. package/bundle/{chunk-ez8vkgfz.js → chunk-k1txw65h.js} +1 -1
  43. package/bundle/{chunk-mxzceza9.js → chunk-k5atbdbm.js} +1 -1
  44. package/bundle/{chunk-4d87mhwn.js → chunk-k75jqg60.js} +1 -1
  45. package/bundle/{chunk-pctt1qv8.js → chunk-k7aenxan.js} +1 -1
  46. package/bundle/{chunk-s9ntkjz3.js → chunk-m2q317gh.js} +1 -1
  47. package/bundle/{chunk-1f7ajq8s.js → chunk-mahgmbt9.js} +1 -1
  48. package/bundle/{chunk-68yw2hk9.js → chunk-mqd1jsg2.js} +1 -1
  49. package/bundle/{chunk-8ymffyep.js → chunk-nkkch4h7.js} +1 -1
  50. package/bundle/{chunk-z6pwkwdr.js → chunk-pje60pj2.js} +1 -1
  51. package/bundle/{chunk-c1vnp55z.js → chunk-pv67gwce.js} +1 -1
  52. package/bundle/{chunk-50sv6y2e.js → chunk-q7vasbxn.js} +1 -1
  53. package/bundle/chunk-qadw6j20.js +2 -0
  54. package/bundle/{chunk-n0dy98h2.js → chunk-qggcszs2.js} +1 -1
  55. package/bundle/{chunk-873skv7w.js → chunk-r7sqdfad.js} +1 -1
  56. package/bundle/{chunk-50tb3g5x.js → chunk-r8m7rtfc.js} +1 -1
  57. package/bundle/{chunk-7pfj4x1a.js → chunk-rkyf0cp8.js} +1 -1
  58. package/bundle/{chunk-f8eter69.js → chunk-rza530gm.js} +1 -1
  59. package/bundle/{chunk-mcg24gkb.js → chunk-s3mnrhbx.js} +1 -1
  60. package/bundle/{chunk-f2btnww9.js → chunk-s6ktx2sx.js} +1 -1
  61. package/bundle/{chunk-eh7e49k4.js → chunk-w7vh8cxt.js} +1 -1
  62. package/bundle/{chunk-pf9g671w.js → chunk-w8saweey.js} +1 -1
  63. package/bundle/{chunk-r78czx4d.js → chunk-we9cv8we.js} +1 -1
  64. package/bundle/{chunk-3h9rq2wq.js → chunk-wezarrvy.js} +1 -1
  65. package/bundle/{chunk-g9cjsfvg.js → chunk-whe7h2mj.js} +1 -1
  66. package/bundle/{chunk-phv9kdq6.js → chunk-wmqsdt2c.js} +1 -1
  67. package/bundle/{chunk-fjq3a347.js → chunk-wqj0xasg.js} +1 -1
  68. package/bundle/{chunk-vb286b31.js → chunk-wr42tphe.js} +1 -1
  69. package/bundle/{chunk-fyqjm5fv.js → chunk-x25zkrz7.js} +1 -1
  70. package/bundle/{chunk-m5m448mg.js → chunk-xj765svc.js} +1 -1
  71. package/bundle/{chunk-d65qs4d0.js → chunk-xrs18kzn.js} +1 -1
  72. package/bundle/{chunk-5v0xjs3x.js → chunk-y6123zvq.js} +1 -1
  73. package/bundle/{chunk-fxdtq2ed.js → chunk-y7sy3w6z.js} +1 -1
  74. package/bundle/{chunk-44a82dg0.js → chunk-ygs5pzk7.js} +2 -2
  75. package/bundle/{chunk-jxswwvr3.js → chunk-za7mwbye.js} +1 -1
  76. package/bundle/{chunk-vbeb74ny.js → chunk-zaks8cae.js} +1 -1
  77. package/bundle/{chunk-9x5232dw.js → chunk-zcsgqk9f.js} +1 -1
  78. package/bundle/{chunk-5eq1fft9.js → chunk-zqqx96jx.js} +1 -1
  79. package/bundle/index.js +3 -3
  80. package/bundle/worker.js +1 -1
  81. package/package.json +1 -1
  82. package/bundle/chunk-excnptfy.js +0 -2
  83. package/bundle/chunk-nsk8dkwp.js +0 -28
  84. package/bundle/chunk-ppjnqexm.js +0 -2
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{rm as f,sm as Gj,tm as Rj,um as Hj,xm as s}from"./chunk-redjxn13.js";import{go as xj}from"./chunk-htz93dsd.js";import{Co as vj}from"./chunk-2hc5z7b5.js";import{br as P,cr as wj,ir as k,jr as Kj}from"./chunk-d6ry9418.js";import{Ms as Ij,Ns as Jj,Qs as Nj,Rs as I,Vr as a,Wr as y,_s as h}from"./chunk-m5m448mg.js";import{st as i}from"./chunk-tqj69nh6.js";import{ut as j}from"./chunk-5tray1fw.js";import{OE as o,QN as l,RM as C,hF as d,pH as Q,zC as Wj}from"./chunk-zs8kqdsf.js";import{BO as Mj,DO as Oj,FO as Ej}from"./chunk-7xm75w1e.js";var tj={};Oj(tj,{stopRefresh:()=>aj,startRefresh:()=>sj,refresh:()=>jj,readModelCatalogResponse:()=>Pj,get:()=>fj,Provider:()=>cj,Model:()=>pj,MODEL_CATALOG_MAX_BYTES:()=>Aj,Data:()=>S});import hj from"path";var U={};Oj(U,{layer:()=>Bj,isPreview:()=>ij,isNewerVersion:()=>qj,isLocal:()=>mj,getReleaseType:()=>yj,defaultLayer:()=>uj,UpgradeFailedError:()=>x,USER_AGENT:()=>Sj,Service:()=>E,Installation:()=>U,Info:()=>Uj,Event:()=>Cj});var _j=(J)=>J.pipe(k.retryTransient({retryOn:"errors-and-responses",times:2,schedule:d.exponential(200).pipe(d.jittered)}));import Yj from"path";var z=Mj(xj(),1);import n from"crypto";import v from"fs";import Zj from"path";class H extends Error{constructor(J){super(J);this.name="SelfUpdateError"}}function $j(J){let V=J?.platform??process.platform,_=J?.arch??process.arch,$=J?.libc??"bionic",W=["qitqode",V==="win32"?"windows":V,_];if(_==="x64")W.push("baseline");if(V==="linux"&&$==="musl")W.push("musl");return`@qitqode/${W.join("-")}`}function kj(J,V){if(V.integrity){let _=V.integrity.match(/^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/);if(!_)throw new H(`registry returned an unrecognized integrity string: ${V.integrity}`);if(n.createHash(_[1]).update(J).digest("base64")!==_[2])throw new H(`checksum mismatch: downloaded tarball does not match the registry ${_[1]} integrity value; refusing to install`);return}if(V.shasum){if(n.createHash("sha1").update(J).digest("hex")!==V.shasum.toLowerCase())throw new H("checksum mismatch: downloaded tarball does not match the registry shasum; refusing to install");return}throw new H("registry provided no integrity metadata for the tarball; refusing to install")}function Qj(J,V){let _=(w,R)=>{let G=w,q=w+R;while(G<q&&J[G]!==0)G++;return new TextDecoder().decode(J.subarray(w,G))},$=0,W;while($+512<=J.length){if(J.subarray($,$+512).every((Z)=>Z===0))break;let R=_($+124,12).trim(),G=R?parseInt(R,8):0;if(!Number.isFinite(G)||G<0)throw new H("downloaded tarball is corrupt (bad tar header)");let q=String.fromCharCode(J[$+156]),B=_($,100),N=_($+345,155);if(N)B=`${N}/${B}`;if(W)B=W,W=void 0;let b=$+512,X=b+G;if(q==="L")W=new TextDecoder().decode(J.subarray(b,X)).replace(/\0+$/,"");else if((q==="0"||q==="\x00"||q==="")&&B===V)return J.slice(b,X);$=b+Math.ceil(G/512)*512}return}var A=(J)=>String(J instanceof Error?J.message:J),u=(J)=>Q.fail(new H(J)),p=(J,V)=>Q.try({try:J,catch:(_)=>new H(V(_))}),Xj=Q.fnUntraced(function*(J){let{target:V,execPath:_,packageName:$,registry:W}=J,w=J.gunzip??((K)=>Bun.gunzipSync(K)),R=Zj.dirname(_);yield*p(()=>v.accessSync(R,v.constants.W_OK),()=>`no write permission for ${R}; cannot replace ${_}. Fix the directory permissions or re-run with sufficient privileges.`);let G=`${W}/${$}/${encodeURIComponent(V)}`,B=(yield*J.fetchJson(G).pipe(Q.mapError((K)=>new H(`download failed: could not fetch ${$}@${V} from ${W} (${A(K)}). Check your network connection and that version ${V} exists.`))))?.dist;if(!B?.tarball)return yield*u(`registry response for ${$}@${V} has no tarball URL; cannot self-update`);let N=B.tarball,b=yield*J.fetchBytes(N).pipe(Q.mapError((K)=>new H(`download failed: could not download ${N} (${A(K)}). Check your network connection and try again.`)));yield*Q.try({try:()=>kj(b,B),catch:(K)=>K instanceof H?K:new H(A(K))});let X=yield*Q.try({try:()=>w(b),catch:()=>new H("downloaded tarball is corrupt (gunzip failed); try again")}),Z=Qj(X,"package/bin/qitqode")??Qj(X,"package/bin/qitqode.exe");if(!Z||Z.length===0)return yield*u(`tarball for ${$}@${V} does not contain the expected binary at bin/qitqode`);let O=Zj.join(R,`.qitqode-upgrade-${process.pid}`),Y=`${_}.backup-${process.pid}`,D=(K)=>{try{v.rmSync(K,{force:!0})}catch{}};yield*p(()=>v.writeFileSync(O,Z,{mode:493}),(K)=>{return D(O),`no write permission: could not write ${O} (${A(K)})`});let L=yield*J.runVersion(O).pipe(Q.mapError((K)=>{return D(O),new H(`downloaded binary failed its --version check (${A(K)}); keeping the current installation`)}));if(L.code!==0)return D(O),yield*u(`downloaded binary failed its --version check (exit ${L.code}); keeping the current installation`);let m=L.stdout.trim();if(m&&!m.includes(V))return D(O),yield*u(`downloaded binary reports version "${m}" instead of ${V}; keeping the current installation`);yield*p(()=>v.renameSync(_,Y),(K)=>{return D(O),`could not move the current binary aside (${A(K)}); check permissions on ${_}`}),yield*Q.try({try:()=>v.renameSync(O,_),catch:(K)=>{try{v.renameSync(Y,_)}catch{return new H(`failed to install the new binary AND failed to restore the old one; your previous binary is preserved at ${Y} \u2014 move it back to ${_} manually`)}return D(O),new H(`could not install the new binary (${A(K)}); the previous version was restored`)}}),D(Y)});var c=h.create({service:"installation"}),M="@qitqode/cli";function qj(J,V){if(!z.default.valid(J)||!z.default.valid(V))return!1;return z.default.gt(V,J)}var Cj={Updated:s.define("installation.updated",j.object({version:j.string()})),UpdateAvailable:s.define("installation.update-available",j.object({version:j.string()}))};function yj(J,V){if(!qj(J,V))throw Error(`Version ${V} is not newer than ${J}`);let _=z.default.major(J),$=z.default.minor(J),W=z.default.major(V),w=z.default.minor(V);if(W>_)return"major";if(w>$)return"minor";return"patch"}var Uj=j.object({version:j.string(),latest:j.string()}).meta({ref:"InstallationInfo"}),Sj=`qitqode/${y}/${a}/${I.QITQODE_CLIENT}`;function ij(){return y!=="latest"}function mj(){return y==="local"}class x extends C.TaggedErrorClass()("UpgradeFailedError",{stderr:C.String}){}var nj=C.Struct({version:C.String});class E extends Wj.Service()("@qitqode/Installation"){}var Bj=o.effect(E,Q.gen(function*(){let J=yield*k.HttpClient,V=k.filterStatusOk(_j(J)),_=yield*f.ChildProcessSpawner,$=(X,Z)=>Gj.make(X[0],X.slice(1),{cwd:Z?.cwd,env:Z?.env,extendEnv:!0}),W=Q.fnUntraced(function*(X){let Z=yield*Hj(_,X);return{code:Z.code,stdout:Z.text,stderr:Z.stderr}},Q.scoped),w=Q.fnUntraced(function*(X,Z){let O=yield*_.spawn($(X,Z)),Y=yield*l.mkString(l.decodeText(O.stdout));return yield*O.exitCode,Y},Q.scoped,Q.catch(()=>Q.succeed(""))),R=Q.fnUntraced(function*(X,Z){return yield*W($(X,Z))},Q.catch(()=>Q.succeed({code:f.ExitCode(1),stdout:"",stderr:""}))),G=Q.fn("Installation.method")(function*(){if(process.execPath.includes(Yj.join(".qitqode","bin")))return"curl";if(process.execPath.includes(Yj.join(".local","bin")))return"curl";let X=process.execPath.toLowerCase(),Z=[{name:"npm",command:()=>w(["npm","list","-g","--depth=0"])},{name:"pnpm",command:()=>w(["pnpm","list","-g","--depth=0"])},{name:"bun",command:()=>w(["bun","pm","ls","-g"])}];Z.sort((O,Y)=>{let D=X.includes(O.name),L=X.includes(Y.name);if(D&&!L)return-1;if(!D&&L)return 1;return 0});for(let O of Z)if((yield*O.command()).includes(M))return O.name;return"unknown"}),q=Q.fn("Installation.latest")(function*(X){let Z=X||(yield*G());if(Z==="curl"){let Y=(yield*w(["curl","-sI","https://github.com/qitqode/qitqode/releases/latest"])).match(/^location:.*\/tag\/v([0-9][^\s/]*)/im);if(Y)return Y[1];return yield*Q.die(Error("failed to resolve latest version from GitHub releases redirect"))}if(Z==="npm"||Z==="bun"||Z==="pnpm"){let Y=(yield*w(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org",D=Y.endsWith("/")?Y.slice(0,-1):Y,L=yield*V.execute(P.get(`${D}/${encodeURIComponent(M)}/${y}`).pipe(P.acceptJson));return(yield*wj.schemaBodyJson(nj)(L)).version}return c.warn("unsupported update channel, skipping",{method:Z}),yield*Q.die(Error(`unsupported update channel: ${Z}`))},Q.orDie),B=Q.fnUntraced(function*(){let Z=(yield*w(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org";return Z.endsWith("/")?Z.slice(0,-1):Z}),N=Q.fnUntraced(function*(X){let Z=yield*B();yield*Xj({target:X,execPath:process.env.QITQODE_SELF_UPDATE_TARGET_BINARY||process.execPath,packageName:$j(),registry:Z,fetchJson:(O)=>V.execute(P.get(O).pipe(P.acceptJson)).pipe(Q.flatMap((Y)=>Y.json)),fetchBytes:(O)=>V.execute(P.get(O)).pipe(Q.flatMap((Y)=>Y.arrayBuffer),Q.map((Y)=>new Uint8Array(Y))),runVersion:(O)=>R([O,"--version"]).pipe(Q.map((Y)=>({code:Y.code,stdout:Y.stdout})))}).pipe(Q.mapError((O)=>new x({stderr:O.message})))}),b=Q.fn("Installation.upgrade")(function*(X,Z){if(X==="curl"){yield*N(Z),c.info("upgraded",{method:X,target:Z});return}let Y=yield*(()=>{if(X==="npm")return R(["npm","install","-g",`${M}@${Z}`]);if(X==="pnpm")return R(["pnpm","install","-g",`${M}@${Z}`]);if(X==="bun")return R(["bun","install","-g",`${M}@${Z}`]);return new x({stderr:`Unknown method: ${X}`})})();if(Y.code!==0){let D=Y.stderr||"";return yield*new x({stderr:D})}c.info("upgraded",{method:X,target:Z,stdout:Y.stdout,stderr:Y.stderr}),yield*w([process.execPath,"--version"])});return E.of({info:Q.fn("Installation.info")(function*(){return{version:a,latest:yield*q()}}),method:G,latest:q,upgrade:b})})),uj=Bj.pipe(o.provide(Kj.layer),o.provide(Rj));var t=j.lazy(()=>j.union([j.string(),j.number(),j.boolean(),j.null(),j.array(t),j.record(j.string(),t)])),Dj=j.object({input:j.number(),output:j.number(),cache_read:j.number().optional(),cache_write:j.number().optional(),context_over_200k:j.object({input:j.number(),output:j.number(),cache_read:j.number().optional(),cache_write:j.number().optional()}).optional()}),r=j.object({id:j.string(),name:j.string(),family:j.string().optional(),release_date:j.string(),attachment:j.boolean(),reasoning:j.boolean(),temperature:j.boolean().optional(),tool_call:j.boolean(),interleaved:j.union([j.literal(!0),j.object({field:j.enum(["reasoning_content","reasoning_details"])}).strict()]).optional(),cost:Dj.optional(),limit:j.object({context:j.number(),input:j.number().optional(),output:j.number()}),modalities:j.object({input:j.array(j.enum(["text","audio","image","video","pdf"])),output:j.array(j.enum(["text","audio","image","video","pdf"]))}).optional(),experimental:j.object({modes:j.record(j.string(),j.object({cost:Dj.optional(),provider:j.object({body:j.record(j.string(),t).optional(),headers:j.record(j.string(),j.string()).optional()}).optional()})).optional()}).optional(),status:j.enum(["alpha","beta","deprecated"]).optional(),provider:j.object({npm:j.string().optional(),api:j.string().optional()}).optional()}),e=j.object({api:j.string().optional(),name:j.string(),env:j.array(j.string()),id:j.string(),npm:j.string().optional(),models:j.record(j.string(),r)});var Vj=h.create({service:"models.dev"}),bj=Fj(),F=hj.join(Nj.Path.cache,bj==="https://models.dev"?"models.json":`models-${Ij.fast(bj)}.json`),gj=300000,Aj=8388608,T,dj=j.record(j.string(),e),pj=r,cj=e;function Fj(){return I.QITQODE_MODELS_URL||"https://models.dev"}function lj(){return Date.now()-Number(i.stat(F)?.mtimeMs??0)<gj}function Lj(J){return!J&&lj()}function g(J){let V=dj.parse(typeof J==="string"?JSON.parse(J):J);for(let[_,$]of Object.entries(V))if($.id!==_)throw Error(`Invalid model provider: ${_}`);return V}async function zj(J){let V=await i.readJson(J).catch(()=>{return});if(!V)return;try{return g(V)}catch(_){Vj.warn("Ignoring invalid model catalog cache",{file:J,error:_});return}}async function Pj(J,V,_=Aj){let $=J.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if($!=="application/json"&&!$?.endsWith("+json"))throw Error(`Invalid model catalog content type: ${$||"missing"}`);let W=Number(J.headers.get("content-length"));if(Number.isFinite(W)&&W>_)throw Error("Model catalog response is too large");if(!J.body)return"";let w=J.body.getReader(),R=()=>void w.cancel(V.reason);V.addEventListener("abort",R,{once:!0});let G=new Uint8Array(_),q=0;try{for(;;){let B=await w.read();if(B.done)break;if(q+=B.value.byteLength,q>_)throw await w.cancel(),Error("Model catalog response is too large");G.set(B.value,q-B.value.byteLength)}}finally{V.removeEventListener("abort",R)}return new TextDecoder().decode(G.subarray(0,q))}var Tj=async()=>{let J=AbortSignal.timeout(1e4),V=await fetch(`${Fj()}/api.json`,{headers:{"User-Agent":U.USER_AGENT},signal:J});if(!V.ok)return;let _=g(await Pj(V,J));return JSON.stringify(_)},S=vj(async()=>{let J=await zj(I.QITQODE_MODELS_PATH??F);if(J)return J;let V=await import("./chunk-31qrzrwy.js").then((_)=>g(_.snapshot)).catch(()=>{return});if(V)return V;if(I.QITQODE_DISABLE_MODELS_FETCH)return{};return Jj.withLock(`models-dev:${F}`,async()=>{let _=await zj(I.QITQODE_MODELS_PATH??F);if(_)return _;let $=await Tj();if($)return await i.write(F,$).catch((W)=>{Vj.error("Failed to write models cache",{error:W})}),g($);return{}})});async function fj(){return S()}async function jj(J=!1){if(Lj(J))return S.reset();await Jj.withLock(`models-dev:${F}`,async()=>{if(Lj(J))return S.reset();let V=await Tj();if(!V)return;await i.write(F,V),S.reset()}).catch((V)=>{Vj.error("Failed to fetch models.dev",{error:V})})}function sj(){if(T||I.QITQODE_DISABLE_MODELS_FETCH||process.argv.includes("--get-yargs-completions"))return;jj(),T=setInterval(async()=>{await jj()},3600000),T.unref()}function aj(){if(!T)return;clearInterval(T),T=void 0}
2
+ import{rm as f,sm as Gj,tm as Rj,um as Hj,xm as s}from"./chunk-ezfy0b6q.js";import{go as xj}from"./chunk-htz93dsd.js";import{Co as vj}from"./chunk-2hc5z7b5.js";import{br as P,cr as wj,ir as k,jr as Kj}from"./chunk-d6ry9418.js";import{Ms as Ij,Ns as Jj,Qs as Nj,Rs as I,Vr as a,Wr as y,_s as h}from"./chunk-xj765svc.js";import{st as i}from"./chunk-tqj69nh6.js";import{ut as j}from"./chunk-5tray1fw.js";import{OE as o,QN as l,RM as C,hF as d,pH as Q,zC as Wj}from"./chunk-zs8kqdsf.js";import{BO as Mj,DO as Oj,FO as Ej}from"./chunk-7xm75w1e.js";var tj={};Oj(tj,{stopRefresh:()=>aj,startRefresh:()=>sj,refresh:()=>jj,readModelCatalogResponse:()=>Pj,get:()=>fj,Provider:()=>cj,Model:()=>pj,MODEL_CATALOG_MAX_BYTES:()=>Aj,Data:()=>S});import hj from"path";var U={};Oj(U,{layer:()=>Bj,isPreview:()=>ij,isNewerVersion:()=>qj,isLocal:()=>mj,getReleaseType:()=>yj,defaultLayer:()=>uj,UpgradeFailedError:()=>x,USER_AGENT:()=>Sj,Service:()=>E,Installation:()=>U,Info:()=>Uj,Event:()=>Cj});var _j=(J)=>J.pipe(k.retryTransient({retryOn:"errors-and-responses",times:2,schedule:d.exponential(200).pipe(d.jittered)}));import Yj from"path";var z=Mj(xj(),1);import n from"crypto";import v from"fs";import Zj from"path";class H extends Error{constructor(J){super(J);this.name="SelfUpdateError"}}function $j(J){let V=J?.platform??process.platform,_=J?.arch??process.arch,$=J?.libc??"bionic",W=["qitqode",V==="win32"?"windows":V,_];if(_==="x64")W.push("baseline");if(V==="linux"&&$==="musl")W.push("musl");return`@qitqode/${W.join("-")}`}function kj(J,V){if(V.integrity){let _=V.integrity.match(/^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/);if(!_)throw new H(`registry returned an unrecognized integrity string: ${V.integrity}`);if(n.createHash(_[1]).update(J).digest("base64")!==_[2])throw new H(`checksum mismatch: downloaded tarball does not match the registry ${_[1]} integrity value; refusing to install`);return}if(V.shasum){if(n.createHash("sha1").update(J).digest("hex")!==V.shasum.toLowerCase())throw new H("checksum mismatch: downloaded tarball does not match the registry shasum; refusing to install");return}throw new H("registry provided no integrity metadata for the tarball; refusing to install")}function Qj(J,V){let _=(w,R)=>{let G=w,q=w+R;while(G<q&&J[G]!==0)G++;return new TextDecoder().decode(J.subarray(w,G))},$=0,W;while($+512<=J.length){if(J.subarray($,$+512).every((Z)=>Z===0))break;let R=_($+124,12).trim(),G=R?parseInt(R,8):0;if(!Number.isFinite(G)||G<0)throw new H("downloaded tarball is corrupt (bad tar header)");let q=String.fromCharCode(J[$+156]),B=_($,100),N=_($+345,155);if(N)B=`${N}/${B}`;if(W)B=W,W=void 0;let b=$+512,X=b+G;if(q==="L")W=new TextDecoder().decode(J.subarray(b,X)).replace(/\0+$/,"");else if((q==="0"||q==="\x00"||q==="")&&B===V)return J.slice(b,X);$=b+Math.ceil(G/512)*512}return}var A=(J)=>String(J instanceof Error?J.message:J),u=(J)=>Q.fail(new H(J)),p=(J,V)=>Q.try({try:J,catch:(_)=>new H(V(_))}),Xj=Q.fnUntraced(function*(J){let{target:V,execPath:_,packageName:$,registry:W}=J,w=J.gunzip??((K)=>Bun.gunzipSync(K)),R=Zj.dirname(_);yield*p(()=>v.accessSync(R,v.constants.W_OK),()=>`no write permission for ${R}; cannot replace ${_}. Fix the directory permissions or re-run with sufficient privileges.`);let G=`${W}/${$}/${encodeURIComponent(V)}`,B=(yield*J.fetchJson(G).pipe(Q.mapError((K)=>new H(`download failed: could not fetch ${$}@${V} from ${W} (${A(K)}). Check your network connection and that version ${V} exists.`))))?.dist;if(!B?.tarball)return yield*u(`registry response for ${$}@${V} has no tarball URL; cannot self-update`);let N=B.tarball,b=yield*J.fetchBytes(N).pipe(Q.mapError((K)=>new H(`download failed: could not download ${N} (${A(K)}). Check your network connection and try again.`)));yield*Q.try({try:()=>kj(b,B),catch:(K)=>K instanceof H?K:new H(A(K))});let X=yield*Q.try({try:()=>w(b),catch:()=>new H("downloaded tarball is corrupt (gunzip failed); try again")}),Z=Qj(X,"package/bin/qitqode")??Qj(X,"package/bin/qitqode.exe");if(!Z||Z.length===0)return yield*u(`tarball for ${$}@${V} does not contain the expected binary at bin/qitqode`);let O=Zj.join(R,`.qitqode-upgrade-${process.pid}`),Y=`${_}.backup-${process.pid}`,D=(K)=>{try{v.rmSync(K,{force:!0})}catch{}};yield*p(()=>v.writeFileSync(O,Z,{mode:493}),(K)=>{return D(O),`no write permission: could not write ${O} (${A(K)})`});let L=yield*J.runVersion(O).pipe(Q.mapError((K)=>{return D(O),new H(`downloaded binary failed its --version check (${A(K)}); keeping the current installation`)}));if(L.code!==0)return D(O),yield*u(`downloaded binary failed its --version check (exit ${L.code}); keeping the current installation`);let m=L.stdout.trim();if(m&&!m.includes(V))return D(O),yield*u(`downloaded binary reports version "${m}" instead of ${V}; keeping the current installation`);yield*p(()=>v.renameSync(_,Y),(K)=>{return D(O),`could not move the current binary aside (${A(K)}); check permissions on ${_}`}),yield*Q.try({try:()=>v.renameSync(O,_),catch:(K)=>{try{v.renameSync(Y,_)}catch{return new H(`failed to install the new binary AND failed to restore the old one; your previous binary is preserved at ${Y} \u2014 move it back to ${_} manually`)}return D(O),new H(`could not install the new binary (${A(K)}); the previous version was restored`)}}),D(Y)});var c=h.create({service:"installation"}),M="@qitqode/cli";function qj(J,V){if(!z.default.valid(J)||!z.default.valid(V))return!1;return z.default.gt(V,J)}var Cj={Updated:s.define("installation.updated",j.object({version:j.string()})),UpdateAvailable:s.define("installation.update-available",j.object({version:j.string()}))};function yj(J,V){if(!qj(J,V))throw Error(`Version ${V} is not newer than ${J}`);let _=z.default.major(J),$=z.default.minor(J),W=z.default.major(V),w=z.default.minor(V);if(W>_)return"major";if(w>$)return"minor";return"patch"}var Uj=j.object({version:j.string(),latest:j.string()}).meta({ref:"InstallationInfo"}),Sj=`qitqode/${y}/${a}/${I.QITQODE_CLIENT}`;function ij(){return y!=="latest"}function mj(){return y==="local"}class x extends C.TaggedErrorClass()("UpgradeFailedError",{stderr:C.String}){}var nj=C.Struct({version:C.String});class E extends Wj.Service()("@qitqode/Installation"){}var Bj=o.effect(E,Q.gen(function*(){let J=yield*k.HttpClient,V=k.filterStatusOk(_j(J)),_=yield*f.ChildProcessSpawner,$=(X,Z)=>Gj.make(X[0],X.slice(1),{cwd:Z?.cwd,env:Z?.env,extendEnv:!0}),W=Q.fnUntraced(function*(X){let Z=yield*Hj(_,X);return{code:Z.code,stdout:Z.text,stderr:Z.stderr}},Q.scoped),w=Q.fnUntraced(function*(X,Z){let O=yield*_.spawn($(X,Z)),Y=yield*l.mkString(l.decodeText(O.stdout));return yield*O.exitCode,Y},Q.scoped,Q.catch(()=>Q.succeed(""))),R=Q.fnUntraced(function*(X,Z){return yield*W($(X,Z))},Q.catch(()=>Q.succeed({code:f.ExitCode(1),stdout:"",stderr:""}))),G=Q.fn("Installation.method")(function*(){if(process.execPath.includes(Yj.join(".qitqode","bin")))return"curl";if(process.execPath.includes(Yj.join(".local","bin")))return"curl";let X=process.execPath.toLowerCase(),Z=[{name:"npm",command:()=>w(["npm","list","-g","--depth=0"])},{name:"pnpm",command:()=>w(["pnpm","list","-g","--depth=0"])},{name:"bun",command:()=>w(["bun","pm","ls","-g"])}];Z.sort((O,Y)=>{let D=X.includes(O.name),L=X.includes(Y.name);if(D&&!L)return-1;if(!D&&L)return 1;return 0});for(let O of Z)if((yield*O.command()).includes(M))return O.name;return"unknown"}),q=Q.fn("Installation.latest")(function*(X){let Z=X||(yield*G());if(Z==="curl"){let Y=(yield*w(["curl","-sI","https://github.com/qitqode/qitqode/releases/latest"])).match(/^location:.*\/tag\/v([0-9][^\s/]*)/im);if(Y)return Y[1];return yield*Q.die(Error("failed to resolve latest version from GitHub releases redirect"))}if(Z==="npm"||Z==="bun"||Z==="pnpm"){let Y=(yield*w(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org",D=Y.endsWith("/")?Y.slice(0,-1):Y,L=yield*V.execute(P.get(`${D}/${encodeURIComponent(M)}/${y}`).pipe(P.acceptJson));return(yield*wj.schemaBodyJson(nj)(L)).version}return c.warn("unsupported update channel, skipping",{method:Z}),yield*Q.die(Error(`unsupported update channel: ${Z}`))},Q.orDie),B=Q.fnUntraced(function*(){let Z=(yield*w(["npm","config","get","registry"])).trim()||"https://registry.npmjs.org";return Z.endsWith("/")?Z.slice(0,-1):Z}),N=Q.fnUntraced(function*(X){let Z=yield*B();yield*Xj({target:X,execPath:process.env.QITQODE_SELF_UPDATE_TARGET_BINARY||process.execPath,packageName:$j(),registry:Z,fetchJson:(O)=>V.execute(P.get(O).pipe(P.acceptJson)).pipe(Q.flatMap((Y)=>Y.json)),fetchBytes:(O)=>V.execute(P.get(O)).pipe(Q.flatMap((Y)=>Y.arrayBuffer),Q.map((Y)=>new Uint8Array(Y))),runVersion:(O)=>R([O,"--version"]).pipe(Q.map((Y)=>({code:Y.code,stdout:Y.stdout})))}).pipe(Q.mapError((O)=>new x({stderr:O.message})))}),b=Q.fn("Installation.upgrade")(function*(X,Z){if(X==="curl"){yield*N(Z),c.info("upgraded",{method:X,target:Z});return}let Y=yield*(()=>{if(X==="npm")return R(["npm","install","-g",`${M}@${Z}`]);if(X==="pnpm")return R(["pnpm","install","-g",`${M}@${Z}`]);if(X==="bun")return R(["bun","install","-g",`${M}@${Z}`]);return new x({stderr:`Unknown method: ${X}`})})();if(Y.code!==0){let D=Y.stderr||"";return yield*new x({stderr:D})}c.info("upgraded",{method:X,target:Z,stdout:Y.stdout,stderr:Y.stderr}),yield*w([process.execPath,"--version"])});return E.of({info:Q.fn("Installation.info")(function*(){return{version:a,latest:yield*q()}}),method:G,latest:q,upgrade:b})})),uj=Bj.pipe(o.provide(Kj.layer),o.provide(Rj));var t=j.lazy(()=>j.union([j.string(),j.number(),j.boolean(),j.null(),j.array(t),j.record(j.string(),t)])),Dj=j.object({input:j.number(),output:j.number(),cache_read:j.number().optional(),cache_write:j.number().optional(),context_over_200k:j.object({input:j.number(),output:j.number(),cache_read:j.number().optional(),cache_write:j.number().optional()}).optional()}),r=j.object({id:j.string(),name:j.string(),family:j.string().optional(),release_date:j.string(),attachment:j.boolean(),reasoning:j.boolean(),temperature:j.boolean().optional(),tool_call:j.boolean(),interleaved:j.union([j.literal(!0),j.object({field:j.enum(["reasoning_content","reasoning_details"])}).strict()]).optional(),cost:Dj.optional(),limit:j.object({context:j.number(),input:j.number().optional(),output:j.number()}),modalities:j.object({input:j.array(j.enum(["text","audio","image","video","pdf"])),output:j.array(j.enum(["text","audio","image","video","pdf"]))}).optional(),experimental:j.object({modes:j.record(j.string(),j.object({cost:Dj.optional(),provider:j.object({body:j.record(j.string(),t).optional(),headers:j.record(j.string(),j.string()).optional()}).optional()})).optional()}).optional(),status:j.enum(["alpha","beta","deprecated"]).optional(),provider:j.object({npm:j.string().optional(),api:j.string().optional()}).optional()}),e=j.object({api:j.string().optional(),name:j.string(),env:j.array(j.string()),id:j.string(),npm:j.string().optional(),models:j.record(j.string(),r)});var Vj=h.create({service:"models.dev"}),bj=Fj(),F=hj.join(Nj.Path.cache,bj==="https://models.dev"?"models.json":`models-${Ij.fast(bj)}.json`),gj=300000,Aj=8388608,T,dj=j.record(j.string(),e),pj=r,cj=e;function Fj(){return I.QITQODE_MODELS_URL||"https://models.dev"}function lj(){return Date.now()-Number(i.stat(F)?.mtimeMs??0)<gj}function Lj(J){return!J&&lj()}function g(J){let V=dj.parse(typeof J==="string"?JSON.parse(J):J);for(let[_,$]of Object.entries(V))if($.id!==_)throw Error(`Invalid model provider: ${_}`);return V}async function zj(J){let V=await i.readJson(J).catch(()=>{return});if(!V)return;try{return g(V)}catch(_){Vj.warn("Ignoring invalid model catalog cache",{file:J,error:_});return}}async function Pj(J,V,_=Aj){let $=J.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();if($!=="application/json"&&!$?.endsWith("+json"))throw Error(`Invalid model catalog content type: ${$||"missing"}`);let W=Number(J.headers.get("content-length"));if(Number.isFinite(W)&&W>_)throw Error("Model catalog response is too large");if(!J.body)return"";let w=J.body.getReader(),R=()=>void w.cancel(V.reason);V.addEventListener("abort",R,{once:!0});let G=new Uint8Array(_),q=0;try{for(;;){let B=await w.read();if(B.done)break;if(q+=B.value.byteLength,q>_)throw await w.cancel(),Error("Model catalog response is too large");G.set(B.value,q-B.value.byteLength)}}finally{V.removeEventListener("abort",R)}return new TextDecoder().decode(G.subarray(0,q))}var Tj=async()=>{let J=AbortSignal.timeout(1e4),V=await fetch(`${Fj()}/api.json`,{headers:{"User-Agent":U.USER_AGENT},signal:J});if(!V.ok)return;let _=g(await Pj(V,J));return JSON.stringify(_)},S=vj(async()=>{let J=await zj(I.QITQODE_MODELS_PATH??F);if(J)return J;let V=await import("./chunk-31qrzrwy.js").then((_)=>g(_.snapshot)).catch(()=>{return});if(V)return V;if(I.QITQODE_DISABLE_MODELS_FETCH)return{};return Jj.withLock(`models-dev:${F}`,async()=>{let _=await zj(I.QITQODE_MODELS_PATH??F);if(_)return _;let $=await Tj();if($)return await i.write(F,$).catch((W)=>{Vj.error("Failed to write models cache",{error:W})}),g($);return{}})});async function fj(){return S()}async function jj(J=!1){if(Lj(J))return S.reset();await Jj.withLock(`models-dev:${F}`,async()=>{if(Lj(J))return S.reset();let V=await Tj();if(!V)return;await i.write(F,V),S.reset()}).catch((V)=>{Vj.error("Failed to fetch models.dev",{error:V})})}function sj(){if(T||I.QITQODE_DISABLE_MODELS_FETCH||process.argv.includes("--get-yargs-completions"))return;jj(),T=setInterval(async()=>{await jj()},3600000),T.unref()}function aj(){if(!T)return;clearInterval(T),T=void 0}
3
3
  export{_j as El,U as Fl,Aj as Gl,pj as Hl,cj as Il,Pj as Jl,S as Kl,fj as Ll,jj as Ml,sj as Nl,aj as Ol,tj as Pl};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{N as R9}from"./chunk-50sv6y2e.js";import{Ed as E9}from"./chunk-fyqjm5fv.js";import{Fd as P6,Id as p$,Jd as S9,Kd as U9,Nd as H9,Od as q6}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as T0}from"./chunk-yajd975f.js";import{Vf as O}from"./chunk-rbk8seme.js";import{Vg as j9,ch as I9,gh as E$}from"./chunk-fq0x3esz.js";import"./chunk-44a82dg0.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{Cl as b9,Wj as T9,lk as O6,mk as M0,rl as w9,tl as D9}from"./chunk-04n2ycg5.js";import{Pl as N9}from"./chunk-8ymffyep.js";import{cm as A0,lm as T$}from"./chunk-mcg24gkb.js";import"./chunk-redjxn13.js";import"./chunk-bn0h9dny.js";import"./chunk-r4ndwym0.js";import"./chunk-3ytjm3az.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-r78czx4d.js";import"./chunk-2hc5z7b5.js";import"./chunk-d68fzyw7.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-gcw4rn10.js";import{Zr as V9,as as R6,bs as L9,gs as F9}from"./chunk-m5m448mg.js";import{ht as C6,st as A9}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import{pH as M9}from"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import{BO as q0,CO as D,FO as E}from"./chunk-7xm75w1e.js";var JZ=D((zZ)=>{/*!
2
+ import{N as R9}from"./chunk-q7vasbxn.js";import{Ed as E9}from"./chunk-x25zkrz7.js";import{Fd as P6,Id as p$,Jd as S9,Kd as U9,Nd as H9,Od as q6}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as T0}from"./chunk-yajd975f.js";import{Vf as O}from"./chunk-rbk8seme.js";import{Vg as j9,ch as I9,gh as E$}from"./chunk-caj1b9y7.js";import"./chunk-ygs5pzk7.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{Cl as b9,Wj as T9,lk as O6,mk as M0,rl as w9,tl as D9}from"./chunk-257me4z3.js";import{Pl as N9}from"./chunk-nkkch4h7.js";import{cm as A0,lm as T$}from"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import"./chunk-hnvn2c25.js";import"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-we9cv8we.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-764fksh3.js";import{Zr as V9,as as R6,bs as L9,gs as F9}from"./chunk-xj765svc.js";import{ht as C6,st as A9}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import{pH as M9}from"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import{BO as q0,CO as D,FO as E}from"./chunk-7xm75w1e.js";var JZ=D((zZ)=>{/*!
3
3
  * content-type
4
4
  * Copyright(c) 2015 Douglas Christopher Wilson
5
5
  * MIT Licensed
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Vr as X}from"./chunk-m5m448mg.js";function D(j){return j.parserConfiguration({"populate--":!0}).scriptName("qitqode").wrap(100).help("help","show help").alias("help","h").version("version","show version number",X).alias("version","v").option("print-logs",{describe:"print logs to stderr",type:"boolean"}).option("log-level",{describe:"log level",type:"string",choices:["DEBUG","INFO","WARN","ERROR"]}).option("pure",{describe:"run without external plugins",type:"boolean"})}var H={port:{type:"number",describe:"port to listen on",default:0},hostname:{type:"string",describe:"hostname to listen on",default:"127.0.0.1"},mdns:{type:"boolean",describe:"enable mDNS service discovery (defaults hostname to 0.0.0.0)",default:!1},"mdns-domain":{type:"string",describe:"custom domain name for mDNS service (default: qitqode.local)",default:"qitqode.local"},cors:{type:"string",array:!0,describe:"additional domains to allow for CORS",default:[]},"no-auth":{type:"boolean",describe:"allow starting without authentication on non-loopback addresses (DANGEROUS)",default:!1}};function u(j){return j.options(H)}function F(j,z=process.argv){return z.some((B)=>B===j||B.startsWith(`${j}=`))}function P(j,z=process.argv){return F("--port",z)||F("--hostname",z)||F("--mdns",z)||!!j.mdns||j.port!==0||j.hostname!=="127.0.0.1"}function _(j,z,B=process.argv){let J=F("--port",B),Z=F("--hostname",B),$=F("--mdns",B),q=F("--mdns-domain",B),K=$?j.mdns:z?.server?.mdns??j.mdns,M=q?j["mdns-domain"]:z?.server?.mdnsDomain??j["mdns-domain"],N=J?j.port:z?.server?.port??j.port,U=Z?j.hostname:K&&!z?.server?.hostname?"0.0.0.0":z?.server?.hostname??j.hostname,V=z?.server?.cors??[],Y=Array.isArray(j.cors)?j.cors:j.cors?[j.cors]:[],b=[...V,...Y],A=j["no-auth"];return{hostname:U,port:N,mdns:K,mdnsDomain:M,cors:b,noAuth:A}}var k={model:{type:"string",alias:["m"],describe:"model to use in the format of provider/model"},continue:{alias:["c"],describe:"continue the last session",type:"boolean"},session:{alias:["s"],type:"string",describe:"session id to continue"},fork:{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"},prompt:{type:"string",describe:"prompt to use"},agent:{type:"string",describe:"agent to use"},dark:{type:"boolean",describe:"start in dark theme (overrides saved theme preference for this launch)"},light:{type:"boolean",describe:"start in light theme (overrides saved theme preference for this launch)"},monochrome:{type:"boolean",describe:"start in monochrome accessible rendering \u2014 no color, plain terminal, screen-reader friendly"},headless:{type:"boolean",describe:"headless permissionless mode for AI subagent use \u2014 auto-approves all tool permissions, implies --never-ask"},fullauto:{type:"boolean",describe:"full-auto mode for the interactive TUI \u2014 never asks: starts in build mode, auto-decides questions and auto-approves every tool permission that is not explicitly denied by your config (dangerous!)"},"api-key":{type:"string",describe:"Qortex API key for non-interactive authentication in headless mode (can also be set via $QLEX_API_KEY)"},sso:{type:"boolean",describe:"sign in via SSO device-code flow before starting a headless session \u2014 prints a URL and code, waits for browser approval (requires --headless)"},free:{type:"boolean",describe:"start in Free tier (no cost) \u2014 shorthand for the Free model tier"},default:{type:"boolean",describe:"start in Default tier \u2014 shorthand for the Default model tier"},fast:{type:"boolean",describe:"start in Fast tier \u2014 shorthand for the Fast model tier"},economy:{type:"boolean",describe:"start in Economy tier \u2014 shorthand for the Economy model tier"},power:{type:"boolean",describe:"start in Power tier \u2014 shorthand for the Power model tier"},orchestrated:{type:"boolean",describe:"start in Orchestrated tier \u2014 shorthand for the Orchestrated model tier"}},L=36,W="\x1B[38;5;214m",I="\x1B[0;2m",Q="\x1B[0m";function G(j,z){let B=Math.round(j/100*L),J=`${"\u25A0".repeat(B)}${"\uFF65".repeat(L-B)}`;return`\r${W}${J} ${j.toString().padStart(3)}%${Q} ${I}${z}${Q}`}
2
+ import{Vr as X}from"./chunk-xj765svc.js";function D(j){return j.parserConfiguration({"populate--":!0}).scriptName("qitqode").wrap(100).help("help","show help").alias("help","h").version("version","show version number",X).alias("version","v").option("print-logs",{describe:"print logs to stderr",type:"boolean"}).option("log-level",{describe:"log level",type:"string",choices:["DEBUG","INFO","WARN","ERROR"]}).option("pure",{describe:"run without external plugins",type:"boolean"})}var H={port:{type:"number",describe:"port to listen on",default:0},hostname:{type:"string",describe:"hostname to listen on",default:"127.0.0.1"},mdns:{type:"boolean",describe:"enable mDNS service discovery (defaults hostname to 0.0.0.0)",default:!1},"mdns-domain":{type:"string",describe:"custom domain name for mDNS service (default: qitqode.local)",default:"qitqode.local"},cors:{type:"string",array:!0,describe:"additional domains to allow for CORS",default:[]},"no-auth":{type:"boolean",describe:"allow starting without authentication on non-loopback addresses (DANGEROUS)",default:!1}};function u(j){return j.options(H)}function F(j,z=process.argv){return z.some((B)=>B===j||B.startsWith(`${j}=`))}function P(j,z=process.argv){return F("--port",z)||F("--hostname",z)||F("--mdns",z)||!!j.mdns||j.port!==0||j.hostname!=="127.0.0.1"}function _(j,z,B=process.argv){let J=F("--port",B),Z=F("--hostname",B),$=F("--mdns",B),q=F("--mdns-domain",B),K=$?j.mdns:z?.server?.mdns??j.mdns,M=q?j["mdns-domain"]:z?.server?.mdnsDomain??j["mdns-domain"],N=J?j.port:z?.server?.port??j.port,U=Z?j.hostname:K&&!z?.server?.hostname?"0.0.0.0":z?.server?.hostname??j.hostname,V=z?.server?.cors??[],Y=Array.isArray(j.cors)?j.cors:j.cors?[j.cors]:[],b=[...V,...Y],A=j["no-auth"];return{hostname:U,port:N,mdns:K,mdnsDomain:M,cors:b,noAuth:A}}var k={model:{type:"string",alias:["m"],describe:"model to use in the format of provider/model"},continue:{alias:["c"],describe:"continue the last session",type:"boolean"},session:{alias:["s"],type:"string",describe:"session id to continue"},fork:{type:"boolean",describe:"fork the session when continuing (use with --continue or --session)"},prompt:{type:"string",describe:"prompt to use"},agent:{type:"string",describe:"agent to use"},dark:{type:"boolean",describe:"start in dark theme (overrides saved theme preference for this launch)"},light:{type:"boolean",describe:"start in light theme (overrides saved theme preference for this launch)"},monochrome:{type:"boolean",describe:"start in monochrome accessible rendering \u2014 no color, plain terminal, screen-reader friendly"},headless:{type:"boolean",describe:"headless permissionless mode for AI subagent use \u2014 auto-approves all tool permissions, implies --never-ask"},fullauto:{type:"boolean",describe:"full-auto mode for the interactive TUI \u2014 never asks: starts in build mode, auto-decides questions and auto-approves every tool permission that is not explicitly denied by your config (dangerous!)"},"api-key":{type:"string",describe:"Qortex API key for non-interactive authentication in headless mode (can also be set via $QLEX_API_KEY)"},sso:{type:"boolean",describe:"sign in via SSO device-code flow before starting a headless session \u2014 prints a URL and code, waits for browser approval (requires --headless)"},free:{type:"boolean",describe:"start in Free tier (no cost) \u2014 shorthand for the Free model tier"},default:{type:"boolean",describe:"start in Default tier \u2014 shorthand for the Default model tier"},fast:{type:"boolean",describe:"start in Fast tier \u2014 shorthand for the Fast model tier"},economy:{type:"boolean",describe:"start in Economy tier \u2014 shorthand for the Economy model tier"},power:{type:"boolean",describe:"start in Power tier \u2014 shorthand for the Power model tier"},orchestrated:{type:"boolean",describe:"start in Orchestrated tier \u2014 shorthand for the Orchestrated model tier"}},L=36,W="\x1B[38;5;214m",I="\x1B[0;2m",Q="\x1B[0m";function G(j,z){let B=Math.round(j/100*L),J=`${"\u25A0".repeat(B)}${"\uFF65".repeat(L-B)}`;return`\r${W}${J} ${j.toString().padStart(3)}%${Q} ${I}${z}${Q}`}
3
3
  export{D as Mf,H as Nf,u as Of,P as Pf,_ as Qf,k as Rf,G as Sf};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Zr as c,bs as s}from"./chunk-m5m448mg.js";var r=["openai","anthropic"],p=["deepseek","zai","zhipuai","moonshotai","moonshotai-cn","kimi-for-coding","stepfun"],d=["opencode","openrouter"],l=["alibaba","alibaba-cn","bytedance","alibaba-coding-plan","alibaba-coding-plan-cn","zai-coding-plan","zhipuai-coding-plan","tencent-coding-plan","minimax-coding-plan","minimax-cn-coding-plan","kuae-cloud-coding-plan"],R=["opencode-go","github-copilot","google","vercel"],P=[r,p,d,l,R],g=Object.fromEntries(P.flatMap((i,a,e)=>{let n=e.slice(0,a).reduce((o,t)=>o+t.length,0);return i.map((o,t)=>[o,n+t])}));function m(i){return i in g}function O(i,a,e){return c(i,s((n)=>a[n.id]??99,(n)=>n.name??n.id),(n)=>n.map((o)=>({label:o.name,value:o.id,hint:e(o)})))}
2
+ import{Zr as c,bs as s}from"./chunk-xj765svc.js";var r=["openai","anthropic"],p=["deepseek","zai","zhipuai","moonshotai","moonshotai-cn","kimi-for-coding","stepfun"],d=["opencode","openrouter"],l=["alibaba","alibaba-cn","bytedance","alibaba-coding-plan","alibaba-coding-plan-cn","zai-coding-plan","zhipuai-coding-plan","tencent-coding-plan","minimax-coding-plan","minimax-cn-coding-plan","kuae-cloud-coding-plan"],R=["opencode-go","github-copilot","google","vercel"],P=[r,p,d,l,R],g=Object.fromEntries(P.flatMap((i,a,e)=>{let n=e.slice(0,a).reduce((o,t)=>o+t.length,0);return i.map((o,t)=>[o,n+t])}));function m(i){return i in g}function O(i,a,e){return c(i,s((n)=>a[n.id]??99,(n)=>n.name??n.id),(n)=>n.map((o)=>({label:o.name,value:o.id,hint:e(o)})))}
3
3
  export{g as L,m as M,O as N};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Cl as a}from"./chunk-257me4z3.js";import"./chunk-nkkch4h7.js";import"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import"./chunk-hnvn2c25.js";import"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-we9cv8we.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-764fksh3.js";import"./chunk-xj765svc.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-zw815d68.js";import"./chunk-7xm75w1e.js";export{a as Session};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Jq as a,Kq as b,Lq as c}from"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-m5m448mg.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{c as makeRuntime,a as attachWith,b as attach};
2
+ import{Jq as a,Kq as b,Lq as c}from"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-xj765svc.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{c as makeRuntime,a as attachWith,b as attach};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{h as N}from"./chunk-5eq1fft9.js";import{F as K,G as L,H as $}from"./chunk-g9cjsfvg.js";import"./chunk-t9mz17gb.js";import{Rd as X}from"./chunk-yajd975f.js";import{Vf as j}from"./chunk-rbk8seme.js";import{zg as H}from"./chunk-takew94z.js";import{gh as Z}from"./chunk-fq0x3esz.js";import"./chunk-44a82dg0.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{Xj as w}from"./chunk-04n2ycg5.js";import"./chunk-8ymffyep.js";import"./chunk-mcg24gkb.js";import"./chunk-redjxn13.js";import"./chunk-bn0h9dny.js";import"./chunk-r4ndwym0.js";import"./chunk-3ytjm3az.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import{qo as F,vo as G}from"./chunk-r78czx4d.js";import"./chunk-2hc5z7b5.js";import"./chunk-d68fzyw7.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-gcw4rn10.js";import"./chunk-m5m448mg.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import{pH as z}from"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import"./chunk-7xm75w1e.js";var Q="forgewise";function R(D){return z.gen(function*(){let J=yield*D.get(Q);if(!J||J.type!=="api")return;return(J.metadata??{}).sub})}var O=()=>z.gen(function*(){if((yield*N())==="revoked")return null;let D=yield*z.promise(()=>F());if(!D)return yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Not signed in to Forgewise. Run `qitqode auth login` first."+j.Style.TEXT_NORMAL)),null;let J=yield*w.Service,M=D.method==="sso"?yield*R(J):void 0;return{key:D.key,method:D.method,sub:M}}),q=()=>z.gen(function*(){let D=yield*O();if(!D)return;let J=yield*z.tryPromise({try:()=>H(D),catch:(P)=>P}).pipe(z.map((P)=>({ok:!0,result:P})),z.catch((P)=>z.succeed({ok:!1,error:P})));if(!J.ok){let P=J.error instanceof G?J.error.message:"Could not fetch balance.";yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+P+j.Style.TEXT_NORMAL));return}let M=J.result;if(!M){yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Could not fetch balance."+j.Style.TEXT_NORMAL));return}yield*z.sync(()=>j.println(j.Style.TEXT_SUCCESS+"Qredits balance: "+j.Style.TEXT_NORMAL+j.Style.TEXT_HIGHLIGHT_BOLD+$(M.balance)+j.Style.TEXT_NORMAL))}).pipe(z.withSpan("qredits.balance")),A=()=>z.gen(function*(){let D=yield*O();if(!D)return;let J=D.method==="sso"&&D.sub?{userId:D.sub,accessToken:D.key}:{},M=yield*z.tryPromise({try:()=>L({...J,limit:20}),catch:(T)=>T});if(M instanceof Error){let T=M instanceof K?M.message:String(M);yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Could not fetch history: "+T+j.Style.TEXT_NORMAL));return}if(M.length===0){yield*z.sync(()=>j.println("No spend history yet."));return}let P=j.Style.TEXT_DIM,V=j.Style.TEXT_NORMAL,W=j.Style.TEXT_DANGER;yield*z.sync(()=>{j.println(P+" Date Description Amount"+V),j.println(P+" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500"+V);for(let T of M){let Y=(T.date||"").slice(0,10).padEnd(18),_=(T.description||"").slice(0,32).padEnd(32),v=(T.amount<0?"-":" ")+$(Math.abs(T.amount)),x=T.amount<0?W:V;j.println(` ${P}${Y}${V} ${_} ${x}${v}${V}`)}})}).pipe(z.withSpan("qredits.history")),U=X({command:"qredits <command>",describe:"Check Qredits balance and spend history",builder:(D)=>D.command(X({command:"balance",describe:"Show current Qredits balance",builder:(J)=>J,async handler(){j.empty(),await Z.runPromise(q())}})).command(X({command:"history",describe:"Show recent Qredit spend history",builder:(J)=>J,async handler(){j.empty(),await Z.runPromise(A())}})).demandCommand(),async handler(){}});export{A as historyEffect,q as balanceEffect,U as QreditsCommand};
2
+ import{h as N}from"./chunk-zqqx96jx.js";import{F as K,G as L,H as $}from"./chunk-whe7h2mj.js";import"./chunk-t9mz17gb.js";import{Rd as X}from"./chunk-yajd975f.js";import{Vf as j}from"./chunk-rbk8seme.js";import{zg as H}from"./chunk-gz8sz7z1.js";import{gh as Z}from"./chunk-caj1b9y7.js";import"./chunk-ygs5pzk7.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{Xj as w}from"./chunk-257me4z3.js";import"./chunk-nkkch4h7.js";import"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import"./chunk-hnvn2c25.js";import"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import{qo as F,vo as G}from"./chunk-we9cv8we.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-764fksh3.js";import"./chunk-xj765svc.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import{pH as z}from"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import"./chunk-7xm75w1e.js";var Q="forgewise";function R(D){return z.gen(function*(){let J=yield*D.get(Q);if(!J||J.type!=="api")return;return(J.metadata??{}).sub})}var O=()=>z.gen(function*(){if((yield*N())==="revoked")return null;let D=yield*z.promise(()=>F());if(!D)return yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Not signed in to Forgewise. Run `qitqode auth login` first."+j.Style.TEXT_NORMAL)),null;let J=yield*w.Service,M=D.method==="sso"?yield*R(J):void 0;return{key:D.key,method:D.method,sub:M}}),q=()=>z.gen(function*(){let D=yield*O();if(!D)return;let J=yield*z.tryPromise({try:()=>H(D),catch:(P)=>P}).pipe(z.map((P)=>({ok:!0,result:P})),z.catch((P)=>z.succeed({ok:!1,error:P})));if(!J.ok){let P=J.error instanceof G?J.error.message:"Could not fetch balance.";yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+P+j.Style.TEXT_NORMAL));return}let M=J.result;if(!M){yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Could not fetch balance."+j.Style.TEXT_NORMAL));return}yield*z.sync(()=>j.println(j.Style.TEXT_SUCCESS+"Qredits balance: "+j.Style.TEXT_NORMAL+j.Style.TEXT_HIGHLIGHT_BOLD+$(M.balance)+j.Style.TEXT_NORMAL))}).pipe(z.withSpan("qredits.balance")),A=()=>z.gen(function*(){let D=yield*O();if(!D)return;let J=D.method==="sso"&&D.sub?{userId:D.sub,accessToken:D.key}:{},M=yield*z.tryPromise({try:()=>L({...J,limit:20}),catch:(T)=>T});if(M instanceof Error){let T=M instanceof K?M.message:String(M);yield*z.sync(()=>j.println(j.Style.TEXT_DANGER+"Could not fetch history: "+T+j.Style.TEXT_NORMAL));return}if(M.length===0){yield*z.sync(()=>j.println("No spend history yet."));return}let P=j.Style.TEXT_DIM,V=j.Style.TEXT_NORMAL,W=j.Style.TEXT_DANGER;yield*z.sync(()=>{j.println(P+" Date Description Amount"+V),j.println(P+" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500"+V);for(let T of M){let Y=(T.date||"").slice(0,10).padEnd(18),_=(T.description||"").slice(0,32).padEnd(32),v=(T.amount<0?"-":" ")+$(Math.abs(T.amount)),x=T.amount<0?W:V;j.println(` ${P}${Y}${V} ${_} ${x}${v}${V}`)}})}).pipe(z.withSpan("qredits.history")),U=X({command:"qredits <command>",describe:"Check Qredits balance and spend history",builder:(D)=>D.command(X({command:"balance",describe:"Show current Qredits balance",builder:(J)=>J,async handler(){j.empty(),await Z.runPromise(q())}})).command(X({command:"history",describe:"Show recent Qredit spend history",builder:(J)=>J,async handler(){j.empty(),await Z.runPromise(A())}})).demandCommand(),async handler(){}});export{A as historyEffect,q as balanceEffect,U as QreditsCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Do as a}from"./chunk-d68fzyw7.js";import"./chunk-10bjs581.js";import"./chunk-m5m448mg.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{a as which};
2
+ import{Do as a}from"./chunk-9gazyynx.js";import"./chunk-10bjs581.js";import"./chunk-xj765svc.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{a as which};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{p as w,q as h,r as I,s as C,t as D}from"./chunk-d65qs4d0.js";import{Id as c,Jd as k,Kd as $,Nd as x}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as P}from"./chunk-yajd975f.js";import{Vf as d}from"./chunk-rbk8seme.js";import{lm as l}from"./chunk-mcg24gkb.js";import"./chunk-redjxn13.js";import"./chunk-bn0h9dny.js";import{Wn as v}from"./chunk-3ytjm3az.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-2hc5z7b5.js";import"./chunk-d68fzyw7.js";import"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import{Qs as b}from"./chunk-m5m448mg.js";import{bt as m}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";var j={spinner:()=>x(),log:{error:(o)=>c.error(o),info:(o)=>c.info(o),success:(o)=>c.success(o)},resolve:(o)=>v(o),...h,global:b.Path.config};function S(o){if(!o||typeof o!=="object")return;if(!("cause"in o))return;return o.cause}function _(o,e=j){let n=o.mod,a=Boolean(o.force),y=Boolean(o.global);return async(f)=>{let u=e.spinner();u.start("Installing plugin package...");let p=await I(n,e);if(!p.ok){u.stop("Install failed",1),e.log.error(`Could not install "${n}"`);let t=w(p.error);if(t.detail)e.log.error(t.detail);if(t.missing)e.log.info("This package depends on a version that is not available in your npm registry."),e.log.info("Check npm registry/auth settings and try again.");return!1}u.stop("Plugin package ready");let s=e.spinner();s.start("Reading plugin manifest...");let i=await C(p.target);if(!i.ok){if(i.code==="manifest_read_failed")return s.stop("Manifest read failed",1),e.log.error(`Installed "${n}" but failed to read ${i.file}`),e.log.error(m(S(i.error)??i.error)),!1;if(i.code==="manifest_no_targets")return s.stop("No plugin targets found",1),e.log.error(`"${n}" does not expose plugin entrypoints in package.json`),e.log.info('Expected one of: exports["./tui"], exports["./server"], package.json main for server, or package.json["oc-themes"] for tui themes.'),!1;return s.stop("Manifest read failed",1),!1}s.stop(`Detected ${i.targets.map((t)=>t.kind).join(" + ")} target${i.targets.length===1?"":"s"}`);let g=e.spinner();g.start("Updating plugin config...");let r=await D({spec:n,targets:i.targets,force:a,global:y,vcs:f.vcs,worktree:f.worktree,directory:f.directory,config:e.global},e);if(!r.ok){if(r.code==="invalid_json")return g.stop(`Failed updating ${r.kind} config`,1),e.log.error(`Invalid JSON in ${r.file} (${r.parse} at line ${r.line}, column ${r.col})`),e.log.info("Fix the config file and run the command again."),!1;return g.stop("Failed updating plugin config",1),e.log.error(m(r.error)),!1}g.stop("Plugin config updated");for(let t of r.items){if(t.mode==="noop"){e.log.info(`Already configured in ${t.file}`);continue}if(t.mode==="replace"){e.log.info(`Replaced in ${t.file}`);continue}e.log.info(`Added to ${t.file}`)}return e.log.success(`Installed ${n}`),e.log.info(y?`Scope: global (${r.dir})`:`Scope: local (${r.dir})`),!0}}var R=P({command:"plugin <module>",aliases:["plug"],describe:"install plugin and update config",builder:(o)=>{return o.positional("module",{type:"string",describe:"npm module name"}).option("global",{alias:["g"],type:"boolean",default:!1,describe:"install in global config"}).option("force",{alias:["f"],type:"boolean",default:!1,describe:"replace existing plugin version"})},handler:async(o)=>{let e=String(o.module??"").trim();if(!e){d.error("module is required"),process.exitCode=1;return}d.empty(),k(`Install plugin ${e}`);let n=_({mod:e,global:Boolean(o.global),force:Boolean(o.force)}),a=!0;if(await l.provide({directory:process.cwd(),fn:async()=>{a=await n({vcs:l.project.vcs,worktree:l.worktree,directory:l.directory})}}),$("Done"),!a)process.exitCode=1}});export{_ as createPlugTask,R as PluginCommand};
2
+ import{p as w,q as h,r as I,s as C,t as D}from"./chunk-xrs18kzn.js";import{Id as c,Jd as k,Kd as $,Nd as x}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as P}from"./chunk-yajd975f.js";import{Vf as d}from"./chunk-rbk8seme.js";import{lm as l}from"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import{Wn as v}from"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import{Qs as b}from"./chunk-xj765svc.js";import{bt as m}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";var j={spinner:()=>x(),log:{error:(o)=>c.error(o),info:(o)=>c.info(o),success:(o)=>c.success(o)},resolve:(o)=>v(o),...h,global:b.Path.config};function S(o){if(!o||typeof o!=="object")return;if(!("cause"in o))return;return o.cause}function _(o,e=j){let n=o.mod,a=Boolean(o.force),y=Boolean(o.global);return async(f)=>{let u=e.spinner();u.start("Installing plugin package...");let p=await I(n,e);if(!p.ok){u.stop("Install failed",1),e.log.error(`Could not install "${n}"`);let t=w(p.error);if(t.detail)e.log.error(t.detail);if(t.missing)e.log.info("This package depends on a version that is not available in your npm registry."),e.log.info("Check npm registry/auth settings and try again.");return!1}u.stop("Plugin package ready");let s=e.spinner();s.start("Reading plugin manifest...");let i=await C(p.target);if(!i.ok){if(i.code==="manifest_read_failed")return s.stop("Manifest read failed",1),e.log.error(`Installed "${n}" but failed to read ${i.file}`),e.log.error(m(S(i.error)??i.error)),!1;if(i.code==="manifest_no_targets")return s.stop("No plugin targets found",1),e.log.error(`"${n}" does not expose plugin entrypoints in package.json`),e.log.info('Expected one of: exports["./tui"], exports["./server"], package.json main for server, or package.json["oc-themes"] for tui themes.'),!1;return s.stop("Manifest read failed",1),!1}s.stop(`Detected ${i.targets.map((t)=>t.kind).join(" + ")} target${i.targets.length===1?"":"s"}`);let g=e.spinner();g.start("Updating plugin config...");let r=await D({spec:n,targets:i.targets,force:a,global:y,vcs:f.vcs,worktree:f.worktree,directory:f.directory,config:e.global},e);if(!r.ok){if(r.code==="invalid_json")return g.stop(`Failed updating ${r.kind} config`,1),e.log.error(`Invalid JSON in ${r.file} (${r.parse} at line ${r.line}, column ${r.col})`),e.log.info("Fix the config file and run the command again."),!1;return g.stop("Failed updating plugin config",1),e.log.error(m(r.error)),!1}g.stop("Plugin config updated");for(let t of r.items){if(t.mode==="noop"){e.log.info(`Already configured in ${t.file}`);continue}if(t.mode==="replace"){e.log.info(`Replaced in ${t.file}`);continue}e.log.info(`Added to ${t.file}`)}return e.log.success(`Installed ${n}`),e.log.info(y?`Scope: global (${r.dir})`:`Scope: local (${r.dir})`),!0}}var R=P({command:"plugin <module>",aliases:["plug"],describe:"install plugin and update config",builder:(o)=>{return o.positional("module",{type:"string",describe:"npm module name"}).option("global",{alias:["g"],type:"boolean",default:!1,describe:"install in global config"}).option("force",{alias:["f"],type:"boolean",default:!1,describe:"replace existing plugin version"})},handler:async(o)=>{let e=String(o.module??"").trim();if(!e){d.error("module is required"),process.exitCode=1;return}d.empty(),k(`Install plugin ${e}`);let n=_({mod:e,global:Boolean(o.global),force:Boolean(o.force)}),a=!0;if(await l.provide({directory:process.cwd(),fn:async()=>{a=await n({vcs:l.project.vcs,worktree:l.worktree,directory:l.directory})}}),$("Done"),!a)process.exitCode=1}});export{_ as createPlugTask,R as PluginCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Fd as T,Hd as q,Id as N,Jd as w,Kd as X,Nd as D}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Vf as Q}from"./chunk-rbk8seme.js";import{gh as A}from"./chunk-fq0x3esz.js";import"./chunk-44a82dg0.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import"./chunk-04n2ycg5.js";import{Fl as $}from"./chunk-8ymffyep.js";import"./chunk-mcg24gkb.js";import"./chunk-redjxn13.js";import"./chunk-bn0h9dny.js";import"./chunk-r4ndwym0.js";import"./chunk-3ytjm3az.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-r78czx4d.js";import"./chunk-2hc5z7b5.js";import"./chunk-d68fzyw7.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-gcw4rn10.js";import{Qs as W}from"./chunk-m5m448mg.js";import{ht as _,st as Y}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import"./chunk-7xm75w1e.js";import V from"fs/promises";import L from"path";import R from"os";var g={command:"uninstall",describe:"uninstall qitqode and remove all related files",builder:(j)=>j.option("keep-config",{alias:"c",type:"boolean",describe:"keep configuration files",default:!1}).option("keep-data",{alias:"d",type:"boolean",describe:"keep session data and snapshots",default:!1}).option("dry-run",{type:"boolean",describe:"show what would be removed without removing",default:!1}).option("force",{alias:"f",type:"boolean",describe:"skip confirmation prompts",default:!1}),handler:async(j)=>{Q.empty(),Q.println(Q.logo(" ")),Q.empty(),w("Uninstall QitQode");let B=await A.runPromise($.Service.use((J)=>J.method()));N.info(`Installation method: ${B}`);let E=await v(j,B);if(await z(E,B),!j.force&&!j.dryRun){let J=await q({message:"Are you sure you want to uninstall?",initialValue:!1});if(!J||T(J)){X("Cancelled");return}}if(j.dryRun){N.warn("Dry run - no changes made"),X("Done");return}await G(B,E),X("Done")}};async function v(j,B){let E=[{path:W.Path.data,label:"Data",keep:j.keepData},{path:W.Path.cache,label:"Cache",keep:!1},{path:W.Path.config,label:"Config",keep:j.keepConfig},{path:W.Path.state,label:"State",keep:!1}],J=B==="curl"?await P():null,H=B==="curl"?process.execPath:null;return{directories:E,shellConfig:J,binary:H}}async function z(j,B){N.message("The following will be removed:");for(let E of j.directories){if(!await V.access(E.path).then(()=>!0).catch(()=>!1))continue;let H=await F(E.path),K=S(H),O=E.keep?Q.Style.TEXT_DIM+"(keeping)":"",M=E.keep?"\u25CB":"\u2713";N.info(` ${M} ${E.label}: ${Z(E.path)} ${Q.Style.TEXT_DIM}(${K})${O}`)}if(j.binary)N.info(` \u2713 Binary: ${Z(j.binary)}`);if(j.shellConfig)N.info(` \u2713 Shell PATH in ${Z(j.shellConfig)}`);if(B!=="curl"&&B!=="unknown"){let E={npm:"npm uninstall -g @qitqode/cli",pnpm:"pnpm uninstall -g @qitqode/cli",bun:"bun remove -g @qitqode/cli"};N.info(` \u2713 Package: ${E[B]||B}`)}}async function G(j,B){let E=D(),J=[];for(let H of B.directories){if(H.keep){N.step(`Skipping ${H.label} (--keep-${H.label.toLowerCase()})`);continue}if(!await V.access(H.path).then(()=>!0).catch(()=>!1))continue;E.start(`Removing ${H.label}...`);let O=await V.rm(H.path,{recursive:!0,force:!0}).catch((M)=>M);if(O){E.stop(`Failed to remove ${H.label}`,1),J.push(`${H.label}: ${O.message}`);continue}E.stop(`Removed ${H.label}`)}if(B.shellConfig){E.start("Cleaning shell config...");let H=await k(B.shellConfig).catch((K)=>K);if(H)E.stop("Failed to clean shell config",1),J.push(`Shell config: ${H.message}`);else E.stop("Cleaned shell config")}if(j!=="curl"&&j!=="unknown"){let K={npm:["npm","uninstall","-g","@qitqode/cli"],pnpm:["pnpm","uninstall","-g","@qitqode/cli"],bun:["bun","remove","-g","@qitqode/cli"]}[j];if(K){E.start(`Running ${K.join(" ")}...`);let O=await _.run(K,{nothrow:!0});if(O.code!==0)E.stop(`Package manager uninstall failed: exit code ${O.code}`,1),N.warn(`You may need to run manually: ${K.join(" ")}`);else E.stop("Package removed")}else N.warn(`Uninstall not supported for method "${j}" yet, skipping package removal`)}if(j==="curl"&&B.binary){Q.empty(),N.message("To finish removing the binary, run:"),N.info(` rm "${B.binary}"`);let H=L.dirname(B.binary);if(H.includes(".qitqode"))N.info(` rmdir "${H}" 2>/dev/null`)}if(J.length>0){Q.empty(),N.warn("Some operations failed:");for(let H of J)N.error(` ${H}`)}Q.empty(),N.success("Thank you for using QitQode!")}async function P(){let j=L.basename(process.env.SHELL||"bash"),B=R.homedir(),E=process.env.XDG_CONFIG_HOME||L.join(B,".config"),J={fish:[L.join(E,"fish","config.fish")],zsh:[L.join(B,".zshrc"),L.join(B,".zshenv"),L.join(E,"zsh",".zshrc"),L.join(E,"zsh",".zshenv")],bash:[L.join(B,".bashrc"),L.join(B,".bash_profile"),L.join(B,".profile"),L.join(E,"bash",".bashrc"),L.join(E,"bash",".bash_profile")],ash:[L.join(B,".ashrc"),L.join(B,".profile")],sh:[L.join(B,".profile")]},H=J[j]||J.bash;for(let K of H){if(!await V.access(K).then(()=>!0).catch(()=>!1))continue;let M=await Y.readText(K).catch(()=>"");if(M.includes("# qitqode")||M.includes(".qitqode/bin"))return K}return null}async function k(j){let E=(await Y.readText(j)).split(`
2
+ import{Fd as T,Hd as q,Id as N,Jd as w,Kd as X,Nd as D}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Vf as Q}from"./chunk-rbk8seme.js";import{gh as A}from"./chunk-caj1b9y7.js";import"./chunk-ygs5pzk7.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import"./chunk-257me4z3.js";import{Fl as $}from"./chunk-nkkch4h7.js";import"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import"./chunk-hnvn2c25.js";import"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-we9cv8we.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-764fksh3.js";import{Qs as W}from"./chunk-xj765svc.js";import{ht as _,st as Y}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import"./chunk-7xm75w1e.js";import V from"fs/promises";import L from"path";import R from"os";var g={command:"uninstall",describe:"uninstall qitqode and remove all related files",builder:(j)=>j.option("keep-config",{alias:"c",type:"boolean",describe:"keep configuration files",default:!1}).option("keep-data",{alias:"d",type:"boolean",describe:"keep session data and snapshots",default:!1}).option("dry-run",{type:"boolean",describe:"show what would be removed without removing",default:!1}).option("force",{alias:"f",type:"boolean",describe:"skip confirmation prompts",default:!1}),handler:async(j)=>{Q.empty(),Q.println(Q.logo(" ")),Q.empty(),w("Uninstall QitQode");let B=await A.runPromise($.Service.use((J)=>J.method()));N.info(`Installation method: ${B}`);let E=await v(j,B);if(await z(E,B),!j.force&&!j.dryRun){let J=await q({message:"Are you sure you want to uninstall?",initialValue:!1});if(!J||T(J)){X("Cancelled");return}}if(j.dryRun){N.warn("Dry run - no changes made"),X("Done");return}await G(B,E),X("Done")}};async function v(j,B){let E=[{path:W.Path.data,label:"Data",keep:j.keepData},{path:W.Path.cache,label:"Cache",keep:!1},{path:W.Path.config,label:"Config",keep:j.keepConfig},{path:W.Path.state,label:"State",keep:!1}],J=B==="curl"?await P():null,H=B==="curl"?process.execPath:null;return{directories:E,shellConfig:J,binary:H}}async function z(j,B){N.message("The following will be removed:");for(let E of j.directories){if(!await V.access(E.path).then(()=>!0).catch(()=>!1))continue;let H=await F(E.path),K=S(H),O=E.keep?Q.Style.TEXT_DIM+"(keeping)":"",M=E.keep?"\u25CB":"\u2713";N.info(` ${M} ${E.label}: ${Z(E.path)} ${Q.Style.TEXT_DIM}(${K})${O}`)}if(j.binary)N.info(` \u2713 Binary: ${Z(j.binary)}`);if(j.shellConfig)N.info(` \u2713 Shell PATH in ${Z(j.shellConfig)}`);if(B!=="curl"&&B!=="unknown"){let E={npm:"npm uninstall -g @qitqode/cli",pnpm:"pnpm uninstall -g @qitqode/cli",bun:"bun remove -g @qitqode/cli"};N.info(` \u2713 Package: ${E[B]||B}`)}}async function G(j,B){let E=D(),J=[];for(let H of B.directories){if(H.keep){N.step(`Skipping ${H.label} (--keep-${H.label.toLowerCase()})`);continue}if(!await V.access(H.path).then(()=>!0).catch(()=>!1))continue;E.start(`Removing ${H.label}...`);let O=await V.rm(H.path,{recursive:!0,force:!0}).catch((M)=>M);if(O){E.stop(`Failed to remove ${H.label}`,1),J.push(`${H.label}: ${O.message}`);continue}E.stop(`Removed ${H.label}`)}if(B.shellConfig){E.start("Cleaning shell config...");let H=await k(B.shellConfig).catch((K)=>K);if(H)E.stop("Failed to clean shell config",1),J.push(`Shell config: ${H.message}`);else E.stop("Cleaned shell config")}if(j!=="curl"&&j!=="unknown"){let K={npm:["npm","uninstall","-g","@qitqode/cli"],pnpm:["pnpm","uninstall","-g","@qitqode/cli"],bun:["bun","remove","-g","@qitqode/cli"]}[j];if(K){E.start(`Running ${K.join(" ")}...`);let O=await _.run(K,{nothrow:!0});if(O.code!==0)E.stop(`Package manager uninstall failed: exit code ${O.code}`,1),N.warn(`You may need to run manually: ${K.join(" ")}`);else E.stop("Package removed")}else N.warn(`Uninstall not supported for method "${j}" yet, skipping package removal`)}if(j==="curl"&&B.binary){Q.empty(),N.message("To finish removing the binary, run:"),N.info(` rm "${B.binary}"`);let H=L.dirname(B.binary);if(H.includes(".qitqode"))N.info(` rmdir "${H}" 2>/dev/null`)}if(J.length>0){Q.empty(),N.warn("Some operations failed:");for(let H of J)N.error(` ${H}`)}Q.empty(),N.success("Thank you for using QitQode!")}async function P(){let j=L.basename(process.env.SHELL||"bash"),B=R.homedir(),E=process.env.XDG_CONFIG_HOME||L.join(B,".config"),J={fish:[L.join(E,"fish","config.fish")],zsh:[L.join(B,".zshrc"),L.join(B,".zshenv"),L.join(E,"zsh",".zshrc"),L.join(E,"zsh",".zshenv")],bash:[L.join(B,".bashrc"),L.join(B,".bash_profile"),L.join(B,".profile"),L.join(E,"bash",".bashrc"),L.join(E,"bash",".bash_profile")],ash:[L.join(B,".ashrc"),L.join(B,".profile")],sh:[L.join(B,".profile")]},H=J[j]||J.bash;for(let K of H){if(!await V.access(K).then(()=>!0).catch(()=>!1))continue;let M=await Y.readText(K).catch(()=>"");if(M.includes("# qitqode")||M.includes(".qitqode/bin"))return K}return null}async function k(j){let E=(await Y.readText(j)).split(`
3
3
  `),J=[],H=!1;for(let O of E){let M=O.trim();if(M==="# qitqode"){H=!0;continue}if(H){if(H=!1,M.includes(".qitqode/bin")||M.includes("fish_add_path"))continue}if(M.startsWith("export PATH=")&&M.includes(".qitqode/bin")||M.startsWith("fish_add_path")&&M.includes(".qitqode"))continue;J.push(O)}while(J.length>0&&J[J.length-1].trim()==="")J.pop();let K=J.join(`
4
4
  `)+`
5
5
  `;await Y.write(j,K)}async function F(j){let B=0,E=async(J)=>{let H=await V.readdir(J,{withFileTypes:!0}).catch(()=>[]);for(let K of H){let O=L.join(J,K.name);if(K.isDirectory()){await E(O);continue}if(K.isFile()){let M=await V.stat(O).catch(()=>null);if(M)B+=M.size}}};return await E(j),B}function S(j){if(j<1024)return`${j} B`;if(j<1048576)return`${(j/1024).toFixed(1)} KB`;if(j<1073741824)return`${(j/1048576).toFixed(1)} MB`;return`${(j/1073741824).toFixed(1)} GB`}function Z(j){let B=R.homedir();if(j===B||j.startsWith(B+L.sep))return"~"+j.slice(B.length);return j}export{g as UninstallCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{rm as jn,sm as pt,tm as bn,um as _t,wm as Xr,xm as Yr}from"./chunk-redjxn13.js";import{$m as fo,Bm as er,Cm as mr,Dm as ur,Dn as ut,Em as yr,Fm as lr,Gm as fr,Hm as gr,Im as sr,Jm as pr,Km as _r,Lm as Nr,Mm as Tr,Nm as q,Om as Ar,Pm as dr,Qm as Or,Rm as $r,Sm as Dr,Tm as vr,Um as F,Vm as D,Wm as yn,Xm as un,Ym as Zo,Zm as Qr,_m as U,an as Rn,bn as go,cn as so,dn as po,en as _o,fn as No,gn as To,hn as Ao,in as Br,jn as Oo,kn as $o,ln as Do,mn as Ir,nn as vo,on as Lr,pn as Qo,qn as Sr,rn as Gr,sn as Mr,tn as xr,un as Cr,vn as Jr,wn as Bo,xn as Io,ym as uo,yn as wo,zm as yo}from"./chunk-bn0h9dny.js";import{ho as wn,lo as Fn}from"./chunk-vcw00k0n.js";import{Co as ft}from"./chunk-2hc5z7b5.js";import{Do as Mo}from"./chunk-d68fzyw7.js";import{Fq as Pn,Gq as hn,Hq as _n,Iq as hr,Jq as it,Lq as nt}from"./chunk-c1bdzxbx.js";import{Mq as rt}from"./chunk-ehhas0ew.js";import{Sr as ro}from"./chunk-4cnwn1rh.js";import{Gs as fn,Qs as On,Rs as nn,Wr as co,_s as a}from"./chunk-m5m448mg.js";import{kt as Zr,nt as ko,ot as z,st as mo}from"./chunk-tqj69nh6.js";import{ut as j}from"./chunk-5tray1fw.js";import{Fz as Cn,jz as Nn,rz as Gn}from"./chunk-gagtmjmp.js";import{EI as In,OE as h,RM as _,WD as Ro,aO as Ur,bE as Zn,bN as Wo,iE as gn,pH as r,uB as an,yE as Wr,zC as Dn}from"./chunk-zs8kqdsf.js";import{DO as dn}from"./chunk-7xm75w1e.js";var qo={};dn(qo,{run:()=>Ot});var mn={time_created:F().notNull().$default(()=>Date.now()),time_updated:F().notNull().$onUpdate(()=>Date.now())};var G=un("project",{id:D().$type().primaryKey(),worktree:D().notNull(),vcs:D(),name:D(),icon_url:D(),icon_color:D(),...mn,time_initialized:F(),sandboxes:D({mode:"json"}).notNull().$type(),commands:D({mode:"json"}).$type()});var ln=un("session",{id:D().$type().primaryKey(),project_id:D().$type().notNull().references(()=>G.id,{onDelete:"cascade"}),workspace_id:D().$type(),parent_id:D().$type(),context_from:D().$type(),context_watermark:D().$type(),slug:D().notNull(),directory:D().notNull(),title:D().notNull(),version:D().notNull(),share_url:D(),summary_additions:F(),summary_deletions:F(),summary_files:F(),summary_diffs:D({mode:"json"}).$type(),revert:D({mode:"json"}).$type(),permission:D({mode:"json"}).$type(),...mn,time_compacting:F(),time_archived:F(),last_checkpoint_message_id:D().$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:D().$type().primaryKey(),session_id:D().$type().notNull().references(()=>ln.id,{onDelete:"cascade"}),agent_id:D().notNull().default("main"),...mn,data:D({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)]),Xo=un("part",{id:D().$type().primaryKey(),message_id:D().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:D().$type().notNull(),...mn,data:D({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)]),Yo=un("todo",{session_id:D().$type().notNull().references(()=>ln.id,{onDelete:"cascade"}),content:D().notNull(),status:D().notNull(),position:F().notNull(),...mn},(n)=>[Zo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),ao=un("permission",{project_id:D().primaryKey().references(()=>G.id,{onDelete:"cascade"}),...mn,data:D({mode:"json"}).notNull().$type()});var zo=un("session_share",{session_id:D().primaryKey().references(()=>ln.id,{onDelete:"cascade"}),id:D().notNull(),secret:D().notNull(),url:D().notNull(),...mn});import Y from"path";var W=a.create({service:"json-migration"});async function Ot(n,o){let t=Y.join(On.Path.data,"storage");if(!await mo.exists(t))return W.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};W.info("starting json to sqlite migration",{storageDir:t});let g=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:[]},T={sessions:0,todos:0,permissions:0,shares:0},p=e.errors,A=1000,M=Date.now();async function H(l){return ko.scan(l,{cwd:t,absolute:!0})}async function C(l,L,x){let v=x-L,N=Array(v);for(let K=0;K<v;K++)N[K]=mo.readJson(l[L+K]);let S=await Promise.allSettled(N),P=Array(v);for(let K=0;K<S.length;K++){let k=S[K];if(k.status==="fulfilled"){P[K]=k.value;continue}p.push(`failed to read ${l[L+K]}: ${k.reason}`)}return P}function J(l,L,x){if(l.length===0)return 0;try{return n.insert(L).values(l).onConflictDoNothing().run(),l.length}catch(v){return p.push(`failed to migrate ${x} batch: ${v}`),0}}W.info("scanning files...");let[R,O,Q,I,f,s,m]=await Promise.all([H("project/*.json"),H("session/*/*.json"),H("message/*/*.json"),H("part/*/*.json"),H("todo/*.json"),H("permission/*.json"),H("session_share/*.json")]);W.info("file scan complete",{projects:R.length,sessions:O.length,messages:Q.length,parts:I.length,todos:f.length,permissions:s.length,shares:m.length});let y=Math.max(1,R.length+O.length+Q.length+I.length+f.length+s.length+m.length),i=o?.progress,u=0,$=(l,L)=>{u=Math.min(y,u+L),i?.({current:u,total:y,label:l})};i?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let B=new Set,d=[];for(let l=0;l<R.length;l+=A){let L=Math.min(l+A,R.length),x=await C(R,l,L);d.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=Y.basename(R[l+v],".json");B.add(S),d.push({id:S,worktree:N.worktree??"/",vcs:N.vcs,name:N.name??void 0,icon_url:N.icon?.url,icon_color:N.icon?.color,time_created:N.time?.created??M,time_updated:N.time?.updated??M,time_initialized:N.time?.initialized,sandboxes:N.sandboxes??[],commands:N.commands})}e.projects+=J(d,G,"project"),$("projects",L-l)}W.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-g)});let E=O.map((l)=>Y.basename(Y.dirname(l))),X=new Set,en=[];for(let l=0;l<O.length;l+=A){let L=Math.min(l+A,O.length),x=await C(O,l,L);en.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=Y.basename(O[l+v],".json"),P=E[l+v];if(!B.has(P)){T.sessions++;continue}X.add(S),en.push({id:S,project_id:P,parent_id:N.parentID??null,slug:N.slug??"",directory:N.directory??"",title:N.title??"",version:N.version??"",share_url:N.share?.url??null,summary_additions:N.summary?.additions??null,summary_deletions:N.summary?.deletions??null,summary_files:N.summary?.files??null,summary_diffs:N.summary?.diffs??null,revert:N.revert??null,permission:N.permission??null,time_created:N.time?.created??M,time_updated:N.time?.updated??M,time_compacting:N.time?.compacting??null,time_archived:N.time?.archived??null})}e.sessions+=J(en,ln,"session"),$("sessions",L-l)}if(W.info("migrated sessions",{count:e.sessions}),T.sessions>0)W.warn("skipped orphaned sessions",{count:T.sessions});let sn=[],c=[],zn=new Map;for(let l of Q){let L=Y.basename(Y.dirname(l));if(!X.has(L))continue;sn.push(l),c.push(L)}for(let l=0;l<sn.length;l+=A){let L=Math.min(l+A,sn.length),x=await C(sn,l,L),v=Array(x.length),N=0;for(let S=0;S<x.length;S++){let P=x[S];if(!P)continue;let K=sn[l+S],k=Y.basename(K,".json"),Hn=c[l+S];zn.set(k,Hn);let vn=P;delete vn.id,delete vn.sessionID,v[N++]={id:k,session_id:Hn,time_created:P.time?.created??M,time_updated:P.time?.updated??M,data:vn}}v.length=N,e.messages+=J(v,eo,"message"),$("messages",L-l)}W.info("migrated messages",{count:e.messages});for(let l=0;l<I.length;l+=A){let L=Math.min(l+A,I.length),x=await C(I,l,L),v=Array(x.length),N=0;for(let S=0;S<x.length;S++){let P=x[S];if(!P)continue;let K=I[l+S],k=Y.basename(K,".json"),Hn=Y.basename(Y.dirname(K)),vn=zn.get(Hn);if(!vn){p.push(`part missing message session: ${K}`);continue}if(!X.has(vn))continue;let Vn=P;delete Vn.id,delete Vn.messageID,delete Vn.sessionID,v[N++]={id:k,message_id:Hn,session_id:vn,time_created:P.time?.created??M,time_updated:P.time?.updated??M,data:Vn}}v.length=N,e.parts+=J(v,Xo,"part"),$("parts",L-l)}W.info("migrated parts",{count:e.parts});let An=f.map((l)=>Y.basename(l,".json"));for(let l=0;l<f.length;l+=A){let L=Math.min(l+A,f.length),x=await C(f,l,L),v=[];for(let N=0;N<x.length;N++){let S=x[N];if(!S)continue;let P=An[l+N];if(!X.has(P)){T.todos++;continue}if(!Array.isArray(S)){p.push(`todo not an array: ${f[l+N]}`);continue}for(let K=0;K<S.length;K++){let k=S[K];if(!k?.content||!k?.status)continue;v.push({session_id:P,content:k.content,status:k.status,position:K,time_created:M,time_updated:M})}}e.todos+=J(v,Yo,"todo"),$("todos",L-l)}if(W.info("migrated todos",{count:e.todos}),T.todos>0)W.warn("skipped orphaned todos",{count:T.todos});let kn=s.map((l)=>Y.basename(l,".json")),Jn=[];for(let l=0;l<s.length;l+=A){let L=Math.min(l+A,s.length),x=await C(s,l,L);Jn.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=kn[l+v];if(!B.has(S)){T.permissions++;continue}Jn.push({project_id:S,data:N})}e.permissions+=J(Jn,ao,"permission"),$("permissions",L-l)}if(W.info("migrated permissions",{count:e.permissions}),T.permissions>0)W.warn("skipped orphaned permissions",{count:T.permissions});let qn=m.map((l)=>Y.basename(l,".json")),Ln=[];for(let l=0;l<m.length;l+=A){let L=Math.min(l+A,m.length),x=await C(m,l,L);Ln.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=qn[l+v];if(!X.has(S)){T.shares++;continue}if(!N?.id||!N?.secret||!N?.url){p.push(`session_share missing id/secret/url: ${m[l+v]}`);continue}Ln.push({session_id:S,id:N.id,secret:N.secret,url:N.url})}e.shares+=J(Ln,zo,"session_share"),$("shares",L-l)}if(W.info("migrated session shares",{count:e.shares}),T.shares>0)W.warn("skipped orphaned session shares",{count:T.shares});if(n.run("COMMIT"),W.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()-g)}),e.errors.length>0)W.warn("migration errors",{errors:e.errors.slice(0,20)});return i?.({current:y,total:y,label:"complete"}),e}var Bn={};dn(Bn,{use:()=>Ce,transaction:()=>He,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>q,relationsOrderToSQL:()=>ci,relationsFilterToSQL:()=>Ri,relationToSQL:()=>Hi,relationExtrasToSQL:()=>Ji,processRelations:()=>Ci,placeholder:()=>dr,param:()=>Tr,orderSelectedFields:()=>oe,orderByOperators:()=>xi,or:()=>go,operators:()=>Mi,notLike:()=>Sr,notInArray:()=>Br,notIlike:()=>Mr,notExists:()=>Ir,notBetween:()=>Lr,not:()=>so,noopMapper:()=>_r,noopEncoder:()=>pr,noopDecoder:()=>sr,ne:()=>fo,name:()=>fr,min:()=>ir,max:()=>tr,mapUpdateSet:()=>ne,mapResultRow:()=>hi,mapRelationalRow:()=>Gi,mapColumnsInSQLToAlias:()=>ti,mapColumnsInAliasedSQLToAlias:()=>ri,lte:()=>To,lt:()=>No,like:()=>Qo,l2Distance:()=>Zi,l1Distance:()=>Ui,jaccardDistance:()=>Wi,isWithEnum:()=>bi,isView:()=>Dr,isTable:()=>Xt,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>gr,isConfig:()=>ji,is:()=>Mt,innerProduct:()=>Pi,inArray:()=>Ao,ilike:()=>Gr,haveSameKeys:()=>Fi,hasOwnEntityKind:()=>Gt,hammingDistance:()=>Ei,gte:()=>_o,gt:()=>po,getViewSelectedFields:()=>wi,getViewName:()=>vr,getTableUniqueName:()=>Zt,getTableName:()=>Ut,getTableLikeName:()=>Vi,getTableColumns:()=>qi,getTableAsAliasSQL:()=>Si,getOriginalColumnFromAlias:()=>oi,getOrderByOperators:()=>Li,getColumns:()=>ki,getColumnTable:()=>Ct,getColumnNameAndConfig:()=>zi,getChannelPath:()=>gt,fillPlaceholders:()=>Or,fieldSelectionToSQL:()=>Ii,extractTablesFromSchema:()=>Bi,extractExtendedColumnType:()=>mi,exists:()=>Do,eq:()=>U,entityKind:()=>St,effect:()=>Je,desc:()=>Io,defineRelationsPart:()=>Qi,defineRelations:()=>vi,createRelationsHelper:()=>Di,countDistinct:()=>bo,count:()=>lo,cosineDistance:()=>Ki,close:()=>xe,buildRelationsParts:()=>$i,buildRelations:()=>Oi,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ai,asc:()=>Bo,arrayOverlaps:()=>Jr,arrayContains:()=>xr,arrayContained:()=>Cr,applyMixins:()=>Yi,and:()=>Rn,aliasedTableColumn:()=>ni,aliasedTable:()=>ht,aliasedRelation:()=>bt,aliasedColumn:()=>jt,WithSubquery:()=>at,ViewSelectionAliasProxyHandler:()=>Ft,ViewBaseConfig:()=>zt,View:()=>$r,TransactionRollbackError:()=>li,TableSchema:()=>Wt,TableColumns:()=>Pt,TableAliasProxyHandler:()=>wt,Table:()=>Et,Subquery:()=>Yt,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>di,RelationsBuilderTable:()=>Ai,RelationsBuilderJunctionColumn:()=>Ti,RelationsBuilderColumn:()=>Ni,RelationTableAliasProxyHandler:()=>Vt,Relation:()=>_i,QueryPromise:()=>ii,Placeholder:()=>Ar,Path:()=>Ko,Param:()=>Nr,OriginalName:()=>Kt,One:()=>pi,NotFoundError:()=>Me,NoopLogger:()=>Lt,Name:()=>lr,Many:()=>si,IsAlias:()=>ct,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Rt,ExtraConfigBuilder:()=>Ht,DrizzleQueryError:()=>yi,DrizzleError:()=>ui,DefaultLogger:()=>It,Count:()=>gi,ConsoleLogWriter:()=>Bt,ColumnTableAliasProxyHandler:()=>qt,ColumnBuilder:()=>ei,ColumnAliasProxyHandler:()=>kt,Column:()=>xt,Client:()=>Mn,CONSTANTS:()=>Xi,BaseName:()=>Jt,AggregatedField:()=>fi});import $t from"crypto";import Vo,{existsSync as Dt,readdirSync as vt}from"fs";import{join as Qt}from"path";function Fo(n){if(Vo.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,t=[],g=vt(o).map((e)=>({path:Qt(o,e,"migration.sql"),name:e})).filter((e)=>Dt(e.path));g.sort((e,T)=>e.name.localeCompare(T.name));for(let e of g){let T=e.path,p=e.name.slice(0,14),A=Vo.readFileSync(T).toString(),M=A.split("--> statement-breakpoint").map((C)=>{return C}),H=wo(p);t.push({sql:M,bps:!0,folderMillis:H,hash:$t.createHash("sha256").update(A).digest("hex"),name:e.name})}return t}function jo(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let g=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,T=g.map((p)=>({sql:p.sql.split("--> statement-breakpoint"),folderMillis:p.timestamp,hash:"",bps:!0,name:p.name}));return n.dialect.migrate(T,n.session,{migrationsTable:e})}let t=Fo(o);return n.dialect.migrate(t,n.session,o)}function lo(n){return q`count(${n||q.raw("*")})`.mapWith(Number)}function bo(n){return q`count(distinct ${n})`.mapWith(Number)}function ho(n){return q`avg(${n})`.mapWith(String)}function nr(n){return q`avg(distinct ${n})`.mapWith(String)}function or(n){return q`sum(${n})`.mapWith(String)}function rr(n){return q`sum(distinct ${n})`.mapWith(String)}function tr(n){return q`max(${n})`.mapWith(uo(n,yo)?n:String)}function ir(n){return q`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Wn={};dn(Wn,{workspaceID:()=>$e,useEffect:()=>Qe,use:()=>ve,make:()=>De,invalidate:()=>Ie,has:()=>Be,get:()=>Ho,directory:()=>no,context:()=>Jo,bind:()=>Oe});import{EventEmitter as te}from"events";var cn=new te;var Lo=new Set;function Hr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function So(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function Kn(n){return n()}var Fr={};dn(Fr,{setInitialized:()=>se,list:()=>fe,layer:()=>wr,get:()=>ge,fromRow:()=>pn,defaultLayer:()=>Co,UpdateInput:()=>le,Service:()=>Sn,Info:()=>qr,Event:()=>Vr});import*as w from"fs/promises";import*as ar from"os";import*as $n from"path";var ie=_.String.pipe(_.brand("ProjectID")),V=ie.pipe(wn((n)=>({global:n.make("global"),zod:j.string().pipe(j.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Kr from"crypto";async function Go(n){let o=b.resolve(n);while(!0){let t=b.join(o,".git"),g=await Qn.stat(t).catch(()=>null);if(g){if(g.isDirectory())return t;let p=(await Qn.readFile(t,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!p)return null;let A=b.isAbsolute(p[1])?p[1]:b.resolve(o,p[1]);return b.resolve(A,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Rr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function cr(n){let o=await Rr(n);if(o)return o;let t=Kr.randomUUID();try{return await Qn.writeFile(n,t,{flag:"wx"}),t}catch(g){if(g.code!=="EEXIST")throw g;let e=await Rr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Er(n){let o=await Go(n);if(o){let g=b.join(o,"qitqode-project-id");return V.make(await cr(g))}let t=b.join(n,".qitqode-project-id");return V.make(await cr(t))}async function me(n){let o=await Go(n);if(!o)return;let t=$n.join(n,".qitqode-project-id"),g=$n.join(o,"qitqode-project-id"),e=(A)=>w.access(A).then(()=>!0).catch(()=>!1);if(await e(t)){if(!await e(g)){let A=await w.readFile(t,"utf-8");await w.writeFile(g,A)}await w.unlink(t).catch(()=>{})}let T=$n.join(o,"info","exclude");if(await w.mkdir($n.dirname(T),{recursive:!0}),!(await w.readFile(T,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await w.appendFile(T,`
2
+ import{rm as jn,sm as pt,tm as bn,um as _t,wm as Xr,xm as Yr}from"./chunk-ezfy0b6q.js";import{$m as fo,Bm as er,Cm as mr,Dm as ur,Dn as ut,Em as yr,Fm as lr,Gm as fr,Hm as gr,Im as sr,Jm as pr,Km as _r,Lm as Nr,Mm as Tr,Nm as q,Om as Ar,Pm as dr,Qm as Or,Rm as $r,Sm as Dr,Tm as vr,Um as F,Vm as D,Wm as yn,Xm as un,Ym as Zo,Zm as Qr,_m as U,an as Rn,bn as go,cn as so,dn as po,en as _o,fn as No,gn as To,hn as Ao,in as Br,jn as Oo,kn as $o,ln as Do,mn as Ir,nn as vo,on as Lr,pn as Qo,qn as Sr,rn as Gr,sn as Mr,tn as xr,un as Cr,vn as Jr,wn as Bo,xn as Io,ym as uo,yn as wo,zm as yo}from"./chunk-bn0h9dny.js";import{ho as wn,lo as Fn}from"./chunk-vcw00k0n.js";import{Co as ft}from"./chunk-2hc5z7b5.js";import{Do as Mo}from"./chunk-9gazyynx.js";import{Fq as Pn,Gq as hn,Hq as _n,Iq as hr,Jq as it,Lq as nt}from"./chunk-d9hbhkbq.js";import{Mq as rt}from"./chunk-ad72gb5f.js";import{Sr as ro}from"./chunk-4cnwn1rh.js";import{Gs as fn,Qs as On,Rs as nn,Wr as co,_s as a}from"./chunk-xj765svc.js";import{kt as Zr,nt as ko,ot as z,st as mo}from"./chunk-tqj69nh6.js";import{ut as j}from"./chunk-5tray1fw.js";import{Fz as Cn,jz as Nn,rz as Gn}from"./chunk-gagtmjmp.js";import{EI as In,OE as h,RM as _,WD as Ro,aO as Ur,bE as Zn,bN as Wo,iE as gn,pH as r,uB as an,yE as Wr,zC as Dn}from"./chunk-zs8kqdsf.js";import{DO as dn}from"./chunk-7xm75w1e.js";var qo={};dn(qo,{run:()=>Ot});var mn={time_created:F().notNull().$default(()=>Date.now()),time_updated:F().notNull().$onUpdate(()=>Date.now())};var G=un("project",{id:D().$type().primaryKey(),worktree:D().notNull(),vcs:D(),name:D(),icon_url:D(),icon_color:D(),...mn,time_initialized:F(),sandboxes:D({mode:"json"}).notNull().$type(),commands:D({mode:"json"}).$type()});var ln=un("session",{id:D().$type().primaryKey(),project_id:D().$type().notNull().references(()=>G.id,{onDelete:"cascade"}),workspace_id:D().$type(),parent_id:D().$type(),context_from:D().$type(),context_watermark:D().$type(),slug:D().notNull(),directory:D().notNull(),title:D().notNull(),version:D().notNull(),share_url:D(),summary_additions:F(),summary_deletions:F(),summary_files:F(),summary_diffs:D({mode:"json"}).$type(),revert:D({mode:"json"}).$type(),permission:D({mode:"json"}).$type(),...mn,time_compacting:F(),time_archived:F(),last_checkpoint_message_id:D().$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:D().$type().primaryKey(),session_id:D().$type().notNull().references(()=>ln.id,{onDelete:"cascade"}),agent_id:D().notNull().default("main"),...mn,data:D({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)]),Xo=un("part",{id:D().$type().primaryKey(),message_id:D().$type().notNull().references(()=>eo.id,{onDelete:"cascade"}),session_id:D().$type().notNull(),...mn,data:D({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)]),Yo=un("todo",{session_id:D().$type().notNull().references(()=>ln.id,{onDelete:"cascade"}),content:D().notNull(),status:D().notNull(),position:F().notNull(),...mn},(n)=>[Zo({columns:[n.session_id,n.position]}),yn("todo_session_idx").on(n.session_id)]),ao=un("permission",{project_id:D().primaryKey().references(()=>G.id,{onDelete:"cascade"}),...mn,data:D({mode:"json"}).notNull().$type()});var zo=un("session_share",{session_id:D().primaryKey().references(()=>ln.id,{onDelete:"cascade"}),id:D().notNull(),secret:D().notNull(),url:D().notNull(),...mn});import Y from"path";var W=a.create({service:"json-migration"});async function Ot(n,o){let t=Y.join(On.Path.data,"storage");if(!await mo.exists(t))return W.info("storage directory does not exist, skipping migration"),{projects:0,sessions:0,messages:0,parts:0,todos:0,permissions:0,shares:0,errors:[]};W.info("starting json to sqlite migration",{storageDir:t});let g=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:[]},T={sessions:0,todos:0,permissions:0,shares:0},p=e.errors,A=1000,M=Date.now();async function H(l){return ko.scan(l,{cwd:t,absolute:!0})}async function C(l,L,x){let v=x-L,N=Array(v);for(let K=0;K<v;K++)N[K]=mo.readJson(l[L+K]);let S=await Promise.allSettled(N),P=Array(v);for(let K=0;K<S.length;K++){let k=S[K];if(k.status==="fulfilled"){P[K]=k.value;continue}p.push(`failed to read ${l[L+K]}: ${k.reason}`)}return P}function J(l,L,x){if(l.length===0)return 0;try{return n.insert(L).values(l).onConflictDoNothing().run(),l.length}catch(v){return p.push(`failed to migrate ${x} batch: ${v}`),0}}W.info("scanning files...");let[R,O,Q,I,f,s,m]=await Promise.all([H("project/*.json"),H("session/*/*.json"),H("message/*/*.json"),H("part/*/*.json"),H("todo/*.json"),H("permission/*.json"),H("session_share/*.json")]);W.info("file scan complete",{projects:R.length,sessions:O.length,messages:Q.length,parts:I.length,todos:f.length,permissions:s.length,shares:m.length});let y=Math.max(1,R.length+O.length+Q.length+I.length+f.length+s.length+m.length),i=o?.progress,u=0,$=(l,L)=>{u=Math.min(y,u+L),i?.({current:u,total:y,label:l})};i?.({current:u,total:y,label:"starting"}),n.run("BEGIN TRANSACTION");let B=new Set,d=[];for(let l=0;l<R.length;l+=A){let L=Math.min(l+A,R.length),x=await C(R,l,L);d.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=Y.basename(R[l+v],".json");B.add(S),d.push({id:S,worktree:N.worktree??"/",vcs:N.vcs,name:N.name??void 0,icon_url:N.icon?.url,icon_color:N.icon?.color,time_created:N.time?.created??M,time_updated:N.time?.updated??M,time_initialized:N.time?.initialized,sandboxes:N.sandboxes??[],commands:N.commands})}e.projects+=J(d,G,"project"),$("projects",L-l)}W.info("migrated projects",{count:e.projects,duration:Math.round(performance.now()-g)});let E=O.map((l)=>Y.basename(Y.dirname(l))),X=new Set,en=[];for(let l=0;l<O.length;l+=A){let L=Math.min(l+A,O.length),x=await C(O,l,L);en.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=Y.basename(O[l+v],".json"),P=E[l+v];if(!B.has(P)){T.sessions++;continue}X.add(S),en.push({id:S,project_id:P,parent_id:N.parentID??null,slug:N.slug??"",directory:N.directory??"",title:N.title??"",version:N.version??"",share_url:N.share?.url??null,summary_additions:N.summary?.additions??null,summary_deletions:N.summary?.deletions??null,summary_files:N.summary?.files??null,summary_diffs:N.summary?.diffs??null,revert:N.revert??null,permission:N.permission??null,time_created:N.time?.created??M,time_updated:N.time?.updated??M,time_compacting:N.time?.compacting??null,time_archived:N.time?.archived??null})}e.sessions+=J(en,ln,"session"),$("sessions",L-l)}if(W.info("migrated sessions",{count:e.sessions}),T.sessions>0)W.warn("skipped orphaned sessions",{count:T.sessions});let sn=[],c=[],zn=new Map;for(let l of Q){let L=Y.basename(Y.dirname(l));if(!X.has(L))continue;sn.push(l),c.push(L)}for(let l=0;l<sn.length;l+=A){let L=Math.min(l+A,sn.length),x=await C(sn,l,L),v=Array(x.length),N=0;for(let S=0;S<x.length;S++){let P=x[S];if(!P)continue;let K=sn[l+S],k=Y.basename(K,".json"),Hn=c[l+S];zn.set(k,Hn);let vn=P;delete vn.id,delete vn.sessionID,v[N++]={id:k,session_id:Hn,time_created:P.time?.created??M,time_updated:P.time?.updated??M,data:vn}}v.length=N,e.messages+=J(v,eo,"message"),$("messages",L-l)}W.info("migrated messages",{count:e.messages});for(let l=0;l<I.length;l+=A){let L=Math.min(l+A,I.length),x=await C(I,l,L),v=Array(x.length),N=0;for(let S=0;S<x.length;S++){let P=x[S];if(!P)continue;let K=I[l+S],k=Y.basename(K,".json"),Hn=Y.basename(Y.dirname(K)),vn=zn.get(Hn);if(!vn){p.push(`part missing message session: ${K}`);continue}if(!X.has(vn))continue;let Vn=P;delete Vn.id,delete Vn.messageID,delete Vn.sessionID,v[N++]={id:k,message_id:Hn,session_id:vn,time_created:P.time?.created??M,time_updated:P.time?.updated??M,data:Vn}}v.length=N,e.parts+=J(v,Xo,"part"),$("parts",L-l)}W.info("migrated parts",{count:e.parts});let An=f.map((l)=>Y.basename(l,".json"));for(let l=0;l<f.length;l+=A){let L=Math.min(l+A,f.length),x=await C(f,l,L),v=[];for(let N=0;N<x.length;N++){let S=x[N];if(!S)continue;let P=An[l+N];if(!X.has(P)){T.todos++;continue}if(!Array.isArray(S)){p.push(`todo not an array: ${f[l+N]}`);continue}for(let K=0;K<S.length;K++){let k=S[K];if(!k?.content||!k?.status)continue;v.push({session_id:P,content:k.content,status:k.status,position:K,time_created:M,time_updated:M})}}e.todos+=J(v,Yo,"todo"),$("todos",L-l)}if(W.info("migrated todos",{count:e.todos}),T.todos>0)W.warn("skipped orphaned todos",{count:T.todos});let kn=s.map((l)=>Y.basename(l,".json")),Jn=[];for(let l=0;l<s.length;l+=A){let L=Math.min(l+A,s.length),x=await C(s,l,L);Jn.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=kn[l+v];if(!B.has(S)){T.permissions++;continue}Jn.push({project_id:S,data:N})}e.permissions+=J(Jn,ao,"permission"),$("permissions",L-l)}if(W.info("migrated permissions",{count:e.permissions}),T.permissions>0)W.warn("skipped orphaned permissions",{count:T.permissions});let qn=m.map((l)=>Y.basename(l,".json")),Ln=[];for(let l=0;l<m.length;l+=A){let L=Math.min(l+A,m.length),x=await C(m,l,L);Ln.length=0;for(let v=0;v<x.length;v++){let N=x[v];if(!N)continue;let S=qn[l+v];if(!X.has(S)){T.shares++;continue}if(!N?.id||!N?.secret||!N?.url){p.push(`session_share missing id/secret/url: ${m[l+v]}`);continue}Ln.push({session_id:S,id:N.id,secret:N.secret,url:N.url})}e.shares+=J(Ln,zo,"session_share"),$("shares",L-l)}if(W.info("migrated session shares",{count:e.shares}),T.shares>0)W.warn("skipped orphaned session shares",{count:T.shares});if(n.run("COMMIT"),W.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()-g)}),e.errors.length>0)W.warn("migration errors",{errors:e.errors.slice(0,20)});return i?.({current:y,total:y,label:"complete"}),e}var Bn={};dn(Bn,{use:()=>Ce,transaction:()=>He,textDecoder:()=>re,sumDistinct:()=>rr,sum:()=>or,sql:()=>q,relationsOrderToSQL:()=>ci,relationsFilterToSQL:()=>Ri,relationToSQL:()=>Hi,relationExtrasToSQL:()=>Ji,processRelations:()=>Ci,placeholder:()=>dr,param:()=>Tr,orderSelectedFields:()=>oe,orderByOperators:()=>xi,or:()=>go,operators:()=>Mi,notLike:()=>Sr,notInArray:()=>Br,notIlike:()=>Mr,notExists:()=>Ir,notBetween:()=>Lr,not:()=>so,noopMapper:()=>_r,noopEncoder:()=>pr,noopDecoder:()=>sr,ne:()=>fo,name:()=>fr,min:()=>ir,max:()=>tr,mapUpdateSet:()=>ne,mapResultRow:()=>hi,mapRelationalRow:()=>Gi,mapColumnsInSQLToAlias:()=>ti,mapColumnsInAliasedSQLToAlias:()=>ri,lte:()=>To,lt:()=>No,like:()=>Qo,l2Distance:()=>Zi,l1Distance:()=>Ui,jaccardDistance:()=>Wi,isWithEnum:()=>bi,isView:()=>Dr,isTable:()=>Xt,isSQLWrapper:()=>mr,isNull:()=>Oo,isNotNull:()=>$o,isDriverValueEncoder:()=>gr,isConfig:()=>ji,is:()=>Mt,innerProduct:()=>Pi,inArray:()=>Ao,ilike:()=>Gr,haveSameKeys:()=>Fi,hasOwnEntityKind:()=>Gt,hammingDistance:()=>Ei,gte:()=>_o,gt:()=>po,getViewSelectedFields:()=>wi,getViewName:()=>vr,getTableUniqueName:()=>Zt,getTableName:()=>Ut,getTableLikeName:()=>Vi,getTableColumns:()=>qi,getTableAsAliasSQL:()=>Si,getOriginalColumnFromAlias:()=>oi,getOrderByOperators:()=>Li,getColumns:()=>ki,getColumnTable:()=>Ct,getColumnNameAndConfig:()=>zi,getChannelPath:()=>gt,fillPlaceholders:()=>Or,fieldSelectionToSQL:()=>Ii,extractTablesFromSchema:()=>Bi,extractExtendedColumnType:()=>mi,exists:()=>Do,eq:()=>U,entityKind:()=>St,effect:()=>Je,desc:()=>Io,defineRelationsPart:()=>Qi,defineRelations:()=>vi,createRelationsHelper:()=>Di,countDistinct:()=>bo,count:()=>lo,cosineDistance:()=>Ki,close:()=>xe,buildRelationsParts:()=>$i,buildRelations:()=>Oi,bindIfParam:()=>Qr,between:()=>vo,avgDistinct:()=>nr,avg:()=>ho,assertUnreachable:()=>ai,asc:()=>Bo,arrayOverlaps:()=>Jr,arrayContains:()=>xr,arrayContained:()=>Cr,applyMixins:()=>Yi,and:()=>Rn,aliasedTableColumn:()=>ni,aliasedTable:()=>ht,aliasedRelation:()=>bt,aliasedColumn:()=>jt,WithSubquery:()=>at,ViewSelectionAliasProxyHandler:()=>Ft,ViewBaseConfig:()=>zt,View:()=>$r,TransactionRollbackError:()=>li,TableSchema:()=>Wt,TableColumns:()=>Pt,TableAliasProxyHandler:()=>wt,Table:()=>Et,Subquery:()=>Yt,StringChunk:()=>ur,SQL:()=>yr,RelationsHelperStatic:()=>di,RelationsBuilderTable:()=>Ai,RelationsBuilderJunctionColumn:()=>Ti,RelationsBuilderColumn:()=>Ni,RelationTableAliasProxyHandler:()=>Vt,Relation:()=>_i,QueryPromise:()=>ii,Placeholder:()=>Ar,Path:()=>Ko,Param:()=>Nr,OriginalName:()=>Kt,One:()=>pi,NotFoundError:()=>Me,NoopLogger:()=>Lt,Name:()=>lr,Many:()=>si,IsAlias:()=>ct,FakePrimitiveParam:()=>er,ExtraConfigColumns:()=>Rt,ExtraConfigBuilder:()=>Ht,DrizzleQueryError:()=>yi,DrizzleError:()=>ui,DefaultLogger:()=>It,Count:()=>gi,ConsoleLogWriter:()=>Bt,ColumnTableAliasProxyHandler:()=>qt,ColumnBuilder:()=>ei,ColumnAliasProxyHandler:()=>kt,Column:()=>xt,Client:()=>Mn,CONSTANTS:()=>Xi,BaseName:()=>Jt,AggregatedField:()=>fi});import $t from"crypto";import Vo,{existsSync as Dt,readdirSync as vt}from"fs";import{join as Qt}from"path";function Fo(n){if(Vo.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,t=[],g=vt(o).map((e)=>({path:Qt(o,e,"migration.sql"),name:e})).filter((e)=>Dt(e.path));g.sort((e,T)=>e.name.localeCompare(T.name));for(let e of g){let T=e.path,p=e.name.slice(0,14),A=Vo.readFileSync(T).toString(),M=A.split("--> statement-breakpoint").map((C)=>{return C}),H=wo(p);t.push({sql:M,bps:!0,folderMillis:H,hash:$t.createHash("sha256").update(A).digest("hex"),name:e.name})}return t}function jo(n,o){if(Array.isArray(o)||"migrationsJournal"in o){let g=Array.isArray(o)?o:o.migrationsJournal,e=Array.isArray(o)?void 0:o.migrationsTable,T=g.map((p)=>({sql:p.sql.split("--> statement-breakpoint"),folderMillis:p.timestamp,hash:"",bps:!0,name:p.name}));return n.dialect.migrate(T,n.session,{migrationsTable:e})}let t=Fo(o);return n.dialect.migrate(t,n.session,o)}function lo(n){return q`count(${n||q.raw("*")})`.mapWith(Number)}function bo(n){return q`count(distinct ${n})`.mapWith(Number)}function ho(n){return q`avg(${n})`.mapWith(String)}function nr(n){return q`avg(distinct ${n})`.mapWith(String)}function or(n){return q`sum(${n})`.mapWith(String)}function rr(n){return q`sum(distinct ${n})`.mapWith(String)}function tr(n){return q`max(${n})`.mapWith(uo(n,yo)?n:String)}function ir(n){return q`min(${n})`.mapWith(uo(n,yo)?n:String)}import oo from"path";var Wn={};dn(Wn,{workspaceID:()=>$e,useEffect:()=>Qe,use:()=>ve,make:()=>De,invalidate:()=>Ie,has:()=>Be,get:()=>Ho,directory:()=>no,context:()=>Jo,bind:()=>Oe});import{EventEmitter as te}from"events";var cn=new te;var Lo=new Set;function Hr(n){return Lo.add(n),()=>{Lo.delete(n)}}async function So(n){await Promise.allSettled([...Lo].map((o)=>o(n)))}function Kn(n){return n()}var Fr={};dn(Fr,{setInitialized:()=>se,list:()=>fe,layer:()=>wr,get:()=>ge,fromRow:()=>pn,defaultLayer:()=>Co,UpdateInput:()=>le,Service:()=>Sn,Info:()=>qr,Event:()=>Vr});import*as w from"fs/promises";import*as ar from"os";import*as $n from"path";var ie=_.String.pipe(_.brand("ProjectID")),V=ie.pipe(wn((n)=>({global:n.make("global"),zod:j.string().pipe(j.custom())})));import*as Qn from"fs/promises";import*as b from"path";import*as Kr from"crypto";async function Go(n){let o=b.resolve(n);while(!0){let t=b.join(o,".git"),g=await Qn.stat(t).catch(()=>null);if(g){if(g.isDirectory())return t;let p=(await Qn.readFile(t,"utf-8")).trim().match(/^gitdir:\s*(.+)$/);if(!p)return null;let A=b.isAbsolute(p[1])?p[1]:b.resolve(o,p[1]);return b.resolve(A,"../..")}let e=b.dirname(o);if(e===o)return null;o=e}}async function Rr(n){let o=await Qn.readFile(n,"utf-8").catch(()=>null);if(o===null)return null;return o.trim()||null}async function cr(n){let o=await Rr(n);if(o)return o;let t=Kr.randomUUID();try{return await Qn.writeFile(n,t,{flag:"wx"}),t}catch(g){if(g.code!=="EEXIST")throw g;let e=await Rr(n);if(e)return e;throw Error(`Project ID file was concurrently created but is empty: ${n}`)}}async function Er(n){let o=await Go(n);if(o){let g=b.join(o,"qitqode-project-id");return V.make(await cr(g))}let t=b.join(n,".qitqode-project-id");return V.make(await cr(t))}async function me(n){let o=await Go(n);if(!o)return;let t=$n.join(n,".qitqode-project-id"),g=$n.join(o,"qitqode-project-id"),e=(A)=>w.access(A).then(()=>!0).catch(()=>!1);if(await e(t)){if(!await e(g)){let A=await w.readFile(t,"utf-8");await w.writeFile(g,A)}await w.unlink(t).catch(()=>{})}let T=$n.join(o,"info","exclude");if(await w.mkdir($n.dirname(T),{recursive:!0}),!(await w.readFile(T,"utf-8").catch(()=>"")).includes(".qitqode-project-id"))await w.appendFile(T,`
3
3
  .qitqode-project-id
4
4
  `)}var Pr=a.create({service:"project"}),ue=262144,xo=_.Literal("git"),zr=_.Struct({url:_.optional(_.String),override:_.optional(_.String),color:_.optional(_.String)}),kr=_.Struct({start:_.optional(_.String.annotate({description:"Startup script to run when creating a new workspace (worktree)"}))}),ye=_.Struct({created:_.Number,updated:_.Number,initialized:_.optional(_.Number)}),qr=_.Struct({id:V,worktree:_.String,vcs:_.optional(xo),name:_.optional(_.String),icon:_.optional(zr),commands:_.optional(kr),time:ye,sandboxes:_.Array(_.String)}).annotate({identifier:"Project"}).pipe(wn((n)=>({zod:Fn(n)}))),Vr={Updated:Yr.define("project.updated",qr.zod)};function pn(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?_.decodeUnknownSync(xo)(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 le=j.object({projectID:V.zod,name:j.string().optional(),icon:Fn(zr).optional(),commands:Fn(kr).optional()});class Sn extends Dn.Service()("@qitqode/Project"){}var wr=h.effect(Sn,r.gen(function*(){let n=yield*z.Service,o=yield*Ur.Path,t=yield*jn.ChildProcessSpawner,g=r.fnUntraced(function*(i,u){return yield*Xr(t,i,u)},r.catch(()=>r.succeed({code:1,text:"",stderr:""}))),e=(i)=>r.sync(()=>Bn.use(i)),T=(i)=>r.sync(()=>cn.emit("event",{directory:"global",project:i.id,payload:{type:Vr.Updated.type,properties:i}})),p=_.decodeUnknownSync(_.optional(xo))(nn.QITQODE_FAKE_VCS),A=(i,u)=>{if(!u)return i;if(u=u.replace(/[\r\n]+$/,""),!u)return i;if(u=z.windowsPath(u),o.isAbsolute(u))return o.normalize(u);return o.resolve(i,u)},M=yield*Wr.Scope,H=r.fn("Project.fromDirectory")(function*(i){Pr.info("fromDirectory",{directory:i});let u=yield*r.gen(function*(){if(nn.QITQODE_DISABLE_GIT)return{id:V.global,worktree:i,sandbox:i,vcs:p};let X=(yield*n.up({targets:[".git"],start:i}).pipe(r.orDie))[0];if(!X)return{id:V.global,worktree:"/",sandbox:"/",vcs:p};let en=o.dirname(X),sn=process.env.HOME??process.env.USERPROFILE??ar.homedir();if(en===sn||$n.parse(en).root===en)return Pr.warn("ignoring .git at home or filesystem root, snapshots disabled",{dotgit:X}),{id:V.global,worktree:i,sandbox:i,vcs:p};let c=en,zn=yield*r.sync(()=>Mo("git")),An;if(!zn)return{id:An??V.global,worktree:c,sandbox:c,vcs:p};let kn=yield*g(["rev-parse","--git-common-dir"],{cwd:c});if(kn.code!==0)return{id:An??V.global,worktree:c,sandbox:c,vcs:p};let Jn=(()=>{let Ln=A(c,kn.text.trim());return Ln===c?c:o.dirname(Ln)})();if(An==null)yield*r.promise(()=>me(c)),An=yield*r.promise(()=>Er(c));let qn=yield*g(["rev-parse","--show-toplevel"],{cwd:c});if(qn.code!==0)return{id:An,worktree:c,sandbox:c,vcs:p};return c=A(c,qn.text.trim()),{id:An,sandbox:c,worktree:Jn,vcs:"git"}}),$=yield*e((E)=>E.select().from(G).where(U(G.id,u.id)).get()),B=$?pn($):{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(B).pipe(r.ignore,r.forkIn(M));let d={...B,worktree:u.worktree,vcs:u.vcs,time:{...B.time,updated:Date.now()}};if(u.sandbox!==d.worktree&&!d.sandboxes.includes(u.sandbox))d.sandboxes.push(u.sandbox);if(d.sandboxes=yield*r.forEach(d.sandboxes,(E)=>n.exists(E).pipe(r.orDie,r.map((X)=>X?E:void 0)),{concurrency:16}).pipe(r.map((E)=>E.filter((X)=>X!==void 0))),yield*e((E)=>E.insert(G).values({id:d.id,worktree:d.worktree,vcs:d.vcs??null,name:d.name,icon_url:d.icon?.url,icon_color:d.icon?.color,time_created:d.time.created,time_updated:d.time.updated,time_initialized:d.time.initialized,sandboxes:d.sandboxes,commands:d.commands}).onConflictDoUpdate({target:G.id,set:{worktree:d.worktree,vcs:d.vcs??null,name:d.name,icon_url:d.icon?.url,icon_color:d.icon?.color,time_updated:d.time.updated,time_initialized:d.time.initialized,sandboxes:d.sandboxes,commands:d.commands}}).run()),u.id!==V.global)yield*e((E)=>E.update(ln).set({project_id:u.id}).where(Rn(U(ln.project_id,V.global),U(ln.directory,u.worktree))).run());return yield*T(d),{project:d,sandbox:u.sandbox}}),C=r.fn("Project.discover")(function*(i){if(i.vcs!=="git")return;if(i.icon?.override)return;if(i.icon?.url)return;let $=(yield*n.glob("**/favicon.{ico,png,svg,jpg,jpeg,webp}",{cwd:i.worktree,absolute:!0,include:"file"}).pipe(r.orDie)).sort((sn,c)=>sn.length-c.length)[0];if(!$)return;let B=yield*n.stat($).pipe(r.orDie);if(Number(B.size)>ue)return;let d=yield*n.readFile($).pipe(r.orDie),E=Buffer.from(d).toString("base64"),en=`data:${z.mimeType($)};base64,${E}`;yield*O({projectID:i.id,icon:{url:en}})}),J=r.fn("Project.list")(function*(){return yield*e((i)=>i.select().from(G).all().map(pn))}),R=r.fn("Project.get")(function*(i){let u=yield*e(($)=>$.select().from(G).where(U(G.id,i)).get());return u?pn(u):void 0}),O=r.fn("Project.update")(function*(i){let u=yield*e((B)=>B.update(G).set({name:i.name,icon_url:i.icon?.url,icon_color:i.icon?.color,commands:i.commands,time_updated:Date.now()}).where(U(G.id,i.projectID)).returning().get());if(!u)throw Error(`Project not found: ${i.projectID}`);let $=pn(u);return yield*T($),$}),Q=r.fn("Project.initGit")(function*(i){if(i.project.vcs==="git")return i.project;if(!(yield*r.sync(()=>Mo("git"))))throw Error("Git is not installed");let u=yield*g(["init","--quiet"],{cwd:i.directory});if(u.code!==0)throw Error(u.stderr.trim()||u.text.trim()||"Failed to initialize git repository");let{project:$}=yield*H(i.directory);return $}),I=r.fn("Project.setInitialized")(function*(i){yield*e((u)=>u.update(G).set({time_initialized:Date.now()}).where(U(G.id,i)).run())}),f=r.fn("Project.sandboxes")(function*(i){let u=yield*e((B)=>B.select().from(G).where(U(G.id,i)).get());if(!u)return[];let $=pn(u);return yield*r.forEach($.sandboxes,(B)=>n.isDir(B).pipe(r.orDie,r.map((d)=>d?B:void 0)),{concurrency:16}).pipe(r.map((B)=>B.filter((d)=>d!==void 0)))}),s=r.fnUntraced(function*(i,u){let $=yield*e((B)=>B.update(G).set({sandboxes:u,time_updated:Date.now()}).where(U(G.id,i)).returning().get());if(!$)throw Error(`Project not found: ${i}`);yield*T(pn($))}),m=r.fn("Project.addSandbox")(function*(i,u){let $=yield*e((d)=>d.select().from(G).where(U(G.id,i)).get());if(!$)throw Error(`Project not found: ${i}`);let B=[...$.sandboxes];if(!B.includes(u))B.push(u);yield*s(i,B)}),y=r.fn("Project.removeSandbox")(function*(i,u){let $=yield*e((d)=>d.select().from(G).where(U(G.id,i)).get());if(!$)throw Error(`Project not found: ${i}`);let B=$.sandboxes.filter((d)=>d!==u);yield*s(i,B)});return Sn.of({fromDirectory:H,discover:C,list:J,get:R,update:O,initGit:Q,setInitialized:I,sandboxes:f,addSandbox:m,removeSandbox:y})})),Co=wr.pipe(h.provide(bn),h.provide(z.defaultLayer),h.provide(Zr.layer));function fe(){return Bn.use((n)=>n.select().from(G).all().map((o)=>pn(o)))}function ge(n){let o=Bn.use((t)=>t.select().from(G).where(U(G.id,n)).get());if(!o)return;return pn(o)}function se(n){Bn.use((o)=>o.update(G).set({time_initialized:Date.now()}).where(U(G.id,n)).run())}import{parse as pe}from"path";var rn=fn.create("instance");hr(()=>rn.use());var tn=new Map,_e=nt(Sn,Co),Ne=new Set(["/etc","/proc","/sys","/dev","/boot","/root","/var","/private/etc","/private/var"]);function Te(n){if(n===pe(n).root)return"filesystem root is not a valid project directory";for(let o of Ne)if(n===o||z.contains(o,n))return"target is a protected system directory";return null}function Ae(n){let o=Te(n);if(o)throw Error("Access denied: "+o)}var En={all:void 0};function jr(n){return Kn(async()=>{let o=n.project&&n.worktree?{directory:n.directory,worktree:n.worktree,project:n.project}:await _e.runPromise((t)=>t.fromDirectory(n.directory)).then(({project:t,sandbox:g})=>({directory:n.directory,worktree:g,project:t}));return await rn.provide(o,async()=>{await n.init?.()}),o})}function br(n,o){let t=o.catch((g)=>{if(tn.get(n)===t)tn.delete(n);throw g});return tn.set(n,t),t}var on={async provide(n){let o=z.resolve(n.directory);Ae(o);let t=tn.get(o);if(!t)a.Default.info("creating instance",{directory:o}),t=br(o,jr({directory:o,init:n.init}));let g=await t;return rn.provide(g,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 t=o??on;if(z.contains(t.directory,n))return!0;if(t.worktree==="/")return!1;return z.contains(t.worktree,n)},bind(n){let o=rn.use();return(...t)=>rn.provide(o,()=>n(...t))},restore(n,o){return rn.provide(n,o)},async reload(n){let o=z.resolve(n.directory);a.Default.info("reloading instance",{directory:o}),await So(o),tn.delete(o);let t=br(o,jr({...n,directory:o}));return cn.emit("event",{directory:o,project:n.project?.id,workspace:_n.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:o}}}),await t},async dispose(){let{directory:n,project:o}=on;a.Default.info("disposing instance",{directory:n}),await So(n),tn.delete(n),cn.emit("event",{directory:n,project:o.id,workspace:_n.workspaceID,payload:{type:"server.instance.disposed",properties:{directory:n}}})},async disposeAll(){if(En.all)return En.all;return En.all=Kn(async()=>{a.Default.info("disposing all instances");let n=[...tn.entries()];for(let[o,t]of n){if(tn.get(o)!==t)continue;let g=await t.catch((e)=>{a.Default.warn("instance dispose failed",{key:o,error:e});return});if(!g){if(tn.get(o)===t)tn.delete(o);continue}if(tn.get(o)!==t)continue;await rn.provide(g,async()=>{await on.dispose()})}}).finally(()=>{En.all=void 0}),En.all}};var ot="~qitqode/InstanceState",Oe=(n)=>{try{return on.bind(n)}catch(g){if(!(g instanceof fn.NotFound))throw g}let o=In.getCurrent(),t=o?Dn.getReferenceUnsafe(o.context,Pn):void 0;if(!t)return n;return(...g)=>on.restore(t,()=>n(...g))},Jo=r.gen(function*(){return(yield*Pn)??on.current}),$e=r.gen(function*(){return(yield*hn)??_n.workspaceID}),no=r.map(Jo,(n)=>n.directory),De=(n)=>r.gen(function*(){let o=yield*Gn.make({capacity:Number.POSITIVE_INFINITY,lookup:()=>r.gen(function*(){return yield*n(yield*Jo)})}),t=Hr((g)=>r.runPromise(Gn.invalidate(o,g).pipe(r.provide(rt))));return yield*r.addFinalizer(()=>r.sync(t)),{[ot]:ot,cache:o}}),Ho=(n)=>r.gen(function*(){return yield*Gn.get(n.cache,yield*no)}),ve=(n,o)=>r.map(Ho(n),o),Qe=(n,o)=>r.flatMap(Ho(n),o),Be=(n)=>r.gen(function*(){return yield*Gn.has(n.cache,yield*no)}),Ie=(n)=>r.gen(function*(){return yield*Gn.invalidate(n.cache,yield*no)});var et={};dn(et,{make:()=>Le});function tt(n,o,t){if(n&&o!==void 0)return _n.restore(o,()=>on.restore(n,t));if(n)return on.restore(n,t);if(o!==void 0)return _n.restore(o,t);return t()}function Le(){return r.gen(function*(){let n=yield*r.context(),t=(yield*Pn)??(()=>{try{return on.current}catch(p){if(!(p instanceof fn.NotFound))throw p}})(),g=(yield*hn)??_n.workspaceID,e=(p)=>it(p,{instance:t,workspace:g}),T=(p)=>e(p).pipe(r.provide(n));return{promise:(p)=>tt(t,g,()=>r.runPromise(T(p))),fork:(p)=>tt(t,g,()=>r.runFork(T(p)))}})}var mt={};dn(mt,{make:()=>Se,Cancelled:()=>Un});class Un extends _.TaggedErrorClass()("RunnerCancelled",{}){}var Se=(n,o)=>{let t=Nn.makeUnsafe({_tag:"Idle"}),g=o?.onIdle??r.void,e=o?.onBusy??r.void,T=o?.onInterrupt,p=0,A=()=>Nn.getUnsafe(t),M=()=>{return p+=1,p},H=(m,y)=>Zn.isFailure(y)&&Ro.hasInterruptsOnly(y.cause)?gn.fail(m,new Un).pipe(r.asVoid):gn.done(m,y).pipe(r.asVoid),C=()=>Nn.modify(t,(m)=>[m._tag==="Idle"?g:r.void,m]).pipe(r.flatten),J=(m,y,i)=>Nn.modify(t,(u)=>[r.gen(function*(){if(u._tag==="Running"&&u.run.id===m)yield*g;yield*H(y,i)}),u._tag==="Running"&&u.run.id===m?{_tag:"Idle"}:u]).pipe(r.flatten),R=(m,y)=>r.gen(function*(){let i=M(),u=yield*m.pipe(r.onExit(($)=>J(i,y,$)),r.forkIn(n));return{id:i,done:y,fiber:u}}),O=(m)=>Nn.modifyEffect(t,r.fnUntraced(function*(y){if(y._tag==="Shell"&&y.shell.id===m)return[g,{_tag:"Idle"}];if(y._tag==="ShellThenRun"&&y.shell.id===m){let i=yield*R(y.run.work,y.run.done);return[r.void,{_tag:"Running",run:i}]}return[r.void,y]})).pipe(r.flatten),Q=(m)=>In.interrupt(m.fiber),I=(m)=>Nn.modifyEffect(t,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[gn.await(y.run.done),y];case"Shell":{let i={id:M(),done:yield*gn.make(),work:m};return[gn.await(i.done),{_tag:"ShellThenRun",shell:y.shell,run:i}]}case"Idle":{let i=yield*gn.make(),u=yield*R(m,i);return[gn.await(i),{_tag:"Running",run:u}]}}})).pipe(r.flatten,r.catch((y)=>y instanceof Un?T??r.die(y):r.fail(y))),f=(m)=>Nn.modifyEffect(t,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 i=M(),u=yield*m.pipe(r.ensuring(O(i)),r.forkChild),$={id:i,fiber:u};return[r.gen(function*(){let B=yield*In.await(u);if(Zn.isSuccess(B))return B.value;if(Ro.hasInterruptsOnly(B.cause)&&T)return yield*T;return yield*r.failCause(B.cause)}),{_tag:"Shell",shell:$}]})).pipe(r.flatten),s=Nn.modify(t,(m)=>{switch(m._tag){case"Idle":return[r.void,m];case"Running":return[r.gen(function*(){yield*In.interrupt(m.run.fiber);let y=yield*In.await(m.run.fiber);yield*H(m.run.done,y),yield*gn.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*gn.fail(m.run.done,new Un).pipe(r.asVoid),yield*Q(m.shell),yield*C()}),{_tag:"Idle"}]}}).pipe(r.flatten);return{get state(){return A()},get busy(){return A()._tag!=="Idle"},ensureRunning:I,startShell:f,cancel:s}};import{Database as Ge}from"bun:sqlite";function yt(n){let o=new Ge(n,{create:!0});return ut({client:o})}var Me=ro.create("NotFoundError",j.object({message:j.string()})),lt=a.create({service:"db"});function gt(){if(["latest","beta","prod"].includes(co)||nn.QITQODE_DISABLE_CHANNEL_DB)return oo.join(On.Path.data,"qitqode.db");let n=co.replace(/[^a-zA-Z0-9._-]/g,"-");return oo.join(On.Path.data,`qitqode-${n}.db`)}var Ko=Kn(()=>{if(nn.QITQODE_DB){if(nn.QITQODE_DB===":memory:"||oo.isAbsolute(nn.QITQODE_DB))return nn.QITQODE_DB;return oo.join(On.Path.data,nn.QITQODE_DB)}return gt()}),Mn=ft(()=>{lt.info("opening database",{path:Ko});let n=yt(Ko);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(lt.info("applying migrations",{count:o.length,mode:"bundled"}),nn.QITQODE_SKIP_MIGRATIONS)for(let t of o)t.sql="select 1;";jo(n,o)}return n});function xe(){Mn().$client.close(),Mn.reset()}var Xn=fn.create("database");function Ce(n){try{return n(Xn.use().tx)}catch(o){if(o instanceof fn.NotFound){let t=[],g=Xn.provide({effects:t,tx:Mn()},()=>n(Mn()));for(let e of t)e();return g}throw o}}function Je(n){let o=Wn.bind(n);try{Xn.use().effects.push(o)}catch{o()}}function He(n,o){try{return n(Xn.use().tx)}catch(t){if(t instanceof fn.NotFound){let g=[],e=Wn.bind((p)=>Xn.provide({tx:p,effects:g},()=>n(p))),T=Mn().transaction(e,{behavior:o?.behavior});for(let p of g)p();return T}throw t}}var dt={};dn(dt,{layer:()=>At,defaultLayer:()=>Ve,Service:()=>io,NotFoundError:()=>Uo});import Z from"path";var xn={};dn(xn,{layer:()=>Nt,defaultLayer:()=>Ke,Service:()=>to,Git:()=>xn});var Re=["--no-optional-locks","-c","core.autocrlf=false","-c","core.fsmonitor=false","-c","core.longpaths=true","-c","core.symlinks=true","-c","core.quotepath=false"],Yn=(n)=>n.text().trim(),Eo=(n)=>n.split("\x00").filter(Boolean),ce=(n)=>({exitCode:1,text:()=>"",stdout:Buffer.alloc(0),stderr:Buffer.from(n instanceof Error?n.message:String(n))}),st=(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 to extends Dn.Service()("@qitqode/Git"){}var Nt=h.effect(to,r.gen(function*(){let n=yield*jn.ChildProcessSpawner,o=r.fn("Git.run")(function*(f,s){let m=pt.make("git",[...Re,...f],{cwd:s.cwd,env:s.env,extendEnv:!0,stdin:"ignore",stdout:"pipe",stderr:"pipe"}),y=yield*_t(n,m);return{exitCode:y.code,text:()=>y.text,stdout:Buffer.from(y.text),stderr:Buffer.from(y.stderr)}},r.scoped,r.catch((f)=>r.succeed(ce(f)))),t=r.fn("Git.text")(function*(f,s){return(yield*o(f,s)).text()}),g=r.fn("Git.lines")(function*(f,s){return(yield*t(f,s)).split(/\r?\n/).map((m)=>m.trim()).filter(Boolean)}),e=r.fnUntraced(function*(f){return yield*g(["for-each-ref","--format=%(refname:short)","refs/heads"],{cwd:f})}),T=r.fnUntraced(function*(f,s){let m=yield*o(["config","init.defaultBranch"],{cwd:f}),y=Yn(m);if(!y||!s.includes(y))return;return{name:y,ref:y}}),p=r.fnUntraced(function*(f){let s=yield*g(["remote"],{cwd:f});if(s.includes("origin"))return"origin";if(s.length===1)return s[0];if(s.includes("upstream"))return"upstream";return s[0]}),A=r.fn("Git.branch")(function*(f){let s=yield*o(["symbolic-ref","--quiet","--short","HEAD"],{cwd:f});if(s.exitCode!==0)return;return Yn(s)||void 0}),M=r.fn("Git.prefix")(function*(f){let s=yield*o(["rev-parse","--show-prefix"],{cwd:f});if(s.exitCode!==0)return"";return Yn(s)}),H=r.fn("Git.defaultBranch")(function*(f){let s=yield*p(f);if(s){let i=yield*o(["symbolic-ref",`refs/remotes/${s}/HEAD`],{cwd:f});if(i.exitCode===0){let u=Yn(i).replace(/^refs\/remotes\//,""),$=u.startsWith(`${s}/`)?u.slice(`${s}/`.length):"";if($)return{name:$,ref:u}}}let m=yield*e(f),y=yield*T(f,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*(f){return(yield*o(["rev-parse","--verify","HEAD"],{cwd:f})).exitCode===0}),J=r.fn("Git.mergeBase")(function*(f,s,m="HEAD"){let y=yield*o(["merge-base",s,m],{cwd:f});if(y.exitCode!==0)return;return Yn(y)||void 0}),R=r.fn("Git.show")(function*(f,s,m,y=""){let i=y?`${y}${m}`:m,u=yield*o(["show",`${s}:${i}`],{cwd:f});if(u.exitCode!==0)return"";if(u.stdout.includes(0))return"";return u.text()}),O=r.fn("Git.status")(function*(f){return Eo(yield*t(["status","--porcelain=v1","--untracked-files=all","--no-renames","-z","--","."],{cwd:f})).flatMap((s)=>{let m=s.slice(3);if(!m)return[];let y=s.slice(0,2);return[{file:m,code:y,status:st(y)}]})}),Q=r.fn("Git.diff")(function*(f,s){let m=Eo(yield*t(["diff","--no-ext-diff","--no-renames","--name-status","-z",s,"--","."],{cwd:f}));return m.flatMap((y,i)=>{if(i%2!==0)return[];let u=m[i+1];if(!y||!u)return[];return[{file:u,code:y,status:st(y)}]})}),I=r.fn("Git.stats")(function*(f,s){return Eo(yield*t(["diff","--no-ext-diff","--no-renames","--numstat","-z",s,"--","."],{cwd:f})).flatMap((m)=>{let y=m.indexOf("\t"),i=m.indexOf("\t",y+1);if(y===-1||i===-1)return[];let u=m.slice(i+1);if(!u)return[];let $=m.slice(0,y),B=m.slice(y+1,i),d=$==="-"?0:Number.parseInt($||"0",10),E=B==="-"?0:Number.parseInt(B||"0",10);return[{file:u,additions:Number.isFinite(d)?d:0,deletions:Number.isFinite(E)?E:0}]})});return to.of({run:o,branch:A,prefix:M,defaultBranch:H,hasHead:C,mergeBase:J,show:R,status:O,diff:Q,stats:I})})),Ke=Nt.pipe(h.provide(bn));var Tn=a.create({service:"storage"}),Uo=ro.create("NotFoundError",j.object({message:j.string()})),Ee=_.Struct({path:_.optional(_.Struct({root:_.optional(_.String)}))}),Pe=_.Struct({id:_.String}),We=_.Struct({id:_.String}),Ue=_.Struct({additions:_.Number,deletions:_.Number}),Ze=_.Struct({id:_.String,projectID:_.String,summary:_.Struct({diffs:_.Array(Ue)})}),Xe=_.decodeUnknownOption(Ee),Ye=_.decodeUnknownOption(Pe),ae=_.decodeUnknownOption(We),ze=_.decodeUnknownOption(Ze);class io extends Dn.Service()("@qitqode/Storage"){}function ke(n,o){return Z.join(n,...o)+".json"}function Po(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 qe(n){let o=Number.parseInt(n,10);return Number.isNaN(o)?0:o}var Tt=[r.fn("Storage.migration.1")(function*(n,o,t){let g=Z.resolve(n,"../project");if(!(yield*o.isDir(g)))return;let e=yield*o.glob("*",{cwd:g,include:"all"});for(let T of e){let p=Z.join(g,T);if(!(yield*o.isDir(p)))continue;Tn.info(`migrating project ${T}`);let A=T,M="/";if(A!=="global"){for(let J of yield*o.glob("storage/session/message/*/*.json",{cwd:p,absolute:!0})){let R=Xe(yield*o.readJson(J),{onExcessProperty:"preserve"}),O=an.isSome(R)?R.value.path?.root:void 0;if(!O)continue;M=O;break}if(!M)continue;if(!(yield*o.isDir(M)))continue;let H=yield*t.run(["rev-list","--max-parents=0","--all"],{cwd:M}),[C]=H.text().split(`
5
5
  `).filter(Boolean).map((J)=>J.trim()).toSorted();if(!C)continue;A=C,yield*o.writeWithDirs(Z.join(n,"project",A+".json"),JSON.stringify({id:C,vcs:"git",worktree:M,time:{created:Date.now(),initialized:Date.now()}},null,2)),Tn.info(`migrating sessions for project ${A}`);for(let J of yield*o.glob("storage/session/info/*.json",{cwd:p,absolute:!0})){let R=Z.join(n,"session",A,Z.basename(J));Tn.info("copying",{sessionFile:J,dest:R});let O=yield*o.readJson(J),Q=Ye(O,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(R,JSON.stringify(O,null,2)),an.isNone(Q))continue;Tn.info(`migrating messages for session ${Q.value.id}`);for(let I of yield*o.glob(`storage/session/message/${Q.value.id}/*.json`,{cwd:p,absolute:!0})){let f=Z.join(n,"message",Q.value.id,Z.basename(I));Tn.info("copying",{msgFile:I,dest:f});let s=yield*o.readJson(I),m=ae(s,{onExcessProperty:"preserve"});if(yield*o.writeWithDirs(f,JSON.stringify(s,null,2)),an.isNone(m))continue;Tn.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:p,absolute:!0})){let i=Z.join(n,"part",m.value.id,Z.basename(y)),u=yield*o.readJson(y);Tn.info("copying",{partFile:y,dest:i}),yield*o.writeWithDirs(i,JSON.stringify(u,null,2))}}}}}}),r.fn("Storage.migration.2")(function*(n,o){for(let t of yield*o.glob("session/*/*.json",{cwd:n,absolute:!0})){let g=yield*o.readJson(t),e=ze(g,{onExcessProperty:"preserve"});if(an.isNone(e))continue;let T=e.value.summary.diffs;yield*o.writeWithDirs(Z.join(n,"session_diff",e.value.id+".json"),JSON.stringify(T,null,2)),yield*o.writeWithDirs(Z.join(n,"session",e.value.projectID,e.value.id+".json"),JSON.stringify({...g,summary:{additions:T.reduce((p,A)=>p+A.additions,0),deletions:T.reduce((p,A)=>p+A.deletions,0)}},null,2))}})],At=h.effect(io,r.gen(function*(){let n=yield*z.Service,o=yield*xn.Service,t=yield*Wo.make({lookup:()=>Cn.make(),idleTimeToLive:0}),g=yield*r.cached(r.gen(function*(){let O=Z.join(On.Path.data,"storage"),Q=Z.join(O,"migration"),I=yield*n.readFileString(Q).pipe(r.map(qe),r.catchIf(Po,()=>r.succeed(0)),r.orElseSucceed(()=>0));for(let f=I;f<Tt.length;f++){Tn.info("running migration",{index:f});let s=Tt[f],m=yield*r.exit(s(O,n,o));if(Zn.isFailure(m)){Tn.error("failed to run migration",{index:f,cause:m.cause});break}yield*n.writeWithDirs(Q,String(f+1))}return{dir:O}})),e=(O)=>r.fail(new Uo({message:`Resource not found: ${O}`})),T=(O,Q)=>Q.pipe(r.catchIf(Po,()=>e(O))),p=r.fnUntraced(function*(O,Q){yield*n.writeWithDirs(O,JSON.stringify(Q,null,2))}),A=(O,Q)=>r.scoped(r.gen(function*(){let I=ke((yield*g).dir,O);return yield*Q(I,yield*Wo.get(t,I))})),M=r.fn("Storage.remove")(function*(O){yield*A(O,(Q,I)=>Cn.withWriteLock(I,n.remove(Q).pipe(r.catchIf(Po,()=>r.void))))}),H=(O)=>r.gen(function*(){return yield*A(O,(I,f)=>Cn.withReadLock(f,T(I,n.readJson(I))))}),C=(O,Q)=>r.gen(function*(){return yield*A(O,(f,s)=>Cn.withWriteLock(s,r.gen(function*(){let m=yield*T(f,n.readJson(f));return Q(m),yield*p(f,m),m})))}),J=(O,Q)=>r.gen(function*(){yield*A(O,(I,f)=>Cn.withWriteLock(f,p(I,Q)))}),R=r.fn("Storage.list")(function*(O){let Q=(yield*g).dir,I=Z.join(Q,...O);return(yield*n.glob("**/*",{cwd:I,include:"file"}).pipe(r.catch(()=>r.succeed([])))).map((s)=>[...O,...s.slice(0,-5).split(Z.sep)]).toSorted((s,m)=>s.join("/").localeCompare(m.join("/")))});return io.of({remove:M,read:H,update:C,write:J,list:R})})),Ve=At.pipe(h.provide(z.defaultLayer),h.provide(xn.defaultLayer));export{cn as Ql,Hr as Rl,Kn as Sl,mn as Tl,G as Ul,ln as Vl,eo as Wl,Xo as Xl,Yo as Yl,ao as Zl,zo as _l,qo as $l,lo as am,Bn as bm,xn as cm,Uo as dm,dt as em,V as fm,Go as gm,Er as hm,se as im,Fr as jm,Te as km,on as lm,Wn as mm,Le as nm,et as om,mt as pm};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Wf as a,Xf as b}from"./chunk-5v0xjs3x.js";import"./chunk-m5m448mg.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{a as start,b as Heap};
2
+ import{Wf as a,Xf as b}from"./chunk-y6123zvq.js";import"./chunk-xj765svc.js";import"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-7xm75w1e.js";export{a as start,b as Heap};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Co as J}from"./chunk-2hc5z7b5.js";import{et as H,ft as I,gt as N,qt as Q}from"./chunk-tqj69nh6.js";import{FO as L}from"./chunk-7xm75w1e.js";import{platform as R,release as U}from"os";import{tmpdir as V}from"os";import X from"path";import Y from"fs/promises";var Z=J(async()=>{let{which:D}=await import("./chunk-50tb3g5x.js");return D}),T=J(async()=>{let{default:D}=await import("./chunk-yp8wyzzm.js");return D});function _(D){if(!process.stdout.isTTY)return;let A=`\x1B]52;c;${Buffer.from(D).toString("base64")}\x07`,E=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${A}\x1B\\`:A;process.stdout.write(E)}async function $(){let D=R();if(D==="darwin"){let k=X.join(V(),"qitqode-clipboard.png");try{return await I(["osascript","-e",'set imageData to the clipboard as "PNGf"',"-e",`set fileRef to open for access POSIX file "${k}" with write permission`,"-e","set eof fileRef to 0","-e","write imageData to fileRef","-e","close access fileRef"],{nothrow:!0}),{data:(await Q(k)).toString("base64"),mime:"image/png"}}catch{}finally{await Y.rm(k,{force:!0}).catch(()=>{})}}if(D==="win32"||U().includes("WSL")){let E=await N(["powershell.exe","-NonInteractive","-NoProfile","-command","Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"],{nothrow:!0});if(E.text){let K=Buffer.from(E.text.trim(),"base64");if(K.length>0)return{data:K.toString("base64"),mime:"image/png"}}}if(D==="linux"){let k=await I(["wl-paste","-t","image/png"],{nothrow:!0});if(k.stdout.byteLength>0)return{data:Buffer.from(k.stdout).toString("base64"),mime:"image/png"};let E=await I(["xclip","-selection","clipboard","-t","image/png","-o"],{nothrow:!0});if(E.stdout.byteLength>0)return{data:Buffer.from(E.stdout).toString("base64"),mime:"image/png"}}let A=await(await T()).read().catch(()=>{});if(A)return{data:A,mime:"text/plain"}}var j=J(async()=>{let D=R(),G=await Z();if(D==="darwin"&&G("osascript"))return console.log("clipboard: using osascript"),async(A)=>{let k=A.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");await I(["osascript","-e",`set the clipboard to "${k}"`],{nothrow:!0})};if(D==="linux"){if(process.env.WAYLAND_DISPLAY&&G("wl-copy"))return console.log("clipboard: using wl-copy"),async(A)=>{let k=H(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xclip"))return console.log("clipboard: using xclip"),async(A)=>{let k=H(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xsel"))return console.log("clipboard: using xsel"),async(A)=>{let k=H(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})}}if(D==="win32")return console.log("clipboard: using powershell"),async(A)=>{let k=H(["powershell.exe","-NonInteractive","-NoProfile","-Command","[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};return console.log("clipboard: no native support"),async(A)=>{await(await T()).write(A).catch(()=>{})}});async function v(D){_(D),await(await j())(D)}
2
+ import{Co as J}from"./chunk-2hc5z7b5.js";import{et as H,ft as I,gt as N,qt as Q}from"./chunk-tqj69nh6.js";import{FO as L}from"./chunk-7xm75w1e.js";import{platform as R,release as U}from"os";import{tmpdir as V}from"os";import X from"path";import Y from"fs/promises";var Z=J(async()=>{let{which:D}=await import("./chunk-r8m7rtfc.js");return D}),T=J(async()=>{let{default:D}=await import("./chunk-yp8wyzzm.js");return D});function _(D){if(!process.stdout.isTTY)return;let A=`\x1B]52;c;${Buffer.from(D).toString("base64")}\x07`,E=process.env.TMUX||process.env.STY?`\x1BPtmux;\x1B${A}\x1B\\`:A;process.stdout.write(E)}async function $(){let D=R();if(D==="darwin"){let k=X.join(V(),"qitqode-clipboard.png");try{return await I(["osascript","-e",'set imageData to the clipboard as "PNGf"',"-e",`set fileRef to open for access POSIX file "${k}" with write permission`,"-e","set eof fileRef to 0","-e","write imageData to fileRef","-e","close access fileRef"],{nothrow:!0}),{data:(await Q(k)).toString("base64"),mime:"image/png"}}catch{}finally{await Y.rm(k,{force:!0}).catch(()=>{})}}if(D==="win32"||U().includes("WSL")){let E=await N(["powershell.exe","-NonInteractive","-NoProfile","-command","Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"],{nothrow:!0});if(E.text){let K=Buffer.from(E.text.trim(),"base64");if(K.length>0)return{data:K.toString("base64"),mime:"image/png"}}}if(D==="linux"){let k=await I(["wl-paste","-t","image/png"],{nothrow:!0});if(k.stdout.byteLength>0)return{data:Buffer.from(k.stdout).toString("base64"),mime:"image/png"};let E=await I(["xclip","-selection","clipboard","-t","image/png","-o"],{nothrow:!0});if(E.stdout.byteLength>0)return{data:Buffer.from(E.stdout).toString("base64"),mime:"image/png"}}let A=await(await T()).read().catch(()=>{});if(A)return{data:A,mime:"text/plain"}}var j=J(async()=>{let D=R(),G=await Z();if(D==="darwin"&&G("osascript"))return console.log("clipboard: using osascript"),async(A)=>{let k=A.replace(/\\/g,"\\\\").replace(/"/g,"\\\"");await I(["osascript","-e",`set the clipboard to "${k}"`],{nothrow:!0})};if(D==="linux"){if(process.env.WAYLAND_DISPLAY&&G("wl-copy"))return console.log("clipboard: using wl-copy"),async(A)=>{let k=H(["wl-copy"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xclip"))return console.log("clipboard: using xclip"),async(A)=>{let k=H(["xclip","-selection","clipboard"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};if(G("xsel"))return console.log("clipboard: using xsel"),async(A)=>{let k=H(["xsel","--clipboard","--input"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})}}if(D==="win32")return console.log("clipboard: using powershell"),async(A)=>{let k=H(["powershell.exe","-NonInteractive","-NoProfile","-Command","[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())"],{stdin:"pipe",stdout:"ignore",stderr:"ignore"});if(!k.stdin)return;k.stdin.write(A),k.stdin.end(),await k.exited.catch(()=>{})};return console.log("clipboard: no native support"),async(A)=>{await(await T()).write(A).catch(()=>{})}});async function v(D){_(D),await(await j())(D)}
3
3
  export{$ as ud,v as vd};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Fd as m,Id as P,Jd as R,Kd as k,Ld as O,Nd as q,Od as $,Pd as I}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as h}from"./chunk-yajd975f.js";import{Vf as r}from"./chunk-rbk8seme.js";import{gh as L}from"./chunk-fq0x3esz.js";import{Uh as E}from"./chunk-44a82dg0.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{ck as N,rl as x}from"./chunk-04n2ycg5.js";import"./chunk-8ymffyep.js";import{lm as i}from"./chunk-mcg24gkb.js";import"./chunk-redjxn13.js";import"./chunk-bn0h9dny.js";import"./chunk-r4ndwym0.js";import"./chunk-3ytjm3az.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-r78czx4d.js";import"./chunk-2hc5z7b5.js";import"./chunk-d68fzyw7.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-c1bdzxbx.js";import"./chunk-ehhas0ew.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-gcw4rn10.js";import{Qs as j}from"./chunk-m5m448mg.js";import{st as C}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import{BO as F}from"./chunk-7xm75w1e.js";import u from"path";import U from"fs/promises";var T=F(N(),1);import{EOL as S}from"os";var c=["bash","read","write","edit","glob","grep","webfetch","actor","task"],B=h({command:"create",describe:"create a new agent",builder:(o)=>o.option("path",{type:"string",describe:"directory path to generate the agent file"}).option("description",{type:"string",describe:"what the agent should do"}).option("mode",{type:"string",describe:"agent mode",choices:["all","primary","subagent"]}).option("tools",{type:"string",describe:`comma-separated list of tools to enable (default: all). Available: "${c.join(", ")}"`}).option("model",{type:"string",alias:["m"],describe:"model to use in the format of provider/model"}),async handler(o){await i.provide({directory:process.cwd(),async fn(){let{path:l,description:t,mode:s,tools:p}=o,d=l&&t&&s&&p!==void 0;if(!d)r.empty(),R("Create agent");let D=i.project,g;if(l)g=u.join(l,"agent");else{let e="global";if(D.vcs==="git"){let n=await $({message:"Location",options:[{label:"Current project",value:"project",hint:i.worktree},{label:"Global",value:"global",hint:j.Path.config}]});if(m(n))throw new r.CancelledError;e=n}g=u.join(e==="global"?j.Path.config:u.join(i.worktree,".qitqode"),"agent")}let b;if(t)b=t;else{let e=await I({message:"Description",placeholder:"What should this agent do?",validate:(n)=>n&&n.length>0?void 0:"Required"});if(m(e))throw new r.CancelledError;b=e}let w=q();w.start("Generating agent configuration...");let G=o.model?x.parseModel(o.model):void 0,f=await L.runPromise(E.Service.use((e)=>e.generate({description:b,model:G}))).catch((e)=>{if(w.stop(`LLM failed to generate agent: ${e.message}`,1),d)process.exit(1);throw new r.CancelledError});w.stop(`Agent ${f.identifier} generated`);let y;if(p!==void 0)y=p?p.split(",").map((e)=>e.trim()):c;else{let e=await O({message:"Select tools to enable (Space to toggle)",options:c.map((n)=>({label:n,value:n})),initialValues:c});if(m(e))throw new r.CancelledError;y=e}let v;if(s)v=s;else{let e=await $({message:"Agent mode",options:[{label:"All",value:"all",hint:"Can function in both primary and subagent roles"},{label:"Primary",value:"primary",hint:"Acts as a primary/main agent"},{label:"Subagent",value:"subagent",hint:"Can be used as a subagent by other agents"}],initialValue:"all"});if(m(e))throw new r.CancelledError;v=e}let A={};for(let e of c)if(!y.includes(e))A[e]=!1;let M={description:f.whenToUse,mode:v};if(Object.keys(A).length>0)M.tools=A;let V=T.default.stringify(f.systemPrompt,M),a=u.join(g,`${f.identifier}.md`);if(await U.mkdir(g,{recursive:!0}),await C.exists(a)){if(d)console.error(`Error: Agent file already exists: ${a}`),process.exit(1);throw P.error(`Agent file already exists: ${a}`),new r.CancelledError}if(await C.write(a,V),d)console.log(a);else P.success(`Agent created: ${a}`),k("Done")}})}}),J=h({command:"list",describe:"list all available agents",async handler(){await i.provide({directory:process.cwd(),async fn(){let l=(await L.runPromise(E.Service.use((t)=>t.list()))).sort((t,s)=>{if(t.native!==s.native)return t.native?-1:1;return t.name.localeCompare(s.name)});for(let t of l)process.stdout.write(`${t.name} (${t.mode})`+S),process.stdout.write(` ${JSON.stringify(t.permission,null,2)}`+S)}})}}),ne=h({command:"agent",describe:"manage agents",builder:(o)=>o.command(B).command(J).demandCommand(),async handler(){}});export{ne as AgentCommand};
2
+ import{Fd as m,Id as P,Jd as R,Kd as k,Ld as O,Nd as q,Od as $,Pd as I}from"./chunk-p62gb4wj.js";import"./chunk-x4sp99g6.js";import{Rd as h}from"./chunk-yajd975f.js";import{Vf as r}from"./chunk-rbk8seme.js";import{gh as L}from"./chunk-caj1b9y7.js";import{Uh as E}from"./chunk-ygs5pzk7.js";import"./chunk-vxyy2dp3.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-5hw6xa49.js";import"./chunk-326p5b10.js";import{ck as N,rl as x}from"./chunk-257me4z3.js";import"./chunk-nkkch4h7.js";import{lm as i}from"./chunk-s3mnrhbx.js";import"./chunk-ezfy0b6q.js";import"./chunk-bn0h9dny.js";import"./chunk-hnvn2c25.js";import"./chunk-3nx7112w.js";import"./chunk-htz93dsd.js";import"./chunk-vcw00k0n.js";import"./chunk-we9cv8we.js";import"./chunk-2hc5z7b5.js";import"./chunk-9gazyynx.js";import"./chunk-4jtxtkj7.js";import"./chunk-ay8emwym.js";import"./chunk-2maqde7w.js";import"./chunk-kj20f048.js";import"./chunk-cqtkxwd8.js";import"./chunk-x9rbv6p6.js";import"./chunk-g5rabwre.js";import"./chunk-jbx3s7nw.js";import"./chunk-15hw2z9t.js";import"./chunk-48ge2ryx.js";import"./chunk-n9xns8by.js";import"./chunk-y9q0hb7b.js";import"./chunk-d9hbhkbq.js";import"./chunk-ad72gb5f.js";import"./chunk-d6ry9418.js";import"./chunk-0dt0bxz6.js";import"./chunk-10bjs581.js";import"./chunk-4cnwn1rh.js";import"./chunk-764fksh3.js";import{Qs as j}from"./chunk-xj765svc.js";import{st as C}from"./chunk-tqj69nh6.js";import"./chunk-ag8kz1e7.js";import"./chunk-5tray1fw.js";import"./chunk-c11d28qn.js";import"./chunk-mzs2pjyc.js";import"./chunk-gagtmjmp.js";import"./chunk-zs8kqdsf.js";import"./chunk-dxpj0cxh.js";import"./chunk-zw815d68.js";import{BO as F}from"./chunk-7xm75w1e.js";import u from"path";import U from"fs/promises";var T=F(N(),1);import{EOL as S}from"os";var c=["bash","read","write","edit","glob","grep","webfetch","actor","task"],B=h({command:"create",describe:"create a new agent",builder:(o)=>o.option("path",{type:"string",describe:"directory path to generate the agent file"}).option("description",{type:"string",describe:"what the agent should do"}).option("mode",{type:"string",describe:"agent mode",choices:["all","primary","subagent"]}).option("tools",{type:"string",describe:`comma-separated list of tools to enable (default: all). Available: "${c.join(", ")}"`}).option("model",{type:"string",alias:["m"],describe:"model to use in the format of provider/model"}),async handler(o){await i.provide({directory:process.cwd(),async fn(){let{path:l,description:t,mode:s,tools:p}=o,d=l&&t&&s&&p!==void 0;if(!d)r.empty(),R("Create agent");let D=i.project,g;if(l)g=u.join(l,"agent");else{let e="global";if(D.vcs==="git"){let n=await $({message:"Location",options:[{label:"Current project",value:"project",hint:i.worktree},{label:"Global",value:"global",hint:j.Path.config}]});if(m(n))throw new r.CancelledError;e=n}g=u.join(e==="global"?j.Path.config:u.join(i.worktree,".qitqode"),"agent")}let b;if(t)b=t;else{let e=await I({message:"Description",placeholder:"What should this agent do?",validate:(n)=>n&&n.length>0?void 0:"Required"});if(m(e))throw new r.CancelledError;b=e}let w=q();w.start("Generating agent configuration...");let G=o.model?x.parseModel(o.model):void 0,f=await L.runPromise(E.Service.use((e)=>e.generate({description:b,model:G}))).catch((e)=>{if(w.stop(`LLM failed to generate agent: ${e.message}`,1),d)process.exit(1);throw new r.CancelledError});w.stop(`Agent ${f.identifier} generated`);let y;if(p!==void 0)y=p?p.split(",").map((e)=>e.trim()):c;else{let e=await O({message:"Select tools to enable (Space to toggle)",options:c.map((n)=>({label:n,value:n})),initialValues:c});if(m(e))throw new r.CancelledError;y=e}let v;if(s)v=s;else{let e=await $({message:"Agent mode",options:[{label:"All",value:"all",hint:"Can function in both primary and subagent roles"},{label:"Primary",value:"primary",hint:"Acts as a primary/main agent"},{label:"Subagent",value:"subagent",hint:"Can be used as a subagent by other agents"}],initialValue:"all"});if(m(e))throw new r.CancelledError;v=e}let A={};for(let e of c)if(!y.includes(e))A[e]=!1;let M={description:f.whenToUse,mode:v};if(Object.keys(A).length>0)M.tools=A;let V=T.default.stringify(f.systemPrompt,M),a=u.join(g,`${f.identifier}.md`);if(await U.mkdir(g,{recursive:!0}),await C.exists(a)){if(d)console.error(`Error: Agent file already exists: ${a}`),process.exit(1);throw P.error(`Agent file already exists: ${a}`),new r.CancelledError}if(await C.write(a,V),d)console.log(a);else P.success(`Agent created: ${a}`),k("Done")}})}}),J=h({command:"list",describe:"list all available agents",async handler(){await i.provide({directory:process.cwd(),async fn(){let l=(await L.runPromise(E.Service.use((t)=>t.list()))).sort((t,s)=>{if(t.native!==s.native)return t.native?-1:1;return t.name.localeCompare(s.name)});for(let t of l)process.stdout.write(`${t.name} (${t.mode})`+S),process.stdout.write(` ${JSON.stringify(t.permission,null,2)}`+S)}})}}),ne=h({command:"agent",describe:"manage agents",builder:(o)=>o.command(B).command(J).demandCommand(),async handler(){}});export{ne as AgentCommand};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{No as qO,Oo as EO,Qo as HO}from"./chunk-ay8emwym.js";import{Ur as u}from"./chunk-gcw4rn10.js";import{Ns as X$,Qs as J$,Rs as R,_s as FO}from"./chunk-m5m448mg.js";import{tt as Y1}from"./chunk-ag8kz1e7.js";import{pH as c}from"./chunk-zs8kqdsf.js";import{BO as J1,DO as D1,FO as RO}from"./chunk-7xm75w1e.js";function x$({onRequest:O,onSseError:$,onSseEvent:Z,responseTransformer:J,responseValidator:Y,sseDefaultRetryDelay:D,sseMaxRetryAttempts:W,sseMaxRetryDelay:G,sseSleepFn:V,url:K,...z}){let L,M=V??((U)=>new Promise((j)=>setTimeout(j,U)));return{stream:async function*(){let U=D??3000,j=0,B=z.signal??new AbortController().signal;while(!0){if(B.aborted)break;j++;let l=z.headers instanceof Headers?z.headers:new Headers(z.headers);if(L!==void 0)l.set("Last-Event-ID",L);try{let E={redirect:"follow",...z,body:z.serializedBody,headers:l,signal:B},A=new Request(K,E);if(O)A=await O(K,E);let Q=await(z.fetch??globalThis.fetch)(A);if(!Q.ok)throw Error(`SSE failed: ${Q.status} ${Q.statusText}`);if(!Q.body)throw Error("No body in SSE response");let w=Q.body.pipeThrough(new TextDecoderStream).getReader(),T="",T$=()=>{try{w.cancel()}catch{}};B.addEventListener("abort",T$);try{while(!0){let{done:CO,value:vO}=await w.read();if(CO)break;T+=vO,T=T.replace(/\r\n?/g,`
2
+ import{No as qO,Oo as EO,Qo as HO}from"./chunk-ay8emwym.js";import{Ur as u}from"./chunk-764fksh3.js";import{Ns as X$,Qs as J$,Rs as R,_s as FO}from"./chunk-xj765svc.js";import{tt as Y1}from"./chunk-ag8kz1e7.js";import{pH as c}from"./chunk-zs8kqdsf.js";import{BO as J1,DO as D1,FO as RO}from"./chunk-7xm75w1e.js";function x$({onRequest:O,onSseError:$,onSseEvent:Z,responseTransformer:J,responseValidator:Y,sseDefaultRetryDelay:D,sseMaxRetryAttempts:W,sseMaxRetryDelay:G,sseSleepFn:V,url:K,...z}){let L,M=V??((U)=>new Promise((j)=>setTimeout(j,U)));return{stream:async function*(){let U=D??3000,j=0,B=z.signal??new AbortController().signal;while(!0){if(B.aborted)break;j++;let l=z.headers instanceof Headers?z.headers:new Headers(z.headers);if(L!==void 0)l.set("Last-Event-ID",L);try{let E={redirect:"follow",...z,body:z.serializedBody,headers:l,signal:B},A=new Request(K,E);if(O)A=await O(K,E);let Q=await(z.fetch??globalThis.fetch)(A);if(!Q.ok)throw Error(`SSE failed: ${Q.status} ${Q.statusText}`);if(!Q.body)throw Error("No body in SSE response");let w=Q.body.pipeThrough(new TextDecoderStream).getReader(),T="",T$=()=>{try{w.cancel()}catch{}};B.addEventListener("abort",T$);try{while(!0){let{done:CO,value:vO}=await w.read();if(CO)break;T+=vO,T=T.replace(/\r\n?/g,`
3
3
  `);let _$=T.split(`
4
4
 
5
5
  `);T=_$.pop()??"";for(let yO of _$){let cO=yO.split(`