@qitqode/qitqode-android-arm64 0.1.34 → 0.1.35

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-4sw6frjt.js → chunk-0442cmw2.js} +1 -1
  2. package/bundle/{chunk-3vnnxq40.js → chunk-085pvqr4.js} +1 -1
  3. package/bundle/{chunk-zm5dfk2b.js → chunk-11g2rpv8.js} +1 -1
  4. package/bundle/{chunk-xy5cjach.js → chunk-2kens6wh.js} +1 -1
  5. package/bundle/{chunk-mdts0641.js → chunk-31g86yn6.js} +1 -1
  6. package/bundle/{chunk-ny9hnvzy.js → chunk-3d91q2qd.js} +1 -1
  7. package/bundle/chunk-496ajawz.js +2 -0
  8. package/bundle/{chunk-g4nq9swr.js → chunk-4hzm14xt.js} +1 -1
  9. package/bundle/{chunk-4ntbxet5.js → chunk-54wh8b12.js} +1 -1
  10. package/bundle/{chunk-57najm15.js → chunk-57nvmhjq.js} +1 -1
  11. package/bundle/{chunk-28cm7m3t.js → chunk-5e4fxy99.js} +43 -43
  12. package/bundle/{chunk-wfegee41.js → chunk-5qr286w8.js} +1 -1
  13. package/bundle/{chunk-jm722vy1.js → chunk-606vpgc4.js} +1 -1
  14. package/bundle/{chunk-p15sv2dg.js → chunk-6a1skxcj.js} +1 -1
  15. package/bundle/{chunk-xkv3yta0.js → chunk-6a77w77q.js} +1 -1
  16. package/bundle/chunk-6cj7cn5x.js +2 -0
  17. package/bundle/{chunk-xhkd9yf3.js → chunk-6ged58yw.js} +1 -1
  18. package/bundle/{chunk-d80hk5x9.js → chunk-8c1ypgw5.js} +1 -1
  19. package/bundle/{chunk-qyzze0dv.js → chunk-8rt63jbm.js} +1 -1
  20. package/bundle/{chunk-w9nzsd3w.js → chunk-8vg4fmg2.js} +19 -19
  21. package/bundle/{chunk-kdvs4871.js → chunk-945ebhte.js} +1 -1
  22. package/bundle/{chunk-npv80mcx.js → chunk-9548cc0c.js} +1 -1
  23. package/bundle/{chunk-q5fygrnr.js → chunk-9ayxg9mq.js} +1 -1
  24. package/bundle/{chunk-gdb67zmn.js → chunk-9yrypq1r.js} +1 -1
  25. package/bundle/{chunk-za63b5mc.js → chunk-a1hzeejj.js} +1 -1
  26. package/bundle/{chunk-5vzrn6za.js → chunk-a949at1c.js} +1 -1
  27. package/bundle/{chunk-ppkqr9cn.js → chunk-aa8hymcv.js} +1 -1
  28. package/bundle/{chunk-6b196wjz.js → chunk-axdzm75h.js} +1 -1
  29. package/bundle/{chunk-fdadk5tw.js → chunk-b6cybdj3.js} +1 -1
  30. package/bundle/{chunk-q1czj6be.js → chunk-ca4r31we.js} +1 -1
  31. package/bundle/{chunk-bja8q0ke.js → chunk-cqj21rfj.js} +1 -1
  32. package/bundle/{chunk-shenqgrx.js → chunk-dhc6e1t7.js} +1 -1
  33. package/bundle/{chunk-cfw9pyt7.js → chunk-dk6rbqvp.js} +1 -1
  34. package/bundle/{chunk-qc3ce3vc.js → chunk-dk975etf.js} +1 -1
  35. package/bundle/{chunk-f9v5n0t6.js → chunk-dyt3n3fe.js} +1 -1
  36. package/bundle/{chunk-wmaz57f6.js → chunk-e74efvj2.js} +4 -4
  37. package/bundle/{chunk-qbx70v64.js → chunk-e8ws454m.js} +1 -1
  38. package/bundle/{chunk-wwgd4rzx.js → chunk-er38zew1.js} +1 -1
  39. package/bundle/{chunk-1hmq2fpt.js → chunk-eva3nqqb.js} +1 -1
  40. package/bundle/{chunk-5xq3h51b.js → chunk-exmw8jfa.js} +1 -1
  41. package/bundle/{chunk-8eje5baf.js → chunk-f3bnn9rf.js} +1 -1
  42. package/bundle/{chunk-v6tgn668.js → chunk-g18ax6yp.js} +1 -1
  43. package/bundle/{chunk-wet3bnwn.js → chunk-gadyp6mb.js} +1 -1
  44. package/bundle/{chunk-knpyt206.js → chunk-gckgaqqr.js} +1 -1
  45. package/bundle/{chunk-sz0gkx88.js → chunk-ge8315te.js} +1 -1
  46. package/bundle/{chunk-a8119c3a.js → chunk-gsyt2sv7.js} +1 -1
  47. package/bundle/{chunk-2fkfbdcy.js → chunk-hv6eccx1.js} +2 -2
  48. package/bundle/{chunk-9y97bzht.js → chunk-jyczz3yh.js} +2 -2
  49. package/bundle/{chunk-zph1c2q1.js → chunk-k8k8z6b7.js} +1 -1
  50. package/bundle/{chunk-d8dk05kd.js → chunk-mxvypy3s.js} +1 -1
  51. package/bundle/chunk-n5ypgxrn.js +28 -0
  52. package/bundle/{chunk-696z96a6.js → chunk-n9xw9kqc.js} +1 -1
  53. package/bundle/{chunk-8d5k45yj.js → chunk-nc4wbc89.js} +1 -1
  54. package/bundle/{chunk-6v9nbb4c.js → chunk-ngk67rt3.js} +1 -1
  55. package/bundle/{chunk-vkqzmzpw.js → chunk-nj2bbtmx.js} +1 -1
  56. package/bundle/{chunk-vkq0faj8.js → chunk-nr1g57b2.js} +1 -1
  57. package/bundle/{chunk-b34t8v7x.js → chunk-p0ahbpxv.js} +1 -1
  58. package/bundle/{chunk-pe98rznj.js → chunk-p7y8z5rd.js} +1 -1
  59. package/bundle/{chunk-b8hmj4jq.js → chunk-pt26gerr.js} +1 -1
  60. package/bundle/{chunk-s2vasbwj.js → chunk-qw980y8h.js} +1 -1
  61. package/bundle/{chunk-q6wm9yt0.js → chunk-rcn0dhbj.js} +1 -1
  62. package/bundle/{chunk-j0jdkqf5.js → chunk-s5nde2kd.js} +1 -1
  63. package/bundle/{chunk-j8q252w3.js → chunk-sjw56r2n.js} +1 -1
  64. package/bundle/{chunk-ya8g02hv.js → chunk-srpe3v8e.js} +1 -1
  65. package/bundle/{chunk-hg0etbkx.js → chunk-st5jaszz.js} +1 -1
  66. package/bundle/{chunk-h2m8fdqm.js → chunk-t2vm08v6.js} +1 -1
  67. package/bundle/{chunk-rjy5mqwz.js → chunk-t3eymzg1.js} +1 -1
  68. package/bundle/{chunk-0csy9x1n.js → chunk-tbgczapt.js} +1 -1
  69. package/bundle/{chunk-x9s90xd1.js → chunk-tns5x4w0.js} +1 -1
  70. package/bundle/{chunk-zpf31kxb.js → chunk-txbwmwxj.js} +1 -1
  71. package/bundle/{chunk-esp6jv63.js → chunk-vysa9hp4.js} +1 -1
  72. package/bundle/{chunk-9msnx26q.js → chunk-w1n4rf6n.js} +1 -1
  73. package/bundle/{chunk-w5kg2yz0.js → chunk-xvntsbb1.js} +1 -1
  74. package/bundle/{chunk-y370dqf3.js → chunk-yprmd5b7.js} +1 -1
  75. package/bundle/{chunk-ygjtwjnk.js → chunk-zddknkw7.js} +1 -1
  76. package/bundle/{chunk-7hh0654f.js → chunk-ze9e6nt3.js} +1 -1
  77. package/bundle/{chunk-7bwe0ayr.js → chunk-znzan00b.js} +1 -1
  78. package/bundle/{chunk-qek6a75r.js → chunk-zrp55k47.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-425mq6k8.js +0 -2
  83. package/bundle/chunk-tt8jke90.js +0 -2
  84. package/bundle/chunk-wbzs30fk.js +0 -28
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{a as ZB,b as $B}from"./chunk-5xq3h51b.js";import"./chunk-d80hk5x9.js";import"./chunk-1pg6pv0m.js";import{B as XB}from"./chunk-gsez13bg.js";import{C as BB,E as JB}from"./chunk-c8k32724.js";import"./chunk-zm5dfk2b.js";import{I as VB}from"./chunk-t9mz17gb.js";import{O as YB}from"./chunk-6p7yg5sr.js";import"./chunk-x66ycpfs.js";import"./chunk-03xppy47.js";import{Rd as e}from"./chunk-yajd975f.js";import{Of as n,Pf as D,Qf as w,Rf as i}from"./chunk-9msnx26q.js";import{Vf as H}from"./chunk-p9cnzxb8.js";import{Cg as s}from"./chunk-ya8g02hv.js";import{gh as U}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Xj as R,ok as o,rl as r}from"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import{km as O}from"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import{Mp as a,Pp as t}from"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import{qt as v}from"./chunk-vkqzmzpw.js";import{Ut as f,Vt as c,Wt as u,Yt as l,gu as g,ru as x}from"./chunk-x9s90xd1.js";import{Au as N,Ou as p,Qu as _}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import{OI as S}from"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import{cQ as I}from"./chunk-3k2b05fv.js";import E from"path";import{fileURLToPath as HB}from"url";import{writeHeapSnapshot as KB}from"v8";import MB,{EOL as M}from"os";var zB={free:"free",default:"default",fast:"fast",economy:"economical",power:"power",orchestrated:"orchestrated"},T="build";function h(B){if(B.agent)return B.agent;if(B.headless||B.fullauto)return T;return}function jB(B){for(let[V,X]of Object.entries(zB))if(B[V]){let Z=v[X];if(Z)return`${Z.providerID}/${Z.modelID}`}return}function GB(B){return async(X,Z)=>{let Y=new Request(X,Z),W=Y.body?await Y.text():void 0,$=await B.call("fetch",{url:Y.url,method:Y.method,headers:Object.fromEntries(Y.headers.entries()),body:W});return new Response($.body,{status:$.status,headers:$.headers})}}function QB(B){return{subscribe:async(V)=>{return B.on("global.event",(X)=>{V(X)})}}}async function bB(){if(typeof globalThis.QITQODE_WORKER_PATH<"u")return globalThis.QITQODE_WORKER_PATH;let B=new URL("./cli/cmd/tui/worker.js",import.meta.url);if(await p(HB(B)))return B;return new URL("./worker.ts",import.meta.url)}async function PB(B){let V=process.stdin.isTTY?void 0:await Bun.stdin.text();if(!B)return V;if(!V)return B;return V+`
3
- `+B}async function d(B){let V=a({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let W=await V.event.subscribe(),$=YB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),A=W.stream[Symbol.asyncIterator](),P=$.completion.then(()=>"DONE");(async()=>{try{while(!0){let z=await Promise.race([A.next(),P]);if(z==="DONE")break;let y=z;if(y.done)break;let j=y.value;$.onEvent(j);let K=j.properties;if(j.type==="message.part.updated"){let J=K?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let C=String(J.text??"").trim();if(C)process.stdout.write(C+M)}}if(j.type==="permission.asked"){if(!K||K.sessionID!==Y)continue;await V.permission.reply({requestID:String(K.id),reply:"once"})}if(j.type==="session.error"){if(!K||K.sessionID!==Y||!K.error)continue;let J=K.error,C=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(C)}}}finally{$.stop(),await A.return?.(void 0).catch(()=>{})}})().catch((z)=>{console.error(z),process.exit(1)});let q=B.model?r.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:q,parts:[{type:"text",text:B.prompt}]}),$.markStarted(),await $.completion}var nB=e({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>n(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(i).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(zB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=JB();try{BB();let X=XB(B);if(X){H.error(X),process.exitCode=1;return}let Z=jB(B)??B.model,Y=_(process.env.PWD??process.cwd()),W=B.project?_(E.isAbsolute(B.project)?B.project:E.join(Y,B.project)):_(process.cwd()),$=O(W);if($){if(B.project){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}let J=_(MB.homedir());if(O(J)){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}x.warn("unsafe start directory, falling back to home",{requested:W,home:J}),W=J}let A=await bB();try{process.chdir(W)}catch{H.error("Failed to change directory to "+W);return}let P=_(process.cwd()),k=l({[c]:"worker",[f]:u()}),q=new Worker(A,{env:k});q.onerror=(J)=>{x.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let z=g(q),y=()=>{z.call("reload",void 0).catch((J)=>{x.warn("worker reload failed",{error:N(J)})})};process.on("SIGUSR2",y);let j=!1,K=async()=>{if(j)return;j=!0,process.off("SIGUSR2",y),await o(z.call("shutdown",void 0),5000).catch((J)=>{x.warn("worker shutdown failed",{error:N(J)})}),q.terminate()};try{let J=import("./chunk-425mq6k8.js"),C=import("./chunk-qbx70v64.js").then(({TuiConfig:F})=>F.get()),L=await PB(B.prompt),WB=await C;if(B.headless&&D(w(B))){H.error("--headless cannot be combined with network-listener flags (--port, --hostname, --mdns)"),process.exitCode=1;return}let m=w(B),b=D(m)?{url:(await z.call("server",m)).url,fetch:void 0,events:void 0}:{url:"http://qitqode.internal",fetch:GB(z),events:QB(z)};if(setTimeout(()=>{z.call("checkUpgrade",{directory:P}).catch(()=>{})},1000).unref?.(),B.headless){if(!L){H.error("--headless requires a prompt: pass --prompt or pipe input via stdin"),process.exitCode=1;return}if(B.sso){try{let G=await s({tryOpen:!1,onCode:(Q)=>{if(process.stdout.write(M),process.stdout.write(" To sign in, open: "+Q.verificationUri+M),process.stdout.write(" and enter code: "+Q.userCode+M),Q.verificationUriComplete)process.stdout.write(M+" Or open this link directly:"+M+" "+Q.verificationUriComplete+M);process.stdout.write(M+" Waiting for approval... (ctrl+c to cancel)"+M)}});await U.runPromise(S.gen(function*(){yield*(yield*R.Service).set("forgewise",VB(G,{rotateRefreshToken:!0}))})),process.stdout.write(" Signed in as "+(G.name||G.email)+M)}catch(G){H.error("SSO sign-in failed: "+N(G)),process.exitCode=1;return}await d({url:b.url,fetch:b.fetch,prompt:L,model:Z,agent:h(B)??T,directory:P});return}let F=ZB(typeof B["api-key"]==="string"?String(B["api-key"]):"");if(F)await U.runPromise($B(F));else if(!await U.runPromise(S.gen(function*(){if(yield*S.promise(()=>t()))return!0;return!!(yield*(yield*R.Service).get("forgewise"))}))){H.error(`Not signed in. Use one of:
2
+ import{a as ZB,b as $B}from"./chunk-exmw8jfa.js";import"./chunk-8c1ypgw5.js";import"./chunk-1pg6pv0m.js";import{B as XB}from"./chunk-gsez13bg.js";import{C as BB,E as JB}from"./chunk-c8k32724.js";import"./chunk-11g2rpv8.js";import{I as VB}from"./chunk-t9mz17gb.js";import{O as YB}from"./chunk-6p7yg5sr.js";import"./chunk-x66ycpfs.js";import"./chunk-03xppy47.js";import{Rd as e}from"./chunk-yajd975f.js";import{Of as n,Pf as D,Qf as w,Rf as i}from"./chunk-w1n4rf6n.js";import{Vf as H}from"./chunk-p9cnzxb8.js";import{Cg as s}from"./chunk-srpe3v8e.js";import{gh as U}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Xj as R,ok as o,rl as r}from"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import{km as O}from"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import{Mp as a,Pp as t}from"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import{qt as v}from"./chunk-nj2bbtmx.js";import{Ut as f,Vt as c,Wt as u,Yt as l,gu as g,ru as x}from"./chunk-tns5x4w0.js";import{Au as N,Ou as p,Qu as _}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import{OI as S}from"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import{cQ as I}from"./chunk-3k2b05fv.js";import E from"path";import{fileURLToPath as HB}from"url";import{writeHeapSnapshot as KB}from"v8";import MB,{EOL as M}from"os";var zB={free:"free",default:"default",fast:"fast",economy:"economical",power:"power",orchestrated:"orchestrated"},T="build";function h(B){if(B.agent)return B.agent;if(B.headless||B.fullauto)return T;return}function jB(B){for(let[V,X]of Object.entries(zB))if(B[V]){let Z=v[X];if(Z)return`${Z.providerID}/${Z.modelID}`}return}function GB(B){return async(X,Z)=>{let Y=new Request(X,Z),W=Y.body?await Y.text():void 0,$=await B.call("fetch",{url:Y.url,method:Y.method,headers:Object.fromEntries(Y.headers.entries()),body:W});return new Response($.body,{status:$.status,headers:$.headers})}}function QB(B){return{subscribe:async(V)=>{return B.on("global.event",(X)=>{V(X)})}}}async function bB(){if(typeof globalThis.QITQODE_WORKER_PATH<"u")return globalThis.QITQODE_WORKER_PATH;let B=new URL("./cli/cmd/tui/worker.js",import.meta.url);if(await p(HB(B)))return B;return new URL("./worker.ts",import.meta.url)}async function PB(B){let V=process.stdin.isTTY?void 0:await Bun.stdin.text();if(!B)return V;if(!V)return B;return V+`
3
+ `+B}async function d(B){let V=a({baseUrl:B.url,fetch:B.fetch,directory:B.directory}),X=[{permission:"question",action:"deny",pattern:"*"},{permission:"plan_enter",action:"deny",pattern:"*"},{permission:"plan_exit",action:"deny",pattern:"*"}],Y=(await V.session.create({permission:X})).data?.id;if(!Y){H.error("headless: failed to create session");return}let W=await V.event.subscribe(),$=YB({sessionID:Y,query:async()=>{return(await V.session.status()).data?.[Y]}}),A=W.stream[Symbol.asyncIterator](),P=$.completion.then(()=>"DONE");(async()=>{try{while(!0){let z=await Promise.race([A.next(),P]);if(z==="DONE")break;let y=z;if(y.done)break;let j=y.value;$.onEvent(j);let K=j.properties;if(j.type==="message.part.updated"){let J=K?.part;if(!J||J.sessionID!==Y)continue;if(J.type==="text"&&J.time?.end){let C=String(J.text??"").trim();if(C)process.stdout.write(C+M)}}if(j.type==="permission.asked"){if(!K||K.sessionID!==Y)continue;await V.permission.reply({requestID:String(K.id),reply:"once"})}if(j.type==="session.error"){if(!K||K.sessionID!==Y||!K.error)continue;let J=K.error,C=J?.data!==null&&typeof J?.data==="object"&&"message"in J.data?String(J.data.message):String(J?.name??J);H.error(C)}}}finally{$.stop(),await A.return?.(void 0).catch(()=>{})}})().catch((z)=>{console.error(z),process.exit(1)});let q=B.model?r.parseModel(B.model):void 0;await V.session.prompt({sessionID:Y,agent:B.agent,model:q,parts:[{type:"text",text:B.prompt}]}),$.markStarted(),await $.completion}var nB=e({command:"$0 [project]",describe:"start qitqode tui",builder:(B)=>n(B).positional("project",{type:"string",describe:"path to start qitqode in"}).options(i).option("never-ask",{type:"boolean",describe:"start in never-ask mode \u2014 auto-decide without asking (permissions excluded), toggle at runtime with /never-ask",default:!1}).check((V)=>{if(V.dark&&V.light)throw Error("--dark and --light are mutually exclusive");if(V.sso&&!V.headless)throw Error("--sso requires --headless");if(V.sso&&V["api-key"]!==void 0)throw Error("--sso and --api-key are mutually exclusive");let X=Object.keys(zB).filter((Z)=>V[Z]);if(X.length>1)throw Error(`${X.map((Z)=>`--${Z}`).join(" and ")} are mutually exclusive \u2014 choose one tier flag`);if(X.length===1&&V.model)throw Error(`--${X[0]} and --model are mutually exclusive \u2014 use one or the other`);return!0}),handler:async(B)=>{if(B.monochrome)process.env.QITQODE_TUI_ACCESSIBLE="1",process.env.NO_COLOR="1";let V=JB();try{BB();let X=XB(B);if(X){H.error(X),process.exitCode=1;return}let Z=jB(B)??B.model,Y=_(process.env.PWD??process.cwd()),W=B.project?_(E.isAbsolute(B.project)?B.project:E.join(Y,B.project)):_(process.cwd()),$=O(W);if($){if(B.project){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}let J=_(MB.homedir());if(O(J)){H.error("Cannot start in "+W+": "+$),process.exitCode=1;return}x.warn("unsafe start directory, falling back to home",{requested:W,home:J}),W=J}let A=await bB();try{process.chdir(W)}catch{H.error("Failed to change directory to "+W);return}let P=_(process.cwd()),k=l({[c]:"worker",[f]:u()}),q=new Worker(A,{env:k});q.onerror=(J)=>{x.error("thread error",{message:J.message,filename:J.filename,lineno:J.lineno,colno:J.colno,error:J.error})};let z=g(q),y=()=>{z.call("reload",void 0).catch((J)=>{x.warn("worker reload failed",{error:N(J)})})};process.on("SIGUSR2",y);let j=!1,K=async()=>{if(j)return;j=!0,process.off("SIGUSR2",y),await o(z.call("shutdown",void 0),5000).catch((J)=>{x.warn("worker shutdown failed",{error:N(J)})}),q.terminate()};try{let J=import("./chunk-496ajawz.js"),C=import("./chunk-e8ws454m.js").then(({TuiConfig:F})=>F.get()),L=await PB(B.prompt),WB=await C;if(B.headless&&D(w(B))){H.error("--headless cannot be combined with network-listener flags (--port, --hostname, --mdns)"),process.exitCode=1;return}let m=w(B),b=D(m)?{url:(await z.call("server",m)).url,fetch:void 0,events:void 0}:{url:"http://qitqode.internal",fetch:GB(z),events:QB(z)};if(setTimeout(()=>{z.call("checkUpgrade",{directory:P}).catch(()=>{})},1000).unref?.(),B.headless){if(!L){H.error("--headless requires a prompt: pass --prompt or pipe input via stdin"),process.exitCode=1;return}if(B.sso){try{let G=await s({tryOpen:!1,onCode:(Q)=>{if(process.stdout.write(M),process.stdout.write(" To sign in, open: "+Q.verificationUri+M),process.stdout.write(" and enter code: "+Q.userCode+M),Q.verificationUriComplete)process.stdout.write(M+" Or open this link directly:"+M+" "+Q.verificationUriComplete+M);process.stdout.write(M+" Waiting for approval... (ctrl+c to cancel)"+M)}});await U.runPromise(S.gen(function*(){yield*(yield*R.Service).set("forgewise",VB(G,{rotateRefreshToken:!0}))})),process.stdout.write(" Signed in as "+(G.name||G.email)+M)}catch(G){H.error("SSO sign-in failed: "+N(G)),process.exitCode=1;return}await d({url:b.url,fetch:b.fetch,prompt:L,model:Z,agent:h(B)??T,directory:P});return}let F=ZB(typeof B["api-key"]==="string"?String(B["api-key"]):"");if(F)await U.runPromise($B(F));else if(!await U.runPromise(S.gen(function*(){if(yield*S.promise(()=>t()))return!0;return!!(yield*(yield*R.Service).get("forgewise"))}))){H.error(`Not signed in. Use one of:
4
4
  qode auth login (browser / device-code flow)
5
5
  qode auth login --api-key (paste a Qortex API key)
6
6
  --api-key <key> (inline for this run)
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{ru as c,uu as i}from"./chunk-x9s90xd1.js";import{Au as s}from"./chunk-e7v9trve.js";function f(u){let n=!1,o=(e,a)=>{if(n)return;n=!0,process.exitCode=1,c.error(e,{error:s(a),process_role:u});let l=setTimeout(()=>process.exit(1),1000);i().finally(()=>{clearTimeout(l),process.exit(1)})},t=(e)=>o("unhandled rejection",e),r=(e)=>o("uncaught exception",e);return process.on("unhandledRejection",t),process.on("uncaughtException",r),()=>{process.off("unhandledRejection",t),process.off("uncaughtException",r)}}
2
+ import{ru as c,uu as i}from"./chunk-tns5x4w0.js";import{Au as s}from"./chunk-e7v9trve.js";function f(u){let n=!1,o=(e,a)=>{if(n)return;n=!0,process.exitCode=1,c.error(e,{error:s(a),process_role:u});let l=setTimeout(()=>process.exit(1),1000);i().finally(()=>{clearTimeout(l),process.exit(1)})},t=(e)=>o("unhandled rejection",e),r=(e)=>o("uncaught exception",e);return process.on("unhandledRejection",t),process.on("uncaughtException",r),()=>{process.off("unhandledRejection",t),process.off("uncaughtException",r)}}
3
3
  export{f as ot};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ed as j}from"./chunk-ppkqr9cn.js";import{Rd as Q}from"./chunk-yajd975f.js";import{Vf as M}from"./chunk-p9cnzxb8.js";import{og as N}from"./chunk-0csy9x1n.js";import{gh as $}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as X,kk as J}from"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import{aq as _}from"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import{eu as Y,ou as Z}from"./chunk-x9s90xd1.js";import{Gu as E,Ru as V}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as L}from"os";import k from"path";function P(){let q=["-R","-S"];if(process.platform!=="win32")return["less",...q];let z=_("less");if(z){if(V.stat(z)?.size)return[z,...q]}if(Z.QITQODE_GIT_BASH_PATH){let G=k.join(Z.QITQODE_GIT_BASH_PATH,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}let B=_("git");if(B){let G=k.join(B,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}return["cmd","/c","more"]}var g=Q({command:"session",describe:"manage sessions",builder:(q)=>q.command(T).command(D).command(v).demandCommand(),async handler(){}}),v=Q({command:"import-claude",describe:"import Claude Code sessions (~/.claude/projects) into qitqode",builder:(q)=>q.option("force",{describe:"re-sync every session, ignoring the mtime cache",type:"boolean",default:!1}),handler:async(q)=>{let z=await N.run({force:q.force});M.println(`Claude import: scanned ${z.scanned}, imported ${z.imported}, resynced ${z.resynced}, skipped ${z.skipped}`+(z.errors.length?`, errors ${z.errors.length}`:""));for(let B of z.errors)M.error(B)}}),D=Q({command:"delete <sessionID>",describe:"delete a session",builder:(q)=>{return q.positional("sessionID",{describe:"session ID to delete",type:"string",demandOption:!0})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=J.make(q.sessionID);try{await $.runPromise(X.Service.use((B)=>B.get(z)))}catch{M.error(`Session not found: ${q.sessionID}`),process.exit(1)}await $.runPromise(X.Service.use((B)=>B.remove(z))),M.println(M.Style.TEXT_SUCCESS_BOLD+`Session ${q.sessionID} deleted`+M.Style.TEXT_NORMAL)})}}),T=Q({command:"list",describe:"list sessions",builder:(q)=>{return q.option("max-count",{alias:"n",describe:"limit to N most recent sessions",type:"number"}).option("format",{describe:"output format",type:"string",choices:["table","json"],default:"table"})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=[...X.list({roots:!0,limit:q.maxCount})];if(z.length===0)return;let B;if(q.format==="json")B=f(z);else B=b(z);if(process.stdout.isTTY&&!q.maxCount&&q.format==="table"){let H=E.spawn(P(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});if(!H.stdin){console.log(B);return}H.stdin.write(B),H.stdin.end(),await H.exited}else console.log(B)})}});function b(q){let z=[],B=Math.max(20,...q.map((K)=>K.id.length)),G=Math.max(25,...q.map((K)=>K.title.length)),H=`Session ID${" ".repeat(B-10)} Title${" ".repeat(G-5)} Updated`;z.push(H),z.push("\u2500".repeat(H.length));for(let K of q){let A=Y.truncate(K.title,G),R=Y.todayTimeOrDateTime(K.time.updated),w=`${K.id.padEnd(B)} ${A.padEnd(G)} ${R}`;z.push(w)}return z.join(L)}function f(q){let z=q.map((B)=>({id:B.id,title:B.title,updated:B.time.updated,created:B.time.created,projectId:B.projectID,directory:B.directory}));return JSON.stringify(z,null,2)}export{T as SessionListCommand,v as SessionImportClaudeCommand,D as SessionDeleteCommand,g as SessionCommand};
2
+ import{Ed as j}from"./chunk-aa8hymcv.js";import{Rd as Q}from"./chunk-yajd975f.js";import{Vf as M}from"./chunk-p9cnzxb8.js";import{og as N}from"./chunk-tbgczapt.js";import{gh as $}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as X,kk as J}from"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import{aq as _}from"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import{eu as Y,ou as Z}from"./chunk-tns5x4w0.js";import{Gu as E,Ru as V}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as L}from"os";import k from"path";function P(){let q=["-R","-S"];if(process.platform!=="win32")return["less",...q];let z=_("less");if(z){if(V.stat(z)?.size)return[z,...q]}if(Z.QITQODE_GIT_BASH_PATH){let G=k.join(Z.QITQODE_GIT_BASH_PATH,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}let B=_("git");if(B){let G=k.join(B,"..","..","usr","bin","less.exe");if(V.stat(G)?.size)return[G,...q]}return["cmd","/c","more"]}var g=Q({command:"session",describe:"manage sessions",builder:(q)=>q.command(T).command(D).command(v).demandCommand(),async handler(){}}),v=Q({command:"import-claude",describe:"import Claude Code sessions (~/.claude/projects) into qitqode",builder:(q)=>q.option("force",{describe:"re-sync every session, ignoring the mtime cache",type:"boolean",default:!1}),handler:async(q)=>{let z=await N.run({force:q.force});M.println(`Claude import: scanned ${z.scanned}, imported ${z.imported}, resynced ${z.resynced}, skipped ${z.skipped}`+(z.errors.length?`, errors ${z.errors.length}`:""));for(let B of z.errors)M.error(B)}}),D=Q({command:"delete <sessionID>",describe:"delete a session",builder:(q)=>{return q.positional("sessionID",{describe:"session ID to delete",type:"string",demandOption:!0})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=J.make(q.sessionID);try{await $.runPromise(X.Service.use((B)=>B.get(z)))}catch{M.error(`Session not found: ${q.sessionID}`),process.exit(1)}await $.runPromise(X.Service.use((B)=>B.remove(z))),M.println(M.Style.TEXT_SUCCESS_BOLD+`Session ${q.sessionID} deleted`+M.Style.TEXT_NORMAL)})}}),T=Q({command:"list",describe:"list sessions",builder:(q)=>{return q.option("max-count",{alias:"n",describe:"limit to N most recent sessions",type:"number"}).option("format",{describe:"output format",type:"string",choices:["table","json"],default:"table"})},handler:async(q)=>{await j(process.cwd(),async()=>{let z=[...X.list({roots:!0,limit:q.maxCount})];if(z.length===0)return;let B;if(q.format==="json")B=f(z);else B=b(z);if(process.stdout.isTTY&&!q.maxCount&&q.format==="table"){let H=E.spawn(P(),{stdin:"pipe",stdout:"inherit",stderr:"inherit"});if(!H.stdin){console.log(B);return}H.stdin.write(B),H.stdin.end(),await H.exited}else console.log(B)})}});function b(q){let z=[],B=Math.max(20,...q.map((K)=>K.id.length)),G=Math.max(25,...q.map((K)=>K.title.length)),H=`Session ID${" ".repeat(B-10)} Title${" ".repeat(G-5)} Updated`;z.push(H),z.push("\u2500".repeat(H.length));for(let K of q){let A=Y.truncate(K.title,G),R=Y.todayTimeOrDateTime(K.time.updated),w=`${K.id.padEnd(B)} ${A.padEnd(G)} ${R}`;z.push(w)}return z.join(L)}function f(q){let z=q.map((B)=>({id:B.id,title:B.title,updated:B.time.updated,created:B.time.created,projectId:B.projectID,directory:B.directory}));return JSON.stringify(z,null,2)}export{T as SessionListCommand,v as SessionImportClaudeCommand,D as SessionDeleteCommand,g as SessionCommand};
@@ -0,0 +1,28 @@
1
+ // @bun
2
+ import{of as ZH}from"./chunk-gy0wm7e1.js";import{mq as XH}from"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import{rt as Q}from"./chunk-nj2bbtmx.js";import{ou as u,wu as VH}from"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";var qH=0.9,OH=256,l="[Earlier tool result removed to fit the request size limit]",b;function C(H){return Buffer.byteLength(JSON.stringify(H),"utf8")}function o(){return u.QITQODE_QLEX_MAX_REQUEST_BYTES??b}function p(H){let J=u.QITQODE_QLEX_MAX_REQUEST_BYTES;if(J!==void 0)return J;let V=Math.max(1,Math.min(Math.floor(H*qH),Math.floor(H)-1));return b=b===void 0?V:Math.min(b,V),b}function I(H,J){return!!H&&typeof H==="object"&&H.role===J}function n(H){let J=[],V=0;while(V<H.length){let X=V,Z=H[V];if(V++,I(Z,"assistant")&&Array.isArray(Z?.tool_calls)&&Z.tool_calls.length>0)while(V<H.length&&I(H[V],"tool"))V++;J.push({start:X,end:V})}return J}function r(H,J){if(J.length===0)return[];let V=-1;for(let X=J.length-1;X>=0;X--){let Z=J[X],K=!1;for(let $=Z.start;$<Z.end;$++)if(I(H[$],"user"))K=!0;if(K){V=X;break}}return J.filter((X,Z)=>{if(Z===J.length-1)return!1;if(Z===V)return!1;if(X.start===0&&I(H[0],"system"))return!1;return!0})}function c(H,J){let V=C(H),X={toolResultsElided:0,unitsDropped:0},Z=()=>({body:H,bytes:V,originalBytes:V,reduced:!1,actions:X});if(!H||typeof H!=="object")return Z();let K=H.messages;if(!Array.isArray(K))return Z();let $=K.map((F)=>F&&typeof F==="object"?{...F}:F),z=()=>({...H,messages:$}),Y=()=>C(z())<=J;{let F=$;for(let L of r(F,n(F))){let O=!1;for(let _=L.start;_<L.end;_++){let S=F[_];if(!I(S,"tool"))continue;let k=S?.content;if(typeof k!=="string"||k.length<OH)continue;if(k===l)continue;F[_]={...S,content:l},X.toolResultsElided++,O=!0}if(O&&Y())break}}if(!Y())for(;;){let F=$,O=r(F,n(F))[0];if(!O)break;if($=[...F.slice(0,O.start),...F.slice(O.end)],X.unitsDropped++,Y())break}let j=z(),D=C(j);return{body:j,bytes:D,originalBytes:V,reduced:D<V&&D<=J,actions:X}}var M=VH({service:"provider.qlex"}),LH=Q.streamUrl(),QH=Q.omniqueryBaseUrl()+"/runOrchestrated";function E(H,J){let V=H;if(J.status!==void 0)V.status=J.status;if(J.upstreamCode!==void 0)V.upstreamCode=J.upstreamCode;V.category=J.category,V.retryable=J.retryable}function w(H,J){return{...H,...J}}class $H extends Error{name="QlexNotLoggedInError";constructor(H){super(Q.copy().notLoggedIn);E(this,w({category:"invalid_credentials",retryable:!1},H))}}class KH extends Error{name="QlexInsufficientBalanceError";constructor(H,J){super(Q.copy().insufficientBalance(H));E(this,w({status:402,category:"billing",retryable:!1},J))}}class zH extends Error{name="QlexRateLimitError";constructor(H){super(Q.copy().rateLimit);E(this,w({status:429,category:"rate_limited",retryable:!0},H))}}class YH extends Error{name="QlexInvalidCredentialsError";constructor(H,J){super(Q.copy().invalidCredentials(H));E(this,w({status:401,category:"invalid_credentials",retryable:!1},J))}}class DH extends Error{name="QlexRequestRejectedError";constructor(H,J,V){super(Q.copy().requestRejected(H,J));E(this,w({status:400,category:"request_rejected",retryable:!1},V))}}class y extends Error{name="QlexRequestTooLargeError";stage;constructor(H="irreducible",J,V){super(H==="after-reduction"?Q.copy().requestTooLargeAfterReduction(J):Q.copy().requestTooLargeIrreducible(J));this.stage=H,E(this,w({status:413,category:"request_too_large",retryable:!1},V))}}class WH extends Error{name="QlexRequestNotSentError";constructor(H,J){super(Q.copy().requestNotSent(H));E(this,w({category:"request_rejected",retryable:!1},J))}}class B extends Error{name="QlexGatewayError";constructor(H,J){super(Q.copy().gatewayUnavailable(H));E(this,w({category:"gateway_routing",retryable:!1},J))}}var SH=60000;function eH(H){return Q.sanitizeUpstreamError(H)}class x extends Error{name="QlexStreamError";constructor(H,J){let V=w({category:"unknown",retryable:!1},J);super(V.category==="stream_truncated"?Q.copy().streamCutOff():Q.copy().streamFailed(H));E(this,V)}}var PH=[{match:/\b(unauthori[sz]ed|forbidden|invalid[ _-]?(api[ _-]?key|token|credential)|expired[ _-]?token|authentication[ _-]?(failed|error)|401|403)\b/i,category:"invalid_credentials",retryable:!1},{match:/\b(insufficient[ _-]?(credits?|qredits?|balance|funds)|payment[ _-]?required|quota[ _-]?exceeded|out[ _-]?of[ _-]?(credits?|qredits?)|402)\b/i,category:"billing",retryable:!1},{match:/\b(rate[ _-]?limit(ed|s)?|too[ _-]?many[ _-]?requests|429)\b/i,category:"rate_limited",retryable:!0},{match:/(unexpected end of (json|input|stream|data)|premature (close|end)|socket hang ?up|incomplete (response|output|json|message)|truncated|stream (ended|closed|terminated) (early|unexpectedly|prematurely)|\bECONNRESET\b|\bEPIPE\b)/i,category:"stream_truncated",retryable:!0},{match:/\b(overloaded|at capacity|service[ _-]?unavailable|temporarily[ _-]?unavailable|bad[ _-]?gateway|gateway[ _-]?time(d[ _-]?out|out)|timed[ _-]?out|502|503|504)\b/i,category:"transient",retryable:!0}];function MH(H){let J=H??"";for(let V of PH)if(V.match.test(J))return{category:V.category,retryable:V.retryable};return{category:"unknown",retryable:!1}}function EH(H){return XH(H)}function wH(H,J){let V,X,Z;try{let Y=JSON.parse(J);if(Y&&typeof Y==="object"){let j=Y.error&&typeof Y.error==="object"?Y.error:void 0;if(typeof j?.code==="string")V=j.code;else if(typeof Y.code==="string")V=Y.code;if(typeof j?.message==="string")X=j.message;else if(typeof Y.message==="string")X=Y.message;if(typeof Y.details?.field==="string")Z=Y.details.field}}catch{}let K=V?.toUpperCase()??"",$=(()=>{if(H===402)return"billing";if(H===413)return"request_too_large";if(H===429)return"rate_limited";if(H===401||H===403)return K==="ERR_GATEWAY_REQUIRED"||EH(J)?"gateway_routing":"invalid_credentials";if(K.includes("CONFIG"))return"configuration";if(H>=500)return"transient";if(H>=400)return"request_rejected";return"unknown"})(),z={status:H,category:$,retryable:$==="transient"||$==="rate_limited"};if(V!==void 0)z.upstreamCode=V;if(X!==void 0)z.upstreamMessage=X;if(Z!==void 0)z.field=Z;return z}var TH=new Set(["coding","agent","research","review","chat"]);function RH(H){if(H===void 0)return;if(typeof H==="string"&&TH.has(H))return H;throw Error(`invalid Qortex posture: ${String(H)}`)}function CH(H){if(H===void 0)return;let J=Array.isArray(H)?H:[H];if(J.every((V)=>typeof V==="string"&&/^[^/\s]+\/[^/\s]+$/.test(V)))return Array.isArray(H)?J:H;throw Error(`invalid Qortex directive registry key: ${String(H)}`)}function f(H){if(typeof H==="string")return H;if(Array.isArray(H))return H.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"){let V=J;if(typeof V.text==="string")return V.text;if(typeof V.content==="string")return V.content}return""}).join("");if(H===void 0||H===null)return"";return String(H)}var AH="[Tool call]",bH="[Tool returned no output]";function NH(H){if(!Array.isArray(H))return{messages:H,dropped:[]};let J=[];return{messages:H.flatMap((X,Z)=>{if(!X||typeof X!=="object")return J.push({index:Z,role:typeof X,reason:"not-an-object"}),[];let K=X,$=f(K.content);if($.trim().length>0)return[{...K,content:$}];if(K.role==="assistant"&&Array.isArray(K.tool_calls)&&K.tool_calls.length>0)return[{...K,content:AH}];if(K.role==="tool"&&typeof K.tool_call_id==="string"&&K.tool_call_id.trim().length>0)return[{...K,content:bH}];return J.push({index:Z,role:typeof K.role==="string"?K.role:"unknown",reason:"empty-content"}),[]}),dropped:J}}function IH(H){return NH(H).messages}function vH(H){if(!Array.isArray(H))return!1;return H.some((J)=>!!J&&typeof J==="object"&&J.role==="user")}function BH(H){if(!Array.isArray(H))return!1;return H.some((J)=>{if(!J||typeof J!=="object")return!1;let V=J;if(V.role!=="user")return!1;return f(V.content).trim().length>0})}function xH(H){if(!Array.isArray(H))return H;let J=(K)=>!!K&&typeof K==="object"&&K.role==="system",V=0;while(V<H.length&&J(H[V]))V++;if(V<=1)return H;let X=H.slice(0,V),Z=X.map((K)=>typeof K.content==="string"?K.content:String(K.content??"")).filter((K)=>K.length>0).join(`
3
+
4
+ `);return[{...X[0],role:"system",content:Z},...H.slice(V)]}var v="<tool_call>",h="</tool_call>";function hH(H){if(!Array.isArray(H)||H.length===0)return;let J=H.map((V)=>{try{return JSON.stringify(V)}catch{return}}).filter((V)=>V!==void 0);if(J.length===0)return;return["# Tools","","You may call one or more functions to assist with the user query.","","You are provided with function signatures within <tools></tools> XML tags:","<tools>",...J,"</tools>","","For each function call, return a json object with function name and arguments within <tool_call></tool_call> XML tags:","<tool_call>",'{"name": <function-name>, "arguments": <args-json-object>}',"</tool_call>","","Function results will be provided within <tool_response></tool_response> XML tags. Do not write <tool_response> blocks yourself.","Only use the functions declared above. Never invent function names, and never write out a function-call-like block in any other format."].join(`
5
+ `)}function fH(H){let J=H.function??{},V=typeof J.name==="string"?J.name:"",X={};if(typeof J.arguments==="string")try{X=JSON.parse(J.arguments)}catch{X=J.arguments}else if(J.arguments!==void 0)X=J.arguments;return`${v}
6
+ ${JSON.stringify({name:V,arguments:X})}
7
+ ${h}`}function FH(H,J){if(!Array.isArray(H))return H;let V=H.map((Z)=>{if(!Z||typeof Z!=="object")return Z;let K=Z;if(K.role==="assistant"&&Array.isArray(K.tool_calls)){let $=K.tool_calls.map(fH).join(`
8
+ `),z=f(K.content),{tool_calls:Y,...j}=K;return{...j,content:z.length>0?`${z}
9
+ ${$}`:$}}if(K.role==="tool"){let{tool_call_id:$,name:z,...Y}=K;return{...Y,role:"user",content:`<tool_response>
10
+ ${f(K.content)}
11
+ </tool_response>`}}return Z}),X=hH(J);if(X){let Z=0;while(Z<V.length&&!!V[Z]&&typeof V[Z]==="object"&&V[Z].role==="system")Z++;V.splice(Z,0,{role:"system",content:X})}return V}function yH(){return process.env.QITQODE_TOOL_PROTOCOL==="text"?"text":"native"}function gH(H){if(Array.isArray(H.tools)&&H.tools.length>0)return!0;let J=H.messages;if(!Array.isArray(J))return!1;return J.some((V)=>{if(!V||typeof V!=="object")return!1;let X=V;return X.role==="tool"||X.role==="assistant"&&Array.isArray(X.tool_calls)})}function a(H,J){let V=J?.toolMode??"native",X=H.model??"default",Z={stream:H.stream??!0};if(H.temperature!==void 0)Z.temperature=H.temperature;if(H.max_tokens!==void 0)Z.max_tokens=H.max_tokens;let K=J?.outputAdvisory;if(K){let D=K.tierOutputLimit;if(Z.max_tokens!==void 0){if(D!==void 0&&Z.max_tokens>D)Z.max_tokens=D}else{let F=K.tierRecommendedStepTokens??D;if(F!==void 0)Z.max_tokens=F}}if(H.tools!==void 0)Z.tools=H.tools;if(H.tool_choice!==void 0)Z.tool_choice=H.tool_choice;if(H.stream_options!==void 0)Z.stream_options=H.stream_options;let $=V==="text"?FH(H.messages,H.tools):H.messages,z={},Y=RH(H.posture);if(Y!==void 0)z.posture=Y;let j=CH(H.directive);if(j!==void 0)z.directive=j;if(H.modelPersona!==void 0)z.modelPersona=H.modelPersona;return{tier:X,messages:xH(IH($)),opts:Z,...z}}var i=new Map;function t(H){return typeof H==="number"&&Number.isFinite(H)&&H>0?H:void 0}function uH(H,J){let V={},X=t(J.tierOutputLimit),Z=t(J.tierRecommendedStepTokens);if(X!==void 0)V.tierOutputLimit=X;if(Z!==void 0)V.tierRecommendedStepTokens=Z;if(V.tierOutputLimit===void 0&&V.tierRecommendedStepTokens===void 0)return;i.set(H,V)}function pH(H){return i.get(H)}function HJ(){i.clear()}function cH(H){let J=(V)=>typeof V==="string"&&(V.startsWith("qlex")||V.startsWith("qortex"));return J(H.id)||J(H.object)}function mH(H){let J=[],V=H.indexOf(`
12
+ `)===-1?[H]:H.split(`
13
+ `);for(let $ of V){let z=$.endsWith("\r")?$.slice(0,-1):$;if(!z.startsWith("data:"))continue;let Y=z.slice(5);if(Y.startsWith(" "))Y=Y.slice(1);J.push(Y)}if(J.length===0)return{kind:"skip"};let X=J.length===1?J[0]:J.join(`
14
+ `);if(X==="")return{kind:"skip"};if(X==="[DONE]")return{kind:"done"};if(X.startsWith("[ERROR]"))return{kind:"error",message:X.slice(7).trim()||"qlex stream error"};let Z=X.charCodeAt(0),K=Z===123||Z===91||Z===32||Z===9||Z===10||Z===13;try{if(!K)return{kind:"token",content:X};let $=JSON.parse(X);if($&&typeof $==="object"){let z=$.id;if(z==="qlex-cost"||z==="qortex-cost")return{kind:"cost",cost:$};if(z==="qlex-stream"&&$.usage&&typeof $.usage==="object"){let D=$.choices,F;if(Array.isArray(D)&&D[0]&&typeof D[0]==="object"){let L=D[0].finish_reason;if(typeof L==="string")F=L}return{kind:"usage",usage:$.usage,finishReason:F}}if(Array.isArray($.choices))return{kind:"passthrough",chunk:$};let Y=$,j=typeof Y.content==="string"?Y.content:typeof Y.text==="string"?Y.text:typeof Y.delta==="string"?Y.delta:void 0;if(j!==void 0)return{kind:"token",content:j};if(cH($)){let D=$.object;return{kind:"control",control:typeof D==="string"&&D.endsWith(".tier.outputLimits")?"tier-output-limits":"unknown",chunk:$}}}}catch{}return{kind:"token",content:X}}function iH(H,J){let V=Math.min(H.length,J.length-1);for(let X=V;X>=1;X--)if(J.startsWith(H.slice(H.length-X)))return X;return 0}class GH{onText;onToolCall;pending="";inBlock=!1;constructor(H,J){this.onText=H;this.onToolCall=J}feed(H){this.pending+=H,this.drain(!1)}flush(){if(this.drain(!0),this.inBlock)this.emitBlock(this.pending,!0),this.inBlock=!1;else if(this.pending.length>0)this.onText(this.pending);this.pending=""}drain(H){while(!0)if(!this.inBlock){let J=this.pending.indexOf(v);if(J===-1){let V=H?0:iH(this.pending,v),X=this.pending.length-V;if(X>0)this.onText(this.pending.slice(0,X)),this.pending=V>0?this.pending.slice(X):"";return}if(J>0)this.onText(this.pending.slice(0,J));this.pending=this.pending.slice(J+v.length),this.inBlock=!0}else{let J=this.pending.indexOf(h);if(J===-1)return;if(this.emitBlock(this.pending.slice(0,J),!1),this.pending=this.pending.slice(J+h.length),this.pending.startsWith(`\r
15
+ `))this.pending=this.pending.slice(2);else if(this.pending.startsWith(`
16
+ `))this.pending=this.pending.slice(1);this.inBlock=!1}}emitBlock(H,J){try{let V=JSON.parse(H.trim());if(V&&typeof V==="object"&&typeof V.name==="string"){let X=V.arguments;this.onToolCall({name:V.name,arguments:typeof X==="string"?X:JSON.stringify(X??{})});return}}catch{}this.onText(`${v}${H}${J?"":h}`)}}function m(H,J,V){let X={id:"qlex-stream",object:"chat.completion.chunk",created:Math.floor(Date.now()/1000),model:"qlex",choices:[{index:0,delta:H,finish_reason:J}]};if(V)X.usage=V;return`data: ${JSON.stringify(X)}
17
+
18
+ `}function dH(H,J){let V=J?.toolProtocolEnabled===!0,X=J?.tier,Z=H.getReader(),K=new TextDecoder,$=new TextEncoder,z="",Y=!1,j=!1,D,F,L,O=0;return new ReadableStream({async start(_){let S=(N)=>{let W=Y?{content:N}:{role:"assistant",content:N};Y=!0,_.enqueue($.encode(m(W,null)))},k=0,U=V?new GH(S,(N)=>{let W={...Y?{}:{role:"assistant"},tool_calls:[{index:k,id:`qlexcall_${Date.now().toString(36)}_${k}`,type:"function",function:{name:N.name,arguments:N.arguments}}]};Y=!0,k++,_.enqueue($.encode(m(W,null)))}):void 0,T=(N)=>U?U.feed(N):S(N),g=()=>{U?.flush();let N=D||F!==void 0?{prompt_tokens:D?.tokens.prompt??0,completion_tokens:D?.tokens.completion??0,total_tokens:D?.tokens.total??(D?.tokens.prompt??0)+(D?.tokens.completion??0),cost_usd:D?.cost_usd,cost_credits:D?.cost_credits??D?.cost_qredits,context_window:F}:void 0,W=k>0?"tool_calls":L??"stop";_.enqueue($.encode(m({},W,N))),_.enqueue($.encode(`data: [DONE]
19
+
20
+ `)),_.close(),j=!0},q=(N)=>{let W=mH(N);switch(O++,W.kind){case"skip":return!1;case"token":return T(W.content),!1;case"passthrough":{let G=W.chunk.choices;if(Array.isArray(G)&&G[0]&&typeof G[0]==="object"){let P=G[0].finish_reason;if(typeof P==="string")L=P}return Y=!0,_.enqueue($.encode(`data: ${JSON.stringify(W.chunk)}
21
+
22
+ `)),!1}case"cost":if(W.cost.final)D=W.cost;return!1;case"usage":if(W.usage.context_window!==void 0)F=W.usage.context_window;if(W.finishReason!==void 0)L=W.finishReason;return!1;case"control":{if(W.control==="tier-output-limits"){let G=W.chunk;if(X!==void 0)uH(X,G);M.debug("qlex tier output limits",{tierOutputLimit:G.tierOutputLimit,tierRecommendedStepTokens:G.tierRecommendedStepTokens,tierStepGuidance:G.tierStepGuidance})}else M.debug("qlex control frame dropped",{id:W.chunk.id,object:W.chunk.object});return!1}case"done":return g(),!0;case"error":{let G=MH(W.message);return M.debug("qlex stream error frame",{tier:X,raw:W.message,frameIndex:O,contentStreamed:Y,category:G.category,retryable:G.retryable}),_.error(new x(W.message,G)),j=!0,!0}}};try{while(!0){let{done:W,value:G}=await Z.read();if(W)break;z+=K.decode(G,{stream:!0});let P;while((P=z.indexOf(`
23
+
24
+ `))!==-1){let R=z.slice(0,P);if(z=z.slice(P+2),q(R))return}}z+=K.decode();let N=z.replace(/\r?\n$/,"");if(N.length>0&&q(N))return;if(!j)g()}catch(N){if(!j)_.error(N instanceof x?N:new x(N instanceof Error?N.message:String(N)))}finally{Z.releaseLock()}},cancel(_){Z.cancel(_).catch(()=>{})}})}function jH(H){return{content:typeof H.content==="string"?H.content:H.choices?.[0]?.message?.content??"",finishReason:H.choices?.[0]?.finish_reason??"stop"}}function lH(H){let J=H??{},{content:V,finishReason:X}=jH(J),Z=J.usage??{},K=Z.prompt_tokens??0,$=Z.completion_tokens??0,z="orch-"+Date.now().toString(36),Y=Math.floor(Date.now()/1000),j=(_,S,k)=>{let U={id:z,object:"chat.completion.chunk",created:Y,model:"orchestrated",choices:[{index:0,delta:_,finish_reason:S}]};if(k)U.usage=k;return`data: ${JSON.stringify(U)}
25
+
26
+ `},D={prompt_tokens:K,completion_tokens:$,total_tokens:Z.total_tokens??K+$};if(typeof Z.cost_usd==="number")D.cost_usd=Z.cost_usd;if(typeof Z.cost_credits==="number")D.cost_credits=Z.cost_credits;if(typeof Z.context_window==="number")D.context_window=Z.context_window;let F=[j({role:"assistant",content:""},null),j({content:V},null),j({},X,D),`data: [DONE]
27
+
28
+ `],L=new TextEncoder,O=new ReadableStream({start(_){for(let S of F)_.enqueue(L.encode(S));_.close()}});return new Response(O,{status:200,headers:{"content-type":"text/event-stream"}})}function JJ(H){let J=H??{},{content:V,finishReason:X}=jH(J),Z=J.usage??{},K=Z.prompt_tokens??0,$=Z.completion_tokens??0,z={id:"orch-"+Date.now(),object:"chat.completion",created:Math.floor(Date.now()/1000),model:"orchestrated",choices:[{index:0,message:{role:"assistant",content:V},finish_reason:X}],usage:{prompt_tokens:K,completion_tokens:$,total_tokens:Z.total_tokens??K+$,...typeof Z.cost_usd==="number"?{cost_usd:Z.cost_usd}:{},...typeof Z.context_window==="number"?{context_window:Z.context_window}:{}}};return new Response(JSON.stringify(z),{status:200,headers:{"content-type":"application/json"}})}async function s(H,J,V){let X=wH(H,J),Z=J?`HTTP ${H}: ${J}`:`HTTP ${H}`;switch(M.error("gateway rejected request",{tier:V.tier,status:H,category:X.category,upstreamCode:X.upstreamCode,field:X.field,retryable:X.retryable}),X.category){case"billing":return new KH(J||void 0,X);case"rate_limited":return new zH(X);case"gateway_routing":return new B(`HTTP ${H}`,X);case"invalid_credentials":return await V.onInvalidCredentials?.().catch(()=>{}),new YH(Z,X);case"request_too_large":return new y("irreducible",X.upstreamMessage??J??void 0,X);case"request_rejected":case"tool_protocol":return new DH(X.upstreamMessage??J??void 0,X.field,X);case"configuration":case"transient":case"unknown":default:return new B(Z,X)}}function e(H){let J=o();if(J===void 0)return H;let V=C(H);if(V<=J)return H;let X=c(H,J);return M.warn("request over known size ceiling, reducing before send",{tier:H.tier,bytes:V,ceiling:J,reducedBytes:X.bytes,fits:X.reduced,...X.actions}),X.bytes<V?X.body:H}function HH(H){let J=C(H),V=p(J),X=c(H,V);if(!X.reduced)throw M.error("request too large and cannot be reduced further",{tier:H.tier,rejectedBytes:J,ceiling:V,reducedBytes:X.bytes,...X.actions}),new y("irreducible");return M.warn("request too large, retrying once with reduced history",{tier:H.tier,rejectedBytes:J,ceiling:V,reducedBytes:X.bytes,...X.actions,notice:Q.copy().requestTooLargeRecovering()}),X.body}function JH(H){let J=C(H);throw p(J),M.error("reduced request still too large",{tier:H.tier,rejectedBytes:J}),new y("after-reduction")}function nH(H,J=globalThis.fetch,V,X){let Z=X?.responseTimeoutMs??SH;return async(K,$)=>{if($?.method==="POST"&&typeof $?.body==="string"){let z;try{z=JSON.parse($.body)}catch{return J(K,$)}let Y=yH(),j=pH(z.model??"default"),D=a(z,{toolMode:Y,outputAdvisory:j});if(vH(z.messages)&&!BH(D.messages)){let{dropped:q}=NH(Y==="text"?FH(z.messages,z.tools):z.messages);throw M.error("refusing to send: user message lost in normalization",{tier:D.tier,toolMode:Y,inputRoles:Array.isArray(z.messages)?z.messages.map((N)=>N&&typeof N==="object"?String(N.role):"?"):"not-an-array",droppedCount:q.length,dropped:q}),new WH("your message could not be turned into sendable content")}let F=await H(),L=typeof F==="string"?{key:F,method:"sso"}:F;if(!L?.key)throw new $H;let O=new Headers($.headers);if(L.method==="api-key")O.delete("Authorization"),O.set("x-api-key",L.key);else O.delete("x-api-key"),O.set("Authorization",`Bearer ${L.key}`);if(O.set("Content-Type","application/json"),D.tier==="orchestrated"){let q=$.signal,N=async(P)=>{let R=new AbortController,A=()=>R.abort(q?.reason);if(q)if(q.aborted)R.abort(q.reason);else q.addEventListener("abort",A,{once:!0});let d=!1,_H=setTimeout(()=>{d=!0,R.abort()},Z);try{return await J(QH,{method:"POST",headers:O,body:JSON.stringify(P),signal:R.signal})}catch(UH){if(d)throw new B(`no response within ${Math.round(Z/1000)}s`);throw UH}finally{clearTimeout(_H),q?.removeEventListener("abort",A)}},W=e(D),G=await N(W);if(G.status===413){if(await G.body?.cancel().catch(()=>{}),W=HH(W),G=await N(W),G.status===413)await G.body?.cancel().catch(()=>{}),JH(W)}if(!G.ok){let P=await G.text().catch(()=>"");throw await s(G.status,P,{onInvalidCredentials:V,tier:D.tier})}return lH(await G.json())}let _=$.signal,S=async(q)=>{let N=new AbortController,W=()=>N.abort(_?.reason);if(_)if(_.aborted)N.abort(_.reason);else _.addEventListener("abort",W,{once:!0});let G=()=>_?.removeEventListener("abort",W),P=!1,R=setTimeout(()=>{P=!0,N.abort()},Z);try{return{res:await J(LH,{method:"POST",headers:O,body:JSON.stringify(q),signal:N.signal}),detach:G}}catch(A){if(G(),P)throw new B(`no response within ${Math.round(Z/1000)}s`);throw A}finally{clearTimeout(R)}},k=e(D),{res:U,detach:T}=await S(k);if(U.status===400&&Y==="native"&&gH(z))T(),await U.body?.cancel().catch(()=>{}),k=a(z,{toolMode:"text",outputAdvisory:j}),{res:U,detach:T}=await S(k);if(U.status===413){if(T(),await U.body?.cancel().catch(()=>{}),k=HH(k),{res:U,detach:T}=await S(k),U.status===413)T(),await U.body?.cancel().catch(()=>{}),JH(k)}try{if(!U.ok){let q=await U.text().catch(()=>"");throw await s(U.status,q,{onInvalidCredentials:V,tier:D.tier})}}catch(q){throw T(),q}if(z.stream!==!1&&U.body){let q=Array.isArray(z.tools)&&z.tools.length>0;return new Response(dH(U.body,{toolProtocolEnabled:q,tier:D.tier}),{status:U.status,statusText:U.statusText,headers:{"content-type":"text/event-stream"}})}return U}return J(K,$)}}function VJ(H){let J=H.getToken??(async()=>H.bearerToken),V=nH(J,globalThis.fetch,H.onInvalidCredentials);return ZH({name:H.name??"qlex",baseURL:Q.streamBaseUrl(),fetch:V})}export{dH as transformQlexStream,lH as toOrchestratedSSEStream,JJ as toOpenAICompletion,eH as sanitizeUpstreamProviderError,yH as resolveToolMode,hH as renderToolProtocolPrompt,uH as recordTierOutputAdvisory,iH as partialTagSuffixLength,mH as parseQlexFrame,wH as parseQlexError,NH as normalizeQlexMessagesWithReport,IH as normalizeQlexMessages,xH as mergeLeadingSystemMessages,EH as isGatewayRequiredError,vH as hasUserRoleMessage,BH as hasUsableUserMessage,gH as hasToolContext,pH as getTierOutputAdvisory,f as flattenMessageContent,FH as encodeToolProtocolMessages,VJ as createQlexProvider,nH as createCustomFetch,HJ as clearTierOutputAdvisories,MH as classifyQlexStreamError,a as buildQlexBody,GH as ToolCallExtractor,v as TOOL_CALL_OPEN,h as TOOL_CALL_CLOSE,x as QlexStreamError,y as QlexRequestTooLargeError,DH as QlexRequestRejectedError,WH as QlexRequestNotSentError,zH as QlexRateLimitError,$H as QlexNotLoggedInError,YH as QlexInvalidCredentialsError,KH as QlexInsufficientBalanceError,B as QlexGatewayError,LH as QLEX_STREAM_URL,SH as QLEX_RESPONSE_TIMEOUT_MS,QH as QLEX_ORCHESTRATED_URL};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ed as b}from"./chunk-ppkqr9cn.js";import{Rd as f}from"./chunk-yajd975f.js";import{gh as S}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as v}from"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import{Vl as U,bm as R,lm as k}from"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import{eu as Z}from"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";var i=f({command:"stats",describe:"show token usage and cost statistics",builder:(z)=>{return z.option("days",{describe:"show stats for the last N days (default: all time)",type:"number"}).option("tools",{describe:"number of tools to show (default: all)",type:"number"}).option("models",{describe:"show model statistics (default: hidden). Pass a number to show top N, otherwise shows all"}).option("project",{describe:"filter by project (default: all projects, empty string: current project)",type:"string"})},handler:async(z)=>{await b(process.cwd(),async()=>{let E=await y(z.days,z.project),_;if(z.models===!0)_=1/0;else if(typeof z.models==="number")_=z.models;u(E,z.tools,_)})}});async function w(){return k.project}async function p(){return R.use((E)=>E.select().from(U).all()).map((E)=>v.fromRow(E))}async function y(z,E){let _=await p(),L=86400000,J=(()=>{if(z===void 0)return 0;if(z===0){let V=new Date;return V.setHours(0,0,0,0),V.getTime()}return Date.now()-z*86400000})(),K=(()=>{if(z===void 0)return;if(z===0)return 1;return z})(),Y=J>0?_.filter((V)=>V.time.updated>=J):_;if(E!==void 0)if(E===""){let V=await w();Y=Y.filter((F)=>F.projectID===V.id)}else Y=Y.filter((V)=>V.projectID===E);let G={totalSessions:Y.length,totalMessages:0,totalCost:0,totalTokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},toolUsage:{},modelUsage:{},dateRange:{earliest:Date.now(),latest:Date.now()},days:0,costPerDay:0,tokensPerSession:0,medianTokensPerSession:0};if(Y.length>1000)console.log(`Large dataset detected (${Y.length} sessions). This may take a while...`);if(Y.length===0)return G.days=K??0,G;let C=Date.now(),x=0,X=[],h=20;for(let V=0;V<Y.length;V+=h){let D=Y.slice(V,V+h).map(async(Q)=>{let W=await S.runPromise(v.Service.use((O)=>O.messages({sessionID:Q.id,agentID:"*"}))),N=0,H={input:0,output:0,reasoning:0,cache:{read:0,write:0}},j={},A={};for(let O of W){if(O.info.role==="assistant"){N+=O.info.cost||0;let B=`${O.info.providerID}/${O.info.modelID}`;if(!A[B])A[B]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};if(A[B].messages++,A[B].cost+=O.info.cost||0,O.info.tokens)H.input+=O.info.tokens.input||0,H.output+=O.info.tokens.output||0,H.reasoning+=O.info.tokens.reasoning||0,H.cache.read+=O.info.tokens.cache?.read||0,H.cache.write+=O.info.tokens.cache?.write||0,A[B].tokens.input+=O.info.tokens.input||0,A[B].tokens.output+=(O.info.tokens.output||0)+(O.info.tokens.reasoning||0),A[B].tokens.cache.read+=O.info.tokens.cache?.read||0,A[B].tokens.cache.write+=O.info.tokens.cache?.write||0}for(let B of O.parts)if(B.type==="tool"&&B.tool)j[B.tool]=(j[B.tool]||0)+1}return{messageCount:W.length,sessionCost:N,sessionTokens:H,sessionTotalTokens:H.input+H.output+H.reasoning+H.cache.read+H.cache.write,sessionToolUsage:j,sessionModelUsage:A,earliestTime:J>0?Q.time.updated:Q.time.created,latestTime:Q.time.updated}}),M=await Promise.all(D);for(let Q of M){C=Math.min(C,Q.earliestTime),x=Math.max(x,Q.latestTime),X.push(Q.sessionTotalTokens),G.totalMessages+=Q.messageCount,G.totalCost+=Q.sessionCost,G.totalTokens.input+=Q.sessionTokens.input,G.totalTokens.output+=Q.sessionTokens.output,G.totalTokens.reasoning+=Q.sessionTokens.reasoning,G.totalTokens.cache.read+=Q.sessionTokens.cache.read,G.totalTokens.cache.write+=Q.sessionTokens.cache.write;for(let[W,N]of Object.entries(Q.sessionToolUsage))G.toolUsage[W]=(G.toolUsage[W]||0)+N;for(let[W,N]of Object.entries(Q.sessionModelUsage)){if(!G.modelUsage[W])G.modelUsage[W]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};G.modelUsage[W].messages+=N.messages,G.modelUsage[W].tokens.input+=N.tokens.input,G.modelUsage[W].tokens.output+=N.tokens.output,G.modelUsage[W].tokens.cache.read+=N.tokens.cache.read,G.modelUsage[W].tokens.cache.write+=N.tokens.cache.write,G.modelUsage[W].cost+=N.cost}}}let $=Math.max(1,Math.ceil((x-C)/86400000)),q=K??$;G.dateRange={earliest:C,latest:x},G.days=q,G.costPerDay=G.totalCost/q;let I=G.totalTokens.input+G.totalTokens.output+G.totalTokens.reasoning+G.totalTokens.cache.read+G.totalTokens.cache.write;G.tokensPerSession=Y.length>0?I/Y.length:0,X.sort((V,F)=>V-F);let P=Math.floor(X.length/2);return G.medianTokensPerSession=X.length===0?0:X.length%2===0?(X[P-1]+X[P])/2:X[P],G}function u(z,E,_){function J(x,X){let $=55-x.length-X.length,q=Math.max(0,$);return`\u2502${x}${" ".repeat(q)}${X} \u2502`}console.log("\u250C\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\u2510"),console.log("\u2502 OVERVIEW \u2502"),console.log("\u251C\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\u2524"),console.log(J("Sessions",z.totalSessions.toLocaleString())),console.log(J("Messages",z.totalMessages.toLocaleString())),console.log(J("Days",z.days.toString())),console.log("\u2514\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\u2518"),console.log(),console.log("\u250C\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\u2510"),console.log("\u2502 COST & TOKENS \u2502"),console.log("\u251C\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\u2524");let K=isNaN(z.totalCost)?0:z.totalCost,Y=isNaN(z.costPerDay)?0:z.costPerDay,G=isNaN(z.tokensPerSession)?0:z.tokensPerSession;console.log(J("Total Cost",`$${K.toFixed(2)}`)),console.log(J("Avg Cost/Day",`$${Y.toFixed(2)}`)),console.log(J("Avg Tokens/Session",Z.number(Math.round(G))));let C=isNaN(z.medianTokensPerSession)?0:z.medianTokensPerSession;if(console.log(J("Median Tokens/Session",Z.number(Math.round(C)))),console.log(J("Input",Z.number(z.totalTokens.input))),console.log(J("Output",Z.number(z.totalTokens.output))),console.log(J("Cache Read",Z.number(z.totalTokens.cache.read))),console.log(J("Cache Write",Z.number(z.totalTokens.cache.write))),console.log("\u2514\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\u2518"),console.log(),_!==void 0&&Object.keys(z.modelUsage).length>0){let x=Object.entries(z.modelUsage).sort(([,h],[,$])=>$.messages-h.messages),X=_===1/0?x:x.slice(0,_);console.log("\u250C\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\u2510"),console.log("\u2502 MODEL USAGE \u2502"),console.log("\u251C\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\u2524");for(let[h,$]of X)console.log(`\u2502 ${h.padEnd(54)} \u2502`),console.log(J(" Messages",$.messages.toLocaleString())),console.log(J(" Input Tokens",Z.number($.tokens.input))),console.log(J(" Output Tokens",Z.number($.tokens.output))),console.log(J(" Cache Read",Z.number($.tokens.cache.read))),console.log(J(" Cache Write",Z.number($.tokens.cache.write))),console.log(J(" Cost",`$${$.cost.toFixed(4)}`)),console.log("\u251C\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\u2524");process.stdout.write("\x1B[1A"),console.log("\u2514\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\u2518")}if(console.log(),Object.keys(z.toolUsage).length>0){let x=Object.entries(z.toolUsage).sort(([,q],[,I])=>I-q),X=E?x.slice(0,E):x;console.log("\u250C\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\u2510"),console.log("\u2502 TOOL USAGE \u2502"),console.log("\u251C\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\u2524");let h=Math.max(...X.map(([,q])=>q)),$=Object.values(z.toolUsage).reduce((q,I)=>q+I,0);for(let[q,I]of X){let P=Math.max(1,Math.floor(I/h*20)),V="\u2588".repeat(P),F=(I/$*100).toFixed(1),D=18,W=` ${(q.length>18?q.substring(0,16)+"..":q).padEnd(18)} ${V.padEnd(20)} ${I.toString().padStart(3)} (${F.padStart(4)}%)`,N=Math.max(0,56-W.length-1);console.log(`\u2502${W}${" ".repeat(N)} \u2502`)}console.log("\u2514\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\u2518")}console.log()}export{u as displayStats,y as aggregateSessionStats,i as StatsCommand};
2
+ import{Ed as b}from"./chunk-aa8hymcv.js";import{Rd as f}from"./chunk-yajd975f.js";import{gh as S}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as v}from"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import{Vl as U,bm as R,lm as k}from"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import{eu as Z}from"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";var i=f({command:"stats",describe:"show token usage and cost statistics",builder:(z)=>{return z.option("days",{describe:"show stats for the last N days (default: all time)",type:"number"}).option("tools",{describe:"number of tools to show (default: all)",type:"number"}).option("models",{describe:"show model statistics (default: hidden). Pass a number to show top N, otherwise shows all"}).option("project",{describe:"filter by project (default: all projects, empty string: current project)",type:"string"})},handler:async(z)=>{await b(process.cwd(),async()=>{let E=await y(z.days,z.project),_;if(z.models===!0)_=1/0;else if(typeof z.models==="number")_=z.models;u(E,z.tools,_)})}});async function w(){return k.project}async function p(){return R.use((E)=>E.select().from(U).all()).map((E)=>v.fromRow(E))}async function y(z,E){let _=await p(),L=86400000,J=(()=>{if(z===void 0)return 0;if(z===0){let V=new Date;return V.setHours(0,0,0,0),V.getTime()}return Date.now()-z*86400000})(),K=(()=>{if(z===void 0)return;if(z===0)return 1;return z})(),Y=J>0?_.filter((V)=>V.time.updated>=J):_;if(E!==void 0)if(E===""){let V=await w();Y=Y.filter((F)=>F.projectID===V.id)}else Y=Y.filter((V)=>V.projectID===E);let G={totalSessions:Y.length,totalMessages:0,totalCost:0,totalTokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},toolUsage:{},modelUsage:{},dateRange:{earliest:Date.now(),latest:Date.now()},days:0,costPerDay:0,tokensPerSession:0,medianTokensPerSession:0};if(Y.length>1000)console.log(`Large dataset detected (${Y.length} sessions). This may take a while...`);if(Y.length===0)return G.days=K??0,G;let C=Date.now(),x=0,X=[],h=20;for(let V=0;V<Y.length;V+=h){let D=Y.slice(V,V+h).map(async(Q)=>{let W=await S.runPromise(v.Service.use((O)=>O.messages({sessionID:Q.id,agentID:"*"}))),N=0,H={input:0,output:0,reasoning:0,cache:{read:0,write:0}},j={},A={};for(let O of W){if(O.info.role==="assistant"){N+=O.info.cost||0;let B=`${O.info.providerID}/${O.info.modelID}`;if(!A[B])A[B]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};if(A[B].messages++,A[B].cost+=O.info.cost||0,O.info.tokens)H.input+=O.info.tokens.input||0,H.output+=O.info.tokens.output||0,H.reasoning+=O.info.tokens.reasoning||0,H.cache.read+=O.info.tokens.cache?.read||0,H.cache.write+=O.info.tokens.cache?.write||0,A[B].tokens.input+=O.info.tokens.input||0,A[B].tokens.output+=(O.info.tokens.output||0)+(O.info.tokens.reasoning||0),A[B].tokens.cache.read+=O.info.tokens.cache?.read||0,A[B].tokens.cache.write+=O.info.tokens.cache?.write||0}for(let B of O.parts)if(B.type==="tool"&&B.tool)j[B.tool]=(j[B.tool]||0)+1}return{messageCount:W.length,sessionCost:N,sessionTokens:H,sessionTotalTokens:H.input+H.output+H.reasoning+H.cache.read+H.cache.write,sessionToolUsage:j,sessionModelUsage:A,earliestTime:J>0?Q.time.updated:Q.time.created,latestTime:Q.time.updated}}),M=await Promise.all(D);for(let Q of M){C=Math.min(C,Q.earliestTime),x=Math.max(x,Q.latestTime),X.push(Q.sessionTotalTokens),G.totalMessages+=Q.messageCount,G.totalCost+=Q.sessionCost,G.totalTokens.input+=Q.sessionTokens.input,G.totalTokens.output+=Q.sessionTokens.output,G.totalTokens.reasoning+=Q.sessionTokens.reasoning,G.totalTokens.cache.read+=Q.sessionTokens.cache.read,G.totalTokens.cache.write+=Q.sessionTokens.cache.write;for(let[W,N]of Object.entries(Q.sessionToolUsage))G.toolUsage[W]=(G.toolUsage[W]||0)+N;for(let[W,N]of Object.entries(Q.sessionModelUsage)){if(!G.modelUsage[W])G.modelUsage[W]={messages:0,tokens:{input:0,output:0,cache:{read:0,write:0}},cost:0};G.modelUsage[W].messages+=N.messages,G.modelUsage[W].tokens.input+=N.tokens.input,G.modelUsage[W].tokens.output+=N.tokens.output,G.modelUsage[W].tokens.cache.read+=N.tokens.cache.read,G.modelUsage[W].tokens.cache.write+=N.tokens.cache.write,G.modelUsage[W].cost+=N.cost}}}let $=Math.max(1,Math.ceil((x-C)/86400000)),q=K??$;G.dateRange={earliest:C,latest:x},G.days=q,G.costPerDay=G.totalCost/q;let I=G.totalTokens.input+G.totalTokens.output+G.totalTokens.reasoning+G.totalTokens.cache.read+G.totalTokens.cache.write;G.tokensPerSession=Y.length>0?I/Y.length:0,X.sort((V,F)=>V-F);let P=Math.floor(X.length/2);return G.medianTokensPerSession=X.length===0?0:X.length%2===0?(X[P-1]+X[P])/2:X[P],G}function u(z,E,_){function J(x,X){let $=55-x.length-X.length,q=Math.max(0,$);return`\u2502${x}${" ".repeat(q)}${X} \u2502`}console.log("\u250C\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\u2510"),console.log("\u2502 OVERVIEW \u2502"),console.log("\u251C\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\u2524"),console.log(J("Sessions",z.totalSessions.toLocaleString())),console.log(J("Messages",z.totalMessages.toLocaleString())),console.log(J("Days",z.days.toString())),console.log("\u2514\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\u2518"),console.log(),console.log("\u250C\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\u2510"),console.log("\u2502 COST & TOKENS \u2502"),console.log("\u251C\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\u2524");let K=isNaN(z.totalCost)?0:z.totalCost,Y=isNaN(z.costPerDay)?0:z.costPerDay,G=isNaN(z.tokensPerSession)?0:z.tokensPerSession;console.log(J("Total Cost",`$${K.toFixed(2)}`)),console.log(J("Avg Cost/Day",`$${Y.toFixed(2)}`)),console.log(J("Avg Tokens/Session",Z.number(Math.round(G))));let C=isNaN(z.medianTokensPerSession)?0:z.medianTokensPerSession;if(console.log(J("Median Tokens/Session",Z.number(Math.round(C)))),console.log(J("Input",Z.number(z.totalTokens.input))),console.log(J("Output",Z.number(z.totalTokens.output))),console.log(J("Cache Read",Z.number(z.totalTokens.cache.read))),console.log(J("Cache Write",Z.number(z.totalTokens.cache.write))),console.log("\u2514\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\u2518"),console.log(),_!==void 0&&Object.keys(z.modelUsage).length>0){let x=Object.entries(z.modelUsage).sort(([,h],[,$])=>$.messages-h.messages),X=_===1/0?x:x.slice(0,_);console.log("\u250C\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\u2510"),console.log("\u2502 MODEL USAGE \u2502"),console.log("\u251C\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\u2524");for(let[h,$]of X)console.log(`\u2502 ${h.padEnd(54)} \u2502`),console.log(J(" Messages",$.messages.toLocaleString())),console.log(J(" Input Tokens",Z.number($.tokens.input))),console.log(J(" Output Tokens",Z.number($.tokens.output))),console.log(J(" Cache Read",Z.number($.tokens.cache.read))),console.log(J(" Cache Write",Z.number($.tokens.cache.write))),console.log(J(" Cost",`$${$.cost.toFixed(4)}`)),console.log("\u251C\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\u2524");process.stdout.write("\x1B[1A"),console.log("\u2514\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\u2518")}if(console.log(),Object.keys(z.toolUsage).length>0){let x=Object.entries(z.toolUsage).sort(([,q],[,I])=>I-q),X=E?x.slice(0,E):x;console.log("\u250C\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\u2510"),console.log("\u2502 TOOL USAGE \u2502"),console.log("\u251C\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\u2524");let h=Math.max(...X.map(([,q])=>q)),$=Object.values(z.toolUsage).reduce((q,I)=>q+I,0);for(let[q,I]of X){let P=Math.max(1,Math.floor(I/h*20)),V="\u2588".repeat(P),F=(I/$*100).toFixed(1),D=18,W=` ${(q.length>18?q.substring(0,16)+"..":q).padEnd(18)} ${V.padEnd(20)} ${I.toString().padStart(3)} (${F.padStart(4)}%)`,N=Math.max(0,56-W.length-1);console.log(`\u2502${W}${" ".repeat(N)} \u2502`)}console.log("\u2514\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\u2518")}console.log()}export{u as displayStats,y as aggregateSessionStats,i as StatsCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Ed as y}from"./chunk-ppkqr9cn.js";import{Rd as L}from"./chunk-yajd975f.js";import{Ug as N,gh as w}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as v,tl as q}from"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import{Vl as V,Wl as A,Xl as E,bm as k,lm as O}from"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import"./chunk-x9s90xd1.js";import{Ru as P}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as X}from"os";function U(C){let G=C.match(/^https?:\/\/[^/]+\/share\/([a-zA-Z0-9_-]+)$/);return G?G[1]:null}function M(C,G){try{return new URL(C).origin===new URL(G).origin}catch{return!1}}function S(C){let G=C.find((z)=>z.type==="session");if(!G)return null;let Z=new Map,Q=new Map;for(let z of C)if(z.type==="message")Z.set(z.data.id,z.data);else if(z.type==="part"){if(!Q.has(z.data.messageID))Q.set(z.data.messageID,[]);Q.get(z.data.messageID).push(z.data)}if(Z.size===0)return null;return{info:G.data,messages:Array.from(Z.values()).map((z)=>({info:z,parts:Q.get(z.id)??[]}))}}var m=L({command:"import <file>",describe:"import session data from JSON file or URL",builder:(C)=>{return C.positional("file",{describe:"path to JSON file or share URL",type:"string",demandOption:!0})},handler:async(C)=>{await y(process.cwd(),async()=>{let G;if(C.file.startsWith("http://")||C.file.startsWith("https://")){let J=U(C.file);if(!J){let Y=await w.runPromise(N.Service.use((R)=>R.url()));process.stdout.write(`Invalid URL format. Expected: ${Y}/share/<slug>`),process.stdout.write(X);return}let _=new URL(C.file).origin,$=await w.runPromise(N.Service.use((Y)=>Y.request())),j=M(C.file,$.baseUrl)?$.headers:{},W=$.api.data(J),K=await fetch(`${_}${W}`,{headers:j});if(!K.ok&&W!==`/api/share/${J}/data`)K=await fetch(`${_}/api/share/${J}/data`,{headers:j});if(!K.ok){process.stdout.write(`Failed to fetch share data: ${K.statusText}`),process.stdout.write(X);return}let H=await K.json(),B=S(H);if(!B){process.stdout.write(`Share not found or empty: ${J}`),process.stdout.write(X);return}G=B}else if(G=await P.readJson(C.file).catch(()=>{return}),!G){process.stdout.write(`File not found: ${C.file}`),process.stdout.write(X);return}if(!G){process.stdout.write("Failed to read session data"),process.stdout.write(X);return}let Q=v.Info.parse({...G.info,projectID:O.project.id}),z=v.toRow(Q);k.use((J)=>J.insert(V).values(z).onConflictDoUpdate({target:V.id,set:{project_id:z.project_id}}).run());for(let J of G.messages){let F=q.Info.parse(J.info),{id:_,sessionID:$,...j}=F;k.use((W)=>W.insert(A).values({id:_,session_id:z.id,time_created:F.time?.created??Date.now(),data:j}).onConflictDoNothing().run());for(let W of J.parts){let K=q.Part.parse(W),{id:H,sessionID:B,messageID:Y,...R}=K;k.use((T)=>T.insert(E).values({id:H,message_id:Y,session_id:z.id,data:R}).onConflictDoNothing().run())}}process.stdout.write(`Imported session: ${G.info.id}`),process.stdout.write(X)})}});export{S as transformShareData,M as shouldAttachShareAuthHeaders,U as parseShareUrl,m as ImportCommand};
2
+ import{Ed as y}from"./chunk-aa8hymcv.js";import{Rd as L}from"./chunk-yajd975f.js";import{Ug as N,gh as w}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{Cl as v,tl as q}from"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import{Vl as V,Wl as A,Xl as E,bm as k,lm as O}from"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import"./chunk-tns5x4w0.js";import{Ru as P}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as X}from"os";function U(C){let G=C.match(/^https?:\/\/[^/]+\/share\/([a-zA-Z0-9_-]+)$/);return G?G[1]:null}function M(C,G){try{return new URL(C).origin===new URL(G).origin}catch{return!1}}function S(C){let G=C.find((z)=>z.type==="session");if(!G)return null;let Z=new Map,Q=new Map;for(let z of C)if(z.type==="message")Z.set(z.data.id,z.data);else if(z.type==="part"){if(!Q.has(z.data.messageID))Q.set(z.data.messageID,[]);Q.get(z.data.messageID).push(z.data)}if(Z.size===0)return null;return{info:G.data,messages:Array.from(Z.values()).map((z)=>({info:z,parts:Q.get(z.id)??[]}))}}var m=L({command:"import <file>",describe:"import session data from JSON file or URL",builder:(C)=>{return C.positional("file",{describe:"path to JSON file or share URL",type:"string",demandOption:!0})},handler:async(C)=>{await y(process.cwd(),async()=>{let G;if(C.file.startsWith("http://")||C.file.startsWith("https://")){let J=U(C.file);if(!J){let Y=await w.runPromise(N.Service.use((R)=>R.url()));process.stdout.write(`Invalid URL format. Expected: ${Y}/share/<slug>`),process.stdout.write(X);return}let _=new URL(C.file).origin,$=await w.runPromise(N.Service.use((Y)=>Y.request())),j=M(C.file,$.baseUrl)?$.headers:{},W=$.api.data(J),K=await fetch(`${_}${W}`,{headers:j});if(!K.ok&&W!==`/api/share/${J}/data`)K=await fetch(`${_}/api/share/${J}/data`,{headers:j});if(!K.ok){process.stdout.write(`Failed to fetch share data: ${K.statusText}`),process.stdout.write(X);return}let H=await K.json(),B=S(H);if(!B){process.stdout.write(`Share not found or empty: ${J}`),process.stdout.write(X);return}G=B}else if(G=await P.readJson(C.file).catch(()=>{return}),!G){process.stdout.write(`File not found: ${C.file}`),process.stdout.write(X);return}if(!G){process.stdout.write("Failed to read session data"),process.stdout.write(X);return}let Q=v.Info.parse({...G.info,projectID:O.project.id}),z=v.toRow(Q);k.use((J)=>J.insert(V).values(z).onConflictDoUpdate({target:V.id,set:{project_id:z.project_id}}).run());for(let J of G.messages){let F=q.Info.parse(J.info),{id:_,sessionID:$,...j}=F;k.use((W)=>W.insert(A).values({id:_,session_id:z.id,time_created:F.time?.created??Date.now(),data:j}).onConflictDoNothing().run());for(let W of J.parts){let K=q.Part.parse(W),{id:H,sessionID:B,messageID:Y,...R}=K;k.use((T)=>T.insert(E).values({id:H,message_id:Y,session_id:z.id,data:R}).onConflictDoNothing().run())}}process.stdout.write(`Imported session: ${G.info.id}`),process.stdout.write(X)})}});export{S as transformShareData,M as shouldAttachShareAuthHeaders,U as parseShareUrl,m as ImportCommand};
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{Rd as q}from"./chunk-yajd975f.js";import{Vf as v}from"./chunk-p9cnzxb8.js";import{gh as S}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import{cm as Q,lm as H}from"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import"./chunk-x9s90xd1.js";import{Gu as K}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
2
+ import{Rd as q}from"./chunk-yajd975f.js";import{Vf as v}from"./chunk-p9cnzxb8.js";import{gh as S}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import{cm as Q,lm as H}from"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import"./chunk-tns5x4w0.js";import{Gu as K}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";var P=q({command:"pr <number>",describe:"fetch and checkout a GitHub PR branch, then run qitqode",builder:(Y)=>Y.positional("number",{type:"number",describe:"PR number to checkout",demandOption:!0}),async handler(Y){await H.provide({directory:process.cwd(),async fn(){if(H.project.vcs!=="git")v.error("Could not find git repository. Please run this command from a git repository."),process.exit(1);let J=Y.number,Z=`pr/${J}`;if(v.println(`Fetching and checking out PR #${J}...`),(await K.run(["gh","pr","checkout",`${J}`,"--branch",Z,"--force"],{nothrow:!0})).code!==0)v.error(`Failed to checkout PR #${J}. Make sure you have gh CLI installed and authenticated.`),process.exit(1);let _=await K.text(["gh","pr","view",`${J}`,"--json","headRepository,headRepositoryOwner,isCrossRepository,headRefName,body"],{nothrow:!0}),V;if(_.code===0){let j=_.text;if(j.trim()){let z=JSON.parse(j);if(z&&z.isCrossRepository&&z.headRepository&&z.headRepositoryOwner){let L=z.headRepositoryOwner.login,W=z.headRepository.name,C=L;if(!(await S.runPromise(Q.Service.use((F)=>F.run(["remote"],{cwd:H.worktree}))).then((F)=>F.text().trim())).split(`
3
3
  `).includes(C))await S.runPromise(Q.Service.use((F)=>F.run(["remote","add",C,`https://github.com/${L}/${W}.git`],{cwd:H.worktree}))),v.println(`Added fork remote: ${C}`);let X=z.headRefName;await S.runPromise(Q.Service.use((F)=>F.run(["branch",`--set-upstream-to=${C}/${X}`,Z],{cwd:H.worktree})))}if(z&&z.body){let L=z.body.match(/https:\/\/opncd\.ai\/s\/([a-zA-Z0-9_-]+)/);if(L){let W=L[0];v.println(`Found qitqode session: ${W}`),v.println("Importing session...");let C=await K.text(["qitqode","import",W],{nothrow:!0});if(C.code===0){let X=C.text.trim().match(/Imported session: ([a-zA-Z0-9_-]+)/);if(X)V=X[1],v.println(`Session imported: ${V}`)}}}}}v.println(`Successfully checked out PR #${J} as branch '${Z}'`),v.println(),v.println("Starting qitqode..."),v.println();let D=V?["-s",V]:[],$=await K.spawn(["qitqode",...D],{stdin:"inherit",stdout:"inherit",stderr:"inherit",cwd:process.cwd()}).exited;if($!==0)throw Error(`qitqode exited with code ${$}`)}})}});export{P as PrCommand};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Mt as D,Ot as h,Pt as w,Qt as M,Rt as O,St as b,Tt as y}from"./chunk-x9s90xd1.js";import{aQ as N}from"./chunk-3k2b05fv.js";var H={free:{providerID:"qlex",modelID:"free"},default:{providerID:"qlex",modelID:"default"},fast:{providerID:"qlex",modelID:"fast"},economical:{providerID:"qlex",modelID:"economical"},power:{providerID:"qlex",modelID:"power"},orchestrated:{providerID:"qlex",modelID:"orchestrated"}},V={free:"Free (no cost)",default:"Default",fast:"Fast",economical:"Economy",power:"Power",orchestrated:"Orchestrated"},Z={},c="pending",Q=new Set;function F(){return c}function Y(){c="pending",X()}function f(x){return Q.add(x),()=>Q.delete(x)}function X(){for(let x of[...Q])try{x()}catch{}}function q(){for(let x of Object.keys(Z))delete Z[x];c="unavailable",X()}function P(x){return typeof x==="number"&&Number.isFinite(x)&&x>=0&&x<=10}function C(x){if(x===void 0){q();return}let K=x!==null&&typeof x==="object"&&!Array.isArray(x)?x:void 0;if(K?.success===!1){q();return}let J=K?.success===!0&&Object.prototype.hasOwnProperty.call(K,"data")?K.data:x,j={};if(J===null||typeof J!=="object"||Array.isArray(J)){q();return}for(let[W,$]of Object.entries(J)){if(!$||typeof $!=="object"||Array.isArray($)){q();return}let z=$;if(!P(z.intelligence)||!P(z.speed)||!P(z.cost)){q();return}j[W]={intelligence:z.intelligence,speed:z.speed,cost:z.cost}}for(let W of Object.keys(Z))delete Z[W];Object.assign(Z,j),c="live",X()}function B(x){if(!Array.isArray(x)||x.length===0)return;let K={},J={};for(let j of x){let W=H[j.id];K[j.id]={providerID:j.providerID??W?.providerID??"qlex",modelID:j.modelID??W?.modelID??j.id},J[j.id]=j.label??V[j.id]??j.id}for(let j of Object.keys(H))delete H[j];Object.assign(H,K);for(let j of Object.keys(V))delete V[j];Object.assign(V,J)}var G={};N(G,{tiers:()=>A,tierRatingsState:()=>F,tierRatings:()=>L,streamUrl:()=>_,streamBaseUrl:()=>I,sanitizeUpstreamError:()=>g,qlexProviderMeta:()=>E,onTierRatingsChange:()=>f,omniqueryBaseUrl:()=>o,mergeLiveTiers:()=>k,mergeLiveTierRatings:()=>u,markTierRatingsUnavailable:()=>q,loadLiveRatings:()=>m,evaluatePermission:()=>S,copy:()=>v,beginTierRatingsLoad:()=>Y,bashPrefixWith:()=>d,TIER_RATINGS:()=>Z,AGENT_PROMPT_NAMES:()=>T});var p=3,U=[250,750];async function m(x){for(let K=0;K<p;K++){let J=await x();if(J!==void 0)return J;let j=U[K];if(j!==void 0)await new Promise((W)=>setTimeout(W,j))}return}function k(x){B(x)}function u(x){C(x)}function A(){return Object.entries(H).map(([x,K])=>({id:x,label:V[x]??x,providerID:K.providerID,modelID:K.modelID}))}function L(){return Z}function S(x,K,...J){return J.flat().findLast(($)=>D(x,$.permission)&&D(K,$.pattern))??{action:"ask",permission:x,pattern:"*"}}function d(x,K){for(let J=K.length;J>0;J--){let j=K.slice(0,J).join(" "),W=x[j];if(W!==void 0)return K.slice(0,W)}if(K.length===0)return[];return K.slice(0,1)}function _(){return h}function I(){return w}function o(){return M}function E(){return O}function g(x){return b(x)}function v(){return y}var T=["generate","explore","dream","distill","summary","compaction","title"];export{H as qt,G as rt};
2
+ import{Mt as D,Ot as h,Pt as w,Qt as M,Rt as O,St as b,Tt as y}from"./chunk-tns5x4w0.js";import{aQ as N}from"./chunk-3k2b05fv.js";var H={free:{providerID:"qlex",modelID:"free"},default:{providerID:"qlex",modelID:"default"},fast:{providerID:"qlex",modelID:"fast"},economical:{providerID:"qlex",modelID:"economical"},power:{providerID:"qlex",modelID:"power"},orchestrated:{providerID:"qlex",modelID:"orchestrated"}},V={free:"Free (no cost)",default:"Default",fast:"Fast",economical:"Economy",power:"Power",orchestrated:"Orchestrated"},Z={},c="pending",Q=new Set;function F(){return c}function Y(){c="pending",X()}function f(x){return Q.add(x),()=>Q.delete(x)}function X(){for(let x of[...Q])try{x()}catch{}}function q(){for(let x of Object.keys(Z))delete Z[x];c="unavailable",X()}function P(x){return typeof x==="number"&&Number.isFinite(x)&&x>=0&&x<=10}function C(x){if(x===void 0){q();return}let K=x!==null&&typeof x==="object"&&!Array.isArray(x)?x:void 0;if(K?.success===!1){q();return}let J=K?.success===!0&&Object.prototype.hasOwnProperty.call(K,"data")?K.data:x,j={};if(J===null||typeof J!=="object"||Array.isArray(J)){q();return}for(let[W,$]of Object.entries(J)){if(!$||typeof $!=="object"||Array.isArray($)){q();return}let z=$;if(!P(z.intelligence)||!P(z.speed)||!P(z.cost)){q();return}j[W]={intelligence:z.intelligence,speed:z.speed,cost:z.cost}}for(let W of Object.keys(Z))delete Z[W];Object.assign(Z,j),c="live",X()}function B(x){if(!Array.isArray(x)||x.length===0)return;let K={},J={};for(let j of x){let W=H[j.id];K[j.id]={providerID:j.providerID??W?.providerID??"qlex",modelID:j.modelID??W?.modelID??j.id},J[j.id]=j.label??V[j.id]??j.id}for(let j of Object.keys(H))delete H[j];Object.assign(H,K);for(let j of Object.keys(V))delete V[j];Object.assign(V,J)}var G={};N(G,{tiers:()=>A,tierRatingsState:()=>F,tierRatings:()=>L,streamUrl:()=>_,streamBaseUrl:()=>I,sanitizeUpstreamError:()=>g,qlexProviderMeta:()=>E,onTierRatingsChange:()=>f,omniqueryBaseUrl:()=>o,mergeLiveTiers:()=>k,mergeLiveTierRatings:()=>u,markTierRatingsUnavailable:()=>q,loadLiveRatings:()=>m,evaluatePermission:()=>S,copy:()=>v,beginTierRatingsLoad:()=>Y,bashPrefixWith:()=>d,TIER_RATINGS:()=>Z,AGENT_PROMPT_NAMES:()=>T});var p=3,U=[250,750];async function m(x){for(let K=0;K<p;K++){let J=await x();if(J!==void 0)return J;let j=U[K];if(j!==void 0)await new Promise((W)=>setTimeout(W,j))}return}function k(x){B(x)}function u(x){C(x)}function A(){return Object.entries(H).map(([x,K])=>({id:x,label:V[x]??x,providerID:K.providerID,modelID:K.modelID}))}function L(){return Z}function S(x,K,...J){return J.flat().findLast(($)=>D(x,$.permission)&&D(K,$.pattern))??{action:"ask",permission:x,pattern:"*"}}function d(x,K){for(let J=K.length;J>0;J--){let j=K.slice(0,J).join(" "),W=x[j];if(W!==void 0)return K.slice(0,W)}if(K.length===0)return[];return K.slice(0,1)}function _(){return h}function I(){return w}function o(){return M}function E(){return O}function g(x){return b(x)}function v(){return y}var T=["generate","explore","dream","distill","summary","compaction","title"];export{H as qt,G as rt};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{aq as a}from"./chunk-6b196wjz.js";import"./chunk-79agp7v3.js";import"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as which};
2
+ import{aq as a}from"./chunk-axdzm75h.js";import"./chunk-79agp7v3.js";import"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as which};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Wf as a,Xf as b}from"./chunk-w5kg2yz0.js";import"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as start,b as Heap};
2
+ import{Wf as a,Xf as b}from"./chunk-xvntsbb1.js";import"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as start,b as Heap};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{mg as a,ng as b,og as c}from"./chunk-0csy9x1n.js";import"./chunk-wmaz57f6.js";import"./chunk-hg0etbkx.js";import"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";export{b as run,a as encodeDir,c as ClaudeImport};
2
+ import{mg as a,ng as b,og as c}from"./chunk-tbgczapt.js";import"./chunk-e74efvj2.js";import"./chunk-st5jaszz.js";import"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";export{b as run,a as encodeDir,c as ClaudeImport};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{ud as a,vd as b}from"./chunk-g4nq9swr.js";import"./chunk-xqdrr7xg.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as read,b as copy};
2
+ import{ud as a,vd as b}from"./chunk-4hzm14xt.js";import"./chunk-xqdrr7xg.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{a as read,b as copy};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{pu as a,qu as b,ru as c,su as d,tu as e,uu as f,vu as g,wu as h}from"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{g as redactValue,e as init,f as flush,d as file,b as enabled,h as create,a as Level,c as Default};
2
+ import{pu as a,qu as b,ru as c,su as d,tu as e,uu as f,vu as g,wu as h}from"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-3k2b05fv.js";export{g as redactValue,e as init,f as flush,d as file,b as enabled,h as create,a as Level,c as Default};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{Rd as b}from"./chunk-yajd975f.js";import{Vf as t}from"./chunk-p9cnzxb8.js";import{gh as u}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{rl as y,yk as m}from"./chunk-wmaz57f6.js";import{Pl as v}from"./chunk-hg0etbkx.js";import{lm as a}from"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import"./chunk-x9s90xd1.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import{OI as s}from"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as f}from"os";var M=b({command:"models [provider]",describe:"list all available models",builder:(r)=>{return r.positional("provider",{describe:"provider ID to filter models by",type:"string",array:!1}).option("verbose",{describe:"use more verbose model output (includes metadata like costs)",type:"boolean"}).option("refresh",{describe:"refresh the models cache from models.dev",type:"boolean"})},handler:async(r)=>{if(r.refresh)await v.refresh(!0),t.println(t.Style.TEXT_SUCCESS_BOLD+"Models cache refreshed"+t.Style.TEXT_NORMAL);await a.provide({directory:process.cwd(),async fn(){await u.runPromise(s.gen(function*(){let n=yield*(yield*y.Service).list(),l=(e,o)=>{let i=n[e],d=Object.entries(i.models).sort(([c],[p])=>c.localeCompare(p));for(let[c,p]of d)if(process.stdout.write(`${e}/${c}`),process.stdout.write(f),o)process.stdout.write(JSON.stringify(p,null,2)),process.stdout.write(f)};if(r.provider){let e=m.make(r.provider);if(!n[e]){yield*s.sync(()=>t.error(`Provider not found: ${r.provider}`));return}yield*s.sync(()=>l(e,r.verbose));return}let h=Object.keys(n).sort((e,o)=>{let i=e.startsWith("opencode"),d=o.startsWith("opencode");if(i&&!d)return-1;if(!i&&d)return 1;return e.localeCompare(o)});yield*s.sync(()=>{for(let e of h)l(m.make(e),r.verbose)})}))}})}});export{M as ModelsCommand};
2
+ import{Rd as b}from"./chunk-yajd975f.js";import{Vf as t}from"./chunk-p9cnzxb8.js";import{gh as u}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import{rl as y,yk as m}from"./chunk-e74efvj2.js";import{Pl as v}from"./chunk-st5jaszz.js";import{lm as a}from"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import"./chunk-tns5x4w0.js";import"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import{OI as s}from"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.js";import{EOL as f}from"os";var M=b({command:"models [provider]",describe:"list all available models",builder:(r)=>{return r.positional("provider",{describe:"provider ID to filter models by",type:"string",array:!1}).option("verbose",{describe:"use more verbose model output (includes metadata like costs)",type:"boolean"}).option("refresh",{describe:"refresh the models cache from models.dev",type:"boolean"})},handler:async(r)=>{if(r.refresh)await v.refresh(!0),t.println(t.Style.TEXT_SUCCESS_BOLD+"Models cache refreshed"+t.Style.TEXT_NORMAL);await a.provide({directory:process.cwd(),async fn(){await u.runPromise(s.gen(function*(){let n=yield*(yield*y.Service).list(),l=(e,o)=>{let i=n[e],d=Object.entries(i.models).sort(([c],[p])=>c.localeCompare(p));for(let[c,p]of d)if(process.stdout.write(`${e}/${c}`),process.stdout.write(f),o)process.stdout.write(JSON.stringify(p,null,2)),process.stdout.write(f)};if(r.provider){let e=m.make(r.provider);if(!n[e]){yield*s.sync(()=>t.error(`Provider not found: ${r.provider}`));return}yield*s.sync(()=>l(e,r.verbose));return}let h=Object.keys(n).sort((e,o)=>{let i=e.startsWith("opencode"),d=o.startsWith("opencode");if(i&&!d)return-1;if(!i&&d)return 1;return e.localeCompare(o)});yield*s.sync(()=>{for(let e of h)l(m.make(e),r.verbose)})}))}})}});export{M as ModelsCommand};
@@ -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-x66ycpfs.js";import"./chunk-03xppy47.js";import{Vf as Q}from"./chunk-p9cnzxb8.js";import{gh as A}from"./chunk-28cm7m3t.js";import"./chunk-w9nzsd3w.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import"./chunk-wmaz57f6.js";import{Fl as $}from"./chunk-hg0etbkx.js";import"./chunk-za63b5mc.js";import"./chunk-j8q252w3.js";import"./chunk-nj4d554m.js";import"./chunk-1hmq2fpt.js";import"./chunk-y370dqf3.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-8eje5baf.js";import"./chunk-xqdrr7xg.js";import"./chunk-6b196wjz.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-wwgd4rzx.js";import"./chunk-qc3ce3vc.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-vkqzmzpw.js";import{nu as W}from"./chunk-x9s90xd1.js";import{Gu as _,Ru as Y}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.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-x66ycpfs.js";import"./chunk-03xppy47.js";import{Vf as Q}from"./chunk-p9cnzxb8.js";import{gh as A}from"./chunk-5e4fxy99.js";import"./chunk-8vg4fmg2.js";import"./chunk-zfcp509b.js";import"./chunk-yp5bypsp.js";import"./chunk-7hm0c2yg.js";import"./chunk-gj0wt0cy.js";import"./chunk-md8161zd.js";import"./chunk-yk97q51d.js";import"./chunk-e74efvj2.js";import{Fl as $}from"./chunk-st5jaszz.js";import"./chunk-a1hzeejj.js";import"./chunk-sjw56r2n.js";import"./chunk-nj4d554m.js";import"./chunk-eva3nqqb.js";import"./chunk-yprmd5b7.js";import"./chunk-snr44en9.js";import"./chunk-keveg5gx.js";import"./chunk-f3bnn9rf.js";import"./chunk-xqdrr7xg.js";import"./chunk-axdzm75h.js";import"./chunk-94pcpztx.js";import"./chunk-hw5qyht3.js";import"./chunk-z8gdmvgg.js";import"./chunk-kwx9ewe0.js";import"./chunk-cqtkxwd8.js";import"./chunk-c5pb87yf.js";import"./chunk-g6cyhxwg.js";import"./chunk-n96tvjgj.js";import"./chunk-pkc4ddw1.js";import"./chunk-xgr6jnd6.js";import"./chunk-a48t0g95.js";import"./chunk-yqk58hf6.js";import"./chunk-er38zew1.js";import"./chunk-dk975etf.js";import"./chunk-6p94fpbn.js";import"./chunk-fg35hwa0.js";import"./chunk-79agp7v3.js";import"./chunk-kv72hxkp.js";import"./chunk-nj2bbtmx.js";import{nu as W}from"./chunk-tns5x4w0.js";import{Gu as _,Ru as Y}from"./chunk-e7v9trve.js";import"./chunk-zh3fny3z.js";import"./chunk-m4j7jyrd.js";import"./chunk-gmzrvxnv.js";import"./chunk-mpygdb5a.js";import"./chunk-wfd5h6ax.js";import"./chunk-a0rp7gh4.js";import"./chunk-kfmz2p27.js";import"./chunk-ee23d2nz.js";import"./chunk-3k2b05fv.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
2
  import{$p as G$}from"./chunk-xqdrr7xg.js";import{Cu as eZ,Hu as U$,Iu as A$,Ku as CZ,Lu as KZ}from"./chunk-e7v9trve.js";import{Su as k$}from"./chunk-zh3fny3z.js";import{Tu as SZ}from"./chunk-m4j7jyrd.js";import{$O as fZ,AH as zZ,AI as p,BF as q$,CB as L,CF as E,CO as DZ,DB as Z$,EF as WZ,FB as ZZ,FF as z$,GO as C,HB as oZ,LD as gZ,OI as P,OO as r,RG as $Z,SG as LZ,TG as qZ,TH as xZ,TO as B$,UG as f,UH as V$,WG as jZ,YG as J$,YO as JZ,ZG as i,aH as K$,aP as iZ,dH as o,eG as D$,eP as PZ,fH as l,fP as lZ,jB as a,jG as RZ,jH as h,jP as cZ,kH as Q$,mC as kZ,mH as c,mI as EZ,nH as vZ,nP as v,pP as Y$,qC as rZ,qO as X$,rC as sZ,sJ as YZ,tO as d,uF as $$,vO as m,xH as IZ,xP as F$}from"./chunk-a0rp7gh4.js";import{_P as u$,aQ as BZ,cQ as h$}from"./chunk-3k2b05fv.js";var pZ={};BZ(pZ,{makeHandle:()=>AZ,make:()=>GZ,ProcessId:()=>UZ,ExitCode:()=>FZ,ChildProcessSpawner:()=>W});var FZ=YZ(),UZ=YZ(),hZ="~effect/ChildProcessSpawner/ChildProcessHandle",j$={[hZ]:hZ,...kZ,toJSON(){return{_id:"ChildProcessHandle",pid:this.pid}}},AZ=(Z)=>Object.assign(Object.create(j$),Z),GZ=(Z)=>{let q=(B,Q)=>Z(B).pipe(h((U)=>fZ(Q?.includeStderr===!0?U.all:U.stdout)),r),z=(B,Q)=>iZ(q(B,Q));return W.of({spawn:Z,exitCode:(B)=>xZ(o(Z(B),(Q)=>Q.exitCode)),streamString:q,streamLines:z,lines:(B,Q)=>lZ(z(B,Q)),string:(B,Q)=>cZ(q(B,Q))})};class W extends gZ()("effect/process/ChildProcessSpawner"){}var x={};BZ(x,{setEnv:()=>HZ,setCwd:()=>yZ,prefix:()=>C$,pipeTo:()=>P$,parseFdName:()=>g,make:()=>k,isStandardCommand:()=>I$,isPipedCommand:()=>E$,isCommand:()=>s,fdName:()=>NZ});var MZ="~effect/unstable/process/ChildProcess",aZ={...rZ,...sZ,[MZ]:MZ,asEffect(){return W.use((Z)=>Z.spawn(this))}},s=(Z)=>oZ(Z,MZ),I$=(Z)=>Z._tag==="StandardCommand",E$=(Z)=>Z._tag==="PipedCommand",I=(Z,q,z)=>Object.assign(Object.create(aZ),{_tag:"StandardCommand",command:Z,args:q,options:z}),e=(Z,q,z={})=>Object.assign(Object.create(aZ),{_tag:"PipedCommand",left:Z,right:q,options:z}),k=function(...q){if(OZ(q[0])){let[U,...A]=q,G=bZ(U,A);return I(G[0]??"",G.slice(1),{})}if(typeof q[0]==="object"&&!Array.isArray(q[0])&&!OZ(q[0])){let U=q[0];return function(A,...G){let b=bZ(A,G);return I(b[0]??"",b.slice(1),U)}}if(typeof q[0]==="string"&&!Array.isArray(q[1])){let[U,A={}]=q;return I(U,[],A)}let[z,B=[],Q={}]=q;return I(z,B,Q)},P$=a((Z)=>s(Z[0])&&s(Z[1]),(Z,q,z)=>e(Z,q,z??{})),C$=function(...q){if(s(q[0])&&q.length>1){let[B,...Q]=q,U=dZ(Q);return _Z(B,U)}let z=dZ(q);return(B)=>_Z(B,z)},dZ=(Z)=>{if(OZ(Z[0])){let[B,...Q]=Z,U=bZ(B,Q);return{command:U[0]??"",args:U.slice(1)}}let[q,z=[]]=Z;return{command:q,args:z}},_Z=(Z,q)=>{switch(Z._tag){case"StandardCommand":return I(q.command,[...q.args,Z.command,...Z.args],Z.options);case"PipedCommand":return e(_Z(Z.left,q),Z.right,Z.options)}},yZ=a(2,(Z,q)=>{switch(Z._tag){case"StandardCommand":return I(Z.command,Z.args,{...Z.options,cwd:q});case"PipedCommand":return e(yZ(Z.left,q),yZ(Z.right,q),Z.options)}}),HZ=a(2,(Z,q)=>{switch(Z._tag){case"StandardCommand":{let z=Z.options.env===void 0?q:{...Z.options.env,...q};return I(Z.command,Z.args,{...Z.options,env:z})}case"PipedCommand":return e(HZ(Z.left,q),HZ(Z.right,q),Z.options)}}),OZ=(Z)=>Array.isArray(Z)&&("raw"in Z)&&Array.isArray(Z.raw),g=(Z)=>{let q=/^fd(\d+)$/.exec(Z);if(q===null)return;let z=parseInt(q[1],10);return z>=3?z:void 0},NZ=(Z)=>`fd${Z}`,bZ=(Z,q)=>{let z=[];for(let[B,Q]of Z.entries())z=S$(Z,q,z,Q,B);return z},S$=(Z,q,z,B,Q)=>{let U=Z.raw[Q];if(U===void 0)throw Error(`Invalid backslash sequence: ${Z.raw[Q]}`);let{hasLeadingWhitespace:A,hasTrailingWhitespace:G,tokens:b}=w$(B,U),N=nZ(z,b,A);if(Q===q.length)return N;let S=q[Q],QZ=Array.isArray(S)?S.map((VZ)=>mZ(VZ)):[mZ(S)];return nZ(N,QZ,G)},mZ=(Z)=>{if(typeof Z==="string")return Z;return String(Z)},tZ=new Set([" ","\t","\r",`
3
3
  `]),T$={x:3,u:5},w$=(Z,q)=>{if(q.length===0)return{tokens:[],hasLeadingWhitespace:!1,hasTrailingWhitespace:!1};let z=tZ.has(q[0]),B=[],Q=0;for(let A=0,G=0;A<Z.length;A+=1,G+=1){let b=q[G];if(tZ.has(b)){if(Q!==A)B.push(Z.slice(Q,A));Q=A+1}else if(b==="\\"){let N=q[G+1];if(N===`
4
- `)A-=1,G+=1;else if(N==="u"&&q[G+2]==="{")G=q.indexOf("}",G+3);else G+=T$[N]??1}}let U=Q===Z.length;if(!U)B.push(Z.slice(Q));return{tokens:B,hasLeadingWhitespace:z,hasTrailingWhitespace:U}},nZ=(Z,q,z)=>z||Z.length===0||q.length===0?[...Z,...q]:[...Z.slice(0,-1),`${Z.at(-1)}${q.at(0)}`,...q.slice(1)];var _$=u$(k$(),1);import*as M$ from"child_process";import{PassThrough as g$}from"stream";var R=(Z)=>Z instanceof globalThis.Error?Z:new globalThis.Error(String(Z)),x$=(Z)=>{switch(Z.code){case"ENOENT":return"NotFound";case"EACCES":return"PermissionDenied";case"EEXIST":return"AlreadyExists";case"EISDIR":return"BadResource";case"ENOTDIR":return"BadResource";case"EBUSY":return"Busy";case"ELOOP":return"BadResource";default:return"Unknown"}},y$=(Z)=>{let q=[],z=[],B=(A)=>{switch(A._tag){case"StandardCommand":q.push(A);return;case"PipedCommand":B(A.left),z.push(A.options),B(A.right);return}};if(B(Z),q.length===0)throw Error("flatten produced empty commands array");let[Q,...U]=q;return{commands:[Q,...U],opts:z}},O=(Z,q,z)=>{let B=y$(z).commands.map((Q)=>`${Q.command} ${Q.args.join(" ")}`).join(" | ");return X$({_tag:x$(q),module:"ChildProcess",method:Z,pathOrDescriptor:B,syscall:q.syscall,cause:q})},f$=J$(function*(){let Z=yield*Y$,q=yield*F$,z=p(function*($){if(L($.cwd))return;return yield*Z.access($.cwd),q.resolve($.cwd)}),B=($)=>$.extendEnv?{...eZ(),...$.env}:$.env,Q=($)=>DZ($)?"pipe":$,U=($)=>d($)?"pipe":$,A=($)=>{let D={stream:"pipe",encoding:"utf-8",endOnDone:!0};if(L($.stdin))return D;if(typeof $.stdin==="string")return{...D,stream:$.stdin};if(DZ($.stdin))return{...D,stream:$.stdin};return{stream:$.stdin.stream,encoding:$.stdin.encoding??D.encoding,endOnDone:$.stdin.endOnDone??D.endOnDone}},G=($,D)=>{let J=$[D];if(L(J))return{stream:"pipe"};if(typeof J==="string")return{stream:J};if(d(J))return{stream:J};return{stream:J.stream}},b=($)=>{if(L($.additionalFds))return[];return Object.entries($.additionalFds).flatMap(([D,J])=>{let K=g(D);return L(K)?[]:[{fd:K,config:J}]}).toSorted((D,J)=>D.fd-J.fd)},N=($,D,J,K)=>{let X=(F)=>process.platform==="win32"&&F==="pipe"?"overlapped":F,Y=[X(Q($.stream)),X(U(D.stream)),X(U(J.stream))];if(K.length===0)return Y;let V=K.reduce((F,_)=>Math.max(F,_.fd),2);for(let F=3;F<=V;F++)Y[F]="ignore";for(let F of K)Y[F.fd]=X("pipe");return Y},S=p(function*($,D,J){if(J.length===0)return{getInputFd:()=>m,getOutputFd:()=>C};let K=new Map,X=new Map;for(let Y of J){let V=D.stdio[Y.fd];switch(Y.config.type){case"input":{let F=m;if(V&&"write"in V)F=CZ.fromWritable({evaluate:()=>V,onError:(_)=>O(`fromWritable(fd${Y.fd})`,R(_),$),endOnDone:!0});if(Y.config.stream)yield*EZ(PZ(Y.config.stream,F));K.set(Y.fd,F);break}case"output":{let F=C;if(V&&"read"in V){let _=new g$;V.on("error",(y)=>_.destroy(R(y))),V.pipe(_),F=KZ.fromReadable({evaluate:()=>_,onError:(y)=>O(`fromReadable(fd${Y.fd})`,R(y),$)})}if(Y.config.sink)F=JZ(F,Y.config.sink);X.set(Y.fd,F);break}}}return{getInputFd:(Y)=>K.get(Y)??m,getOutputFd:(Y)=>X.get(Y)??C}}),QZ=($,D,J)=>LZ(()=>{let K=m;if(ZZ(D.stdin))K=CZ.fromWritable({evaluate:()=>D.stdin,onError:(X)=>O("fromWritable(stdin)",R(X),$),endOnDone:J.endOnDone,encoding:J.encoding});if(DZ(J.stream))return Q$(EZ(PZ(J.stream,K)),K);return $Z(K)}),VZ=($,D,J,K)=>{let X=D.stdout?KZ.fromReadable({evaluate:()=>D.stdout,onError:(V)=>O("fromReadable(stdout)",R(V),$)}):C,Y=D.stderr?KZ.fromReadable({evaluate:()=>D.stderr,onError:(V)=>O("fromReadable(stderr)",R(V),$)}):C;if(d(J.stream))X=JZ(X,J.stream);if(d(K.stream))Y=JZ(Y,K.stream);return{stdout:X,stderr:Y,all:B$(X,Y)}},b$=($,D)=>jZ((J)=>{let K=q$(),X=_$.default($.command,$.args,D),Y=!1,V;return X.on("error",(F)=>{J(i(O("spawn",F,$)))}),X.on("exit",(...F)=>{V=F}),X.on("close",(...F)=>{if(Y)return;Y=!0,z$(K,$$(V??F))}),X.on("spawn",()=>{J($Z([X,K]))}),qZ(()=>{X.kill("SIGTERM")})}),XZ=($,D,J)=>{if(globalThis.process.platform==="win32")return jZ((K)=>{M$.exec(`taskkill /pid ${D.pid} /T /F`,{windowsHide:!0},(X)=>{if(X)return K(i(O("kill",R(X),$)));K(f)})});return K$({try:()=>{globalThis.process.kill(-D.pid,J)},catch:(K)=>O("kill",R(K),$)})},wZ=($,D,J)=>LZ(()=>{if(D.kill(J))return f;return i(O("kill",Error("Failed to kill child process"),$))}),N$=($,D,J)=>(K)=>{let X=J?.killSignal??"SIGTERM";if(L(J?.forceKillAfter))return K(D,$,X);return zZ(K(D,$,X),{duration:J.forceKillAfter,orElse:()=>K(D,$,"SIGKILL")})},W$=($,D)=>{let J=D??"stdout";switch(J){case"stdout":return $.stdout;case"stderr":return $.stderr;case"all":return $.all;default:{let K=g(J);return Z$(K)?$.getOutputFd(K):$.stdout}}},T=p(function*($){switch($._tag){case"StandardCommand":{let D=A($.options),J=G($.options,"stdout"),K=G($.options,"stderr"),X=b($.options),Y=yield*z($.options),[V,F]=yield*V$(b$($,{cwd:Y,env:B($.options),stdio:N(D,J,K,X),detached:$.options.detached??process.platform!=="win32",shell:$.options.shell,windowsHide:process.platform==="win32"}),p(function*([M,H]){let t=yield*WZ(H),n=N$(M,$,$.options);if(t){let[u]=yield*E(H);if(process.platform==="win32")return yield*f;if(u!==0&&ZZ(u))return yield*IZ(n(XZ));return yield*f}let w=(u)=>vZ(XZ($,M,u),()=>wZ($,M,u)),R$=$.options.killSignal??"SIGTERM",uZ=w(R$).pipe(l(E(H)),c),L$=$.options.forceKillAfter?zZ(uZ,{duration:$.options.forceKillAfter,orElse:()=>w("SIGKILL").pipe(l(E(H)),c)}):uZ;return yield*IZ(L$)})),_=yield*S($,V,X),y=VZ($,V,J,K),j=!0;return AZ({pid:UZ(V.pid),stdin:yield*QZ($,V,D),stdout:y.stdout,stderr:y.stderr,all:y.all,getInputFd:_.getInputFd,getOutputFd:_.getOutputFd,isRunning:h(WZ(F),(M)=>!M),exitCode:o(E(F),([M,H])=>{if(ZZ(M))return $Z(FZ(M));return i(O("exitCode",Error(`Process interrupted due to receipt of signal: '${H}'`),$))}),kill:(M)=>{let H=M?.killSignal??"SIGTERM",t=(w)=>vZ(XZ($,V,w),()=>wZ($,V,w)),n=t(H).pipe(l(E(F)),c);if(!M?.forceKillAfter)return n;return zZ(n,{duration:M.forceKillAfter,orElse:()=>t("SIGKILL").pipe(l(E(F)),c)})},unref:qZ(()=>{if(j)V.unref(),j=!1;return qZ(()=>{if(!j)V.ref(),j=!0})})})}case"PipedCommand":{let D=y$($),[J,...K]=D.commands,X=T(J);for(let Y=0;Y<K.length;Y++){let V=K[Y],F=D.opts[Y]??{},_=A(V.options),y=r(h(X,(H)=>W$(H,F.from))),j=F.to??"stdin";if(j==="stdin"){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}let M=g(j);if(L(M)){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}X=T(k(V.command,V.args,{...V.options,additionalFds:{...V.options.additionalFds,[NZ(M)]:{type:"input",stream:y}}}))}return yield*X}}});return GZ(T)}),i$=D$(W,f$),l$=i$.pipe(RZ(U$.layer),RZ(A$)),Bq=G$(async()=>{let{makeRuntime:Z}=await import("./chunk-qek6a75r.js");return Z(W,l$)});var H$=(Z,q)=>P.gen(function*(){let z=yield*Z.spawn(q),[B,Q]=yield*P.all([v.mkString(v.decodeText(z.stdout)),v.mkString(v.decodeText(z.stderr))],{concurrency:2});return{code:yield*z.exitCode,text:B,stderr:Q}}).pipe(P.scoped),Mq=H$,_q=(Z,q,z)=>H$(Z,x.make("git",q,{cwd:z?.cwd,extendEnv:!0,stdin:"ignore"}));var TZ={};BZ(TZ,{payloads:()=>p$,define:()=>c$,BusEvent:()=>TZ});var O$=new Map;function c$(Z,q){let z={type:Z,properties:q};return O$.set(Z,z),z}function p$(){return O$.entries().map(([Z,q])=>{return SZ.object({type:SZ.literal(Z),properties:q.properties}).meta({ref:`Event.${q.type}`})}).toArray()}
4
+ `)A-=1,G+=1;else if(N==="u"&&q[G+2]==="{")G=q.indexOf("}",G+3);else G+=T$[N]??1}}let U=Q===Z.length;if(!U)B.push(Z.slice(Q));return{tokens:B,hasLeadingWhitespace:z,hasTrailingWhitespace:U}},nZ=(Z,q,z)=>z||Z.length===0||q.length===0?[...Z,...q]:[...Z.slice(0,-1),`${Z.at(-1)}${q.at(0)}`,...q.slice(1)];var _$=u$(k$(),1);import*as M$ from"child_process";import{PassThrough as g$}from"stream";var R=(Z)=>Z instanceof globalThis.Error?Z:new globalThis.Error(String(Z)),x$=(Z)=>{switch(Z.code){case"ENOENT":return"NotFound";case"EACCES":return"PermissionDenied";case"EEXIST":return"AlreadyExists";case"EISDIR":return"BadResource";case"ENOTDIR":return"BadResource";case"EBUSY":return"Busy";case"ELOOP":return"BadResource";default:return"Unknown"}},y$=(Z)=>{let q=[],z=[],B=(A)=>{switch(A._tag){case"StandardCommand":q.push(A);return;case"PipedCommand":B(A.left),z.push(A.options),B(A.right);return}};if(B(Z),q.length===0)throw Error("flatten produced empty commands array");let[Q,...U]=q;return{commands:[Q,...U],opts:z}},O=(Z,q,z)=>{let B=y$(z).commands.map((Q)=>`${Q.command} ${Q.args.join(" ")}`).join(" | ");return X$({_tag:x$(q),module:"ChildProcess",method:Z,pathOrDescriptor:B,syscall:q.syscall,cause:q})},f$=J$(function*(){let Z=yield*Y$,q=yield*F$,z=p(function*($){if(L($.cwd))return;return yield*Z.access($.cwd),q.resolve($.cwd)}),B=($)=>$.extendEnv?{...eZ(),...$.env}:$.env,Q=($)=>DZ($)?"pipe":$,U=($)=>d($)?"pipe":$,A=($)=>{let D={stream:"pipe",encoding:"utf-8",endOnDone:!0};if(L($.stdin))return D;if(typeof $.stdin==="string")return{...D,stream:$.stdin};if(DZ($.stdin))return{...D,stream:$.stdin};return{stream:$.stdin.stream,encoding:$.stdin.encoding??D.encoding,endOnDone:$.stdin.endOnDone??D.endOnDone}},G=($,D)=>{let J=$[D];if(L(J))return{stream:"pipe"};if(typeof J==="string")return{stream:J};if(d(J))return{stream:J};return{stream:J.stream}},b=($)=>{if(L($.additionalFds))return[];return Object.entries($.additionalFds).flatMap(([D,J])=>{let K=g(D);return L(K)?[]:[{fd:K,config:J}]}).toSorted((D,J)=>D.fd-J.fd)},N=($,D,J,K)=>{let X=(F)=>process.platform==="win32"&&F==="pipe"?"overlapped":F,Y=[X(Q($.stream)),X(U(D.stream)),X(U(J.stream))];if(K.length===0)return Y;let V=K.reduce((F,_)=>Math.max(F,_.fd),2);for(let F=3;F<=V;F++)Y[F]="ignore";for(let F of K)Y[F.fd]=X("pipe");return Y},S=p(function*($,D,J){if(J.length===0)return{getInputFd:()=>m,getOutputFd:()=>C};let K=new Map,X=new Map;for(let Y of J){let V=D.stdio[Y.fd];switch(Y.config.type){case"input":{let F=m;if(V&&"write"in V)F=CZ.fromWritable({evaluate:()=>V,onError:(_)=>O(`fromWritable(fd${Y.fd})`,R(_),$),endOnDone:!0});if(Y.config.stream)yield*EZ(PZ(Y.config.stream,F));K.set(Y.fd,F);break}case"output":{let F=C;if(V&&"read"in V){let _=new g$;V.on("error",(y)=>_.destroy(R(y))),V.pipe(_),F=KZ.fromReadable({evaluate:()=>_,onError:(y)=>O(`fromReadable(fd${Y.fd})`,R(y),$)})}if(Y.config.sink)F=JZ(F,Y.config.sink);X.set(Y.fd,F);break}}}return{getInputFd:(Y)=>K.get(Y)??m,getOutputFd:(Y)=>X.get(Y)??C}}),QZ=($,D,J)=>LZ(()=>{let K=m;if(ZZ(D.stdin))K=CZ.fromWritable({evaluate:()=>D.stdin,onError:(X)=>O("fromWritable(stdin)",R(X),$),endOnDone:J.endOnDone,encoding:J.encoding});if(DZ(J.stream))return Q$(EZ(PZ(J.stream,K)),K);return $Z(K)}),VZ=($,D,J,K)=>{let X=D.stdout?KZ.fromReadable({evaluate:()=>D.stdout,onError:(V)=>O("fromReadable(stdout)",R(V),$)}):C,Y=D.stderr?KZ.fromReadable({evaluate:()=>D.stderr,onError:(V)=>O("fromReadable(stderr)",R(V),$)}):C;if(d(J.stream))X=JZ(X,J.stream);if(d(K.stream))Y=JZ(Y,K.stream);return{stdout:X,stderr:Y,all:B$(X,Y)}},b$=($,D)=>jZ((J)=>{let K=q$(),X=_$.default($.command,$.args,D),Y=!1,V;return X.on("error",(F)=>{J(i(O("spawn",F,$)))}),X.on("exit",(...F)=>{V=F}),X.on("close",(...F)=>{if(Y)return;Y=!0,z$(K,$$(V??F))}),X.on("spawn",()=>{J($Z([X,K]))}),qZ(()=>{X.kill("SIGTERM")})}),XZ=($,D,J)=>{if(globalThis.process.platform==="win32")return jZ((K)=>{M$.exec(`taskkill /pid ${D.pid} /T /F`,{windowsHide:!0},(X)=>{if(X)return K(i(O("kill",R(X),$)));K(f)})});return K$({try:()=>{globalThis.process.kill(-D.pid,J)},catch:(K)=>O("kill",R(K),$)})},wZ=($,D,J)=>LZ(()=>{if(D.kill(J))return f;return i(O("kill",Error("Failed to kill child process"),$))}),N$=($,D,J)=>(K)=>{let X=J?.killSignal??"SIGTERM";if(L(J?.forceKillAfter))return K(D,$,X);return zZ(K(D,$,X),{duration:J.forceKillAfter,orElse:()=>K(D,$,"SIGKILL")})},W$=($,D)=>{let J=D??"stdout";switch(J){case"stdout":return $.stdout;case"stderr":return $.stderr;case"all":return $.all;default:{let K=g(J);return Z$(K)?$.getOutputFd(K):$.stdout}}},T=p(function*($){switch($._tag){case"StandardCommand":{let D=A($.options),J=G($.options,"stdout"),K=G($.options,"stderr"),X=b($.options),Y=yield*z($.options),[V,F]=yield*V$(b$($,{cwd:Y,env:B($.options),stdio:N(D,J,K,X),detached:$.options.detached??process.platform!=="win32",shell:$.options.shell,windowsHide:process.platform==="win32"}),p(function*([M,H]){let t=yield*WZ(H),n=N$(M,$,$.options);if(t){let[u]=yield*E(H);if(process.platform==="win32")return yield*f;if(u!==0&&ZZ(u))return yield*IZ(n(XZ));return yield*f}let w=(u)=>vZ(XZ($,M,u),()=>wZ($,M,u)),R$=$.options.killSignal??"SIGTERM",uZ=w(R$).pipe(l(E(H)),c),L$=$.options.forceKillAfter?zZ(uZ,{duration:$.options.forceKillAfter,orElse:()=>w("SIGKILL").pipe(l(E(H)),c)}):uZ;return yield*IZ(L$)})),_=yield*S($,V,X),y=VZ($,V,J,K),j=!0;return AZ({pid:UZ(V.pid),stdin:yield*QZ($,V,D),stdout:y.stdout,stderr:y.stderr,all:y.all,getInputFd:_.getInputFd,getOutputFd:_.getOutputFd,isRunning:h(WZ(F),(M)=>!M),exitCode:o(E(F),([M,H])=>{if(ZZ(M))return $Z(FZ(M));return i(O("exitCode",Error(`Process interrupted due to receipt of signal: '${H}'`),$))}),kill:(M)=>{let H=M?.killSignal??"SIGTERM",t=(w)=>vZ(XZ($,V,w),()=>wZ($,V,w)),n=t(H).pipe(l(E(F)),c);if(!M?.forceKillAfter)return n;return zZ(n,{duration:M.forceKillAfter,orElse:()=>t("SIGKILL").pipe(l(E(F)),c)})},unref:qZ(()=>{if(j)V.unref(),j=!1;return qZ(()=>{if(!j)V.ref(),j=!0})})})}case"PipedCommand":{let D=y$($),[J,...K]=D.commands,X=T(J);for(let Y=0;Y<K.length;Y++){let V=K[Y],F=D.opts[Y]??{},_=A(V.options),y=r(h(X,(H)=>W$(H,F.from))),j=F.to??"stdin";if(j==="stdin"){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}let M=g(j);if(L(M)){X=T(k(V.command,V.args,{...V.options,stdin:{..._,stream:y}}));continue}X=T(k(V.command,V.args,{...V.options,additionalFds:{...V.options.additionalFds,[NZ(M)]:{type:"input",stream:y}}}))}return yield*X}}});return GZ(T)}),i$=D$(W,f$),l$=i$.pipe(RZ(U$.layer),RZ(A$)),Bq=G$(async()=>{let{makeRuntime:Z}=await import("./chunk-zrp55k47.js");return Z(W,l$)});var H$=(Z,q)=>P.gen(function*(){let z=yield*Z.spawn(q),[B,Q]=yield*P.all([v.mkString(v.decodeText(z.stdout)),v.mkString(v.decodeText(z.stderr))],{concurrency:2});return{code:yield*z.exitCode,text:B,stderr:Q}}).pipe(P.scoped),Mq=H$,_q=(Z,q,z)=>H$(Z,x.make("git",q,{cwd:z?.cwd,extendEnv:!0,stdin:"ignore"}));var TZ={};BZ(TZ,{payloads:()=>p$,define:()=>c$,BusEvent:()=>TZ});var O$=new Map;function c$(Z,q){let z={type:Z,properties:q};return O$.set(Z,z),z}function p$(){return O$.entries().map(([Z,q])=>{return SZ.object({type:SZ.literal(Z),properties:q.properties}).meta({ref:`Event.${q.type}`})}).toArray()}
5
5
  export{W as qm,pZ as rm,x as sm,l$ as tm,H$ as um,Mq as vm,_q as wm,TZ as xm};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{ai as O}from"./chunk-zfcp509b.js";import{Vp as w,Zp as T}from"./chunk-8eje5baf.js";import{ou as l,xu as _}from"./chunk-x9s90xd1.js";class x extends Error{cause;constructor(J,V){super(J);this.name="ForgewiseError",this.cause=V}}class K extends x{constructor(J="Device flow is not supported by this issuer."){super(J);this.name="DeviceFlowUnsupportedError"}}var n=_.create({service:"forgewise.config"}),t="https://accounts.forgewise.tech",o="forgewise-cli",F=!1,s={defaultFallbacks:0};function D(...J){return J.find((V)=>V!==void 0&&V.trim().length>0)}function r(){return!!process.env.REPLIT_DEV_DOMAIN}async function z(){let J=process.env.ACCOUNTS_ISSUER,V=process.env.FORGEWISE_CLIENT_ID;if(J&&V)return{issuer:J.replace(/\/+$/,""),clientId:V};let X,Y;try{X=await w()}catch(H){X=void 0,Y=H}let $=D(J,X?.issuer,t).replace(/\/+$/,""),Z=D(V,X?.clientId,o),W=D(J,X?.issuer)===void 0,G=D(V,X?.clientId)===void 0;if((W||G)&&!F)F=!0,s.defaultFallbacks++,n.warn("remote Forgewise coordinate lookup unavailable; falling back to baked-in defaults",{issuer:$,clientId:Z,usedDefaultIssuer:W,usedDefaultClientId:G,remoteError:Y instanceof Error?Y.message:Y?String(Y):void 0});return{issuer:$,clientId:Z}}function S(J,V,X){if(J>=200&&J<300)return{kind:"success"};let Y=V?.error??"";if(Y==="authorization_pending")return{kind:"wait",intervalMs:X};if(Y==="slow_down")return{kind:"wait",intervalMs:X+5000};if(Y==="access_denied")return{kind:"fatal",message:"Sign-in was denied in the browser."};if(Y==="expired_token")return{kind:"fatal",message:"The sign-in code expired before it was approved. Try again."};return{kind:"fatal",message:`Device sign-in failed: ${V?.error_description||Y||`HTTP ${J}`}`}}import k from"http";var E="/callback",I=[51737,51738],L=new Set;function h(J){return J.replace(/[&<>\"']/g,(V)=>{switch(V){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function m(J){return`http://127.0.0.1:${J}${E}`}async function e(J){return new Promise((V,X)=>{let Y=k.createServer();Y.listen(J,"127.0.0.1",()=>{Y.close(()=>V(J))}),Y.on("error",X)})}async function b(){for(let J of I){if(L.has(J))continue;L.add(J);try{return await e(J)}catch{L.delete(J)}}throw new x(`Could not bind to any loopback port (tried ${I.join(", ")}). Free one of those ports and retry.`)}function P(J,V,X,Y){return new Promise(($,Z)=>{let W=()=>L.delete(J),G=k.createServer((N,Q)=>{try{let q=new URL(N.url??"/",`http://localhost:${J}`);if(q.pathname!==E){Q.writeHead(404),Q.end();return}let j=q.searchParams.get("code"),M=q.searchParams.get("state"),U=q.searchParams.get("error"),B=q.searchParams.get("error_description");if(U){let a=`${h(U)}${B?": "+h(B):""}`;Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(`<html><body style="font-family:sans-serif;padding:2rem"><h2>Authorization failed</h2><p>${a}</p><p>You can close this tab.</p></body></html>`),G.close(),Z(new x(`Authorization error: ${U}${B?" \u2014 "+B:""}`));return}if(!j||M!==V){Q.writeHead(400),Q.end("Invalid request");return}Q.writeHead(200,{"Content-Type":"text/html"}),Q.end('<html><body style="font-family:sans-serif;padding:2rem"><h2>Signed in! You can close this tab.</h2><p>Return to your terminal to continue.</p></body></html>'),G.close(),$({code:j})}catch(q){G.close(),Z(q)}});if(X?.aborted){W(),Z(new x("Login cancelled"));return}let H=()=>{W(),G.close(()=>Z(new x("Login cancelled")))};if(X?.addEventListener("abort",H,{once:!0}),X?.aborted){H();return}G.listen(J,"127.0.0.1",()=>{W(),Y?.()}),G.on("error",(N)=>{W(),Z(N)})})}function v(J,V){return new Promise((X,Y)=>{if(V?.aborted){Y(new x("Login cancelled"));return}let $,Z=()=>{clearTimeout($),V?.removeEventListener("abort",Z),Y(new x("Login cancelled"))};if($=setTimeout(()=>{V?.removeEventListener("abort",Z),X()},J),V?.addEventListener("abort",Z,{once:!0}),V?.aborted)Z()})}function J0(J,V=300000){if(!J)return!1;return Date.now()>=J-V}async function V0(J){if(J.method==="api-key")return T({});let{issuer:V}=await z();return T({issuer:V,accessToken:J.key})}import f from"crypto";var g="openid profile email",A=(J)=>J.toString("base64url");function c(){let J=A(f.randomBytes(32)),V=A(f.createHash("sha256").update(J).digest()),X=A(f.randomBytes(16));return{verifier:J,challenge:V,state:X}}function d(J){let V=new URL(`${J.issuer}/api/oauth/authorize`);return V.searchParams.set("response_type","code"),V.searchParams.set("client_id",J.clientId),V.searchParams.set("redirect_uri",J.redirectUri),V.searchParams.set("scope",g),V.searchParams.set("state",J.state),V.searchParams.set("code_challenge",J.challenge),V.searchParams.set("code_challenge_method","S256"),V.toString()}async function C(J,V){let X=await fetch(`${J}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${V.access_token}`}});if(!X.ok)throw new x(`Failed to fetch user profile (${X.status})`);let Y=await X.json();if(!Y.sub)throw new x("Userinfo response is missing required 'sub' field \u2014 the server returned an invalid user profile.");return{sub:Y.sub,name:Y.name??"",email:Y.email??"",access_token:V.access_token,expires_at:Date.now()+(V.expires_in??3600)*1000,...V.refresh_token?{refresh_token:V.refresh_token}:{}}}async function y(J){let V=await fetch(`${J.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:J.code,redirect_uri:J.redirectUri,client_id:J.clientId,code_verifier:J.verifier}).toString(),signal:J.signal??null});if(!V.ok){let Y=await V.text().catch(()=>"");throw new x(`Token exchange failed (${V.status}): ${Y}`)}let X=await V.json();return C(J.issuer,X)}async function X0(J,V,X=5000){let Y=new AbortController,$=setTimeout(()=>Y.abort(),X);try{let Z=await fetch(`${J}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${V}`},signal:Y.signal});if(Z.status===401||Z.status===403)return!1;if(!Z.ok)return null;return!0}catch{return null}finally{clearTimeout($)}}async function Y0(J){let{issuer:V,clientId:X}=await z(),Y;try{Y=await fetch(`${V}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:X,refresh_token:J}).toString()})}catch(Z){throw new x(`Could not reach the sign-in server to refresh the session: ${Z instanceof Error?Z.message:String(Z)}`,Z)}if(!Y.ok){let Z=await Y.json().catch(()=>{return});if(Z?.error==="invalid_grant")return"invalid_grant";throw new x(`Token refresh failed (${Y.status}): ${Z?.error??""}`)}let $=await Y.json();return C(V,$)}async function u(J){let V;try{V=await fetch(`${J.issuer}/api/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:J.clientId,scope:g}).toString(),signal:J.signal??null})}catch{if(J.signal?.aborted)throw new x("Login cancelled");throw new K}if(V.status===404||V.status===405||V.status===501)throw new K;if(!V.ok){let Y=await V.text().catch(()=>"");throw new x(`Device authorization failed (${V.status}): ${Y}`)}let X;try{X=await V.json()}catch{throw new K}if(!X.device_code||!X.user_code||!X.verification_uri)throw new K;return{deviceCode:X.device_code,info:{userCode:X.user_code,verificationUri:X.verification_uri,verificationUriComplete:X.verification_uri_complete,expiresAt:Date.now()+(X.expires_in??900)*1000},intervalMs:Math.max(1,X.interval??5)*1000}}async function p(J){let V;try{V=await fetch(`${J.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:J.deviceCode,client_id:J.clientId}).toString(),signal:J.signal??null})}catch{if(J.signal?.aborted)throw new x("Login cancelled");return{kind:"wait",intervalMs:J.currentIntervalMs}}let X;try{X=await V.json()}catch{X=void 0}let Y=S(V.status,X,J.currentIntervalMs);if(Y.kind==="success"){if(!X?.access_token)throw new x("Token endpoint returned success without an access_token.");return{kind:"success",profile:await C(J.issuer,{access_token:X.access_token,expires_in:X.expires_in})}}if(Y.kind==="fatal")throw new x(Y.message);return{kind:"wait",intervalMs:Y.intervalMs}}var Z0=300000;async function i(){let{issuer:J,clientId:V}=await z(),{verifier:X,challenge:Y,state:$}=c(),Z=await b(),W=m(Z),G=d({issuer:J,clientId:V,redirectUri:W,challenge:Y,state:$});return{issuer:J,clientId:V,verifier:X,port:Z,redirectUri:W,authorizeStr:G,state:$}}async function $0(J){let{issuer:V,clientId:X}=await z(),{deviceCode:Y,info:$,intervalMs:Z}=await u({issuer:V,clientId:X,signal:J.signal});if(J.onCode($),J.tryOpen){let G=$.verificationUriComplete??$.verificationUri;O(G)}let W=Z;while(Date.now()<$.expiresAt){await v(W,J.signal);let G=await p({issuer:V,clientId:X,deviceCode:Y,currentIntervalMs:W,signal:J.signal});if(G.kind==="success")return G.profile;W=G.intervalMs}throw new x("The sign-in code expired before it was approved. Try again.")}async function x0(){let{issuer:J,clientId:V,verifier:X,port:Y,redirectUri:$,authorizeStr:Z,state:W}=await i();process.stdout.write(`
2
+ import{ai as O}from"./chunk-zfcp509b.js";import{Vp as w,Zp as T}from"./chunk-f3bnn9rf.js";import{ou as l,xu as _}from"./chunk-tns5x4w0.js";class x extends Error{cause;constructor(J,V){super(J);this.name="ForgewiseError",this.cause=V}}class K extends x{constructor(J="Device flow is not supported by this issuer."){super(J);this.name="DeviceFlowUnsupportedError"}}var n=_.create({service:"forgewise.config"}),t="https://accounts.forgewise.tech",o="forgewise-cli",F=!1,s={defaultFallbacks:0};function D(...J){return J.find((V)=>V!==void 0&&V.trim().length>0)}function r(){return!!process.env.REPLIT_DEV_DOMAIN}async function z(){let J=process.env.ACCOUNTS_ISSUER,V=process.env.FORGEWISE_CLIENT_ID;if(J&&V)return{issuer:J.replace(/\/+$/,""),clientId:V};let X,Y;try{X=await w()}catch(H){X=void 0,Y=H}let $=D(J,X?.issuer,t).replace(/\/+$/,""),Z=D(V,X?.clientId,o),W=D(J,X?.issuer)===void 0,G=D(V,X?.clientId)===void 0;if((W||G)&&!F)F=!0,s.defaultFallbacks++,n.warn("remote Forgewise coordinate lookup unavailable; falling back to baked-in defaults",{issuer:$,clientId:Z,usedDefaultIssuer:W,usedDefaultClientId:G,remoteError:Y instanceof Error?Y.message:Y?String(Y):void 0});return{issuer:$,clientId:Z}}function S(J,V,X){if(J>=200&&J<300)return{kind:"success"};let Y=V?.error??"";if(Y==="authorization_pending")return{kind:"wait",intervalMs:X};if(Y==="slow_down")return{kind:"wait",intervalMs:X+5000};if(Y==="access_denied")return{kind:"fatal",message:"Sign-in was denied in the browser."};if(Y==="expired_token")return{kind:"fatal",message:"The sign-in code expired before it was approved. Try again."};return{kind:"fatal",message:`Device sign-in failed: ${V?.error_description||Y||`HTTP ${J}`}`}}import k from"http";var E="/callback",I=[51737,51738],L=new Set;function h(J){return J.replace(/[&<>\"']/g,(V)=>{switch(V){case"&":return"&amp;";case"<":return"&lt;";case">":return"&gt;";case'"':return"&quot;";default:return"&#39;"}})}function m(J){return`http://127.0.0.1:${J}${E}`}async function e(J){return new Promise((V,X)=>{let Y=k.createServer();Y.listen(J,"127.0.0.1",()=>{Y.close(()=>V(J))}),Y.on("error",X)})}async function b(){for(let J of I){if(L.has(J))continue;L.add(J);try{return await e(J)}catch{L.delete(J)}}throw new x(`Could not bind to any loopback port (tried ${I.join(", ")}). Free one of those ports and retry.`)}function P(J,V,X,Y){return new Promise(($,Z)=>{let W=()=>L.delete(J),G=k.createServer((N,Q)=>{try{let q=new URL(N.url??"/",`http://localhost:${J}`);if(q.pathname!==E){Q.writeHead(404),Q.end();return}let j=q.searchParams.get("code"),M=q.searchParams.get("state"),U=q.searchParams.get("error"),B=q.searchParams.get("error_description");if(U){let a=`${h(U)}${B?": "+h(B):""}`;Q.writeHead(200,{"Content-Type":"text/html"}),Q.end(`<html><body style="font-family:sans-serif;padding:2rem"><h2>Authorization failed</h2><p>${a}</p><p>You can close this tab.</p></body></html>`),G.close(),Z(new x(`Authorization error: ${U}${B?" \u2014 "+B:""}`));return}if(!j||M!==V){Q.writeHead(400),Q.end("Invalid request");return}Q.writeHead(200,{"Content-Type":"text/html"}),Q.end('<html><body style="font-family:sans-serif;padding:2rem"><h2>Signed in! You can close this tab.</h2><p>Return to your terminal to continue.</p></body></html>'),G.close(),$({code:j})}catch(q){G.close(),Z(q)}});if(X?.aborted){W(),Z(new x("Login cancelled"));return}let H=()=>{W(),G.close(()=>Z(new x("Login cancelled")))};if(X?.addEventListener("abort",H,{once:!0}),X?.aborted){H();return}G.listen(J,"127.0.0.1",()=>{W(),Y?.()}),G.on("error",(N)=>{W(),Z(N)})})}function v(J,V){return new Promise((X,Y)=>{if(V?.aborted){Y(new x("Login cancelled"));return}let $,Z=()=>{clearTimeout($),V?.removeEventListener("abort",Z),Y(new x("Login cancelled"))};if($=setTimeout(()=>{V?.removeEventListener("abort",Z),X()},J),V?.addEventListener("abort",Z,{once:!0}),V?.aborted)Z()})}function J0(J,V=300000){if(!J)return!1;return Date.now()>=J-V}async function V0(J){if(J.method==="api-key")return T({});let{issuer:V}=await z();return T({issuer:V,accessToken:J.key})}import f from"crypto";var g="openid profile email",A=(J)=>J.toString("base64url");function c(){let J=A(f.randomBytes(32)),V=A(f.createHash("sha256").update(J).digest()),X=A(f.randomBytes(16));return{verifier:J,challenge:V,state:X}}function d(J){let V=new URL(`${J.issuer}/api/oauth/authorize`);return V.searchParams.set("response_type","code"),V.searchParams.set("client_id",J.clientId),V.searchParams.set("redirect_uri",J.redirectUri),V.searchParams.set("scope",g),V.searchParams.set("state",J.state),V.searchParams.set("code_challenge",J.challenge),V.searchParams.set("code_challenge_method","S256"),V.toString()}async function C(J,V){let X=await fetch(`${J}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${V.access_token}`}});if(!X.ok)throw new x(`Failed to fetch user profile (${X.status})`);let Y=await X.json();if(!Y.sub)throw new x("Userinfo response is missing required 'sub' field \u2014 the server returned an invalid user profile.");return{sub:Y.sub,name:Y.name??"",email:Y.email??"",access_token:V.access_token,expires_at:Date.now()+(V.expires_in??3600)*1000,...V.refresh_token?{refresh_token:V.refresh_token}:{}}}async function y(J){let V=await fetch(`${J.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",code:J.code,redirect_uri:J.redirectUri,client_id:J.clientId,code_verifier:J.verifier}).toString(),signal:J.signal??null});if(!V.ok){let Y=await V.text().catch(()=>"");throw new x(`Token exchange failed (${V.status}): ${Y}`)}let X=await V.json();return C(J.issuer,X)}async function X0(J,V,X=5000){let Y=new AbortController,$=setTimeout(()=>Y.abort(),X);try{let Z=await fetch(`${J}/api/oauth/userinfo`,{headers:{Authorization:`Bearer ${V}`},signal:Y.signal});if(Z.status===401||Z.status===403)return!1;if(!Z.ok)return null;return!0}catch{return null}finally{clearTimeout($)}}async function Y0(J){let{issuer:V,clientId:X}=await z(),Y;try{Y=await fetch(`${V}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",client_id:X,refresh_token:J}).toString()})}catch(Z){throw new x(`Could not reach the sign-in server to refresh the session: ${Z instanceof Error?Z.message:String(Z)}`,Z)}if(!Y.ok){let Z=await Y.json().catch(()=>{return});if(Z?.error==="invalid_grant")return"invalid_grant";throw new x(`Token refresh failed (${Y.status}): ${Z?.error??""}`)}let $=await Y.json();return C(V,$)}async function u(J){let V;try{V=await fetch(`${J.issuer}/api/oauth/device_authorization`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:J.clientId,scope:g}).toString(),signal:J.signal??null})}catch{if(J.signal?.aborted)throw new x("Login cancelled");throw new K}if(V.status===404||V.status===405||V.status===501)throw new K;if(!V.ok){let Y=await V.text().catch(()=>"");throw new x(`Device authorization failed (${V.status}): ${Y}`)}let X;try{X=await V.json()}catch{throw new K}if(!X.device_code||!X.user_code||!X.verification_uri)throw new K;return{deviceCode:X.device_code,info:{userCode:X.user_code,verificationUri:X.verification_uri,verificationUriComplete:X.verification_uri_complete,expiresAt:Date.now()+(X.expires_in??900)*1000},intervalMs:Math.max(1,X.interval??5)*1000}}async function p(J){let V;try{V=await fetch(`${J.issuer}/api/oauth/token`,{method:"POST",headers:{"content-type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:J.deviceCode,client_id:J.clientId}).toString(),signal:J.signal??null})}catch{if(J.signal?.aborted)throw new x("Login cancelled");return{kind:"wait",intervalMs:J.currentIntervalMs}}let X;try{X=await V.json()}catch{X=void 0}let Y=S(V.status,X,J.currentIntervalMs);if(Y.kind==="success"){if(!X?.access_token)throw new x("Token endpoint returned success without an access_token.");return{kind:"success",profile:await C(J.issuer,{access_token:X.access_token,expires_in:X.expires_in})}}if(Y.kind==="fatal")throw new x(Y.message);return{kind:"wait",intervalMs:Y.intervalMs}}var Z0=300000;async function i(){let{issuer:J,clientId:V}=await z(),{verifier:X,challenge:Y,state:$}=c(),Z=await b(),W=m(Z),G=d({issuer:J,clientId:V,redirectUri:W,challenge:Y,state:$});return{issuer:J,clientId:V,verifier:X,port:Z,redirectUri:W,authorizeStr:G,state:$}}async function $0(J){let{issuer:V,clientId:X}=await z(),{deviceCode:Y,info:$,intervalMs:Z}=await u({issuer:V,clientId:X,signal:J.signal});if(J.onCode($),J.tryOpen){let G=$.verificationUriComplete??$.verificationUri;O(G)}let W=Z;while(Date.now()<$.expiresAt){await v(W,J.signal);let G=await p({issuer:V,clientId:X,deviceCode:Y,currentIntervalMs:W,signal:J.signal});if(G.kind==="success")return G.profile;W=G.intervalMs}throw new x("The sign-in code expired before it was approved. Try again.")}async function x0(){let{issuer:J,clientId:V,verifier:X,port:Y,redirectUri:$,authorizeStr:Z,state:W}=await i();process.stdout.write(`
3
3
  `),process.stdout.write(` Opening Forgewise sign-in in your browser...
4
4
  `),process.stdout.write(" Sign-in URL: "+Z+`
5
5
  `),process.stdout.write(`